@decaf-ts/core 0.7.9 → 0.7.10
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/ram/RamPaginator.js +1 -1
- package/lib/esm/ram/RamPaginator.js.map +1 -1
- package/lib/esm/repository/Repository.js +16 -16
- package/lib/esm/repository/Repository.js.map +1 -1
- package/lib/ram/RamPaginator.cjs +1 -1
- package/lib/ram/RamPaginator.js.map +1 -1
- package/lib/repository/Repository.cjs +16 -16
- package/lib/repository/Repository.js.map +1 -1
- package/package.json +1 -1
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 n,__metadata as i}from"tslib";import{InternalError as a,Context as o,DefaultRepositoryFlags as c,OperationKeys as l,Repository as u,wrapMethodWithContext as d,enforceDBDecorators as h,ValidationError as p,reduceErrorsToPrint as g,DefaultSeparator as f,BulkCrudOperationKeys as y,NotFoundError as w,BadRequestError as m,ConflictError as b,onCreateUpdate as v,timestamp as x,onCreate as A,onUpdate as E,onDelete as O,afterAny as N,readonly as T,DBKeys as C,BaseError as _}from"@decaf-ts/db-decorators";import{Model as $,hashObj as R,required as P,sf as D,ValidationKeys as I,async as B,type as j,list as k,model as L}from"@decaf-ts/decorator-validation";import{LoggedClass as F,Logging as M,final as U,isClass as q}from"@decaf-ts/logging";import{Decoration as G,DefaultFlavour as z,Metadata as H,apply as Y,methodMetadata as V,DecorationKeys as Q,uses as W,metadata as X,propMetadata as J,prop as K}from"@decaf-ts/decoration";import{Lock as Z}from"@decaf-ts/transactional-decorators";var tt;(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"})(tt||(tt={}));class et{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new a("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 a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:n,ctxArgs:i}=ot.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,...i)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...i)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class rt extends a{constructor(t){super(t,rt.name,500)}}class st extends a{constructor(t,e=st.name){super(t,e,500)}}class nt extends st{constructor(t){super(t,nt.name)}}class it extends F{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return it.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof o))throw new a("No context provided");if(t.filter(t=>t instanceof o).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 at=G.flavourResolver.bind(G);G.flavourResolver=t=>{try{const e=at(t);if(e&&e!==z)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof H.registeredFlavour?H.registeredFlavour(r):void 0;if(s&&s!==z)return s;const n=ot._currentFlavour;if(n){const t=ot._cache?.[n];return t?.flavour?t.flavour:n}}catch(t){return z}};class ot extends it{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ot._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return ot._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("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=o,this.alias in ot._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ot._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ot._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ot._currentFlavour=this.alias)}Dispatch(){return new ot._baseDispatch}ObserverHandler(){return new et}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ot._baseSequence(t,this)}async flags(t,e,r,...s){let n=r.logger||M.for(this.toString());return r.correlationId&&(n=n.for({correlationId:r.correlationId})),Object.assign({},c,r,{affectedTables:(Array.isArray(e)?e:[e]).map($.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:H.validationExceptions(e,t),logger:n})}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 n=await this.flags(t,r,e,...s);return(new this.Context).accumulate(n)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),n=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const n=$.columnName(t.constructor,r);if(this.isReserved(n))throw new a(`Property name ${n} is reserved`);return e[n]=s,e},{});return t[tt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[tt.METADATA]),Object.defineProperty(n,tt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[tt.METADATA]})),{record:n,id:t[$.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...n){const{log:i,ctx:o}=this.logCtx(n,this.revert),c={},l=$.pk(e);c[l]=r;const u=new e(c);i.silly(`Rebuilding model ${u.constructor.name} id ${r}`);const d=t[tt.METADATA],h=Object.keys(u).reduce((r,s)=>(s===l||(r[s]=t[$.columnName(e,s)]),r),u);return o.get("rebuildWithTransient")&&s&&(i.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in h)throw new a(`Transient property ${t} already exists on model ${u.constructor.name}. should be impossible`);h[t]=e})),d&&(i.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${r}: ${d}`),Object.defineProperty(h,tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),h}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:n,ctxArgs:i}=this.logCtx(s,this.createAll),o=$.tableName(t);return n.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.create(t,e,r[s],...i)))}async readAll(t,e,...r){const{log:s,ctxArgs:n}=this.logCtx(r,this.readAll),i=$.tableName(t);return s.debug(`Reading ${e.length} entries ${i} table`),Promise.all(e.map(e=>this.read(t,e,...n)))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:n,ctxArgs:i}=this.logCtx(s,this.updateAll),o=$.tableName(t);return n.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...i)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:n}=ot.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map(e=>this.delete(t,e,...n)))}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 a("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 a("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:i}=ot.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...i)}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(!ot._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return ot._currentFlavour}static get current(){return ot.get(this.currentFlavour)}static get(t){if(!t)return ot.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t)}catch(t){throw new a(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} - ${R(t)}`;if(r in this.proxies)return this.proxies[r];let s;const n=new Proxy(this,{get:(e,r,n)=>{if("_config"===r){const s=Reflect.get(e,r,n);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,n)},set:(t,e,r,n)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,n)});return this.proxies[r]=n,n}migrations(){return H.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof o&&(e=[t],t=this.migrations());const{ctx:r}=ot.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 st(t)}}}var ct,lt;n([U(),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],ot.prototype,"shutdownProxies",null),n([U(),i("design:type",Function),i("design:paramtypes",[String,Object,Object,Object]),i("design:returntype",Promise)],ot.prototype,"context",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object,Function]),i("design:returntype",void 0)],ot.prototype,"observe",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",void 0)],ot.prototype,"unObserve",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],ot.prototype,"client",null),(t=>{t.ASC="asc",t.DSC="desc"})(ct||(ct={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(lt||(lt={}));const ut={update:lt.CASCADE,delete:lt.NONE};var dt,ht,pt;(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"})(dt||(dt={})),(t=>{t.AND="AND",t.OR="OR"})(ht||(ht={}));class gt extends a{constructor(t){super(t,gt.name,500)}}class ft extends a{constructor(t){super(t,ft.name,500)}}class yt extends ${constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=t,this.operator=e,this.comparison=r}and(t){return yt.and(this,t)}or(t){return yt.or(this,t)}not(t){return new yt(this,dt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof yt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(dt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof yt){if(!(this.comparison instanceof yt)&&this.operator!==dt.NOT)return{comparison:{condition:t}};if(-1===Object.values(ht).indexOf(this.operator)&&this.operator!==dt.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 yt.group(t,ht.AND,e)}static or(t,e){return yt.group(t,ht.OR,e)}static group(t,e,r){return new yt(t,e,r)}static attribute(t){return(new yt.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(dt.EQUAL,t)}dif(t){return this.setOp(dt.DIFFERENT,t)}gt(t){return this.setOp(dt.BIGGER,t)}lt(t){return this.setOp(dt.SMALLER,t)}gte(t){return this.setOp(dt.BIGGER_EQ,t)}lte(t){return this.setOp(dt.SMALLER_EQ,t)}in(t){return this.setOp(dt.IN,t)}regexp(t){return this.setOp(dt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new yt(this.attr1,this.operator,this.comparison)}catch(t){throw new gt(t)}}}}static builder(){return new yt.Builder}}n([P(),i("design:type",Object)],yt.prototype,"attr1",void 0),n([P(),i("design:type",String)],yt.prototype,"operator",void 0),n([P(),i("design:type",Object)],yt.prototype,"comparison",void 0),(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"})(pt||(pt={}));const wt={Equals:(t,e)=>yt.attribute(t).eq(e),Diff:(t,e)=>yt.attribute(t).dif(e),LessThan:(t,e)=>yt.attribute(t).lt(e),LessThanEqual:(t,e)=>yt.attribute(t).lte(e),GreaterThan:(t,e)=>yt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>yt.attribute(t).gte(e),Between:(t,e,r)=>yt.attribute(t).gte(e).and(yt.attribute(t).lte(r)),In:(t,e)=>yt.attribute(t).in(e),Matches:(t,e)=>yt.attribute(t).regexp(e)},mt=t=>t.charAt(0).toLowerCase()+t.slice(1);class bt{static build(t,...e){if(!t.startsWith(pt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),i=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:i,groupBy:n,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(pt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static extractSelect(t){const e=t.indexOf(pt.SELECT);if(-1===e)return;const r=t.substring(e+pt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(pt.AND).map(mt).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(pt.GROUP_BY);if(-1!==e)return t.substring(e+pt.GROUP_BY.length).split(pt.ORDER_BY)[0].split(pt.THEN_BY).map(mt).filter(Boolean)}static buildWhere(t,e){const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(r.forEach((t,r)=>{const{field:i,operator:a}=this.parseFieldAndOperator(t),o=a?wt[a]:wt.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+i);const l=o(i,c);n=0===r?l:s[r-1]===pt.AND?n.and(l):n.or(l)}),!n)throw Error("No conditions found in method name");return n}static parseFieldAndOperator(t){for(const e of Object.keys(wt))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:mt(r),operator:e}}return{field:mt(t)}}static extractOrderLimitOffset(t,e){const r=t.split(/And|Or/).length,s=e.slice(r);let n,i,a;return s.length>=1&&Array.isArray(s[0])&&(n=s[0]),2>s.length||"number"!=typeof s[1]||(i=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:n,limit:i,offset:a}}}function vt(){return G.for(tt.STATEMENT).define({decorator:()=>(t,e,r)=>Y(V(H.key(tt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function xt(t={}){return G.for(tt.QUERY).define({decorator:t=>(e,r,s)=>Y(V(H.key(tt.QUERY,r),t),vt(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:n,where:i,groupBy:a,orderBy:o,limit:c,offset:l}=bt.build(e.name,...s);let u=r.select(n);i&&(u=u.where(i));const{allowLimit:d,allowOffset:h,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:h}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new gt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(u=u[t.key](t.value))}return u.execute()}})})(t))(e,r,s),args:[t]}).apply()}class At extends u{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 a("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=$.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(At.register(e,this,this.adapter.alias),t)&&H.get(e,Q.FLAVOUR)===z&&W(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 ot.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const n=Reflect.get(e,r,s);return"_overrides"!==r?n:Object.assign({},n,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,n)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,n)})}ObserverHandler(){return new et}async createPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),n=!r.context.get("ignoreValidation");if(t=new this.class(t),s&&await h(this,r.context,t,l.CREATE,l.ON),n){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:n}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${$.tableName(this.class)}`);let{record:i,id:a,transient:o}=this.adapter.prepare(t,r);return i=await this.adapter.create(this.class,a,i,...n),this.adapter.revert(i,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:n}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const i=t.map(t=>this.adapter.prepare(t,r)),a=i.map(t=>t.id);let o=i.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...n),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?i[e].transient:void 0,r))}async createAllPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),n=!r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const i=$.sequenceFor(t[0]);let c=[];if(i.type?(i.name||(i.name=$.sequenceName(t[0],"pk")),c=await(await this.adapter.Sequence(i)).range(t.length,...r.args)):c=t.map((t,e)=>{if(void 0===t[this.pk])throw new a("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),i.type&&(t[this.pk]="String"!==i.type||i.generated?c[e]:""+t[this.pk]),s&&await h(this,r.context,t,l.CREATE,l.ON),t))),n){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),n=g(s);if(n)throw new p(n)}return[t,...r.args]}async readPrefix(t,...e){const r=await o.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await h(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${$.tableName(this.class)} with pk ${this.pk}`);const i=await this.adapter.read(this.class,t,...n);return this.adapter.revert(i,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await o.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,h(this,r.context,e,l.READ,l.ON)})),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...n)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:n}=this.logCtx(e,this.update);let{record:i,id:a,transient:o}=this.adapter.prepare(t,n);return s.debug(`updating ${this.class.name} in table ${$.tableName(this.class)} with id ${a}`),i=await this.adapter.update(this.class,a,i,...r),this.adapter.revert(i,this.class,a,o,n)}async updatePrefix(t,...e){const r=await o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),n=!r.context.get("ignoreValidation"),i=t[this.pk];if(!i)throw new a("No value for the Id is defined under the property "+this.pk);const c=await this.read(i,...r.args);if(t=$.merge(c,t,this.class),s&&await h(this,r.context,t,l.UPDATE,l.ON,c),n){const e=await Promise.resolve(t.hasErrors(c,...$.relations(this.class),...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:n}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const i=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,i.map(t=>t.id),i.map(t=>t.record),...n)).map((t,e)=>this.adapter.revert(t,this.class,i[e].id,r.get("rebuildWithTransient")?i[e].transient:void 0,r))}async updateAllPrefix(t,...e){const r=await o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),n=!r.context.get("ignoreValidation"),i=t.map(t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e}),c=await this.readAll(i,...r.args);if(t=t.map((t,e)=>$.merge(c[e],t,this.class)),s&&await Promise.all(t.map((t,e)=>h(this,r.context,t,l.UPDATE,l.ON,c[e]))),n){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(c[r],t,...e)))),n=g(s);if(n)throw new p(n)}return[t,...r.args]}async deletePrefix(t,...e){const r=await o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await h(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${$.tableName(this.class)} with pk ${t}`);const i=await this.adapter.delete(this.class,t,...n);return this.adapter.revert(i,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await o.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=>h(this,r.context,t,l.DELETE,l.ON))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...n)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=ct.ASC,s,n){const i=[e,r],a=this.select().where(t).orderBy(i);return s&&a.limit(s),n&&a.offset(n),a.execute()}async listBy(t,e,...r){const s=await o.args("list",this.class,r,this.adapter,this._overrides||{}),{log:n,ctxArgs:i}=this.logCtx(s.args,this.listBy);return n.verbose(`listing ${$.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r,...s){const n=await o.args("paginateBy",this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:a}=this.logCtx(n.args,this.paginateBy);return i.verbose(`paginating ${$.tableName(this.class)} with page size ${r}`),this.select().orderBy([t,e]).paginate(r,...a)}async findOneBy(t,e,...r){const s=await o.args("findOneBy",this.class,r,this.adapter,this._overrides||{}),{log:n,ctxArgs:i}=this.logCtx(s.args,this.findOneBy);return n.verbose(`finding ${$.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async statement(t,...e){if(!At.statements(this,t))throw new gt("Invalid prepared statement requested "+t);const r=await o.args("statement",this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:n}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...n)}attr(t){return yt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=$.tableName(this.class);this.adapter.observe(this,(t,e,r,...n)=>"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 a("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 a("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:i}=this.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ot._baseSequence.parseValue($.sequenceFor(this.class).type,t)):ot._baseSequence.parseValue($.sequenceFor(this.class).type,r),...i)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const n=e||H.flavourOf(t)||ot.currentFlavour;try{s=this.get(t,n)}catch(t){s=void 0}if(s instanceof At)return s;const i=e||H.flavourOf(t)||s&&H.get(s,tt.ADAPTER)||ot.currentFlavour,o=i?ot.get(i):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+i);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=$.tableName(t);let s=r;if(e&&(s=[r,e].join(f)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=$.tableName(t);if(r&&(s=[s,r].join(f)),s in this._cache&&this._cache[s]instanceof At)throw new a(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof At?t.constructor:t,s=H.get(r,e?H.key(tt.STATEMENT,e):tt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof At?t.constructor:t;return H.get(r,e?H.key(tt.QUERY,e):tt.QUERY)}}function Et(t,e){if(!(e||(e=G.flavourResolver(t instanceof $?t.constructor:t))&&e!==z))throw new a("Could not retrieve flavour from model "+(t instanceof $?t.constructor.name:t.name));return D(tt.INJECTABLE,e,$.tableName(t))}n([vt(),i("design:type",Function),i("design:paramtypes",[Object,String,void 0]),i("design:returntype",Promise)],At.prototype,"listBy",null),n([vt(),i("design:type",Function),i("design:paramtypes",[Object,String,Number,void 0]),i("design:returntype",Promise)],At.prototype,"paginateBy",null),n([vt(),i("design:type",Function),i("design:paramtypes",[Object,Object,void 0]),i("design:returntype",Promise)],At.prototype,"findOneBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object,Function]),i("design:returntype",void 0)],At.prototype,"observe",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",void 0)],At.prototype,"unObserve",null),ot&&(ot._baseRepository=At);class Ot extends t{get log(){return this.logger||(this.logger=M.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let n;try{n=super.get(t)}catch{}if(!n){let i;if("function"==typeof t?i=$.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(i=$.get(t.toString())),!i)return;const a=tt.ADAPTER,o=r||H.get(i,a);try{let t=o;try{o&&ot.get(o)}catch{const e=ot.current;e&&e.flavour===o&&(t=e.alias)}if(n=At.forModel(i,t),n instanceof At)return n;const r=o||H.get(n.constructor,a)||H.get(i,a);e.register(n,Et(i,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=At.get(i,o);if("function"==typeof e){const t=o?ot.get(o):ot.current;if(!t)return;return new e(t,i)}}}return n}}class Nt extends it{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,y.CREATE_ALL,y.UPDATE_ALL,y.DELETE_ALL].forEach(e=>{if(!t[e])throw new a(`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:n,ctxArgs:i}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,i);return this.updateObservers(a,(t=>{switch(t){case y.CREATE_ALL:return l.CREATE;case y.UPDATE_ALL:return l.UPDATE;case y.DELETE_ALL:return l.DELETE;default:return t}})(e),o,c,...i.slice(s.length)).then(()=>{n.verbose(`Observer refresh dispatched by ${e} for ${a}`),n.debug("pks: "+o)}).catch(t=>n.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 ot))throw new rt("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ot.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 rt("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const n="string"==typeof t?t:$.tableName(t),{log:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{i.debug(`Dispatching ${e} from table ${n} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${n}:${e}`)}}ot&&(ot._baseDispatch=Nt);class St{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 St._instance||(St._instance=new St),St._instance}}class Tt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Tt._instance||(Tt._instance=new Tt),Tt._instance}}function Ct(t,e,r,s){const n=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof nt)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),i=s||e.name;Object.defineProperty(n,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),t[i]=n}class _t extends F{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;Ct(this,t,this.prefix(e))})}get adapter(){const t=H.get(this.constructor,tt.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return ot.get(e)}async enforceRules(t,e,r){const s=H.get(this.constructor,tt.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const n of s)if(!await n(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ot?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await o.args("migration",$,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new nt("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function $t(t,e){return G.for(tt.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(tt.MIGRATION),t)||[];return H.set(tt.MIGRATION,t,[...s,{class:r}]),X(tt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}async function Rt(t,e,r,s){if(!s){const e=$.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=At.forModel(e,r)}if(void 0===t[$.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof w))throw r;return s.create(t,e)}}async function Pt(t,e,r,s){const n=s[r];if(!n)return;if("object"!=typeof n){const e=qt(s,r,this.adapter.alias),i=await e.read(n);return await Ft(t,s,r,n,i),void(s[r]=n)}const i=q(e.class)?e.class:e.class();if(!i)throw new a("Could not find model "+e.class);const o=At.forModel(i,this.adapter.alias),c=await o.create(n),l=$.pk(c);await Ft(t,s,r,c[l],c),s[r]=c[l]}async function Dt(t,e,r,s){const n=s[r];if(!n)return;if(e.cascade.update!==lt.CASCADE)return;if("object"!=typeof n){const e=qt(s,r,this.adapter.alias),i=await e.read(n);return await Ft(t,s,r,n,i),void(s[r]=n)}const i=await Rt(s[r],t,this.adapter.alias),a=$.pk(i);await Ft(t,s,r,i[a],i),s[r]=i[a]}async function It(t,e,r,s){const n=s[r];if(!n)return;if(e.cascade.update!==lt.CASCADE)return;const i=qt(s,r,this.adapter.alias);let a;a=n instanceof $?await i.delete(s[r][i.pk]):await i.delete(s[r]),await Ft(t,s,r,a[i.pk],a)}async function Bt(t,e,r,s){const n=s[r];if(!n||!n.length)return;const i=typeof n[0];if(!n.every(t=>typeof t===i))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...n]);if("object"!==i){const e=qt(s,r,this.adapter.alias);for(const n of o){const i=await e.read(n);await Ft(t,s,r,n,i)}return void(s[r]=[...o])}const c=$.pk(n[0]),l=new Set;for(const e of n){const n=await Rt(e,t,this.adapter.alias);await Ft(t,s,r,n[c],n),l.add(n[c])}s[r]=[...l]}async function jt(t,e,r,s){const{cascade:n}=e;if(n.update===lt.CASCADE)return Bt.call(this,t,e,r,s)}async function kt(t,e,r,s){if(e.cascade.delete!==lt.CASCADE)return;const n=s[r];if(!n||!n.length)return;const i=typeof n[0];if(!n.every(t=>typeof t===i))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===i,c=o?At.forModel(n[0],this.adapter.alias):qt(s,r,this.adapter.alias),l=new Set([...o?n.map(t=>t[c.pk]):n]);for(const e of l.values()){const n=await c.delete(e);await Ft(t,s,r,e,n)}s[r]=[...l]}function Lt(t,e,r){return[tt.POPULATE,t,e,r].join(".")}async function Ft(t,e,r,s,n){const i=Lt(e.constructor.name,r,s);return t.accumulate({[i]:n})}async function Mt(t,e,r,s){if(!e.populate)return;const n=s[r],i=Array.isArray(n);if(void 0===n||i&&0===n.length)return;const o=await(async(t,e,r,s,n)=>{let i,o;const c=[];for(const l of s){i=Lt(e.constructor.name,r,l);try{o=await t.get(i)}catch(t){const s=qt(e,r,n);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,i?n:[n],this.adapter.alias);s[r]=i?o:o[0]}const Ut=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function qt(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 $?t.constructor:t,H.key(I.REFLECT,e,I.LIST))?.clazz;if(!r)throw new a("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 $?t.constructor:t,e)?.designTypes;const n=s?.find(t=>!Ut.includes((""+t.name).toLowerCase()));return At.forModel(n,r)}class Gt extends m{constructor(t,e=Gt.name,r=401){super(t,e,r)}}class zt extends Gt{constructor(t,e=zt.name){super(t,e,403)}}class Ht extends a{constructor(t){super(t,Ht.name,503)}}function Yt(t){return G.for(tt.TABLE).define({decorator:t=>e=>X(tt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Vt(t){return G.for(tt.COLUMN).define({decorator:t=>(e,r)=>J(H.key(tt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Qt(t,e,r){return G.for(tt.INDEX).define({decorator:(t,e,r)=>(s,n)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![ct.ASC,ct.DSC].includes(t))&&(e=t,t=void 0),J(H.key(`${tt.INDEX}${e&&e?.length?"."+e.join("."):""}`,n),{directions:t,compositions:e,name:r})(s,n)),args:[t,e,r]}).apply()}async function Wt(t,e,r,s){if(s[r]&&(await this.select().where(yt.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 Xt(){const t=tt.UNIQUE;return G.for(t).define(B(),v(Wt),J(t,{})).apply()}async function Jt(t,e,r,s){throw new Gt("This adapter does not support user identification")}function Kt(){const t=tt.CREATED_BY;return G.for(t).define({decorator:()=>Y(A(Jt),J(t,{})),args:[]}).apply()}function Zt(){const t=tt.UPDATED_BY;return G.for(t).define({decorator:()=>Y(E(Jt),J(t,{})),args:[]}).apply()}function te(){return x([l.CREATE])}function ee(){return x()}function re(t,e=ut,r=!0,s,n){const i=tt.ONE_TO_ONE;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),j([t,String,Number,BigInt]),A(Pt,a),E(Dt,a),O(It,a),N(Mt,a))},args:[t,e,r,s,n]}).apply()}function se(t,e=ut,r=!0,s,n){const i=tt.ONE_TO_MANY;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),k([t,String,Number,BigInt]),A(Bt,a),E(jt,a),O(kt,a),N(Mt,a))},args:[t,e,r,s,n]}).apply()}function ne(t,e=ut,r=!0,s,n){const i=tt.MANY_TO_ONE;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),j([t,String,Number,BigInt]))},args:[t,e,r,s,n]}).apply()}function ie(t,e=ut,r=!0,s,n){const i=tt.MANY_TO_MANY;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),k([t,String,Number,BigInt]))},args:[t,e,r,s,n]}).apply()}function ae(...t){return(e,r)=>{const s=H.get(e,H.key(tt.NO_VALIDATE,r))||[],n=[...new Set([...s,...t])];return Y(X(H.key(tt.NO_VALIDATE,r),n))(e,r)}}function oe(){return ae(l.CREATE)}function ce(){return ae(l.UPDATE)}function le(){return ae(l.UPDATE,l.CREATE)}function ue(t,e){return G.for(tt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(J(t,e)(r,s),J(H.key(tt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class de extends ${constructor(t){super(t)}}n([te(),i("design:type",Date)],de.prototype,"createdAt",void 0),n([ee(),i("design:type",Date)],de.prototype,"updatedAt",void 0);const he={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},pe=he,ge={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},fe=Object.assign({},ge,{type:"BigInt"});async function ye(t,e,r,s){if(!e.type||!e.generated||s[r])return;let n;e.name||(e.name=$.sequenceName(s,"pk"));try{n=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var i,o,c;i=s,o=r,c=await n.next(t),Reflect.set(i,o,c)}function we(t,e){return(r,s)=>{switch(K()(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")}return void 0===t.generated&&(t.generated=!0),Y(Qt([ct.ASC,ct.DSC]),P(),T(),J(H.key(C.ID,s),t),A(ye,t,e))(r,s)}}function me(t=pe){return t=Object.assign({},pe,t),G.for(C.ID).define({decorator:we,args:[t,{priority:60}]}).apply()}let be=class extends de{constructor(t){super(t)}};n([me({type:"String",generated:!1}),i("design:type",String)],be.prototype,"id",void 0),n([P(),Qt(),i("design:type",Object)],be.prototype,"current",void 0),be=n([Yt("??sequence"),L(),i("design:paramtypes",[Object])],be);class ve extends it{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=At.forModel(be,e.alias)}async current(...t){const e=(await o.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){if(t instanceof w){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:n,name:i}=this.options;let o;const c=e||n;if(c%n!==0)throw new a("Value to increment does not consider the incrementBy setting: "+n);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:o=this.parse(t)+c;break;case BigInt.name:o=this.parse(t)+BigInt(c);break;case String.name:o=this.parse(t);break;case"serial":o=Tt.instance.generate(t);break;case"uuid":o=St.instance.generate(t);break;default:throw new a("Should never happen")}let l;try{l=await this.repo.update(new be({id:i,current:o}),r)}catch(n){if(!(n instanceof w))throw n;try{l=await this.repo.create(new be({id:i,current:o}),r)}catch(n){if(!(n instanceof b)||"uuid"!==s)throw n;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await o.args(l.UPDATE,be,t,this.adapter),{context:r,args:s}=e,n=await this.current(...s);return this.increment(n,void 0,r)}async range(t,...e){const r=await o.args(l.UPDATE,be,e,this.adapter),{context:s,args:n}=r,i=await this.current(...n),c=this.parse(this.options.incrementBy),u=await this.increment(i,this.parse(t)*c,s),d=[];for(let e=1;t>=e;e++)d.push(i+c*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new rt(`type ${this.options.type} is currently not suppported for this adapter`);const h="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(d[d.length-1]!==u&&"String"!==h)throw new a("Miscalculation of range");return d}parse(t){return ve.parseValue(this.options.type,t)}static pk(t){return $.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 rt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function xe(t,e){return(n,i)=>i?r(H.constr(t))(n,i):(H.set(C.REPOSITORY,H.key(e||ot.currentFlavour,$.tableName(t)),n),X(C.REPOSITORY,n.name)(t),e=e||H.get(n.constructor,tt.ADAPTER),At.register(H.constr(t),n,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,C.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(n))}ot._baseSequence=ve,H.validationExceptions=((t,e)=>{const r=H.get(t,tt.NO_VALIDATE);return r?Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t):[]}).bind(H),$.shouldValidateNestedHandler=((t,e)=>{const r=H.get(t.constructor);if(!r)return!1;const s=r[tt.RELATIONS],n=r[tt.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(n)[0],s=$.isPropertyModel(t,e);return n[r]?.class!==s}return!0}).bind($),H.migrationsFor=(t=>{if(!(t=t??ot.current))throw new a("Could not get adapter for migrations");return H.innerGet(Symbol.for(tt.MIGRATION),t.alias).map(t=>t.class)}).bind(H),H.relations=((t,e)=>{const r=H.get(t,tt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(H),$.relations=(t,e)=>H.relations(t instanceof $?t.constructor:t,e)||[],$.tableName=t=>{if(!(t instanceof $?$.get(t.constructor.name):t))throw new a("Unable to find model "+t);return H.get(t instanceof $?t.constructor:t,tt.TABLE)||(t instanceof $?t.constructor.name:t.name)},$.columnName=(t,e)=>H.get(t instanceof $?t.constructor:t,H.key(tt.COLUMN,e))||e,$.sequenceName=(t,...e)=>[$.tableName(t),...e].join("_"),$.sequenceFor=(t,e)=>{if(e)throw new rt("not currently supported");const r=$.pkProps(t instanceof $?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},$.indexes=t=>{const e=H.get(t instanceof $?t.constructor:t,tt.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[tt.INDEX]:e[r]},t),{})},e.services=()=>H.innerGet(Symbol.for(tt.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(C.REPOSITORY));class Ae extends a{constructor(t){super(t,Ae.name,500)}}class Ee extends F{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}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 ft("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ft(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}function Oe(t){return function(e,r,s){const n=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 n.apply(this,e)},s}}const Ne=()=>Oe(l.CREATE),Se=()=>Oe(l.READ),Te=()=>Oe(l.UPDATE),Ce=()=>Oe(l.DELETE);function _e(t){return t="string"==typeof t?t:H.Symbol(t).toString(),(e,n,i)=>{H.set(tt.SERVICE,t,e);const a=[];if(i&&"number"==typeof i.value)a.push(r(t));else if(i||n){if(i)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(X(tt.SERVICE,t)),Y(...a)(e,n,i)}}class $e{constructor(t){this.name=t,this.Context=o}async flags(t,e,...r){let s=e.logger||M.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},c,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=await this.flags(t,e,...r);return(new this.Context).accumulate(s)}async logCtx(t,e,r=!1){return await $e.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const n=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await n()]);const i=t.pop();i instanceof o||(t=[...t,await n()]);const c=this?i.logger.for(this).for(e):i.logger.clear().for(this).for(e);return{ctx:i,log:e?c.for(e):c,ctxArgs:[...t,i]}}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("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 o).accumulate(Object.assign({},c,{timestamp:new Date,operation:t,logger:M.get()}))},{log:s,ctxArgs:n}=await this.logCtx.bind(r)(t,this.boot,!0),i=e.services();for(const[t,e]of Object.entries(i))try{const t=new e;t instanceof Re&&await t.boot(...n)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class Re extends $e{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:n}=await this.initialize(...r);this._config=s,this._client=n}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("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...`)}}n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Re.prototype,"boot",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],Re.prototype,"config",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],Re.prototype,"client",null);const Pe=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class De extends $e{get class(){if(!this.clazz)throw new a("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=At.forModel(t)}static getService(t){if(!t)throw new a("No name provided");const e=Pe(t);try{const t=$e.get(e);if(t)return t}catch(t){}throw new a("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,n)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,n)})}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 logCtx(t,e,r=!1){return await De.logCtx.bind(this.repo.adapter)(t,e,r,{},this.class)}static forModel(t,e){let r;e=Pe(e||t);try{r=De.get(e)}catch(t){r=void 0}if(r instanceof De)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=n([_e(e),i("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},n){const i=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,s,n)}.bind(this);1>t.length&&(t=[await i()]);const c=t.pop();c instanceof o||(t=[...t,await i()]);const l=this?c.logger.for(this).for(e):c.logger.clear().for(this).for(e);return{ctx:c,log:e?l.for(e):l,ctxArgs:[...t,c]}}}var Ie,Be,je,ke;n([Ne(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"create",null),n([Ne(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"createAll",null),n([Ce(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"delete",null),n([Ce(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"deleteAll",null),n([Se(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"read",null),n([Se(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"readAll",null),n([Se(),i("design:type",Function),i("design:paramtypes",[String,Object]),i("design:returntype",Promise)],De.prototype,"query",null),n([Te(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"update",null),n([Te(),i("design:type",Function),i("design:paramtypes",[Array,Object]),i("design:returntype",Promise)],De.prototype,"updateAll",null);class Le extends it{constructor(t){super(),this.adapter=t}get log(){return this.adapter.log.for(Le)}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?$.get(t):t,!this.fromSelector)throw new gt("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){let e=t;if((!e.length||!(e[e.length-1]instanceof o))&&this.fromSelector){const t=await this.adapter.context(l.READ,{},this.fromSelector);e=[...e,t]}const{ctx:r}=ot.logCtx(e,this.toString());try{const t=this.build();return await this.raw(t,r)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),n=await this.adapter.raw(t,...s);if(!this.selectSelector)return n;const i=$.pk(this.fromSelector),a=function(t){const e=t[i];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(n)?n.map(a):a(n)}toString(){return this.adapter.flavour+" statement"}}n([U(),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Object)],Le.prototype,"select",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(Ie="undefined"!=typeof S&&S)?Ie:Object]),i("design:returntype",Object)],Le.prototype,"distinct",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(Be="undefined"!=typeof S&&S)?Be:Object]),i("design:returntype",Object)],Le.prototype,"max",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(je="undefined"!=typeof S&&S)?je:Object]),i("design:returntype",Object)],Le.prototype,"min",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(ke="undefined"!=typeof S&&S)?ke:Object]),i("design:returntype",Object)],Le.prototype,"count",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Object)],Le.prototype,"from",null),n([U(),i("design:type",Function),i("design:paramtypes",[yt]),i("design:returntype",Object)],Le.prototype,"where",null),n([U(),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Object)],Le.prototype,"orderBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Object)],Le.prototype,"groupBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Object)],Le.prototype,"limit",null),n([U(),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Object)],Le.prototype,"offset",null),n([U(),i("design:type",Function),i("design:paramtypes",[void 0]),i("design:returntype",Promise)],Le.prototype,"execute",null);class Fe extends Ee{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 r=await o.args(l.READ,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const n=await this.adapter.raw(s,await this.adapter.context(l.READ,{},this.clazz));return this._currentPage=t,n}}class Me extends Le{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=H.getPropDesignTypes(t.constructor,s);if(!i)throw new gt("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===n?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===n?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new gt("Sorting not supported for not date classes");default:throw new gt("sorting not supported for type "+i)}}}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}async paginate(t){try{const e=this.build();return new Fe(this.adapter,e,t,this.fromSelector)}catch(t){throw new a(t)}}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:n}=t;if(-1===[ht.AND,ht.OR,dt.NOT].indexOf(s))switch(s){case dt.BIGGER:return e[r]>n;case dt.BIGGER_EQ:return e[r]>=n;case dt.DIFFERENT:return e[r]!==n;case dt.EQUAL:return e[r]===n;case dt.REGEXP:if("string"!=typeof e[r])throw new gt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(n,"g"));case dt.SMALLER:return e[r]<n;case dt.SMALLER_EQ:return e[r]<=n;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===dt.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),i=this.parseCondition(n);switch(s){case ht.AND:return t.where(e)&&i.where(e);case ht.OR:return t.where(e)||i.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Ue(t,e,r,s){const n=t.get("UUID");if(!n)throw new rt("This adapter does not support user identification");s[r]=n}const qe="ram";class Ge extends ot{constructor(t={},e){super(t,qe,e),this.Context=o,this.indexes={},this.lock=new Z}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[$.pk(t.constructor)],s}revert(t,e,r,s,...n){return super.revert(t,e,r,s,...n)}async create(t,e,r,s){const n=s.logger.for(this.create),i=$.tableName(t);if(n.debug(`creating record in table ${i} with id ${e}`),await this.lock.acquire(),this.client.has(i)||this.client.set(i,new Map),this.client.get(i)&&this.client.get(i)?.has(e))throw new b(`Record with id ${e} already exists in table ${i}`);return this.client.get(i)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=$.tableName(t);if(!this.client.has(s))throw new w(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new w(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const n=s.logger.for(this.update),i=$.tableName(t);if(n.debug(`updating record in table ${i} with id ${e}`),await this.lock.acquire(),!this.client.has(i))throw new w(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new w(`Record with id ${e} not found in table ${i}`);return this.client.get(i)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),n=$.tableName(t);if(s.debug(`deleting record from table ${n} with pk ${e}`),await this.lock.acquire(),!this.client.has(n))throw new w(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new w(`Record with id ${e} not found in table ${n}`);const i=this.client.get(n)?.get(e);return this.client.get(n)?.delete(e),this.lock.release(),i}tableFor(t){"string"==typeof t&&(t=$.get(t));const e=$.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:n,skip:i,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const u=$.pk(o),d=H.get(o,H.key(C.ID,u));let h=Array.from(l.entries()).map(([t,r])=>this.revert(r,o,ve.parseValue(d.type,t),void 0,e));return h=r?h.filter(r):h,s&&(h=h.sort(s)),i&&(h=h.slice(i)),n&&(h=h.slice(0,n)),c&&(c=Array.isArray(c)?c:[c],h=h.map(t=>Object.entries(t).reduce((t,[e,r])=>(c.includes(e)&&(t[e]=r),t),{}))),h}parseError(t){return t instanceof _?t:new a(t)}Statement(){return new Me(this)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${R(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const n=Reflect.get(e,r,s);return Object.assign({},n,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=tt.CREATED_BY,e=tt.UPDATED_BY;G.flavouredAs(qe).for(t).define(A(Ue),J(t,{})).apply(),G.flavouredAs(qe).for(e).define(v(Ue),J(e,{})).apply()}getClient(){return new Map}}Ge.decoration(),e.setRegistry(new Ot);const ze="##VERSION##",He="##PACKAGE##";H.registerLibrary(He,ze);export{_t as AbsMigration,ot as Adapter,Gt as AuthorizationError,de as BaseModel,fe as BigIntSequence,lt as Cascade,Re as ClientBasedService,yt as Condition,Ht as ConnectionError,it as ContextualLoggedClass,ut as DefaultCascade,pe as DefaultSequenceOptions,Nt as Dispatch,zt as ForbiddenError,ht as GroupOperator,Ot as InjectablesRegistry,bt as MethodQueryBuilder,st as MigrationError,nt as MigrationRuleError,De as ModelService,he as NoneSequenceOptions,ge as NumericSequence,Ae as ObserverError,et as ObserverHandler,dt as Operator,wt as OperatorsMap,ct as OrderDirection,He as PACKAGE_NAME,Ee as Paginator,ft as PagingError,tt as PersistenceKeys,pt as QueryClause,gt as QueryError,Ge as RamAdapter,qe as RamFlavour,Fe as RamPaginator,Me as RamStatement,At as Repository,ve as Sequence,be as SequenceModel,Tt as Serial,$e as Service,Le as Statement,St as UUID,rt as UnsupportedError,ze as VERSION,Ft as cacheModelForPopulate,Vt as column,Ne as create,Rt as createOrUpdate,te as createdAt,Kt as createdBy,Jt as createdByOnCreateUpdate,Ue as createdByOnRamCreateUpdate,Ce as del,Et as generateInjectableNameForRepository,Lt as getPopulateKey,Qt as index,ie as manyToMany,ne as manyToOne,$t as migration,ae as noValidateOn,oe as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,se as oneToMany,Bt as oneToManyOnCreate,kt as oneToManyOnDelete,jt as oneToManyOnUpdate,re as oneToOne,Pt as oneToOneOnCreate,It as oneToOneOnDelete,Dt as oneToOneOnUpdate,me as pk,we as pkDec,ye as pkOnCreate,Mt as populate,Ct as prefixMethod,vt as prepared,xt as query,Se as read,ue as relation,xe as repository,qt as repositoryFromTypeMetadata,_e as service,Yt as table,Xt as unique,Wt as uniqueOnCreateUpdate,Te 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 n,__metadata as i}from"tslib";import{InternalError as a,Context as o,DefaultRepositoryFlags as c,OperationKeys as l,Repository as u,wrapMethodWithContext as d,enforceDBDecorators as h,ValidationError as p,reduceErrorsToPrint as g,DefaultSeparator as f,BulkCrudOperationKeys as y,NotFoundError as w,BadRequestError as m,ConflictError as b,onCreateUpdate as v,timestamp as x,onCreate as A,onUpdate as E,onDelete as O,afterAny as N,readonly as T,DBKeys as C,BaseError as _}from"@decaf-ts/db-decorators";import{Model as $,hashObj as R,required as P,sf as D,ValidationKeys as I,async as B,type as j,list as k,model as L}from"@decaf-ts/decorator-validation";import{LoggedClass as F,Logging as M,final as U,isClass as q}from"@decaf-ts/logging";import{Decoration as G,DefaultFlavour as z,Metadata as H,apply as Y,methodMetadata as V,DecorationKeys as Q,uses as W,metadata as X,propMetadata as J,prop as K}from"@decaf-ts/decoration";import{Lock as Z}from"@decaf-ts/transactional-decorators";var tt;(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"})(tt||(tt={}));class et{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map((t=>t.observer)).indexOf(t))throw new a("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 a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:n,ctxArgs:i}=ot.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,...i)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((s=>{s.observer.refresh(t,e,r,...i)})))).forEach(((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}class rt extends a{constructor(t){super(t,rt.name,500)}}class st extends a{constructor(t,e=st.name){super(t,e,500)}}class nt extends st{constructor(t){super(t,nt.name)}}class it extends F{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return it.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof o))throw new a("No context provided");if(t.filter((t=>t instanceof o)).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 at=G.flavourResolver.bind(G);G.flavourResolver=t=>{try{const e=at(t);if(e&&e!==z)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof H.registeredFlavour?H.registeredFlavour(r):void 0;if(s&&s!==z)return s;const n=ot._currentFlavour;if(n){const t=ot._cache?.[n];return t?.flavour?t.flavour:n}}catch(t){return z}};class ot extends it{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ot._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return ot._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("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=o,this.alias in ot._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ot._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ot._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ot._currentFlavour=this.alias)}Dispatch(){return new ot._baseDispatch}ObserverHandler(){return new et}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ot._baseSequence(t,this)}async flags(t,e,r,...s){let n=r.logger||M.for(this.toString());return r.correlationId&&(n=n.for({correlationId:r.correlationId})),Object.assign({},c,r,{affectedTables:(Array.isArray(e)?e:[e]).map($.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:H.validationExceptions(e,t),logger:n})}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 n=await this.flags(t,r,e,...s);return(new this.Context).accumulate(n)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),n=Object.entries(s.model).reduce(((e,[r,s])=>{if(void 0===s)return e;const n=$.columnName(t.constructor,r);if(this.isReserved(n))throw new a(`Property name ${n} is reserved`);return e[n]=s,e}),{});return t[tt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[tt.METADATA]),Object.defineProperty(n,tt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[tt.METADATA]})),{record:n,id:t[$.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...n){const{log:i,ctx:o}=this.logCtx(n,this.revert),c={},l=$.pk(e);c[l]=r;const u=new e(c);i.silly(`Rebuilding model ${u.constructor.name} id ${r}`);const d=t[tt.METADATA],h=Object.keys(u).reduce(((r,s)=>(s===l||(r[s]=t[$.columnName(e,s)]),r)),u);return o.get("rebuildWithTransient")&&s&&(i.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach((([t,e])=>{if(t in h)throw new a(`Transient property ${t} already exists on model ${u.constructor.name}. should be impossible`);h[t]=e}))),d&&(i.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${r}: ${d}`),Object.defineProperty(h,tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),h}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:n,ctxArgs:i}=this.logCtx(s,this.createAll),o=$.tableName(t);return n.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.create(t,e,r[s],...i))))}async readAll(t,e,...r){const{log:s,ctxArgs:n}=this.logCtx(r,this.readAll),i=$.tableName(t);return s.debug(`Reading ${e.length} entries ${i} table`),Promise.all(e.map((e=>this.read(t,e,...n))))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:n,ctxArgs:i}=this.logCtx(s,this.updateAll),o=$.tableName(t);return n.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.update(t,e,r[s],...i))))}async deleteAll(t,e,...r){const{log:s,ctxArgs:n}=ot.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map((e=>this.delete(t,e,...n))))}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 a("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 a("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:i}=ot.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...i)}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(!ot._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return ot._currentFlavour}static get current(){return ot.get(this.currentFlavour)}static get(t){if(!t)return ot.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t)}catch(t){throw new a(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} - ${R(t)}`;if(r in this.proxies)return this.proxies[r];let s;const n=new Proxy(this,{get:(e,r,n)=>{if("_config"===r){const s=Reflect.get(e,r,n);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,n)},set:(t,e,r,n)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,n)});return this.proxies[r]=n,n}migrations(){return H.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof o&&(e=[t],t=this.migrations());const{ctx:r}=ot.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 st(t)}}}var ct,lt;n([U(),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],ot.prototype,"shutdownProxies",null),n([U(),i("design:type",Function),i("design:paramtypes",[String,Object,Object,Object]),i("design:returntype",Promise)],ot.prototype,"context",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object,Function]),i("design:returntype",void 0)],ot.prototype,"observe",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",void 0)],ot.prototype,"unObserve",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],ot.prototype,"client",null),(t=>{t.ASC="asc",t.DSC="desc"})(ct||(ct={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(lt||(lt={}));const ut={update:lt.CASCADE,delete:lt.NONE};var dt,ht,pt;(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"})(dt||(dt={})),(t=>{t.AND="AND",t.OR="OR"})(ht||(ht={}));class gt extends a{constructor(t){super(t,gt.name,500)}}class ft extends a{constructor(t){super(t,ft.name,500)}}class yt extends ${constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=t,this.operator=e,this.comparison=r}and(t){return yt.and(this,t)}or(t){return yt.or(this,t)}not(t){return new yt(this,dt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof yt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(dt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof yt){if(!(this.comparison instanceof yt)&&this.operator!==dt.NOT)return{comparison:{condition:t}};if(-1===Object.values(ht).indexOf(this.operator)&&this.operator!==dt.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 yt.group(t,ht.AND,e)}static or(t,e){return yt.group(t,ht.OR,e)}static group(t,e,r){return new yt(t,e,r)}static attribute(t){return(new yt.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(dt.EQUAL,t)}dif(t){return this.setOp(dt.DIFFERENT,t)}gt(t){return this.setOp(dt.BIGGER,t)}lt(t){return this.setOp(dt.SMALLER,t)}gte(t){return this.setOp(dt.BIGGER_EQ,t)}lte(t){return this.setOp(dt.SMALLER_EQ,t)}in(t){return this.setOp(dt.IN,t)}regexp(t){return this.setOp(dt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new yt(this.attr1,this.operator,this.comparison)}catch(t){throw new gt(t)}}}}static builder(){return new yt.Builder}}n([P(),i("design:type",Object)],yt.prototype,"attr1",void 0),n([P(),i("design:type",String)],yt.prototype,"operator",void 0),n([P(),i("design:type",Object)],yt.prototype,"comparison",void 0),(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"})(pt||(pt={}));const wt={Equals:(t,e)=>yt.attribute(t).eq(e),Diff:(t,e)=>yt.attribute(t).dif(e),LessThan:(t,e)=>yt.attribute(t).lt(e),LessThanEqual:(t,e)=>yt.attribute(t).lte(e),GreaterThan:(t,e)=>yt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>yt.attribute(t).gte(e),Between:(t,e,r)=>yt.attribute(t).gte(e).and(yt.attribute(t).lte(r)),In:(t,e)=>yt.attribute(t).in(e),Matches:(t,e)=>yt.attribute(t).regexp(e)},mt=t=>t.charAt(0).toLowerCase()+t.slice(1);class bt{static build(t,...e){if(!t.startsWith(pt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),i=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:i,groupBy:n,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(pt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static extractSelect(t){const e=t.indexOf(pt.SELECT);if(-1===e)return;const r=t.substring(e+pt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(pt.AND).map(mt).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(pt.GROUP_BY);if(-1!==e)return t.substring(e+pt.GROUP_BY.length).split(pt.ORDER_BY)[0].split(pt.THEN_BY).map(mt).filter(Boolean)}static buildWhere(t,e){const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(r.forEach(((t,r)=>{const{field:i,operator:a}=this.parseFieldAndOperator(t),o=a?wt[a]:wt.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+i);const l=o(i,c);n=0===r?l:s[r-1]===pt.AND?n.and(l):n.or(l)})),!n)throw Error("No conditions found in method name");return n}static parseFieldAndOperator(t){for(const e of Object.keys(wt))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:mt(r),operator:e}}return{field:mt(t)}}static extractOrderLimitOffset(t,e){const r=t.split(/And|Or/).length,s=e.slice(r);let n,i,a;return s.length>=1&&Array.isArray(s[0])&&(n=s[0]),2>s.length||"number"!=typeof s[1]||(i=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:n,limit:i,offset:a}}}function vt(){return G.for(tt.STATEMENT).define({decorator:()=>(t,e,r)=>Y(V(H.key(tt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function xt(t={}){return G.for(tt.QUERY).define({decorator:t=>(e,r,s)=>Y(V(H.key(tt.QUERY,r),t),vt(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:n,where:i,groupBy:a,orderBy:o,limit:c,offset:l}=bt.build(e.name,...s);let u=r.select(n);i&&(u=u.where(i));const{allowLimit:d,allowOffset:h,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:h}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new gt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(u=u[t.key](t.value))}return u.execute()}})})(t))(e,r,s),args:[t]}).apply()}class At extends u{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 a("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=$.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(At.register(e,this,this.adapter.alias),t)&&H.get(e,Q.FLAVOUR)===z&&W(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 ot.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const n=Reflect.get(e,r,s);return"_overrides"!==r?n:Object.assign({},n,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,n)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,n)})}ObserverHandler(){return new et}async createPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation");if(t=new this.class(t),s||await h(this,r.context,t,l.CREATE,l.ON),!n){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:n}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${$.tableName(this.class)}`);let{record:i,id:a,transient:o}=this.adapter.prepare(t,r);return i=await this.adapter.create(this.class,a,i,...n),this.adapter.revert(i,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:n}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const i=t.map((t=>this.adapter.prepare(t,r))),a=i.map((t=>t.id));let o=i.map((t=>t.record));return o=await this.adapter.createAll(this.class,a,o,...n),o.map(((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?i[e].transient:void 0,r)))}async createAllPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const i=$.sequenceFor(t[0]);let c=[];if(i.type?(i.name||(i.name=$.sequenceName(t[0],"pk")),c=await(await this.adapter.Sequence(i)).range(t.length,...r.args)):c=t.map(((t,e)=>{if(void 0===t[this.pk])throw new a("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),i.type&&(t[this.pk]="String"!==i.type||i.generated?c[e]:""+t[this.pk]),s||await h(this,r.context,t,l.CREATE,l.ON),t)))),!n){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),n=g(s);if(n)throw new p(n)}return[t,...r.args]}async readPrefix(t,...e){const r=await o.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await h(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${$.tableName(this.class)} with pk ${this.pk}`);const i=await this.adapter.read(this.class,t,...n);return this.adapter.revert(i,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await o.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,h(this,r.context,e,l.READ,l.ON)}))),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...n)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}async update(t,...e){const{ctxArgs:r,log:s,ctx:n}=this.logCtx(e,this.update);let{record:i,id:a,transient:o}=this.adapter.prepare(t,n);return s.debug(`updating ${this.class.name} in table ${$.tableName(this.class)} with id ${a}`),i=await this.adapter.update(this.class,a,i,...r),this.adapter.revert(i,this.class,a,o,n)}async updatePrefix(t,...e){const r=await o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation"),i=t[this.pk];if(!i)throw new a("No value for the Id is defined under the property "+this.pk);const c=await this.read(i,...r.args);if(t=$.merge(c,t,this.class),s||await h(this,r.context,t,l.UPDATE,l.ON,c),!n){const e=await Promise.resolve(t.hasErrors(c,...$.relations(this.class),...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:n}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const i=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,i.map((t=>t.id)),i.map((t=>t.record)),...n)).map(((t,e)=>this.adapter.revert(t,this.class,i[e].id,r.get("rebuildWithTransient")?i[e].transient:void 0,r)))}async updateAllPrefix(t,...e){const r=await o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation"),i=t.map((t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e})),c=await this.readAll(i,...r.args);if(t=t.map(((t,e)=>$.merge(c[e],t,this.class))),s||await Promise.all(t.map(((t,e)=>h(this,r.context,t,l.UPDATE,l.ON,c[e])))),!n){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(((t,r)=>Promise.resolve(t.hasErrors(c[r],t,...e))))),n=g(s);if(n)throw new p(n)}return[t,...r.args]}async deletePrefix(t,...e){const r=await o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await h(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${$.tableName(this.class)} with pk ${t}`);const i=await this.adapter.delete(this.class,t,...n);return this.adapter.revert(i,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await o.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=>h(this,r.context,t,l.DELETE,l.ON)))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:n}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...n)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=ct.ASC,s,n){const i=[e,r],a=this.select().where(t).orderBy(i);return s&&a.limit(s),n&&a.offset(n),a.execute()}async listBy(t,e,...r){const s=await o.args("list",this.class,r,this.adapter,this._overrides||{}),{log:n,ctxArgs:i}=this.logCtx(s.args,this.listBy);return n.verbose(`listing ${$.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r,...s){const n=await o.args("paginateBy",this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:a}=this.logCtx(n.args,this.paginateBy);return i.verbose(`paginating ${$.tableName(this.class)} with page size ${r}`),this.select().orderBy([t,e]).paginate(r,...a)}async findOneBy(t,e,...r){const s=await o.args("findOneBy",this.class,r,this.adapter,this._overrides||{}),{log:n,ctxArgs:i}=this.logCtx(s.args,this.findOneBy);return n.verbose(`finding ${$.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async statement(t,...e){if(!At.statements(this,t))throw new gt("Invalid prepared statement requested "+t);const r=await o.args("statement",this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:n}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...n)}attr(t){return yt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=$.tableName(this.class);this.adapter.observe(this,((t,e,r,...n)=>"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 a("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 a("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:i}=this.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map((t=>ot._baseSequence.parseValue($.sequenceFor(this.class).type,t))):ot._baseSequence.parseValue($.sequenceFor(this.class).type,r),...i)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const n=e||H.flavourOf(t)||ot.currentFlavour;try{s=this.get(t,n)}catch(t){s=void 0}if(s instanceof At)return s;const i=e||H.flavourOf(t)||s&&H.get(s,tt.ADAPTER)||ot.currentFlavour,o=i?ot.get(i):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+i);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=$.tableName(t);let s=r;if(e&&(s=[r,e].join(f)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=$.tableName(t);if(r&&(s=[s,r].join(f)),s in this._cache&&this._cache[s]instanceof At)throw new a(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof At?t.constructor:t,s=H.get(r,e?H.key(tt.STATEMENT,e):tt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof At?t.constructor:t;return H.get(r,e?H.key(tt.QUERY,e):tt.QUERY)}}function Et(t,e){if(!(e||(e=G.flavourResolver(t instanceof $?t.constructor:t))&&e!==z))throw new a("Could not retrieve flavour from model "+(t instanceof $?t.constructor.name:t.name));return D(tt.INJECTABLE,e,$.tableName(t))}n([vt(),i("design:type",Function),i("design:paramtypes",[Object,String,void 0]),i("design:returntype",Promise)],At.prototype,"listBy",null),n([vt(),i("design:type",Function),i("design:paramtypes",[Object,String,Number,void 0]),i("design:returntype",Promise)],At.prototype,"paginateBy",null),n([vt(),i("design:type",Function),i("design:paramtypes",[Object,Object,void 0]),i("design:returntype",Promise)],At.prototype,"findOneBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object,Function]),i("design:returntype",void 0)],At.prototype,"observe",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",void 0)],At.prototype,"unObserve",null),ot&&(ot._baseRepository=At);class Ot extends t{get log(){return this.logger||(this.logger=M.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let n;try{n=super.get(t)}catch{}if(!n){let i;if("function"==typeof t?i=$.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(i=$.get(t.toString())),!i)return;const a=tt.ADAPTER,o=r||H.get(i,a);try{let t=o;try{o&&ot.get(o)}catch{const e=ot.current;e&&e.flavour===o&&(t=e.alias)}if(n=At.forModel(i,t),n instanceof At)return n;const r=o||H.get(n.constructor,a)||H.get(i,a);e.register(n,Et(i,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=At.get(i,o);if("function"==typeof e){const t=o?ot.get(o):ot.current;if(!t)return;return new e(t,i)}}}return n}}class Nt extends it{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,y.CREATE_ALL,y.UPDATE_ALL,y.DELETE_ALL].forEach((e=>{if(!t[e])throw new a(`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:n,ctxArgs:i}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,i);return this.updateObservers(a,(t=>{switch(t){case y.CREATE_ALL:return l.CREATE;case y.UPDATE_ALL:return l.UPDATE;case y.DELETE_ALL:return l.DELETE;default:return t}})(e),o,c,...i.slice(s.length)).then((()=>{n.verbose(`Observer refresh dispatched by ${e} for ${a}`),n.debug("pks: "+o)})).catch((t=>n.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 ot))throw new rt("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ot.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 rt("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const n="string"==typeof t?t:$.tableName(t),{log:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{i.debug(`Dispatching ${e} from table ${n} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${n}:${e}`)}}ot&&(ot._baseDispatch=Nt);class St{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 St._instance||(St._instance=new St),St._instance}}class Tt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Tt._instance||(Tt._instance=new Tt),Tt._instance}}function Ct(t,e,r,s){const n=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof nt)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),i=s||e.name;Object.defineProperty(n,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),t[i]=n}class _t extends F{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach((t=>{const e=t.name;Ct(this,t,this.prefix(e))}))}get adapter(){const t=H.get(this.constructor,tt.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return ot.get(e)}async enforceRules(t,e,r){const s=H.get(this.constructor,tt.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const n of s)if(!await n(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ot?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await o.args("migration",$,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new nt("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function $t(t,e){return G.for(tt.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(tt.MIGRATION),t)||[];return H.set(tt.MIGRATION,t,[...s,{class:r}]),X(tt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}async function Rt(t,e,r,s){if(!s){const e=$.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=At.forModel(e,r)}if(void 0===t[$.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof w))throw r;return s.create(t,e)}}async function Pt(t,e,r,s){const n=s[r];if(!n)return;if("object"!=typeof n){const e=qt(s,r,this.adapter.alias),i=await e.read(n);return await Ft(t,s,r,n,i),void(s[r]=n)}const i=q(e.class)?e.class:e.class();if(!i)throw new a("Could not find model "+e.class);const o=At.forModel(i,this.adapter.alias),c=await o.create(n),l=$.pk(c);await Ft(t,s,r,c[l],c),s[r]=c[l]}async function Dt(t,e,r,s){const n=s[r];if(!n)return;if(e.cascade.update!==lt.CASCADE)return;if("object"!=typeof n){const e=qt(s,r,this.adapter.alias),i=await e.read(n);return await Ft(t,s,r,n,i),void(s[r]=n)}const i=await Rt(s[r],t,this.adapter.alias),a=$.pk(i);await Ft(t,s,r,i[a],i),s[r]=i[a]}async function It(t,e,r,s){const n=s[r];if(!n)return;if(e.cascade.update!==lt.CASCADE)return;const i=qt(s,r,this.adapter.alias);let a;a=n instanceof $?await i.delete(s[r][i.pk]):await i.delete(s[r]),await Ft(t,s,r,a[i.pk],a)}async function Bt(t,e,r,s){const n=s[r];if(!n||!n.length)return;const i=typeof n[0];if(!n.every((t=>typeof t===i)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...n]);if("object"!==i){const e=qt(s,r,this.adapter.alias);for(const n of o){const i=await e.read(n);await Ft(t,s,r,n,i)}return void(s[r]=[...o])}const c=$.pk(n[0]),l=new Set;for(const e of n){const n=await Rt(e,t,this.adapter.alias);await Ft(t,s,r,n[c],n),l.add(n[c])}s[r]=[...l]}async function jt(t,e,r,s){const{cascade:n}=e;if(n.update===lt.CASCADE)return Bt.call(this,t,e,r,s)}async function kt(t,e,r,s){if(e.cascade.delete!==lt.CASCADE)return;const n=s[r];if(!n||!n.length)return;const i=typeof n[0];if(!n.every((t=>typeof t===i)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===i,c=o?At.forModel(n[0],this.adapter.alias):qt(s,r,this.adapter.alias),l=new Set([...o?n.map((t=>t[c.pk])):n]);for(const e of l.values()){const n=await c.delete(e);await Ft(t,s,r,e,n)}s[r]=[...l]}function Lt(t,e,r){return[tt.POPULATE,t,e,r].join(".")}async function Ft(t,e,r,s,n){const i=Lt(e.constructor.name,r,s);return t.accumulate({[i]:n})}async function Mt(t,e,r,s){if(!e.populate)return;const n=s[r],i=Array.isArray(n);if(void 0===n||i&&0===n.length)return;const o=await(async(t,e,r,s,n)=>{let i,o;const c=[];for(const l of s){i=Lt(e.constructor.name,r,l);try{o=await t.get(i)}catch(t){const s=qt(e,r,n);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,i?n:[n],this.adapter.alias);s[r]=i?o:o[0]}const Ut=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function qt(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 $?t.constructor:t,H.key(I.REFLECT,e,I.LIST))?.clazz;if(!r)throw new a("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 $?t.constructor:t,e)?.designTypes;const n=s?.find((t=>!Ut.includes((""+t.name).toLowerCase())));return At.forModel(n,r)}class Gt extends m{constructor(t,e=Gt.name,r=401){super(t,e,r)}}class zt extends Gt{constructor(t,e=zt.name){super(t,e,403)}}class Ht extends a{constructor(t){super(t,Ht.name,503)}}function Yt(t){return G.for(tt.TABLE).define({decorator:t=>e=>X(tt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Vt(t){return G.for(tt.COLUMN).define({decorator:t=>(e,r)=>J(H.key(tt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Qt(t,e,r){return G.for(tt.INDEX).define({decorator:(t,e,r)=>(s,n)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find((t=>![ct.ASC,ct.DSC].includes(t)))&&(e=t,t=void 0),J(H.key(`${tt.INDEX}${e&&e?.length?"."+e.join("."):""}`,n),{directions:t,compositions:e,name:r})(s,n)),args:[t,e,r]}).apply()}async function Wt(t,e,r,s){if(s[r]&&(await this.select().where(yt.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 Xt(){const t=tt.UNIQUE;return G.for(t).define(B(),v(Wt),J(t,{})).apply()}async function Jt(t,e,r,s){throw new Gt("This adapter does not support user identification")}function Kt(){const t=tt.CREATED_BY;return G.for(t).define({decorator:()=>Y(A(Jt),J(t,{})),args:[]}).apply()}function Zt(){const t=tt.UPDATED_BY;return G.for(t).define({decorator:()=>Y(E(Jt),J(t,{})),args:[]}).apply()}function te(){return x([l.CREATE])}function ee(){return x()}function re(t,e=ut,r=!0,s,n){const i=tt.ONE_TO_ONE;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),j([t,String,Number,BigInt]),A(Pt,a),E(Dt,a),O(It,a),N(Mt,a))},args:[t,e,r,s,n]}).apply()}function se(t,e=ut,r=!0,s,n){const i=tt.ONE_TO_MANY;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),k([t,String,Number,BigInt]),A(Bt,a),E(jt,a),O(kt,a),N(Mt,a))},args:[t,e,r,s,n]}).apply()}function ne(t,e=ut,r=!0,s,n){const i=tt.MANY_TO_ONE;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),j([t,String,Number,BigInt]))},args:[t,e,r,s,n]}).apply()}function ie(t,e=ut,r=!0,s,n){const i=tt.MANY_TO_MANY;return G.for(i).define({decorator:(t,e,r,s,n)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),n&&(a.name=n),Y(K(),ue(i,a),k([t,String,Number,BigInt]))},args:[t,e,r,s,n]}).apply()}function ae(...t){return(e,r)=>{const s=H.get(e,H.key(tt.NO_VALIDATE,r))||[],n=[...new Set([...s,...t])];return Y(X(H.key(tt.NO_VALIDATE,r),n))(e,r)}}function oe(){return ae(l.CREATE)}function ce(){return ae(l.UPDATE)}function le(){return ae(l.UPDATE,l.CREATE)}function ue(t,e){return G.for(tt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(J(t,e)(r,s),J(H.key(tt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class de extends ${constructor(t){super(t)}}n([te(),i("design:type",Date)],de.prototype,"createdAt",void 0),n([ee(),i("design:type",Date)],de.prototype,"updatedAt",void 0);const he={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},pe=he,ge={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},fe=Object.assign({},ge,{type:"BigInt"});async function ye(t,e,r,s){if(!e.type||!e.generated||s[r])return;let n;e.name||(e.name=$.sequenceName(s,"pk"));try{n=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var i,o,c;i=s,o=r,c=await n.next(t),Reflect.set(i,o,c)}function we(t,e){return(r,s)=>{switch(K()(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")}return void 0===t.generated&&(t.generated=!0),Y(Qt([ct.ASC,ct.DSC]),P(),T(),J(H.key(C.ID,s),t),A(ye,t,e))(r,s)}}function me(t=pe){return t=Object.assign({},pe,t),G.for(C.ID).define({decorator:we,args:[t,{priority:60}]}).apply()}let be=class extends de{constructor(t){super(t)}};n([me({type:"String",generated:!1}),i("design:type",String)],be.prototype,"id",void 0),n([P(),Qt(),i("design:type",Object)],be.prototype,"current",void 0),be=n([Yt("??sequence"),L(),i("design:paramtypes",[Object])],be);class ve extends it{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=At.forModel(be,e.alias)}async current(...t){const e=(await o.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){if(t instanceof w){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:n,name:i}=this.options;let o;const c=e||n;if(c%n!=0)throw new a("Value to increment does not consider the incrementBy setting: "+n);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:o=this.parse(t)+c;break;case BigInt.name:o=this.parse(t)+BigInt(c);break;case String.name:o=this.parse(t);break;case"serial":o=Tt.instance.generate(t);break;case"uuid":o=St.instance.generate(t);break;default:throw new a("Should never happen")}let l;try{l=await this.repo.update(new be({id:i,current:o}),r)}catch(n){if(!(n instanceof w))throw n;try{l=await this.repo.create(new be({id:i,current:o}),r)}catch(n){if(!(n instanceof b)||"uuid"!==s)throw n;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await o.args(l.UPDATE,be,t,this.adapter),{context:r,args:s}=e,n=await this.current(...s);return this.increment(n,void 0,r)}async range(t,...e){const r=await o.args(l.UPDATE,be,e,this.adapter),{context:s,args:n}=r,i=await this.current(...n),c=this.parse(this.options.incrementBy),u=await this.increment(i,this.parse(t)*c,s),d=[];for(let e=1;t>=e;e++)d.push(i+c*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new rt(`type ${this.options.type} is currently not suppported for this adapter`);const h="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(d[d.length-1]!==u&&"String"!==h)throw new a("Miscalculation of range");return d}parse(t){return ve.parseValue(this.options.type,t)}static pk(t){return $.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 rt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function xe(t,e){return(n,i)=>i?r(H.constr(t))(n,i):(H.set(C.REPOSITORY,H.key(e||ot.currentFlavour,$.tableName(t)),n),X(C.REPOSITORY,n.name)(t),e=e||H.get(n.constructor,tt.ADAPTER),At.register(H.constr(t),n,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,C.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(n))}ot._baseSequence=ve,H.validationExceptions=((t,e)=>{const r=H.get(t,tt.NO_VALIDATE);return r?Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t)):[]}).bind(H),$.shouldValidateNestedHandler=((t,e)=>{const r=H.get(t.constructor);if(!r)return!1;const s=r[tt.RELATIONS],n=r[tt.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(n)[0],s=$.isPropertyModel(t,e);return n[r]?.class!==s}return!0}).bind($),H.migrationsFor=(t=>{if(!(t=t??ot.current))throw new a("Could not get adapter for migrations");return H.innerGet(Symbol.for(tt.MIGRATION),t.alias).map((t=>t.class))}).bind(H),H.relations=((t,e)=>{const r=H.get(t,tt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(H),$.relations=(t,e)=>H.relations(t instanceof $?t.constructor:t,e)||[],$.tableName=t=>{if(!(t instanceof $?$.get(t.constructor.name):t))throw new a("Unable to find model "+t);return H.get(t instanceof $?t.constructor:t,tt.TABLE)||(t instanceof $?t.constructor.name:t.name)},$.columnName=(t,e)=>H.get(t instanceof $?t.constructor:t,H.key(tt.COLUMN,e))||e,$.sequenceName=(t,...e)=>[$.tableName(t),...e].join("_"),$.sequenceFor=(t,e)=>{if(e)throw new rt("not currently supported");const r=$.pkProps(t instanceof $?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},$.indexes=t=>{const e=H.get(t instanceof $?t.constructor:t,tt.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[tt.INDEX]:e[r]},t)),{})},e.services=()=>H.innerGet(Symbol.for(tt.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(C.REPOSITORY));class Ae extends a{constructor(t){super(t,Ae.name,500)}}class Ee extends F{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}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 ft("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ft(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}function Oe(t){return function(e,r,s){const n=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 n.apply(this,e)},s}}const Ne=()=>Oe(l.CREATE),Se=()=>Oe(l.READ),Te=()=>Oe(l.UPDATE),Ce=()=>Oe(l.DELETE);function _e(t){return t="string"==typeof t?t:H.Symbol(t).toString(),(e,n,i)=>{H.set(tt.SERVICE,t,e);const a=[];if(i&&"number"==typeof i.value)a.push(r(t));else if(i||n){if(i)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(X(tt.SERVICE,t)),Y(...a)(e,n,i)}}class $e{constructor(t){this.name=t,this.Context=o}async flags(t,e,...r){let s=e.logger||M.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},c,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=await this.flags(t,e,...r);return(new this.Context).accumulate(s)}async logCtx(t,e,r=!1){return await $e.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const n=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await n()]);const i=t.pop();i instanceof o||(t=[...t,await n()]);const c=this?i.logger.for(this).for(e):i.logger.clear().for(this).for(e);return{ctx:i,log:e?c.for(e):c,ctxArgs:[...t,i]}}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("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 o).accumulate(Object.assign({},c,{timestamp:new Date,operation:t,logger:M.get()}))},{log:s,ctxArgs:n}=await this.logCtx.bind(r)(t,this.boot,!0),i=e.services();for(const[t,e]of Object.entries(i))try{const t=new e;t instanceof Re&&await t.boot(...n)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class Re extends $e{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:n}=await this.initialize(...r);this._config=s,this._client=n}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("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...`)}}n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Re.prototype,"boot",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],Re.prototype,"config",null),n([U(),i("design:type",Object),i("design:paramtypes",[])],Re.prototype,"client",null);const Pe=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class De extends $e{get class(){if(!this.clazz)throw new a("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=At.forModel(t)}static getService(t){if(!t)throw new a("No name provided");const e=Pe(t);try{const t=$e.get(e);if(t)return t}catch(t){}throw new a("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,n)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,n)})}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 logCtx(t,e,r=!1){return await De.logCtx.bind(this.repo.adapter)(t,e,r,{},this.class)}static forModel(t,e){let r;e=Pe(e||t);try{r=De.get(e)}catch(t){r=void 0}if(r instanceof De)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=n([_e(e),i("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},n){const i=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,s,n)}.bind(this);1>t.length&&(t=[await i()]);const c=t.pop();c instanceof o||(t=[...t,await i()]);const l=this?c.logger.for(this).for(e):c.logger.clear().for(this).for(e);return{ctx:c,log:e?l.for(e):l,ctxArgs:[...t,c]}}}var Ie,Be,je,ke;n([Ne(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"create",null),n([Ne(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"createAll",null),n([Ce(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"delete",null),n([Ce(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"deleteAll",null),n([Se(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"read",null),n([Se(),i("design:type",Function),i("design:paramtypes",[Array,void 0]),i("design:returntype",Promise)],De.prototype,"readAll",null),n([Se(),i("design:type",Function),i("design:paramtypes",[String,Object]),i("design:returntype",Promise)],De.prototype,"query",null),n([Te(),i("design:type",Function),i("design:paramtypes",[Object,void 0]),i("design:returntype",Promise)],De.prototype,"update",null),n([Te(),i("design:type",Function),i("design:paramtypes",[Array,Object]),i("design:returntype",Promise)],De.prototype,"updateAll",null);class Le extends it{constructor(t){super(),this.adapter=t}get log(){return this.adapter.log.for(Le)}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?$.get(t):t,!this.fromSelector)throw new gt("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){let e=t;if((!e.length||!(e[e.length-1]instanceof o))&&this.fromSelector){const t=await this.adapter.context(l.READ,{},this.fromSelector);e=[...e,t]}const{ctx:r}=ot.logCtx(e,this.toString());try{const t=this.build();return await this.raw(t,r)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),n=await this.adapter.raw(t,...s);if(!this.selectSelector)return n;const i=$.pk(this.fromSelector),a=function(t){const e=t[i];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(n)?n.map(a):a(n)}toString(){return this.adapter.flavour+" statement"}}n([U(),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Object)],Le.prototype,"select",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(Ie="undefined"!=typeof S&&S)?Ie:Object]),i("design:returntype",Object)],Le.prototype,"distinct",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(Be="undefined"!=typeof S&&S)?Be:Object]),i("design:returntype",Object)],Le.prototype,"max",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(je="undefined"!=typeof S&&S)?je:Object]),i("design:returntype",Object)],Le.prototype,"min",null),n([U(),i("design:type",Function),i("design:paramtypes",["function"==typeof(ke="undefined"!=typeof S&&S)?ke:Object]),i("design:returntype",Object)],Le.prototype,"count",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Object)],Le.prototype,"from",null),n([U(),i("design:type",Function),i("design:paramtypes",[yt]),i("design:returntype",Object)],Le.prototype,"where",null),n([U(),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Object)],Le.prototype,"orderBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Object)],Le.prototype,"groupBy",null),n([U(),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Object)],Le.prototype,"limit",null),n([U(),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Object)],Le.prototype,"offset",null),n([U(),i("design:type",Function),i("design:paramtypes",[void 0]),i("design:returntype",Promise)],Le.prototype,"execute",null);class Fe extends Ee{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 r=await o.args(l.READ,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const n=await this.adapter.raw(s,...r.args);return this._currentPage=t,n}}class Me extends Le{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=H.getPropDesignTypes(t.constructor,s);if(!i)throw new gt("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===n?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===n?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new gt("Sorting not supported for not date classes");default:throw new gt("sorting not supported for type "+i)}}}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}async paginate(t){try{const e=this.build();return new Fe(this.adapter,e,t,this.fromSelector)}catch(t){throw new a(t)}}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:n}=t;if(-1===[ht.AND,ht.OR,dt.NOT].indexOf(s))switch(s){case dt.BIGGER:return e[r]>n;case dt.BIGGER_EQ:return e[r]>=n;case dt.DIFFERENT:return e[r]!==n;case dt.EQUAL:return e[r]===n;case dt.REGEXP:if("string"!=typeof e[r])throw new gt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(n,"g"));case dt.SMALLER:return e[r]<n;case dt.SMALLER_EQ:return e[r]<=n;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===dt.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),i=this.parseCondition(n);switch(s){case ht.AND:return t.where(e)&&i.where(e);case ht.OR:return t.where(e)||i.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Ue(t,e,r,s){const n=t.get("UUID");if(!n)throw new rt("This adapter does not support user identification");s[r]=n}const qe="ram";class Ge extends ot{constructor(t={},e){super(t,qe,e),this.Context=o,this.indexes={},this.lock=new Z}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[$.pk(t.constructor)],s}revert(t,e,r,s,...n){return super.revert(t,e,r,s,...n)}async create(t,e,r,s){const n=s.logger.for(this.create),i=$.tableName(t);if(n.debug(`creating record in table ${i} with id ${e}`),await this.lock.acquire(),this.client.has(i)||this.client.set(i,new Map),this.client.get(i)&&this.client.get(i)?.has(e))throw new b(`Record with id ${e} already exists in table ${i}`);return this.client.get(i)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=$.tableName(t);if(!this.client.has(s))throw new w(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new w(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const n=s.logger.for(this.update),i=$.tableName(t);if(n.debug(`updating record in table ${i} with id ${e}`),await this.lock.acquire(),!this.client.has(i))throw new w(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new w(`Record with id ${e} not found in table ${i}`);return this.client.get(i)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),n=$.tableName(t);if(s.debug(`deleting record from table ${n} with pk ${e}`),await this.lock.acquire(),!this.client.has(n))throw new w(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new w(`Record with id ${e} not found in table ${n}`);const i=this.client.get(n)?.get(e);return this.client.get(n)?.delete(e),this.lock.release(),i}tableFor(t){"string"==typeof t&&(t=$.get(t));const e=$.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:n,skip:i,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const u=$.pk(o),d=H.get(o,H.key(C.ID,u));let h=Array.from(l.entries()).map((([t,r])=>this.revert(r,o,ve.parseValue(d.type,t),void 0,e)));return h=r?h.filter(r):h,s&&(h=h.sort(s)),i&&(h=h.slice(i)),n&&(h=h.slice(0,n)),c&&(c=Array.isArray(c)?c:[c],h=h.map((t=>Object.entries(t).reduce(((t,[e,r])=>(c.includes(e)&&(t[e]=r),t)),{})))),h}parseError(t){return t instanceof _?t:new a(t)}Statement(){return new Me(this)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${R(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const n=Reflect.get(e,r,s);return Object.assign({},n,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=tt.CREATED_BY,e=tt.UPDATED_BY;G.flavouredAs(qe).for(t).define(A(Ue),J(t,{})).apply(),G.flavouredAs(qe).for(e).define(v(Ue),J(e,{})).apply()}getClient(){return new Map}}Ge.decoration(),e.setRegistry(new Ot);const ze="##VERSION##",He="##PACKAGE##";H.registerLibrary(He,ze);export{_t as AbsMigration,ot as Adapter,Gt as AuthorizationError,de as BaseModel,fe as BigIntSequence,lt as Cascade,Re as ClientBasedService,yt as Condition,Ht as ConnectionError,it as ContextualLoggedClass,ut as DefaultCascade,pe as DefaultSequenceOptions,Nt as Dispatch,zt as ForbiddenError,ht as GroupOperator,Ot as InjectablesRegistry,bt as MethodQueryBuilder,st as MigrationError,nt as MigrationRuleError,De as ModelService,he as NoneSequenceOptions,ge as NumericSequence,Ae as ObserverError,et as ObserverHandler,dt as Operator,wt as OperatorsMap,ct as OrderDirection,He as PACKAGE_NAME,Ee as Paginator,ft as PagingError,tt as PersistenceKeys,pt as QueryClause,gt as QueryError,Ge as RamAdapter,qe as RamFlavour,Fe as RamPaginator,Me as RamStatement,At as Repository,ve as Sequence,be as SequenceModel,Tt as Serial,$e as Service,Le as Statement,St as UUID,rt as UnsupportedError,ze as VERSION,Ft as cacheModelForPopulate,Vt as column,Ne as create,Rt as createOrUpdate,te as createdAt,Kt as createdBy,Jt as createdByOnCreateUpdate,Ue as createdByOnRamCreateUpdate,Ce as del,Et as generateInjectableNameForRepository,Lt as getPopulateKey,Qt as index,ie as manyToMany,ne as manyToOne,$t as migration,ae as noValidateOn,oe as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,se as oneToMany,Bt as oneToManyOnCreate,kt as oneToManyOnDelete,jt as oneToManyOnUpdate,re as oneToOne,Pt as oneToOneOnCreate,It as oneToOneOnDelete,Dt as oneToOneOnUpdate,me as pk,we as pkDec,ye as pkOnCreate,Mt as populate,Ct as prefixMethod,vt as prepared,xt as query,Se as read,ue as relation,xe as repository,qt as repositoryFromTypeMetadata,_e as service,Yt as table,Xt as unique,Wt as uniqueOnCreateUpdate,Te as update,ee as updatedAt,Zt as updatedBy};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|