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