@decaf-ts/core 0.7.38 → 0.7.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/lib/esm/identity/decorators.d.ts +1 -1
- package/lib/esm/identity/decorators.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/model/construction.d.ts +1 -3
- package/lib/esm/model/construction.js +32 -8
- package/lib/esm/model/construction.js.map +1 -1
- package/lib/esm/overrides/Model.d.ts +2 -0
- package/lib/esm/overrides/overrides.js +11 -2
- package/lib/esm/overrides/overrides.js.map +1 -1
- package/lib/esm/persistence/Adapter.js +10 -11
- package/lib/esm/persistence/Adapter.js.map +1 -1
- package/lib/esm/persistence/Sequence.d.ts +2 -1
- package/lib/esm/persistence/Sequence.js +63 -50
- package/lib/esm/persistence/Sequence.js.map +1 -1
- package/lib/esm/persistence/constants.js +1 -0
- package/lib/esm/persistence/constants.js.map +1 -1
- package/lib/esm/persistence/types.d.ts +1 -0
- package/lib/esm/ram/RamAdapter.js +2 -1
- package/lib/esm/ram/RamAdapter.js.map +1 -1
- package/lib/esm/ram/RamStatement.d.ts +5 -0
- package/lib/esm/ram/RamStatement.js +46 -18
- package/lib/esm/ram/RamStatement.js.map +1 -1
- package/lib/esm/repository/Repository.d.ts +2 -10
- package/lib/esm/repository/Repository.js +45 -33
- package/lib/esm/repository/Repository.js.map +1 -1
- package/lib/esm/utils/utils.d.ts +1 -0
- package/lib/esm/utils/utils.js +3 -0
- package/lib/esm/utils/utils.js.map +1 -1
- package/lib/identity/decorators.d.ts +1 -1
- package/lib/identity/decorators.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/model/construction.cjs +32 -8
- package/lib/model/construction.d.ts +1 -3
- package/lib/model/construction.js.map +1 -1
- package/lib/overrides/Model.d.ts +2 -0
- package/lib/overrides/overrides.cjs +11 -2
- package/lib/overrides/overrides.js.map +1 -1
- package/lib/persistence/Adapter.cjs +10 -11
- package/lib/persistence/Adapter.js.map +1 -1
- package/lib/persistence/Sequence.cjs +63 -50
- package/lib/persistence/Sequence.d.ts +2 -1
- package/lib/persistence/Sequence.js.map +1 -1
- package/lib/persistence/constants.cjs +1 -0
- package/lib/persistence/constants.js.map +1 -1
- package/lib/persistence/types.d.ts +1 -0
- package/lib/ram/RamAdapter.cjs +2 -1
- package/lib/ram/RamAdapter.js.map +1 -1
- package/lib/ram/RamStatement.cjs +46 -18
- package/lib/ram/RamStatement.d.ts +5 -0
- package/lib/ram/RamStatement.js.map +1 -1
- package/lib/repository/Repository.cjs +44 -32
- package/lib/repository/Repository.d.ts +2 -10
- package/lib/repository/Repository.js.map +1 -1
- package/lib/utils/utils.cjs +4 -0
- package/lib/utils/utils.d.ts +1 -0
- package/lib/utils/utils.js.map +1 -1
- package/package.json +4 -2
- package/workdocs/assets/slogans.json +186 -0
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,InternalError as o,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as d,enforceDBDecorators as u,ValidationError as p,reduceErrorsToPrint as g,NotFoundError as f,DefaultSeparator as y,BadRequestError as m,ConflictError as w,onCreateUpdate as b,timestamp as v,onCreate as x,onUpdate as A,onDelete as E,afterAny as O,DBKeys as N,BulkCrudOperationKeys as _,readonly as C,SerializationError as T,prefixMethod as B,BaseError as P}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as $,final as D,isClass as k,toCamelCase as I}from"@decaf-ts/logging";import{Model as j,hashObj as L,required as F,sf as M,ValidationKeys as U,async as G,type as Y,list as q,model as z}from"@decaf-ts/decorator-validation";import{Decoration as Q,DefaultFlavour as H,Metadata as V,apply as W,methodMetadata as X,DecorationKeys as J,uses as K,metadata as Z,propMetadata as tt,prop as et}from"@decaf-ts/decoration";import{Lock as rt}from"@decaf-ts/transactional-decorators";var st;(t=>{t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.GENERATED="generated"})(st||(st={}));const it=Object.assign({},a,{allowGenerationOverride:!1,enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1});class nt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new o("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new o("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...n)}))).forEach((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class at extends c{constructor(){super()}}class ot extends o{constructor(t){super(t,ot.name,500)}}class ct extends o{constructor(t,e=ct.name){super(t,e,500)}}class lt extends ct{constructor(t){super(t,lt.name)}}class ht extends R{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return ht.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new o("No context provided");const r=t.pop();if(!(r instanceof c))throw new o("No context provided");if(t.filter(t=>t instanceof c).length>1)throw Error("here");const s=this?r.logger.for(this).for(e):r.logger.clear().for(this).for(e);return{ctx:r,log:e?s.for(e):s,ctxArgs:[...t,r]}}}const dt=Q.flavourResolver.bind(Q);Q.flavourResolver=t=>{try{const e=dt(t);if(e&&e!==H)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof V.registeredFlavour?V.registeredFlavour(r):void 0;if(s&&s!==H)return s;const i=ut._currentFlavour;if(i){const t=ut._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return H}};class ut extends ht{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ut._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return ut._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new o("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=at,this.alias in ut._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ut._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ut._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ut._currentFlavour=this.alias)}Dispatch(){return new ut._baseDispatch}ObserverHandler(){return new nt}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ut._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||$.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},it,r,{affectedTables:(Array.isArray(e)?e:[e]).map(j.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:V.validationExceptions(e,t),logger:i})}async context(t,e,r,...s){this.log.for(this.context).debug(`Creating new context for ${t} operation on ${Array.isArray(r)?r.map(t=>t.name):r.name} model with flag overrides: ${JSON.stringify(e)}`);const i=await this.flags(t,r,e,...s);return(new this.Context).accumulate(i)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=j.columnName(t.constructor,r);if(this.isReserved(i))throw new o(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[st.METADATA]&&(r.silly("Passing along persistence metadata for "+t[st.METADATA]),Object.defineProperty(i,st.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[st.METADATA]})),{record:i,id:t[j.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),c={},l=j.pk(e);c[l]=r;const h=new e(c);n.silly(`Rebuilding model ${h.constructor.name} id ${r}`);const d=t[st.METADATA],u=Object.keys(h).reduce((r,s)=>(s===l||(r[s]=t[j.columnName(e,s)]),r),h);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in u)throw new o(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);u[t]=e})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,st.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),a=j.tableName(t);return i.debug(`Creating ${e.length} entries ${a} table`),Promise.all(e.map((e,s)=>this.create(t,e,r[s],...n)))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=j.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Promise.all(e.map(e=>this.read(t,e,...i)))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),a=j.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=ut.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map(e=>this.delete(t,e,...i)))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return V.flavourOf(t)}static get currentFlavour(){if(!ut._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return ut._currentFlavour}static get current(){return ut.get(this.currentFlavour)}static get(t){if(!t)return ut.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new o(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return V.flavouredAs(t).filter(j.isModel)}catch(t){throw new o(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${L(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return V.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof at&&(e=[t],t=this.migrations());const{ctx:r}=ut.logCtx(e,this.migrate),s=await this.getQueryRunner();for(const e of t)try{const t=new e;await t.up(s,this,r),await t.down(s,this,r)}catch(t){throw new ct(t)}}}i([D(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],ut.prototype,"shutdownProxies",null),i([D(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],ut.prototype,"context",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ut.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ut.prototype,"unObserve",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],ut.prototype,"client",null);class pt extends o{constructor(t){super(t,pt.name,500)}}class gt extends o{constructor(t){super(t,gt.name,500)}}var ft,yt,mt,wt,bt,vt;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(ft||(ft={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP"})(yt||(yt={})),(t=>{t.AND="AND",t.OR="OR"})(mt||(mt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(wt||(wt={}));class xt extends j{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):j.fromModel(this,t)}and(t){return xt.and(this,t)}or(t){return xt.or(this,t)}not(t){return new xt(this,yt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof xt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(yt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof xt){if(!(this.comparison instanceof xt)&&this.operator!==yt.NOT)return{comparison:{condition:t}};if(-1===Object.values(mt).indexOf(this.operator)&&this.operator!==yt.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return xt.group(t,mt.AND,e)}static or(t,e){return xt.group(t,mt.OR,e)}static group(t,e,r){return new xt(t,e,r)}static attribute(t){return(new xt.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(yt.EQUAL,t)}dif(t){return this.setOp(yt.DIFFERENT,t)}gt(t){return this.setOp(yt.BIGGER,t)}lt(t){return this.setOp(yt.SMALLER,t)}gte(t){return this.setOp(yt.BIGGER_EQ,t)}lte(t){return this.setOp(yt.SMALLER_EQ,t)}in(t){return this.setOp(yt.IN,t)}regexp(t){return this.setOp(yt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new xt(this.attr1,this.operator,this.comparison)}catch(t){throw new pt(t)}}}}static builder(){return new xt.Builder}static from(t){return new xt(t)}}i([F(),n("design:type",Object)],xt.prototype,"attr1",void 0),i([F(),n("design:type",String)],xt.prototype,"operator",void 0),i([F(),n("design:type",Object)],xt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(bt||(bt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(vt||(vt={}));const At={update:vt.CASCADE,delete:vt.NONE},Et={Equals:(t,e)=>xt.attribute(t).eq(e),Diff:(t,e)=>xt.attribute(t).dif(e),LessThan:(t,e)=>xt.attribute(t).lt(e),LessThanEqual:(t,e)=>xt.attribute(t).lte(e),GreaterThan:(t,e)=>xt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>xt.attribute(t).gte(e),In:(t,e)=>xt.attribute(t).in(e),Matches:(t,e)=>xt.attribute(t).regexp(e)},Ot=t=>t.charAt(0).toLowerCase()+t.slice(1);class St extends R{static get log(){return this._logger||(this._logger=$.for(St.name)),this._logger}static build(t,...e){if(!t.startsWith(ft.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(ft.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})}static extractSelect(t){const e=t.indexOf(ft.SELECT);if(-1===e)return;const r=t.substring(e+ft.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(ft.AND).map(Ot).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(ft.GROUP_BY);if(-1!==e)return t.substring(e+ft.GROUP_BY.length).split(ft.ORDER_BY)[0].split(ft.THEN_BY).map(Ot).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach((t,r)=>{const{field:n,operator:a}=this.parseFieldAndOperator(t),o=a?Et[a]:Et.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(n,c);i=0===r?l:s[r-1]===ft.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(Et))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:Ot(r),operator:e}}return{field:Ot(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=St.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new pt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(bt).includes(e))throw new pt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(bt).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e){const r=this.extractCore(t).split(/And|Or/).length,s=e.slice(r)??[];let i,n,a;if(s.at(-1)instanceof c&&s.pop(),s.length>=1){const e=s[0],r=this.extractOrderByField(t);i=this.getProperlyOrderByOrThrow(r,e)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function Nt(){return Q.for(st.STATEMENT).define({decorator:()=>(t,e,r)=>W(X(V.key(st.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function _t(t={}){return Q.for(st.QUERY).define({decorator:t=>(e,r,s)=>{const i=St.getFieldsFromMethodName(r);return W(X(V.key(st.QUERY,r),{...t,fields:i}),Nt(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:a,orderBy:o,limit:c,offset:l}=St.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:d,allowOffset:u,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:u}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new pt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(h=h[t.key](t.value))}return h.execute()}})})(t))(e,r,s)},args:[t]}).apply()}class Ct extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new o("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=j.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1},t&&(this._adapter=t),e&&(Ct.register(e,this,this.adapter.alias),t)&&V.get(e,J.FLAVOUR)===H&&K(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(t=>{const e=t.name;d(this,this[e+"Prefix"],t,this[e+"Suffix"])})}logCtx(t,e){return ut.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new nt}async createPrefix(t,...e){const r=await at.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(t=new this.class(t),s||await u(this,r.context,t,l.CREATE,l.ON),!i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${j.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,r)}async createSuffix(t,e){return super.createSuffix(t,e)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${j.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async createAllPrefix(t,...e){const r=await at.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=j.sequenceFor(t[0]);let a=[];if(n.type?(n.name||(n.name=j.sequenceName(t[0],"pk")),a=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):a=t.map((t,e)=>{if(void 0===t[this.pk])throw new o("Primary key is not defined for model in position "+e);return t[this.pk]}),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?a[e]:""+t[this.pk]),s||await u(this,r.context,t,l.CREATE,l.ON),t))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await at.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await u(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${j.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await at.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,u(this,r.context,e,l.READ,l.ON)})),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${j.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${j.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,i)}async updatePrefix(t,...e){const r=await at.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t[this.pk];if(!n)throw new o("No value for the Id is defined under the property "+this.pk);const a=await this.read(n,...r.args);if(t=j.merge(a,t,this.class),s||await u(this,r.context,t,l.UPDATE,l.ON,a),!i){const e=await Promise.resolve(t.hasErrors(a,...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${j.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const r=await at.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t.map(t=>{const e=t[this.pk];if(!e)throw new o("missing id on update operation");return e}),a=await this.readAll(n,...r.args);if(t=t.map((t,e)=>j.merge(a[e],t,this.class)),s||await Promise.all(t.map((t,e)=>u(this,r.context,t,l.UPDATE,l.ON,a[e]))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(a[r],t,...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async deletePrefix(t,...e){const r=await at.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await u(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${j.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await at.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map(async t=>u(this,r.context,t,l.DELETE,l.ON))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${j.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}async query(t,e,r=bt.ASC,s,i,...n){const a=await at.args(st.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:o}=this.logCtx(a.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(o)}async listBy(t,e,...r){const s=await at.args(wt.LIST_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.listBy);return i.verbose(`listing ${j.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...n)}async paginateBy(t,e,r={offset:1,limit:10},...s){let{offset:i,bookmark:n,limit:a}=r;if(!i&&!n)throw new pt("PaginateBy needs a page or a bookmark");const o=await at.args(wt.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:c,ctxArgs:l}=this.logCtx(o.args,this.paginateBy);let h;if(c.verbose(`paginating ${j.tableName(this.class)} with page size ${a}`),n)h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(this.attr(j.pk(this.class)).gt(n)).orderBy([t,e]).paginate(a,...l),i=1;else{if(!i)throw new pt("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...l)}const d=await h.page(i,...l);return h.serialize(d)}async findOneBy(t,e,...r){const s=await at.args(wt.FIND_ONE_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findOneBy);i.verbose(`finding ${j.tableName(this.class)} with ${t} ${e}`);const a=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!a.length)throw new f("No results found");return a[0]}async findBy(t,e,...r){const s=await at.args(wt.FIND_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findBy);return i.verbose(`finding ${j.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...n)}async statement(t,...e){if(!Ct.statements(this,t))throw new pt("Invalid prepared statement requested "+t);const r=await at.args(st.STATEMENT,this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:i}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...i)}attr(t){return xt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=j.tableName(this.class);this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:V.constr(t)===V.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString())}unObserve(t){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ut._baseSequence.parseValue(j.sequenceFor(this.class).type,t)):ut._baseSequence.parseValue(j.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||V.flavourOf(t)||ut.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ct)return s;const n=e||V.flavourOf(t)||s&&V.get(s,st.ADAPTER)||ut.currentFlavour,a=n?ut.get(n):void 0;if(!a)throw new o("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,t,...r)}static get(t,e){const r=j.tableName(t);let s=r;if(e&&(s=[r,e].join(y)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new o("Could not find repository registered under "+r)}static register(t,e,r){let s=j.tableName(t);if(r&&(s=[s,r].join(y)),s in this._cache&&this._cache[s]instanceof Ct)throw new o(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ct?t.constructor:t,s=V.get(r,e?V.key(st.STATEMENT,e):st.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ct?t.constructor:t;return V.get(r,e?V.key(st.QUERY,e):st.QUERY)}}function Tt(t,e){if(!(e||(e=Q.flavourResolver(t instanceof j?t.constructor:t))&&e!==H))throw new o("Could not retrieve flavour from model "+(t instanceof j?t.constructor.name:t.name));return M(st.INJECTABLE,e,j.tableName(t))}i([Nt(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ct.prototype,"listBy",null),i([Nt(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"paginateBy",null),i([Nt(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findOneBy",null),i([Nt(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Ct.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ct.prototype,"unObserve",null),ut&&(ut._baseRepository=Ct);class Bt extends t{get log(){return this.logger||(this.logger=$.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=j.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(n=j.get(t.toString())),!n)return;const a=st.ADAPTER,o=r||V.get(n,a);try{let t=o;try{o&&ut.get(o)}catch{const e=ut.current;e&&e.flavour===o&&(t=e.alias)}if(i=Ct.forModel(n,t),i instanceof Ct)return i;const r=o||V.get(i.constructor,a)||V.get(n,a);e.register(i,Tt(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Ct.get(n,o);if("function"==typeof e){const t=o?ut.get(o):ut.current;if(!t)return;return new e(t,n)}}}return i}}async function Pt(t,e,r,s){const i=e.logger.for(Pt);if(!s){const e=j.get(t.constructor.name);if(!e)throw new o("Could not find model "+t.constructor.name);s=Ct.forModel(e,r),i.info("Retrieved "+s.toString())}let n;if(void 0===t[j.pk(s.class)])i.info(`No pk found in ${j.tableName(s.class)} - creating`),n=await s.create(t,e);else{i.info(`pk found in ${j.tableName(s.class)} - attempting update`);try{n=await s.update(t,e),i.info("Updated "+j.tableName(s.class))}catch(r){if(!(r instanceof f))throw r;i.info("update Failed - creating new "+j.tableName(s.class)),n=await s.create(t,e)}i.info("After create update: "+n)}return n}async function Rt(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=Gt(s,r,this.adapter.alias),n=await e.read(i);return await Ft(t,s,r,i,n),void(s[r]=i)}const n=k(e.class)?e.class:e.class();if(!n)throw new o("Could not find model "+e.class);const a=Ct.forModel(n,this.adapter.alias),c=await a.create(i,t),l=j.pk(c);await Ft(t,s,r,c[l],c),s[r]=c[l]}async function $t(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==vt.CASCADE)return;if("object"!=typeof i){const e=Gt(s,r,this.adapter.alias),n=await e.read(i,t);return await Ft(t,s,r,i,n),void(s[r]=i)}const n=await Pt(s[r],t,this.adapter.alias),a=j.pk(n);await Ft(t,s,r,n[a],n),s[r]=n[a]}async function Dt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==vt.CASCADE)return;const n=Gt(s,r,this.adapter.alias);let a;a=i instanceof j?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Ft(t,s,r,a[n.pk],a)}async function kt(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new o(`Invalid operation. All elements of property ${r} must match the same type.`);const a=new Set([...i]);if("object"!==n){const e=Gt(s,r,this.adapter.alias);for(const i of a){const n=await e.read(i,t);await Ft(t,s,r,i,n)}return void(s[r]=[...a])}const c=j.pk(i[0]),l=new Set;for(const e of i){const i=await Pt(e,t,this.adapter.alias);await Ft(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function It(t,e,r,s){const{cascade:i}=e;if(i.update===vt.CASCADE)return kt.call(this,t,e,r,s)}async function jt(t,e,r,s){if(e.cascade.delete!==vt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new o(`Invalid operation. All elements of property ${r} must match the same type.`);const a="object"===n,c=a?Ct.forModel(i[0],this.adapter.alias):Gt(s,r,this.adapter.alias),l=new Set([...a?i.map(t=>t[c.pk]):i]);for(const e of l.values()){const i=await c.delete(e,t);await Ft(t,s,r,e,i)}s[r]=[...l]}function Lt(t,e,r){return[st.POPULATE,t,e,r].join(".")}async function Ft(t,e,r,s,i){const n=Lt(e.constructor.name,r,s);return t.accumulate({[n]:i})}async function Mt(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const a=await(async(e,r,s,i,n)=>{let a,c;const l=[];for(const h of i){a=Lt(r.constructor.name,s,h);try{c=await e.get(a)}catch(e){const i=Gt(r,s,n);if(!i)throw new o("Could not find repo");c=await i.read(h,t)}l.push(c)}return l})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?a:a[0]}const Ut=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Gt(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=V.get(t instanceof j?t.constructor:t,V.key(U.REFLECT,e,U.LIST))?.clazz;if(!r)throw new o("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=V.getPropDesignTypes(t instanceof j?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Ut.includes((""+t.name).toLowerCase()));return Ct.forModel(i,r)}class Yt extends m{constructor(t,e=Yt.name,r=401){super(t,e,r)}}class qt extends Yt{constructor(t,e=qt.name){super(t,e,403)}}class zt extends o{constructor(t){super(t,zt.name,503)}}function Qt(t){return Q.for(st.TABLE).define({decorator:t=>e=>Z(st.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Ht(t){return Q.for(st.COLUMN).define({decorator:t=>(e,r)=>tt(V.key(st.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Vt(t,e,r){return Q.for(st.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![bt.ASC,bt.DSC].includes(t))&&(e=t,t=void 0),tt(V.key(`${st.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Wt(t,e,r,s){if(s[r]&&(await this.select().where(xt.attribute(r).eq(s[r])).execute()).length)throw new w(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Xt(){const t=st.UNIQUE;return Q.for(t).define(G(),b(Wt),tt(t,{})).apply()}async function Jt(t,e,r,s){throw new Yt("This adapter does not support user identification")}function Kt(){return Q.for(st.CREATED_BY).define({decorator:()=>(t,e)=>W(x(Jt),tt(st.CREATED_BY,e),ae())(t,e),args:[]}).apply()}function Zt(){return Q.for(st.UPDATED_BY).define({decorator:()=>(t,e)=>W(A(Jt),tt(st.UPDATED_BY,e),ae())(t,e),args:[]}).apply()}function te(){return v([l.CREATE])}function ee(){return v()}function re(t,e=At,r=!0,s,i){const n=st.ONE_TO_ONE;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),W(et(),de(n,a),Y([t,String,Number,BigInt]),x(Rt,a),A($t,a),E(Dt,a),O(Mt,a))},args:[t,e,r,s,i]}).apply()}function se(t,e=At,r=!0,s,i){const n=st.ONE_TO_MANY;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),W(et(),de(n,a),q([t,String,Number,BigInt]),x(kt,a),A(It,a),E(jt,a),O(Mt,a))},args:[t,e,r,s,i]}).apply()}function ie(t,e=At,r=!0,s,i){const n=st.MANY_TO_ONE;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),W(et(),de(n,a),Y([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ne(t,e=At,r=!0,s,i){const n=st.MANY_TO_MANY;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),W(et(),de(n,a),q([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ae(){return(t,e)=>tt(V.key(st.GENERATED,e),!0)(t,e)}function oe(...t){return(e,r)=>{const s=V.get(e,V.key(st.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return W(Z(V.key(st.NO_VALIDATE,r),i))(e,r)}}function ce(){return oe(l.CREATE)}function le(){return oe(l.UPDATE)}function he(){return oe(l.UPDATE,l.CREATE)}function de(t,e){return Q.for(st.RELATIONS).define({decorator:(t,e)=>(r,s)=>(tt(t,e)(r,s),tt(V.key(st.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}Q.for(N.TIMESTAMP).extend(ae()).apply(),Q.for(N.COMPOSED).extend(ae()).apply(),V.validationExceptions=((t,e)=>{const r=V.get(t,st.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t),i=j.nestedRelations(t);return[...new Set([...s,...i])]}).bind(V),V.migrationsFor=(t=>{if(!(t=t??ut.current))throw new o("Could not get adapter for migrations");return V.innerGet(Symbol.for(st.MIGRATION),t.alias).map(t=>t.class)}).bind(V),V.relations=((t,e)=>{const r=V.get(t,st.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new o("No relations metadata found for property "+e);return r[e]}}).bind(V),j.relations=(t,e)=>V.relations(t instanceof j?t.constructor:t,e)||[],j.nestedRelations=(t,e)=>{e?.length||(e=j.relations(t));let r=[];const s=V.get(t,st.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&j.relations(i.class)){const s=j.relations(i.class),n=s.map(e=>`${t}.${e}`);e=[...e,...s,...n],r=j.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]},V.generated=((t,e)=>!!V.get("function"!=typeof t?t.constructor:t,V.key(st.GENERATED,e))).bind(V),V.createdBy=(t=>{const e=V.get("function"!=typeof t?t.constructor:t,st.CREATED_BY);if(!e)throw new o("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(V),V.updatedBy=(t=>{const e=V.get("function"!=typeof t?t.constructor:t,st.UPDATED_BY);if(!e)throw new o("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(V),j.tableName=t=>{if(!(t instanceof j?j.get(t.constructor.name):t))throw new o("Unable to find model "+t);return V.get(t instanceof j?t.constructor:t,st.TABLE)||(t instanceof j?t.constructor.name:t.name)},j.columnName=(t,e)=>V.get(t instanceof j?t.constructor:t,V.key(st.COLUMN,e))||e,j.sequenceName=(t,...e)=>[j.tableName(t),...e].join("_"),j.sequenceFor=(t,e)=>{if(e)throw new ot("not currently supported");const r=j.pkProps(t instanceof j?t.constructor:t);if(!r)throw new o("No sequence options defined for model. did you use the @pk decorator?");return r},j.indexes=t=>{const e=V.get(t instanceof j?t.constructor:t,st.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[st.INDEX]:e[r]},t),{})},e.services=()=>V.innerGet(Symbol.for(st.SERVICE)),e.repositories=()=>V.innerGet(Symbol.for(N.REPOSITORY));class ue extends ht{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const t=this.adapter;[l.CREATE,l.UPDATE,l.DELETE,_.CREATE_ALL,_.UPDATE_ALL,_.DELETE_ALL].forEach(e=>{if(!t[e])throw new o(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(t=>{switch(t){case _.CREATE_ALL:return l.CREATE;case _.UPDATE_ALL:return l.UPDATE;case _.DELETE_ALL:return l.DELETE;default:return t}})(e),o,c,...n.slice(s.length)).then(()=>{i.verbose(`Observer refresh dispatched by ${e} for ${a}`),i.debug("pks: "+o)}).catch(t=>i.error(`Failed to dispatch observer refresh for ${e} on ${a}: ${t}`)),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof ut))throw new ot("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ut.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(t){if(this.adapter!==t)throw new ot("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const i="string"==typeof t?t:j.tableName(t),{log:n,ctxArgs:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...a)}catch(t){throw new o("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}ut&&(ut._baseDispatch=ue);class pe{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}static get instance(){return pe._instance||(pe._instance=new pe),pe._instance}}class ge{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return ge._instance||(ge._instance=new ge),ge._instance}}function fe(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof lt)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class ye extends R{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;fe(this,t,this.prefix(e))})}get adapter(){const t=V.get(this.constructor,st.MIGRATION);if(!t)throw new o("No migration metadata for "+this.constructor.name);const e=t.flavour;return ut.get(e)}async enforceRules(t,e,r){const s=V.get(this.constructor,st.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const i of s)if(!await i(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ut?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await at.args("migration",j,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new lt("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function me(t,e){return Q.for(st.MIGRATION).define({decorator:(t,e)=>r=>{const s=V.innerGet(Symbol.for(st.MIGRATION),t)||[];return V.set(st.MIGRATION,t,[...s,{class:r}]),Z(st.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}class we extends j{constructor(t){super(t)}}i([te(),n("design:type",Date)],we.prototype,"createdAt",void 0),i([ee(),n("design:type",Date)],we.prototype,"updatedAt",void 0);const be={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},ve=be,xe={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Ae=Object.assign({},xe,{type:"BigInt"});async function Ee(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=j.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new o(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,c;n=s,a=r,c=await i.next(t),Reflect.set(n,a,c)}function Oe(t,e){return(r,s)=>{switch(et()(r,s),t.type){case void 0:{const e=V.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[Vt([bt.ASC,bt.DSC]),F(),C(),tt(V.key(N.ID,s),t),x(Ee,t,e)];return t.generated&&i.push(ae()),W(...i)(r,s)}}function Se(t=ve){return t=Object.assign({},ve,t),Q.for(N.ID).define({decorator:Oe,args:[t,{priority:60}]}).apply()}let Ne=class extends we{constructor(t){super(t)}};i([Se({type:"String",generated:!1}),n("design:type",String)],Ne.prototype,"id",void 0),i([F(),Vt(),n("design:type",Object)],Ne.prototype,"current",void 0),Ne=i([Qt("??sequence"),z(),n("design:paramtypes",[Object])],Ne);class _e extends ht{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=Ct.forModel(Ne,e.alias)}async current(...t){const e=(await at.args(l.READ,Ne,t,this.adapter)).context,{name:r,startWith:s}=this.options;try{const t=await this.repo.read(r,e);return this.parse(t.current)}catch(t){if(t instanceof f){if(void 0===s)throw new o("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new o(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new o(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let a;const c=e||i;if(c%i!==0)throw new o("Value to increment does not consider the incrementBy setting: "+i);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:a=this.parse(t)+c;break;case BigInt.name:a=this.parse(t)+BigInt(c);break;case String.name:a=this.parse(t);break;case"serial":a=ge.instance.generate(t);break;case"uuid":a=pe.instance.generate(t);break;default:throw new o("Should never happen")}let l;try{l=await this.repo.update(new Ne({id:n,current:a}),r)}catch(i){if(!(i instanceof f))throw i;try{l=await this.repo.create(new Ne({id:n,current:a}),r)}catch(i){if(!(i instanceof w)||"uuid"!==s)throw i;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await at.args(l.UPDATE,Ne,t,this.adapter),{context:r,args:s}=e,i=await this.current(...s);return this.increment(i,void 0,r)}async range(t,...e){const r=await at.args(l.UPDATE,Ne,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),a=this.parse(this.options.incrementBy),c=await this.increment(n,this.parse(t)*a,s),h=[];for(let e=1;t>=e;e++)h.push(n+a*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new ot(`type ${this.options.type} is currently not suppported for this adapter`);const d="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==d)throw new o("Miscalculation of range");return h}parse(t){return _e.parseValue(this.options.type,t)}static pk(t){return j.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new ot(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ce(t,e){return(i,n)=>n?r(V.constr(t))(i,n):(V.set(N.REPOSITORY,V.key(e||ut.currentFlavour,j.tableName(t)),i),Z(N.REPOSITORY,i.name)(t),e=e||V.get(i.constructor,st.ADAPTER),Ct.register(V.constr(t),i,e),s(V.constr(t),{callback:e=>(Object.defineProperty(e,N.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut._baseSequence=_e;class Te extends o{constructor(t){super(t,Te.name,500)}}class Be extends R{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,fe(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${wt.FIND_BY}|${wt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){return[t,...(await at.args(st.QUERY,this.clazz,e,this.adapter)).args]}async pagePrepared(t,...e){const r=Ct.forModel(this.clazz,this.adapter.alias),s=this.query,{method:i,args:n,params:a}=s,o=RegExp(`^${wt.FIND_BY}|${wt.LIST_BY}`,"gi");if(!i.match(o))throw new ot(`Method ${i} is not supported for pagination`);o.lastIndex=0;const c=i.replace(o,wt.PAGE_BY),l=[c,...n];let h={limit:this.size,offset:t,bookmark:this._bookmark};c!==wt.PAGE_BY||l.length>2?h={direction:a.direction,limit:this.size,offset:t,bookmark:this._bookmark}:l.push(a.direction),l.push(h);const d=await r.statement(...l,...e);return this.apply(d)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new gt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new gt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,...e){const{ctxArgs:r}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...r);throw new ot("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new T(t)}}apply(t){const e="string"==typeof t?Be.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new T(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}function Pe(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&((t,e)=>{const{handler:r,args:s}=V.get(t,l.REFLECT+l.BLOCK)||{};return!!r&&(r(...s,e)??!1)})(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}const Re=()=>Pe(l.CREATE),$e=()=>Pe(l.READ),De=()=>Pe(l.UPDATE),ke=()=>Pe(l.DELETE);function Ie(t){return t="string"==typeof t?t:V.Symbol(t).toString(),(e,i,n)=>{V.set(st.SERVICE,t,e);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else a.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return a.push(Z(st.SERVICE,t)),W(...a)(e,i,n)}}class je{constructor(t){this.name=t,this.Context=at}async flags(t,e,...r){let s=e.logger||$.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},it,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=e,i=await this.flags(t,s,...r);return(new this.Context).accumulate(i)}async logCtx(t,e,r=!1){return await je.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const i=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await i()]);const n=t.pop();n instanceof at||(t=[...t,await i()]);const a=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?a.for(e):a,ctxArgs:[...t,n]}}static get(t){if(!t)throw new o("No name provided");const r=e.get(t);if(r)return r;throw new o("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){const r={context:async t=>(new at).accumulate(Object.assign({},it,{timestamp:new Date,operation:t,logger:$.get()}))},{log:s,ctxArgs:i}=await this.logCtx.bind(r)(t,this.boot,!0),n=e.services();for(const[t,e]of Object.entries(n))try{const t=new e;t instanceof Le&&await t.boot(...i)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class Le extends je{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=await this.logCtx(t,this.boot,!0);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new o("Config not initialized");return this._config}get client(){if(!this._client)throw new o("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],Le.prototype,"boot",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],Le.prototype,"config",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],Le.prototype,"client",null);const Fe=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Me extends je{get class(){if(!this.clazz)throw new o("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ct.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new o("No name provided");const e=Fe(t);try{const t=je.get(e);if(t)return t}catch(t){}throw new o("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.create,!0);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.createAll,!0);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.delete,!0);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.deleteAll,!0);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.read,!0);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.readAll,!0);return this.repo.readAll(t,...r)}async query(t,...e){const r=this.repo?.[t];if("function"!=typeof r)throw Error(`Method "${t}" is not implemented`);return r.apply(this.repo,e)}async update(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.update,!0);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.updateAll,!0);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.listBy,!0);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=await this.logCtx(s,this.paginateBy,!0);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findOneBy,!0);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findBy,!0);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.statement,!0);return this.repo.statement(t,...r)}async logCtx(t,e,r=!1){return await Me.logCtx.bind(this.repo.adapter)(t,e,r,this.repo._overrides,this.class)}static forModel(t,e){let r;e=Fe(e||t);try{r=Me.get(e)}catch(t){r=void 0}if(r instanceof Me)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([Ie(e),n("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);let a=t.pop();a instanceof at||(void 0!==a&&t.push(a),a=await n());const c=this?a.logger.for(this).for(e):a.logger.clear().for(this).for(e);return{ctx:a,log:c,ctxArgs:[...t,a]}}}var Ue,Ge,Ye,qe;i([Re(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Me.prototype,"create",null),i([Re(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Me.prototype,"createAll",null),i([ke(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Me.prototype,"delete",null),i([ke(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Me.prototype,"deleteAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Me.prototype,"read",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Me.prototype,"readAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Me.prototype,"query",null),i([De(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Me.prototype,"update",null),i([De(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Me.prototype,"updateAll",null);class ze extends ht{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{B(this,t,async(...e)=>{let r=e;if((!r.length||!(r[r.length-1]instanceof at))&&this.fromSelector){const t=await this.adapter.context(st.QUERY,this.overrides||{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=ut.logCtx(r,t.name),n=s.get("forcePrepareSimpleQueries"),a=s.get("forcePrepareComplexQueries");return(n&&this.isSimpleQuery()||a)&&await this.prepare(s),i},t.name)})}get log(){return this.adapter.log.for(ze)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?j.get(t):t,!this.fromSelector)throw new pt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){try{if(this.prepared)return this.executePrepared(...t);const e=this.build();return await this.raw(e,...t)}catch(t){throw new pt(t)}}async executePrepared(...t){const e=Ct.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new ot("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=j.pk(this.fromSelector),a=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(a):a(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case mt.AND:case mt.OR:{let t=r,a=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof xt){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case yt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case yt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case yt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case yt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case yt.BIGGER_EQ:n.method=r+" bigger than equal";break;case yt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case yt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case yt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new pt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof xt)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,bt.DSC]:[j.pk(this.fromSelector),bt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const a={class:this.fromSelector,method:wt.LIST_BY,args:[s],params:n};return e&&(a.method=wt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(st.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[ft.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(ft.SELECT,this.selectSelector.join(` ${ft.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(ft.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(ft.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=I(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new pt(t)}}toString(){return this.adapter.flavour+" statement"}}i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],ze.prototype,"select",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ue="undefined"!=typeof S&&S)?Ue:Object]),n("design:returntype",Object)],ze.prototype,"distinct",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ge="undefined"!=typeof S&&S)?Ge:Object]),n("design:returntype",Object)],ze.prototype,"max",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ye="undefined"!=typeof S&&S)?Ye:Object]),n("design:returntype",Object)],ze.prototype,"min",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(qe="undefined"!=typeof S&&S)?qe:Object]),n("design:returntype",Object)],ze.prototype,"count",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],ze.prototype,"from",null),i([D(),n("design:type",Function),n("design:paramtypes",[xt]),n("design:returntype",Object)],ze.prototype,"where",null),i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],ze.prototype,"orderBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],ze.prototype,"groupBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],ze.prototype,"limit",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],ze.prototype,"offset",null),i([D(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],ze.prototype,"execute",null);class Qe extends ze{constructor(t,e){super(t,e)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new o("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=V.getPropDesignTypes(t.constructor,s);if(!n)throw new pt("type not compatible with sorting: "+n);switch(n.name){case"string":case"String":return("asc"===i?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===i?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===i?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new pt("Sorting not supported for not date classes");default:throw new pt("sorting not supported for type "+n)}}}build(){const t={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:t=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(t.sort=this.getSort()),t}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[mt.AND,mt.OR,yt.NOT].indexOf(s))switch(s){case yt.BIGGER:return e[r]>i;case yt.BIGGER_EQ:return e[r]>=i;case yt.DIFFERENT:return e[r]!==i;case yt.EQUAL:return e[r]===i;case yt.REGEXP:if("string"!=typeof e[r])throw new pt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case yt.SMALLER:return e[r]<i;case yt.SMALLER_EQ:return e[r]<=i;default:throw new o("Invalid operator for standard comparisons: "+s)}else{if(s===yt.NOT)throw new o("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case mt.AND:return t.where(e)&&n.where(e);case mt.OR:return t.where(e)||n.where(e);default:throw new o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function He(t,e,r,s){const i=t.get("UUID");if(!i)throw new ot("This adapter does not support user identification");s[r]=i}const Ve="ram";class We extends Be{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const{ctx:r,ctxArgs:s}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...s);const i=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)t=this.validatePage(t),i.skip=(t-1)*this.size,n=await this.adapter.raw(i,!0,...e,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...i,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const t=i?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}return this._currentPage=t,n.data||n}}class Xe extends ut{constructor(t={},e){super(t,Ve,e),this.indexes={},this.lock=new rt}repository(){return super.repository()}async flags(t,e,r){return Object.assign(await super.flags(t,e,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...t){return Promise.resolve(void 0)}prepare(t,...e){const r=e.pop(),s=super.prepare(t,...e,r);return delete s.record[j.pk(t.constructor)],s}revert(t,e,r,s,...i){return super.revert(t,e,r,s,...i)}async create(t,e,r,s){const i=s.logger.for(this.create),n=j.tableName(t);if(i.debug(`creating record in table ${n} with id ${e}`),this.client.has(n)||this.client.set(n,new Map),this.client.get(n)&&this.client.get(n)?.has(e))throw new w(`Record with id ${e} already exists in table ${n}`);return await this.lock.acquire(),this.client.get(n)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=j.tableName(t);if(!this.client.has(s))throw new f(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new f(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const i=s.logger.for(this.update),n=j.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),!this.client.has(n))throw new f(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new f(`Record with id ${e} not found in table ${n}`);return await this.lock.acquire(),this.client.get(n)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),i=j.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),!this.client.has(i))throw new f(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new f(`Record with id ${e} not found in table ${i}`);await this.lock.acquire();const n=this.client.get(i)?.get(e);return this.client.get(i)?.delete(e),this.lock.release(),n}tableFor(t){"string"==typeof t&&(t=j.get(t));const e=j.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e=!0,r){r.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:s,sort:i,limit:n,skip:a,from:c}=t;let{select:l}=t;const h=this.tableFor(c);if(!h)throw new o(`Table ${c} not found in RamAdapter`);const d=j.pk(c),u=V.get(c,V.key(N.ID,d));let p=Array.from(h.entries()).map(([t,e])=>this.revert(e,c,_e.parseValue(u.type,t),void 0,r));p=s?p.filter(s):p;const g=p.length;return i&&(p=p.sort(i)),a&&(p=p.slice(a)),n&&(p=p.slice(0,n)),l&&(l=Array.isArray(l)?l:[l],p=p.map(t=>Object.entries(t).reduce((t,[e,r])=>(l.includes(e)&&(t[e]=r),t),{}))),e?p:{data:p,count:g}}parseError(t){return t instanceof P?t:new o(t)}Statement(t){return new Qe(this,t)}Paginator(t,e,r){return new We(this,t,e,r)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${L(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const i=Reflect.get(e,r,s);return Object.assign({},i,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=st.CREATED_BY,e=st.UPDATED_BY;Q.flavouredAs(Ve).for(t).define(x(He),tt(t,{})).apply(),Q.flavouredAs(Ve).for(e).define(b(He),tt(e,{})).apply()}getClient(){return new Map}}Xe.decoration(),e.setRegistry(new Bt);const Je="##VERSION##",Ke="##PACKAGE##";V.registerLibrary(Ke,Je);export{ye as AbsMigration,ut as Adapter,Yt as AuthorizationError,we as BaseModel,Ae as BigIntSequence,vt as Cascade,Le as ClientBasedService,xt as Condition,zt as ConnectionError,at as Context,ht as ContextualLoggedClass,it as DefaultAdapterFlags,At as DefaultCascade,ve as DefaultSequenceOptions,ue as Dispatch,qt as ForbiddenError,mt as GroupOperator,Bt as InjectablesRegistry,St as MethodQueryBuilder,ct as MigrationError,lt as MigrationRuleError,Me as ModelService,be as NoneSequenceOptions,xe as NumericSequence,Te as ObserverError,nt as ObserverHandler,yt as Operator,Et as OperatorsMap,bt as OrderDirection,Ke as PACKAGE_NAME,Be as Paginator,gt as PagingError,st as PersistenceKeys,wt as PreparedStatementKeys,ft as QueryClause,pt as QueryError,Xe as RamAdapter,Ve as RamFlavour,We as RamPaginator,Qe as RamStatement,Ct as Repository,_e as Sequence,Ne as SequenceModel,ge as Serial,je as Service,ze as Statement,pe as UUID,ot as UnsupportedError,Je as VERSION,Ft as cacheModelForPopulate,Ht as column,Re as create,Pt as createOrUpdate,te as createdAt,Kt as createdBy,Jt as createdByOnCreateUpdate,He as createdByOnRamCreateUpdate,ke as del,Tt as generateInjectableNameForRepository,ae as generated,Lt as getPopulateKey,Vt as index,ne as manyToMany,ie as manyToOne,me as migration,oe as noValidateOn,ce as noValidateOnCreate,he as noValidateOnCreateUpdate,le as noValidateOnUpdate,se as oneToMany,kt as oneToManyOnCreate,jt as oneToManyOnDelete,It as oneToManyOnUpdate,re as oneToOne,Rt as oneToOneOnCreate,Dt as oneToOneOnDelete,$t as oneToOneOnUpdate,Se as pk,Oe as pkDec,Ee as pkOnCreate,Mt as populate,fe as prefixMethod,Nt as prepared,_t as query,$e as read,de as relation,Ce as repository,Gt as repositoryFromTypeMetadata,Ie as service,Qt as table,Xt as unique,Wt as uniqueOnCreateUpdate,De as update,ee as updatedAt,Zt as updatedBy};
|
|
1
|
+
import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,InternalError as o,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as u,wrapMethodWithContextForUpdate as d,enforceDBDecorators as p,ValidationError as g,reduceErrorsToPrint as f,NotFoundError as y,DefaultSeparator as m,BadRequestError as w,ConflictError as b,onCreateUpdate as v,timestamp as x,onCreate as A,onUpdate as E,onDelete as O,afterAny as N,DBKeys as _,BulkCrudOperationKeys as C,readonly as B,SerializationError as T,prefixMethod as P,BaseError as $}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as D,final as I,isClass as k,toCamelCase as F}from"@decaf-ts/logging";import{Model as j,hashObj as L,required as M,sf as U,ValidationKeys as q,async as G,type as Y,list as z,model as Q}from"@decaf-ts/decorator-validation";import{Metadata as H,Decoration as V,DefaultFlavour as W,apply as J,methodMetadata as X,DecorationKeys as K,uses as Z,metadata as tt,propMetadata as et,prop as rt}from"@decaf-ts/decoration";import{MultiLock as st,Lock as it}from"@decaf-ts/transactional-decorators";var nt;(t=>{t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.GENERATED="generated"})(nt||(nt={}));const at=Object.assign({},a,{allowGenerationOverride:!1,enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{}});class ot{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new o("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new o("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=ft.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...n)}))).forEach((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class ct extends c{constructor(){super()}}class lt extends o{constructor(t){super(t,lt.name,500)}}class ht extends o{constructor(t,e=ht.name){super(t,e,500)}}class ut extends ht{constructor(t){super(t,ut.name)}}class dt extends R{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return dt.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new o("No context provided");const r=t.pop();if(!(r instanceof c))throw new o("No context provided");if(t.filter(t=>t instanceof c).length>1)throw Error("here");const s=this?r.logger.for(this).for(e):r.logger.clear().for(this).for(e);return{ctx:r,log:e?s.for(e):s,ctxArgs:[...t,r]}}}function pt(t){return t.reduce((t,e)=>t.then(async t=>[...t,await e()]),Promise.resolve([]))}const gt=V.flavourResolver.bind(V);V.flavourResolver=t=>{try{const e=gt(t);if(e&&e!==W)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof H.registeredFlavour?H.registeredFlavour(r):void 0;if(s&&s!==W)return s;const i=ft._currentFlavour;if(i){const t=ft._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return W}};class ft extends dt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ft._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return ft._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new o("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=ct,this.alias in ft._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ft._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ft._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ft._currentFlavour=this.alias)}Dispatch(){return new ft._baseDispatch}ObserverHandler(){return new ot}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ft._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||D.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},at,r,{affectedTables:(Array.isArray(e)?e:[e]).map(j.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:H.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t),logger:i})}async context(t,e,r,...s){this.log.for(this.context).debug(`Creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>t.name):r.name:"no"} model with flag overrides: ${JSON.stringify(e)}`);const i=await this.flags(t,r,e,...s);return(new this.Context).accumulate(i)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=j.columnName(t.constructor,r);if(this.isReserved(i))throw new o(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[nt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[nt.METADATA]),Object.defineProperty(i,nt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[nt.METADATA]})),{record:i,id:t[j.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),c={};c[j.pk(e)]=r;const l=new e(c);n.silly(`Rebuilding model ${l.constructor.name} id ${r}`);const h=t[nt.METADATA],u=Object.keys(l).reduce((r,s)=>(r[s]=t[j.columnName(e,s)],r),l);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in u)throw new o(`Transient property ${t} already exists on model ${l.constructor.name}. should be impossible`);u[t]=e})),h&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${l.constructor.name} id ${r}: ${h}`),Object.defineProperty(u,nt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:h})),u}async createAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),a=j.tableName(t);return i.debug(`Creating ${e.length} entries ${a} table`),pt(e.map((e,s)=>()=>this.create(t,e,r[s],...n)))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=j.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),pt(e.map(e=>()=>this.read(t,e,...i)))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),a=j.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),pt(e.map((e,s)=>()=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=ft.logCtx(r,this.deleteAll);return s.debug(`Deleting ${e.length} entries from ${t} table`),pt(e.map(e=>()=>this.delete(t,e,...i)))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=ft.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return H.flavourOf(t)}static get currentFlavour(){if(!ft._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return ft._currentFlavour}static get current(){return ft.get(this.currentFlavour)}static get(t){if(!t)return ft.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new o(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t).filter(j.isModel)}catch(t){throw new o(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${L(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return H.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof ct&&(e=[t],t=this.migrations());const{ctx:r}=ft.logCtx(e,this.migrate),s=await this.getQueryRunner();for(const e of t)try{const t=new e;await t.up(s,this,r),await t.down(s,this,r)}catch(t){throw new ht(t)}}}i([I(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],ft.prototype,"shutdownProxies",null),i([I(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],ft.prototype,"context",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ft.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ft.prototype,"unObserve",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],ft.prototype,"client",null);class yt extends o{constructor(t){super(t,yt.name,500)}}class mt extends o{constructor(t){super(t,mt.name,500)}}var wt,bt,vt,xt,At,Et;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(wt||(wt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP"})(bt||(bt={})),(t=>{t.AND="AND",t.OR="OR"})(vt||(vt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(xt||(xt={}));class Ot extends j{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):j.fromModel(this,t)}and(t){return Ot.and(this,t)}or(t){return Ot.or(this,t)}not(t){return new Ot(this,bt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Ot)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(bt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof Ot){if(!(this.comparison instanceof Ot)&&this.operator!==bt.NOT)return{comparison:{condition:t}};if(-1===Object.values(vt).indexOf(this.operator)&&this.operator!==bt.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return Ot.group(t,vt.AND,e)}static or(t,e){return Ot.group(t,vt.OR,e)}static group(t,e,r){return new Ot(t,e,r)}static attribute(t){return(new Ot.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(bt.EQUAL,t)}dif(t){return this.setOp(bt.DIFFERENT,t)}gt(t){return this.setOp(bt.BIGGER,t)}lt(t){return this.setOp(bt.SMALLER,t)}gte(t){return this.setOp(bt.BIGGER_EQ,t)}lte(t){return this.setOp(bt.SMALLER_EQ,t)}in(t){return this.setOp(bt.IN,t)}regexp(t){return this.setOp(bt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Ot(this.attr1,this.operator,this.comparison)}catch(t){throw new yt(t)}}}}static builder(){return new Ot.Builder}static from(t){return new Ot(t)}}i([M(),n("design:type",Object)],Ot.prototype,"attr1",void 0),i([M(),n("design:type",String)],Ot.prototype,"operator",void 0),i([M(),n("design:type",Object)],Ot.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(At||(At={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Et||(Et={}));const St={update:Et.CASCADE,delete:Et.NONE},Nt={Equals:(t,e)=>Ot.attribute(t).eq(e),Diff:(t,e)=>Ot.attribute(t).dif(e),LessThan:(t,e)=>Ot.attribute(t).lt(e),LessThanEqual:(t,e)=>Ot.attribute(t).lte(e),GreaterThan:(t,e)=>Ot.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Ot.attribute(t).gte(e),In:(t,e)=>Ot.attribute(t).in(e),Matches:(t,e)=>Ot.attribute(t).regexp(e)},_t=t=>t.charAt(0).toLowerCase()+t.slice(1);class Ct extends R{static get log(){return this._logger||(this._logger=D.for(Ct.name)),this._logger}static build(t,...e){if(!t.startsWith(wt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(wt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})}static extractSelect(t){const e=t.indexOf(wt.SELECT);if(-1===e)return;const r=t.substring(e+wt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(wt.AND).map(_t).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(wt.GROUP_BY);if(-1!==e)return t.substring(e+wt.GROUP_BY.length).split(wt.ORDER_BY)[0].split(wt.THEN_BY).map(_t).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach((t,r)=>{const{field:n,operator:a}=this.parseFieldAndOperator(t),o=a?Nt[a]:Nt.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(n,c);i=0===r?l:s[r-1]===wt.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(Nt))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:_t(r),operator:e}}return{field:_t(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=Ct.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new yt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(At).includes(e))throw new yt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(At).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e){const r=this.extractCore(t).split(/And|Or/).length,s=e.slice(r)??[];let i,n,a;if(s.at(-1)instanceof c&&s.pop(),s.length>=1){const e=s[0],r=this.extractOrderByField(t);i=this.getProperlyOrderByOrThrow(r,e)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function Bt(){return V.for(nt.STATEMENT).define({decorator:()=>(t,e,r)=>J(X(H.key(nt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function Tt(t={}){return V.for(nt.QUERY).define({decorator:t=>(e,r,s)=>{const i=Ct.getFieldsFromMethodName(r);return J(X(H.key(nt.QUERY,r),{...t,fields:i}),Bt(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:a,orderBy:o,limit:c,offset:l}=Ct.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:u,allowOffset:d,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:d}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new yt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(h=h[t.key](t.value))}return h.execute()}})})(t))(e,r,s)},args:[t]}).apply()}class Pt extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new o("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=j.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},t&&(this._adapter=t),e&&(Pt.register(e,this,this.adapter.alias),t)&&H.get(e,K.FLAVOUR)===W&&Z(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;u(s,s[e+"Prefix"],t,s[e+"Suffix"])}),d(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(t,e){return ft.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new ot}async createPrefix(t,...e){const r=await ct.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(t=new this.class(t),s||await p(this,r.context,t,l.CREATE,l.ON),!i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new g(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${j.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,r)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${j.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async createAllPrefix(t,...e){const r=await ct.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=j.sequenceFor(t[0]);let a=[];if(j.generatedBySequence(this.class)?(n.name||(n.name=j.sequenceName(t[0],"pk")),a=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):j.generated(this.class,this.pk)||(a=t.map((t,e)=>{if(void 0===t[this.pk])throw new o("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?a[e]:""+t[this.pk]),s||await p(this,r.context,t,l.CREATE,l.ON),t))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),i=f(s);if(i)throw new g(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await ct.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await p(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${j.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await ct.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,p(this,r.context,e,l.READ,l.ON)})),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${j.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${j.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,i)}async updatePrefix(t,...e){const r=await ct.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context,i=s.get("ignoreHandlers"),n=s.get("ignoreValidation"),a=t[this.pk];if(!a)throw new o("No value for the Id is defined under the property "+this.pk);let c;if(s.get("applyUpdateValidation")&&(c=await this.read(a),s.get("mergeForUpdate")&&(t=j.merge(c,t,this.class))),i||await p(this,r.context,t,l.UPDATE,l.ON,c),!n){const e=await Promise.resolve(t.hasErrors(c,...r.context.get("ignoredValidationProperties")||[]));if(e)throw new g(e.toString())}return[t,...r.args,c]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${j.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const r=await ct.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context,i=s.get("ignoreHandlers"),n=s.get("ignoreValidation"),a=t.map(t=>{const e=t[this.pk];if(!e)throw new o("missing id on update operation");return e});let c;if(s.get("applyUpdateValidation")&&(c=await this.readAll(a,s),s.get("mergeForUpdate")&&(t=t.map((t,e)=>j.merge(c[e],t,this.class)))),i||await Promise.all(t.map((t,e)=>p(this,r.context,t,l.UPDATE,l.ON,c?c[e]:void 0))),!n){const e=s.get("ignoredValidationProperties")||[];let r;r=s.get("applyUpdateValidation")?await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(c[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const i=f(r);if(i)throw new g(i)}return[t,...r.args,c]}async deletePrefix(t,...e){const r=await ct.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await p(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${j.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await ct.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map(async t=>p(this,ct.childFrom(r.context),t,l.DELETE,l.ON))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${j.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}async query(t,e,r=At.ASC,s,i,...n){const a=await ct.args(nt.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:o}=this.logCtx(a.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(o)}async listBy(t,e,...r){const s=await ct.args(xt.LIST_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.listBy);return i.verbose(`listing ${j.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...n)}async paginateBy(t,e,r={offset:1,limit:10},...s){let{offset:i,bookmark:n,limit:a}=r;if(!i&&!n)throw new yt("PaginateBy needs a page or a bookmark");const o=await ct.args(xt.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:c,ctxArgs:l}=this.logCtx(o.args,this.paginateBy);let h;if(c.verbose(`paginating ${j.tableName(this.class)} with page size ${a}`),n)h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(this.attr(j.pk(this.class)).gt(n)).orderBy([t,e]).paginate(a,...l),i=1;else{if(!i)throw new yt("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...l)}const u=await h.page(i,...l);return h.serialize(u)}async findOneBy(t,e,...r){const s=await ct.args(xt.FIND_ONE_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findOneBy);i.verbose(`finding ${j.tableName(this.class)} with ${t} ${e}`);const a=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!a.length)throw new y("No results found");return a[0]}async findBy(t,e,...r){const s=await ct.args(xt.FIND_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findBy);return i.verbose(`finding ${j.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...n)}async statement(t,...e){if(!Pt.statements(this,t))throw new yt("Invalid prepared statement requested "+t);const r=await ct.args(nt.STATEMENT,this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:i}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...i)}attr(t){return Ot.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=j.tableName(this.class);this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:H.constr(t)===H.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString())}unObserve(t){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ft._baseSequence.parseValue(j.sequenceFor(this.class).type,t)):ft._baseSequence.parseValue(j.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||H.flavourOf(t)||ft.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Pt)return s;const n=e||H.flavourOf(t)||s&&H.get(s,nt.ADAPTER)||ft.currentFlavour,a=n?ft.get(n):void 0;if(!a)throw new o("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,t,...r)}static get(t,e){const r=j.tableName(t);let s=r;if(e&&(s=[r,e].join(m)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new o("Could not find repository registered under "+r)}static register(t,e,r){let s=j.tableName(t);if(r&&(s=[s,r].join(m)),s in this._cache&&this._cache[s]instanceof Pt)throw new o(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Pt?t.constructor:t,s=H.get(r,e?H.key(nt.STATEMENT,e):nt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Pt?t.constructor:t;return H.get(r,e?H.key(nt.QUERY,e):nt.QUERY)}}function $t(t,e){if(!(e||(e=V.flavourResolver(t instanceof j?t.constructor:t))&&e!==W))throw new o("Could not retrieve flavour from model "+(t instanceof j?t.constructor.name:t.name));return U(nt.INJECTABLE,e,j.tableName(t))}i([Bt(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Pt.prototype,"listBy",null),i([Bt(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Pt.prototype,"paginateBy",null),i([Bt(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Pt.prototype,"findOneBy",null),i([Bt(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Pt.prototype,"findBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Pt.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Pt.prototype,"unObserve",null),ft&&(ft._baseRepository=Pt);class Rt extends t{get log(){return this.logger||(this.logger=D.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=j.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(n=j.get(t.toString())),!n)return;const a=nt.ADAPTER,o=r||H.get(n,a);try{let t=o;try{o&&ft.get(o)}catch{const e=ft.current;e&&e.flavour===o&&(t=e.alias)}if(i=Pt.forModel(n,t),i instanceof Pt)return i;const r=o||H.get(i.constructor,a)||H.get(n,a);e.register(i,$t(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Pt.get(n,o);if("function"==typeof e){const t=o?ft.get(o):ft.current;if(!t)return;return new e(t,n)}}}return i}}async function Dt(t,e,r,s){const i=e.logger.for(Dt);if(!s){const e=j.get(t.constructor.name);if(!e)throw new o("Could not find model "+t.constructor.name);s=Pt.forModel(e,r),i.info("Retrieved "+s.toString())}let n;if(void 0===t[j.pk(s.class)])i.info(`No pk found in ${j.tableName(s.class)} - creating`),n=await s.create(t,e);else{i.info(`pk found in ${j.tableName(s.class)} - attempting update`);try{n=await s.update(t,e),i.info("Updated "+j.tableName(s.class))}catch(r){if(!(r instanceof y))throw r;i.info("update Failed - creating new "+j.tableName(s.class)),n=await s.create(t,e)}i.info("After create update: "+n)}return n}async function It(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=zt(s,r,this.adapter.alias),n=await e.read(i);return await qt(t,s,r,i,n),void(s[r]=i)}const n=k(e.class)?e.class:e.class();if(!n)throw new o("Could not find model "+e.class);const a=Pt.forModel(n,this.adapter.alias),c=await a.create(i,t),l=j.pk(c);await qt(t,s,r,c[l],c),s[r]=c[l]}async function kt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Et.CASCADE)return;if("object"!=typeof i){const e=zt(s,r,this.adapter.alias),n=await e.read(i,t);return await qt(t,s,r,i,n),void(s[r]=i)}const n=await Dt(s[r],t,this.adapter.alias),a=j.pk(n);await qt(t,s,r,n[a],n),s[r]=n[a]}async function Ft(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Et.CASCADE)return;const n=zt(s,r,this.adapter.alias);let a;a=i instanceof j?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await qt(t,s,r,a[n.pk],a)}async function jt(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new o(`Invalid operation. All elements of property ${r} must match the same type.`);const a=new Set([...i]);if("object"!==n){const e=zt(s,r,this.adapter.alias);for(const i of a){const n=await e.read(i,t);await qt(t,s,r,i,n)}return void(s[r]=[...a])}const c=j.pk(i[0].constructor),l=new Set;for(const e of i){const i=await Dt(e,t,this.adapter.alias);await qt(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function Lt(t,e,r,s){const{cascade:i}=e;if(i.update===Et.CASCADE)return jt.call(this,t,e,r,s)}async function Mt(t,e,r,s){if(e.cascade.delete!==Et.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new o(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),c="object"===n,l=c?Pt.forModel(a,this.adapter.alias):zt(s,r,this.adapter.alias),h=[...new Set([...c?i.map(t=>t[l.pk]):i]).values()];let u,d;try{u=await l.deleteAll(h,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){d=u[e];try{await qt(t,s,r,h[e],d)}catch(i){throw t.logger.error(`Failed to cache record ${h[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=h}function Ut(t,e,r){return[nt.POPULATE,t,e,r].join(".")}async function qt(t,e,r,s,i){const n=Ut(e.constructor.name,r,s),a=t.get("cacheForPopulate")||{};return a[n]=i,t.accumulate({cacheForPopulate:a})}async function Gt(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const a=await(async(e,r,s,i,n)=>{let a,c;const l=[],h=e.get("cacheForPopulate")||{};for(const e of i){a=Ut(r.constructor.name,s,e);try{if(c=h[a],!c)throw Error("Not found in cache")}catch(i){const a=zt(r,s,n);if(!a)throw new o("Could not find repo");c=await a.read(e,t)}l.push(c)}return l})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?a:a[0]}const Yt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function zt(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=H.get(t instanceof j?t.constructor:t,H.key(q.REFLECT,e,q.LIST))?.clazz;if(!r)throw new o("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=H.getPropDesignTypes(t instanceof j?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Yt.includes((""+t.name).toLowerCase()));return Pt.forModel(i,r)}class Qt extends w{constructor(t,e=Qt.name,r=401){super(t,e,r)}}class Ht extends Qt{constructor(t,e=Ht.name){super(t,e,403)}}class Vt extends o{constructor(t){super(t,Vt.name,503)}}function Wt(t){return V.for(nt.TABLE).define({decorator:t=>e=>tt(nt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Jt(t){return V.for(nt.COLUMN).define({decorator:t=>(e,r)=>et(H.key(nt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Xt(t,e,r){return V.for(nt.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![At.ASC,At.DSC].includes(t))&&(e=t,t=void 0),et(H.key(`${nt.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Kt(t,e,r,s){if(s[r]&&(await this.select().where(Ot.attribute(r).eq(s[r])).execute()).length)throw new b(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Zt(){const t=nt.UNIQUE;return V.for(t).define(G(),v(Kt),et(t,{})).apply()}async function te(t,e,r,s){throw new Qt("This adapter does not support user identification")}function ee(){return V.for(nt.CREATED_BY).define({decorator:()=>(t,e)=>J(A(te),et(nt.CREATED_BY,e),le())(t,e),args:[]}).apply()}function re(){return V.for(nt.UPDATED_BY).define({decorator:()=>(t,e)=>J(E(te),et(nt.UPDATED_BY,e),le())(t,e),args:[]}).apply()}function se(){return x([l.CREATE])}function ie(){return x()}function ne(t,e=St,r=!0,s,i){const n=nt.ONE_TO_ONE;return V.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),J(rt(),ge(n,a),Y([t,String,Number,BigInt]),A(It,a),E(kt,a),O(Ft,a),N(Gt,a))},args:[t,e,r,s,i]}).apply()}function ae(t,e=St,r=!0,s,i){const n=nt.ONE_TO_MANY;return V.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),J(rt(),ge(n,a),z([t,String,Number,BigInt]),A(jt,a),E(Lt,a),O(Mt,a),N(Gt,a))},args:[t,e,r,s,i]}).apply()}function oe(t,e=St,r=!0,s,i){const n=nt.MANY_TO_ONE;return V.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),J(rt(),ge(n,a),Y([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ce(t,e=St,r=!0,s,i){const n=nt.MANY_TO_MANY;return V.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),J(rt(),ge(n,a),z([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function le(){return(t,e)=>et(H.key(nt.GENERATED,e),!0)(t,e)}function he(...t){return(e,r)=>{const s=H.get(e,H.key(nt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return J(tt(H.key(nt.NO_VALIDATE,r),i))(e,r)}}function ue(){return he(l.CREATE)}function de(){return he(l.UPDATE)}function pe(){return he(l.UPDATE,l.CREATE)}function ge(t,e){return V.for(nt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(et(t,e)(r,s),et(H.key(nt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}V.for(_.TIMESTAMP).extend(le()).apply(),V.for(_.COMPOSED).extend(le()).apply(),H.validationExceptions=((t,e)=>{const r=H.get(t,nt.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t),i=j.nestedRelations(t);return[...new Set([...s,...i])]}).bind(H),H.migrationsFor=(t=>{if(!(t=t??ft.current))throw new o("Could not get adapter for migrations");return H.innerGet(Symbol.for(nt.MIGRATION),t.alias).map(t=>t.class)}).bind(H),H.relations=((t,e)=>{const r=H.get(t,nt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new o("No relations metadata found for property "+e);return r[e]}}).bind(H),j.relations=(t,e)=>H.relations(t instanceof j?t.constructor:t,e)||[],j.nestedRelations=(t,e)=>{e?.length||(e=j.relations(t));let r=[];const s=H.get(t,nt.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&j.relations(i.class)){const s=j.relations(i.class),n=s.map(e=>`${t}.${e}`);e=[...e,...s,...n],r=j.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]},j.generated=((t,e)=>!!H.get("function"!=typeof t?t.constructor:t,H.key(nt.GENERATED,e))).bind(H),j.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!j.sequenceFor(r).generated}).bind(H),H.createdBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,nt.CREATED_BY);if(!e)throw new o("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(H),H.updatedBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,nt.UPDATED_BY);if(!e)throw new o("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(H),j.tableName=t=>{if(!(t instanceof j?j.get(t.constructor.name):t))throw new o("Unable to find model "+t);return H.get(t instanceof j?t.constructor:t,nt.TABLE)||(t instanceof j?t.constructor.name:t.name)},j.columnName=(t,e)=>H.get(t instanceof j?t.constructor:t,H.key(nt.COLUMN,e))||e,j.sequenceName=(t,...e)=>[j.tableName(t),...e].join("_"),j.sequenceFor=(t,e)=>{if(e)throw new lt("not currently supported");const r=j.pkProps(t instanceof j?t.constructor:t);if(!r)throw new o("No sequence options defined for model. did you use the @pk decorator?");return r},j.indexes=t=>{const e=H.get(t instanceof j?t.constructor:t,nt.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[nt.INDEX]:e[r]},t),{})},e.services=()=>H.innerGet(Symbol.for(nt.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(_.REPOSITORY));class fe extends dt{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const t=this.adapter;[l.CREATE,l.UPDATE,l.DELETE,C.CREATE_ALL,C.UPDATE_ALL,C.DELETE_ALL].forEach(e=>{if(!t[e])throw new o(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(t=>{switch(t){case C.CREATE_ALL:return l.CREATE;case C.UPDATE_ALL:return l.UPDATE;case C.DELETE_ALL:return l.DELETE;default:return t}})(e),o,c,...n.slice(s.length)).then(()=>{i.verbose(`Observer refresh dispatched by ${e} for ${a}`),i.debug("pks: "+o)}).catch(t=>i.error(`Failed to dispatch observer refresh for ${e} on ${a}: ${t}`)),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof ft))throw new lt("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ft.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(t){if(this.adapter!==t)throw new lt("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const i="string"==typeof t?t:j.tableName(t),{log:n,ctxArgs:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...a)}catch(t){throw new o("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}ft&&(ft._baseDispatch=fe);class ye{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}static get instance(){return ye._instance||(ye._instance=new ye),ye._instance}}class me{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return me._instance||(me._instance=new me),me._instance}}function we(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof ut)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class be extends R{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;we(this,t,this.prefix(e))})}get adapter(){const t=H.get(this.constructor,nt.MIGRATION);if(!t)throw new o("No migration metadata for "+this.constructor.name);const e=t.flavour;return ft.get(e)}async enforceRules(t,e,r){const s=H.get(this.constructor,nt.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const i of s)if(!await i(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ft?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await ct.args("migration",j,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new ut("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function ve(t,e){return V.for(nt.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(nt.MIGRATION),t)||[];return H.set(nt.MIGRATION,t,[...s,{class:r}]),tt(nt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}class xe extends j{constructor(t){super(t)}}i([se(),n("design:type",Date)],xe.prototype,"createdAt",void 0),i([ie(),n("design:type",Date)],xe.prototype,"updatedAt",void 0);const Ae={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ee=Ae,Oe={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Se=Object.assign({},Oe,{type:"BigInt"});async function Ne(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=j.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new o(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,c;n=s,a=r,c=await i.next(t),Reflect.set(n,a,c)}function _e(t,e){return(r,s)=>{switch(rt()(r,s),t.type){case void 0:{const e=H.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[Xt([At.ASC,At.DSC]),M(),B(),et(H.key(_.ID,s),t),A(Ne,t,e)];return t.generated&&i.push(le()),J(...i)(r,s)}}function Ce(t=Ee){return t=Object.assign({},Ee,t),V.for(_.ID).define({decorator:_e,args:[t,{priority:60}]}).apply()}let Be=class extends xe{constructor(t){super(t)}};i([Ce({type:"String",generated:!1}),n("design:type",String)],Be.prototype,"id",void 0),i([M(),Xt(),n("design:type",Object)],Be.prototype,"current",void 0),Be=i([Wt("??sequence"),Q(),n("design:paramtypes",[Object])],Be);class Te extends dt{static{this.lock=new st}constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=Pt.forModel(Be,e.alias)}async current(...t){const e=(await ct.args(l.READ,Be,t,this.adapter)).context,{name:r,startWith:s}=this.options;try{const t=await this.repo.read(r,e);return this.parse(t.current)}catch(t){const i=e.logger.for(this.current);if(t instanceof y){if(i.debug(`Sequence.current missing ${r}, returning startWith=${s}`),void 0===s)throw new o("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new o(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new o(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e){const r=e.logger.for(this.increment),{type:s,incrementBy:i,name:n}=this.options;if(!n)throw new o("Sequence name is required");return Te.lock.execute(async()=>{const a=t||i;if(a%i!==0)throw new o("Value to increment does not consider the incrementBy setting: "+i);const c="function"==typeof s&&s?.name?s.name:s,l=await this.current(e),h=async t=>{try{return await this.repo.update(new Be({id:n,current:t}),e)}catch(s){if(s instanceof y)return r.debug(`Sequence create ${n} current=${l} next=${t}`),this.repo.create(new Be({id:n,current:t}),e);throw s}};if("uuid"===c)for(;;){const t=ye.instance.generate(l);try{const e=await h(t);return r.debug(`Sequence uuid increment ${n} current=${l} next=${t}`),e.current}catch(t){if(t instanceof b)continue;throw t}}const u=(t=>{switch(c){case Number.name:return this.parse(t)+a;case BigInt.name:return this.parse(t)+BigInt(a);case String.name:return this.parse(t);case"serial":return me.instance.generate(t);default:throw new o("Should never happen")}})(l),d=await h(u);return r.debug(`Sequence.increment ${n} current=${l} next=${u}`),d.current},n)}async next(...t){const e=await ct.args(l.UPDATE,Be,t,this.adapter),{context:r}=e;return this.increment(void 0,r)}async range(t,...e){const r=await ct.args(l.UPDATE,Be,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),a=this.parse(this.options.incrementBy),c=await this.increment(this.parse(t)*a,s),h=[];for(let e=1;t>=e;e++)h.push(n+a*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new lt(`type ${this.options.type} is currently not suppported for this adapter`);const u="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==u)throw new o("Miscalculation of range");return h}parse(t){return Te.parseValue(this.options.type,t)}static pk(t){return j.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new lt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Pe(t,e){return(i,n)=>n?r(H.constr(t))(i,n):(H.set(_.REPOSITORY,H.key(e||ft.currentFlavour,j.tableName(t)),i),tt(_.REPOSITORY,i.name)(t),e=e||H.get(i.constructor,nt.ADAPTER),Pt.register(H.constr(t),i,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,_.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ft._baseSequence=Te;class $e extends o{constructor(t){super(t,$e.name,500)}}class Re extends R{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,we(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${xt.FIND_BY}|${xt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){return[t,...(await ct.args(nt.QUERY,this.clazz,e,this.adapter)).args]}async pagePrepared(t,...e){const r=Pt.forModel(this.clazz,this.adapter.alias),s=this.query,{method:i,args:n,params:a}=s,o=RegExp(`^${xt.FIND_BY}|${xt.LIST_BY}`,"gi");if(!i.match(o))throw new lt(`Method ${i} is not supported for pagination`);o.lastIndex=0;const c=i.replace(o,xt.PAGE_BY),l=[c,...n];let h={limit:this.size,offset:t,bookmark:this._bookmark};c!==xt.PAGE_BY||l.length>2?h={direction:a.direction,limit:this.size,offset:t,bookmark:this._bookmark}:l.push(a.direction),l.push(h);const u=await r.statement(...l,...e);return this.apply(u)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new mt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new mt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,...e){const{ctxArgs:r}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...r);throw new lt("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new T(t)}}apply(t){const e="string"==typeof t?Re.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new T(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}function De(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&((t,e)=>{const{handler:r,args:s}=H.get(t,l.REFLECT+l.BLOCK)||{};return!!r&&(r(...s,e)??!1)})(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}const Ie=()=>De(l.CREATE),ke=()=>De(l.READ),Fe=()=>De(l.UPDATE),je=()=>De(l.DELETE);function Le(t){return t="string"==typeof t?t:H.Symbol(t).toString(),(e,i,n)=>{H.set(nt.SERVICE,t,e);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else a.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return a.push(tt(nt.SERVICE,t)),J(...a)(e,i,n)}}class Me{constructor(t){this.name=t,this.Context=ct}async flags(t,e,...r){let s=e.logger||D.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},at,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=e,i=await this.flags(t,s,...r);return(new this.Context).accumulate(i)}async logCtx(t,e,r=!1){return await Me.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const i=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await i()]);const n=t.pop();n instanceof ct||(t=[...t,await i()]);const a=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?a.for(e):a,ctxArgs:[...t,n]}}static get(t){if(!t)throw new o("No name provided");const r=e.get(t);if(r)return r;throw new o("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){const r={context:async t=>(new ct).accumulate(Object.assign({},at,{timestamp:new Date,operation:t,logger:D.get()}))},{log:s,ctxArgs:i}=await this.logCtx.bind(r)(t,this.boot,!0),n=e.services();for(const[t,e]of Object.entries(n))try{const t=new e;t instanceof Ue&&await t.boot(...i)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class Ue extends Me{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=await this.logCtx(t,this.boot,!0);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new o("Config not initialized");return this._config}get client(){if(!this._client)throw new o("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],Ue.prototype,"boot",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ue.prototype,"config",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ue.prototype,"client",null);const qe=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Ge extends Me{get class(){if(!this.clazz)throw new o("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Pt.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new o("No name provided");const e=qe(t);try{const t=Me.get(e);if(t)return t}catch(t){}throw new o("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.create,!0);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.createAll,!0);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.delete,!0);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.deleteAll,!0);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.read,!0);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.readAll,!0);return this.repo.readAll(t,...r)}async query(t,...e){const r=this.repo?.[t];if("function"!=typeof r)throw Error(`Method "${t}" is not implemented`);return r.apply(this.repo,e)}async update(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.update,!0);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.updateAll,!0);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.listBy,!0);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=await this.logCtx(s,this.paginateBy,!0);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findOneBy,!0);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findBy,!0);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.statement,!0);return this.repo.statement(t,...r)}async logCtx(t,e,r=!1){return await Ge.logCtx.bind(this.repo.adapter)(t,e,r,this.repo._overrides,this.class)}static forModel(t,e){let r;e=qe(e||t);try{r=Ge.get(e)}catch(t){r=void 0}if(r instanceof Ge)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([Le(e),n("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);let a=t.pop();a instanceof ct||(void 0!==a&&t.push(a),a=await n());const c=this?a.logger.for(this).for(e):a.logger.clear().for(this).for(e);return{ctx:a,log:c,ctxArgs:[...t,a]}}}var Ye,ze,Qe,He;i([Ie(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ge.prototype,"create",null),i([Ie(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ge.prototype,"createAll",null),i([je(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ge.prototype,"delete",null),i([je(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ge.prototype,"deleteAll",null),i([ke(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ge.prototype,"read",null),i([ke(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ge.prototype,"readAll",null),i([ke(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Ge.prototype,"query",null),i([Fe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ge.prototype,"update",null),i([Fe(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Ge.prototype,"updateAll",null);class Ve extends dt{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{P(this,t,async(...e)=>{let r=e;if((!r.length||!(r[r.length-1]instanceof ct))&&this.fromSelector){const t=await this.adapter.context(nt.QUERY,this.overrides||{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=ft.logCtx(r,t.name),n=s.get("forcePrepareSimpleQueries"),a=s.get("forcePrepareComplexQueries");return(n&&this.isSimpleQuery()||a)&&await this.prepare(s),i},t.name)})}get log(){return this.adapter.log.for(Ve)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?j.get(t):t,!this.fromSelector)throw new yt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){try{if(this.prepared)return this.executePrepared(...t);const e=this.build();return await this.raw(e,...t)}catch(t){throw new yt(t)}}async executePrepared(...t){const e=Pt.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new lt("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=j.pk(this.fromSelector),a=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(a):a(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case vt.AND:case vt.OR:{let t=r,a=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Ot){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case bt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case bt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case bt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case bt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case bt.BIGGER_EQ:n.method=r+" bigger than equal";break;case bt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case bt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case bt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new yt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof Ot)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,At.DSC]:[j.pk(this.fromSelector),At.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const a={class:this.fromSelector,method:xt.LIST_BY,args:[s],params:n};return e&&(a.method=xt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(nt.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[wt.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(wt.SELECT,this.selectSelector.join(` ${wt.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(wt.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(wt.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=F(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new yt(t)}}toString(){return this.adapter.flavour+" statement"}}i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ve.prototype,"select",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ye="undefined"!=typeof S&&S)?Ye:Object]),n("design:returntype",Object)],Ve.prototype,"distinct",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ze="undefined"!=typeof S&&S)?ze:Object]),n("design:returntype",Object)],Ve.prototype,"max",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Qe="undefined"!=typeof S&&S)?Qe:Object]),n("design:returntype",Object)],Ve.prototype,"min",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(He="undefined"!=typeof S&&S)?He:Object]),n("design:returntype",Object)],Ve.prototype,"count",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ve.prototype,"from",null),i([I(),n("design:type",Function),n("design:paramtypes",[Ot]),n("design:returntype",Object)],Ve.prototype,"where",null),i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ve.prototype,"orderBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ve.prototype,"groupBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ve.prototype,"limit",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ve.prototype,"offset",null),i([I(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Ve.prototype,"execute",null);class We extends Ve{constructor(t,e){super(t,e)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new o("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,n=(i+"").toLowerCase()===At.ASC?1:-1,a=t[s],c=e[s];if(a===c)return 0;if(null==a||null==c)return n*(null==a?1:-1);const{designType:l}=H.getPropDesignTypes(t.constructor,s),h=l&&l.name&&l.name.toLowerCase()||typeof a;switch(h){case"string":return n*this.compareStrings(a,c);case"number":return n*this.compareNumbers(a,c);case"bigint":return n*this.compareBigInts(a,c);case"boolean":return n*this.compareBooleans(a,c);case"date":case"object":if(a instanceof Date&&c instanceof Date)return n*this.compareDates(a,c)}throw new yt("sorting not supported for type "+h)}}compareBooleans(t,e){return t===e?0:t?1:-1}compareNumbers(t,e){return t-e}compareBigInts(t,e){return t===e?0:t>e?1:-1}compareStrings(t,e){return t.localeCompare(e)}compareDates(t,e){return t.valueOf()-e.valueOf()}build(){const t={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:t=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(t.sort=this.getSort()),t}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[vt.AND,vt.OR,bt.NOT].indexOf(s))switch(s){case bt.BIGGER:return e[r]>i;case bt.BIGGER_EQ:return e[r]>=i;case bt.DIFFERENT:return e[r]!==i;case bt.EQUAL:return e[r]===i;case bt.REGEXP:if("string"!=typeof e[r])throw new yt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case bt.SMALLER:return e[r]<i;case bt.SMALLER_EQ:return e[r]<=i;default:throw new o("Invalid operator for standard comparisons: "+s)}else{if(s===bt.NOT)throw new o("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case vt.AND:return t.where(e)&&n.where(e);case vt.OR:return t.where(e)||n.where(e);default:throw new o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Je(t,e,r,s){const i=t.get("UUID");if(!i)throw new lt("This adapter does not support user identification");s[r]=i}const Xe="ram";class Ke extends Re{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const{ctx:r,ctxArgs:s}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...s);const i=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)t=this.validatePage(t),i.skip=(t-1)*this.size,n=await this.adapter.raw(i,!0,...e,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...i,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const t=i?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}return this._currentPage=t,n.data||n}}class Ze extends ft{constructor(t={},e){super(t,Xe,e),this.indexes={},this.lock=new it}repository(){return super.repository()}async flags(t,e,r){return Object.assign(await super.flags(t,e,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...t){return Promise.resolve(void 0)}prepare(t,...e){const r=e.pop();return super.prepare(t,...e,r)}revert(t,e,r,s,...i){return super.revert(t,e,r,s,...i)}async create(t,e,r,s){const i=s.logger.for(this.create),n=j.tableName(t);if(i.debug(`creating record in table ${n} with id ${e}`),this.client.has(n)||this.client.set(n,new Map),this.client.get(n)&&this.client.get(n)?.has(e))throw new b(`Record with id ${e} already exists in table ${n}`);return await this.lock.acquire(),this.client.get(n)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=j.tableName(t);if(!this.client.has(s))throw new y(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new y(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const i=s.logger.for(this.update),n=j.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),!this.client.has(n))throw new y(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new y(`Record with id ${e} not found in table ${n}`);return await this.lock.acquire(),this.client.get(n)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),i=j.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),!this.client.has(i))throw new y(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new y(`Record with id ${e} not found in table ${i}`);await this.lock.acquire(),this.client.get(i);const n=this.client.get(i)?.get(e);return this.client.get(i)?.delete(e),this.lock.release(),n}tableFor(t){"string"==typeof t&&(t=j.get(t));const e=j.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e=!0,r){r.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:s,sort:i,limit:n,skip:a,from:c}=t;let{select:l}=t;const h=this.tableFor(c);if(!h)throw new o(`Table ${c} not found in RamAdapter`);const u=j.pk(c),d=H.get(c,H.key(_.ID,u));let p=Array.from(h.entries()).map(([t,e])=>this.revert(e,c,Te.parseValue(d.type,t),void 0,r));p=s?p.filter(s):p;const g=p.length;return i&&(p=p.sort(i)),a&&(p=p.slice(a)),n&&(p=p.slice(0,n)),l&&(l=Array.isArray(l)?l:[l],p=p.map(t=>Object.entries(t).reduce((t,[e,r])=>(l.includes(e)&&(t[e]=r),t),{}))),e?p:{data:p,count:g}}parseError(t){return t instanceof $?t:new o(t)}Statement(t){return new We(this,t)}Paginator(t,e,r){return new Ke(this,t,e,r)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${L(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const i=Reflect.get(e,r,s);return Object.assign({},i,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=nt.CREATED_BY,e=nt.UPDATED_BY;V.flavouredAs(Xe).for(t).define(A(Je),et(t,{})).apply(),V.flavouredAs(Xe).for(e).define(v(Je),et(e,{})).apply()}getClient(){return new Map}}Ze.decoration(),e.setRegistry(new Rt);const tr="##VERSION##",er="##PACKAGE##";H.registerLibrary(er,tr);export{be as AbsMigration,ft as Adapter,Qt as AuthorizationError,xe as BaseModel,Se as BigIntSequence,Et as Cascade,Ue as ClientBasedService,Ot as Condition,Vt as ConnectionError,ct as Context,dt as ContextualLoggedClass,at as DefaultAdapterFlags,St as DefaultCascade,Ee as DefaultSequenceOptions,fe as Dispatch,Ht as ForbiddenError,vt as GroupOperator,Rt as InjectablesRegistry,Ct as MethodQueryBuilder,ht as MigrationError,ut as MigrationRuleError,Ge as ModelService,Ae as NoneSequenceOptions,Oe as NumericSequence,$e as ObserverError,ot as ObserverHandler,bt as Operator,Nt as OperatorsMap,At as OrderDirection,er as PACKAGE_NAME,Re as Paginator,mt as PagingError,nt as PersistenceKeys,xt as PreparedStatementKeys,wt as QueryClause,yt as QueryError,Ze as RamAdapter,Xe as RamFlavour,Ke as RamPaginator,We as RamStatement,Pt as Repository,Te as Sequence,Be as SequenceModel,me as Serial,Me as Service,Ve as Statement,ye as UUID,lt as UnsupportedError,tr as VERSION,qt as cacheModelForPopulate,Jt as column,Ie as create,Dt as createOrUpdate,se as createdAt,ee as createdBy,te as createdByOnCreateUpdate,Je as createdByOnRamCreateUpdate,je as del,$t as generateInjectableNameForRepository,le as generated,Ut as getPopulateKey,Xt as index,ce as manyToMany,oe as manyToOne,ve as migration,he as noValidateOn,ue as noValidateOnCreate,pe as noValidateOnCreateUpdate,de as noValidateOnUpdate,ae as oneToMany,jt as oneToManyOnCreate,Mt as oneToManyOnDelete,Lt as oneToManyOnUpdate,ne as oneToOne,It as oneToOneOnCreate,Ft as oneToOneOnDelete,kt as oneToOneOnUpdate,Ce as pk,_e as pkDec,Ne as pkOnCreate,Gt as populate,we as prefixMethod,Bt as prepared,Tt as query,ke as read,ge as relation,Pe as repository,zt as repositoryFromTypeMetadata,Le as service,Wt as table,Zt as unique,Kt as uniqueOnCreateUpdate,Fe as update,ie as updatedAt,re as updatedBy};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|