/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/dobo@2.32.0/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import nql from"@tryghost/nql";import{collectConnections,collectAdapters,collectFeatures,collectModels}from"./lib/helper.js";const propertyType={integer:{validator:"number",rules:[]},smallint:{validator:"number",rules:[]},text:{validator:"string",textType:"text",rules:[]},string:{validator:"string",maxLength:50,minLength:0,rules:[]},float:{validator:"number",rules:[]},double:{validator:"number",rules:[]},boolean:{validator:"boolean",rules:[]},datetime:{validator:"date",rules:[]},object:{validator:"object",rules:[]},array:{validator:"array",rules:[]}},commonPropertyTypes=["name","type","required","rules","validator","ref","default","values","rulesMsg","immutable","feature","format","getValue","virtual"];async function factory(t){const e=this,{breakNsPath:s}=this.app.bajo,{find:i,filter:a,isString:r,map:n,pick:o,groupBy:l,isEmpty:c}=this.app.lib._;class p extends this.app.baseClass.Base{static aggregateTypes=["count","avg","min","max","sum"];static idTypes=["string","integer","smallint"];static histogramTypes=["daily","monthly","yearly"];static propertyType=propertyType;static indexTypes=["index","unique","primary","fulltext"];constructor(){super(t,e.app),this.config={connections:[],validationParams:{abortEarly:!1,convert:!1,allowUnknown:!0},default:{filter:{limit:25,maxLimit:200,maxPage:400,sort:["dt:-1","updatedAt:-1","createdAt:-1","ts:-1","username","name"]},cache:{ttlDur:"10s"},hardCap:1e4,warnings:!0,attachment:{thumbSizes:["s","m","l"]}},memDb:{persistenceDur:"1s"},applet:{confirmation:!1}},this.adapters=[],this.connections=[],this.features=[],this.models=[]}getPropertyKeysByType=t=>{const e=[...commonPropertyTypes];return["string"].includes(t)&&e.push("minLength","maxLength","values"),["text"].includes(t)&&e.push("textType"),["smallint","integer"].includes(t)&&e.push("autoInc","values"),["float","double"].includes(t)&&e.push("values"),e};getAllPropertyKeys=t=>{const{uniq:e,isEmpty:s}=this.app.lib._,i=[...commonPropertyTypes];for(const t in propertyType)i.push(...Object.keys(propertyType[t]));return t&&!s(t.constructor.propertyKeys)&&i.push(...t.constructor.propertyKeys),e(i)};init=async()=>{const{fs:t}=this.app.lib;await collectAdapters.call(this),await collectConnections.call(this),await collectFeatures.call(this),await collectModels.call(this);const e=`${this.app.getPluginDataDir("dobo")}/attachment`;t.ensureDirSync(e)};start=async(t="all",e=!0)=>{t="all"===t?this.connections:r(t)?a(this.connections,{name:t}):n(t,t=>i(this.connections,{name:t})),this.log.debug("dbInit");for(const s of t)await s.connect(e),this.log.trace("dbInit%s%s%s",s.adapter.plugin.ns,s.adapter.name,s.name)};getConnection=(t,e)=>{const s=i(this.connections,{name:t});if(!s&&!e)throw this.error("unknown%s%s",this.t("connection"),t);return s};getAdapter=(t,e)=>{const{breakNsPath:s}=this.app.bajo;let r;if(!t.includes(":")){if(r=i(this.adapters,{name:t}),r)return r;if(r=a(this.adapters,e=>e.plugin.ns===t),1===r.length)return r[0];if(!e)throw this.error("unknown%s%s",this.t("adapter"),t);return}const{ns:n,path:o}=s(t);if(r=i(this.adapters,t=>t.name===o&&t.plugin.ns===n),!r&&!e)throw this.error("unknown%s%s",this.t("adapter"),t);return r};getFeature=t=>{if(!t.includes(":"))return i(this.features,{name:t});const{ns:e,path:a}=s(t),r=i(this.features,t=>t.name===a&&t.plugin.ns===e);if(!r)throw this.error("unknown%s%s",this.t("feature"),t);return r};getModel=(t,e)=>{const{pascalCase:s}=this.app.lib.aneka;let a=i(this.models,{name:t});if(a||(a=i(this.models,{name:s(t)})),!a&&!e)throw this.error("unknown%s%s",this.t("model"),t);return a};getModelsByConnection=t=>{const e=this.getConnection(t);return this.models.filter(t=>t.connection.name===e.name)};validationErrorMessage=t=>{let e=t.message;return t.details&&(e+=" -> ",e+=this.app.bajo.join(t.details.map((e,s)=>`${e.field}@${t.model}: ${e.error} (${e.value})`))),e};sanitizeDate=(t,{inputFormat:e,outputFormat:s,silent:i=!0}={})=>{const{dayjs:a}=this.app.lib;if(0===t)return null;const r=a(t,e);if(!r.isValid()){if(i)return null;throw this.error("invalidDate")}return"native"!==s&&s?r.format(s):r.toDate()};sanitizeFloat=(t,{strict:e=!1}={})=>{const{isNumber:s}=this.app.lib._;return s(t)?t:e?Number(t):parseFloat(t)||null};sanitizeInt=(t,{strict:e=!1}={})=>{const{isNumber:s}=this.app.lib._;return s(t)?t:e?Number(t):parseInt(t)||null};sanitizeObject=(t,{strict:e=!1,action:s,model:i}={})=>{const{isString:a}=this.app.lib._;let r=null;if(a(t))try{r=JSON.parse(t)}catch(t){if(e)throw t}else try{r=JSON.parse(JSON.stringify(t))}catch(t){if(e)throw t}return r};sanitizeBoolean=t=>null===t?null:["true",!0].includes(t);sanitizeTimestamp=t=>{const{isNumber:e}=this.app.lib._,{dayjs:s}=this.app.lib;if(!e(t))return-1;const i=s.unix(t);return i.isValid()?i.unix():-1};sanitizeString=t=>t+"";sanitizeByType=(t,e,s={})=>{const{isNaN:i}=this.app.lib._;let a=t;return["object","array"].includes(e)?a=this.sanitizeObject(t,s):"boolean"===e?a=this.sanitizeBoolean(t):["float","double"].includes(e)?a=this.sanitizeFloat(t,s):["integer","smallint"].includes(e)?a=this.sanitizeInt(t,s):["string","text"].includes(e)?a=this.sanitizeString(a,s):["datetime"].includes(e)&&(a=this.sanitizeDate(a,s)),!s.strict&&i(a)&&(a=null),a};_calcStats=(t,e,s)=>{const{generateId:i,isSet:a}=this.app.lib.aneka,r={id:i,count:0,avg:null,min:null,max:null};let n=0;for(const i of t){const t=Number(i[e])??0;s.includes("count")&&r.count++,s.includes("avg")&&(n+=t),s.includes("min")&&(!a(r.min)||t<r.min)&&(r.min=t),s.includes("max")&&(!a(r.max)||t>r.max)&&(r.max=t)}return r.avg=n/t.length,r};calcAggregate=({data:t=[],group:e="",field:s="",aggregates:i=["count"]}={})=>{this.checkAggregateParams({group:e,field:s,aggregates:i});const{pick:a,groupBy:r}=this.app.lib._,n=r(t,e),o=[];for(const t in n){const r=n[t],l=this._calcStats(r,s,i);l[e]=t,o.push(a(l,["id",e,...i]))}return o};calcHistogram=({data:t=[],type:e="",group:s="",field:i="",aggregates:a=["count"]}={})=>{this.checkHistogramParams({group:s,field:i,type:e,aggregates:a});const{dayjs:r}=this.app.lib,n={daily:["YYYY-MM-DD","date"],monthly:["YYYY-MM","month"],yearly:["YYYY","year"]};for(const i of t)i._group=r(i[s]).format(n[e][0]);const c=l(t,"_group"),p=[];for(const t in c){const s=c[t],r=this._calcStats(s,i,a),l=n[e][1];r[l]=t,p.push(o(r,["id",l,...a]))}return p};checkAggregateParams=(t={})=>{let{group:e,field:s,aggregates:i}=t;if(r(i)&&(i=[i]),t.aggregates=i,c(e))throw this.error("fieldGroupMissing");if(c(s))throw this.error("fieldCalcMissing");for(const t of i)if(!this.constructor.aggregateTypes.includes(t))throw this.error("unsupportedAggregateType%s",t)};checkHistogramParams=(t={})=>{this.checkAggregateParams(t);const{type:e}=t;if(c(e))throw this.error("histogramTypeMissing");if(!this.constructor.histogramTypes.includes(e))throw this.error("unsupportedHistogramType%s",e)};runModelHook=async(t,e,...s)=>{const{orderBy:i}=this.app.lib._,a=i(t.hooks.filter(t=>t.name===e),["level"]);for(const e of a)e.noWait?e.handler.call(t,...s):await e.handler.call(t,...s)};getDefaultValues=(t={})=>{const{defaultsDeep:e}=this.app.lib.aneka;let s=this.getConfig("default.filter");s.hardCap=this.config.default.hardCap,s.warnings=this.config.default.warnings,t.req&&(s=e({},t.req.getSetting("dobo:default"),s));const{limit:i,maxLimit:a,maxPage:r,hardCap:n,warnings:o}=s;return{limit:i,maxLimit:a,hardCap:n,maxPage:r,warnings:o,t:t.req?t.req.t:this.t}};handleLastPage=(t={},e={})=>{const{count:s,limit:i,page:a}=t,{hardCap:r}=this.getDefaultValues(e);if(s>r){if(a>Math.floor(r/i)){return{data:[],count:r,warnings:[this.t("hardCapWarning%s%s",s,r)]}}}};parseNql=t=>{const e=t.split("+").map(t=>{const[e,...s]=t.split(":").map(t=>t.trim());let i=s.join(":");const a="-"===i[1]?"-":"";if(("{"===i[0]||"{"===i[1])&&"}"===i[i.length-1]){"-"===i[0]&&(i=i.slice(1));const t=i.slice(1,-1).split(",");i=`${a}>=${t[0]}+${e}:${a}<=${t[1]}`}return`${e}:${i}`}).join("+");return nql(e).parse()};parseAny=(t,e)=>{const{isEmpty:s}=this.app.lib._;let a={};if(!e)throw this.error("invalidQuery");let r=[...e.scanables];0===r.length&&(r=[...e.sortables]);const n=r.filter(t=>!!i(e.properties,{name:t,type:"string"})).map(e=>"*"===t[0]?`${e}:~$'${t.replaceAll("*","")}'`:"*"===t[t.length-1]?`${e}:~^'${t.replaceAll("*","")}'`:`${e}:~'${t.replaceAll("*","")}'`);if(1===n.length?a=this.parseNql(n[0]):n.length>1&&(a=this.parseNql(n.join(","))),s(a))throw this.error("invalidQuery");return a};parseQuery=(t,e,s=!0)=>{const{isEmpty:i,isPlainObject:a,trim:r}=this.app.lib._;let n={};if(a(t))n=t;else{if(i(t=r(t)))return n;try{n=t.startsWith("{")?JSON.parse(t):t.includes(":")?this.parseNql(t):this.parseAny(t,e)}catch(t){if(s)return{};throw t}}let o=this.replaceRegexInJson(n);e&&"id"!==e.adapter.idField.name&&(o=o.replaceAll('"id"',`"${e.adapter.idField.name}"`));try{n=this.reviveRegexInJson(o)}catch(t){}return n};replaceRegexInJson=(t={},e=!0)=>{const{isString:s}=this.app.lib._;s(t)&&(t=JSON.parse(t)??{});const i=JSON.stringify(t,(t,e)=>e instanceof RegExp?["__REGEXP__",e.source,e.flags]:e);return e?i:JSON.parse(i)};reviveRegexInJson=(t,e=!0)=>{const{isPlainObject:s}=this.app.lib._;s(t)&&(t=JSON.stringify(t));const i=JSON.parse(t,(t,e)=>Array.isArray(e)&&"__REGEXP__"===e[0]?new RegExp(e[1],e[2]):e);return e?i:JSON.stringify(i)}}return p}export default factory;
//# sourceMappingURL=/sm/048ff967aba94519c6a2f930b7ebbea692490523175792b73699c98840a66012.map