@decaf-ts/core 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as e,Injectables as t,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,InternalError as l,Context as u,ValidationError as d,Repository as p,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as b,DBKeys as w,generated as v,onCreate as A,onUpdate as x,readonly as E,BadRequestError as O,ConflictError as C,onCreateUpdate as N,timestamp as T,onDelete as _,afterUpdate as P,afterAny as B,SerializationError as $,prefixMethod as D}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as I,final as L,toCamelCase as k}from"@decaf-ts/logging";import{Model as F,hashObj as j,required as U,sf as Y,isEqual as M,ValidationKeys as q,async as G,type as z,list as H,model as Q}from"@decaf-ts/decorator-validation";import{Lock as V,MultiLock as W}from"@decaf-ts/transactional-decorators";import{Metadata as J,Decoration as X,DefaultFlavour as Z,apply as K,methodMetadata as ee,DecorationKeys as te,uses as re,metadata as se,propMetadata as ie,prop as ne}from"@decaf-ts/decoration";var oe,ae,ce,le,ue;(e=>{e.FIND_BY="findBy",e.SELECT="Select",e.AND="And",e.OR="Or",e.GROUP_BY="GroupBy",e.ORDER_BY="OrderBy",e.THEN="Then",e.THEN_BY="ThenBy"})(oe||(oe={})),(e=>{e.EQUAL="EQUAL",e.DIFFERENT="DIFFERENT",e.BIGGER="BIGGER",e.BIGGER_EQ="BIGGER_EQ",e.SMALLER="SMALLER",e.SMALLER_EQ="SMALLER_EQ",e.NOT="NOT",e.IN="IN",e.REGEXP="REGEXP"})(ae||(ae={})),(e=>{e.AND="AND",e.OR="OR"})(ce||(ce={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(le||(le={})),(e=>{e.PERSISTENCE="persistence",e.INDEX="index",e.UNIQUE="unique",e.ADAPTER="adapter",e.INJECTABLE="decaf_{0}_adapter_for_{1}",e.SERVICE="service",e.TABLE="table",e.COLUMN="column",e.METADATA="__metadata",e.OWNERSHIP="ownership",e.CREATED_BY="ownership.created-by",e.UPDATED_BY="ownership.updated-by",e.RELATIONS="__relations",e.RELATION="relation",e.ONE_TO_ONE="relation.one-to-one",e.ONE_TO_MANY="relation.one-to-many",e.MANY_TO_ONE="relation.many-to-one",e.MANY_TO_MANY="relation.many-to-many",e.POPULATE="populate",e.NO_VALIDATE="no-validate",e.MIGRATION="migration",e.STATEMENT="statement",e.QUERY="query",e.UUID="uuid",e.TAG_FOR_DELETION="tag_for_deletion",e.INITIALIZATION="initialization",e.SHUTDOWN="shutdown",e.BY_KEY="by-key"})(ue||(ue={}));const de=Object.assign({},{ignoreDevSafeGuards:!1}),pe=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),he=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],ge=[a.READ,c.READ_ALL],fe=[ue.STATEMENT,le.FIND_ONE_BY],ye=[ue.QUERY,le.PAGE_BY,le.LIST_BY,le.FIND_BY],me=[le.PAGE_BY];class be{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new l("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new l("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...s){const{log:i,ctxArgs:n}=Re.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${s.observer.toString()}: ${e}`),!1}}).map(s=>{s.observer.refresh(e,t,r,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class we extends V{constructor(){super()}}class ve extends u{constructor(e){super(e)}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new l(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t)}pending(){try{return this.get("pending")}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const n=i[0];if(!n)throw new l("Invalid property access to overridden context: "+n);return n in e?e[n]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class Ae extends R{logCtx(e,t,r=!1,s){return Ae.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,s){const i=e.context?t.clear().for(e):t.for(e);return s?i.for(s):i}static logCtx(e,t,r=!1,...s){const i=(e,t,r)=>{const s=t.log||I.get();return t.log=e.context?s.clear().for(e):s.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let n=s.pop();const o=n instanceof ve;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new l("No context provided");if(o&&!r){if(!n)throw new l("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},e)}return async function(...r){if(!this)throw new l("No contextual provided");if(!this.context)throw new l("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(t=>i(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class xe extends Ae{constructor(){super(),this._Context=ve}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let s=r.pop();return s instanceof ve||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(t):new this.Context(s).accumulate(t)}}class Ee extends l{constructor(e){super(e,Ee.name,500)}}class Oe extends l{constructor(e,t=Oe.name){super(e,t,500)}}class Se extends Oe{constructor(e){super(e,Se.name)}}function Ce(e){if(!e)throw new l("No name provided");return"string"==typeof e?e.replaceAll(".","-"):J.Symbol(J.constr(e)).toString().replaceAll(".","-")}function Ne(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function Te(e,t){const{handler:r,args:s}=J.get(e,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,t)??!1)}async function _e(e){return e.then(e=>e.default||e)}function Pe(e,t,r,s){const i=async function(...e){let s;try{s=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof Se)return;throw e}return Promise.resolve(t.apply(this,s))}.bind(e),n=s||t.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=i}class Be{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 Be._instance||(Be._instance=new Be),Be._instance}}class $e{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return $e._instance||($e._instance=new $e),$e._instance}}const De=X.flavourResolver.bind(X);X.flavourResolver=e=>{try{const t=De(e);if(t&&t!==Z)return t;const r="function"==typeof e?e:e?.constructor,s=r&&"function"==typeof J.registeredFlavour?J.registeredFlavour(r):void 0;if(s&&s!==Z)return s;const i=Re._currentFlavour;if(i){const e=Re._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return Z}};class Re extends xe{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Re._baseRepository)throw new l("This should be overridden when necessary. Otherwise it will be replaced lazily");return Re._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new l("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.alias in Re._cache)throw new l(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Re._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Re._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Re._currentFlavour=this.alias)}Dispatch(){return new Re._baseDispatch}ObserverHandler(){return new be}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new Re._baseSequence(e,this,t)}async flags(e,t,r,...s){if("string"==typeof t)throw new l("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(t)?t.length?t[0]:void 0:t,n=i?F.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${e}-${Be.instance.generate()}`;const o=r.logger||I.for(this);return Object.assign({},pe,r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:he.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?J.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:o})}get Context(){return ve}async context(e,t,r,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>F.tableName(e)):F.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof ve||(s.push(i),i=void 0),t=i?Object.assign({},i.toOverrides(),t):t;const n=await this.flags("string"==typeof e?e:e.name,r,t,...s,i);if(i){if(!(i instanceof this.Context))return(new this.Context).accumulate({...i.cache,...n,parentContext:i});const t=i.get("operation"),s=i.get("affectedTables");return t!==e||r!==s?(new this.Context).accumulate({...i.cache,...n,parentContext:i}):i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(e,...t){const{log:r}=this.logCtx(t,this.prepare),s=e.segregate(),i=Object.entries(s.model).reduce((t,[r,s])=>{if(void 0===s)return t;const i=F.columnName(e.constructor,r);if(this.isReserved(i))throw new l(`Property name ${i} is reserved`);return t[i]=s,t},{});return e[ue.METADATA]&&(r.silly("Passing along persistence metadata for "+e[ue.METADATA]),Object.defineProperty(i,ue.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:e[ue.METADATA]})),{record:i,id:e[F.pk(e.constructor)],transient:s.transient}}revert(e,t,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=F.pk(t),c=new t;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const u=e[ue.METADATA],d=Object.keys(c).filter(e=>e!==a).reduce((r,s)=>(r[s]=e[F.columnName(t,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in d&&void 0!==d[e])throw new l(`Transient property ${e} already exists on model ${c.constructor.name}. should be impossible`);d[e]=t})),u&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${u}`),Object.defineProperty(d,ue.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),d}async createAll(e,t,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new d("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new d("Ids and models must have the same length");const o=F.tableName(e);return i.debug(`Creating ${t.length} entries ${o} table`),Ne(t.map((t,i)=>()=>this.create(e,t,r[i],...s,n.override({noEmitSingle:!0}))))}async readAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=F.tableName(e);return s.debug(`Reading ${t.length} entries ${n} table`),Ne(t.map(t=>()=>this.read(e,t,...r,i.override({noEmitSingle:!0}))))}async updateAll(e,t,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new l("Ids and models must have the same length");const o=F.tableName(e);return i.debug(`Updating ${t.length} entries ${o} table`),Ne(t.map((t,i)=>()=>this.update(e,t,r[i],...s,n.override({noEmitSingle:!0}))))}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),Ne(t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0}))))}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);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(e){return J.flavourOf(e)}static get currentFlavour(){if(!Re._currentFlavour)throw new l("No persistence flavour set. Please initialize your adapter");return Re._currentFlavour}static get current(){return Re.get(this.currentFlavour)}static get(e){if(!e)return Re.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new l(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return J.flavouredAs(e).filter(F.isModel)}catch(e){throw new l(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(e)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(t,r,i)=>{if("_config"===r){const s=Reflect.get(t,r,i);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,i)},set:(e,t,r,i)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,i)});return this.proxies[r]=i,i}migrations(){return J.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,s){return super.logCtx(e,t,r,s)}}i([L(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],Re.prototype,"shutdownProxies",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,ve]),n("design:returntype",Promise)],Re.prototype,"context",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Re.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Re.prototype,"unObserve",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],Re.prototype,"client",null);class Ie extends l{constructor(e){super(e,Ie.name,500)}}class Le extends l{constructor(e){super(e,Le.name,500)}}class ke extends F{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):F.fromModel(this,e)}and(e){return ke.and(this,e)}or(e){return ke.or(this,e)}not(e){return new ke(this,ae.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof ke)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ae).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof ke){if(!(this.comparison instanceof ke)&&this.operator!==ae.NOT)return{comparison:{condition:e}};if(-1===Object.values(ce).indexOf(this.operator)&&this.operator!==ae.NOT)return{operator:{condition:e}}}},r=super.hasErrors(...e);return this.isAsync()?(async()=>await Promise.resolve(r)??t())():r??t()}static and(e,t){return ke.group(e,ce.AND,t)}static or(e,t){return ke.group(e,ce.OR,t)}static group(e,t,r){return new ke(e,t,r)}static attribute(e){return(new ke.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(e){return this.setOp(ae.EQUAL,e)}dif(e){return this.setOp(ae.DIFFERENT,e)}gt(e){return this.setOp(ae.BIGGER,e)}lt(e){return this.setOp(ae.SMALLER,e)}gte(e){return this.setOp(ae.BIGGER_EQ,e)}lte(e){return this.setOp(ae.SMALLER_EQ,e)}in(e){return this.setOp(ae.IN,e)}regexp(e){return this.setOp(ae.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new ke(this.attr1,this.operator,this.comparison)}catch(e){throw new Ie(e)}}}}static builder(){return new ke.Builder}static from(e){return new ke(e)}}var Fe,je;i([U(),n("design:type",Object)],ke.prototype,"attr1",void 0),i([U(),n("design:type",String)],ke.prototype,"operator",void 0),i([U(),n("design:type",Object)],ke.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(Fe||(Fe={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(je||(je={}));const Ue={update:je.CASCADE,delete:je.NONE},Ye={Equals:(e,t)=>ke.attribute(e).eq(t),Diff:(e,t)=>ke.attribute(e).dif(t),LessThan:(e,t)=>ke.attribute(e).lt(t),LessThanEqual:(e,t)=>ke.attribute(e).lte(t),GreaterThan:(e,t)=>ke.attribute(e).gt(t),GreaterThanEqual:(e,t)=>ke.attribute(e).gte(t),In:(e,t)=>ke.attribute(e).in(t),Matches:(e,t)=>ke.attribute(e).regexp(t)},Me=e=>e.charAt(0).toLowerCase()+e.slice(1);class qe extends R{static get log(){return this._logger||(this._logger=I.for(qe.name)),this._logger}static build(e,...t){if(!e.startsWith(oe.FIND_BY))throw Error("Unsupported method "+e);const r=this.extractCore(e),s=this.extractSelect(e),i=this.extractGroupBy(e),n=this.buildWhere(r,t),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(e,t);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(e){const t=e.substring(oe.FIND_BY.length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?t.substring(0,r.index):t}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(e){const t=e.indexOf(oe.SELECT);if(-1===t)return;const r=e.substring(t+oe.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(oe.AND).map(Me).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(oe.GROUP_BY);if(-1!==t)return e.substring(t+oe.GROUP_BY.length).split(oe.ORDER_BY)[0].split(oe.THEN_BY).map(Me).filter(Boolean)}static buildWhere(e,t){if(!e&&0===t.length)return;const r=(e.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=e.match(/And|Or/g)||[];let i;if(r.forEach((e,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(e),a=o?Ye[o]:Ye.Equals;if(!a)throw Error("Unsupported operator "+o);const c=t[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===oe.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(e){for(const t of Object.keys(Ye))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:Me(r),operator:t}}return{field:Me(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(e,t){const r=qe.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new Ie("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(Fe).includes(t))throw new Ie(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Fe).join(", ")}.`);return[[e,t]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let i,n,o;if(s.at(-1)instanceof u&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);i=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function Ge(){return X.for(ue.STATEMENT).define({decorator:()=>(e,t,r)=>K(ee(J.key(ue.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function ze(e={}){return X.for(ue.QUERY).define({decorator:e=>(t,r,s)=>{const i=qe.getFieldsFromMethodName(r);return K(ee(J.key(ue.QUERY,r),{...e,fields:i}),Ge(),(e=>(t,r,s)=>{s.value=new Proxy(s.value,{apply(t,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=qe.build(t.name,...s);let u=r.select(i);n&&(u=u.where(n));const{allowLimit:d,allowOffset:p,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(a||[])[0],allowed:h},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:p}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&g)throw new Ie(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(u=u[e.key](e.value))}return u.execute()}})})(e))(t,r,s)},args:[e]}).apply()}function He(e){return Ze(e,[a.CREATE,c.CREATE_ALL])}function Qe(e){return Ze(e,[a.UPDATE,c.UPDATE_ALL])}function Ve(e){return Ze(e,[a.DELETE,c.DELETE_ALL])}function We(e){return Ze(e,he)}function Je(e){return Ze(e,Object.values(a))}function Xe(e){return Ze(e,Object.values(c))}function Ze(e,t){return(r,s,i,...n)=>{if("string"==typeof e)throw new l("clazz cannot be string. This should be impossible");const{log:o}=Ae.prototype.logCtx(n,Ze);return o.silly(`filtering ${s} event for${r?" "+(F.tableName(r)||r):""} ${i}`),("string"==typeof r?r===F.tableName(e)||r===e.constructor.name:J.constr(e)===J.constr(r))&&t.includes(s)}}const Ke={onlyOnCreate:He,onlyOnUpdate:Qe,onlyOnDelete:Ve,onlyOnTransactional:We,onlyOnSingle:Je,onlyOnBulk:Xe};function et(e){const t=Object.assign({},Ke);return Object.entries(t).forEach(([r,s])=>{t[r]=s(e.class)}),t}class tt extends p{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 l("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=F.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return et(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(tt.register(t,this,this.adapter.alias),e)&&J.get(t,te.FLAVOUR)===Z&&re(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;h(s,s[t+"Prefix"],e,s[t+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,s){const i=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},s||{},this._overrides||{}));function n(e){return e.ctxArgs.shift(),e}return i instanceof Promise?i.then(n):n(i)}override(e){return new Proxy(this,{get:(t,r,s)=>{const i=Reflect.get(t,r,s);return"_overrides"!==r?i:Object.assign({},i,e)}})}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(e,...t):Reflect.get(r,s,i)})}ObserverHandler(){return new be}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await f(this,r,e,a.CREATE,a.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new d(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${F.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let a=n.map(e=>e.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((e,t)=>this.adapter.revert(e,this.class,o[t],r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!e.length)return[e,...s];const u=F.sequenceFor(e[0]);let p=[];if(F.generatedBySequence(this.class)?(u.name||(u.name=F.sequenceName(e[0],"pk")),p=await(await this.adapter.Sequence(u)).range(e.length,...s)):F.generated(this.class,this.pk)||(p=e.map((e,t)=>{if(void 0===e[this.pk])throw new l("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),u.type&&(e[this.pk]="String"!==u.type||u.generated?p[t]:""+e[this.pk]),n||await f(this,r,e,a.CREATE,a.ON),e))),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=y(s);if(n)throw new d(n)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await f(this,r,o,a.READ,a.ON),[e,...s]}async read(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${F.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,f(this,r,t,a.READ,a.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${F.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}async update(e,...t){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${F.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=e[this.pk];if(!c)throw new l("No value for the Id is defined under the property "+this.pk);let u;if(r.get("applyUpdateValidation")&&(u=await this.read(c,r),r.get("mergeForUpdate")&&(e=F.merge(u,e,this.class))),n||await f(this,r,e,a.UPDATE,a.ON,u),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(u,...t));if(s)throw new d(s.toString())}return[e,...s,u]}async updateAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const u=e.map(e=>{const t=e[this.pk];if(!t)throw new l("missing id on update operation");return t});let p;if(r.get("applyUpdateValidation")&&(p=await this.readAll(u,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>F.merge(p[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>f(this,r,e,a.UPDATE,a.ON,p?p[t]:void 0))),!o){const t=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(p[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=y(s);if(n)throw new d(n)}return[e,...s,p]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await f(this,r,t,a.DELETE,a.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${F.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>f(this,r,e,a.DELETE,a.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${F.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(e,t,r=Fe.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,ue.QUERY,!0)).for(this.query),a=[t,r],c=this.select().where(e).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${F.tableName(this.class)} by ${e} ${t}`),this.select().orderBy([e,t]).execute(...i)}async paginateBy(e,t,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new Ie("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);let d;if(c.verbose(`paginating ${F.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>t===Fe.ASC?this.attr(F.pk(this.class)).gt(o):this.attr(F.pk(this.class)).lt(o))()).orderBy([e,t]).paginate(a,...u);else{if(!n)throw new Ie("PaginateBy needs a page or a bookmark");d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,t]).paginate(a,...u)}const p=await d.page(i,o,...u);return d.serialize(p)}async findOneBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${F.tableName(this.class)} with ${e} ${t}`);const n=await this.select().where(this.attr(e).eq(t)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${F.tableName(this.class)} with ${e} ${t}`),this.select().where(this.attr(e).eq(t)).execute(...i)}async statement(e,...t){if(!tt.statements(this,e))throw new Ie("Invalid prepared statement requested "+e);const{log:r,ctxArgs:s}=(await this.logCtx(t,ue.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+e),this[e](...s)}attr(e){return ke.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=F.tableName(this.class);return this.adapter.observe(this,(e,t,r,...i)=>"string"==typeof e?e===s:J.constr(e)===J.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("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 l("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>Re._baseSequence.parseValue(F.sequenceFor(this.class).type,e)):Re._baseSequence.parseValue(F.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}static forModel(e,t,...r){let s;const i=t||J.flavourOf(e)||Re.currentFlavour;try{s=this.get(e,i)}catch(e){s=void 0}if(s instanceof tt)return s;const n=t||J.flavourOf(e)||s&&J.get(s,ue.ADAPTER)||Re.currentFlavour,o=n?Re.get(n):void 0;if(!o)throw new l("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,e,...r)}static get(e,t){const r=F.tableName(e);let s=r;if(t&&(s=[r,t].join(b)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new l("Could not find repository registered under "+r)}static register(e,t,r){let s=F.tableName(e);if(r&&(s=[s,r].join(b)),s in this._cache&&this._cache[s]instanceof tt)throw new l(s+" already has a registered instance");this._cache[s]=t}static statements(e,t){const r=e instanceof tt?e.constructor:e,s=J.get(r,t?J.key(ue.STATEMENT,t):ue.STATEMENT);return(t?s:Object.keys(s))||!1}static queries(e,t){const r=e instanceof tt?e.constructor:e;return J.get(r,t?J.key(ue.QUERY,t):ue.QUERY)}}function rt(e,t){if(!(t||(t=X.flavourResolver(e instanceof F?e.constructor:e))&&t!==Z))throw new l("Could not retrieve flavour from model "+(e instanceof F?e.constructor.name:e.name));return Y(ue.INJECTABLE,t,F.tableName(e))}i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],tt.prototype,"listBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"paginateBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"findOneBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"findBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],tt.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],tt.prototype,"unObserve",null),Re&&(Re._baseRepository=tt);class st extends e{get log(){return this.logger||(this.logger=I.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=F.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=F.get(e.toString())),!n)return;const o=ue.ADAPTER,a=r||J.get(n,o);try{let e=a;try{a&&Re.get(a)}catch{const t=Re.current;t&&t.flavour===a&&(e=t.alias)}if(i=tt.forModel(n,e),i instanceof tt)return i;const r=a||J.get(i.constructor,o)||J.get(n,o);t.register(i,rt(n,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=tt.get(n,a);if("function"==typeof t){const e=a?Re.get(a):Re.current;if(!e)return;return new t(e,n)}}}return i}}var it,nt,ot,at,ct;(e=>{e.PENDING="pending",e.RUNNING="running",e.FAILED="failed",e.SUCCEEDED="succeeded",e.CANCELED="canceled",e.WAITING_RETRY="waiting_retry"})(it||(it={})),(e=>{e.EXPONENTIAL="exponential",e.FIXED="fixed"})(nt||(nt={})),(e=>{e.NONE="none",e.FULL="full"})(ot||(ot={})),(e=>{e.STATUS="status",e.LOG="log",e.PROGRESS="progress",e.ALL="all"})(at||(at={})),(e=>{e.ATOMIC="atomic",e.COMPOSITE="composite"})(ct||(ct={})),J.tasks=(()=>J.innerGet(Symbol.for("tasks"))).bind(J),J.taskFor=(e=>{const t=J.tasks();return t?t[e]:void 0}).bind(J),J.validationExceptions=((e,t)=>{const r=J.get(e,ue.NO_VALIDATE)||[],s=Object.entries(r).filter(([,e])=>e.includes(t)).map(([e])=>e);let i=[];return t!==a.CREATE&&t!==a.UPDATE||(i=F.nestedRelations(e)),[...new Set([...s,...i])]}).bind(J),J.migrationsFor=(e=>{if(!(e=e??Re.current))throw new l("Could not get adapter for migrations");return J.innerGet(Symbol.for(ue.MIGRATION),e.alias).map(e=>e.class)}).bind(J),J.migrations=(()=>{const e=J.innerGet(Symbol.for([ue.MIGRATION,ue.BY_KEY].join("-")));return Object.values(e).flat().map(e=>[e.class.name,e.class])}).bind(J),J.relations=((e,t)=>{const r=J.get(e,ue.RELATIONS);if(r){if(!t)return Object.keys(r);if(!r[t])throw new l("No relations metadata found for property "+t);return r[t]}}).bind(J),F.relations=(e,t)=>J.relations(e instanceof F?e.constructor:e,t)||[],F.nestedRelations=((e,t=[])=>{let r=[];const s=J.get(e,ue.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...t])];for(const e in s){const i=s[e];if(i?.class&&F.relations(i.class)){const s=F.relations(i.class).map(t=>`${e}.${t}`);t=[...t,...s],r=F.nestedRelations(i.class,t)}}return[...new Set([...t,...r])]}).bind(F),F.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!F.sequenceFor(r).generated}).bind(F),F.fromTable=(e=>{const t=J.innerGet(Symbol.for(ue.TABLE));if(!t||!t[e]||!F.get(t[e].name))throw new l("No table metadata found for model. did you use @table()?");return F.get(t[e].name)}).bind(F),J.createdBy=(e=>{const t=J.get("function"!=typeof e?e.constructor:e,ue.CREATED_BY);if(!t)throw new l("No createdBy metadata found for model. did you use @createdBy()?");return t}).bind(J),J.updatedBy=(e=>{const t=J.get("function"!=typeof e?e.constructor:e,ue.UPDATED_BY);if(!t)throw new l("No updatedBy metadata found for model. did you use @updatedBy()?");return t}).bind(J),F.tableName=e=>{if(!(e instanceof F?F.get(e.constructor.name):e))throw new l("Unable to find model "+e);return J.get(e instanceof F?e.constructor:e,ue.TABLE)||(e instanceof F?e.constructor.name:e.name)},F.columnName=(e,t)=>J.get(e instanceof F?e.constructor:e,J.key(ue.COLUMN,t))||t,F.sequenceName=(e,...t)=>[F.tableName(e),...t].join("_"),F.sequenceFor=(e,t)=>{if(t)throw new Ee("not currently supported");const r=F.pkProps(e instanceof F?e.constructor:e);if(!r)throw new l("No sequence options defined for model. did you use the @pk decorator?");return r},F.indexes=e=>{const t=J.get(e instanceof F?e.constructor:e,ue.INDEX);return Object.keys(t||{}).reduce((e,r)=>(e[r]={[ue.INDEX]:t[r]},e),{})},t.services=()=>J.innerGet(Symbol.for(ue.SERVICE)),t.repositories=()=>J.innerGet(Symbol.for(w.REPOSITORY));class lt extends Ae{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new l("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...e){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:t}=(await this.logCtx(e,ue.INITIALIZATION,!0)).for(this.initialize);t.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(e=>{if(!r[e])throw new l(`Method ${e} not found in ${r.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(r,e),s=r;for(;!t&&s!==Object.prototype;)s=Object.getPrototypeOf(s),t=Object.getOwnPropertyDescriptor(s,e);function i(e){switch(e){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return e}}t&&t.writable?r[e]=new Proxy(r[e],{apply:async(t,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),t),[c,l,u]=s,d=await t.call(r,c,l,u,...o),p=[c,i(e),l];return a.get("observeFullResult")&&p.push(d),this.updateObservers(...p,...o).catch(t=>n.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),d}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof Re))throw new Ee("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=Re.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(this.adapter!==e)throw new Ee("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){if(!e)throw new l("Model must be provided for observer update");const i=e&&"string"==typeof e?e:F.tableName(e),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...o)}catch(e){throw new l("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function ut(e,t,r,s){if(e.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=t;i&&"function"==typeof i&&(i=i(s,...n||[],e)),s[r]=await Be.instance.generate(i)}function dt(e=!1,t,...r){"function"==typeof e&&(t=e,e=!1);const s=ue.UUID;return X.for(s).define({decorator:(e,t,...r)=>{const s={update:e,seed:t,args:r},i=[U(),v(ue.UUID),A(ut,s,{priority:54})];return e&&i.push(x(ut,s,{priority:54})),e||i.push(E()),K(...i)},args:[e,t,...r]}).apply()}async function pt(e,t,r,s,i){const n=t.logger.for(pt);if(!s){const t=F.get(e.constructor.name);if(!t)throw new l("Could not find model "+e.constructor.name);s=tt.forModel(t,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===e[F.pk(s.class)])n.info(`No pk found in ${F.tableName(s.class)} - creating`),o=await s.create(e,t);else{n.info(`pk found in ${F.tableName(s.class)} - attempting update`);try{o=await s.update(e,t),n.info("Updated "+F.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+F.tableName(s.class)),o=await s.create(e,t)}n.info("After create update: "+o)}return o}async function ht(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=St(s,r,this.adapter.alias),n=await t.read(i,e);return await At(e,s,r,i,n),void(s[r]=i)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new l("Could not find model "+t.class);const o=tt.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,e),c=F.pk(a);await At(e,s,r,a[c],a),s[r]=a[c]}async function gt(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==je.CASCADE)return;if("object"!=typeof i){const t=St(s,r,this.adapter.alias),n=await t.override(this._overrides).read(i,e);return await At(e,s,r,i,n),void(s[r]=i)}const n=await pt(s[r],e,this.adapter.alias,void 0,this._overrides),o=F.pk(n);await At(e,s,r,n[o],n),s[r]=n[o]}async function ft(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==je.CASCADE)return;const n=St(s,r,this.adapter.alias);let o;o=i instanceof F?await n.delete(s[r][n.pk],e):await n.delete(s[r],e),await At(e,s,r,o[n.pk],o)}async function yt(e,t,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o=e.logger.for(yt),a=new Set([...i]);if("object"!==n){const t=St(s,r,this.adapter.alias),i=await t.readAll([...a.values()],e);for(let t=0;t<i.length;t++){const s=i[t];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await At(e,s,r,[...a.values()][t],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=F.pk(i[0].constructor),u=new Set;for(const t of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(t));const i=await pt(t,e,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await At(e,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(t)),u.add(i[c])}s[r]=[...u]}async function mt(e,t,r,s){const{cascade:i}=t;if(i.update===je.CASCADE)return yt.call(this,e,t,r,s)}async function bt(e,t,r,s){if(t.cascade.delete!==je.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof t.class||t.class.name?t.class:t.class(),a="object"===n,c=a?tt.forModel(o,this.adapter.alias):St(s,r,this.adapter.alias),u=[...new Set([...a?i.map(e=>e[c.pk]):i]).values()];let d,p;try{d=await c.deleteAll(u,e)}catch(t){throw e.logger.error("Failed to delete all records",t),t}for(let t=0;t<d.length;t++){p=d[t];try{await At(e,s,r,u[t],p)}catch(i){throw e.logger.error(`Failed to cache record ${u[t]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=u}function wt(e,t,r){return[ue.POPULATE,e,t,r].join(".")}function vt(e,t,r){return[ue.TAG_FOR_DELETION,e,r].join(".")}async function At(e,t,r,s,i){const n=wt(t.constructor.name,r,s),o=e.get("cacheForPopulate")||{};return o[n]=i,e.accumulate({cacheForPopulate:o})}async function xt(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,r,s,i)=>{let n,o;const a=[],c=t.get("cacheForPopulate")||{};for(const t of i){n=wt(r.constructor.name,s,t);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=St(r,s);if(!n)throw new l("Could not find repo");o=await n.read(t,e)}a.push(o)}return a})(e,s,r,n?i:[i]);s[r]=n?o:o[0]}async function Et(e,t,r,s,i){if(t.cascade.update!==je.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new l("No way to compare old model. do you have updateValidation and mergeModels enabled?");function o(e){return Array.isArray(e)?e.map(o):"object"!=typeof e?e:e[F.pk(e)]}const a=o(s[r]),c=o(i[r]);if(M(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new l("Cannot cascade update for different array types");const u=(Array.isArray(a)?a:[a]).filter(Boolean),d=(Array.isArray(c)?c:[c]).filter(Boolean).filter(e=>!u.includes(e)),p=St(s,r);if(!p)throw new l("Could not find repo");try{const t=await p.deleteAll(d,e);e.logger.debug(`Deleted ${t.length} entries from table ${F.tableName(p.class)} due to cascade rules with `)}catch(e){throw new l("Error deleting cascade entries: "+e)}}Re&&(Re._baseDispatch=lt);const Ot=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function St(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=J.get(e instanceof F?e.constructor:e,J.key(q.REFLECT,t,q.LIST))?.clazz;if(!r)throw new l("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=J.getPropDesignTypes(e instanceof F?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!Ot.includes((""+e.name).toLowerCase()));return tt.forModel(i,r)}class Ct extends O{constructor(e,t=Ct.name,r=401){super(e,t,r)}}class Nt extends Ct{constructor(e,t=Nt.name){super(e,t,403)}}class Tt extends l{constructor(e){super(e,Tt.name,503)}}function _t(e){return X.for(ue.TABLE).define({decorator:e=>t=>(J.set(ue.TABLE,e||t.name.toLowerCase(),t),se(ue.TABLE,e||t.name.toLowerCase())(t)),args:[e]}).apply()}function Pt(e){return X.for(ue.COLUMN).define({decorator:e=>(t,r)=>ie(J.key(ue.COLUMN,r),e||r)(t,r),args:[e]}).apply()}function Bt(e,t,r){return X.for(ue.INDEX).define({decorator:(e,t,r)=>(s,i)=>("string"==typeof e&&(r=e,e=void 0,t=void 0),"string"==typeof t&&(r=t,t=void 0),!t&&e&&e.find(e=>![Fe.ASC,Fe.DSC].includes(e))&&(t=e,e=void 0),ie(J.key(`${ue.INDEX}${t&&t?.length?"."+t.join("."):""}`,i),{directions:e,compositions:t,name:r})(s,i)),args:[e,t,r]}).apply()}async function $t(e,t,r,s){if(s[r]&&(await this.select().where(ke.attribute(r).eq(s[r])).execute()).length)throw new C(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Dt(){const e=ue.UNIQUE;return X.for(e).define(G(),N($t),ie(e,{})).apply()}async function Rt(e,t,r,s){throw new Ct("This adapter does not support user identification")}function It(){return X.for(ue.CREATED_BY).define({decorator:()=>(e,t)=>K(A(Rt),ie(ue.CREATED_BY,t),v(ue.CREATED_BY))(e,t),args:[]}).apply()}function Lt(){return X.for(ue.UPDATED_BY).define({decorator:()=>(e,t)=>K(x(Rt),ie(ue.UPDATED_BY,t),v(ue.UPDATED_BY))(e,t),args:[]}).apply()}function kt(){return T([a.CREATE])}function Ft(){return T()}function jt(e){const t="function"==typeof e&&e.name?e:e(),r=F.pk(t);return J.allowedTypes(t,r)||[]}function Ut(e,t=Ue,r=!0,s,i){const n=ue.ONE_TO_ONE;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),z([e,...a]),A(ht,o,{priority:70}),x(gt,o,{priority:70}),_(ft,o,{priority:70}),P(Et,o,{priority:70}),B(xt,o,{priority:70})];return K(...c)},args:[e,t,r,s,i]}).apply()}function Yt(e,t=Ue,r=!0,s,i){const n=ue.ONE_TO_MANY;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),H([e,...a]),A(yt,o,{priority:70}),x(mt,o,{priority:70}),_(bt,o,{priority:70}),P(Et,o,{priority:70}),B(xt,o,{priority:70})];return K(...c)},args:[e,t,r,s,i]}).apply()}function Mt(e,t=Ue,r=!0,s,i){const n=ue.MANY_TO_ONE;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),z([e,...a])];return K(...c)},args:[e,t,r,s,i]}).apply()}function qt(e,t=Ue,r=!0,s,i){const n=ue.MANY_TO_MANY;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),H([e,...a])];return K(...c)},args:[e,t,r,s,i]}).apply()}function Gt(...e){return(t,r)=>{const s=J.get(t,J.key(ue.NO_VALIDATE,r))||[],i=[...new Set([...s,...e])];return K(se(J.key(ue.NO_VALIDATE,r),i))(t,r)}}function zt(){return Gt(a.CREATE)}function Ht(){return Gt(a.UPDATE)}function Qt(){return Gt(a.UPDATE,a.CREATE)}function Vt(e,t){return X.for(ue.RELATIONS).define({decorator:(e,t)=>(r,s)=>(ie(e,t)(r,s),ie(J.key(ue.RELATIONS,s),Object.assign({},t,{key:e}))(r,s)),args:[e,t]}).apply()}class Wt extends F{constructor(e){super(e)}}i([kt(),n("design:type",Date)],Wt.prototype,"createdAt",void 0),i([Ft(),n("design:type",Date)],Wt.prototype,"updatedAt",void 0);const Jt={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Xt=Jt,Zt={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Kt=Object.assign({},Zt,{type:"BigInt"});async function er(e,t,r,s){if(!t.type||!t.generated||s[r])return;let i;t.name||(t.name=F.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new l(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,o,a;n=s,o=r,a=await i.next(e),Reflect.set(n,o,a)}function tr(e,t){return(r,s)=>{if(ne()(r,s),!e.type){const t=J.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(t?.name||t))throw Error("Incorrrect option type");e.type=t}switch(e.type){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated,e.type=String;break;case Number.name||String.name.toLowerCase():case Number:e.generated=void 0===e.generated||e.generated,e.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:e.type=BigInt,e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;default:throw Error("Unsupported type")}void 0===e.generated&&(e.generated=!0);const i=[Bt([Fe.ASC,Fe.DSC]),ne(),U(),E(),ie(J.key(w.ID,s),e),A(er,e,t)];return e.generated&&i.push(v()),K(...i)(r,s)}}function rr(e){const t=Object.assign({},Xt);return delete t.generated,e=Object.assign({},t,e),X.for(w.ID).define({decorator:tr,args:[e,{priority:60}]}).apply()}let sr=class extends Wt{constructor(e){super(e)}};i([rr({type:String,generated:!1}),n("design:type",String)],sr.prototype,"id",void 0),i([U(),Bt(),n("design:type",Object)],sr.prototype,"current",void 0),sr=i([_t("??sequence"),Q(),n("design:paramtypes",[Object])],sr);class ir extends Ae{static{this.lock=new W}constructor(e,t,r={}){super(),this.options=e,this.adapter=t,this.repo=tt.forModel(sr,t.alias).override(r)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof m){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new l("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new l(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new l(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(e,t){const{log:r,ctx:s}=this.adapter.logCtx([t],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new l("Sequence name is required");return ir.lock.execute(async()=>{const t=e||n;if(t%n!==0)throw new l("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),u=async e=>{try{return await this.repo.update(new sr({id:o,current:e}),s)}catch(t){if(t instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${e}`),this.repo.create(new sr({id:o,current:e}),s);throw t}};if("uuid"===a)for(;;){const e=await Promise.resolve(Be.instance.generate(c));try{const t=await u(e);return r.debug(`Sequence uuid increment ${o} current=${c} next=${e}`),t.current}catch(e){if(e instanceof C)continue;throw e}}const d=await(async e=>{switch(a){case Number.name:return this.parse(e)+t;case BigInt.name:return this.parse(e)+BigInt(t);case String.name:return this.parse(e);case"serial":return await Promise.resolve($e.instance.generate(e));default:throw new l("Should never happen")}})(c),p=await u(d);return r.debug(`Sequence.increment ${o} current=${c} next=${d}`),p.current},o)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ee(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new l("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return ir.parseValue(this.options.type,e)}logCtx(e,t,r=!1){const s=this.adapter.logCtx([sr,...e],t,r);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return F.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 Ee(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function nr(e,t){return(i,n)=>n?r(J.constr(e))(i,n):(J.set(w.REPOSITORY,J.key(t||Re.currentFlavour,F.tableName(e)),i),se(w.REPOSITORY,i.name)(e),t=t||J.get(i.constructor,ue.ADAPTER),tt.register(e,i,t),s(J.constr(e),{callback:t=>(Object.defineProperty(t,w.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}Re._baseSequence=ir;class or extends l{constructor(e){super(e,or.name,500)}}class ar extends R{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,s){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=s,Pe(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${le.FIND_BY}|${le.LIST_BY}`,"gi"))}async pagePrefix(e,...t){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...t],le.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[e,...r]}async pagePrepared(e,t,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!t||t instanceof ve?[t,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${e} page${t?" - bookmark "+t:""}`),!t||t instanceof ve||(this._bookmark=t);const n=tt.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,u=RegExp(`^${le.FIND_BY}|${le.LIST_BY}`,"gi");if(!a.match(u))throw new Ee(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,le.PAGE_BY),p=[d,...c];let h={limit:this.size,offset:e,bookmark:this._bookmark};d!==le.PAGE_BY||p.length>2?h={direction:l.direction,limit:this.size,offset:e,bookmark:this._bookmark}:p.push(l.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}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 Le("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new Le(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:s}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...s);throw new Ee("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new $(e)}}apply(e){const t="string"==typeof e?ar.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new $(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var cr,lr,ur,dr;class pr extends Ae{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{D(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...t],e.name===this.paginate.name?le.PAGE_BY:ue.QUERY,!0,this.overrides||{})).for(e);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(pr)}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?F.get(e):e,!this.fromSelector)throw new Ie("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{log:t,ctxArgs:r}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();return t.silly("executing raw statement"),await this.raw(s,...r)}catch(e){throw new Ie(e)}}async executePrepared(...e){const t=tt.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return t.statement(r,...s,i,...e)}async raw(e,...t){const{ctx:r,ctxArgs:s}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new Ee("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(e,!0,...s);if(!this.selectSelector)return i;const n=F.pk(this.fromSelector),o=function(e){const t=e[n];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(e,t){let{attr1:r,operator:s,comparison:i}=e;const n={};switch(s){case ce.AND:case ce.OR:{let e=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,t);e=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof ke){const e=this.prepareCondition(i,t);o=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${o}`;break}case ae.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ae.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ae.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ae.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ae.BIGGER_EQ:n.method=r+" bigger than equal";break;case ae.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ae.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ae.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Ie("Unsupported operator "+s)}return n}squash(e){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let t;if(this.whereCondition){if(this.whereCondition.comparison instanceof ke)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,Fe.DSC]:[F.pk(this.fromSelector),Fe.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:le.LIST_BY,args:[s],params:n};return t&&(o.method=le.FIND_BY,o.args=[t,this.whereCondition.comparison],o.params=n),o}async prepare(e){if(e=e||await this.adapter.context(ue.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},s={class:this.fromSelector,args:t,params:r},i=[oe.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);i.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&i.push(oe.SELECT,this.selectSelector.join(` ${oe.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(oe.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(oe.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=k(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new Ie(e)}}toString(){return this.adapter.flavour+" statement"}}i([L(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"select",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(cr="undefined"!=typeof S&&S)?cr:Object]),n("design:returntype",Object)],pr.prototype,"distinct",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(lr="undefined"!=typeof S&&S)?lr:Object]),n("design:returntype",Object)],pr.prototype,"max",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ur="undefined"!=typeof S&&S)?ur:Object]),n("design:returntype",Object)],pr.prototype,"min",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(dr="undefined"!=typeof S&&S)?dr:Object]),n("design:returntype",Object)],pr.prototype,"count",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"from",null),i([L(),n("design:type",Function),n("design:paramtypes",[ke]),n("design:returntype",Object)],pr.prototype,"where",null),i([L(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"orderBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"groupBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"limit",null),i([L(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"offset",null),i([L(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],pr.prototype,"execute",null);class hr extends Ae{constructor(e){super(),this.name=e,this.observers=[],this.Context=ve}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new be,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${Be.instance.generate()}`;const s=t.logger||I.for(this);return s.setConfig({correlationId:t.correlationId}),Object.assign({},t,{args:r,timestamp:new Date,operation:e,logger:s})}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let s=r.pop();void 0===s||s instanceof ve||(r.push(s),s=void 0),t=s?Object.assign({},s.toOverrides(),t):t;const i=await this.flags("string"==typeof e?e:e.name,t,...r,s);return s?s instanceof this.Context?s.get("operation")!==e?(new this.Context).accumulate({...s.cache,...i,parentContext:s}):s.accumulate(i):(new this.Context).accumulate({...s.cache,...i,parentContext:s}):(new this.Context).accumulate({...de,...i})}logCtx(e,t,r=!1,s){return Ae.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new l("No name provided");const r=Ce(e),s=t.get(r);if(s)return s;throw new l("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){let r=e.pop();void 0===r||r instanceof ve||(e.push(r),r=void 0);const s=await hr.prototype.flags(ue.INITIALIZATION,{},...e);r=r?new ve(r).accumulate({...s,parentContext:r}):(new ve).accumulate(s),e=[...e,r];const{log:i,ctxArgs:n}=hr.prototype.logCtx(e,this.boot),o=t.services();for(const[e,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=t.get(r);if(!s)throw new l("Failed to resolve injectable for "+e);s instanceof gr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new l(`Failed to boot ${e} service:${t}`)}}}i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],hr.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],hr.prototype,"unObserve",null);class gr extends hr{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=(await this.logCtx(e,ue.INITIALIZATION,!0)).for(this.boot);t.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new l("Config not initialized");return this._config}get client(){if(!this._client)throw new l("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...`)}}function fr(e){return function(t,r,s){const i=s.value;return s.value=function(...t){const r=this.class;if(r&&Te(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,t)},s}}i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],gr.prototype,"boot",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"config",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"client",null);const yr=()=>fr(a.CREATE),mr=()=>fr(a.READ),br=()=>fr(a.UPDATE),wr=()=>fr(a.DELETE);function vr(e){return(t,i,n)=>{n||i?(ne()(t,i),e=e||J.type(t.constructor,i)):e=e||t,e=Ce(e);const o=[];if(n&&"number"==typeof n.value)o.push(r(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(e))}else J.set(ue.SERVICE,e,t),o.push(s(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return K(...o)(t,i,n)}}const Ar=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class xr extends hr{get class(){if(!this.clazz)throw new l("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=tt.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new l("No name provided");const t=Ar(e);try{const e=hr.get(t);if(e)return e}catch(e){}throw new l("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(e,...t):Reflect.get(r,s,i)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(e,...t){const{ctxArgs:r}=(await this.logCtx(t,ue.QUERY,!0)).for(this.query),s=this.repo?.[e];if("function"!=typeof s)throw new l(`Method "${e}" is not implemented`);return s.apply(this.repo,r)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(e,t,...s)}async paginateBy(e,t,r,...s){const{ctxArgs:i}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(e,t,r,...i)}async findOneBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(e,t,...s)}async findBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(e,t,...s)}async statement(e,...t){const{ctxArgs:r}=(await this.logCtx(t,ue.STATEMENT,!0)).for(this.statement);return this.repo.statement(e,...r)}static forModel(e,t){let r;t=Ar(t||e);try{r=xr.get(t)}catch(e){r=void 0}if(r instanceof xr)return r;const s=this;let o=class extends s{constructor(){super(e)}};return o=i([vr(t),n("design:paramtypes",[])],o),new o}refresh(e,t,r,...s){return this.repo.refresh(e,t,r,...s)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...s){return this.repo.updateObservers(e,t,r,...s)}logCtx(e,t,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}}i([yr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"create",null),i([yr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"createAll",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"delete",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"deleteAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"read",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"readAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],xr.prototype,"query",null),i([br(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"update",null),i([br(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],xr.prototype,"updateAll",null);class Er extends gr{constructor(){super()}async initialize(...e){const t=e.shift();if(!t||!Array.isArray(t)||t instanceof ve||!t.every(e=>Array.isArray(e)))throw new l("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(e,ue.INITIALIZATION,!0)).for(this.initialize),i=t.map(([e,t,...s])=>{try{r.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const i=new e(t,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(t){throw new l(`Failed to initialize ${e.name}: ${t}`)}});for(const e of i)try{await e.initialize(...s)}catch(t){throw new l(`Failed to initialize ${e.toString()}: ${t}`)}return{client:i,config:t}}}t.setRegistry(new st);const Or="##VERSION##",Sr="##PACKAGE##";J.registerLibrary(Sr,Or);export{xe as AbsContextual,Re as Adapter,Ct as AuthorizationError,Wt as BaseModel,Kt as BigIntSequence,je as Cascade,gr as ClientBasedService,ke as Condition,Tt as ConnectionError,ve as Context,we as ContextLock,Ae as ContextualLoggedClass,pe as DefaultAdapterFlags,Ue as DefaultCascade,de as DefaultContextFlags,Ke as DefaultRepositoryFilters,Xt as DefaultSequenceOptions,lt as Dispatch,Nt as ForbiddenError,ce as GroupOperator,st as InjectablesRegistry,qe as MethodQueryBuilder,Oe as MigrationError,Se as MigrationRuleError,xr as ModelService,ye as MultipleSelectOperationKeys,ge as NonTransactionOperationKeys,Jt as NoneSequenceOptions,Zt as NumericSequence,or as ObserverError,be as ObserverHandler,ae as Operator,Ye as OperatorsMap,Fe as OrderDirection,Sr as PACKAGE_NAME,me as PaginationOperationKeys,ar as Paginator,Le as PagingError,ue as PersistenceKeys,Er as PersistenceService,le as PreparedStatementKeys,oe as QueryClause,Ie as QueryError,tt as Repository,fe as SelectOperationKeys,ir as Sequence,sr as SequenceModel,$e as Serial,hr as Service,pr as Statement,he as TransactionOperationKeys,Be as UUID,Ee as UnsupportedError,Or as VERSION,At as cacheModelForPopulate,Et as cascadeDelete,Pt as column,yr as create,pt as createOrUpdate,kt as createdAt,It as createdBy,Rt as createdByOnCreateUpdate,wr as del,rt as generateInjectableNameForRepository,et as getFilters,jt as getPkTypes,wt as getPopulateKey,vt as getTagForDeleteKey,Bt as index,Ce as injectableServiceKey,Te as isOperationBlocked,qt as manyToMany,Mt as manyToOne,Gt as noValidateOn,zt as noValidateOnCreate,Qt as noValidateOnCreateUpdate,Ht as noValidateOnUpdate,_e as normalizeImport,Yt as oneToMany,yt as oneToManyOnCreate,bt as oneToManyOnDelete,mt as oneToManyOnUpdate,Ut as oneToOne,ht as oneToOneOnCreate,ft as oneToOneOnDelete,gt as oneToOneOnUpdate,Xe as onlyOnBulk,He as onlyOnCreate,Ve as onlyOnDelete,Ze as onlyOnFilter,Je as onlyOnSingle,We as onlyOnTransactional,Qe as onlyOnUpdate,rr as pk,tr as pkDec,er as pkOnCreate,xt as populate,Pe as prefixMethod,Ge as prepared,Ne as promiseSequence,ze as query,mr as read,Vt as relation,nr as repository,St as repositoryFromTypeMetadata,vr as service,_t as table,Dt as unique,$t as uniqueOnCreateUpdate,br as update,Ft as updatedAt,Lt as updatedBy,dt as uuid,ut as uuidCreateUpdateHandler};
1
+ import{InjectableRegistryImp as e,Injectables as t,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,InternalError as l,Context as d,ValidationError as u,Repository as p,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as b,DBKeys as w,generated as v,onCreate as A,onUpdate as x,readonly as E,BadRequestError as O,ConflictError as C,onCreateUpdate as N,timestamp as T,onDelete as _,afterUpdate as B,afterAny as P,SerializationError as $,prefixMethod as D}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as I,final as L,toCamelCase as k}from"@decaf-ts/logging";import{Model as F,hashObj as j,required as U,sf as Y,isEqual as M,ValidationKeys as q,async as G,type as z,list as H,model as Q}from"@decaf-ts/decorator-validation";import{Lock as V,MultiLock as W}from"@decaf-ts/transactional-decorators";import{Metadata as J,Decoration as X,DefaultFlavour as Z,apply as K,methodMetadata as ee,DecorationKeys as te,uses as re,metadata as se,propMetadata as ie,prop as ne}from"@decaf-ts/decoration";var oe,ae,ce,le,de;(e=>{e.FIND_BY="findBy",e.SELECT="Select",e.AND="And",e.OR="Or",e.GROUP_BY="GroupBy",e.ORDER_BY="OrderBy",e.THEN="Then",e.THEN_BY="ThenBy"})(oe||(oe={})),(e=>{e.EQUAL="EQUAL",e.DIFFERENT="DIFFERENT",e.BIGGER="BIGGER",e.BIGGER_EQ="BIGGER_EQ",e.SMALLER="SMALLER",e.SMALLER_EQ="SMALLER_EQ",e.NOT="NOT",e.IN="IN",e.REGEXP="REGEXP"})(ae||(ae={})),(e=>{e.AND="AND",e.OR="OR"})(ce||(ce={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(le||(le={})),(e=>{e.PERSISTENCE="persistence",e.INDEX="index",e.UNIQUE="unique",e.ADAPTER="adapter",e.INJECTABLE="decaf_{0}_adapter_for_{1}",e.SERVICE="service",e.TABLE="table",e.COLUMN="column",e.METADATA="__metadata",e.OWNERSHIP="ownership",e.CREATED_BY="ownership.created-by",e.UPDATED_BY="ownership.updated-by",e.RELATIONS="__relations",e.RELATION="relation",e.ONE_TO_ONE="relation.one-to-one",e.ONE_TO_MANY="relation.one-to-many",e.MANY_TO_ONE="relation.many-to-one",e.MANY_TO_MANY="relation.many-to-many",e.POPULATE="populate",e.NO_VALIDATE="no-validate",e.MIGRATION="migration",e.STATEMENT="statement",e.QUERY="query",e.UUID="uuid",e.TAG_FOR_DELETION="tag_for_deletion",e.INITIALIZATION="initialization",e.SHUTDOWN="shutdown",e.BY_KEY="by-key"})(de||(de={}));const ue=Object.assign({},{ignoreDevSafeGuards:!1}),pe=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),he=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],ge=[a.READ,c.READ_ALL],fe=[de.STATEMENT,le.FIND_ONE_BY],ye=[de.QUERY,le.PAGE_BY,le.LIST_BY,le.FIND_BY],me=[le.PAGE_BY];class be{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new l("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new l("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...s){const{log:i,ctxArgs:n}=Re.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${s.observer.toString()}: ${e}`),!1}}).map(s=>{s.observer.refresh(e,t,r,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class we extends V{constructor(){super()}}class ve extends d{constructor(e){super(e)}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new l(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t)}pending(){try{return this.get("pending")}catch(e){return}}getOrUndefined(e){try{return this.get(e)}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const n=i[0];if(!n)throw new l("Invalid property access to overridden context: "+n);return n in e?e[n]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class Ae extends R{logCtx(e,t,r=!1,s){return Ae.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,s){const i=e.context?t.clear().for(e):t.for(e);return s?i.for(s):i}static logCtx(e,t,r=!1,...s){const i=(e,t,r)=>{const s=t.log||I.get();return t.log=e.context?s.clear().for(e):s.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let n=s.pop();const o=n instanceof ve;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new l("No context provided");if(o&&!r){if(!n)throw new l("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},e)}return async function(...r){if(!this)throw new l("No contextual provided");if(!this.context)throw new l("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(t=>i(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class xe extends Ae{constructor(){super(),this._Context=ve}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let s=r.pop();return s instanceof ve||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(t):new this.Context(s).accumulate(t)}}class Ee extends l{constructor(e){super(e,Ee.name,500)}}class Oe extends l{constructor(e,t=Oe.name){super(e,t,500)}}class Se extends Oe{constructor(e){super(e,Se.name)}}function Ce(e){if(!e)throw new l("No name provided");return"string"==typeof e?e.replaceAll(".","-"):J.Symbol(J.constr(e)).toString().replaceAll(".","-")}function Ne(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function Te(e,t){const{handler:r,args:s}=J.get(e,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,t)??!1)}async function _e(e){return e.then(e=>e.default||e)}function Be(e,t,r,s){const i=async function(...e){let s;try{s=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof Se)return;throw e}return Promise.resolve(t.apply(this,s))}.bind(e),n=s||t.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=i}class Pe{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 Pe._instance||(Pe._instance=new Pe),Pe._instance}}class $e{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return $e._instance||($e._instance=new $e),$e._instance}}const De=X.flavourResolver.bind(X);X.flavourResolver=e=>{try{const t=De(e);if(t&&t!==Z)return t;const r="function"==typeof e?e:e?.constructor,s=r&&"function"==typeof J.registeredFlavour?J.registeredFlavour(r):void 0;if(s&&s!==Z)return s;const i=Re._currentFlavour;if(i){const e=Re._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return Z}};class Re extends xe{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Re._baseRepository)throw new l("This should be overridden when necessary. Otherwise it will be replaced lazily");return Re._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new l("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.alias in Re._cache)throw new l(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Re._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Re._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Re._currentFlavour=this.alias)}Dispatch(){return new Re._baseDispatch}ObserverHandler(){return new be}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new Re._baseSequence(e,this,t)}async flags(e,t,r,...s){if("string"==typeof t)throw new l("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(t)?t.length?t[0]:void 0:t,n=i?F.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${e}-${Pe.instance.generate()}`;const o=r.logger||I.for(this);return Object.assign({},pe,r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:he.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?J.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:o})}get Context(){return ve}async context(e,t,r,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>F.tableName(e)):F.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof ve||(s.push(i),i=void 0),t=i?Object.assign({},i.toOverrides(),t):t;const n=await this.flags("string"==typeof e?e:e.name,r,t,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context))return(new this.Context).accumulate({...i.cache,...n,parentContext:i});const t=i.get("operation"),s=i.getOrUndefined("affectedTables");return t!==e||r&&r!==s?(new this.Context).accumulate({...i.cache,...n,parentContext:i}):i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(e,...t){const{log:r}=this.logCtx(t,this.prepare),s=e.segregate(),i=Object.entries(s.model).reduce((t,[r,s])=>{if(void 0===s)return t;const i=F.columnName(e.constructor,r);if(this.isReserved(i))throw new l(`Property name ${i} is reserved`);return t[i]=s,t},{});return e[de.METADATA]&&(r.silly("Passing along persistence metadata for "+e[de.METADATA]),Object.defineProperty(i,de.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:e[de.METADATA]})),{record:i,id:e[F.pk(e.constructor)],transient:s.transient}}revert(e,t,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=F.pk(t),c=new t;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const d=e[de.METADATA],u=Object.keys(c).filter(e=>e!==a).reduce((r,s)=>(r[s]=e[F.columnName(t,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u&&void 0!==u[e])throw new l(`Transient property ${e} already exists on model ${c.constructor.name}. should be impossible`);u[e]=t})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,de.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(e,t,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new u("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new u("Ids and models must have the same length");const o=F.tableName(e);return i.debug(`Creating ${t.length} entries ${o} table`),Ne(t.map((t,i)=>()=>this.create(e,t,r[i],...s,n.override({noEmitSingle:!0}))))}async readAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=F.tableName(e);return s.debug(`Reading ${t.length} entries ${n} table`),Ne(t.map(t=>()=>this.read(e,t,...r,i.override({noEmitSingle:!0}))))}async updateAll(e,t,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new l("Ids and models must have the same length");const o=F.tableName(e);return i.debug(`Updating ${t.length} entries ${o} table`),Ne(t.map((t,i)=>()=>this.update(e,t,r[i],...s,n.override({noEmitSingle:!0}))))}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),Ne(t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0}))))}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);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(e){return J.flavourOf(e)}static get currentFlavour(){if(!Re._currentFlavour)throw new l("No persistence flavour set. Please initialize your adapter");return Re._currentFlavour}static get current(){return Re.get(this.currentFlavour)}static get(e){if(!e)return Re.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new l(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return J.flavouredAs(e).filter(F.isModel)}catch(e){throw new l(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(e)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(t,r,i)=>{if("_config"===r){const s=Reflect.get(t,r,i);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,i)},set:(e,t,r,i)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,i)});return this.proxies[r]=i,i}migrations(){return J.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,s){return super.logCtx(e,t,r,s)}}i([L(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],Re.prototype,"shutdownProxies",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,ve]),n("design:returntype",Promise)],Re.prototype,"context",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Re.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Re.prototype,"unObserve",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],Re.prototype,"client",null);class Ie extends l{constructor(e){super(e,Ie.name,500)}}class Le extends l{constructor(e){super(e,Le.name,500)}}class ke extends F{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):F.fromModel(this,e)}and(e){return ke.and(this,e)}or(e){return ke.or(this,e)}not(e){return new ke(this,ae.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof ke)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ae).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof ke){if(!(this.comparison instanceof ke)&&this.operator!==ae.NOT)return{comparison:{condition:e}};if(-1===Object.values(ce).indexOf(this.operator)&&this.operator!==ae.NOT)return{operator:{condition:e}}}},r=super.hasErrors(...e);return this.isAsync()?(async()=>await Promise.resolve(r)??t())():r??t()}static and(e,t){return ke.group(e,ce.AND,t)}static or(e,t){return ke.group(e,ce.OR,t)}static group(e,t,r){return new ke(e,t,r)}static attribute(e){return(new ke.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(e){return this.setOp(ae.EQUAL,e)}dif(e){return this.setOp(ae.DIFFERENT,e)}gt(e){return this.setOp(ae.BIGGER,e)}lt(e){return this.setOp(ae.SMALLER,e)}gte(e){return this.setOp(ae.BIGGER_EQ,e)}lte(e){return this.setOp(ae.SMALLER_EQ,e)}in(e){return this.setOp(ae.IN,e)}regexp(e){return this.setOp(ae.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new ke(this.attr1,this.operator,this.comparison)}catch(e){throw new Ie(e)}}}}static builder(){return new ke.Builder}static from(e){return new ke(e)}}var Fe,je;i([U(),n("design:type",Object)],ke.prototype,"attr1",void 0),i([U(),n("design:type",String)],ke.prototype,"operator",void 0),i([U(),n("design:type",Object)],ke.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(Fe||(Fe={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(je||(je={}));const Ue={update:je.CASCADE,delete:je.NONE},Ye={Equals:(e,t)=>ke.attribute(e).eq(t),Diff:(e,t)=>ke.attribute(e).dif(t),LessThan:(e,t)=>ke.attribute(e).lt(t),LessThanEqual:(e,t)=>ke.attribute(e).lte(t),GreaterThan:(e,t)=>ke.attribute(e).gt(t),GreaterThanEqual:(e,t)=>ke.attribute(e).gte(t),In:(e,t)=>ke.attribute(e).in(t),Matches:(e,t)=>ke.attribute(e).regexp(t)},Me=e=>e.charAt(0).toLowerCase()+e.slice(1);class qe extends R{static get log(){return this._logger||(this._logger=I.for(qe.name)),this._logger}static build(e,...t){if(!e.startsWith(oe.FIND_BY))throw Error("Unsupported method "+e);const r=this.extractCore(e),s=this.extractSelect(e),i=this.extractGroupBy(e),n=this.buildWhere(r,t),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(e,t);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(e){const t=e.substring(oe.FIND_BY.length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?t.substring(0,r.index):t}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(e){const t=e.indexOf(oe.SELECT);if(-1===t)return;const r=e.substring(t+oe.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(oe.AND).map(Me).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(oe.GROUP_BY);if(-1!==t)return e.substring(t+oe.GROUP_BY.length).split(oe.ORDER_BY)[0].split(oe.THEN_BY).map(Me).filter(Boolean)}static buildWhere(e,t){if(!e&&0===t.length)return;const r=(e.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=e.match(/And|Or/g)||[];let i;if(r.forEach((e,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(e),a=o?Ye[o]:Ye.Equals;if(!a)throw Error("Unsupported operator "+o);const c=t[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===oe.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(e){for(const t of Object.keys(Ye))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:Me(r),operator:t}}return{field:Me(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(e,t){const r=qe.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new Ie("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(Fe).includes(t))throw new Ie(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Fe).join(", ")}.`);return[[e,t]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let i,n,o;if(s.at(-1)instanceof d&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);i=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function Ge(){return X.for(de.STATEMENT).define({decorator:()=>(e,t,r)=>K(ee(J.key(de.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function ze(e={}){return X.for(de.QUERY).define({decorator:e=>(t,r,s)=>{const i=qe.getFieldsFromMethodName(r);return K(ee(J.key(de.QUERY,r),{...e,fields:i}),Ge(),(e=>(t,r,s)=>{s.value=new Proxy(s.value,{apply(t,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=qe.build(t.name,...s);let d=r.select(i);n&&(d=d.where(n));const{allowLimit:u,allowOffset:p,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(a||[])[0],allowed:h},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:p}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&g)throw new Ie(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()}})})(e))(t,r,s)},args:[e]}).apply()}function He(e){return Ze(e,[a.CREATE,c.CREATE_ALL])}function Qe(e){return Ze(e,[a.UPDATE,c.UPDATE_ALL])}function Ve(e){return Ze(e,[a.DELETE,c.DELETE_ALL])}function We(e){return Ze(e,he)}function Je(e){return Ze(e,Object.values(a))}function Xe(e){return Ze(e,Object.values(c))}function Ze(e,t){return(r,s,i,...n)=>{if("string"==typeof e)throw new l("clazz cannot be string. This should be impossible");const{log:o}=Ae.prototype.logCtx(n,Ze);return o.silly(`filtering ${s} event for${r?" "+(F.tableName(r)||r):""} ${i}`),("string"==typeof r?r===F.tableName(e)||r===e.constructor.name:J.constr(e)===J.constr(r))&&t.includes(s)}}const Ke={onlyOnCreate:He,onlyOnUpdate:Qe,onlyOnDelete:Ve,onlyOnTransactional:We,onlyOnSingle:Je,onlyOnBulk:Xe};function et(e){const t=Object.assign({},Ke);return Object.entries(t).forEach(([r,s])=>{t[r]=s(e.class)}),t}class tt extends p{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 l("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=F.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return et(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(tt.register(t,this,this.adapter.alias),e)&&J.get(t,te.FLAVOUR)===Z&&re(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;h(s,s[t+"Prefix"],e,s[t+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,s){const i=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},s||{},this._overrides||{}));function n(e){return e.ctxArgs.shift(),e}return i instanceof Promise?i.then(n):n(i)}override(e){return new Proxy(this,{get:(t,r,s)=>{const i=Reflect.get(t,r,s);return"_overrides"!==r?i:Object.assign({},i,e)}})}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(e,...t):Reflect.get(r,s,i)})}ObserverHandler(){return new be}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await f(this,r,e,a.CREATE,a.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new u(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${F.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let a=n.map(e=>e.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((e,t)=>this.adapter.revert(e,this.class,o[t],r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!e.length)return[e,...s];const d=F.sequenceFor(e[0]);let p=[];if(F.generatedBySequence(this.class)?(d.name||(d.name=F.sequenceName(e[0],"pk")),p=await(await this.adapter.Sequence(d)).range(e.length,...s)):F.generated(this.class,this.pk)||(p=e.map((e,t)=>{if(void 0===e[this.pk])throw new l("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),d.type&&(e[this.pk]="String"!==d.type||d.generated?p[t]:""+e[this.pk]),n||await f(this,r,e,a.CREATE,a.ON),e))),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=y(s);if(n)throw new u(n)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await f(this,r,o,a.READ,a.ON),[e,...s]}async read(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${F.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,f(this,r,t,a.READ,a.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${F.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}async update(e,...t){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${F.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=e[this.pk];if(!c)throw new l("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(c,r),r.get("mergeForUpdate")&&(e=F.merge(d,e,this.class))),n||await f(this,r,e,a.UPDATE,a.ON,d),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new u(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const d=e.map(e=>{const t=e[this.pk];if(!t)throw new l("missing id on update operation");return t});let p;if(r.get("applyUpdateValidation")&&(p=await this.readAll(d,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>F.merge(p[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>f(this,r,e,a.UPDATE,a.ON,p?p[t]:void 0))),!o){const t=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(p[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=y(s);if(n)throw new u(n)}return[e,...s,p]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await f(this,r,t,a.DELETE,a.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${F.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>f(this,r,e,a.DELETE,a.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${F.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(e,t,r=Fe.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,de.QUERY,!0)).for(this.query),a=[t,r],c=this.select().where(e).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${F.tableName(this.class)} by ${e} ${t}`),this.select().orderBy([e,t]).execute(...i)}async paginateBy(e,t,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new Ie("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:d}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);let u;if(c.verbose(`paginating ${F.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>t===Fe.ASC?this.attr(F.pk(this.class)).gt(o):this.attr(F.pk(this.class)).lt(o))()).orderBy([e,t]).paginate(a,...d);else{if(!n)throw new Ie("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,t]).paginate(a,...d)}const p=await u.page(i,o,...d);return u.serialize(p)}async findOneBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${F.tableName(this.class)} with ${e} ${t}`);const n=await this.select().where(this.attr(e).eq(t)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${F.tableName(this.class)} with ${e} ${t}`),this.select().where(this.attr(e).eq(t)).execute(...i)}async statement(e,...t){if(!tt.statements(this,e))throw new Ie("Invalid prepared statement requested "+e);const{log:r,ctxArgs:s}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+e),this[e](...s)}attr(e){return ke.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=F.tableName(this.class);return this.adapter.observe(this,(e,t,r,...i)=>"string"==typeof e?e===s:J.constr(e)===J.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("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 l("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>Re._baseSequence.parseValue(F.sequenceFor(this.class).type,e)):Re._baseSequence.parseValue(F.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}static forModel(e,t,...r){let s;const i=t||J.flavourOf(e)||Re.currentFlavour;try{s=this.get(e,i)}catch(e){s=void 0}if(s instanceof tt)return s;const n=t||J.flavourOf(e)||s&&J.get(s,de.ADAPTER)||Re.currentFlavour,o=n?Re.get(n):void 0;if(!o)throw new l("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,e,...r)}static get(e,t){const r=F.tableName(e);let s=r;if(t&&(s=[r,t].join(b)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new l("Could not find repository registered under "+r)}static register(e,t,r){let s=F.tableName(e);if(r&&(s=[s,r].join(b)),s in this._cache&&this._cache[s]instanceof tt)throw new l(s+" already has a registered instance");this._cache[s]=t}static statements(e,t){const r=e instanceof tt?e.constructor:e,s=J.get(r,t?J.key(de.STATEMENT,t):de.STATEMENT);return(t?s:Object.keys(s))||!1}static queries(e,t){const r=e instanceof tt?e.constructor:e;return J.get(r,t?J.key(de.QUERY,t):de.QUERY)}}function rt(e,t){if(!(t||(t=X.flavourResolver(e instanceof F?e.constructor:e))&&t!==Z))throw new l("Could not retrieve flavour from model "+(e instanceof F?e.constructor.name:e.name));return Y(de.INJECTABLE,t,F.tableName(e))}i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],tt.prototype,"listBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"paginateBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"findOneBy",null),i([Ge(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],tt.prototype,"findBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],tt.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],tt.prototype,"unObserve",null),Re&&(Re._baseRepository=tt);class st extends e{get log(){return this.logger||(this.logger=I.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=F.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=F.get(e.toString())),!n)return;const o=de.ADAPTER,a=r||J.get(n,o);try{let e=a;try{a&&Re.get(a)}catch{const t=Re.current;t&&t.flavour===a&&(e=t.alias)}if(i=tt.forModel(n,e),i instanceof tt)return i;const r=a||J.get(i.constructor,o)||J.get(n,o);t.register(i,rt(n,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=tt.get(n,a);if("function"==typeof t){const e=a?Re.get(a):Re.current;if(!e)return;return new t(e,n)}}}return i}}var it,nt,ot,at,ct;(e=>{e.PENDING="pending",e.RUNNING="running",e.FAILED="failed",e.SUCCEEDED="succeeded",e.CANCELED="canceled",e.WAITING_RETRY="waiting_retry"})(it||(it={})),(e=>{e.EXPONENTIAL="exponential",e.FIXED="fixed"})(nt||(nt={})),(e=>{e.NONE="none",e.FULL="full"})(ot||(ot={})),(e=>{e.STATUS="status",e.LOG="log",e.PROGRESS="progress",e.ALL="all"})(at||(at={})),(e=>{e.ATOMIC="atomic",e.COMPOSITE="composite"})(ct||(ct={})),J.tasks=(()=>J.innerGet(Symbol.for("tasks"))).bind(J),J.taskFor=(e=>{const t=J.tasks();return t?t[e]:void 0}).bind(J),J.validationExceptions=((e,t)=>{const r=J.get(e,de.NO_VALIDATE)||[],s=Object.entries(r).filter(([,e])=>e.includes(t)).map(([e])=>e);let i=[];return t!==a.CREATE&&t!==a.UPDATE||(i=F.nestedRelations(e)),[...new Set([...s,...i])]}).bind(J),J.migrationsFor=(e=>{if(!(e=e??Re.current))throw new l("Could not get adapter for migrations");return J.innerGet(Symbol.for(de.MIGRATION),e.alias).map(e=>e.class)}).bind(J),J.migrations=(()=>{const e=J.innerGet(Symbol.for([de.MIGRATION,de.BY_KEY].join("-")));return Object.values(e).flat().map(e=>[e.class.name,e.class])}).bind(J),J.relations=((e,t)=>{const r=J.get(e,de.RELATIONS);if(r){if(!t)return Object.keys(r);if(!r[t])throw new l("No relations metadata found for property "+t);return r[t]}}).bind(J),F.relations=(e,t)=>J.relations(e instanceof F?e.constructor:e,t)||[],F.nestedRelations=((e,t=[])=>{let r=[];const s=J.get(e,de.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...t])];for(const e in s){const i=s[e];if(i?.class&&F.relations(i.class)){const s=F.relations(i.class).map(t=>`${e}.${t}`);t=[...t,...s],r=F.nestedRelations(i.class,t)}}return[...new Set([...t,...r])]}).bind(F),F.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!F.sequenceFor(r).generated}).bind(F),F.fromTable=(e=>{const t=J.innerGet(Symbol.for(de.TABLE));if(!t||!t[e]||!F.get(t[e].name))throw new l("No table metadata found for model. did you use @table()?");return F.get(t[e].name)}).bind(F),J.createdBy=(e=>{const t=J.get("function"!=typeof e?e.constructor:e,de.CREATED_BY);if(!t)throw new l("No createdBy metadata found for model. did you use @createdBy()?");return t}).bind(J),J.updatedBy=(e=>{const t=J.get("function"!=typeof e?e.constructor:e,de.UPDATED_BY);if(!t)throw new l("No updatedBy metadata found for model. did you use @updatedBy()?");return t}).bind(J),F.tableName=e=>{if(!(e instanceof F?F.get(e.constructor.name):e))throw new l("Unable to find model "+e);return J.get(e instanceof F?e.constructor:e,de.TABLE)||(e instanceof F?e.constructor.name:e.name)},F.columnName=(e,t)=>J.get(e instanceof F?e.constructor:e,J.key(de.COLUMN,t))||t,F.sequenceName=(e,...t)=>[F.tableName(e),...t].join("_"),F.sequenceFor=(e,t)=>{if(t)throw new Ee("not currently supported");const r=F.pkProps(e instanceof F?e.constructor:e);if(!r)throw new l("No sequence options defined for model. did you use the @pk decorator?");return r},F.indexes=e=>{const t=J.get(e instanceof F?e.constructor:e,de.INDEX);return Object.keys(t||{}).reduce((e,r)=>(e[r]={[de.INDEX]:t[r]},e),{})},t.services=()=>J.innerGet(Symbol.for(de.SERVICE)),t.repositories=()=>J.innerGet(Symbol.for(w.REPOSITORY));class lt extends Ae{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new l("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...e){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:t}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize);t.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(e=>{if(!r[e])throw new l(`Method ${e} not found in ${r.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(r,e),s=r;for(;!t&&s!==Object.prototype;)s=Object.getPrototypeOf(s),t=Object.getOwnPropertyDescriptor(s,e);function i(e){switch(e){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return e}}t&&t.writable?r[e]=new Proxy(r[e],{apply:async(t,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),t),[c,l,d]=s,u=await t.call(r,c,l,d,...o),p=[c,i(e),l];return a.get("observeFullResult")&&p.push(u),this.updateObservers(...p,...o).catch(t=>n.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof Re))throw new Ee("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=Re.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(this.adapter!==e)throw new Ee("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){if(!e)throw new l("Model must be provided for observer update");const i=e&&"string"==typeof e?e:F.tableName(e),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...o)}catch(e){throw new l("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function dt(e,t,r,s){if(e.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=t;i&&"function"==typeof i&&(i=i(s,...n||[],e)),s[r]=await Pe.instance.generate(i)}function ut(e=!1,t,...r){"function"==typeof e&&(t=e,e=!1);const s=de.UUID;return X.for(s).define({decorator:(e,t,...r)=>{const s={update:e,seed:t,args:r},i=[U(),v(de.UUID),A(dt,s,{priority:54})];return e&&i.push(x(dt,s,{priority:54})),e||i.push(E()),K(...i)},args:[e,t,...r]}).apply()}async function pt(e,t,r,s,i){const n=t.logger.for(pt);if(!s){const t=F.get(e.constructor.name);if(!t)throw new l("Could not find model "+e.constructor.name);s=tt.forModel(t,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===e[F.pk(s.class)])n.info(`No pk found in ${F.tableName(s.class)} - creating`),o=await s.create(e,t);else{n.info(`pk found in ${F.tableName(s.class)} - attempting update`);try{o=await s.update(e,t),n.info("Updated "+F.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+F.tableName(s.class)),o=await s.create(e,t)}n.info("After create update: "+o)}return o}async function ht(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=St(s,r,this.adapter.alias),n=await t.read(i,e);return await At(e,s,r,i,n),void(s[r]=i)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new l("Could not find model "+t.class);const o=tt.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,e),c=F.pk(a);await At(e,s,r,a[c],a),s[r]=a[c]}async function gt(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==je.CASCADE)return;if("object"!=typeof i){const t=St(s,r,this.adapter.alias),n=await t.override(this._overrides).read(i,e);return await At(e,s,r,i,n),void(s[r]=i)}const n=await pt(s[r],e,this.adapter.alias,void 0,this._overrides),o=F.pk(n);await At(e,s,r,n[o],n),s[r]=n[o]}async function ft(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==je.CASCADE)return;const n=St(s,r,this.adapter.alias);let o;o=i instanceof F?await n.delete(s[r][n.pk],e):await n.delete(s[r],e),await At(e,s,r,o[n.pk],o)}async function yt(e,t,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o=e.logger.for(yt),a=new Set([...i]);if("object"!==n){const t=St(s,r,this.adapter.alias),i=await t.readAll([...a.values()],e);for(let t=0;t<i.length;t++){const s=i[t];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await At(e,s,r,[...a.values()][t],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=F.pk(i[0].constructor),d=new Set;for(const t of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(t));const i=await pt(t,e,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await At(e,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(t)),d.add(i[c])}s[r]=[...d]}async function mt(e,t,r,s){const{cascade:i}=t;if(i.update===je.CASCADE)return yt.call(this,e,t,r,s)}async function bt(e,t,r,s){if(t.cascade.delete!==je.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof t.class||t.class.name?t.class:t.class(),a="object"===n,c=a?tt.forModel(o,this.adapter.alias):St(s,r,this.adapter.alias),d=[...new Set([...a?i.map(e=>e[c.pk]):i]).values()];let u,p;try{u=await c.deleteAll(d,e)}catch(t){throw e.logger.error("Failed to delete all records",t),t}for(let t=0;t<u.length;t++){p=u[t];try{await At(e,s,r,d[t],p)}catch(i){throw e.logger.error(`Failed to cache record ${d[t]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=d}function wt(e,t,r){return[de.POPULATE,e,t,r].join(".")}function vt(e,t,r){return[de.TAG_FOR_DELETION,e,r].join(".")}async function At(e,t,r,s,i){const n=wt(t.constructor.name,r,s),o=e.get("cacheForPopulate")||{};return o[n]=i,e.accumulate({cacheForPopulate:o})}async function xt(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,r,s,i)=>{let n,o;const a=[],c=t.get("cacheForPopulate")||{};for(const t of i){n=wt(r.constructor.name,s,t);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=St(r,s);if(!n)throw new l("Could not find repo");o=await n.read(t,e)}a.push(o)}return a})(e,s,r,n?i:[i]);s[r]=n?o:o[0]}async function Et(e,t,r,s,i){if(t.cascade.update!==je.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new l("No way to compare old model. do you have updateValidation and mergeModels enabled?");function o(e){return Array.isArray(e)?e.map(o):"object"!=typeof e?e:e[F.pk(e)]}const a=o(s[r]),c=o(i[r]);if(M(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new l("Cannot cascade update for different array types");const d=(Array.isArray(a)?a:[a]).filter(Boolean),u=(Array.isArray(c)?c:[c]).filter(Boolean).filter(e=>!d.includes(e)),p=St(s,r);if(!p)throw new l("Could not find repo");try{const t=await p.deleteAll(u,e);e.logger.debug(`Deleted ${t.length} entries from table ${F.tableName(p.class)} due to cascade rules with `)}catch(e){throw new l("Error deleting cascade entries: "+e)}}Re&&(Re._baseDispatch=lt);const Ot=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function St(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=J.get(e instanceof F?e.constructor:e,J.key(q.REFLECT,t,q.LIST))?.clazz;if(!r)throw new l("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=J.getPropDesignTypes(e instanceof F?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!Ot.includes((""+e.name).toLowerCase()));return tt.forModel(i,r)}class Ct extends O{constructor(e,t=Ct.name,r=401){super(e,t,r)}}class Nt extends Ct{constructor(e,t=Nt.name){super(e,t,403)}}class Tt extends l{constructor(e){super(e,Tt.name,503)}}function _t(e){return X.for(de.TABLE).define({decorator:e=>t=>(J.set(de.TABLE,e||t.name.toLowerCase(),t),se(de.TABLE,e||t.name.toLowerCase())(t)),args:[e]}).apply()}function Bt(e){return X.for(de.COLUMN).define({decorator:e=>(t,r)=>ie(J.key(de.COLUMN,r),e||r)(t,r),args:[e]}).apply()}function Pt(e,t,r){return X.for(de.INDEX).define({decorator:(e,t,r)=>(s,i)=>("string"==typeof e&&(r=e,e=void 0,t=void 0),"string"==typeof t&&(r=t,t=void 0),!t&&e&&e.find(e=>![Fe.ASC,Fe.DSC].includes(e))&&(t=e,e=void 0),ie(J.key(`${de.INDEX}${t&&t?.length?"."+t.join("."):""}`,i),{directions:e,compositions:t,name:r})(s,i)),args:[e,t,r]}).apply()}async function $t(e,t,r,s){if(s[r]&&(await this.select().where(ke.attribute(r).eq(s[r])).execute()).length)throw new C(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Dt(){const e=de.UNIQUE;return X.for(e).define(G(),N($t),ie(e,{})).apply()}async function Rt(e,t,r,s){throw new Ct("This adapter does not support user identification")}function It(){return X.for(de.CREATED_BY).define({decorator:()=>(e,t)=>K(A(Rt),ie(de.CREATED_BY,t),v(de.CREATED_BY))(e,t),args:[]}).apply()}function Lt(){return X.for(de.UPDATED_BY).define({decorator:()=>(e,t)=>K(x(Rt),ie(de.UPDATED_BY,t),v(de.UPDATED_BY))(e,t),args:[]}).apply()}function kt(){return T([a.CREATE])}function Ft(){return T()}function jt(e){const t="function"==typeof e&&e.name?e:e(),r=F.pk(t);return J.allowedTypes(t,r)||[]}function Ut(e,t=Ue,r=!0,s,i){const n=de.ONE_TO_ONE;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),z([e,...a]),A(ht,o,{priority:70}),x(gt,o,{priority:70}),_(ft,o,{priority:70}),B(Et,o,{priority:70}),P(xt,o,{priority:70})];return K(...c)},args:[e,t,r,s,i]}).apply()}function Yt(e,t=Ue,r=!0,s,i){const n=de.ONE_TO_MANY;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),H([e,...a]),A(yt,o,{priority:70}),x(mt,o,{priority:70}),_(bt,o,{priority:70}),B(Et,o,{priority:70}),P(xt,o,{priority:70})];return K(...c)},args:[e,t,r,s,i]}).apply()}function Mt(e,t=Ue,r=!0,s,i){const n=de.MANY_TO_ONE;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),z([e,...a])];return K(...c)},args:[e,t,r,s,i]}).apply()}function qt(e,t=Ue,r=!0,s,i){const n=de.MANY_TO_MANY;return X.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=jt(e),c=[ne(),Vt(n,o),H([e,...a])];return K(...c)},args:[e,t,r,s,i]}).apply()}function Gt(...e){return(t,r)=>{const s=J.get(t,J.key(de.NO_VALIDATE,r))||[],i=[...new Set([...s,...e])];return K(se(J.key(de.NO_VALIDATE,r),i))(t,r)}}function zt(){return Gt(a.CREATE)}function Ht(){return Gt(a.UPDATE)}function Qt(){return Gt(a.UPDATE,a.CREATE)}function Vt(e,t){return X.for(de.RELATIONS).define({decorator:(e,t)=>(r,s)=>(ie(e,t)(r,s),ie(J.key(de.RELATIONS,s),Object.assign({},t,{key:e}))(r,s)),args:[e,t]}).apply()}class Wt extends F{constructor(e){super(e)}}i([kt(),n("design:type",Date)],Wt.prototype,"createdAt",void 0),i([Ft(),n("design:type",Date)],Wt.prototype,"updatedAt",void 0);const Jt={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Xt=Jt,Zt={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Kt=Object.assign({},Zt,{type:"BigInt"});async function er(e,t,r,s){if(!t.type||!t.generated||s[r])return;let i;t.name||(t.name=F.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new l(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,o,a;n=s,o=r,a=await i.next(e),Reflect.set(n,o,a)}function tr(e,t){return(r,s)=>{if(ne()(r,s),!e.type){const t=J.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(t?.name||t))throw Error("Incorrrect option type");e.type=t}switch(e.type){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated,e.type=String;break;case Number.name||String.name.toLowerCase():case Number:e.generated=void 0===e.generated||e.generated,e.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:e.type=BigInt,e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;default:throw Error("Unsupported type")}void 0===e.generated&&(e.generated=!0);const i=[Pt([Fe.ASC,Fe.DSC]),ne(),U(),E(),ie(J.key(w.ID,s),e),A(er,e,t)];return e.generated&&i.push(v()),K(...i)(r,s)}}function rr(e){const t=Object.assign({},Xt);return delete t.generated,e=Object.assign({},t,e),X.for(w.ID).define({decorator:tr,args:[e,{priority:60}]}).apply()}let sr=class extends Wt{constructor(e){super(e)}};i([rr({type:String,generated:!1}),n("design:type",String)],sr.prototype,"id",void 0),i([U(),Pt(),n("design:type",Object)],sr.prototype,"current",void 0),sr=i([_t("??sequence"),Q(),n("design:paramtypes",[Object])],sr);class ir extends Ae{static{this.lock=new W}constructor(e,t,r={}){super(),this.options=e,this.adapter=t,this.repo=tt.forModel(sr,t.alias).override(r)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof m){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new l("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new l(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new l(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(e,t){const{log:r,ctx:s}=this.adapter.logCtx([t],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new l("Sequence name is required");return ir.lock.execute(async()=>{const t=e||n;if(t%n!==0)throw new l("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),d=async e=>{try{return await this.repo.update(new sr({id:o,current:e}),s)}catch(t){if(t instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${e}`),this.repo.create(new sr({id:o,current:e}),s);throw t}};if("uuid"===a)for(;;){const e=await Promise.resolve(Pe.instance.generate(c));try{const t=await d(e);return r.debug(`Sequence uuid increment ${o} current=${c} next=${e}`),t.current}catch(e){if(e instanceof C)continue;throw e}}const u=await(async e=>{switch(a){case Number.name:return this.parse(e)+t;case BigInt.name:return this.parse(e)+BigInt(t);case String.name:return this.parse(e);case"serial":return await Promise.resolve($e.instance.generate(e));default:throw new l("Should never happen")}})(c),p=await d(u);return r.debug(`Sequence.increment ${o} current=${c} next=${u}`),p.current},o)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ee(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new l("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return ir.parseValue(this.options.type,e)}logCtx(e,t,r=!1){const s=this.adapter.logCtx([sr,...e],t,r);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return F.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 Ee(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function nr(e,t){return(i,n)=>n?r(J.constr(e))(i,n):(J.set(w.REPOSITORY,J.key(t||Re.currentFlavour,F.tableName(e)),i),se(w.REPOSITORY,i.name)(e),t=t||J.get(i.constructor,de.ADAPTER),tt.register(e,i,t),s(J.constr(e),{callback:t=>(Object.defineProperty(t,w.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}Re._baseSequence=ir;class or extends l{constructor(e){super(e,or.name,500)}}class ar extends R{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,s){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=s,Be(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${le.FIND_BY}|${le.LIST_BY}`,"gi"))}async pagePrefix(e,...t){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...t],le.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[e,...r]}async pagePrepared(e,t,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!t||t instanceof ve?[t,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${e} page${t?" - bookmark "+t:""}`),!t||t instanceof ve||(this._bookmark=t);const n=tt.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,d=RegExp(`^${le.FIND_BY}|${le.LIST_BY}`,"gi");if(!a.match(d))throw new Ee(`Method ${a} is not supported for pagination`);d.lastIndex=0;const u=a.replace(d,le.PAGE_BY),p=[u,...c];let h={limit:this.size,offset:e,bookmark:this._bookmark};u!==le.PAGE_BY||p.length>2?h={direction:l.direction,limit:this.size,offset:e,bookmark:this._bookmark}:p.push(l.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}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 Le("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new Le(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:s}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...s);throw new Ee("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new $(e)}}apply(e){const t="string"==typeof e?ar.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new $(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var cr,lr,dr,ur;class pr extends Ae{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{D(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...t],e.name===this.paginate.name?le.PAGE_BY:de.QUERY,!0,this.overrides||{})).for(e);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(pr)}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?F.get(e):e,!this.fromSelector)throw new Ie("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{log:t,ctxArgs:r}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();return t.silly("executing raw statement"),await this.raw(s,...r)}catch(e){throw new Ie(e)}}async executePrepared(...e){const t=tt.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return t.statement(r,...s,i,...e)}async raw(e,...t){const{ctx:r,ctxArgs:s}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new Ee("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(e,!0,...s);if(!this.selectSelector)return i;const n=F.pk(this.fromSelector),o=function(e){const t=e[n];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(e,t){let{attr1:r,operator:s,comparison:i}=e;const n={};switch(s){case ce.AND:case ce.OR:{let e=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,t);e=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof ke){const e=this.prepareCondition(i,t);o=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${o}`;break}case ae.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ae.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ae.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ae.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ae.BIGGER_EQ:n.method=r+" bigger than equal";break;case ae.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ae.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ae.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Ie("Unsupported operator "+s)}return n}squash(e){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let t;if(this.whereCondition){if(this.whereCondition.comparison instanceof ke)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,Fe.DSC]:[F.pk(this.fromSelector),Fe.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:le.LIST_BY,args:[s],params:n};return t&&(o.method=le.FIND_BY,o.args=[t,this.whereCondition.comparison],o.params=n),o}async prepare(e){if(e=e||await this.adapter.context(de.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},s={class:this.fromSelector,args:t,params:r},i=[oe.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);i.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&i.push(oe.SELECT,this.selectSelector.join(` ${oe.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(oe.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(oe.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=k(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new Ie(e)}}toString(){return this.adapter.flavour+" statement"}}i([L(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"select",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(cr="undefined"!=typeof S&&S)?cr:Object]),n("design:returntype",Object)],pr.prototype,"distinct",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(lr="undefined"!=typeof S&&S)?lr:Object]),n("design:returntype",Object)],pr.prototype,"max",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(dr="undefined"!=typeof S&&S)?dr:Object]),n("design:returntype",Object)],pr.prototype,"min",null),i([L(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ur="undefined"!=typeof S&&S)?ur:Object]),n("design:returntype",Object)],pr.prototype,"count",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"from",null),i([L(),n("design:type",Function),n("design:paramtypes",[ke]),n("design:returntype",Object)],pr.prototype,"where",null),i([L(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"orderBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"groupBy",null),i([L(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"limit",null),i([L(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"offset",null),i([L(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],pr.prototype,"execute",null);class hr extends Ae{constructor(e){super(),this.name=e,this.observers=[],this.Context=ve}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new be,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${Pe.instance.generate()}`;const s=t.logger||I.for(this);return s.setConfig({correlationId:t.correlationId}),Object.assign({},ue,t,{args:r,timestamp:new Date,operation:e,logger:s})}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let s=r.pop();void 0===s||s instanceof ve||(r.push(s),s=void 0),t=s?Object.assign({},s.toOverrides(),t):t;const i=await this.flags("string"==typeof e?e:e.name,t,...[...r,s].filter(Boolean));return s?s instanceof this.Context?s.get("operation")!==e?(new this.Context).accumulate({...s.cache,...i,parentContext:s}):s.accumulate(i):(new this.Context).accumulate({...s.cache,...i,parentContext:s}):(new this.Context).accumulate({...i})}logCtx(e,t,r=!1,s){return Ae.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new l("No name provided");const r=Ce(e),s=t.get(r);if(s)return s;throw new l("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){let r=e.pop();void 0===r||r instanceof ve||(e.push(r),r=void 0);const s=await hr.prototype.flags(de.INITIALIZATION,{},...e);r=r?new ve(r).accumulate({...s,parentContext:r}):(new ve).accumulate(s),e=[...e,r];const{log:i,ctxArgs:n}=hr.prototype.logCtx(e,this.boot),o=t.services();for(const[e,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=t.get(r);if(!s)throw new l("Failed to resolve injectable for "+e);s instanceof gr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new l(`Failed to boot ${e} service:${t}`)}}}i([L(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],hr.prototype,"observe",null),i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],hr.prototype,"unObserve",null);class gr extends hr{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.boot);t.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new l("Config not initialized");return this._config}get client(){if(!this._client)throw new l("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...`)}}function fr(e){return function(t,r,s){const i=s.value;return s.value=function(...t){const r=this.class;if(r&&Te(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,t)},s}}i([L(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],gr.prototype,"boot",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"config",null),i([L(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"client",null);const yr=()=>fr(a.CREATE),mr=()=>fr(a.READ),br=()=>fr(a.UPDATE),wr=()=>fr(a.DELETE);function vr(e){return(t,i,n)=>{n||i?(ne()(t,i),e=e||J.type(t.constructor,i)):e=e||t,e=Ce(e);const o=[];if(n&&"number"==typeof n.value)o.push(r(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(e))}else J.set(de.SERVICE,e,t),o.push(s(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return K(...o)(t,i,n)}}const Ar=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class xr extends hr{get class(){if(!this.clazz)throw new l("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=tt.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new l("No name provided");const t=Ar(e);try{const e=hr.get(t);if(e)return e}catch(e){}throw new l("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(e,...t):Reflect.get(r,s,i)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.QUERY,!0)).for(this.query),s=this.repo?.[e];if("function"!=typeof s)throw new l(`Method "${e}" is not implemented`);return s.apply(this.repo,r)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(e,t,...s)}async paginateBy(e,t,r,...s){const{ctxArgs:i}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(e,t,r,...i)}async findOneBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(e,t,...s)}async findBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(e,t,...s)}async statement(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return this.repo.statement(e,...r)}static forModel(e,t){let r;t=Ar(t||e);try{r=xr.get(t)}catch(e){r=void 0}if(r instanceof xr)return r;const s=this;let o=class extends s{constructor(){super(e)}};return o=i([vr(t),n("design:paramtypes",[])],o),new o}refresh(e,t,r,...s){return this.repo.refresh(e,t,r,...s)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...s){return this.repo.updateObservers(e,t,r,...s)}logCtx(e,t,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}}i([yr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"create",null),i([yr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"createAll",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"delete",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"deleteAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"read",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],xr.prototype,"readAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],xr.prototype,"query",null),i([br(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],xr.prototype,"update",null),i([br(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],xr.prototype,"updateAll",null);class Er extends gr{constructor(){super()}async initialize(...e){const t=e.shift();if(!t||!Array.isArray(t)||t instanceof ve||!t.every(e=>Array.isArray(e)))throw new l("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize),i=t.map(([e,t,...s])=>{try{r.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const i=new e(t,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(t){throw new l(`Failed to initialize ${e.name}: ${t}`)}});for(const e of i)try{await e.initialize(...s)}catch(t){throw new l(`Failed to initialize ${e.toString()}: ${t}`)}return{client:i,config:t}}}t.setRegistry(new st);const Or="##VERSION##",Sr="##PACKAGE##";J.registerLibrary(Sr,Or);export{xe as AbsContextual,Re as Adapter,Ct as AuthorizationError,Wt as BaseModel,Kt as BigIntSequence,je as Cascade,gr as ClientBasedService,ke as Condition,Tt as ConnectionError,ve as Context,we as ContextLock,Ae as ContextualLoggedClass,pe as DefaultAdapterFlags,Ue as DefaultCascade,ue as DefaultContextFlags,Ke as DefaultRepositoryFilters,Xt as DefaultSequenceOptions,lt as Dispatch,Nt as ForbiddenError,ce as GroupOperator,st as InjectablesRegistry,qe as MethodQueryBuilder,Oe as MigrationError,Se as MigrationRuleError,xr as ModelService,ye as MultipleSelectOperationKeys,ge as NonTransactionOperationKeys,Jt as NoneSequenceOptions,Zt as NumericSequence,or as ObserverError,be as ObserverHandler,ae as Operator,Ye as OperatorsMap,Fe as OrderDirection,Sr as PACKAGE_NAME,me as PaginationOperationKeys,ar as Paginator,Le as PagingError,de as PersistenceKeys,Er as PersistenceService,le as PreparedStatementKeys,oe as QueryClause,Ie as QueryError,tt as Repository,fe as SelectOperationKeys,ir as Sequence,sr as SequenceModel,$e as Serial,hr as Service,pr as Statement,he as TransactionOperationKeys,Pe as UUID,Ee as UnsupportedError,Or as VERSION,At as cacheModelForPopulate,Et as cascadeDelete,Bt as column,yr as create,pt as createOrUpdate,kt as createdAt,It as createdBy,Rt as createdByOnCreateUpdate,wr as del,rt as generateInjectableNameForRepository,et as getFilters,jt as getPkTypes,wt as getPopulateKey,vt as getTagForDeleteKey,Pt as index,Ce as injectableServiceKey,Te as isOperationBlocked,qt as manyToMany,Mt as manyToOne,Gt as noValidateOn,zt as noValidateOnCreate,Qt as noValidateOnCreateUpdate,Ht as noValidateOnUpdate,_e as normalizeImport,Yt as oneToMany,yt as oneToManyOnCreate,bt as oneToManyOnDelete,mt as oneToManyOnUpdate,Ut as oneToOne,ht as oneToOneOnCreate,ft as oneToOneOnDelete,gt as oneToOneOnUpdate,Xe as onlyOnBulk,He as onlyOnCreate,Ve as onlyOnDelete,Ze as onlyOnFilter,Je as onlyOnSingle,We as onlyOnTransactional,Qe as onlyOnUpdate,rr as pk,tr as pkDec,er as pkOnCreate,xt as populate,Be as prefixMethod,Ge as prepared,Ne as promiseSequence,ze as query,mr as read,Vt as relation,nr as repository,St as repositoryFromTypeMetadata,vr as service,_t as table,Dt as unique,$t as uniqueOnCreateUpdate,br as update,Ft as updatedAt,Lt as updatedBy,ut as uuid,dt as uuidCreateUpdateHandler};
2
2
  //# sourceMappingURL=core.js.map