@decaf-ts/core 0.7.14 → 0.7.15

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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/dist/core.cjs +1 -1
  3. package/dist/core.cjs.map +1 -1
  4. package/dist/core.js +1 -1
  5. package/dist/core.js.map +1 -1
  6. package/lib/esm/index.d.ts +1 -1
  7. package/lib/esm/index.js +1 -1
  8. package/lib/esm/interfaces/RawExecutor.d.ts +11 -0
  9. package/lib/esm/persistence/Adapter.d.ts +7 -6
  10. package/lib/esm/persistence/Adapter.js.map +1 -1
  11. package/lib/esm/persistence/constants.js +3 -3
  12. package/lib/esm/persistence/constants.js.map +1 -1
  13. package/lib/esm/persistence/types.d.ts +7 -3
  14. package/lib/esm/query/Paginator.d.ts +8 -4
  15. package/lib/esm/query/Paginator.js +31 -0
  16. package/lib/esm/query/Paginator.js.map +1 -1
  17. package/lib/esm/query/Statement.d.ts +5 -2
  18. package/lib/esm/query/Statement.js +38 -91
  19. package/lib/esm/query/Statement.js.map +1 -1
  20. package/lib/esm/ram/RamAdapter.d.ts +3 -3
  21. package/lib/esm/ram/RamAdapter.js +11 -5
  22. package/lib/esm/ram/RamAdapter.js.map +1 -1
  23. package/lib/esm/ram/RamPaginator.js +13 -9
  24. package/lib/esm/ram/RamPaginator.js.map +1 -1
  25. package/lib/esm/ram/RamStatement.d.ts +2 -2
  26. package/lib/esm/ram/RamStatement.js +2 -2
  27. package/lib/esm/ram/RamStatement.js.map +1 -1
  28. package/lib/esm/repository/Repository.d.ts +1 -1
  29. package/lib/esm/repository/Repository.js +12 -2
  30. package/lib/esm/repository/Repository.js.map +1 -1
  31. package/lib/index.cjs +1 -1
  32. package/lib/index.d.ts +1 -1
  33. package/lib/interfaces/RawExecutor.d.ts +11 -0
  34. package/lib/persistence/Adapter.d.ts +7 -6
  35. package/lib/persistence/Adapter.js.map +1 -1
  36. package/lib/persistence/constants.cjs +3 -3
  37. package/lib/persistence/constants.js.map +1 -1
  38. package/lib/persistence/types.d.ts +7 -3
  39. package/lib/query/Paginator.cjs +31 -0
  40. package/lib/query/Paginator.d.ts +8 -4
  41. package/lib/query/Paginator.js.map +1 -1
  42. package/lib/query/Statement.cjs +38 -91
  43. package/lib/query/Statement.d.ts +5 -2
  44. package/lib/query/Statement.js.map +1 -1
  45. package/lib/ram/RamAdapter.cjs +10 -4
  46. package/lib/ram/RamAdapter.d.ts +3 -3
  47. package/lib/ram/RamAdapter.js.map +1 -1
  48. package/lib/ram/RamPaginator.cjs +13 -9
  49. package/lib/ram/RamPaginator.js.map +1 -1
  50. package/lib/ram/RamStatement.cjs +2 -2
  51. package/lib/ram/RamStatement.d.ts +2 -2
  52. package/lib/ram/RamStatement.js.map +1 -1
  53. package/lib/repository/Repository.cjs +12 -2
  54. package/lib/repository/Repository.d.ts +1 -1
  55. package/lib/repository/Repository.js.map +1 -1
  56. package/package.json +1 -1
package/README.md CHANGED
@@ -29,7 +29,7 @@ Decaf Core provides the foundational building blocks for the Decaf TypeScript ec
29
29
 
30
30
  Documentation [here](https://decaf-ts.github.io/injectable-decorators/), Test results [here](https://decaf-ts.github.io/injectable-decorators/workdocs/reports/html/test-report.html) and Coverage [here](https://decaf-ts.github.io/injectable-decorators/workdocs/reports/coverage/lcov-report/index.html)
31
31
 
32
- Minimal size: 18.1 KB kb gzipped
32
+ Minimal size: 18.5 KB kb gzipped
33
33
 
34
34
 
35
35
  # Core Package — Detailed Description
package/dist/core.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,s,n,o,i){"use strict";var c;e.PersistenceKeys=void 0,(c=e.PersistenceKeys||(e.PersistenceKeys={})).INDEX="index",c.UNIQUE="unique",c.ADAPTER="adapter",c.INJECTABLE="decaf_{0}_adapter_for_{1}",c.SERVICE="service",c.TABLE="table",c.COLUMN="column",c.METADATA="__metadata",c.OWNERSHIP="ownership",c.CREATED_BY="ownership.created-by",c.UPDATED_BY="ownership.updated-by",c.RELATIONS="__relations",c.RELATION="relation",c.ONE_TO_ONE="relation.one-to-one",c.ONE_TO_MANY="relation.one-to-many",c.MANY_TO_ONE="relation.many-to-one",c.MANY_TO_MANY="relation.many-to-many",c.POPULATE="populate",c.NO_VALIDATE="no-validate",c.MIGRATION="migration",c.STATEMENT="statement",c.QUERY="query",c.GENERATED="generated";const l=Object.assign({},a.DefaultRepositoryFlags,{allowRawStatements:!0,allowGenerationOverride:!1,squashSimpleQueries:!0,allowComplexStatements:!0});class d{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map((e=>e.observer)).indexOf(e))throw new a.InternalError("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 a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:n}=m.logCtx(a,this.updateObservers);(await Promise.allSettled(this.observers.filter((a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}})).map((a=>{a.observer.refresh(e,t,r,...n)})))).forEach(((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)}))}}class p extends a.Context{constructor(){super()}}class u extends a.InternalError{constructor(e){super(e,u.name,500)}}class h extends a.InternalError{constructor(e,t=h.name){super(e,t,500)}}class g extends h{constructor(e){super(e,g.name)}}class y extends s.LoggedClass{logFor(e,...t){return e.logger.for(this)}logCtx(e,t){return y.logCtx.call(this,e,t)}static logCtx(e,t){if(1>e.length)throw new a.InternalError("No context provided");const r=e.pop();if(!(r instanceof a.Context))throw new a.InternalError("No context provided");if(e.filter((e=>e instanceof a.Context)).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]}}}const f=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=f(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=m._currentFlavour;if(s){const e=m._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class m extends y{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!m._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return m._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("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=p,this.alias in m._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);m._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),m._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),m._currentFlavour=this.alias)}Dispatch(){return new m._baseDispatch}ObserverHandler(){return new d}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new m._baseSequence(e,this)}async flags(e,t,r,...i){let c=r.logger||s.Logging.for(this.toString());return r.correlationId&&(c=c.for({correlationId:r.correlationId})),Object.assign({},l,r,{affectedTables:(Array.isArray(t)?t:[t]).map(n.Model.tableName),writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:Array.isArray(t)?[]:o.Metadata.validationExceptions(t,e),logger:c})}async context(e,t,r,...a){this.log.for(this.context).debug(`Creating new context for ${e} operation on ${Array.isArray(r)?r.map((e=>e.name)):r.name} model with flag overrides: ${JSON.stringify(t)}`);const s=await this.flags(e,r,t,...a);return(new this.Context).accumulate(s)}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce(((e,[r,s])=>{if(void 0===s)return e;const o=n.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e}),{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[n.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...i){const{log:c,ctx:l}=this.logCtx(i,this.revert),d={},p=n.Model.pk(r);d[p]=s;const u=new r(d);c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const h=t[e.PersistenceKeys.METADATA],g=Object.keys(u).reduce(((e,a)=>(a===p||(e[a]=t[n.Model.columnName(r,a)]),e)),u);return l.get("rebuildWithTransient")&&o&&(c.verbose("re-adding transient properties: "+Object.keys(o).join(", ")),Object.entries(o).forEach((([e,t])=>{if(e in g)throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);g[e]=t}))),h&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${h}`),Object.defineProperty(g,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:h})),g}async createAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(s,this.createAll),c=n.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),Promise.all(t.map(((t,a)=>this.create(e,t,r[a],...i))))}async readAll(e,t,...r){const{log:a,ctxArgs:s}=this.logCtx(r,this.readAll),o=n.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),Promise.all(t.map((t=>this.read(e,t,...s))))}async updateAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateAll),c=n.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),Promise.all(t.map(((t,a)=>this.update(e,t,r[a],...i))))}async deleteAll(e,t,...r){const{log:a,ctxArgs:s}=m.logCtx(r,this.deleteAll);return a.verbose(`Deleting ${t.length} entries from ${e} table`),Promise.all(t.map((t=>this.delete(e,t,...s))))}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 a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=m.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(e,t,r,...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!m._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return m._currentFlavour}static get current(){return m.get(this.currentFlavour)}static get(e){if(!e)return m.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e)}catch(e){throw new a.InternalError(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} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}async migrate(e=this.migrations(),...t){e instanceof p&&(t=[e],e=this.migrations());const{ctx:r}=m.logCtx(t,this.migrate),a=await this.getQueryRunner();for(const t of e)try{const e=new t;await e.up(a,this,r),await e.down(a,this,r)}catch(e){throw new h(e)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],m.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],m.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],m.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],m.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],m.prototype,"client",null);class w extends a.InternalError{constructor(e){super(e,w.name,500)}}class b extends a.InternalError{constructor(e){super(e,b.name,500)}}var _,O,E,v,x,A;e.QueryClause=void 0,(_=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",_.SELECT="Select",_.AND="And",_.OR="Or",_.GROUP_BY="GroupBy",_.ORDER_BY="OrderBy",_.THEN="Then",_.THEN_BY="ThenBy",e.Operator=void 0,(O=e.Operator||(e.Operator={})).EQUAL="EQUAL",O.DIFFERENT="DIFFERENT",O.BIGGER="BIGGER",O.BIGGER_EQ="BIGGER_EQ",O.SMALLER="SMALLER",O.SMALLER_EQ="SMALLER_EQ",O.NOT="NOT",O.IN="IN",O.REGEXP="REGEXP",e.GroupOperator=void 0,(E=e.GroupOperator||(e.GroupOperator={})).AND="AND",E.OR="OR",e.PreparedStatementKeys=void 0,(v=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",v.FIND_BY="findBy",v.FIND_ONE_BY="findOneBy",v.PAGE_BY="paginateBy";class M extends n.Model{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):n.Model.fromModel(this,e)}and(e){return M.and(this,e)}or(e){return M.or(this,e)}not(t){return new M(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof M)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof M){if(!(this.comparison instanceof M)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return M.group(t,e.GroupOperator.AND,r)}static or(t,r){return M.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new M(e,t,r)}static attribute(e){return(new M.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(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new M(this.attr1,this.operator,this.comparison)}catch(e){throw new w(e)}}}}static builder(){return new M.Builder}static from(e){return new M(e)}}r.__decorate([n.required(),r.__metadata("design:type",Object)],M.prototype,"attr1",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],M.prototype,"operator",void 0),r.__decorate([n.required(),r.__metadata("design:type",Object)],M.prototype,"comparison",void 0),e.OrderDirection=void 0,(x=e.OrderDirection||(e.OrderDirection={})).ASC="asc",x.DSC="desc",e.Cascade=void 0,(A=e.Cascade||(e.Cascade={})).CASCADE="cascade",A.NONE="none";const C={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},P={Equals:(e,t)=>M.attribute(e).eq(t),Diff:(e,t)=>M.attribute(e).dif(t),LessThan:(e,t)=>M.attribute(e).lt(t),LessThanEqual:(e,t)=>M.attribute(e).lte(t),GreaterThan:(e,t)=>M.attribute(e).gt(t),GreaterThanEqual:(e,t)=>M.attribute(e).gte(t),Between:(e,t,r)=>M.attribute(e).gte(t).and(M.attribute(e).lte(r)),In:(e,t)=>M.attribute(e).in(t),Matches:(e,t)=>M.attribute(e).regexp(t)},D=e=>e.charAt(0).toLowerCase()+e.slice(1);class N{static build(t,...r){if(!t.startsWith(e.QueryClause.FIND_BY))throw Error("Unsupported method "+t);const a=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),o=this.buildWhere(a,r),{orderBy:i,limit:c,offset:l}=this.extractOrderLimitOffset(a,r);return{action:"find",select:s,where:o,groupBy:n,orderBy:i,limit:c,offset:l}}static extractCore(t){const r=t.substring(e.QueryClause.FIND_BY.length),a=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return a?r.substring(0,a.index):r}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map((e=>{const{field:t}=this.parseFieldAndOperator(e);return t}))}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(D).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(D).filter(Boolean)}static buildWhere(t,r){if(!t&&0===r.length)return;const a=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(a.forEach(((t,a)=>{const{field:o,operator:i}=this.parseFieldAndOperator(t),c=i?P[i]:P.Equals;if(!c)throw Error("Unsupported operator "+i);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+o);const d=c(o,l);n=0===a?d:s[a-1]===e.QueryClause.AND?n.and(d):n.or(d)})),0!==a.length){if(!n)throw Error("No conditions found in method name");return n}}static parseFieldAndOperator(e){for(const t of Object.keys(P))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:D(r),operator:t}}return{field:D(e)}}static extractOrderLimitOffset(e,t){const r=e.split(/And|Or/).length,a=t.slice(r);let s,n,o;return a.length>=1&&Array.isArray(a[0])&&(s=a[0]),2>a.length||"number"!=typeof a[1]||(n=a[1]),3>a.length||"number"!=typeof a[2]||(o=a[2]),{orderBy:s,limit:n,offset:o}}}function I(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}class T extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("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=n.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(e,t,...r){super(t),this.observers=[],e&&(this._adapter=e),t&&(T.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach((e=>{const t=e.name;a.wrapMethodWithContext(this,this[t+"Prefix"],e,this[t+"Suffix"])}))}logCtx(e,t){return m.logCtx(e,t)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new d}async createPrefix(e,...t){const r=await p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation");if(e=new this.class(e),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!n){const t=await Promise.resolve(e.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${n.Model.tableName(this.class)}`);let{record:o,id:i,transient:c}=this.adapter.prepare(e,r);return o=await this.adapter.create(this.class,i,o,...s),this.adapter.revert(o,this.class,i,c,r)}async createSuffix(e,t){return super.createSuffix(e,t)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map((e=>this.adapter.prepare(e,r))),i=o.map((e=>e.id));let c=o.map((e=>e.record));return c=await this.adapter.createAll(this.class,i,c,...s),c.map(((e,t)=>this.adapter.revert(e,this.class,i[t],r.get("rebuildWithTransient")?o[t].transient:void 0,r)))}async createAllPrefix(e,...t){const r=await p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation");if(!e.length)return[e,...r.args];const i=n.Model.sequenceFor(e[0]);let c=[];if(i.type?(i.name||(i.name=n.Model.sequenceName(e[0],"pk")),c=await(await this.adapter.Sequence(i)).range(e.length,...r.args)):c=e.map(((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("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),i.type&&(e[this.pk]="String"!==i.type||i.generated?c[t]:""+e[this.pk]),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e)))),!o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map((e=>Promise.resolve(e.hasErrors(...t))))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async readPrefix(e,...t){const r=await p.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=e,await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.READ,a.OperationKeys.ON),[e,...r.args]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${n.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const r=await p.args(a.OperationKeys.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,a.enforceDBDecorators(this,r.context,t,a.OperationKeys.READ,a.OperationKeys.ON)}))),[e,...r.args]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map(((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r)))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:i,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${n.Model.tableName(this.class)} with id ${i}`),o=await this.adapter.update(this.class,i,o,...r),this.adapter.revert(o,this.class,i,c,s)}async updatePrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation"),i=e[this.pk];if(!i)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);const c=await this.read(i,...r.args);if(e=n.Model.merge(c,e,this.class),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c),!o){const t=await Promise.resolve(e.hasErrors(c,...n.Model.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map((e=>this.adapter.prepare(e,r)));return(await this.adapter.updateAll(this.class,o.map((e=>e.id)),o.map((e=>e.record)),...s)).map(((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r)))}async updateAllPrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation"),i=e.map((e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t})),c=await this.readAll(i,...r.args);if(e=e.map(((e,t)=>n.Model.merge(c[t],e,this.class))),s||await Promise.all(e.map(((e,t)=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c[t])))),!o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map(((e,r)=>Promise.resolve(e.hasErrors(c[r],e,...t))))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async deletePrefix(e,...t){const r=await p.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.read(e,...r.args);return await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.DELETE,a.OperationKeys.ON),[e,...r.args]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${n.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const r=await p.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.readAll(e,...r.args);return await Promise.all(s.map((async e=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))),[e,...r.args]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map(((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r)))}select(e){return this.adapter.Statement().select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n,...o){const i=await p.args(e.PersistenceKeys.QUERY,this.class,o,this.adapter,this._overrides||{}),{ctx:c}=this.logCtx(i.args,this.query),l=[r,a],d=this.select().where(t).orderBy(l);return s&&d.limit(s),n&&d.offset(n),d.execute(c)}async listBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.LIST_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.listBy);return o.verbose(`listing ${n.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...i)}async paginateBy(t,r,a,...s){const o=await p.args(e.PreparedStatementKeys.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:c}=this.logCtx(o.args,this.paginateBy);return i.verbose(`paginating ${n.Model.tableName(this.class)} with page size ${a}`),this.select().orderBy([t,r]).paginate(a,...c)}async findOneBy(t,r,...s){const o=await p.args(e.PreparedStatementKeys.FIND_ONE_BY,this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:c}=this.logCtx(o.args,this.findOneBy);i.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`);const l=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...c);if(!l.length)throw new a.NotFoundError("No results found");return l[0]}async findBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.FIND_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.findBy);return o.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...i)}async statement(t,...r){if(!T.statements(this,t))throw new w("Invalid prepared statement requested "+t);const a=await p.args(e.PersistenceKeys.STATEMENT,this.class,r,this.adapter,this._overrides||{}),{log:s,ctxArgs:n}=this.logCtx(a.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...n)}attr(e){return M.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=n.Model.tableName(this.class);this.adapter.observe(this,((e,t,r,...s)=>"string"==typeof e?e===a:o.Metadata.constr(e)===o.Metadata.constr(this.class))),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map((e=>m._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,e))):m._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,r),...i)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const i=r||o.Metadata.flavourOf(t)||m.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof T)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||m.currentFlavour,l=c?m.get(c):void 0;if(!l)throw new a.InternalError("No registered persistence adapter found flavour "+c);return n=n||l.repository(),new n(l,t,...s)}static get(e,t){const r=n.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=n.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof T)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof T?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof T?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function B(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof n.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof n.Model?t.constructor.name:t.name));return n.sf(e.PersistenceKeys.INJECTABLE,r,n.Model.tableName(t))}r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"listBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Number,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"paginateBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"findOneBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"findBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],T.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],T.prototype,"unObserve",null),m&&(m._baseRepository=T);class R extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=n.Model.get(r.toString())||r:"symbol"!=typeof r&&"string"!=typeof r||(c=n.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&m.get(d)}catch{const t=m.current;t&&t.flavour===d&&(e=t.alias)}if(i=T.forModel(c,e),i instanceof T)return i;const r=d||o.Metadata.get(i.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(i,B(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=T.get(c,d);if("function"==typeof t){const e=d?m.get(d):m.current;if(!e)return;return new t(e,c)}}}return i}}async function K(e,t,r,s){if(!s){const t=n.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=T.forModel(t,r)}if(void 0===e[n.Model.pk(s.class)])return s.create(e,t);try{return s.update(e,t)}catch(r){if(!(r instanceof a.NotFoundError))throw r;return s.create(e,t)}}async function $(e,t,r,o){const i=o[r];if(!i)return;if("object"!=typeof i){const t=V(o,r,this.adapter.alias),a=await t.read(i);return await G(e,o,r,i,a),void(o[r]=i)}const c=s.isClass(t.class)?t.class:t.class();if(!c)throw new a.InternalError("Could not find model "+t.class);const l=T.forModel(c,this.adapter.alias),d=await l.create(i),p=n.Model.pk(d);await G(e,o,r,d[p],d),o[r]=d[p]}async function j(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=V(s,a,this.adapter.alias),r=await e.read(o);return await G(t,s,a,o,r),void(s[a]=o)}const i=await K(s[a],t,this.adapter.alias),c=n.Model.pk(i);await G(t,s,a,i[c],i),s[a]=i[c]}async function F(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=V(s,a,this.adapter.alias);let c;c=o instanceof n.Model?await i.delete(s[a][i.pk]):await i.delete(s[a]),await G(t,s,a,c[i.pk],c)}async function k(e,t,r,s){const o=s[r];if(!o||!o.length)return;const i=typeof o[0];if(!o.every((e=>typeof e===i)))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=new Set([...o]);if("object"!==i){const t=V(s,r,this.adapter.alias);for(const a of c){const n=await t.read(a);await G(e,s,r,a,n)}return void(s[r]=[...c])}const l=n.Model.pk(o[0]),d=new Set;for(const t of o){const a=await K(t,e,this.adapter.alias);await G(e,s,r,a[l],a),d.add(a[l])}s[r]=[...d]}async function L(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return k.call(this,t,r,a,s)}async function q(t,r,s,n){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=n[s];if(!o||!o.length)return;const i=typeof o[0];if(!o.every((e=>typeof e===i)))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="object"===i,l=c?T.forModel(o[0],this.adapter.alias):V(n,s,this.adapter.alias),d=new Set([...c?o.map((e=>e[l.pk])):o]);for(const e of d.values()){const r=await l.delete(e);await G(t,n,s,e,r)}n[s]=[...d]}function U(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function G(e,t,r,a,s){const n=U(t.constructor.name,r,a);return e.accumulate({[n]:s})}async function Y(e,t,r,s){if(!t.populate)return;const n=s[r],o=Array.isArray(n);if(void 0===n||o&&0===n.length)return;const i=await(async(e,t,r,s,n)=>{let o,i;const c=[];for(const l of s){o=U(t.constructor.name,r,l);try{i=await e.get(o)}catch(e){const s=V(t,r,n);if(!s)throw new a.InternalError("Could not find repo");i=await s.read(l)}c.push(i)}return c})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}const Q=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function V(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=o.Metadata.get(e instanceof n.Model?e.constructor:e,o.Metadata.key(n.ValidationKeys.REFLECT,t,n.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("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=o.Metadata.getPropDesignTypes(e instanceof n.Model?e.constructor:e,t)?.designTypes;const i=s?.find((e=>!Q.includes((""+e.name).toLowerCase())));return T.forModel(i,r)}class z extends a.BadRequestError{constructor(e,t=z.name,r=401){super(e,t,r)}}class H extends z{constructor(e,t=H.name){super(e,t,403)}}class W extends a.InternalError{constructor(e){super(e,W.name,503)}}function X(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r),args:[t]}).apply()}function J(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,n)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find((t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t)))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,n),{directions:t,compositions:r,name:a})(s,n)),args:[t,r,a]}).apply()}async function Z(e,t,r,s){if(s[r]&&(await this.select().where(M.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function ee(e,t,r,a){throw new z("This adapter does not support user identification")}function te(){return a.timestamp([a.OperationKeys.CREATE])}function re(){return a.timestamp()}function ae(){return(t,r)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.GENERATED,r),!0)(t,r)}function se(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],n=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),n))(r,a)}}function ne(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}o.Decoration.for(a.DBKeys.TIMESTAMP).extend(ae()).apply(),o.Decoration.for(a.DBKeys.COMPOSED).extend(ae()).apply(),o.Metadata.validationExceptions=((t,r)=>{const a=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE);return a?Object.entries(a).filter((([,e])=>e.includes(r))).map((([e])=>e)):[]}).bind(o.Metadata),n.Model.shouldValidateNestedHandler=((t,r)=>{const a=o.Metadata.get(t.constructor);if(!a)return!1;const s=a[e.PersistenceKeys.RELATIONS],i=a[e.PersistenceKeys.RELATION];if(Array.isArray(s)&&s?.includes(r)){const e=Object.keys(i)[0],a=n.Model.isPropertyModel(t,r);return i[e]?.class!==a}return!0}).bind(n.Model),o.Metadata.migrationsFor=(t=>{if(!(t=t??m.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map((e=>e.class))}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),n.Model.relations=(e,t)=>o.Metadata.relations(e instanceof n.Model?e.constructor:e,t)||[],o.Metadata.generated=((t,r)=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.PersistenceKeys.GENERATED,r))).bind(o.Metadata),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),n.Model.tableName=t=>{if(!(t instanceof n.Model?n.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof n.Model?t.constructor.name:t.name)},n.Model.columnName=(t,r)=>o.Metadata.get(t instanceof n.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,n.Model.sequenceName=(e,...t)=>[n.Model.tableName(e),...t].join("_"),n.Model.sequenceFor=(e,t)=>{if(t)throw new u("not currently supported");const r=n.Model.pkProps(e instanceof n.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},n.Model.indexes=t=>{const r=o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce(((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t)),{})},t.Injectables.services=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class oe extends y{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;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach((t=>{if(!e[t])throw new a.InternalError(`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:n,ctxArgs:o}=r.logCtx(s,e),[i,c]=s,l=await e.apply(r,o);return this.updateObservers(i,(e=>{switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}})(t),c,l,...o.slice(s.length)).then((()=>{n.verbose(`Observer refresh dispatched by ${t} for ${i}`),n.debug("pks: "+c)})).catch((e=>n.error(`Failed to dispatch observer refresh for ${t} on ${i}: ${e}`))),l}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)}))}async close(){}observe(e){if(!(e instanceof m))throw new u("Only Adapters can be observed by dispatch");this.adapter=e,this.models=m.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 u("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){const o="string"==typeof e?e:n.Model.tableName(e),{log:i,ctxArgs:c}=this.logCtx(s,this.updateObservers);if(this.adapter)try{i.debug(`Dispatching ${t} from table ${o} for ${t} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}}m&&(m._baseDispatch=oe);class ie{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 ie._instance||(ie._instance=new ie),ie._instance}}class ce{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return ce._instance||(ce._instance=new ce),ce._instance}}function le(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof g)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),n=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=s}class de extends s.LoggedClass{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach((e=>{const t=e.name;le(this,e,this.prefix(t))}))}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return m.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const e of s)if(!await e(t,r,a))return!1;return!0}prefix(e){return async function(t){let r;t instanceof m?r=this.getQueryRunner(t.client):(r=t,t=this.adapter);const a=await p.args("migration",n.Model,[e],t);if(!await this.enforceRules(r,t,a.context))throw a.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new g("Migration skipped for rule enforcement");return[r,t,a.context]}.bind(this)}}class pe extends n.Model{constructor(e){super(e)}}r.__decorate([te(),r.__metadata("design:type",Date)],pe.prototype,"createdAt",void 0),r.__decorate([re(),r.__metadata("design:type",Date)],pe.prototype,"updatedAt",void 0);const ue={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},he=ue,ge={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},ye=Object.assign({},ge,{type:"BigInt"});async function fe(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=n.Model.sequenceName(s,"pk"));try{o=await this.adapter.Sequence(t)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var i,c,l;i=s,c=r,l=await o.next(e),Reflect.set(i,c,l)}function me(t,r){return(s,i)=>{switch(o.prop()(s,i),t.type){case void 0:{const e=o.Metadata.type(s.constructor,i);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[J([e.OrderDirection.ASC,e.OrderDirection.DSC]),n.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(fe,t,r)];return t.generated&&c.push(ae()),o.apply(...c)(s,i)}}function we(e=he){return e=Object.assign({},he,e),o.Decoration.for(a.DBKeys.ID).define({decorator:me,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends pe{constructor(e){super(e)}},r.__decorate([we({type:"String",generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([n.required(),J(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([X("??sequence"),n.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class be extends y{constructor(t,r){super(),this.options=t,this.adapter=r,this.repo=T.forModel(e.SequenceModel,r.alias)}async current(...t){const r=(await p.args(a.OperationKeys.READ,e.SequenceModel,t,this.adapter)).context,{name:s,startWith:n}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){if(void 0===n)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(n)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${n}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r,s){const{type:n,incrementBy:o,name:i}=this.options;let c;const l=r||o;if(l%o!=0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);switch("function"==typeof n&&n?.name?n.name:n){case Number.name:c=this.parse(t)+l;break;case BigInt.name:c=this.parse(t)+BigInt(l);break;case String.name:c=this.parse(t);break;case"serial":c=ce.instance.generate(t);break;case"uuid":c=ie.instance.generate(t);break;default:throw new a.InternalError("Should never happen")}let d;try{d=await this.repo.update(new e.SequenceModel({id:i,current:c}),s)}catch(o){if(!(o instanceof a.NotFoundError))throw o;try{d=await this.repo.create(new e.SequenceModel({id:i,current:c}),s)}catch(e){if(!(e instanceof a.ConflictError)||"uuid"!==n)throw e;return this.increment(t,r,s)}}return d.current}async next(...t){const r=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,t,this.adapter),{context:s,args:n}=r,o=await this.current(...n);return this.increment(o,void 0,s)}async range(t,...r){const s=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,r,this.adapter),{context:n,args:o}=s,i=await this.current(...o),c=this.parse(this.options.incrementBy),l=await this.increment(i,this.parse(t)*c,n),d=[];for(let e=1;t>=e;e++)d.push(i+c*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new u(`type ${this.options.type} is currently not suppported for this adapter`);const h="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(d[d.length-1]!==l&&"String"!==h)throw new a.InternalError("Miscalculation of range");return d}parse(e){return be.parseValue(this.options.type,e)}static pk(e){return n.Model.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 u(`Unsupported sequence type: ${e} for adapter ${this}`)}}}m._baseSequence=be;class _e extends a.InternalError{constructor(e){super(e,_e.name,500)}}class Oe extends s.LoggedClass{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,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a}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 b("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new b(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}}function Ee(e){return function(t,r,s){const n=s.value;return s.value=function(...t){const r=this.class;if(r&&((e,t)=>{const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)})(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return n.apply(this,t)},s}}const ve=()=>Ee(a.OperationKeys.CREATE),xe=()=>Ee(a.OperationKeys.READ),Ae=()=>Ee(a.OperationKeys.UPDATE),Me=()=>Ee(a.OperationKeys.DELETE);function Se(r){return r="string"==typeof r?r:o.Metadata.Symbol(r).toString(),(a,s,n)=>{o.Metadata.set(e.PersistenceKeys.SERVICE,r,a);const i=[];if(n&&"number"==typeof n.value)i.push(t.inject(r));else if(n||s){if(n)throw Error("Invalid decorator usage. Should be impossible");i.push(t.inject(r))}else i.push(t.injectable(r,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return i.push(o.metadata(e.PersistenceKeys.SERVICE,r)),o.apply(...i)(a,s,n)}}class Ce{constructor(e){this.name=e,this.Context=p}async flags(e,t,...r){let a=t.logger||s.Logging.for(this.toString());return t.correlationId&&(a=a.for({correlationId:t.correlationId})),Object.assign({},l,t,{timestamp:new Date,operation:e,logger:a})}async context(e,t,...r){const a=t,s=await this.flags(e,a,...r);return(new this.Context).accumulate(s)}async logCtx(e,t,r=!1){return await Ce.logCtx.bind(this)(e,t,r)}static async logCtx(e,t,r=!1,...s){const n=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,{})}.bind(this);1>e.length&&(e=[await n()]);const o=e.pop();o instanceof p||(e=[...e,await n()]);const i=this?o.logger.for(this).for(t):o.logger.clear().for(this).for(t);return{ctx:o,log:t?i.for(t):i,ctxArgs:[...e,o]}}static get(e){if(!e)throw new a.InternalError("No name provided");const r=t.Injectables.get(e);if(r)return r;throw new a.InternalError("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 p).accumulate(Object.assign({},l,{timestamp:new Date,operation:e,logger:s.Logging.get()}))},{log:a,ctxArgs:n}=await this.logCtx.bind(r)(e,this.boot,!0),o=t.Injectables.services();for(const[e,t]of Object.entries(o))try{const e=new t;e instanceof Pe&&await e.boot(...n)}catch(t){a.error(`Failed to boot ${e} service`,t)}}}class Pe extends Ce{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=await this.logCtx(e,this.boot,!0);t.verbose(`Initializing ${this.toString()}...`);const{config:a,client:s}=await this.initialize(...r);this._config=a,this._client=s}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("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...`)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Pe.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Pe.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Pe.prototype,"client",null);const De=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ne extends Ce{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}constructor(e){super(),this.clazz=e,this.repo=T.forModel(e)}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=De(e);try{const e=Ce.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.for(e,...t):Reflect.get(r,a,s)})}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 logCtx(e,t,r=!1){return await Ne.logCtx.bind(this.repo.adapter)(e,t,r,{},this.class)}static forModel(e,t){let a;t=De(t||e);try{a=Ne.get(t)}catch(e){a=void 0}if(a instanceof Ne)return a;const s=this;let n=class extends s{constructor(){super(e)}};return n=r.__decorate([Se(t),r.__metadata("design:paramtypes",[])],n),new n}static async logCtx(e,t,r=!1,s={},n){const o=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,s,n)}.bind(this);1>e.length&&(e=[await o()]);const i=e.pop();i instanceof p||(e=[...e,await o()]);const c=this?i.logger.for(this).for(t):i.logger.clear().for(this).for(t);return{ctx:i,log:t?c.for(t):c,ctxArgs:[...e,i]}}}var Ie,Te,Be,Re;r.__decorate([ve(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"create",null),r.__decorate([ve(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"createAll",null),r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"delete",null),r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"deleteAll",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"read",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"readAll",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Ne.prototype,"query",null),r.__decorate([Ae(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"update",null),r.__decorate([Ae(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Ne.prototype,"updateAll",null);class Ke extends y{constructor(t){super(),this.adapter=t,[this.execute,this.paginate].forEach((t=>{a.prefixMethod(this,t,(async(...r)=>{let a=r;if((!a.length||!(a[a.length-1]instanceof p))&&this.fromSelector){const t=await this.adapter.context(e.PersistenceKeys.QUERY,{},this.fromSelector);a=[...a,t]}const{ctx:s,ctxArgs:n}=m.logCtx(a,t.name);return s.get("allowRawStatements")||this.prepared||await this.prepare(s),n}),t.name)}))}get log(){return this.adapter.log.for(Ke)}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?n.Model.get(e):e,!this.fromSelector)throw new w("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){const t=e.pop();try{const e=this.build();return await this.raw(e,t)}catch(e){throw new a.InternalError(e)}}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw),s=await this.adapter.raw(e,...a);if(!this.selectSelector)return s;const o=n.Model.pk(this.fromSelector),i=function(e){const t=e[o];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(s)?s.map(i):i(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:n}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=n;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(n instanceof M){const e=this.prepareCondition(n,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],n];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],n];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],n];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],n];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],n];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],n];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],n];break;default:throw new w("Unsupported operator "+s)}return o}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let r;if(this.whereCondition){if(this.whereCondition.comparison instanceof M)return;r=this.whereCondition.attr1}const a=this.orderBySelector?this.orderBySelector:r?[r,e.OrderDirection.DSC]:[n.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,i={direction:o};this.limitSelector&&(i.limit=this.limitSelector),this.offsetSelector&&(i.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:i};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=i),c}async prepare(t){if((t=t||await this.adapter.context(e.PersistenceKeys.QUERY,{},this.fromSelector)).get("squashSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},n={class:this.fromSelector,args:r,params:a},o=[e.QueryClause.FIND_BY];if(this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);o.push(e.method),e.args&&e.args.length&&r.push(...e.args)}return this.selectSelector&&o.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&o.push(e.QueryClause.ORDER_BY,...this.orderBySelector),this.groupBySelector&&o.push(e.QueryClause.GROUP_BY,this.groupBySelector),this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),n.method=s.toCamelCase(o.join(" ")),n.params=a,this.prepared=n,!t.get("squashSimpleQueries")||this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector||(this.prepared=n),this}async paginate(e,...t){t.pop();try{const t=this.build();return this.adapter.Paginator(t,e,this.fromSelector)}catch(e){throw new w(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Ke.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ie="undefined"!=typeof S&&S)?Ie:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Te="undefined"!=typeof S&&S)?Te:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Be="undefined"!=typeof S&&S)?Be:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Re="undefined"!=typeof S&&S)?Re:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[M]),r.__metadata("design:returntype",Object)],Ke.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Ke.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Ke.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Ke.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],Ke.prototype,"execute",null);class $e extends Ke{constructor(e){super(e)}getSort(){return(e,t)=>{if(!this.orderBySelector)throw new a.InternalError("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=o.Metadata.getPropDesignTypes(e.constructor,s);if(!i)throw new w("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*e[s].localeCompare(t[s]);case"number":case"Number":return("asc"===n?1:-1)*(e[s]-t[s]);case"object":case"Object":if(e[s]instanceof Date&&t[s]instanceof Date)return("asc"===n?1:-1)*(e[s].valueOf()-t[s].valueOf());throw new w("Sorting not supported for not date classes");default:throw new w("sorting not supported for type "+i)}}}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(t){return{where:r=>{const{attr1:s,operator:n,comparison:o}=t;if(-1===[e.GroupOperator.AND,e.GroupOperator.OR,e.Operator.NOT].indexOf(n))switch(n){case e.Operator.BIGGER:return r[s]>o;case e.Operator.BIGGER_EQ:return r[s]>=o;case e.Operator.DIFFERENT:return r[s]!==o;case e.Operator.EQUAL:return r[s]===o;case e.Operator.REGEXP:if("string"!=typeof r[s])throw new w("Invalid regexp comparison on a non string attribute: "+r[s]);return!!r[s].match(RegExp(o,"g"));case e.Operator.SMALLER:return r[s]<o;case e.Operator.SMALLER_EQ:return r[s]<=o;default:throw new a.InternalError("Invalid operator for standard comparisons: "+n)}else{if(n===e.Operator.NOT)throw new a.InternalError("Not implemented");{const t=this.parseCondition(s),i=this.parseCondition(o);switch(n){case e.GroupOperator.AND:return t.where(r)&&i.where(r);case e.GroupOperator.OR:return t.where(r)||i.where(r);default:throw new a.InternalError("Invalid operator for And/Or comparisons: "+n)}}}}}}}async function je(e,t,r,a){const s=e.get("UUID");if(!s)throw new u("This adapter does not support user identification");a[r]=s}const Fe="ram";class ke extends Oe{constructor(e,t,r,a){super(e,t,r,a)}prepare(e){const t=Object.assign({},e);return t.limit=this.size,t}async page(t=1,...r){const a=await p.args(e.PersistenceKeys.QUERY,this.clazz,r,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const e=await this.adapter.raw({...s,limit:void 0},a.context)||[];if(this._recordCount=e.length,this._recordCount>0){const e=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/e)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const n=await this.adapter.raw(s,...r,a.context);return this._currentPage=t,n}}class Le extends m{constructor(e={},t){super(e,Fe,t),this.indexes={},this.lock=new i.Lock}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(),a=super.prepare(e,...t,r);return delete a.record[n.Model.pk(e.constructor)],a}revert(e,t,r,a,...s){return super.revert(e,t,r,a,...s)}async create(e,t,r,s){const o=s.logger.for(this.create),i=n.Model.tableName(e);if(o.debug(`creating record in table ${i} with id ${t}`),await this.lock.acquire(),this.client.has(i)||this.client.set(i,new Map),this.client.get(i)&&this.client.get(i)?.has(t))throw new a.ConflictError(`Record with id ${t} already exists in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async read(e,t,r){const s=n.Model.tableName(e);if(!this.client.has(s))throw new a.NotFoundError(`Table ${s} not found`);if(!this.client.get(s)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${s}`);return this.client.get(s)?.get(t)}async update(e,t,r,s){const o=s.logger.for(this.update),i=n.Model.tableName(e);if(o.debug(`updating record in table ${i} with id ${t}`),await this.lock.acquire(),!this.client.has(i))throw new a.NotFoundError(`Table ${i} not found`);if(!this.client.get(i)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async delete(e,t,r){const s=r.logger.for(this.delete),o=n.Model.tableName(e);if(s.debug(`deleting record from table ${o} with pk ${t}`),await this.lock.acquire(),!this.client.has(o))throw new a.NotFoundError(`Table ${o} not found`);if(!this.client.get(o)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${o}`);const i=this.client.get(o)?.get(t);return this.client.get(o)?.delete(t),this.lock.release(),i}tableFor(e){"string"==typeof e&&(e=n.Model.get(e));const t=n.Model.tableName(e);return this.client.has(t)||this.client.set(t,new Map),this.client.get(t)}async raw(e,t){t.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(e));const{where:r,sort:s,limit:i,skip:c,from:l}=e;let{select:d}=e;const p=this.tableFor(l);if(!p)throw new a.InternalError(`Table ${l} not found in RamAdapter`);const u=n.Model.pk(l),h=o.Metadata.get(l,o.Metadata.key(a.DBKeys.ID,u));let g=Array.from(p.entries()).map((([e,r])=>this.revert(r,l,be.parseValue(h.type,e),void 0,t)));return g=r?g.filter(r):g,s&&(g=g.sort(s)),c&&(g=g.slice(c)),i&&(g=g.slice(0,i)),d&&(d=Array.isArray(d)?d:[d],g=g.map((e=>Object.entries(e).reduce(((e,[t,r])=>(d.includes(t)&&(e[t]=r),e)),{})))),g}parseError(e){return e instanceof a.BaseError?e:new a.InternalError(e)}Statement(){return new $e(this)}Paginator(e,t,r){return new ke(this,e,t,r)}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];const a=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return Reflect.get(t,r,a)}});return this.proxies[r]=a,a}static decoration(){super.decoration();const t=e.PersistenceKeys.CREATED_BY,r=e.PersistenceKeys.UPDATED_BY;o.Decoration.flavouredAs(Fe).for(t).define(a.onCreate(je),o.propMetadata(t,{})).apply(),o.Decoration.flavouredAs(Fe).for(r).define(a.onCreateUpdate(je),o.propMetadata(r,{})).apply()}getClient(){return new Map}}Le.decoration(),t.Injectables.setRegistry(new R);const qe="##VERSION##",Ue="##PACKAGE##";o.Metadata.registerLibrary(Ue,qe),e.AbsMigration=de,e.Adapter=m,e.AuthorizationError=z,e.BaseModel=pe,e.BigIntSequence=ye,e.ClientBasedService=Pe,e.Condition=M,e.ConnectionError=W,e.Context=p,e.ContextualLoggedClass=y,e.DefaultAdapterFlags=l,e.DefaultCascade=C,e.DefaultSequenceOptions=he,e.Dispatch=oe,e.ForbiddenError=H,e.InjectablesRegistry=R,e.MethodQueryBuilder=N,e.MigrationError=h,e.MigrationRuleError=g,e.ModelService=Ne,e.NoneSequenceOptions=ue,e.NumericSequence=ge,e.ObserverError=_e,e.ObserverHandler=d,e.OperatorsMap=P,e.PACKAGE_NAME=Ue,e.Paginator=Oe,e.PagingError=b,e.QueryError=w,e.RamAdapter=Le,e.RamFlavour=Fe,e.RamPaginator=ke,e.RamStatement=$e,e.Repository=T,e.Sequence=be,e.Serial=ce,e.Service=Ce,e.Statement=Ke,e.UUID=ie,e.UnsupportedError=u,e.VERSION=qe,e.cacheModelForPopulate=G,e.column=t=>o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply(),e.create=ve,e.createOrUpdate=K,e.createdAt=te,e.createdBy=()=>o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(ee),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),ae())(t,r),args:[]}).apply(),e.createdByOnCreateUpdate=ee,e.createdByOnRamCreateUpdate=je,e.del=Me,e.generateInjectableNameForRepository=B,e.generated=ae,e.getPopulateKey=U,e.index=J,e.manyToMany=(t,r=C,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),s&&(i.name=s),o.apply(o.prop(),ne(c,i),n.list([e,String,Number,BigInt]))},args:[t,r,a,s,i]}).apply()},e.manyToOne=(t,r=C,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),s&&(i.name=s),o.apply(o.prop(),ne(c,i),n.type([e,String,Number,BigInt]))},args:[t,r,a,s,i]}).apply()},e.migration=(t,r)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(t,r)=>a=>{const s=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t)||[];return o.Metadata.set(e.PersistenceKeys.MIGRATION,t,[...s,{class:a}]),o.metadata(e.PersistenceKeys.MIGRATION,{flavour:t,rules:r})(a)},args:[t,r]}).apply(),e.noValidateOn=se,e.noValidateOnCreate=()=>se(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>se(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>se(a.OperationKeys.UPDATE),e.oneToMany=(t,r=C,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};return s&&(c.joinTable=s),i&&(c.name=i),o.apply(o.prop(),ne(l,c),n.list([e,String,Number,BigInt]),a.onCreate(k,c),a.onUpdate(L,c),a.onDelete(q,c),a.afterAny(Y,c))},args:[t,r,s,i,c]}).apply()},e.oneToManyOnCreate=k,e.oneToManyOnDelete=q,e.oneToManyOnUpdate=L,e.oneToOne=(t,r=C,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};return s&&(c.joinTable=s),i&&(c.name=i),o.apply(o.prop(),ne(l,c),n.type([e,String,Number,BigInt]),a.onCreate($,c),a.onUpdate(j,c),a.onDelete(F,c),a.afterAny(Y,c))},args:[t,r,s,i,c]}).apply()},e.oneToOneOnCreate=$,e.oneToOneOnDelete=F,e.oneToOneOnUpdate=j,e.pk=we,e.pkDec=me,e.pkOnCreate=fe,e.populate=Y,e.prefixMethod=le,e.prepared=I,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const n=N.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:n}),I(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{select:s,where:n,groupBy:o,orderBy:i,limit:c,offset:l}=N.build(t.name,...a);let d=r.select(s);n&&(d=d.where(n));const{allowLimit:p,allowOffset:u,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},y=[{key:"orderBy",value:(i||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:u}];for(const e of y)if(void 0!==e.value){if(!e.allowed&&g)throw new w(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(d=d[e.key](e.value))}return d.execute()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=xe,e.relation=ne,e.repository=(r,s)=>(i,c)=>c?t.inject(o.Metadata.constr(r))(i,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||m.currentFlavour,n.Model.tableName(r)),i),o.metadata(a.DBKeys.REPOSITORY,i.name)(r),s=s||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),T.register(o.Metadata.constr(r),i,s),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(i)),e.repositoryFromTypeMetadata=V,e.service=Se,e.table=X,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(n.async(),a.onCreateUpdate(Z),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=Z,e.update=Ae,e.updatedAt=re,e.updatedBy=()=>o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(ee),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),ae())(t,r),args:[]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
1
+ var e,t;e=this,t=function(e,t,r,a,s,n,o,i){"use strict";var c;e.PersistenceKeys=void 0,(c=e.PersistenceKeys||(e.PersistenceKeys={})).INDEX="index",c.UNIQUE="unique",c.ADAPTER="adapter",c.INJECTABLE="decaf_{0}_adapter_for_{1}",c.SERVICE="service",c.TABLE="table",c.COLUMN="column",c.METADATA="__metadata",c.OWNERSHIP="ownership",c.CREATED_BY="ownership.created-by",c.UPDATED_BY="ownership.updated-by",c.RELATIONS="__relations",c.RELATION="relation",c.ONE_TO_ONE="relation.one-to-one",c.ONE_TO_MANY="relation.one-to-many",c.MANY_TO_ONE="relation.many-to-one",c.MANY_TO_MANY="relation.many-to-many",c.POPULATE="populate",c.NO_VALIDATE="no-validate",c.MIGRATION="migration",c.STATEMENT="statement",c.QUERY="query",c.GENERATED="generated";const l=Object.assign({},a.DefaultRepositoryFlags,{allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1});class d{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("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 a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:n}=m.logCtx(a,this.updateObservers);(await Promise.allSettled(this.observers.filter(a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>{a.observer.refresh(e,t,r,...n)}))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class p extends a.Context{constructor(){super()}}class u extends a.InternalError{constructor(e){super(e,u.name,500)}}class h extends a.InternalError{constructor(e,t=h.name){super(e,t,500)}}class g extends h{constructor(e){super(e,g.name)}}class y extends s.LoggedClass{logFor(e,...t){return e.logger.for(this)}logCtx(e,t){return y.logCtx.call(this,e,t)}static logCtx(e,t){if(1>e.length)throw new a.InternalError("No context provided");const r=e.pop();if(!(r instanceof a.Context))throw new a.InternalError("No context provided");if(e.filter(e=>e instanceof a.Context).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]}}}const f=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=f(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=m._currentFlavour;if(s){const e=m._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class m extends y{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!m._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return m._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("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=p,this.alias in m._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);m._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),m._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),m._currentFlavour=this.alias)}Dispatch(){return new m._baseDispatch}ObserverHandler(){return new d}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new m._baseSequence(e,this)}async flags(e,t,r,...i){let c=r.logger||s.Logging.for(this.toString());return r.correlationId&&(c=c.for({correlationId:r.correlationId})),Object.assign({},l,r,{affectedTables:(Array.isArray(t)?t:[t]).map(n.Model.tableName),writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:Array.isArray(t)?[]:o.Metadata.validationExceptions(t,e),logger:c})}async context(e,t,r,...a){this.log.for(this.context).debug(`Creating new context for ${e} operation on ${Array.isArray(r)?r.map(e=>e.name):r.name} model with flag overrides: ${JSON.stringify(t)}`);const s=await this.flags(e,r,t,...a);return(new this.Context).accumulate(s)}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const o=n.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[n.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...i){const{log:c,ctx:l}=this.logCtx(i,this.revert),d={},p=n.Model.pk(r);d[p]=s;const u=new r(d);c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const h=t[e.PersistenceKeys.METADATA],g=Object.keys(u).reduce((e,a)=>(a===p||(e[a]=t[n.Model.columnName(r,a)]),e),u);return l.get("rebuildWithTransient")&&o&&(c.verbose("re-adding transient properties: "+Object.keys(o).join(", ")),Object.entries(o).forEach(([e,t])=>{if(e in g)throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);g[e]=t})),h&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${h}`),Object.defineProperty(g,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:h})),g}async createAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(s,this.createAll),c=n.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),Promise.all(t.map((t,a)=>this.create(e,t,r[a],...i)))}async readAll(e,t,...r){const{log:a,ctxArgs:s}=this.logCtx(r,this.readAll),o=n.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),Promise.all(t.map(t=>this.read(e,t,...s)))}async updateAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateAll),c=n.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),Promise.all(t.map((t,a)=>this.update(e,t,r[a],...i)))}async deleteAll(e,t,...r){const{log:a,ctxArgs:s}=m.logCtx(r,this.deleteAll);return a.verbose(`Deleting ${t.length} entries from ${e} table`),Promise.all(t.map(t=>this.delete(e,t,...s)))}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 a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=m.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(e,t,r,...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!m._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return m._currentFlavour}static get current(){return m.get(this.currentFlavour)}static get(e){if(!e)return m.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e)}catch(e){throw new a.InternalError(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} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}async migrate(e=this.migrations(),...t){e instanceof p&&(t=[e],e=this.migrations());const{ctx:r}=m.logCtx(t,this.migrate),a=await this.getQueryRunner();for(const t of e)try{const e=new t;await e.up(a,this,r),await e.down(a,this,r)}catch(e){throw new h(e)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],m.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],m.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],m.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],m.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],m.prototype,"client",null);class w extends a.InternalError{constructor(e){super(e,w.name,500)}}class b extends a.InternalError{constructor(e){super(e,b.name,500)}}var _,O,E,v,x,A;e.QueryClause=void 0,(_=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",_.SELECT="Select",_.AND="And",_.OR="Or",_.GROUP_BY="GroupBy",_.ORDER_BY="OrderBy",_.THEN="Then",_.THEN_BY="ThenBy",e.Operator=void 0,(O=e.Operator||(e.Operator={})).EQUAL="EQUAL",O.DIFFERENT="DIFFERENT",O.BIGGER="BIGGER",O.BIGGER_EQ="BIGGER_EQ",O.SMALLER="SMALLER",O.SMALLER_EQ="SMALLER_EQ",O.NOT="NOT",O.IN="IN",O.REGEXP="REGEXP",e.GroupOperator=void 0,(E=e.GroupOperator||(e.GroupOperator={})).AND="AND",E.OR="OR",e.PreparedStatementKeys=void 0,(v=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",v.FIND_BY="findBy",v.FIND_ONE_BY="findOneBy",v.PAGE_BY="paginateBy";class M extends n.Model{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):n.Model.fromModel(this,e)}and(e){return M.and(this,e)}or(e){return M.or(this,e)}not(t){return new M(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof M)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof M){if(!(this.comparison instanceof M)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return M.group(t,e.GroupOperator.AND,r)}static or(t,r){return M.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new M(e,t,r)}static attribute(e){return(new M.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(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new M(this.attr1,this.operator,this.comparison)}catch(e){throw new w(e)}}}}static builder(){return new M.Builder}static from(e){return new M(e)}}r.__decorate([n.required(),r.__metadata("design:type",Object)],M.prototype,"attr1",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],M.prototype,"operator",void 0),r.__decorate([n.required(),r.__metadata("design:type",Object)],M.prototype,"comparison",void 0),e.OrderDirection=void 0,(x=e.OrderDirection||(e.OrderDirection={})).ASC="asc",x.DSC="desc",e.Cascade=void 0,(A=e.Cascade||(e.Cascade={})).CASCADE="cascade",A.NONE="none";const P={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},C={Equals:(e,t)=>M.attribute(e).eq(t),Diff:(e,t)=>M.attribute(e).dif(t),LessThan:(e,t)=>M.attribute(e).lt(t),LessThanEqual:(e,t)=>M.attribute(e).lte(t),GreaterThan:(e,t)=>M.attribute(e).gt(t),GreaterThanEqual:(e,t)=>M.attribute(e).gte(t),Between:(e,t,r)=>M.attribute(e).gte(t).and(M.attribute(e).lte(r)),In:(e,t)=>M.attribute(e).in(t),Matches:(e,t)=>M.attribute(e).regexp(t)},D=e=>e.charAt(0).toLowerCase()+e.slice(1);class N{static build(t,...r){if(!t.startsWith(e.QueryClause.FIND_BY))throw Error("Unsupported method "+t);const a=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),o=this.buildWhere(a,r),{orderBy:i,limit:c,offset:l}=this.extractOrderLimitOffset(a,r);return{action:"find",select:s,where:o,groupBy:n,orderBy:i,limit:c,offset:l}}static extractCore(t){const r=t.substring(e.QueryClause.FIND_BY.length),a=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return a?r.substring(0,a.index):r}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{field:t}=this.parseFieldAndOperator(e);return t})}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(D).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(D).filter(Boolean)}static buildWhere(t,r){if(!t&&0===r.length)return;const a=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(a.forEach((t,a)=>{const{field:o,operator:i}=this.parseFieldAndOperator(t),c=i?C[i]:C.Equals;if(!c)throw Error("Unsupported operator "+i);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+o);const d=c(o,l);n=0===a?d:s[a-1]===e.QueryClause.AND?n.and(d):n.or(d)}),0!==a.length){if(!n)throw Error("No conditions found in method name");return n}}static parseFieldAndOperator(e){for(const t of Object.keys(C))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:D(r),operator:t}}return{field:D(e)}}static extractOrderLimitOffset(e,t){const r=e.split(/And|Or/).length,a=t.slice(r);let s,n,o;return a.length>=1&&Array.isArray(a[0])&&(s=a[0]),2>a.length||"number"!=typeof a[1]||(n=a[1]),3>a.length||"number"!=typeof a[2]||(o=a[2]),{orderBy:s,limit:n,offset:o}}}function I(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}class T extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("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=n.Model.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},e&&(this._adapter=e),t&&(T.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(this,this[t+"Prefix"],e,this[t+"Suffix"])})}logCtx(e,t){return m.logCtx(e,t)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new d}async createPrefix(e,...t){const r=await p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),n=r.context.get("ignoreValidation");if(e=new this.class(e),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!n){const t=await Promise.resolve(e.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${n.Model.tableName(this.class)}`);let{record:o,id:i,transient:c}=this.adapter.prepare(e,r);return o=await this.adapter.create(this.class,i,o,...s),this.adapter.revert(o,this.class,i,c,r)}async createSuffix(e,t){return super.createSuffix(e,t)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r)),i=o.map(e=>e.id);let c=o.map(e=>e.record);return c=await this.adapter.createAll(this.class,i,c,...s),c.map((e,t)=>this.adapter.revert(e,this.class,i[t],r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async createAllPrefix(e,...t){const r=await p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation");if(!e.length)return[e,...r.args];const i=n.Model.sequenceFor(e[0]);let c=[];if(i.type?(i.name||(i.name=n.Model.sequenceName(e[0],"pk")),c=await(await this.adapter.Sequence(i)).range(e.length,...r.args)):c=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("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),i.type&&(e[this.pk]="String"!==i.type||i.generated?c[t]:""+e[this.pk]),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async readPrefix(e,...t){const r=await p.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=e,await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.READ,a.OperationKeys.ON),[e,...r.args]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${n.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const r=await p.args(a.OperationKeys.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,a.enforceDBDecorators(this,r.context,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...r.args]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:i,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${n.Model.tableName(this.class)} with id ${i}`),o=await this.adapter.update(this.class,i,o,...r),this.adapter.revert(o,this.class,i,c,s)}async updatePrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation"),i=e[this.pk];if(!i)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);const c=await this.read(i,...r.args);if(e=n.Model.merge(c,e,this.class),s||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c),!o){const t=await Promise.resolve(e.hasErrors(c,...n.Model.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,o.map(e=>e.id),o.map(e=>e.record),...s)).map((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async updateAllPrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation"),i=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t}),c=await this.readAll(i,...r.args);if(e=e.map((e,t)=>n.Model.merge(c[t],e,this.class)),s||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c[t]))),!o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(c[r],e,...t)))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async deletePrefix(e,...t){const r=await p.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.read(e,...r.args);return await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.DELETE,a.OperationKeys.ON),[e,...r.args]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${n.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const r=await p.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.readAll(e,...r.args);return await Promise.all(s.map(async e=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.DELETE,a.OperationKeys.ON))),[e,...r.args]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n,...o){const i=await p.args(e.PersistenceKeys.QUERY,this.class,o,this.adapter,this._overrides||{}),{ctx:c}=this.logCtx(i.args,this.query),l=[r,a],d=this.select().where(t).orderBy(l);return s&&d.limit(s),n&&d.offset(n),d.execute(c)}async listBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.LIST_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.listBy);return o.verbose(`listing ${n.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...i)}async paginateBy(t,r,a,...s){const o=await p.args(e.PreparedStatementKeys.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:c}=this.logCtx(o.args,this.paginateBy);return i.verbose(`paginating ${n.Model.tableName(this.class)} with page size ${a}`),this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(a,...c)}async findOneBy(t,r,...s){const o=await p.args(e.PreparedStatementKeys.FIND_ONE_BY,this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:c}=this.logCtx(o.args,this.findOneBy);i.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`);const l=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...c);if(!l.length)throw new a.NotFoundError("No results found");return l[0]}async findBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.FIND_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.findBy);return o.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...i)}async statement(t,...r){if(!T.statements(this,t))throw new w("Invalid prepared statement requested "+t);const a=await p.args(e.PersistenceKeys.STATEMENT,this.class,r,this.adapter,this._overrides||{}),{log:s,ctxArgs:n}=this.logCtx(a.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...n)}attr(e){return M.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=n.Model.tableName(this.class);this.adapter.observe(this,(e,t,r,...s)=>"string"==typeof e?e===a:o.Metadata.constr(e)===o.Metadata.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>m._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,e)):m._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,r),...i)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const i=r||o.Metadata.flavourOf(t)||m.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof T)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||m.currentFlavour,l=c?m.get(c):void 0;if(!l)throw new a.InternalError("No registered persistence adapter found flavour "+c);return n=n||l.repository(),new n(l,t,...s)}static get(e,t){const r=n.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=n.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof T)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof T?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof T?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function B(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof n.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof n.Model?t.constructor.name:t.name));return n.sf(e.PersistenceKeys.INJECTABLE,r,n.Model.tableName(t))}r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"listBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Number,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"paginateBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"findOneBy",null),r.__decorate([I(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],T.prototype,"findBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],T.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],T.prototype,"unObserve",null),m&&(m._baseRepository=T);class R extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=n.Model.get(r.toString())||r:"symbol"!=typeof r&&"string"!=typeof r||(c=n.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&m.get(d)}catch{const t=m.current;t&&t.flavour===d&&(e=t.alias)}if(i=T.forModel(c,e),i instanceof T)return i;const r=d||o.Metadata.get(i.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(i,B(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=T.get(c,d);if("function"==typeof t){const e=d?m.get(d):m.current;if(!e)return;return new t(e,c)}}}return i}}async function K(e,t,r,s){if(!s){const t=n.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=T.forModel(t,r)}if(void 0===e[n.Model.pk(s.class)])return s.create(e,t);try{return s.update(e,t)}catch(r){if(!(r instanceof a.NotFoundError))throw r;return s.create(e,t)}}async function $(e,t,r,o){const i=o[r];if(!i)return;if("object"!=typeof i){const t=z(o,r,this.adapter.alias),a=await t.read(i);return await G(e,o,r,i,a),void(o[r]=i)}const c=s.isClass(t.class)?t.class:t.class();if(!c)throw new a.InternalError("Could not find model "+t.class);const l=T.forModel(c,this.adapter.alias),d=await l.create(i),p=n.Model.pk(d);await G(e,o,r,d[p],d),o[r]=d[p]}async function j(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=z(s,a,this.adapter.alias),r=await e.read(o);return await G(t,s,a,o,r),void(s[a]=o)}const i=await K(s[a],t,this.adapter.alias),c=n.Model.pk(i);await G(t,s,a,i[c],i),s[a]=i[c]}async function F(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=z(s,a,this.adapter.alias);let c;c=o instanceof n.Model?await i.delete(s[a][i.pk]):await i.delete(s[a]),await G(t,s,a,c[i.pk],c)}async function k(e,t,r,s){const o=s[r];if(!o||!o.length)return;const i=typeof o[0];if(!o.every(e=>typeof e===i))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=new Set([...o]);if("object"!==i){const t=z(s,r,this.adapter.alias);for(const a of c){const n=await t.read(a);await G(e,s,r,a,n)}return void(s[r]=[...c])}const l=n.Model.pk(o[0]),d=new Set;for(const t of o){const a=await K(t,e,this.adapter.alias);await G(e,s,r,a[l],a),d.add(a[l])}s[r]=[...d]}async function L(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return k.call(this,t,r,a,s)}async function q(t,r,s,n){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=n[s];if(!o||!o.length)return;const i=typeof o[0];if(!o.every(e=>typeof e===i))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="object"===i,l=c?T.forModel(o[0],this.adapter.alias):z(n,s,this.adapter.alias),d=new Set([...c?o.map(e=>e[l.pk]):o]);for(const e of d.values()){const r=await l.delete(e);await G(t,n,s,e,r)}n[s]=[...d]}function U(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function G(e,t,r,a,s){const n=U(t.constructor.name,r,a);return e.accumulate({[n]:s})}async function Q(e,t,r,s){if(!t.populate)return;const n=s[r],o=Array.isArray(n);if(void 0===n||o&&0===n.length)return;const i=await(async(e,t,r,s,n)=>{let o,i;const c=[];for(const l of s){o=U(t.constructor.name,r,l);try{i=await e.get(o)}catch(e){const s=z(t,r,n);if(!s)throw new a.InternalError("Could not find repo");i=await s.read(l)}c.push(i)}return c})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}const Y=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function z(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=o.Metadata.get(e instanceof n.Model?e.constructor:e,o.Metadata.key(n.ValidationKeys.REFLECT,t,n.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("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=o.Metadata.getPropDesignTypes(e instanceof n.Model?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!Y.includes((""+e.name).toLowerCase()));return T.forModel(i,r)}class V extends a.BadRequestError{constructor(e,t=V.name,r=401){super(e,t,r)}}class H extends V{constructor(e,t=H.name){super(e,t,403)}}class W extends a.InternalError{constructor(e){super(e,W.name,503)}}function X(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r),args:[t]}).apply()}function J(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,n)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,n),{directions:t,compositions:r,name:a})(s,n)),args:[t,r,a]}).apply()}async function Z(e,t,r,s){if(s[r]&&(await this.select().where(M.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function ee(e,t,r,a){throw new V("This adapter does not support user identification")}function te(){return a.timestamp([a.OperationKeys.CREATE])}function re(){return a.timestamp()}function ae(){return(t,r)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.GENERATED,r),!0)(t,r)}function se(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],n=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),n))(r,a)}}function ne(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}o.Decoration.for(a.DBKeys.TIMESTAMP).extend(ae()).apply(),o.Decoration.for(a.DBKeys.COMPOSED).extend(ae()).apply(),o.Metadata.validationExceptions=((t,r)=>{const a=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE);return a?Object.entries(a).filter(([,e])=>e.includes(r)).map(([e])=>e):[]}).bind(o.Metadata),n.Model.shouldValidateNestedHandler=((t,r)=>{const a=o.Metadata.get(t.constructor);if(!a)return!1;const s=a[e.PersistenceKeys.RELATIONS],i=a[e.PersistenceKeys.RELATION];if(Array.isArray(s)&&s?.includes(r)){const e=Object.keys(i)[0],a=n.Model.isPropertyModel(t,r);return i[e]?.class!==a}return!0}).bind(n.Model),o.Metadata.migrationsFor=(t=>{if(!(t=t??m.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),n.Model.relations=(e,t)=>o.Metadata.relations(e instanceof n.Model?e.constructor:e,t)||[],o.Metadata.generated=((t,r)=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.PersistenceKeys.GENERATED,r))).bind(o.Metadata),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),n.Model.tableName=t=>{if(!(t instanceof n.Model?n.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof n.Model?t.constructor.name:t.name)},n.Model.columnName=(t,r)=>o.Metadata.get(t instanceof n.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,n.Model.sequenceName=(e,...t)=>[n.Model.tableName(e),...t].join("_"),n.Model.sequenceFor=(e,t)=>{if(t)throw new u("not currently supported");const r=n.Model.pkProps(e instanceof n.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},n.Model.indexes=t=>{const r=o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})},t.Injectables.services=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class oe extends y{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;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(t=>{if(!e[t])throw new a.InternalError(`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:n,ctxArgs:o}=r.logCtx(s,e),[i,c]=s,l=await e.apply(r,o);return this.updateObservers(i,(e=>{switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}})(t),c,l,...o.slice(s.length)).then(()=>{n.verbose(`Observer refresh dispatched by ${t} for ${i}`),n.debug("pks: "+c)}).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${i}: ${e}`)),l}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof m))throw new u("Only Adapters can be observed by dispatch");this.adapter=e,this.models=m.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 u("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){const o="string"==typeof e?e:n.Model.tableName(e),{log:i,ctxArgs:c}=this.logCtx(s,this.updateObservers);if(this.adapter)try{i.debug(`Dispatching ${t} from table ${o} for ${t} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}}m&&(m._baseDispatch=oe);class ie{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 ie._instance||(ie._instance=new ie),ie._instance}}class ce{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return ce._instance||(ce._instance=new ce),ce._instance}}function le(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof g)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),n=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=s}class de extends s.LoggedClass{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;le(this,e,this.prefix(t))})}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return m.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const e of s)if(!await e(t,r,a))return!1;return!0}prefix(e){return async function(t){let r;t instanceof m?r=this.getQueryRunner(t.client):(r=t,t=this.adapter);const a=await p.args("migration",n.Model,[e],t);if(!await this.enforceRules(r,t,a.context))throw a.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new g("Migration skipped for rule enforcement");return[r,t,a.context]}.bind(this)}}class pe extends n.Model{constructor(e){super(e)}}r.__decorate([te(),r.__metadata("design:type",Date)],pe.prototype,"createdAt",void 0),r.__decorate([re(),r.__metadata("design:type",Date)],pe.prototype,"updatedAt",void 0);const ue={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},he=ue,ge={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},ye=Object.assign({},ge,{type:"BigInt"});async function fe(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=n.Model.sequenceName(s,"pk"));try{o=await this.adapter.Sequence(t)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var i,c,l;i=s,c=r,l=await o.next(e),Reflect.set(i,c,l)}function me(t,r){return(s,i)=>{switch(o.prop()(s,i),t.type){case void 0:{const e=o.Metadata.type(s.constructor,i);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[J([e.OrderDirection.ASC,e.OrderDirection.DSC]),n.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(fe,t,r)];return t.generated&&c.push(ae()),o.apply(...c)(s,i)}}function we(e=he){return e=Object.assign({},he,e),o.Decoration.for(a.DBKeys.ID).define({decorator:me,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends pe{constructor(e){super(e)}},r.__decorate([we({type:"String",generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([n.required(),J(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([X("??sequence"),n.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class be extends y{constructor(t,r){super(),this.options=t,this.adapter=r,this.repo=T.forModel(e.SequenceModel,r.alias)}async current(...t){const r=(await p.args(a.OperationKeys.READ,e.SequenceModel,t,this.adapter)).context,{name:s,startWith:n}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){if(void 0===n)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(n)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${n}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r,s){const{type:n,incrementBy:o,name:i}=this.options;let c;const l=r||o;if(l%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);switch("function"==typeof n&&n?.name?n.name:n){case Number.name:c=this.parse(t)+l;break;case BigInt.name:c=this.parse(t)+BigInt(l);break;case String.name:c=this.parse(t);break;case"serial":c=ce.instance.generate(t);break;case"uuid":c=ie.instance.generate(t);break;default:throw new a.InternalError("Should never happen")}let d;try{d=await this.repo.update(new e.SequenceModel({id:i,current:c}),s)}catch(o){if(!(o instanceof a.NotFoundError))throw o;try{d=await this.repo.create(new e.SequenceModel({id:i,current:c}),s)}catch(e){if(!(e instanceof a.ConflictError)||"uuid"!==n)throw e;return this.increment(t,r,s)}}return d.current}async next(...t){const r=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,t,this.adapter),{context:s,args:n}=r,o=await this.current(...n);return this.increment(o,void 0,s)}async range(t,...r){const s=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,r,this.adapter),{context:n,args:o}=s,i=await this.current(...o),c=this.parse(this.options.incrementBy),l=await this.increment(i,this.parse(t)*c,n),d=[];for(let e=1;t>=e;e++)d.push(i+c*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new u(`type ${this.options.type} is currently not suppported for this adapter`);const h="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(d[d.length-1]!==l&&"String"!==h)throw new a.InternalError("Miscalculation of range");return d}parse(e){return be.parseValue(this.options.type,e)}static pk(e){return n.Model.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 u(`Unsupported sequence type: ${e} for adapter ${this}`)}}}m._baseSequence=be;class _e extends a.InternalError{constructor(e){super(e,_e.name,500)}}class Oe extends s.LoggedClass{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,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,le(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi"))}async pagePrefix(t,...r){return[t,...(await p.args(e.PersistenceKeys.QUERY,this.clazz,r,this.adapter)).args]}pagePrepared(t,...r){const a=T.forModel(this.clazz,this.adapter.alias),s=this.query,{method:n,args:o,params:i}=s,c=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!n.match(c))throw new u(`Method ${n} is not supported for pagination`);c.lastIndex=0;const l=n.replace(c,e.PreparedStatementKeys.PAGE_BY);return a.statement(l,...o,t,Object.assign({},i,{limit:this.size}),...r)}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 b("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new b(`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 this.pagePrepared(e,...r);throw new u("Raw support not available without subclassing this")}}function Ee(e){return function(t,r,s){const n=s.value;return s.value=function(...t){const r=this.class;if(r&&((e,t)=>{const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)})(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return n.apply(this,t)},s}}const ve=()=>Ee(a.OperationKeys.CREATE),xe=()=>Ee(a.OperationKeys.READ),Ae=()=>Ee(a.OperationKeys.UPDATE),Me=()=>Ee(a.OperationKeys.DELETE);function Se(r){return r="string"==typeof r?r:o.Metadata.Symbol(r).toString(),(a,s,n)=>{o.Metadata.set(e.PersistenceKeys.SERVICE,r,a);const i=[];if(n&&"number"==typeof n.value)i.push(t.inject(r));else if(n||s){if(n)throw Error("Invalid decorator usage. Should be impossible");i.push(t.inject(r))}else i.push(t.injectable(r,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return i.push(o.metadata(e.PersistenceKeys.SERVICE,r)),o.apply(...i)(a,s,n)}}class Pe{constructor(e){this.name=e,this.Context=p}async flags(e,t,...r){let a=t.logger||s.Logging.for(this.toString());return t.correlationId&&(a=a.for({correlationId:t.correlationId})),Object.assign({},l,t,{timestamp:new Date,operation:e,logger:a})}async context(e,t,...r){const a=t,s=await this.flags(e,a,...r);return(new this.Context).accumulate(s)}async logCtx(e,t,r=!1){return await Pe.logCtx.bind(this)(e,t,r)}static async logCtx(e,t,r=!1,...s){const n=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,{})}.bind(this);1>e.length&&(e=[await n()]);const o=e.pop();o instanceof p||(e=[...e,await n()]);const i=this?o.logger.for(this).for(t):o.logger.clear().for(this).for(t);return{ctx:o,log:t?i.for(t):i,ctxArgs:[...e,o]}}static get(e){if(!e)throw new a.InternalError("No name provided");const r=t.Injectables.get(e);if(r)return r;throw new a.InternalError("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 p).accumulate(Object.assign({},l,{timestamp:new Date,operation:e,logger:s.Logging.get()}))},{log:a,ctxArgs:n}=await this.logCtx.bind(r)(e,this.boot,!0),o=t.Injectables.services();for(const[e,t]of Object.entries(o))try{const e=new t;e instanceof Ce&&await e.boot(...n)}catch(t){a.error(`Failed to boot ${e} service`,t)}}}class Ce extends Pe{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=await this.logCtx(e,this.boot,!0);t.verbose(`Initializing ${this.toString()}...`);const{config:a,client:s}=await this.initialize(...r);this._config=a,this._client=s}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("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...`)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Ce.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Ce.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Ce.prototype,"client",null);const De=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ne extends Pe{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}constructor(e){super(),this.clazz=e,this.repo=T.forModel(e)}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=De(e);try{const e=Pe.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.for(e,...t):Reflect.get(r,a,s)})}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 logCtx(e,t,r=!1){return await Ne.logCtx.bind(this.repo.adapter)(e,t,r,{},this.class)}static forModel(e,t){let a;t=De(t||e);try{a=Ne.get(t)}catch(e){a=void 0}if(a instanceof Ne)return a;const s=this;let n=class extends s{constructor(){super(e)}};return n=r.__decorate([Se(t),r.__metadata("design:paramtypes",[])],n),new n}static async logCtx(e,t,r=!1,s={},n){const o=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,s,n)}.bind(this);1>e.length&&(e=[await o()]);const i=e.pop();i instanceof p||(e=[...e,await o()]);const c=this?i.logger.for(this).for(t):i.logger.clear().for(this).for(t);return{ctx:i,log:t?c.for(t):c,ctxArgs:[...e,i]}}}var Ie,Te,Be,Re;r.__decorate([ve(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"create",null),r.__decorate([ve(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"createAll",null),r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"delete",null),r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"deleteAll",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"read",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"readAll",null),r.__decorate([xe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Ne.prototype,"query",null),r.__decorate([Ae(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ne.prototype,"update",null),r.__decorate([Ae(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Ne.prototype,"updateAll",null);class Ke extends y{constructor(t,r){super(),this.adapter=t,this.overrides=r,[this.execute,this.paginate].forEach(t=>{a.prefixMethod(this,t,async(...r)=>{let a=r;if((!a.length||!(a[a.length-1]instanceof p))&&this.fromSelector){const t=await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector);a=[...a,t]}const{ctx:s,ctxArgs:n}=m.logCtx(a,t.name),o=s.get("forcePrepareSimpleQueries"),i=s.get("forcePrepareComplexQueries");return(o&&this.isSimpleQuery()||i)&&await this.prepare(s),n},t.name)})}get log(){return this.adapter.log.for(Ke)}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?n.Model.get(e):e,!this.fromSelector)throw new w("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 w(e)}}async executePrepared(...e){const t=T.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new u("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(!this.selectSelector)return s;const o=n.Model.pk(this.fromSelector),i=function(e){const t=e[o];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(s)?s.map(i):i(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:n}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=n;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(n instanceof M){const e=this.prepareCondition(n,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],n];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],n];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],n];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],n];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],n];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],n];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],n];break;default:throw new w("Unsupported operator "+s)}return o}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let r;if(this.whereCondition){if(this.whereCondition.comparison instanceof M)return;r=this.whereCondition.attr1}const a=this.orderBySelector?this.orderBySelector:r?[r,e.OrderDirection.DSC]:[n.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,i={direction:o};this.limitSelector&&(i.limit=this.limitSelector),this.offsetSelector&&(i.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:i};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=i),c}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},n={class:this.fromSelector,args:r,params:a},o=[e.QueryClause.FIND_BY];if(this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);o.push(e.method),e.args&&e.args.length&&r.push(...e.args)}return this.selectSelector&&o.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&(o.push(e.QueryClause.ORDER_BY,this.orderBySelector[0]),a.direction=this.orderBySelector[1]),this.groupBySelector&&o.push(e.QueryClause.GROUP_BY,this.groupBySelector),this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),n.method=s.toCamelCase(o.join(" ")),n.params=a,this.prepared=n,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 w(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Ke.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ie="undefined"!=typeof S&&S)?Ie:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Te="undefined"!=typeof S&&S)?Te:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Be="undefined"!=typeof S&&S)?Be:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Re="undefined"!=typeof S&&S)?Re:Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[M]),r.__metadata("design:returntype",Object)],Ke.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Ke.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Ke.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Ke.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Ke.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],Ke.prototype,"execute",null);class $e extends Ke{constructor(e,t){super(e,t)}getSort(){return(e,t)=>{if(!this.orderBySelector)throw new a.InternalError("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=o.Metadata.getPropDesignTypes(e.constructor,s);if(!i)throw new w("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*e[s].localeCompare(t[s]);case"number":case"Number":return("asc"===n?1:-1)*(e[s]-t[s]);case"object":case"Object":if(e[s]instanceof Date&&t[s]instanceof Date)return("asc"===n?1:-1)*(e[s].valueOf()-t[s].valueOf());throw new w("Sorting not supported for not date classes");default:throw new w("sorting not supported for type "+i)}}}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(t){return{where:r=>{const{attr1:s,operator:n,comparison:o}=t;if(-1===[e.GroupOperator.AND,e.GroupOperator.OR,e.Operator.NOT].indexOf(n))switch(n){case e.Operator.BIGGER:return r[s]>o;case e.Operator.BIGGER_EQ:return r[s]>=o;case e.Operator.DIFFERENT:return r[s]!==o;case e.Operator.EQUAL:return r[s]===o;case e.Operator.REGEXP:if("string"!=typeof r[s])throw new w("Invalid regexp comparison on a non string attribute: "+r[s]);return!!r[s].match(RegExp(o,"g"));case e.Operator.SMALLER:return r[s]<o;case e.Operator.SMALLER_EQ:return r[s]<=o;default:throw new a.InternalError("Invalid operator for standard comparisons: "+n)}else{if(n===e.Operator.NOT)throw new a.InternalError("Not implemented");{const t=this.parseCondition(s),i=this.parseCondition(o);switch(n){case e.GroupOperator.AND:return t.where(r)&&i.where(r);case e.GroupOperator.OR:return t.where(r)||i.where(r);default:throw new a.InternalError("Invalid operator for And/Or comparisons: "+n)}}}}}}}async function je(e,t,r,a){const s=e.get("UUID");if(!s)throw new u("This adapter does not support user identification");a[r]=s}const Fe="ram";class ke extends Oe{constructor(e,t,r,a){super(e,t,r,a)}prepare(e){const t=Object.assign({},e);return t.limit=this.size,t}async page(e=1,...t){const{ctx:r,ctxArgs:a}=this.adapter.logCtx(t,this.page);if(this.isPreparedStatement())return this.pagePrepared(e,...a);const s=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)e=this.validatePage(e),s.skip=(e-1)*this.size,n=await this.adapter.raw(s,!0,...t,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...s,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const e=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/e)}return this._currentPage=e,n.data||n}}class Le extends m{constructor(e={},t){super(e,Fe,t),this.indexes={},this.lock=new i.Lock}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(),a=super.prepare(e,...t,r);return delete a.record[n.Model.pk(e.constructor)],a}revert(e,t,r,a,...s){return super.revert(e,t,r,a,...s)}async create(e,t,r,s){const o=s.logger.for(this.create),i=n.Model.tableName(e);if(o.debug(`creating record in table ${i} with id ${t}`),await this.lock.acquire(),this.client.has(i)||this.client.set(i,new Map),this.client.get(i)&&this.client.get(i)?.has(t))throw new a.ConflictError(`Record with id ${t} already exists in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async read(e,t,r){const s=n.Model.tableName(e);if(!this.client.has(s))throw new a.NotFoundError(`Table ${s} not found`);if(!this.client.get(s)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${s}`);return this.client.get(s)?.get(t)}async update(e,t,r,s){const o=s.logger.for(this.update),i=n.Model.tableName(e);if(o.debug(`updating record in table ${i} with id ${t}`),await this.lock.acquire(),!this.client.has(i))throw new a.NotFoundError(`Table ${i} not found`);if(!this.client.get(i)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async delete(e,t,r){const s=r.logger.for(this.delete),o=n.Model.tableName(e);if(s.debug(`deleting record from table ${o} with pk ${t}`),await this.lock.acquire(),!this.client.has(o))throw new a.NotFoundError(`Table ${o} not found`);if(!this.client.get(o)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${o}`);const i=this.client.get(o)?.get(t);return this.client.get(o)?.delete(t),this.lock.release(),i}tableFor(e){"string"==typeof e&&(e=n.Model.get(e));const t=n.Model.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:c,skip:l,from:d}=e;let{select:p}=e;const u=this.tableFor(d);if(!u)throw new a.InternalError(`Table ${d} not found in RamAdapter`);const h=n.Model.pk(d),g=o.Metadata.get(d,o.Metadata.key(a.DBKeys.ID,h));let y=Array.from(u.entries()).map(([e,t])=>this.revert(t,d,be.parseValue(g.type,e),void 0,r));y=s?y.filter(s):y;const f=y.length;return i&&(y=y.sort(i)),l&&(y=y.slice(l)),c&&(y=y.slice(0,c)),p&&(p=Array.isArray(p)?p:[p],y=y.map(e=>Object.entries(e).reduce((e,[t,r])=>(p.includes(t)&&(e[t]=r),e),{}))),t?y:{data:y,count:f}}parseError(e){return e instanceof a.BaseError?e:new a.InternalError(e)}Statement(e){return new $e(this,e)}Paginator(e,t,r){return new ke(this,e,t,r)}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];const a=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return Reflect.get(t,r,a)}});return this.proxies[r]=a,a}static decoration(){super.decoration();const t=e.PersistenceKeys.CREATED_BY,r=e.PersistenceKeys.UPDATED_BY;o.Decoration.flavouredAs(Fe).for(t).define(a.onCreate(je),o.propMetadata(t,{})).apply(),o.Decoration.flavouredAs(Fe).for(r).define(a.onCreateUpdate(je),o.propMetadata(r,{})).apply()}getClient(){return new Map}}Le.decoration(),t.Injectables.setRegistry(new R);const qe="##VERSION##",Ue="##PACKAGE##";o.Metadata.registerLibrary(Ue,qe),e.AbsMigration=de,e.Adapter=m,e.AuthorizationError=V,e.BaseModel=pe,e.BigIntSequence=ye,e.ClientBasedService=Ce,e.Condition=M,e.ConnectionError=W,e.Context=p,e.ContextualLoggedClass=y,e.DefaultAdapterFlags=l,e.DefaultCascade=P,e.DefaultSequenceOptions=he,e.Dispatch=oe,e.ForbiddenError=H,e.InjectablesRegistry=R,e.MethodQueryBuilder=N,e.MigrationError=h,e.MigrationRuleError=g,e.ModelService=Ne,e.NoneSequenceOptions=ue,e.NumericSequence=ge,e.ObserverError=_e,e.ObserverHandler=d,e.OperatorsMap=C,e.PACKAGE_NAME=Ue,e.Paginator=Oe,e.PagingError=b,e.QueryError=w,e.RamAdapter=Le,e.RamFlavour=Fe,e.RamPaginator=ke,e.RamStatement=$e,e.Repository=T,e.Sequence=be,e.Serial=ce,e.Service=Pe,e.Statement=Ke,e.UUID=ie,e.UnsupportedError=u,e.VERSION=qe,e.cacheModelForPopulate=G,e.column=t=>o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply(),e.create=ve,e.createOrUpdate=K,e.createdAt=te,e.createdBy=()=>o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(ee),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),ae())(t,r),args:[]}).apply(),e.createdByOnCreateUpdate=ee,e.createdByOnRamCreateUpdate=je,e.del=Me,e.generateInjectableNameForRepository=B,e.generated=ae,e.getPopulateKey=U,e.index=J,e.manyToMany=(t,r=P,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),s&&(i.name=s),o.apply(o.prop(),ne(c,i),n.list([e,String,Number,BigInt]))},args:[t,r,a,s,i]}).apply()},e.manyToOne=(t,r=P,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),s&&(i.name=s),o.apply(o.prop(),ne(c,i),n.type([e,String,Number,BigInt]))},args:[t,r,a,s,i]}).apply()},e.migration=(t,r)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(t,r)=>a=>{const s=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t)||[];return o.Metadata.set(e.PersistenceKeys.MIGRATION,t,[...s,{class:a}]),o.metadata(e.PersistenceKeys.MIGRATION,{flavour:t,rules:r})(a)},args:[t,r]}).apply(),e.noValidateOn=se,e.noValidateOnCreate=()=>se(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>se(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>se(a.OperationKeys.UPDATE),e.oneToMany=(t,r=P,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};return s&&(c.joinTable=s),i&&(c.name=i),o.apply(o.prop(),ne(l,c),n.list([e,String,Number,BigInt]),a.onCreate(k,c),a.onUpdate(L,c),a.onDelete(q,c),a.afterAny(Q,c))},args:[t,r,s,i,c]}).apply()},e.oneToManyOnCreate=k,e.oneToManyOnDelete=q,e.oneToManyOnUpdate=L,e.oneToOne=(t,r=P,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};return s&&(c.joinTable=s),i&&(c.name=i),o.apply(o.prop(),ne(l,c),n.type([e,String,Number,BigInt]),a.onCreate($,c),a.onUpdate(j,c),a.onDelete(F,c),a.afterAny(Q,c))},args:[t,r,s,i,c]}).apply()},e.oneToOneOnCreate=$,e.oneToOneOnDelete=F,e.oneToOneOnUpdate=j,e.pk=we,e.pkDec=me,e.pkOnCreate=fe,e.populate=Q,e.prefixMethod=le,e.prepared=I,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const n=N.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:n}),I(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{select:s,where:n,groupBy:o,orderBy:i,limit:c,offset:l}=N.build(t.name,...a);let d=r.select(s);n&&(d=d.where(n));const{allowLimit:p,allowOffset:u,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},y=[{key:"orderBy",value:(i||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:u}];for(const e of y)if(void 0!==e.value){if(!e.allowed&&g)throw new w(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(d=d[e.key](e.value))}return d.execute()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=xe,e.relation=ne,e.repository=(r,s)=>(i,c)=>c?t.inject(o.Metadata.constr(r))(i,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||m.currentFlavour,n.Model.tableName(r)),i),o.metadata(a.DBKeys.REPOSITORY,i.name)(r),s=s||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),T.register(o.Metadata.constr(r),i,s),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(i)),e.repositoryFromTypeMetadata=z,e.service=Se,e.table=X,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(n.async(),a.onCreateUpdate(Z),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=Z,e.update=Ae,e.updatedAt=re,e.updatedBy=()=>o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(ee),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),ae())(t,r),args:[]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
2
2
  //# sourceMappingURL=core.cjs.map