@decaf-ts/core 0.7.48 → 0.7.49
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/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/decorators.d.ts +1 -1
- package/lib/esm/utils/decorators.js +17 -7
- package/lib/esm/utils/decorators.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/utils/decorators.cjs +16 -6
- package/lib/utils/decorators.d.ts +1 -1
- package/lib/utils/decorators.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 C,BulkCrudOperationKeys as _,readonly as T,SerializationError as B,prefixMethod as P,BaseError as $}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as D,final as I,isClass as k,toCamelCase as F}from"@decaf-ts/logging";import{Model as j,hashObj as L,required as M,sf as U,ValidationKeys as q,async as G,type as Y,list as z,model as Q}from"@decaf-ts/decorator-validation";import{Metadata as H,Decoration as V,DefaultFlavour as 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}=fe.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){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}const ge=V.flavourResolver.bind(V);V.flavourResolver=e=>{try{const t=ge(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=fe._currentFlavour;if(i){const e=fe._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return J}};class fe extends de{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!fe._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return fe._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 fe._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);fe._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),fe._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),fe._currentFlavour=this.alias)}Dispatch(){return new fe._baseDispatch}ObserverHandler(){return new oe}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new fe._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`),pe(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`),pe(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`),pe(t.map((t,s)=>()=>this.update(e,t,r[s],...n)))}async deleteAll(e,t,...r){const{log:s,ctxArgs:i}=fe.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),pe(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}=fe.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(!fe._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return fe._currentFlavour}static get current(){return fe.get(this.currentFlavour)}static get(e){if(!e)return fe.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}=fe.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)],fe.prototype,"shutdownProxies",null),i([I(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],fe.prototype,"context",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],fe.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],fe.prototype,"unObserve",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],fe.prototype,"client",null);class ye extends o{constructor(e){super(e,ye.name,500)}}class me extends o{constructor(e){super(e,me.name,500)}}var we,be,ve,xe,Ae,Ee;(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"})(we||(we={})),(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"})(be||(be={})),(e=>{e.AND="AND",e.OR="OR"})(ve||(ve={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(xe||(xe={}));class Oe 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 Oe.and(this,e)}or(e){return Oe.or(this,e)}not(e){return new Oe(this,be.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Oe)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(be).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof Oe){if(!(this.comparison instanceof Oe)&&this.operator!==be.NOT)return{comparison:{condition:e}};if(-1===Object.values(ve).indexOf(this.operator)&&this.operator!==be.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 Oe.group(e,ve.AND,t)}static or(e,t){return Oe.group(e,ve.OR,t)}static group(e,t,r){return new Oe(e,t,r)}static attribute(e){return(new Oe.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(be.EQUAL,e)}dif(e){return this.setOp(be.DIFFERENT,e)}gt(e){return this.setOp(be.BIGGER,e)}lt(e){return this.setOp(be.SMALLER,e)}gte(e){return this.setOp(be.BIGGER_EQ,e)}lte(e){return this.setOp(be.SMALLER_EQ,e)}in(e){return this.setOp(be.IN,e)}regexp(e){return this.setOp(be.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Oe(this.attr1,this.operator,this.comparison)}catch(e){throw new ye(e)}}}}static builder(){return new Oe.Builder}static from(e){return new Oe(e)}}i([M(),n("design:type",Object)],Oe.prototype,"attr1",void 0),i([M(),n("design:type",String)],Oe.prototype,"operator",void 0),i([M(),n("design:type",Object)],Oe.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(Ae||(Ae={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(Ee||(Ee={}));const Se={update:Ee.CASCADE,delete:Ee.NONE},Ne={Equals:(e,t)=>Oe.attribute(e).eq(t),Diff:(e,t)=>Oe.attribute(e).dif(t),LessThan:(e,t)=>Oe.attribute(e).lt(t),LessThanEqual:(e,t)=>Oe.attribute(e).lte(t),GreaterThan:(e,t)=>Oe.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Oe.attribute(e).gte(t),In:(e,t)=>Oe.attribute(e).in(t),Matches:(e,t)=>Oe.attribute(e).regexp(t)},Ce=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(we.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(we.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(we.SELECT);if(-1===t)return;const r=e.substring(t+we.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(we.AND).map(Ce).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(we.GROUP_BY);if(-1!==t)return e.substring(t+we.GROUP_BY.length).split(we.ORDER_BY)[0].split(we.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?Ne[a]:Ne.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]===we.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(Ne))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=_e.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new ye("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(Ae).includes(t))throw new ye(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Ae).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 Te(){return V.for(ne.STATEMENT).define({decorator:()=>(e,t,r)=>W(X(H.key(ne.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function Be(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}),Te(),(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 ye(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 fe.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=Ae.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(xe.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 ye("PaginateBy needs a page or a bookmark");const o=await ce.args(xe.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 ye("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(xe.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(xe.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 ye("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 Oe.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=>fe._baseSequence.parseValue(j.sequenceFor(this.class).type,e)):fe._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)||fe.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)||fe.currentFlavour,a=n?fe.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 $e(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([Te(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Pe.prototype,"listBy",null),i([Te(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Pe.prototype,"paginateBy",null),i([Te(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Pe.prototype,"findOneBy",null),i([Te(),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),fe&&(fe._baseRepository=Pe);class Re 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.toString())||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&&fe.get(o)}catch{const t=fe.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,$e(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?fe.get(o):fe.current;if(!e)return;return new t(e,n)}}}return i}}async function De(e,t,r,s){const i=t.logger.for(De);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 Ie(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=ze(s,r,this.adapter.alias),n=await t.read(i);return await qe(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 qe(e,s,r,c[l],c),s[r]=c[l]}async function ke(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Ee.CASCADE)return;if("object"!=typeof i){const t=ze(s,r,this.adapter.alias),n=await t.read(i,e);return await qe(e,s,r,i,n),void(s[r]=i)}const n=await De(s[r],e,this.adapter.alias),a=j.pk(n);await qe(e,s,r,n[a],n),s[r]=n[a]}async function Fe(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Ee.CASCADE)return;const n=ze(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 qe(e,s,r,a[n.pk],a)}async function je(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(je),c=new Set([...i]);if("object"!==n){const t=ze(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 qe(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 De(t,e,this.adapter.alias);a.info(`caching: ${JSON.stringify(i)} under ${i[l]}`),await qe(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 Le(e,t,r,s){const{cascade:i}=t;if(i.update===Ee.CASCADE)return je.call(this,e,t,r,s)}async function Me(e,t,r,s){if(t.cascade.delete!==Ee.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):ze(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 qe(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 Ue(e,t,r){return[ne.POPULATE,e,t,r].join(".")}async function qe(e,t,r,s,i){const n=Ue(t.constructor.name,r,s),a=e.get("cacheForPopulate")||{};return a[n]=i,e.accumulate({cacheForPopulate:a})}async function Ge(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=Ue(r.constructor.name,s,t);try{if(c=h[a],!c)throw Error("Not found in cache")}catch(i){const a=ze(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 Ye=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function ze(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=>!Ye.includes((""+e.name).toLowerCase()));return Pe.forModel(i,r)}class Qe extends w{constructor(e,t=Qe.name,r=401){super(e,t,r)}}class He extends Qe{constructor(e,t=He.name){super(e,t,403)}}class Ve extends o{constructor(e){super(e,Ve.name,503)}}function Je(e){return V.for(ne.TABLE).define({decorator:e=>t=>ee(ne.TABLE,e||t.name.toLowerCase())(t),args:[e]}).apply()}function We(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 Xe(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=>![Ae.ASC,Ae.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 Ke(e,t,r,s){if(s[r]&&(await this.select().where(Oe.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 Ze(){const e=ne.UNIQUE;return V.for(e).define(G(),v(Ke),te(e,{})).apply()}async function et(e,t,r,s){throw new Qe("This adapter does not support user identification")}function tt(){return V.for(ne.CREATED_BY).define({decorator:()=>(e,t)=>W(A(et),te(ne.CREATED_BY,t),lt())(e,t),args:[]}).apply()}function rt(){return V.for(ne.UPDATED_BY).define({decorator:()=>(e,t)=>W(E(et),te(ne.UPDATED_BY,t),lt())(e,t),args:[]}).apply()}function st(){return x([l.CREATE])}function it(){return x()}function nt(e,t=Se,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(),gt(n,a),Y([e,String,Number,BigInt]),A(Ie,a),E(ke,a),O(Fe,a),N(Ge,a))},args:[e,t,r,s,i]}).apply()}function at(e,t=Se,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(),gt(n,a),z([e,String,Number,BigInt]),A(je,a),E(Le,a),O(Me,a),N(Ge,a))},args:[e,t,r,s,i]}).apply()}function ot(e,t=Se,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(),gt(n,a),Y([e,String,Number,BigInt]))},args:[e,t,r,s,i]}).apply()}function ct(e,t=Se,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(),gt(n,a),z([e,String,Number,BigInt]))},args:[e,t,r,s,i]}).apply()}function lt(e){return(t,r)=>te(H.key(ne.GENERATED,r),e||!0)(t,r)}function ht(...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 ut(){return ht(l.CREATE)}function dt(){return ht(l.UPDATE)}function pt(){return ht(l.UPDATE,l.CREATE)}function gt(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(C.TIMESTAMP).extend(lt()).apply(),V.for(C.COMPOSED).extend(lt()).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??fe.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(C.REPOSITORY));class ft 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,_.CREATE_ALL,_.UPDATE_ALL,_.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 _.CREATE_ALL:return l.CREATE;case _.UPDATE_ALL:return l.UPDATE;case _.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 fe))throw new le("Only Adapters can be observed by dispatch");this.adapter=e,this.models=fe.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}`)}}fe&&(fe._baseDispatch=ft);class yt{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 yt._instance||(yt._instance=new yt),yt._instance}}class mt{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return mt._instance||(mt._instance=new mt),mt._instance}}function wt(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 bt extends R{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;wt(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 fe.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 fe?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 vt(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 xt extends j{constructor(e){super(e)}}i([st(),n("design:type",Date)],xt.prototype,"createdAt",void 0),i([it(),n("design:type",Date)],xt.prototype,"updatedAt",void 0);const At={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Et=At,Ot={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},St=Object.assign({},Ot,{type:"BigInt"});async function Nt(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=[Xe([Ae.ASC,Ae.DSC]),M(),T(),te(H.key(C.ID,s),e),A(Nt,e,t)];return e.generated&&i.push(lt()),W(...i)(r,s)}}function _t(e=Et){return e=Object.assign({},Et,e),V.for(C.ID).define({decorator:Ct,args:[e,{priority:60}]}).apply()}let Tt=class extends xt{constructor(e){super(e)}};i([_t({type:"String",generated:!1}),n("design:type",String)],Tt.prototype,"id",void 0),i([M(),Xe(),n("design:type",Object)],Tt.prototype,"current",void 0),Tt=i([Je("??sequence"),Q(),n("design:paramtypes",[Object])],Tt);class Bt extends de{static{this.lock=new se}constructor(e,t){super(),this.options=e,this.adapter=t,this.repo=Pe.forModel(Tt,t.alias)}async current(...e){const t=(await ce.args(l.READ,Tt,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 Bt.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 Tt({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 Tt({id:n,current:e}),t);throw s}};if("uuid"===c)for(;;){const e=yt.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 mt.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,Tt,e,this.adapter),{context:r}=t;return this.increment(void 0,r)}async range(e,...t){const r=await ce.args(l.UPDATE,Tt,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 Bt.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(C.REPOSITORY,H.key(t||fe.currentFlavour,j.tableName(e)),i),ee(C.REPOSITORY,i.name)(e),t=t||H.get(i.constructor,ne.ADAPTER),Pe.register(H.constr(e),i,t),s(H.constr(e),{callback:t=>(Object.defineProperty(t,C.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}fe._baseSequence=Bt;class $t extends o{constructor(e){super(e,$t.name,500)}}class Rt 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,wt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${xe.FIND_BY}|${xe.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(`^${xe.FIND_BY}|${xe.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,xe.PAGE_BY),l=[c,...n];let h={limit:this.size,offset:e,bookmark:this._bookmark};c!==xe.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 me("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new me(`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?Rt.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 Dt(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 It=()=>Dt(l.CREATE),kt=()=>Dt(l.READ),Ft=()=>Dt(l.UPDATE),jt=()=>Dt(l.DELETE);function Lt(e){return e="string"==typeof e?e:H.Symbol(e).toString(),(t,i,n)=>{H.set(ne.SERVICE,e,t);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 a.push(s(e,{callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return a.push(ee(ne.SERVICE,e)),W(...a)(t,i,n)}}class Mt{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 Mt.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=t.get(e);if(r)return r;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,t]of Object.entries(n))try{const e=new t;e instanceof Ut&&await e.boot(...i)}catch(t){s.error(`Failed to boot ${e} service`,t)}}}class Ut extends Mt{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)],Ut.prototype,"boot",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ut.prototype,"config",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ut.prototype,"client",null);const qt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Gt extends Mt{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=qt(e);try{const e=Mt.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 Gt.logCtx.bind(this.repo.adapter)(e,t,r,this.repo._overrides,this.class)}static forModel(e,t){let r;t=qt(t||e);try{r=Gt.get(t)}catch(e){r=void 0}if(r instanceof Gt)return r;const s=this;let a=class extends s{constructor(){super(e)}};return a=i([Lt(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 Yt,zt,Qt,Ht;i([It(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"create",null),i([It(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"createAll",null),i([jt(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"delete",null),i([jt(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"deleteAll",null),i([kt(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"read",null),i([kt(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"readAll",null),i([kt(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Gt.prototype,"query",null),i([Ft(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"update",null),i([Ft(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Gt.prototype,"updateAll",null);class Vt extends de{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{P(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}=fe.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(Vt)}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 ye("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 ye(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 ve.AND:case ve.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 Oe){const e=this.prepareCondition(i,t);a=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${a}`;break}case be.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case be.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case be.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case be.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case be.BIGGER_EQ:n.method=r+" bigger than equal";break;case be.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case be.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case be.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new ye("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 Oe)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,Ae.DSC]:[j.pk(this.fromSelector),Ae.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:xe.LIST_BY,args:[s],params:n};return t&&(a.method=xe.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=[we.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(we.SELECT,this.selectSelector.join(` ${we.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(we.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(we.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 ye(e)}}toString(){return this.adapter.flavour+" statement"}}i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Vt.prototype,"select",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Yt="undefined"!=typeof S&&S)?Yt:Object]),n("design:returntype",Object)],Vt.prototype,"distinct",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(zt="undefined"!=typeof S&&S)?zt:Object]),n("design:returntype",Object)],Vt.prototype,"max",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Qt="undefined"!=typeof S&&S)?Qt:Object]),n("design:returntype",Object)],Vt.prototype,"min",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ht="undefined"!=typeof S&&S)?Ht:Object]),n("design:returntype",Object)],Vt.prototype,"count",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Vt.prototype,"from",null),i([I(),n("design:type",Function),n("design:paramtypes",[Oe]),n("design:returntype",Object)],Vt.prototype,"where",null),i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Vt.prototype,"orderBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Vt.prototype,"groupBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Vt.prototype,"limit",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Vt.prototype,"offset",null),i([I(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Vt.prototype,"execute",null);class Jt extends Vt{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()===Ae.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 ye("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===[ve.AND,ve.OR,be.NOT].indexOf(s))switch(s){case be.BIGGER:return t[r]>i;case be.BIGGER_EQ:return t[r]>=i;case be.DIFFERENT:return t[r]!==i;case be.EQUAL:return t[r]===i;case be.REGEXP:if("string"!=typeof t[r])throw new ye("Invalid regexp comparison on a non string attribute: "+t[r]);return!!t[r].match(RegExp(i,"g"));case be.SMALLER:return t[r]<i;case be.SMALLER_EQ:return t[r]<=i;default:throw new o("Invalid operator for standard comparisons: "+s)}else{if(s===be.NOT)throw new o("Not implemented");{const e=this.parseCondition(r),n=this.parseCondition(i);switch(s){case ve.AND:return e.where(t)&&n.where(t);case ve.OR:return e.where(t)||n.where(t);default:throw new o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Wt(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 Xt="ram";class Kt extends Rt{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 Zt extends fe{constructor(e={},t){super(e,Xt,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(C.ID,u));let p=Array.from(h.entries()).map(([e,t])=>this.revert(t,c,Bt.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 $?e:new o(e)}Statement(e){return new Jt(this,e)}Paginator(e,t,r){return new Kt(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(Xt).for(e).define(A(Wt),te(e,{})).apply(),V.flavouredAs(Xt).for(t).define(v(Wt),te(t,{})).apply()}getClient(){return new Map}}Zt.decoration(),t.setRegistry(new Re);const er="##VERSION##",tr="##PACKAGE##";H.registerLibrary(tr,er);export{bt as AbsMigration,fe as Adapter,Qe as AuthorizationError,xt as BaseModel,St as BigIntSequence,Ee as Cascade,Ut as ClientBasedService,Oe as Condition,Ve as ConnectionError,ce as Context,de as ContextualLoggedClass,ae as DefaultAdapterFlags,Se as DefaultCascade,Et as DefaultSequenceOptions,ft as Dispatch,He as ForbiddenError,ve as GroupOperator,Re as InjectablesRegistry,_e as MethodQueryBuilder,he as MigrationError,ue as MigrationRuleError,Gt as ModelService,At as NoneSequenceOptions,Ot as NumericSequence,$t as ObserverError,oe as ObserverHandler,be as Operator,Ne as OperatorsMap,Ae as OrderDirection,tr as PACKAGE_NAME,Rt as Paginator,me as PagingError,ne as PersistenceKeys,xe as PreparedStatementKeys,we as QueryClause,ye as QueryError,Zt as RamAdapter,Xt as RamFlavour,Kt as RamPaginator,Jt as RamStatement,Pe as Repository,Bt as Sequence,Tt as SequenceModel,mt as Serial,Mt as Service,Vt as Statement,yt as UUID,le as UnsupportedError,er as VERSION,qe as cacheModelForPopulate,We as column,It as create,De as createOrUpdate,st as createdAt,tt as createdBy,et as createdByOnCreateUpdate,Wt as createdByOnRamCreateUpdate,jt as del,$e as generateInjectableNameForRepository,lt as generated,Ue as getPopulateKey,Xe as index,ct as manyToMany,ot as manyToOne,vt as migration,ht as noValidateOn,ut as noValidateOnCreate,pt as noValidateOnCreateUpdate,dt as noValidateOnUpdate,at as oneToMany,je as oneToManyOnCreate,Me as oneToManyOnDelete,Le as oneToManyOnUpdate,nt as oneToOne,Ie as oneToOneOnCreate,Fe as oneToOneOnDelete,ke as oneToOneOnUpdate,_t as pk,Ct as pkDec,Nt as pkOnCreate,Ge as populate,wt as prefixMethod,Te as prepared,Be as query,kt as read,gt as relation,Pt as repository,ze as repositoryFromTypeMetadata,Lt as service,Je as table,Ze as unique,Ke as uniqueOnCreateUpdate,Ft as update,it as updatedAt,rt 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 P,BaseError as $}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as D,final as I,isClass as k,toCamelCase as F}from"@decaf-ts/logging";import{Model as j,hashObj as L,required as M,sf as U,ValidationKeys as q,async as G,type as Y,list as z,model as Q}from"@decaf-ts/decorator-validation";import{Metadata as H,Decoration as V,DefaultFlavour as 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}=fe.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){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}const ge=V.flavourResolver.bind(V);V.flavourResolver=e=>{try{const t=ge(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=fe._currentFlavour;if(i){const e=fe._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return J}};class fe extends de{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!fe._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return fe._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 fe._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);fe._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),fe._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),fe._currentFlavour=this.alias)}Dispatch(){return new fe._baseDispatch}ObserverHandler(){return new oe}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new fe._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`),pe(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`),pe(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`),pe(t.map((t,s)=>()=>this.update(e,t,r[s],...n)))}async deleteAll(e,t,...r){const{log:s,ctxArgs:i}=fe.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),pe(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}=fe.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(!fe._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return fe._currentFlavour}static get current(){return fe.get(this.currentFlavour)}static get(e){if(!e)return fe.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}=fe.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)],fe.prototype,"shutdownProxies",null),i([I(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],fe.prototype,"context",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],fe.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],fe.prototype,"unObserve",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],fe.prototype,"client",null);class ye extends o{constructor(e){super(e,ye.name,500)}}class me extends o{constructor(e){super(e,me.name,500)}}var we,be,ve,xe,Ae,Ee;(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"})(we||(we={})),(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"})(be||(be={})),(e=>{e.AND="AND",e.OR="OR"})(ve||(ve={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(xe||(xe={}));class Oe 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 Oe.and(this,e)}or(e){return Oe.or(this,e)}not(e){return new Oe(this,be.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Oe)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(be).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof Oe){if(!(this.comparison instanceof Oe)&&this.operator!==be.NOT)return{comparison:{condition:e}};if(-1===Object.values(ve).indexOf(this.operator)&&this.operator!==be.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 Oe.group(e,ve.AND,t)}static or(e,t){return Oe.group(e,ve.OR,t)}static group(e,t,r){return new Oe(e,t,r)}static attribute(e){return(new Oe.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(be.EQUAL,e)}dif(e){return this.setOp(be.DIFFERENT,e)}gt(e){return this.setOp(be.BIGGER,e)}lt(e){return this.setOp(be.SMALLER,e)}gte(e){return this.setOp(be.BIGGER_EQ,e)}lte(e){return this.setOp(be.SMALLER_EQ,e)}in(e){return this.setOp(be.IN,e)}regexp(e){return this.setOp(be.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Oe(this.attr1,this.operator,this.comparison)}catch(e){throw new ye(e)}}}}static builder(){return new Oe.Builder}static from(e){return new Oe(e)}}i([M(),n("design:type",Object)],Oe.prototype,"attr1",void 0),i([M(),n("design:type",String)],Oe.prototype,"operator",void 0),i([M(),n("design:type",Object)],Oe.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(Ae||(Ae={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(Ee||(Ee={}));const Se={update:Ee.CASCADE,delete:Ee.NONE},Ne={Equals:(e,t)=>Oe.attribute(e).eq(t),Diff:(e,t)=>Oe.attribute(e).dif(t),LessThan:(e,t)=>Oe.attribute(e).lt(t),LessThanEqual:(e,t)=>Oe.attribute(e).lte(t),GreaterThan:(e,t)=>Oe.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Oe.attribute(e).gte(t),In:(e,t)=>Oe.attribute(e).in(t),Matches:(e,t)=>Oe.attribute(e).regexp(t)},_e=e=>e.charAt(0).toLowerCase()+e.slice(1);class Ce extends R{static get log(){return this._logger||(this._logger=D.for(Ce.name)),this._logger}static build(e,...t){if(!e.startsWith(we.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(we.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(we.SELECT);if(-1===t)return;const r=e.substring(t+we.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(we.AND).map(_e).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(we.GROUP_BY);if(-1!==t)return e.substring(t+we.GROUP_BY.length).split(we.ORDER_BY)[0].split(we.THEN_BY).map(_e).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?Ne[a]:Ne.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]===we.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(Ne))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:_e(r),operator:t}}return{field:_e(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=Ce.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new ye("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(Ae).includes(t))throw new ye(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Ae).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 Te(){return V.for(ne.STATEMENT).define({decorator:()=>(e,t,r)=>W(X(H.key(ne.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function Be(e={}){return V.for(ne.QUERY).define({decorator:e=>(t,r,s)=>{const i=Ce.getFieldsFromMethodName(r);return W(X(H.key(ne.QUERY,r),{...e,fields:i}),Te(),(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}=Ce.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 ye(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 fe.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=Ae.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(xe.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 ye("PaginateBy needs a page or a bookmark");const o=await ce.args(xe.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 ye("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(xe.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(xe.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 ye("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 Oe.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=>fe._baseSequence.parseValue(j.sequenceFor(this.class).type,e)):fe._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)||fe.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)||fe.currentFlavour,a=n?fe.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 $e(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([Te(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Pe.prototype,"listBy",null),i([Te(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Pe.prototype,"paginateBy",null),i([Te(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Pe.prototype,"findOneBy",null),i([Te(),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),fe&&(fe._baseRepository=Pe);class Re 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.toString())||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&&fe.get(o)}catch{const t=fe.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,$e(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?fe.get(o):fe.current;if(!e)return;return new t(e,n)}}}return i}}async function De(e,t,r,s){const i=t.logger.for(De);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 Ie(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=ze(s,r,this.adapter.alias),n=await t.read(i);return await qe(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 qe(e,s,r,c[l],c),s[r]=c[l]}async function ke(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Ee.CASCADE)return;if("object"!=typeof i){const t=ze(s,r,this.adapter.alias),n=await t.read(i,e);return await qe(e,s,r,i,n),void(s[r]=i)}const n=await De(s[r],e,this.adapter.alias),a=j.pk(n);await qe(e,s,r,n[a],n),s[r]=n[a]}async function Fe(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Ee.CASCADE)return;const n=ze(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 qe(e,s,r,a[n.pk],a)}async function je(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(je),c=new Set([...i]);if("object"!==n){const t=ze(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 qe(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 De(t,e,this.adapter.alias);a.info(`caching: ${JSON.stringify(i)} under ${i[l]}`),await qe(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 Le(e,t,r,s){const{cascade:i}=t;if(i.update===Ee.CASCADE)return je.call(this,e,t,r,s)}async function Me(e,t,r,s){if(t.cascade.delete!==Ee.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):ze(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 qe(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 Ue(e,t,r){return[ne.POPULATE,e,t,r].join(".")}async function qe(e,t,r,s,i){const n=Ue(t.constructor.name,r,s),a=e.get("cacheForPopulate")||{};return a[n]=i,e.accumulate({cacheForPopulate:a})}async function Ge(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=Ue(r.constructor.name,s,t);try{if(c=h[a],!c)throw Error("Not found in cache")}catch(i){const a=ze(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 Ye=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function ze(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=>!Ye.includes((""+e.name).toLowerCase()));return Pe.forModel(i,r)}class Qe extends w{constructor(e,t=Qe.name,r=401){super(e,t,r)}}class He extends Qe{constructor(e,t=He.name){super(e,t,403)}}class Ve extends o{constructor(e){super(e,Ve.name,503)}}function Je(e){return V.for(ne.TABLE).define({decorator:e=>t=>ee(ne.TABLE,e||t.name.toLowerCase())(t),args:[e]}).apply()}function We(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 Xe(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=>![Ae.ASC,Ae.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 Ke(e,t,r,s){if(s[r]&&(await this.select().where(Oe.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 Ze(){const e=ne.UNIQUE;return V.for(e).define(G(),v(Ke),te(e,{})).apply()}async function et(e,t,r,s){throw new Qe("This adapter does not support user identification")}function tt(){return V.for(ne.CREATED_BY).define({decorator:()=>(e,t)=>W(A(et),te(ne.CREATED_BY,t),lt())(e,t),args:[]}).apply()}function rt(){return V.for(ne.UPDATED_BY).define({decorator:()=>(e,t)=>W(E(et),te(ne.UPDATED_BY,t),lt())(e,t),args:[]}).apply()}function st(){return x([l.CREATE])}function it(){return x()}function nt(e,t=Se,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(),gt(n,a),Y([e,String,Number,BigInt]),A(Ie,a),E(ke,a),O(Fe,a),N(Ge,a))},args:[e,t,r,s,i]}).apply()}function at(e,t=Se,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(),gt(n,a),z([e,String,Number,BigInt]),A(je,a),E(Le,a),O(Me,a),N(Ge,a))},args:[e,t,r,s,i]}).apply()}function ot(e,t=Se,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(),gt(n,a),Y([e,String,Number,BigInt]))},args:[e,t,r,s,i]}).apply()}function ct(e,t=Se,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(),gt(n,a),z([e,String,Number,BigInt]))},args:[e,t,r,s,i]}).apply()}function lt(e){return(t,r)=>te(H.key(ne.GENERATED,r),e||!0)(t,r)}function ht(...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 ut(){return ht(l.CREATE)}function dt(){return ht(l.UPDATE)}function pt(){return ht(l.UPDATE,l.CREATE)}function gt(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(lt()).apply(),V.for(_.COMPOSED).extend(lt()).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??fe.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 ft 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 fe))throw new le("Only Adapters can be observed by dispatch");this.adapter=e,this.models=fe.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}`)}}fe&&(fe._baseDispatch=ft);class yt{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 yt._instance||(yt._instance=new yt),yt._instance}}class mt{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return mt._instance||(mt._instance=new mt),mt._instance}}function wt(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 bt extends R{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;wt(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 fe.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 fe?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 vt(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 xt extends j{constructor(e){super(e)}}i([st(),n("design:type",Date)],xt.prototype,"createdAt",void 0),i([it(),n("design:type",Date)],xt.prototype,"updatedAt",void 0);const At={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Et=At,Ot={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},St=Object.assign({},Ot,{type:"BigInt"});async function Nt(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 _t(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=[Xe([Ae.ASC,Ae.DSC]),M(),T(),te(H.key(_.ID,s),e),A(Nt,e,t)];return e.generated&&i.push(lt()),W(...i)(r,s)}}function Ct(e=Et){return e=Object.assign({},Et,e),V.for(_.ID).define({decorator:_t,args:[e,{priority:60}]}).apply()}let Tt=class extends xt{constructor(e){super(e)}};i([Ct({type:"String",generated:!1}),n("design:type",String)],Tt.prototype,"id",void 0),i([M(),Xe(),n("design:type",Object)],Tt.prototype,"current",void 0),Tt=i([Je("??sequence"),Q(),n("design:paramtypes",[Object])],Tt);class Bt extends de{static{this.lock=new se}constructor(e,t){super(),this.options=e,this.adapter=t,this.repo=Pe.forModel(Tt,t.alias)}async current(...e){const t=(await ce.args(l.READ,Tt,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 Bt.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 Tt({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 Tt({id:n,current:e}),t);throw s}};if("uuid"===c)for(;;){const e=yt.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 mt.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,Tt,e,this.adapter),{context:r}=t;return this.increment(void 0,r)}async range(e,...t){const r=await ce.args(l.UPDATE,Tt,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 Bt.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||fe.currentFlavour,j.tableName(e)),i),ee(_.REPOSITORY,i.name)(e),t=t||H.get(i.constructor,ne.ADAPTER),Pe.register(H.constr(e),i,t),s(H.constr(e),{callback:t=>(Object.defineProperty(t,_.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}fe._baseSequence=Bt;class $t extends o{constructor(e){super(e,$t.name,500)}}class Rt 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,wt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${xe.FIND_BY}|${xe.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(`^${xe.FIND_BY}|${xe.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,xe.PAGE_BY),l=[c,...n];let h={limit:this.size,offset:e,bookmark:this._bookmark};c!==xe.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 me("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new me(`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?Rt.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 Dt(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 It=()=>Dt(l.CREATE),kt=()=>Dt(l.READ),Ft=()=>Dt(l.UPDATE),jt=()=>Dt(l.DELETE);function Lt(e){return(t,i,n)=>{e="string"==typeof(e=n?e||H.type(t.constructor,i):e||t)?e:H.Symbol(H.constr(e)).toString().replaceAll(".","-");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,{callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return W(...a)(t,i,n)}}class Mt{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 Mt.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=t.get(e);if(r)return r;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,t]of Object.entries(n))try{const e=new t;e instanceof Ut&&await e.boot(...i)}catch(t){s.error(`Failed to boot ${e} service`,t)}}}class Ut extends Mt{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)],Ut.prototype,"boot",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ut.prototype,"config",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],Ut.prototype,"client",null);const qt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Gt extends Mt{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=qt(e);try{const e=Mt.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 Gt.logCtx.bind(this.repo.adapter)(e,t,r,this.repo._overrides,this.class)}static forModel(e,t){let r;t=qt(t||e);try{r=Gt.get(t)}catch(e){r=void 0}if(r instanceof Gt)return r;const s=this;let a=class extends s{constructor(){super(e)}};return a=i([Lt(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 Yt,zt,Qt,Ht;i([It(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"create",null),i([It(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"createAll",null),i([jt(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"delete",null),i([jt(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"deleteAll",null),i([kt(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"read",null),i([kt(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Gt.prototype,"readAll",null),i([kt(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Gt.prototype,"query",null),i([Ft(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Gt.prototype,"update",null),i([Ft(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Gt.prototype,"updateAll",null);class Vt extends de{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{P(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}=fe.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(Vt)}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 ye("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 ye(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 ve.AND:case ve.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 Oe){const e=this.prepareCondition(i,t);a=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${a}`;break}case be.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case be.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case be.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case be.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case be.BIGGER_EQ:n.method=r+" bigger than equal";break;case be.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case be.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case be.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new ye("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 Oe)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,Ae.DSC]:[j.pk(this.fromSelector),Ae.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:xe.LIST_BY,args:[s],params:n};return t&&(a.method=xe.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=[we.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(we.SELECT,this.selectSelector.join(` ${we.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(we.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(we.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 ye(e)}}toString(){return this.adapter.flavour+" statement"}}i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Vt.prototype,"select",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Yt="undefined"!=typeof S&&S)?Yt:Object]),n("design:returntype",Object)],Vt.prototype,"distinct",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(zt="undefined"!=typeof S&&S)?zt:Object]),n("design:returntype",Object)],Vt.prototype,"max",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Qt="undefined"!=typeof S&&S)?Qt:Object]),n("design:returntype",Object)],Vt.prototype,"min",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ht="undefined"!=typeof S&&S)?Ht:Object]),n("design:returntype",Object)],Vt.prototype,"count",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Vt.prototype,"from",null),i([I(),n("design:type",Function),n("design:paramtypes",[Oe]),n("design:returntype",Object)],Vt.prototype,"where",null),i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Vt.prototype,"orderBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Vt.prototype,"groupBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Vt.prototype,"limit",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Vt.prototype,"offset",null),i([I(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Vt.prototype,"execute",null);class Jt extends Vt{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()===Ae.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 ye("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===[ve.AND,ve.OR,be.NOT].indexOf(s))switch(s){case be.BIGGER:return t[r]>i;case be.BIGGER_EQ:return t[r]>=i;case be.DIFFERENT:return t[r]!==i;case be.EQUAL:return t[r]===i;case be.REGEXP:if("string"!=typeof t[r])throw new ye("Invalid regexp comparison on a non string attribute: "+t[r]);return!!t[r].match(RegExp(i,"g"));case be.SMALLER:return t[r]<i;case be.SMALLER_EQ:return t[r]<=i;default:throw new o("Invalid operator for standard comparisons: "+s)}else{if(s===be.NOT)throw new o("Not implemented");{const e=this.parseCondition(r),n=this.parseCondition(i);switch(s){case ve.AND:return e.where(t)&&n.where(t);case ve.OR:return e.where(t)||n.where(t);default:throw new o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Wt(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 Xt="ram";class Kt extends Rt{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 Zt extends fe{constructor(e={},t){super(e,Xt,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,Bt.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 $?e:new o(e)}Statement(e){return new Jt(this,e)}Paginator(e,t,r){return new Kt(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(Xt).for(e).define(A(Wt),te(e,{})).apply(),V.flavouredAs(Xt).for(t).define(v(Wt),te(t,{})).apply()}getClient(){return new Map}}Zt.decoration(),t.setRegistry(new Re);const er="##VERSION##",tr="##PACKAGE##";H.registerLibrary(tr,er);export{bt as AbsMigration,fe as Adapter,Qe as AuthorizationError,xt as BaseModel,St as BigIntSequence,Ee as Cascade,Ut as ClientBasedService,Oe as Condition,Ve as ConnectionError,ce as Context,de as ContextualLoggedClass,ae as DefaultAdapterFlags,Se as DefaultCascade,Et as DefaultSequenceOptions,ft as Dispatch,He as ForbiddenError,ve as GroupOperator,Re as InjectablesRegistry,Ce as MethodQueryBuilder,he as MigrationError,ue as MigrationRuleError,Gt as ModelService,At as NoneSequenceOptions,Ot as NumericSequence,$t as ObserverError,oe as ObserverHandler,be as Operator,Ne as OperatorsMap,Ae as OrderDirection,tr as PACKAGE_NAME,Rt as Paginator,me as PagingError,ne as PersistenceKeys,xe as PreparedStatementKeys,we as QueryClause,ye as QueryError,Zt as RamAdapter,Xt as RamFlavour,Kt as RamPaginator,Jt as RamStatement,Pe as Repository,Bt as Sequence,Tt as SequenceModel,mt as Serial,Mt as Service,Vt as Statement,yt as UUID,le as UnsupportedError,er as VERSION,qe as cacheModelForPopulate,We as column,It as create,De as createOrUpdate,st as createdAt,tt as createdBy,et as createdByOnCreateUpdate,Wt as createdByOnRamCreateUpdate,jt as del,$e as generateInjectableNameForRepository,lt as generated,Ue as getPopulateKey,Xe as index,ct as manyToMany,ot as manyToOne,vt as migration,ht as noValidateOn,ut as noValidateOnCreate,pt as noValidateOnCreateUpdate,dt as noValidateOnUpdate,at as oneToMany,je as oneToManyOnCreate,Me as oneToManyOnDelete,Le as oneToManyOnUpdate,nt as oneToOne,Ie as oneToOneOnCreate,Fe as oneToOneOnDelete,ke as oneToOneOnUpdate,Ct as pk,_t as pkDec,Nt as pkOnCreate,Ge as populate,wt as prefixMethod,Te as prepared,Be as query,kt as read,gt as relation,Pt as repository,ze as repositoryFromTypeMetadata,Lt as service,Je as table,Ze as unique,Ke as uniqueOnCreateUpdate,Ft as update,it as updatedAt,rt as updatedBy};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|