@decaf-ts/core 0.14.3 → 0.14.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,s,i,n,o){"use strict";var c,l,d,u,p;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_BY_PAGINATE="findByPaginate",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.FIND="find",u.PAGE="page",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf",e.PersistenceKeys=void 0,(p=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",p.INDEX="index",p.SEQUENCE="sequence",p.UNIQUE="unique",p.ADAPTER="adapter",p.INJECTABLE="decaf_{0}_adapter_for_{1}",p.SERVICE="service",p.TABLE="table",p.COLUMN="column",p.METADATA="__metadata",p.OWNERSHIP="ownership",p.CREATED_BY="ownership.created-by",p.UPDATED_BY="ownership.updated-by",p.RELATIONS="__relations",p.RELATION="relation",p.ONE_TO_ONE="relation.one-to-one",p.ONE_TO_MANY="relation.one-to-many",p.MANY_TO_ONE="relation.many-to-one",p.MANY_TO_MANY="relation.many-to-many",p.POPULATE="populate",p.NO_VALIDATE="no-validate",p.MIGRATION="migration",p.STATEMENT="statement",p.QUERY="query",p.UUID="uuid",p.TAG_FOR_DELETION="tag_for_deletion",p.INITIALIZATION="initialization",p.SHUTDOWN="shutdown",p.BY_KEY="by-key",p.AUTH="auth",p.AUTH_ROLE="auth-role",p.DECAF_ROUTE="DecafRoute",p.THROTTLE="throttle",p.PERSISTENT_VERSION="persistent-version",p.DEFAULT_QUERY_ATTR="default-query-attr";const h=Object.assign({},{ignoreDevSafeGuards:!1}),g=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1}),f=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],y=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],m=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],w=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],_=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.PAGE];class v extends a.Context{constructor(e){super(e)}static{this.factory=e=>(new v).accumulate(Object.assign({},e,{timestamp:new Date,logger:e.logger||s.Logging.get()}))}static async from(e,t,r,...a){return this.factory(Object.assign({},t||{},{operation:e,model:r,affectedTables:r,args:a,logger:t?.logger||s.Logging.get()}))}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).reduce((e,t)=>(Array.isArray(t)?e.push(...t):null!=t&&e.push(t),e),[]).filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}pending(){return this.getFromChildren("pending")}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 a.InternalError("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 b extends s.LoggedClass{logCtx(e,t,r=!1,a){return b.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...i){const n=(e,t,r)=>{const a=t.log||s.Logging.get();return t.log=e.context?a.clear().for(e):a.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let o=i.pop();const c=o instanceof v||(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"function"==typeof t.get&&"function"==typeof t.accumulate&&"function"==typeof t.override&&"function"==typeof t.toOverrides&&void 0!==t.cache})(o);if(o&&!c&&(i.push(o),o=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!o)throw new a.InternalError("Missing context. should be impossible");return n(this,{log:o.logger,ctx:o,ctxArgs:[...i,o]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...i,o].filter(Boolean)).then(t=>n(this,{log:t.logger,ctx:t,ctxArgs:[...i,t]},e))}}class E extends b{constructor(){super(),this._Context=v}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 a=r.pop();return a instanceof v||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class k{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");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 a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=b.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:n}=a;if(!n)return!0;try{return n(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>{a.observer.refresh(e,t,r,...i)}))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class T extends a.InternalError{constructor(e){super(e,T.name,500)}}class O extends a.InternalError{constructor(e,t=O.name){super(e,t,500)}}class A extends O{constructor(e){super(e,A.name)}}function x(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}async function C(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}const M=[a.OperationKeys.CREATE,a.OperationKeys.READ,a.OperationKeys.UPDATE,a.OperationKeys.DELETE];function D(e){return M.includes(e)}function I(e,t,r){const s=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};if(!s?.handler)return!1;const i=void 0===r&&D(t)?"crud":t,n=void 0===r&&D(t)?t:r,c=s.args?.[0]||[];return s.handler(c,i,n)??!1}function P(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof A)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class N{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 N._instance||(N._instance=new N),N._instance}}class B{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return B._instance||(B._instance=new B),B._instance}}class R{constructor(e,...t){this.adapter=e}async begin(...e){}async commit(...e){}async rollback(...e){}}class L extends n.Lock{constructor(e){super(),this.adapterTransaction=e,this.acquireCount=0,this.lock=new n.Lock}async acquire(...e){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...e)):this.lock.release()}async release(...e){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...e)}catch(t){await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+t),...e)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(e,...t){await this.lock.acquire();try{await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+e),...t)}catch(e){throw new a.InternalError("Failed to rollback transaction: "+e)}finally{this.lock.release()}}}const $=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{const t=e=>{if(!e)return;const t=U._cache?.[e];return t?.flavour||e};try{const r=$(e);if(r&&r!==o.DefaultFlavour)return t(r);const a="function"==typeof e?e:e?.constructor,s=a&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(a):void 0;if(s&&s!==o.DefaultFlavour)return t(s);const i=U._currentFlavour;if(i){const e=U._cache?.[i];return e?.flavour?e.flavour:t(i)}}catch(e){return o.DefaultFlavour}};const F=Symbol("AdapterProxyCleanup");function j(e,t,r,a){if(!t)return e;const s=e,i=[],n=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):n.push(e.reason);if(n.length){r.warn(`Bulk ${a} encountered ${n.length} failure(s) while continuing`);const e=new AggregateError(n,`Bulk ${a} failed for ${n.length} item(s)`);throw e.results=s,e}return i}class U extends E{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!U._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return U._baseRepository}transactionLock(...e){return new R(this,...e)}async shutdownProxies(e,...t){e&&"string"!=typeof e&&(t=[e,...t],e=void 0);const{log:r}=this.logCtx(t,this.shutdownProxies);if(!this.proxies)return;if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);const s=async e=>{if(!e)return;const t=e[F];"function"==typeof t&&await t()};if(e)try{await s(this.proxies[e]),delete this.proxies[e]}catch(t){r.error("Failed to cleanup proxied adapter "+e,t)}else for(const e in this.proxies){try{await s(this.proxies[e])}catch(t){r.error("Failed to cleanup proxied adapter "+e,t);continue}delete this.proxies[e]}}async shutdown(...t){const{log:r,ctxArgs:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(e.PersistenceKeys.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:r}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...s),this.dispatch&&await this.dispatch.close(...s)})()}catch(e){throw new a.InternalError("Failed to create shutdown wrapper: "+e)}finally{this.internalLock.release(e.PersistenceKeys.SHUTDOWN)}try{await this.shutdownPromise}catch(e){r.error("Error during proxy shutdown",e)}finally{this.shutdownPromise=void 0}}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.internalLock=new n.Lock,this.alias in U._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);U._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in U._cache||(U._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),U._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),U._currentFlavour=this.alias)}Dispatch(){return new U._baseDispatch}ObserverHandler(){return new k}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new U._baseSequence(e,this,t)}async flags(e,t,r,...n){if("string"==typeof t)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(t)?t.length?t[0]:void 0:t,l=c?""+i.Model.tableName(c):"";r.correlationId=r.correlationId||`${l}|${e}|${N.instance.generate()}`;const d=r.logger||s.Logging.for(this),u=Object.assign({},g.cacheForPopulate,r.cacheForPopulate);return Object.assign({},g,r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,cacheForPopulate:u,args:n,writeOperation:f.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:d})}get Context(){return v}async context(e,t,r,...a){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>i.Model.tableName(e)):i.Model.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let s=a.pop();void 0===s||s instanceof v||(a.push(s),s=void 0);const n=(()=>{if(!s)return!1;try{return!!s.get("allowGenerationOverride")}catch{return!1}})();t=s?Object.assign({},s.toOverrides(),t):t,n&&(t.allowGenerationOverride=!0);const o=await this.flags("string"==typeof e?e:e.name,r,t,...[...a,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}const t=s.getOrUndefined("operation"),a=s.getOrUndefined("affectedTables");if(!t||t!==e||r&&r!==a){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}return s.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),n=t.segregate(),o=Object.entries(n.model).reduce((e,[r,s])=>{if(void 0===s)return e;const n=i.Model.columnName(t.constructor,r);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return e[n]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(o,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:o,id:t[i.Model.pk(t.constructor)],transient:n.transient}}revert(t,r,s,n,...o){const{log:c,ctx:l}=this.logCtx(o,this.revert),d=i.Model.pk(r),u=new r;u[d]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return l.get("rebuildWithTransient")&&n&&(c.verbose("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,r,...s){const{log:n,ctx:o}=this.logCtx(s,this.createAll);if(!t||!r)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new a.ValidationError("Ids and models must have the same length");const c=i.Model.tableName(e);n.debug(`Creating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.create(e,t,r[a],...s,o.override({noEmitSingle:!0})));return j(l?await C(d,!0):await C(d),l,n,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...r){const{log:s,ctx:n}=this.logCtx(r,this.readAll),o=i.Model.tableName(e);s.debug(`Reading ${t.length} entries ${o} table`);const c=!(n.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...r,n.override({noEmitSingle:!0})));return j(c?await C(l,!0):await C(l),c,s,a.BulkCrudOperationKeys.READ_ALL)}async updateAll(e,t,r,...s){const{log:n,ctx:o}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const c=i.Model.tableName(e);n.debug(`Updating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.update(e,t,r[a],...s,o.override({noEmitSingle:!0})));return j(l?await C(d,!0):await C(d),l,n,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return j(n?await C(o,!0):await C(o),n,s,a.BulkCrudOperationKeys.DELETE_ALL)}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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(a&&o||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!U._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return U._currentFlavour}static get current(){return U.get(this.currentFlavour)}static unregister(e){if(!e)return;const t=U._cache[e];t&&(delete U._cache[e],U._currentFlavour===e&&(U._currentFlavour=void 0),t.flavour&&U._cache[t.flavour]&&U._cache[t.flavour]===t&&delete U._cache[t.flavour])}static get(e){if(!e)return U.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e).filter(i.Model.isModel)}catch(e){throw new a.InternalError(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} - ${i.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return Reflect.defineProperty(s,F,{value:async()=>{if(!a)return;const e=["cancel","close","destroy","disconnect"];for(const t of e){const e=a[t];if("function"==typeof e)try{const t=e.call(a);t instanceof Promise&&await t}catch{}}a=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,v]),r.__metadata("design:returntype",Promise)],U.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],U.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],U.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],U.prototype,"client",null);class q extends a.InternalError{constructor(e){super(e,q.name,500)}}class G extends a.InternalError{constructor(e){super(e,G.name,500)}}class z extends i.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):i.Model.fromModel(this,e)}and(e){return z.and(this,e)}or(e){return z.or(this,e)}not(t){return new z(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof z)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof z){if(!(this.comparison instanceof z)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return z.group(t,e.GroupOperator.AND,r)}static or(t,r){return z.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new z(e,t,r)}static attribute(e){return(new z.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new z(this.attr1,this.operator,this.comparison)}catch(e){throw new q(e)}}}}static builder(){return new z.Builder}static from(e){return new z(e)}}var Y,H;r.__decorate([i.required(),r.__metadata("design:type",Object)],z.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],z.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],z.prototype,"comparison",void 0),e.OrderDirection=void 0,(Y=e.OrderDirection||(e.OrderDirection={})).ASC="asc",Y.DSC="desc",e.Cascade=void 0,(H=e.Cascade||(e.Cascade={})).CASCADE="cascade",H.NONE="none";const V={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},Q={Equals:(e,t)=>z.attribute(e).eq(t),Diff:(e,t)=>z.attribute(e).dif(t),LessThan:(e,t)=>z.attribute(e).lt(t),LessThanEqual:(e,t)=>z.attribute(e).lte(t),GreaterThan:(e,t)=>z.attribute(e).gt(t),GreaterThanEqual:(e,t)=>z.attribute(e).gte(t),In:(e,t)=>z.attribute(e).in(t),Matches:(e,t)=>z.attribute(e).regexp(t)},W=e=>e.charAt(0).toLowerCase()+e.slice(1);class J extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(J.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const n=this.extractCore(e,s),o=this.extractSelect(e),c=this.extractGroupBy(e),l=this.buildWhere(n,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,n);return{action:a,select:o,selector:i,where:l,groupBy:c,orderBy:d,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?W(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(W).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(W).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),n=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&n.push(W(r))}return n.length>0?n:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach((t,a)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),c=o?Q[o]:Q.Equals;if(!c)throw Error("Unsupported operator "+o);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);n=0===a?d:i[a-1]===e.QueryClause.AND?n.and(d):n.or(d)}),n}static parseFieldAndOperator(e){for(const t of Object.keys(Q))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:W(r),operator:t}}return{field:W(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(t,r){const a=J.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new q("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new q(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,n=t.slice(i)??[];let o,c,l;if(n.at(-1)instanceof a.Context&&n.pop(),n.length>=1){const t=n[0],r=this.extractOrderByField(e);o=this.getProperlyOrderByOrThrow(r,t)}return 2>n.length||"number"!=typeof n[1]||(c=n[1]),3>n.length||"number"!=typeof n[2]||(l=n[2]),{orderBy:o,limit:c,offset:l}}}function X(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function Z(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(o.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),n=o.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return o.propMetadata(n,c)(a,s)}}function ee(e){return ne(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function te(e){return ne(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function re(e){return ne(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ae(e){return ne(e,f)}function se(e){return ne(e,Object.values(a.OperationKeys))}function ie(e){return ne(e,Object.values(a.BulkCrudOperationKeys))}function ne(e,t){return(r,s,n,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=b.prototype.logCtx(c,ne);return l.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${n}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:o.Metadata.constr(e)===o.Metadata.constr(r))&&t.includes(s)}}const oe={onlyOnCreate:ee,onlyOnUpdate:te,onlyOnDelete:re,onlyOnTransactional:ae,onlyOnSingle:se,onlyOnBulk:ie};function ce(e){const t=Object.assign({},oe);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var le,de,ue,pe,he,ge,fe,ye,me,we,_e;class ve extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=i.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ce(this)}constructor(e,t,r=!1,...s){super(t),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),t&&(ve.register(t,this,this.adapter.alias,r),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t);const i=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(i,i[t+"Prefix"],e,i[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(i,i[this.updateAll.name+"Prefix"],this.updateAll,i[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new k}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.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 a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.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 a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${i.Model.tableName(this.class)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...s),this.adapter.revert(n,this.class,o,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let c=n.map(e=>e.record);return c=await this.adapter.createAll(this.class,o,c,...s),c.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:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(n.silly(`handlerSetting: ${o}, validationSetting: ${c}`),!e.length)return[e,...s];const l=i.Model.sequenceFor(e[0]);let d=[];if(i.Model.generatedBySequence(this.class)?(l.name||(l.name=i.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=r.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.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 a.enforceDBDecorators(this,r,o,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${i.Model.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...s);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,a.BulkCrudOperationKeys.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,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${i.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,c,s)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");n.silly(`handlerSetting: ${o}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=i.Model.merge(d,e,this.class))),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.verbose(`Updating ${e.length} new ${this.class.name} in table ${i.Model.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),...s)).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:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");n.silly(`handlerSetting: ${o}, ignoredValidation: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(d[t],e,this.class)))),o||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let s;n.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s,d]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${i.Model.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...s);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,a.BulkCrudOperationKeys.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=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(...o)}async listBy(t,r,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${i.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...n)}async paginateBy(t,r,a={offset:1,limit:10},...s){a.offset=a.offset||1,a.limit=a.limit||10;const{offset:n,bookmark:o,limit:c}=a;if(!n&&!o)throw new q("PaginateBy needs a page or a bookmark");const{log:l,ctx:d,ctxArgs:u}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let p;if(l.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${c}`),o&&d.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>r===e.OrderDirection.ASC?this.attr(i.Model.pk(this.class)).gt(o):this.attr(i.Model.pk(this.class)).lt(o))()).orderBy([t,r]).paginate(c,...u);else{if(!n)throw new q("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(c,...u)}const h=await p.page(n,o,...u);return p.serialize(h)}async find(t,r=e.OrderDirection.ASC,...a){if("string"!=typeof t)throw new q("Find value must be a string");const s=this.getDefaultQueryAttributes(),{log:n,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.FIND,!0)).for(this.find);n.verbose(`finding ${i.Model.tableName(this.class)} by default attributes ${s.join(", ")}`);const c=this.buildDefaultStartsWithCondition(t,s);return this.select().where(c).orderBy([s[0],r]).execute(...o)}async page(t,r=e.OrderDirection.ASC,a={offset:1,limit:10},...s){if("string"!=typeof t)throw new q("Page value must be a string");const n=a.offset||1,{offset:o,bookmark:c,limit:l}=a;if(!o&&!c)throw new q("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${i.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const f=l??10,y=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let w;if(c&&h.get("paginateByBookmark")){const t=i.Model.pk(this.class),a=r===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);w=await m.select().where(u.and(a)).orderBy([y,r]).paginate(f,...g)}else{if(!o)throw new q("PaginateBy needs a page or a bookmark");w=await m.select().where(u).orderBy([y,r]).paginate(f,...g)}const _=await w.page(n,c,...g);return w.serialize(_)}async findOneBy(t,r,...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);n.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`);const c=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...o);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,r,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...n)}async findByPaginate(t,r,a={direction:e.OrderDirection.DSC,offset:1,limit:10},...s){a.direction=a.direction||e.OrderDirection.DSC,a.offset=a.offset||1,a.limit=a.limit||10;const{direction:n,offset:o,bookmark:c,limit:l}=a;if(!o&&!c)throw new q("FindByPaginate needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);d.verbose(`finding and paginating ${i.Model.tableName(this.class)} with ${t} ${r}`);const h=this.attr(t).eq(r);let g;if(c&&u.get("paginateByBookmark")){const r=i.Model.pk(this.class),a=n===e.OrderDirection.ASC?this.attr(r).gt(c):this.attr(r).lt(c);g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h.and(a)).orderBy([t,n]).paginate(l,...p)}else{if(!o)throw new q("FindByPaginate needs a page or a bookmark");g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h).orderBy([t,n]).paginate(l,...p)}const f=await g.page(o,c,...p);return g.serialize(f)}async countOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return a.verbose(`counting ${i.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${t} in ${i.Model.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${t} in ${i.Model.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating average of ${t} in ${i.Model.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${t} in ${i.Model.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${t} in ${i.Model.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${i.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...r){if(!ve.statements(this,t))throw new q("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const e=i.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new q("No default query attributes defined for "+i.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new q("Default query value must be a string");let r;for(const a of t){const t=this.attr(a).startsWith(e);r=r?r.or(t):t}if(!r)throw new q("No default query attributes available for "+i.Model.tableName(this.class));return r}attr(e){return z.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,t,r,...s)=>"string"==typeof e?e===a:o.Metadata.constr(e)===o.Metadata.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>U._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):U._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,r),...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const c=o.Metadata.registeredFlavour(t),l=c&&c!==o.DefaultFlavour?c:void 0,d=r||l||o.Metadata.flavourOf(t)||U.currentFlavour;try{n=this.get(t,d)}catch(e){n=void 0}const u="function"==typeof n?n:void 0,p=r||l||o.Metadata.flavourOf(t)||u&&o.Metadata.get(u,e.PersistenceKeys.ADAPTER)||U.currentFlavour,h=p?U.get(p):void 0;if(!h)throw new a.InternalError("No registered persistence adapter found flavour "+p);if(n instanceof ve)return n;const g=[i.Model.tableName(t),h.alias].join(a.DefaultSeparator),f=u||h.repository();return delete this._cache[g],new f(h,t,...s)}static get(e,t){const r=i.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r,s=!1){let n=i.Model.tableName(e);if(r&&(n=[n,r].join(a.DefaultSeparator)),n in this._cache&&this._cache[n]instanceof ve&&!s)throw new a.InternalError(n+" already has a registered instance");this._cache[n]=t}static statements(t,r){const a=t instanceof ve?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof ve?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function be(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof i.Model?t.constructor.name:t.name));return i.sf(e.PersistenceKeys.INJECTABLE,r,i.Model.tableName(t))}r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"listBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"paginateBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"find",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"page",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findOneBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findByPaginate",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"countOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(le="undefined"!=typeof K&&K)?le:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"maxOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(de="undefined"!=typeof K&&K)?de:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"minOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ue="undefined"!=typeof K&&K)?ue:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"avgOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(pe="undefined"!=typeof K&&K)?pe:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"sumOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(he="undefined"!=typeof K&&K)?he:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"distinctOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ge="undefined"!=typeof K&&K)?ge:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],ve.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],ve.prototype,"unObserve",null),U&&(U._baseRepository=ve);class Se extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let n;try{n=super.get(r)}catch{}if(!n){let c;if("function"==typeof r?c=i.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=i.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l)||o.Metadata.flavourOf(c);try{let e=d;try{d&&U.get(d)}catch{const t=U.current;t&&t.flavour===d&&(e=t.alias)}if(n=ve.forModel(c,e),n instanceof ve)return n;const r=d||o.Metadata.get(n.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(n,be(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ve.get(c,d);if("function"==typeof t){const e=d?U.get(d):U.current;if(!e)return;return new t(e,c)}}}return n}}e.TaskStatus=void 0,(fe=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",fe.SCHEDULED="scheduled",fe.RUNNING="running",fe.FAILED="failed",fe.SUCCEEDED="succeeded",fe.CANCELED="canceled",fe.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(ye=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",ye.FIXED="fixed",e.JitterStrategy=void 0,(me=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",me.FULL="full",e.TaskEventType=void 0,(we=e.TaskEventType||(e.TaskEventType={})).STATUS="status",we.UPDATE="update",we.LOG="log",we.PROGRESS="progress",we.ALL="all",e.TaskType=void 0,(_e=e.TaskType||(e.TaskType={})).ATOMIC="atomic",_e.COMPOSITE="composite";const Ee="tasks",ke={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};function Te(r,s){return(n,c)=>c?t.inject(o.Metadata.constr(r))(n,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||U.currentFlavour,i.Model.tableName(r)),n),o.metadata(a.DBKeys.REPOSITORY,n.name)(r),s=s||o.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),ve.register(r,n),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(n))}o.Metadata.tasks=(()=>o.Metadata.innerGet(Symbol.for(Ee))).bind(o.Metadata),o.Metadata.taskFor=(e=>{const t=o.Metadata.tasks();return t?t[e]:void 0}).bind(o.Metadata),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],n=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=i.Model.nestedRelations(t)),[...new Set([...n,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??U.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.migrations=(()=>{const t=o.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(t).flat().map(e=>[e.class.name,e.class])}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),i.Model.relations=(e,t)=>o.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&i.Model.relations(t.class)){const s=i.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=i.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]}).bind(i.Model),i.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!i.Model.sequenceFor(r).generated}).bind(i.Model),i.Model.fromTable=(t=>{const r=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!r||!r[t]||!i.Model.get(r[t].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return i.Model.get(r[t].name)}).bind(i.Model),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),i.Model.tableName=t=>{if(!(t instanceof i.Model?i.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof i.Model?t.constructor.name:t.name)},i.Model.columnName=(t,r)=>o.Metadata.get(t instanceof i.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.defaultQueryAttributes=(t,r=!1)=>{const a="function"==typeof t?t:t.constructor;return o.Metadata.get(a,o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||(r?[i.Model.pk(t)]:[])},i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.versionOf=(t=>{const r=o.Metadata.get(t.constructor),s=r?.[e.PersistenceKeys.PERSISTENT_VERSION],i=s&&"object"==typeof s?Object.keys(s)[0]:void 0,n=r?.[a.DBKeys.VERSION],c=n&&"object"==typeof n?Object.keys(n)[0]:void 0,l=i??c;if(!l)throw new a.InternalError("No version found for "+t.constructor.name);const d=t[l];if("number"!=typeof d||1>d)throw new a.InternalError("Invalid version number: "+d);return d}).bind(i.Model),i.Model.sequenceFor=(t,r)=>{const s="function"!=typeof t?t.constructor:t;let n=e.PersistenceKeys.SEQUENCE;const c=i.Model.pk(s);r&&r+""!=c+""||(r=c,n=a.DBKeys.ID),n=o.Metadata.key(n,r);const l=o.Metadata.get(s,n);if(!l)throw new a.InternalError(`No sequence options defined for property ${r+""}. did you use @sequence() or @pk()?`);return l},i.Model.indexes=t=>{const r=o.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})},t.Injectables.services=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY)),i.Model.merge=((e,t,r)=>{const a=e=>Object.entries(e).reduce((e,[t,a])=>{let s=!1;try{"relation.one-to-one"===i.Model.relations(r,t).key&&(s=!0)}catch(e){s=!1}return(void 0!==a||s)&&(e[t]=a),e},{});return new(r=r||e.constructor)(Object.assign({},a(e),a(t)))}).bind(i.Model);class Oe extends a.InternalError{constructor(e){super(e,Oe.name,500)}}var Ae;e.AuthKeys=void 0,(Ae=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Ae.ROLES="roles",Ae.NAMESPACE="namespace";const xe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ce=xe,Me={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},De=Object.assign({},Me,{type:"BigInt"});function Ie(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,i)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,i),{directions:t,compositions:r,name:a})(s,i)),args:[t,r,a]}).apply()}function Pe(e){return"function"==typeof e}function Ne(e,t,r){if(!r.type){const a=o.Metadata.type(e.constructor,t);if(![Number.name,String.name,BigInt.name].includes(a?.name||a))throw Error("Incorrrect option type");r.type=a}switch(r.type){case String.name||String.name.toLowerCase():case String:r.generated=void 0!==r.generated&&r.generated,r.type=String;break;case Number.name||String.name.toLowerCase():case Number:r.generated=void 0===r.generated||r.generated,r.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:r.type=BigInt,r.generated=void 0===r.generated||r.generated;break;case"uuid":case"serial":r.generated=!0;break;default:throw Error("Unsupported type")}void 0===r.generated&&(r.generated=!0)}async function Be(e,t,r,s){if(!t.type||!t.generated||s[r])return;let n;t.name||(t.name=i.Model.sequenceName(s,"pk"));try{n=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var o,c,l;o=s,c=r,l=await n.next(e),Reflect.set(o,c,l)}async function Re(e,t,r,s,n){if(!t.type||!t.generated)return;if(!t.name){const e=i.Model.pk(s,!0);if(null==e)throw new a.InternalError("Cannot generate sequence without an id for "+s.constructor.name);t.name=i.Model.sequenceName(s,e+"",r+"")}let o;try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const c=null!=n,l=void 0!==s[r]&&null!==s[r],d=!!e.get("allowGenerationOverride")&&l;if(l&&await o.ensureAtLeast(s[r],e),c&&!t.update)return;if(d)return;const u=await o.next(e);Reflect.set(s,r,u)}function Le(t,r){return(s,n)=>{var c,l;o.prop()(s,n),Ne(s,n,t),t.name||(t.name=(c=s.constructor,l="pk",Pe(i.Model.sequenceName)?i.Model.sequenceName(c,l):[Pe(i.Model.tableName)?i.Model.tableName(c):c?.name??"",l].filter(Boolean).join("_")));const d=[o.propMetadata(o.Metadata.key(a.DBKeys.ID,n),t),o.propMetadata(o.Metadata.key(e.PersistenceKeys.SEQUENCE,n),t),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),a.onCreate(Be,t,r)];return t.generated&&d.push(a.generated()),o.apply(...d)(s,n)}}function $e(t,r={},s){return(n,c)=>{o.prop()(n,c),Ne(n,c,t);const l=[i.required(),o.propMetadata(o.Metadata.key(e.PersistenceKeys.SEQUENCE,c),t),a.onCreate(Re,{...t,...r},s)];return r.update&&l.push(a.onUpdate(Re,{...t,...r},s)),t.generated&&l.push(a.generated()),o.apply(...l)(n,c)}}function Fe(e){const t=Object.assign({},Ce);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:Le,args:[e,{priority:60}]}).apply()}async function Ke(e,t,r,s,n){const o=t.logger.for(Ke);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=ve.forModel(t,r),o.info("Retrieved "+s.toString())}let c;if(s=n?s.override(n):s,void 0===e[i.Model.pk(s.class)])o.info(`No pk found in ${i.Model.tableName(s.class)} - creating`),c=await s.create(e,t);else{o.info(`pk found in ${i.Model.tableName(s.class)} - attempting update`);try{c=await s.update(e,t),o.info("Updated "+i.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;o.info("update Failed - creating new "+i.Model.tableName(s.class)),c=await s.create(e,t)}o.info("After create update: "+c)}return c}async function je(e,t,r,s){const n=s[r];if(!n)return;if(Ve(s,t),"object"!=typeof n){const t=it(s,r,this.adapter.alias),a=await t.override(this._overrides).read(n,e);return await tt(e,s,r,n,a),void(s[r]=n)}const o="function"!=typeof t.class||t.class.name?t.class:t.class();if(!o)throw new a.InternalError("Could not find model "+t.class);const c=ve.forModel(o,this.adapter.alias),l=await c.override(this._overrides).create(n,e),d=i.Model.pk(l);await tt(e,s,r,l[d],l),s[r]=l[d]}async function Ue(t,r,a,s){const n=s[a];if(!n)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof n){const e=it(s,a,this.adapter.alias),r=await e.override(this._overrides).read(n,t);return await tt(t,s,a,n,r),void(s[a]=n)}const o=await Ke(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(o);await tt(t,s,a,o[c],o),s[a]=o[c]}async function qe(t,r,a,s){const n=s[a];if(null==n)return;if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=it(s,a,this.adapter.alias);let c;c=n instanceof i.Model?await o.delete(s[a][o.pk],t):await o.delete(s[a],t),await tt(t,s,a,c[o.pk],c)}async function Ge(e,t,r,a,s){const n=a[r];if(!n||!n.length)return;Ve(a,t);const o=e.logger.for(Ge),c=it(a,r,this.adapter.alias),l=i.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of n){let s;"object"!=typeof t?(s=await c.override(this._overrides).read(t,e),o.debug("read: "+s[l])):(o.verbose("Creating or updating one-to-many model: "+t[l]),s=await Ke(t,e,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(s)} under ${s[l]}`),await tt(e,a,r,s[l],s),d.add(s[l])}a[r]=[...d]}async function ze(t,r,a,s,i){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return Ge.call(this,t,r,a,s,i)}async function Ye(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ve.forModel(c,this.adapter.alias):it(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await tt(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}async function He(e,t,r,s){const n=s[r];if(!n)return;Ve(s,t);const o=e.logger.for(He);if("object"!=typeof n){const t=it(s,r,this.adapter.alias),a=await t.override(this._overrides).read(n,e);return await tt(e,s,r,n,a),void(s[r]=n)}if(!(t.class instanceof i.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);o.info("Creating or updating many-to-one model: "+JSON.stringify(n));const c=await Ke(n,e,this.adapter.alias,void 0,this._overrides),l=i.Model.pk(c);o.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await tt(e,s,r,c[l],c),s[r]=c[l]}function Ve(t,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=o.Metadata.get(i,e.PersistenceKeys.RELATIONS);if(n&&(s=Object.values(n)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===s?.populate&&!0===r?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Qe(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return He.call(this,t,r,a,s)}async function We(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const n="object"==typeof i,o=n?ve.forModel(i,this.adapter.alias):it(s,a,this.adapter.alias),c=n?i[o.pk]:i,l=await o.override(this._overrides).delete(c);await tt(t,s,a,c,l),s[a]=c}async function Je(e,t,r,s){const n=s[r];if(!n||!n.length)return;Ve(s,t);const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=e.logger.for(Je),l=new Set([...n]);if("object"!==o){const a=it(s,r,this.adapter.alias),i=await a.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<i.length;t++){const a=i[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(a)),await tt(e,a,r,[...l.values()][t],i)}return await Xe.call(this,s,[...n],c,e,t),s[r]=[...l],void c.info("SET MANY TO MANY IDS: "+s[r])}const d=i.Model.pk(n[0].constructor),u=new Set;for(const t of n){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const a=await Ke(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await tt(e,s,r,a[d],a),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=a.id,u.add(a[d])}const p=i.Model.pk(s.constructor);if(void 0===s[p]){const t=await(async(e,t,r)=>{const s=t[i.Model.pk(t.constructor)];if(void 0!==s)return s;const n=i.Model.sequenceFor(t.constructor);let o;n?.name||(n.name=i.Model.sequenceName(t,"pk"));try{return o=await e.adapter.Sequence(n,e._overrides),await o.next(r)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${n.name}: ${e}`)}})(this,s,e);s[p]=t}const h=await Xe.call(this,s,n,c,e,t);c.info("Junction model created: "+h.name),s[r]=[...u]}async function Xe(e,t,r,a,s){const{JunctionModel:n,fkA:o,fkB:c}=Ze(e,t[0],s),l=[];for(const s of t){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(s));const t={[o]:e instanceof i.Model?e[i.Model.pk(e.constructor)]:e,[c]:s instanceof i.Model?s[i.Model.pk(s.constructor)]:s},d=await Ke(new n(t),a,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=ve.forModel(n);await(e?.override(this._overrides).readAll(l))}return n}function Ze(t,r,s){const n=i.Model.tableName(t);let c;if(r instanceof i.Model)c=i.Model.tableName(r);else if(i.Model.isModel(r)&&"function"==typeof r)c=r.name?r.name:r()?.name;else if(s?.class){const e="function"!=typeof s.class||s.class.name?s.class:s.class();c=i.Model.tableName(e)}if(!n||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=s?.joinTable?.name?s?.joinTable?.name:`${n}_${c}`,d=n?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends i.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),Fe({type:Number})(p.prototype,"id"),i.required()(p.prototype,d),i.required()(p.prototype,u);const h=i.model()(p);return o.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function et(t,r,a){return r?[e.PersistenceKeys.POPULATE,t,r,a].join("."):[e.PersistenceKeys.POPULATE,t,a].join(".")}async function tt(e,t,r,a,s){const i=et(t.constructor.name,r,a),n=e.logger.for(tt),o=e.get("cacheForPopulate")||{};let c=o[i],l=e.getOrUndefined("preferFromCache");if(!l)try{n.silly("retrieving from children"),l=e.getFromChildren("preferFromCache")||!1,l&&(c=(e.getFromChildren("cacheForPopulate")||{})[i])}catch(e){l=!1}return l&&n.debug("preferring previous cache: "+!!o[i]),o[i]=l&&c?c:s,e.accumulate({cacheForPopulate:o})}async function rt(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=this,c=await(async(t,r,s,i)=>{let n,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){n=et(r.constructor.name,s,t);try{if(c=u[n],!c)throw Error("Not found in cache")}catch(i){const n=it(r,s,o.adapter.alias);if(!n)throw new a.InternalError("Could not find repo");c=await n.override(o._overrides).read(t,e)}l.push(c)}return l})(e,s,r,n?i:[i]);s[r]=n?c:c[0]}async function at(t,r,s,n,o){if(r.cascade.update!==e.Cascade.CASCADE)return;if(!o)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function c(e){return Array.isArray(e)?e.map(c):"object"!=typeof e?e:e[i.Model.pk(e)]}const l=c(n[s]),d=c(o[s]);if(void 0===d||i.isEqual(l,d))return;if(Array.isArray(l)!==Array.isArray(d))throw new a.InternalError("Cannot cascade update for different array types");const u=(Array.isArray(l)?l:[l]).filter(Boolean),p=(Array.isArray(d)?d:[d]).filter(Boolean).filter(e=>!u.includes(e)),h=it(n,s,this.adapter.alias);if(!h)throw new a.InternalError("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${i.Model.tableName(h.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}const st=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function it(e,t,r){if(!e)throw Error("No model was provided to get repository");let s,n=e instanceof i.Model?e.constructor:e;if(Array.isArray(e[t])||e[t]instanceof Set){const e=o.Metadata.get(n,o.Metadata.key(i.ValidationKeys.REFLECT,t,i.ValidationKeys.LIST))?.clazz;if(!e)throw new a.InternalError("Failed to find types decorators for property "+t);s=(Array.isArray(e)?[...e]:[e]).map(e=>"function"!=typeof e||e.name?e:e())}else s=i.Model.relations(n).includes(t)?o.Metadata.allowedTypes(n,t):o.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;n=s?.find(e=>!st.includes((""+e.name).toLowerCase()));const c=ve.forModel(n,r);if(n!==c.class)throw new a.InternalError("Invalid repository class for "+t);return c}class nt extends a.BadRequestError{constructor(e,t=nt.name,r=401){super(e,t,r)}}class ot extends nt{constructor(e,t=ot.name){super(e,t,403)}}class ct extends a.InternalError{constructor(e){super(e,ct.name,503)}}function lt(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(o.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function dt(t){return o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}async function ut(e,t,r,s){if(s[r]&&(await this.select().where(z.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function pt(e,t,r,a){throw new nt("This adapter does not support user identification")}function ht(){return o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(pt),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function gt(){return o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(pt),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ft(){return a.timestamp([a.OperationKeys.CREATE])}function yt(){return a.timestamp()}async function mt(e,t,r,s){if("??sequence"===i.Model.tableName(s))return;const n=i.Model.pk(s,!0);if(null==n)throw new a.InternalError("Cannot generate persistent version without an id for "+s.constructor.name);const o={name:i.Model.sequenceName(s,n+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},c=await this.adapter.Sequence(o,this._overrides),l=void 0!==s[r]&&null!==s[r],d=!!e.get("allowGenerationOverride")&&l;if(l&&(await c.ensureAtLeast(s[r],e),d))return;const u=await c.next(e);s[r]=u}async function wt(e,t,r,s,n){if("??sequence"===i.Model.tableName(s))return;if(e.get("applyUpdateValidation")&&n&&s[r]!==n[r])throw new a.ValidationError(`Version mismatch: ${s[r]} !== ${n[r]}`);const o=i.Model.pk(s,!0);if(null==o)throw new a.InternalError("Cannot generate persistent version without an id for "+s.constructor.name);const c={name:i.Model.sequenceName(s,o+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},l=await this.adapter.Sequence(c,this._overrides),d=void 0!==s[r]&&null!==s[r],u=!!e.get("allowGenerationOverride")&&d;if(d&&(await l.ensureAtLeast(s[r],e),u))return;const p=await l.next(e);s[r]=p}function _t(){const t=e.PersistenceKeys.PERSISTENT_VERSION;return(e,r)=>o.Decoration.for(t).define(o.prop(),o.propMetadata(o.Metadata.key(t,r),!0),a.generated(t),i.type(Number),a.onCreate(mt,{},{priority:70}),a.onUpdate(wt,{},{priority:70})).apply()(e,r)}function vt(e){return[()=>{const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return(o.Metadata.allowedTypes(t,r)||[])[0]}]}function bt(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function St(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class Et extends i.Model{constructor(e){super(e)}}r.__decorate([ft(),r.__metadata("design:type",Date)],Et.prototype,"createdAt",void 0),r.__decorate([yt(),r.__metadata("design:type",Date)],Et.prototype,"updatedAt",void 0),e.SequenceModel=class extends Et{constructor(e){super(e)}},r.__decorate([Fe({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),Ie(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([lt("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class kt extends s.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,P(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.FIND_BY_PAGINATE}|${e.PreparedStatementKeys.LIST_BY}|${e.PreparedStatementKeys.PAGE_BY}|${e.PreparedStatementKeys.FIND}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof v?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof v||(this._bookmark=r);const n=ve.forModel(this.clazz,this.adapter.alias),o=this.query,{method:c,args:l,params:d}=o;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await n.statement(...r,...i);return this.apply(s)}let u;if(c===e.PreparedStatementKeys.FIND_BY?u=e.PreparedStatementKeys.FIND_BY_PAGINATE:c.startsWith(e.PreparedStatementKeys.FIND_BY)?u=c.replace(e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.PAGE_BY):c===e.PreparedStatementKeys.LIST_BY?u=e.PreparedStatementKeys.PAGE_BY:c!==e.PreparedStatementKeys.PAGE_BY&&c!==e.PreparedStatementKeys.FIND_BY_PAGINATE||(u=c),!u)throw new T(`Method ${c} is not supported for pagination`);const p=[u,...l];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==e.PreparedStatementKeys.PAGE_BY||p.length>2?h={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:p.push(d.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 G("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new G(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new T("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 a.SerializationError(e)}}apply(e){const t="string"==typeof e?kt.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(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 Tt,Ot,At,xt,Ct,Mt,Dt;class It extends b{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=a.get("forcePrepareSimpleQueries"),o=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||c)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(It)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new q("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?i.Model.get(e):e,!this.fromSelector)throw new q("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new q("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new q("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new q("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new q(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new q("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const i=await this.raw(s,...a);if(this.hasAggregation())return i;if(!this.selectSelector){const e=e=>this.processRecord(e,r);if(this.groupBySelectors?.length){const t=this.revertGroupedResults(i,e);return await this.applyAfterHandlersToResult(t,r)}if(Array.isArray(i)){const t=i.map(e);return await this.applyAfterHandlersToResult(t,r)}const t=e(i);return await this.applyAfterHandlersToResult(t,r)}return i}catch(e){throw new q(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ve.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new T("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const i=e=>this.processRecord(e,r);if(Array.isArray(s)){const e=s.map(i);return await this.applyAfterHandlersToResult(e,r)}const n=i(s);return await this.applyAfterHandlersToResult(n,r)}processRecord(e,t){const r=e[i.Model.pk(this.fromSelector)];return this.adapter.revert(e,this.fromSelector,r,void 0,t)}async applyAfterHandlersToResult(e,t){return t.getOrUndefined("afterQueryHandlers")?e instanceof i.Model?(await a.enforceDBDecorators(this.getRepository(),t,e,a.OperationKeys.READ,a.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterHandlersToResult(e,t))),e):e&&"object"==typeof e?(await Promise.all(Object.entries(e).map(([r,a])=>this.applyAfterHandlersToResult(a,t).then(t=>{e[r]=t}))),e):e:e}getRepository(){return ve.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const n={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,n.args=[...n.args||[],...t.args||[]]}if(i instanceof z){const e=this.prepareCondition(i,r);t=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:n.method=a,n.args=[...n.args||[],i];break;case e.Operator.DIFFERENT:n.method=a+" diff",n.args=[...n.args||[],i];break;case e.Operator.REGEXP:n.method=a+" matches",n.args=[...n.args||[],i];break;case e.Operator.BIGGER:n.method=a+" bigger",n.args=[...n.args||[],i];break;case e.Operator.BIGGER_EQ:n.method=a+" bigger than equal";break;case e.Operator.SMALLER:n.method=a+" less",n.args=[...n.args||[],i];break;case e.Operator.SMALLER_EQ:n.method=a+" less than equal",n.args=[...n.args||[],i];break;case e.Operator.IN:n.method=a+" in",n.args=[...n.args||[],i];break;default:throw new q("Unsupported operator "+s)}return n}squash(t){const r=this.matchDefaultQueryCondition();if(r){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[r.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof z)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let a;this.whereCondition&&(a=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:a?[a,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[n,o]=s,c={direction:o};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[n],params:c};return a&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[a,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=i.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const r=Array.from(new Set(t.map(String))),a=Array.from(new Set(e.attributes.map(String)));return r.length===a.length&&r.every(e=>a.includes(e))?{value:e.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof z?this.collectStartsWithAttributes(r):void 0,t=s instanceof z?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof z?this.collectStartsWithAttributes(r):void 0)||(s instanceof z?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},i={class:this.fromSelector,args:r,params:a};let n,o=e.QueryClause.FIND_BY;void 0!==this.countSelector?(o=e.QueryClause.COUNT_BY,n=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(o=e.QueryClause.SUM_BY,n=this.sumSelector):this.avgSelector?(o=e.QueryClause.AVG_BY,n=this.avgSelector):this.minSelector?(o=e.QueryClause.MIN_BY,n=this.minSelector):this.maxSelector?(o=e.QueryClause.MAX_BY,n=this.maxSelector):this.distinctSelector?(o=e.QueryClause.DISTINCT_BY,n=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(o=e.QueryClause.GROUP_BY_PREFIX,n=this.groupBySelectors[0]);const c=[o];if(n&&c.push(n),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&o!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&o===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),i.method=s.toCamelCase(c.join(" ")),i.params=a,this.prepared=i,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelectors&&this.groupBySelectors.length||void 0!==this.countSelector||this.countDistinctSelector||this.maxSelector||this.minSelector||this.sumSelector||this.avgSelector||this.distinctSelector)}hasAggregation(){return void 0!==this.countSelector||void 0!==this.countDistinctSelector||void 0!==this.maxSelector||void 0!==this.minSelector||void 0!==this.sumSelector||void 0!==this.avgSelector||void 0!==this.distinctSelector||(this.groupBySelectors?.length||0)>0}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new q(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],It.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Tt="undefined"!=typeof S&&S)?Tt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ot="undefined"!=typeof S&&S)?Ot:Object]),r.__metadata("design:returntype",Object)],It.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(At="undefined"!=typeof S&&S)?At:Object]),r.__metadata("design:returntype",Object)],It.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(xt="undefined"!=typeof S&&S)?xt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ct="undefined"!=typeof S&&S)?Ct:Object]),r.__metadata("design:returntype",Object)],It.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Mt="undefined"!=typeof S&&S)?Mt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],It.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[z]),r.__metadata("design:returntype",Object)],It.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],It.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],It.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Dt="undefined"!=typeof Key&&Key)?Dt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],It.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],It.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],It.prototype,"execute",null);class Pt extends b{constructor(e){super(),this.name=e,this.observers=[],this.Context=v}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Pt?i.for(e,...t):i instanceof ve?i.override(e):i}})}override(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Pt?i.override(e,...t):i instanceof ve?i.override(e):i}})}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new k,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 a.InternalError("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 a.InternalError("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}-${N.instance.generate()}`;const a=t.logger||s.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},h,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof v||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return b.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const r=x(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...r){let s=r.pop();void 0===s||s instanceof v||(r.push(s),s=void 0);const i=await Pt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new v(s).accumulate({...i,parentContext:s}):(new v).accumulate(i),r=[...r,s];const{log:n,ctxArgs:o}=Pt.prototype.logCtx(r,this.boot),c=t.Injectables.services();for(const[e,r]of Object.entries(c))try{n.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof Nt&&(n.verbose(`Initializing ${r.name} service...`),await s.boot(...o))}catch(e){throw new a.InternalError(`Failed to boot ${r.name} service:${e}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof v||(r.push(s),s=void 0);const i=await Pt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new v(s).accumulate({...i,parentContext:s}):(new v).accumulate(i),r=[...r,s];const{log:n,ctxArgs:o}=Pt.prototype.logCtx(r,this.shutdown),c=t.Injectables.services();for(const[e,r]of Object.entries(c).reverse())try{n.verbose(`Shutting down ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);if(s instanceof Nt){n.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...o)}catch(e){n.error(`Failed to gracefully shutdown ${r.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],Pt.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],Pt.prototype,"unObserve",null);class Nt extends Pt{constructor(){super()}async boot(...t){const{config:r,client:a}=await this.initialize(...t);this._config=r,this._client=a;const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info("Shutting down...")}}function Bt(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&I(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Nt.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Nt.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Nt.prototype,"client",null);const Rt=()=>Bt(a.OperationKeys.CREATE),Lt=()=>Bt(a.OperationKeys.READ),$t=()=>Bt(a.OperationKeys.UPDATE),Ft=()=>Bt(a.OperationKeys.DELETE);function Kt(r){return(a,s,i)=>{i||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=x(r);const n=[];if(i&&"number"==typeof i.value)n.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...n)(a,s,i)}}const jt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ut extends Pt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ve.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=jt(e);try{const e=Pt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}select(e){return this.repo.select(e)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let a;t=jt(t||e);try{a=Ut.get(t)}catch(e){a=void 0}if(a instanceof Ut)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Kt(t),r.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo._adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"create",null),r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"createAll",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"delete",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"deleteAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"read",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"readAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Ut.prototype,"query",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"update",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Ut.prototype,"updateAll",null);class qt extends b{isSameObservedAdapter(e){if(!this.adapter)return!1;if(this.adapter===e)return!0;const t=this.adapter,r=e;return r instanceof U&&t.alias===r.alias&&t.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:n,ctx:o}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,l,d]=a,u=await t.call(r,c,l,d,...n),p=[c,i(e),l];return o.get("observeFullResult")&&p.push(Array.isArray(u)?u.map(e=>c(e)):c(u)),this.updateObservers(...p,...n).catch(t=>s.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(...e){}observe(e){if(!(e instanceof U))throw new T("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(e))return()=>this.unObserve(e);throw new T("Dispatch is already observing another adapter")}return this.adapter=e,this.models=U.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(!this.isSameObservedAdapter(e))throw new T("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 a.InternalError("Model must be provided for observer update");const n=e&&"string"==typeof e?e:i.Model.tableName(e);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${n}:${t}`);const{log:o,ctxArgs:c,ctx:l}=this.logCtx(s,this.updateObservers);try{o.debug(`dispatching observer refresh for ${t}:${n}: ${r}${l.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Gt(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await N.instance.generate(s)}function zt(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const n=e.PersistenceKeys.UUID;return o.Decoration.for(n).define({decorator:(t,r,...s)=>{const n={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Gt,n,{priority:54})];return t&&c.push(a.onUpdate(Gt,n,{priority:54})),t||c.push(a.readonly()),o.apply(...c)},args:[t,r,...s]}).apply()}U&&(U._baseDispatch=qt);class Yt extends b{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ve.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.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 a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:n,incrementBy:o,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return Yt.lock.execute(async()=>{const r=t||o;if(r%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof n&&n?.name?n.name:n,d=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(N.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(B.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.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.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new T(`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 a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}async ensureAtLeast(t,...r){const{ctx:s}=(await this.logCtx(r,a.OperationKeys.UPDATE,!0)).for(this.ensureAtLeast),{name:i}=this.options;if(!i)throw new a.InternalError("Sequence name is required");const n=this.parse(t),o=(e,t)=>"bigint"==typeof e||"bigint"==typeof t?BigInt(e)>BigInt(t):"number"==typeof e||"number"==typeof t?Number(e)>Number(t):e+"">t+"";return Yt.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(i,s)}catch(e){if(e instanceof a.NotFoundError)return;throw e}};for(;;)try{const r=await t();if(!r)return await this.repo.create(new e.SequenceModel({id:i,current:n}),s),n;const a=this.parse(r.current);return o(n,a)?(await this.repo.update(new e.SequenceModel({id:i,current:n}),s),n):a}catch(e){if(e instanceof a.ConflictError)continue;throw e}},i)}parse(e){return Yt.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return i.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new T(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Ht(e,...t){let r;if(e instanceof Ut&&(r=e.repo.adapter),e instanceof ve&&(r=e.adapter),e instanceof U&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function Vt(e,...t){return new L(Ht(e,...t))}U._baseSequence=Yt,o.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:(...e)=>(t,r,s)=>{if(!s)throw new a.InternalError("This decorator only applies to methods");return o.method()(t,r,s),o.Metadata.set(t.constructor,o.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,r),{data:e}),s.value=new Proxy(s.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),n=i.getOrUndefined("transactionLock")||Vt(t);let o;i.put("transactionLock",n),await n.acquire();try{o=await e.call(t,...r,i)}catch(e){try{await n.rollback(e)}catch(e){s.error("Failed to rollback transaction",e)}throw e}try{await n.release()}catch(e){throw new a.InternalError("Failed to release transaction: "+e)}return o}}),s}}).apply(),e.TaskBackoffModel=class extends i.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},r.__decorate([i.required(),i.type(String),i.option(e.BackoffStrategy),o.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),o.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),o.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),o.description("optional jitter strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([o.prop(),o.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([o.prop(),o.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([o.prop(),o.description("The error details"),r.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends i.Model{constructor(e){if(super(e),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}},r.__decorate([Fe(),a.composed(["taskId","classification","uuid"],":"),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([dt(),a.readonly(),i.required(),a.transient(),zt(!1),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),r.__decorate([dt(),a.readonly(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),r.__decorate([i.date(),dt(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),r.__decorate([dt(),a.readonly(),i.required(),i.option(e.TaskEventType),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),r.__decorate([o.prop(),dt(),a.serialize(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([lt("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Qt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof z){const r=this.serializePlain(e,...t);return r[i.ModelKeys.ANCHOR]="??condition",r}return i.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const r=this.serializePlain(e,...t),a=this.getMetadata(e.constructor)??e.constructor?.name;return a&&(r[i.ModelKeys.ANCHOR]=a),r}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return o.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[i.ModelKeys.ANCHOR],r=this.rebuildObject(e);return t?"??condition"===t?z.from(r):i.Model.build(r,t):r}rebuildObject(e){const t={};for(const[r,a]of Object.entries(e))r!==i.ModelKeys.ANCHOR&&(t[r]=this.rebuildValue(a));return t}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),r.__decorate([i.required(),i.option(s.LogLevel),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),r.__decorate([i.min(0),r.__metadata("design:type",Number)],e.TaskLogEntryModel.prototype,"step",void 0),r.__decorate([i.required(),o.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends i.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},r.__decorate([Fe(),zt(),o.description("the task id"),r.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),r.__decorate([dt(),i.required(),i.type(String),i.option(e.TaskType),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([dt(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([dt(),o.prop(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),r.__decorate([dt(),o.prop(),o.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),r.__metadata("design:type",String)],e.TaskModel.prototype,"lock",void 0),r.__decorate([dt(),i.required(),i.type(String),i.option(e.TaskStatus),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["nextRunAt"]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["leaseExpiry"]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["scheduledTo"]),o.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([o.prop(),dt(),a.serialize(Qt),o.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([o.prop(),dt(),a.serialize(Qt),o.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the error for failed tasks"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),r.__decorate([dt(),i.required(),i.min(0),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([dt(),i.min(1),i.required(),o.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([dt(),i.required(),a.serialize(),o.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),dt(),o.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),dt(),o.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([dt(),a.serialize(),o.description("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"dependencies",void 0),r.__decorate([o.prop(),dt(),o.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),dt(),o.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the various steps definition and inputs - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),r.__decorate([o.prop(),dt(),i.min(0),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([dt(),ft(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([dt(),yt(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([dt(),ht(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([dt(),gt(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([o.description("Holds the current step when applicable"),lt("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([o.prop(),o.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([o.prop(),o.description("the error of a failed step"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),e.TaskStepResultModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([i.minlength(1),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"name",void 0),r.__decorate([o.description("optional task step input"),o.prop(),r.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),r.__decorate([o.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),o.prop(),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"lock",void 0),r.__decorate([o.description("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),o.prop(),i.list(()=>String),r.__metadata("design:type",Array)],e.TaskStepSpecModel.prototype,"dependsOn",void 0),e.TaskStepSpecModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class Wt extends i.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,i.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}r.__decorate([i.required(),i.min(1e3),r.__metadata("design:type",Number)],Wt.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],Wt.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],Wt.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],Wt.prototype,"strategy",void 0);class Jt extends i.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Wt,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setLock(e){return this.lock=e,this}setDependencies(e){return this.dependencies=e,this}setDependsOn(e){return this.setDependencies(e)}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,i.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"classification",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],Jt.prototype,"name",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],Jt.prototype,"backoff",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],Jt.prototype,"input",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],Jt.prototype,"lock",void 0),r.__decorate([o.prop(),i.list(()=>String),r.__metadata("design:type",Array)],Jt.prototype,"dependencies",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],Jt.prototype,"maxAttempts",void 0);class Xt{constructor(e,t){this.parent=e,this.step=t}setClassification(e){return this.step.classification=e,this}setName(e){return this.step.name=e,this}setInput(e){return this.step.input=e,this}setLock(e){return this.step.lock=e,this}setDependsOn(e){return this.step.dependsOn=e,this}addStep(e,t,r){return this.parent.addStep(e,t,r)}setSteps(e){return this.parent.setSteps(e)}build(){return this.parent}}class Zt extends Jt{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),this}addStep(t,r,a){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,o=n&&"string"==typeof r?r:void 0,c=n?a:i?void 0:r,l=new e.TaskStepSpecModel({classification:t,name:o,input:c,createdAt:s,updatedAt:s});return this.steps.push(l),i?new Xt(this,l):this}}r.__decorate([i.list(()=>e.TaskStepSpecModel),r.__metadata("design:type",Array)],Zt.prototype,"steps",void 0);class er extends E{get type(){if(!this._type){const e=o.Metadata.get(this.constructor,Ee);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}async catch(e,t,r){}}function tr(e){return o.Decoration.for(Ee).define({decorator:e=>t=>{const r={type:e};return o.Metadata.set(Ee,e,t),o.metadata(Ee,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends er{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof z)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=z.attr("status").eq(e.TaskStatus.SUCCEEDED).and(z.attr("updatedAt").lte(t.successfulExpiry)),i=z.attr("status").eq(e.TaskStatus.FAILED).and(z.attr("updatedAt").lte(t.failedExpiry)),n=z.attr("status").eq(e.TaskStatus.CANCELED).and(z.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(n)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${n.length} tasks`),a.debug("deleted tasks:",n),n}catch(e){throw a.error("Error during task cleanup",e),e}}},r.__decorate([Te(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([tr("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class rr{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(s.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}for(e,...t){return new Proxy(this,{get(r,a){if("logger"===a){const s=Reflect.get(r,a);try{return s.for(e,...t)}catch(e){r.error("Failed to bind task logger. received: "+(s&&s.constructor?s.constructor.name:s.name?s.name:"unknown"),e);try{r.trace(JSON.stringify(s,void 0,2))}catch(e){r.trace("unserializable output: "+(s.name||"unknown"))}throw e}}return Reflect.get(r,a)}})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function ar(t,r={logProgress:!0,logStatus:!0,style:!0}){return async i=>{switch(t=t.for(i.taskId,{style:!1}),i.classification){case e.TaskEventType.LOG:{const e=i.payload.map(e=>Array.isArray(e)?e:[e.level,e.msg,e.meta]);for(let[a,i,n]of e){r.style||(i=s.style(i),i=i.clear().toString());const e=[i];a===s.LogLevel.verbose&&e.push(1),e.push(n);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=i.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=i.payload?.status??i.payload;let n=s.style(r);switch(r){case e.TaskStatus.SUCCEEDED:n=n.green.bold;break;case e.TaskStatus.RUNNING:n=n.blue.bold;break;case e.TaskStatus.PENDING:n=n.yellow;break;case e.TaskStatus.WAITING_RETRY:n=n.yellow.bold;break;case e.TaskStatus.FAILED:n=n.red.bold;break;case e.TaskStatus.CANCELED:n=n.magenta.bold;break;case e.TaskStatus.SCHEDULED:n=n.cyan;break;default:throw new a.InternalError("Received unknown task status: "+i.payload)}t.info("### STATUS "+n)}break;default:throw new a.InternalError("Unknown task event classification: "+i.classification)}}}function sr(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function ir(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function nr(e){return new Promise(t=>setTimeout(t,e))}class or extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=or.name,Object.setPrototypeOf(this,or.prototype)}}class cr extends v{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(e){this.cache.put("step",e)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new or({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?ir(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const r=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t));return{afterCurrent:async()=>{const e=this.getOrUndefined("scheduleCompositeSteps");if(!e)throw new a.InternalError("scheduleSteps().afterCurrent() is only available while running a composite task step");await e(r)}}}constructor(e){super(e)}}class lr{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=o.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class dr extends k{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:n}=U.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class ur extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class pr extends ur{constructor(e,t,r){super(pr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class hr extends ur{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(hr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class gr extends ur{constructor(e,t,r){super(gr.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class fr extends ur{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(fr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class yr{constructor(t,r){this.bus=t,this.task=r,this.resolved=!1,this.unregistration=t.observe(this,(t,r,a,...s)=>a.startsWith(this.task.id)&&(t===e.TaskEventModel||t===i.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(ar(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=(r.payload??[]).map(e=>Array.isArray(e)?e:[e.level,`${e.ts} - ${e.msg}`,e.meta]);await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}onUpdate(t){const r=async(r,a)=>{r.classification===e.TaskEventType.UPDATE&&await t(r,a)};return this.pipe(r,e.TaskEventType.UPDATE),()=>{this.pipes?.[e.TaskEventType.UPDATE]?.delete(r)}}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,n);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(t.classification!==e.TaskEventType.STATUS)return;if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new v),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new pr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new gr(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new hr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new fr(this.task.id,r,a);default:return new pr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class mr extends E{get Context(){return cr}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,e.TaskModel,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,e.TaskEventModel,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(e,t){const r=new cr(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1;const t=Object.assign({},ke.autoShutdown,e.autoShutdown);this.config=Object.assign({},ke,e,{autoShutdown:t,bus:e.bus||new dr,registry:e.registry||new lr}),this.idleDelayMs=this.config.pollMsIdle}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const n=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${n.id}`),t?{task:n,tracker:new yr(this.bus,n)}:n}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new yr(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await nr(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const n=await this.tasks.update(s,a);return await this.emitStatus(a,n,e.TaskStatus.CANCELED,i),n}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.idleDelayMs=this.config.pollMsIdle,this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(z.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const n=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(n),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(n),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},a=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),s=r.backoffStepMs??0;for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e)));const i=0===e.length;if(i)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+s,a),this.idleDelayMs>=a)return t.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(t)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const n=i?this.idleDelayMs:this.config.pollMsBusy;await nr(Math.max(n,0))}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=z.attribute("status").eq(e.TaskStatus.PENDING),i=z.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(z.attribute("nextRunAt").lte(a)),n=z.attribute("status").eq(e.TaskStatus.RUNNING).and(z.attribute("leaseExpiry").lte(a)),o=z.attribute("status").eq(e.TaskStatus.SCHEDULED).and(z.attribute("scheduledTo").lte(a)),c=s.or(i).or(n).or(o),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}if(!await this.isRunnable(i,r))return null;const n=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,r)}catch{return null}}isTaskFinished(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t)}parseTaskDependency(e){const t=e?.trim();if(!t)return;const r=t.lastIndexOf(":");if(0>=r||r>=t.length-1)return{taskId:t};const a=t.slice(0,r).trim(),s=t.slice(r+1).trim();return a&&s?{taskId:a,stepRef:s}:{taskId:t}}normalizeDependencies(e){if(!e)return[];let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{t=[t]}return t instanceof Set&&(t=Array.from(t)),Array.isArray(t)?t.filter(e=>"string"==typeof e).map(e=>this.parseTaskDependency(e)).filter(Boolean):[]}resolveDependencyStepIndex(e,t){const r=t.trim();if(!r)return;const a=Number(r);if(Number.isInteger(a)&&a>=0)return a;const s=this.normalizeSteps(e.steps).findIndex(e=>e.name===r||e.classification===r);return 0>s?void 0:s}async areDependenciesSatisfied(e,t){if(!e.length)return!0;const r=Array.from(new Set(e.map(e=>e.taskId))),a=new Map;try{const e=await this.tasks.readAll(r,t);for(const t of e)t?.id&&a.set(t.id,t)}catch{return!1}for(const t of e)try{const e=a.get(t.taskId);if(!e)return!1;if(!t.stepRef){if(!this.isTaskFinished(e.status))return!1;continue}const r=this.resolveDependencyStepIndex(e,t.stepRef);if(null==r)return!1;const s=this.normalizeStepResults(e.stepResults)[r];if(!s||!this.isTaskFinished(s.status))return!1}catch{return!1}return!0}getStepLock(t,r){if(t.atomicity!==e.TaskType.COMPOSITE)return;const a=this.normalizeSteps(t.steps);if(!a.length)return;const s=a[r??0];return s?.lock}async hasLockConflict(t,r,a){const s=[t.lock,this.getStepLock(t,r)].filter(e=>!!e&&"string"==typeof e);if(!s.length)return!1;const i=await this.tasks.select().where(z.attribute("status").eq(e.TaskStatus.RUNNING)).execute(a);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(e=>!!e&&"string"==typeof e).some(e=>s.includes(e)))return!0;return!1}async isRunnable(t,r){const a=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(a,r))return!1;const s=t.atomicity===e.TaskType.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,r)}async executeClaimed(t){const{ctx:r,log:i}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),n=this;let o=Promise.resolve();const c=new cr(r).accumulate({taskId:t.id,logger:new rr(i,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=n.normalizePipeArgs(e);r.length&&(o=o.then(async()=>{const[e,a]=await n.appendLog(this,t,r);Object.assign(t,e),await n.emitLog(this,t.id,a)}),await o)},flush:async()=>c.logger.flush(c.pipe),progress:async e=>{await this.emitProgress(c,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let l,d;await this.emitStatus(c,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,c);try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(l=e,d=t.input,i.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,c),await c.flush(),i.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const s=await this.tasks.update(t,c);Object.assign(t,s),c.logger.info(`task ${t.id} success state ${t.status}`),i.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(c,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{await c.flush()}catch{}try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}if(r instanceof or)return void await this.handleTaskStateChange(r.request,t,c);try{await(l?.catch?.(d,r,c))}catch(e){i.error("task handler catch() hook failed",e)}if(i.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=ir(r);if(a<t.maxAttempts){const o=sr(a,this.normalizeBackoff(t.backoff)),l=new Date(Date.now()+o);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=l,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const d=await this.tasks.update(t,c);Object.assign(t,d),i.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await c.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:l,delayMs:o,attempt:a}),await this.emitStatus(c,t,e.TaskStatus.WAITING_RETRY,n,r)}else{t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const o=await this.tasks.update(t,c);Object.assign(t,o),i.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await c.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(c,t,e.TaskStatus.FAILED,n,r)}}}async handleTaskStateChange(t,r,i){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.CANCELED,a),void await i.pipe(s.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,n=sr(a,this.normalizeBackoff(r.backoff)),o=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+n),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=o,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.WAITING_RETRY,c),void await i.pipe(s.LogLevel.warn,"Retry requested",{nextRunAt:o,delayMs:n,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const n=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=n,r.nextRunAt=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.SCHEDULED,n),void await i.pipe(s.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite);let i=this.normalizeSteps(t.steps),n=t.currentStep??0;const o=this.normalizeStepResults(t.stepResults),c=(e,t)=>{r.cacheResult(e,t),a instanceof cr&&a!==r&&a.cacheResult(e,t)};for(let r=0;r<o.length;r+=1){const a=o[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=i[r];if(!e)continue;const s=`${t.id}:step:${r}`;c(e.classification,a.output),c(s,a.output)}}for(;n<i.length;){r.setStep(n);const l=i[n],d=this.registry.get(l.classification);if(!d)throw Error("No task handler registered for composite step: "+l.classification);const u=this.normalizeDependencies(l.dependsOn);await this.areDependenciesSatisfied(u,r)||r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${n} (${l.classification})`),await this.hasLockConflict(t,n,r)&&r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${n} (${l.classification})`),t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await r.progress({currentStep:n,totalSteps:i.length});const h=n;r.cache.put("scheduleCompositeSteps",async a=>{const s=this.normalizeSteps(a);if(!s.length)return;const n=this.normalizeSteps(t.steps),o=Math.min(h+1,n.length);n.splice(o,0,...s),t.steps=n;const c=await this.tasks.update(t,r);Object.assign(t,c),i=this.normalizeSteps(t.steps);const l=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:h,totalSteps:i.length,output:{added:s.length,insertionIndex:o}});this.bus.emit(l,r)}),await r.pipe([s.LogLevel.info,`Composite step ${n+1}/${i.length}: ${l.classification}`]);try{const a=await d.run(l.input,r);await r.flush();const s=new Date;o[h]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:a,createdAt:s,updatedAt:s});const u=`${t.id}:step:${h}`;c(l.classification,a),c(u,a),n=h+1,t.stepResults=o,t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await this.emitProgress(r,t.id,{currentStep:n,totalSteps:i.length,output:a})}catch(s){try{await(d.catch?.(l.input,s,r))}catch(e){a.logger.warn("composite step catch() hook failed",{error:e})}const i=new Date;o[n]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:ir(s),createdAt:i,updatedAt:i}),t.stepResults=o,t.currentStep=n,t.error=ir(s);const c=await this.tasks.update(t);throw Object.assign(t,c),s}}return{stepResults:o}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=Array.isArray(a)&&Array.isArray(a[0]),i=r.atomicity===e.TaskType.COMPOSITE?t instanceof cr?t.step??r.currentStep:r.currentStep:void 0,n=(s?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a,step:i})),o=[...r.logTail??[],...n].slice(-this.config.logTailMax);r.logTail=o;try{return[await this.tasks.update(r,t),n]}catch{return[r,[]]}}async emitStatus(t,r,a,s,i){t instanceof cr&&await t.flush();const n={status:a};s&&s instanceof e.TaskErrorModel?n.error=s:s&&(n.output=s),r.nextRunAt&&(n.nextRunAt=r.nextRunAt),r.scheduledTo&&(n.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,n),c=void 0!==i?Object.assign({},n,{originalError:i}):n,l=new e.TaskEventModel({...o,payload:c});this.bus.emit(l,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta,step:e.step})));this.bus.emit(s,t)}normalizePipeArgs(e){if(!e.length)return[];if(1===e.length){const t=e[0];return Array.isArray(t)?0===t.length?[]:Array.isArray(t[0])?t.filter(Array.isArray):[t]:[]}const[t,r,a]=e;return"string"!=typeof t||"string"!=typeof r?[]:[[t,r,a]]}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class wr extends Nt{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...e){const t=e.shift();if(!t||t instanceof v)throw new a.InternalError("No/invalid config provided");if(!t.adapter)throw new a.InternalError("No adapter provided");return{client:new(t.engine||mr)(t),config:t}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}select(e){return this.tasks.select(e)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.tasks.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.tasks.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.tasks.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.tasks?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.tasks,s)}async update(e,...t){throw new T("Updates to tasks are not available")}async updateAll(e,...t){throw new T("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...a)}refresh(e,t,r,...a){return this.tasks.refresh(e,t,r,...a)}observe(e,t){return this.tasks.observe(e,t)}unObserve(e){return this.tasks.unObserve(e)}updateObservers(e,t,r,...a){return this.tasks.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.tasks._adapter.logCtx([this.tasks.class,...e],t,r,this.tasks._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}function _r(e,t){return e.reduce((e,r)=>e+(e=>{if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}})(r[t]),0)}function vr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"create",null),r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"createAll",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"delete",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"deleteAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"read",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"readAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"query",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"update",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"updateAll",null);const br=Object.assign({},g,{persistMigrationSteps:!0});class Sr{constructor(e="migration-task"){this.builder=(new Zt).setClassification("migration-composite").setName(e).setMaxAttempts(1)}addMigrationStep(e){return this.builder.addStep("migration",e),this}addStep(e,t){return this.builder.addStep(e,t),this}build(){return this.builder.build()}}class Er{isVersionHint(e){return!!e}normalize(e,t){return t&&e&&(e.includes(t)||e===t)?t:e||t||"migration"}compare(e,t){return e.localeCompare(t)}gt(e,t){return this.compare(e,t)>0}lte(e,t){return 0>=this.compare(e,t)}}class kr extends Nt{constructor(){super(),this.versioning=new Er,this.queuedTaskChain=[],this.reference=kr.name,this.precedence=null}static async migrateAdapters(e,t={},...r){const s=t.flavours?.length?new Set(t.flavours):void 0,i=e.filter(e=>!s||s.has(e.flavour)),n=new Set(e.map(e=>e.alias||e.flavour).filter(Boolean)),o=t.taskService?.client,c=o?.adapter?.alias||o?.adapter?.flavour;if(c&&n.has(c))throw new a.InternalError(`TaskEngine adapter alias "${c}" cannot participate in the migration targets`);const l=[];for(const e of i){const a=t.handlers?.[e.flavour]||{},s=new kr;l.push(s),await s.boot({persistenceFlavour:e.flavour,targetVersion:t.toVersion,taskMode:!!t.taskMode,includeGenericInTaskMode:!(t.taskMode&&i.length>1),retrieveLastVersion:a.retrieveLastVersion,setCurrentVersion:a.setCurrentVersion,taskService:t.taskService}),t.taskMode?await s.migrateViaTasks(void 0,void 0,...r):await s.migrateNormally(void 0,void 0,...r)}return l}async initialize(...t){const{log:r,ctx:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);try{Pt.get(e.PersistenceKeys.PERSISTENCE)}catch(e){a.get("ignoreDevSafeGuards")||r.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:br,br);return this.versioning=s.versioning||new Er,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?U.get(s.persistenceFlavour):void 0}}async down(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(s.style("Cleaning up after all migrations").green.bold)}normalizeVersion(e,t){return this.versioning.normalize(e,t)}extractPrecedenceTokens(e){const t=e.precedence;return t?(Array.isArray(t)?t:[t]).map(e=>{if(e&&"string"!=typeof e)return"function"==typeof e?e.name:"string"==typeof e.reference?e.reference:e.constructor?.name?e.constructor.name:void 0}).filter(e=>!!e):[]}referencesMigration(e,t){const r=this.extractPrecedenceTokens(e);return!!r.length&&(r.includes(t.reference)||r.includes(t.migration?.constructor?.name))}precedenceHint(e){return"string"==typeof e.precedence?e.precedence:void 0}compareByPrecedence(e,t){const r=e.migration,a=t.migration,s=this.referencesMigration(r,t),i=this.referencesMigration(a,e);if(s&&!i)return 1;if(i&&!s)return-1;const n=this.extractPrecedenceTokens(r),o=this.extractPrecedenceTokens(a);return n.length!==o.length?n.length-o.length:0}sort(e){const t=[...e].sort((e,t)=>{const r=this.versioning.compare(e.version,t.version);if(0!==r)return r;const a=this.compareByPrecedence(e,t);if(0!==a)return a;const s=e.flavour.localeCompare(t.flavour);return 0!==s?s:e.reference.localeCompare(t.reference)});for(let e=0;e<t.length;e++){const r=t[e],s=t[e+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new a.InternalError(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return t}resolveMigration(t){const r=o.Metadata.get(t.constructor,e.PersistenceKeys.MIGRATION),a=r?.flavour||t.flavour||o.DefaultFlavour,s=r?.reference||t.reference,i=this.precedenceHint(t);return{migration:t,flavour:a,reference:s,version:this.normalizeVersion(s,i)}}shouldIncludeMigration(e,t,r=!0){return!t||e.flavour===t||r&&e.flavour===o.DefaultFlavour}collectMigrations(e,t=!0){const r=o.Metadata.migrations(),s=[];for(const[i,n]of r){let r;try{r=new n}catch(e){throw new a.InternalError(`failed to create migration ${i}: ${e}`)}const o=this.resolveMigration(r);this.shouldIncludeMigration(o,e,t)&&s.push(o)}return s}buildExecutionPlan(e){const t=e?.fromVersion?this.normalizeVersion(e.fromVersion):void 0,r=e?.toVersion?this.normalizeVersion(e.toVersion):void 0;return this.sort(this.collectMigrations(e?.targetFlavour,e?.includeGeneric)).filter(e=>!(t&&!this.versioning.gt(e.version,t)||r&&!this.versioning.lte(e.version,r)))}async executeMigration(e,...t){const r=e.migration;let s,i;try{if(s=U.get(e.flavour),!s)throw new a.InternalError(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(e){throw new a.InternalError(`Failed to load adapter to migrate ${r.reference}: ${e}`)}try{await r.up(i,s,...t)}catch(e){throw new O(`failed to initialize migration ${r.reference}: ${e}`)}try{await r.migrate(i,s,...t)}catch(e){throw new O(`failed to migrate ${r.reference}: ${e}`)}try{await r.down(i,s,...t)}catch(e){throw new O(`failed to conclude migration ${r.reference}: ${e}`)}}buildMigrationTaskForPlan(e,...t){const r=[...t],a=new Sr;return e.forEach(e=>{const t={reference:e.reference,args:r};a.addMigrationStep(t)}),a.build()}buildMigrationTasksForPlan(e,...t){const r=new Map;for(const t of e){const e=r.get(t.version)||[];e.push(t),r.set(t.version,e)}return[...r.entries()].map(([e,r])=>({version:e,task:this.buildMigrationTaskForPlan(r,...t)}))}createMigrationTask(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTaskForPlan(i,...r)}createMigrationTasks(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTasksForPlan(i,...r)}migrationTaskIdsFromContext(e,t){const r=t[t.length-1],a=r?.pending?.()||r?.pending||{},s=a?.[e];return Array.isArray(s)?s.filter(e=>"string"==typeof e):[]}async migrate(e,t,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(t,r,...a){const{ctxArgs:s,log:i}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateNormally),n=this.config,o=n.persistenceFlavour,c=!n.taskMode||(n.includeGenericInTaskMode??!0),l=o?U.get(o):void 0;let d;if(n.retrieveLastVersion&&l){const e=await n.retrieveLastVersion(l,...s);e&&(d=this.normalizeVersion(e))}const u=this.buildExecutionPlan({fromVersion:d,toVersion:n.targetVersion,targetFlavour:o,includeGeneric:c});i.debug("sorted migration before execution: "+u.map(e=>`${e.reference}@${e.version}`));for(const e of u)await this.executeMigration(e,...s);if(n.setCurrentVersion&&l){const e=n.targetVersion||u[u.length-1]?.version||d||void 0;e&&await n.setCurrentVersion(this.normalizeVersion(e),l,...s)}}async migrateViaTasks(t,r,...a){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateViaTasks),o=this.config,c=o.persistenceFlavour,l=o.includeGenericInTaskMode??!0,d=c?U.get(c):void 0;let u;if(o.retrieveLastVersion&&d){const e=await o.retrieveLastVersion(d,...i);e&&(u=this.normalizeVersion(e))}const p=this.buildExecutionPlan({fromVersion:u,toVersion:o.targetVersion,targetFlavour:c,includeGeneric:l});if(n.debug("sorted migration before execution: "+p.map(e=>`${e.reference}@${e.version}`)),this.queuedTaskChain=[],p.length){const t=this.buildMigrationTasksForPlan(p,...i);if(o.taskService){let r;for(const a of t){r&&(a.task.dependencies=[...a.task.dependencies||[],r]);const t=await o.taskService.push(a.task,!1,...i);r=t.id,this.queuedTaskChain.push({id:t.id,version:a.version}),t?.id||n.warn("TaskService.push returned missing id for version "+a.version),s.pushPending(e.PersistenceKeys.MIGRATION,t.id)}}else{for(const e of p)await this.executeMigration(e,...i);if(o.setCurrentVersion&&d){const e=o.targetVersion||p[p.length-1]?.version||u||void 0;e&&await o.setCurrentVersion(this.normalizeVersion(e),d,...i)}}}}async track(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.track),s=this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return;const l=this.queuedTaskChain.reduce((e,t)=>(e[t.id]=t.version,e),{}),d=this.config.persistenceFlavour?U.get(this.config.persistenceFlavour):void 0;for(const e of c){const{tracker:t}=await s.taskService.track(e,...a);await t.wait(),s.setCurrentVersion&&d&&l[e]&&await s.setCurrentVersion(this.normalizeVersion(l[e]),d,...a)}}async retry(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.retry),s=this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...a);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return void await this.migrateViaTasks(void 0,void 0,...a);const l=s.taskService.client.tasks,d="function"==typeof l?.override?l.override({ignoreHandlers:!0}):l;for(const t of c){const r=(await s.taskService.track(t,...a)).task;if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(r.status))continue;const i=new e.TaskModel({...r,status:e.TaskStatus.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await d.update(i,...a)}}async up(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(s.style("Setting up migration process").yellow.bold)}}const Tr=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),o.DefaultFlavour)||[];o.Metadata.set(e.PersistenceKeys.MIGRATION,o.DefaultFlavour,[...Tr,kr]),e.MigrationTask=class extends er{async run(t,r){r.logger.info("Executing migration "+t.reference);const s=o.Metadata.migrations().find(([,r])=>{const a=r?.name,s=o.Metadata.get(r,e.PersistenceKeys.MIGRATION)?.reference;return a===t.reference||s===t.reference});if(!s)throw new a.InternalError(`Migration ${t.reference} is not registered with the metadata layer`);const i=s[1];let n;try{n=new i}catch(e){throw new a.InternalError(`Failed to instantiate migration ${t.reference}: ${e}`)}const c=o.Metadata.get(n.constructor,e.PersistenceKeys.MIGRATION),l=c?.flavour||n.flavour,d=U.get(l);if(!d)throw new a.InternalError("Unable to resolve adapter for migration "+t.reference);const u=d.client,p=t.args??[];try{await n.up(u,d,...p,r)}catch(e){throw r.logger.error(`Up phase for ${t.reference} failed: ${e}`),new O(`Up phase for ${t.reference} failed: ${e}`)}try{await n.migrate(u,d,...p,r)}catch(e){throw r.logger.error(`migration phase for ${t.reference} failed: ${e}`),new O(`Migration phase for ${t.reference} failed: ${e}`)}try{await n.down(u,d,...p,r)}catch(e){throw r.logger.error(`down phase for ${t.reference} failed: ${e}`),new O(`Down phase for ${t.reference} failed: ${e}`)}r.logger.info(`migration ${t.reference} completed`)}},e.MigrationTask=r.__decorate([tr("migration")],e.MigrationTask),t.Injectables.setRegistry(new Se);const Or="##VERSION##",Ar="##PACKAGE##";o.Metadata.registerLibrary(Ar,Or),e.AbsContextual=E,e.AbsMigration=class extends E{get reference(){if(!this._reference){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._reference=t.reference,!this._reference)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._precedence=t.precedence,!this._precedence)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;P(this,e,this.prefix(t))})}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return U.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const e of s)if(!await e(t,r,a))return!1;return!0}prefix(t){return async function(r){let a;r instanceof U?a=this.getQueryRunner(r.client):(a=r,r=this.adapter);const{ctx:s,log:i}=await this.logCtx([t],e.PersistenceKeys.MIGRATION,!0);if(!await this.enforceRules(a,r,s))throw i.verbose(`Skipping migration ${this.constructor.name} due to rules`),new A("Migration skipped for rule enforcement");return[a,r,s]}.bind(this)}},e.Adapter=U,e.AdapterTransaction=R,e.AuthorizationError=nt,e.BaseModel=Et,e.BigIntSequence=De,e.ClientBasedService=Nt,e.CompositeTaskBuilder=Zt,e.Condition=z,e.ConnectionError=ct,e.Context=v,e.ContextLock=L,e.ContextualLoggedClass=b,e.DefaultAdapterFlags=g,e.DefaultCascade=V,e.DefaultContextFlags=h,e.DefaultMigrationConfig=br,e.DefaultRepositoryFilters=oe,e.DefaultSequenceOptions=Ce,e.DefaultTaskEngineConfig=ke,e.Dispatch=qt,e.ForbiddenError=ot,e.InjectablesRegistry=Se,e.MethodQueryBuilder=J,e.MigrationError=O,e.MigrationRuleError=A,e.MigrationService=kr,e.MigrationTaskBuilder=Sr,e.ModelService=Ut,e.MultipleSelectOperationKeys=w,e.NonTransactionOperationKeys=y,e.NoneSequenceOptions=xe,e.NumericSequence=Me,e.ObserverError=Oe,e.ObserverHandler=k,e.OperatorsMap=Q,e.PACKAGE_NAME=Ar,e.PaginationOperationKeys=_,e.Paginator=kt,e.PagingError=G,e.PersistenceService=class extends Nt{constructor(){super()}for(e,...t){throw new T("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof v||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),n=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of n)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:n,config:r}}},e.QueryError=q,e.Repository=ve,e.SelectOperationKeys=m,e.Sequence=Yt,e.Serial=B,e.Service=Pt,e.StandardMigrationVersioning=Er,e.Statement=It,e.TaskBackoffBuilder=Wt,e.TaskBuilder=Jt,e.TaskCancelError=gr,e.TaskContext=cr,e.TaskControlError=ur,e.TaskEngine=mr,e.TaskEventBus=dr,e.TaskEventService=class extends Ut{constructor(){super(e.TaskEventModel)}get repo(){return this._repository||(this._repository=Pt.get(e.TaskModel).events),this._repository}},e.TaskFailError=pr,e.TaskHandler=er,e.TaskHandlerRegistry=lr,e.TaskIOSerializer=Qt,e.TaskLogger=rr,e.TaskRescheduleError=fr,e.TaskRetryError=hr,e.TaskService=wr,e.TaskStepSpecBuilder=Xt,e.TaskTracker=yr,e.TasksKey=Ee,e.TransactionOperationKeys=f,e.UUID=N,e.UnsupportedError=T,e.VERSION=Or,e.allowIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:o}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,n)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...o)}})},e.applyViewDecorator=Z,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return o.Decoration.for(r).define({decorator:e=>o.metadata(r,e),args:[t]}).apply()},e.blockIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:o}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,n)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...o)}})},e.cacheModelForPopulate=tt,e.cascadeDelete=at,e.column=dt,e.computeBackoffMs=sr,e.create=Rt,e.createOrUpdate=Ke,e.createdAt=ft,e.createdBy=ht,e.createdByOnCreateUpdate=pt,e.defaultQueryAttr=()=>(t,r)=>{const a=o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let s=o.Metadata.get(t.constructor,a)||[];return s=[...new Set([...s,r])],o.apply(o.propMetadata(a,s))(t,r)},e.del=Ft,e.generateInjectableNameForRepository=be,e.getAdapterTransaction=Ht,e.getAndConstructJunctionTable=Ze,e.getContextLock=Vt,e.getFilters=ce,e.getLogPipe=ar,e.getPkTypes=vt,e.getPopulateKey=et,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ie,e.injectableServiceKey=x,e.isOperationBlocked=I,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.list([e,...d]),a.onCreate(Je,c),a.onUpdate(ze,c),a.afterAny(rt,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToManyOnCreate=Je,e.manyToManyOnDelete=async function(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n||!n.length)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ve.forModel(c,this.adapter.alias):it(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await tt(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Je.call(this,t,r,a,s)},e.manyToOne=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.type([e,...d]),a.onCreate(He,c),a.onUpdate(Qe,c),a.onDelete(We,c),a.afterAny(rt,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToOneOnCreate=He,e.manyToOneOnDelete=We,e.manyToOneOnUpdate=Qe,e.migration=(t,r,a,s)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(r,a,s)=>i=>{const n=r&&"object"==typeof r&&!("name"in r)?r:void 0,c=n?.precedence,l=n?.flavour,d=n?.rules,u=n?c:r,p=n?l:a,h=n?d:s,g=n?void 0!==c:void 0!==u&&("string"!=typeof u||"string"==typeof u&&"string"==typeof p);let f,y,m=u;"string"==typeof u?"string"==typeof p?(m=u,f=p,y=h):Array.isArray(p)?(m=void 0,f=u,y=p):(m=void 0,f=u,y=h):Array.isArray(p)?y=p:(f=p,y=h),void 0===m&&null!==m&&(m=kr);const w=o.Metadata.flavourOf(i)||o.DefaultFlavour,_=(g&&m===kr&&t&&t!==f?t:f)||w,v=o.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")),_||o.DefaultFlavour)||[];return o.Metadata.set([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-"),_||o.DefaultFlavour,[...v,{class:i}]),o.Metadata.set(e.PersistenceKeys.MIGRATION,t,i),o.metadata(e.PersistenceKeys.MIGRATION,{reference:t||i.name,precedence:m,flavour:_||o.DefaultFlavour,rules:y})(i)},args:[r,a,s]}).apply(),e.noValidateOn=bt,e.noValidateOnCreate=()=>bt(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>bt(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>bt(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.list([e,...d]),a.onCreate(Ge,c,{priority:70}),a.onUpdate(ze,c,{priority:70}),a.onDelete(Ye,c,{priority:70}),a.onUpdate(at,c,{priority:80}),a.afterAny(rt,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToManyOnCreateUpdate=Ge,e.oneToManyOnDelete=Ye,e.oneToManyOnUpdate=ze,e.oneToOne=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.type([e,...d]),a.onCreate(je,c,{priority:70}),a.onUpdate(Ue,c,{priority:70}),a.onDelete(qe,c,{priority:70}),a.onUpdate(at,c,{priority:80}),a.afterAny(rt,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToOneOnCreate=je,e.oneToOneOnDelete=qe,e.oneToOneOnUpdate=Ue,e.onlyOnBulk=ie,e.onlyOnCreate=ee,e.onlyOnDelete=re,e.onlyOnFilter=ne,e.onlyOnSingle=se,e.onlyOnTransactional=ae,e.onlyOnUpdate=te,e.persistentVersion=_t,e.pk=Fe,e.pkDec=Le,e.pkOnCreate=Be,e.populate=rt,e.prefixMethod=P,e.prepared=X,e.promiseSequence=C,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>function r(s,i,n){const c=J.getFieldsFromMethodName(i);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,i),{...t,fields:c}),X(),(e=>(t,s,i)=>{i.value=new Proxy(i.value,{async apply(t,s,i){const{action:n,select:o,selector:c,where:l,groupBy:d,orderBy:u,limit:p,offset:h}=J.build(t.name,...i);if(!(s instanceof a.Repository))throw Error("thisArg must be an instance of Repository");const g=s,{ctx:f}=(await g.logCtx(i,r.name,!0)).for(r);let y;switch(n){case"find":case"page":y=g.select(o);break;case"count":y=g.count(c);break;case"sum":y=g.sum(c);break;case"avg":y=g.avg(c);break;case"min":y=g.min(c);break;case"max":y=g.max(c);break;case"distinct":y=g.distinct(c);break;case"group":y=g.select(),c&&(y=y.groupBy(c));break;default:throw new q("Unsupported action: "+n)}if(l&&(y=y.where(l)),d&&d.length>0&&"group"!==n){y=y.groupBy(d[0]);for(let e=1;e<d.length;e++)y=y.thenBy(d[e])}else if(d&&d.length>0&&"group"===n)for(const e of d)y=y.thenBy(e);const{allowLimit:m,allowOffset:w,allowOrderBy:_,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},b=[{key:"orderBy",value:(u||[])[0],allowed:_},{key:"limit",value:p,allowed:m},{key:"offset",value:h,allowed:w}];for(const e of b)if(void 0!==e.value){if(!e.allowed&&v)throw new q(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(y=y[e.key](e.value))}if("page"===n){const e=i[i.length-1],t="number"==typeof e?e:e?.limit??10;return y.paginate(t,f)}return y.execute(f)}})})(t))(s,i,n)},args:[t]}).apply(),e.read=Lt,e.relation=St,e.repository=Te,e.repositoryFromTypeMetadata=it,e.resolveBulkSequenceResult=j,e.roles=t=>o.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return o.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const n={path:r,httpMethod:t,handler:i};return o.apply(o.methodMetadata(o.Metadata.key(a,s),n))(e,s,i)},args:[]}).apply()},e.sequence=(t,r)=>{const a=Object.assign({},Ce);delete a.generated,t=Object.assign({},a,t);const s="boolean"==typeof r?{update:r}:r||{};return o.Decoration.for(e.PersistenceKeys.SEQUENCE).define({decorator:$e,args:[t,s,{priority:70}]}).apply()},e.sequenceDec=$e,e.sequenceOnCreateUpdate=Re,e.serializeError=ir,e.service=Kt,e.sleep=nr,e.table=lt,e.task=tr,e.throttle=(t={count:1},r=0)=>function s(i,n,c){return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.THROTTLE,n),t),(i,n,o)=>{o.value=new Proxy(o.value,{async apply(i,o,c){const l=c,d=(()=>{try{return"function"==typeof t?t(...l):t}catch(e){throw new a.InternalError("Failed to obtain throttling configuration from handler: "+e)}})(),{log:u,ctx:p}=(await o.logCtx(c,e.PersistenceKeys.THROTTLE,!0)).for(s),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttling() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(r);if(!h.length)throw new a.InternalError("@throttling() expects at least one argument index to throttle");h.forEach(e=>{if(e>=l.length)throw new a.InternalError(`@throttling() requires argument index ${e} but only ${l.length} provided`);if(!Array.isArray(l[e]))throw new a.InternalError(`@throttling() expects argument at index ${e} to be an array`)});const g=h.map(e=>l[e]),f=g[0].length;if(!g.every(e=>e.length===f))throw new a.InternalError("@throttling() requires all targeted arguments to have the same length");if(0===f)return i.apply(o,l);const y=((e,t,r)=>{if("count"in r){if(0>=r.count)throw new a.InternalError("@throttling() configuration 'count' must be greater than zero");const t=[];for(let a=0;e>a;a+=r.count)t.push({start:a,end:Math.min(e,a+r.count)});return t}if("bufferSize"in r){if(0>=r.bufferSize)throw new a.InternalError("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let a=0;e>a;a++){const e=_r(t,a);n>0&&n+e>r.bufferSize?(s.push({start:i,end:a}),i=a,n=e):n+=e}return i>=e&&s.length||s.push({start:i,end:e}),s}return[{start:0,end:e}]})(f,g,d),m=y.map(({start:e,end:t})=>l.map((r,a)=>{const s=h.indexOf(a);return-1===s?r:g[s].slice(e,t)})),w=p.get("breakOnSingleFailureInBulk")??!0,_=[],v=[];for(const e of m){try{vr(await i.apply(o,e),_)}catch(e){if(w)throw e;v.push(e)}d.delayMs&&await new Promise(e=>setTimeout(e,d.delayMs))}if(v.length){u.warn(`${n+""} throttled execution continued with ${v.length} failure(s)`);const e=new AggregateError(v,`Throttled ${n+""} failed for ${v.length} chunk(s)`);throw e.results=_,e}return _}})})(i,n,c)},e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(i.async(),a.onCreateUpdate(ut),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=ut,e.update=$t,e.updatedAt=yt,e.updatedBy=gt,e.uuid=zt,e.uuidCreateUpdateHandler=Gt,e.validBidirectionalRelation=Ve,e.version=(e=!1)=>e?_t():a.version(),e.view=t=>o.Decoration.for(e.Operator.VIEW).define({decorator:t=>Z(e.Operator.VIEW,"view",t),args:[t]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/transactional-decorators","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsTransactionalDecorators,e.decafTsDecoration);
1
+ var e,t;e=this,t=function(e,t,r,a,s,i,n,o){"use strict";var c,l,d,u,p;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_BY_PAGINATE="findByPaginate",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.FIND="find",u.PAGE="page",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf",e.PersistenceKeys=void 0,(p=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",p.INDEX="index",p.SEQUENCE="sequence",p.UNIQUE="unique",p.ADAPTER="adapter",p.INJECTABLE="decaf_{0}_adapter_for_{1}",p.SERVICE="service",p.TABLE="table",p.COLUMN="column",p.METADATA="__metadata",p.OWNERSHIP="ownership",p.CREATED_BY="ownership.created-by",p.UPDATED_BY="ownership.updated-by",p.RELATIONS="__relations",p.RELATION="relation",p.ONE_TO_ONE="relation.one-to-one",p.ONE_TO_MANY="relation.one-to-many",p.MANY_TO_ONE="relation.many-to-one",p.MANY_TO_MANY="relation.many-to-many",p.POPULATE="populate",p.NO_VALIDATE="no-validate",p.MIGRATION="migration",p.STATEMENT="statement",p.QUERY="query",p.UUID="uuid",p.TAG_FOR_DELETION="tag_for_deletion",p.INITIALIZATION="initialization",p.SHUTDOWN="shutdown",p.BY_KEY="by-key",p.AUTH="auth",p.AUTH_ROLE="auth-role",p.DECAF_ROUTE="DecafRoute",p.THROTTLE="throttle",p.PERSISTENT_VERSION="persistent-version",p.DEFAULT_QUERY_ATTR="default-query-attr";const h=Object.assign({},{ignoreDevSafeGuards:!1}),g=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1}),f=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],y=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],m=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],w=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],_=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.PAGE];class v extends a.Context{constructor(e){super(e)}static{this.factory=e=>(new v).accumulate(Object.assign({},e,{timestamp:new Date,logger:e.logger||s.Logging.get()}))}static async from(e,t,r,...a){return this.factory(Object.assign({},t||{},{operation:e,model:r,affectedTables:r,args:a,logger:t?.logger||s.Logging.get()}))}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).reduce((e,t)=>(Array.isArray(t)?e.push(...t):null!=t&&e.push(t),e),[]).filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}pending(){return this.getFromChildren("pending")}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 a.InternalError("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 b extends s.LoggedClass{logCtx(e,t,r=!1,a){return b.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...i){const n=(e,t,r)=>{const a=t.log||s.Logging.get();return t.log=e.context?a.clear().for(e):a.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let o=i.pop();const c=o instanceof v||(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"function"==typeof t.get&&"function"==typeof t.accumulate&&"function"==typeof t.override&&"function"==typeof t.toOverrides&&void 0!==t.cache})(o);if(o&&!c&&(i.push(o),o=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!o)throw new a.InternalError("Missing context. should be impossible");return n(this,{log:o.logger,ctx:o,ctxArgs:[...i,o]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...i,o].filter(Boolean)).then(t=>n(this,{log:t.logger,ctx:t,ctxArgs:[...i,t]},e))}}class E extends b{constructor(){super(),this._Context=v}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 a=r.pop();return a instanceof v||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class k{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");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 a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=b.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:n}=a;if(!n)return!0;try{return n(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>{a.observer.refresh(e,t,r,...i)}))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class T extends a.InternalError{constructor(e){super(e,T.name,500)}}class O extends a.InternalError{constructor(e,t=O.name){super(e,t,500)}}class A extends O{constructor(e){super(e,A.name)}}function x(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}async function C(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}const M=[a.OperationKeys.CREATE,a.OperationKeys.READ,a.OperationKeys.UPDATE,a.OperationKeys.DELETE];function D(e){return M.includes(e)}function I(e,t,r){const s=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};if(!s?.handler)return!1;const i=void 0===r&&D(t)?"crud":t,n=void 0===r&&D(t)?t:r,c=s.args?.[0]||[];return s.handler(c,i,n)??!1}function P(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof A)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class N{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 N._instance||(N._instance=new N),N._instance}}class B{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return B._instance||(B._instance=new B),B._instance}}class R{constructor(e,...t){this.adapter=e}async begin(...e){}async commit(...e){}async rollback(...e){}}class L extends n.Lock{constructor(e){super(),this.adapterTransaction=e,this.acquireCount=0,this.lock=new n.Lock}async acquire(...e){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...e)):this.lock.release()}async release(...e){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...e)}catch(t){await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+t),...e)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(e,...t){await this.lock.acquire();try{await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+e),...t)}catch(e){throw new a.InternalError("Failed to rollback transaction: "+e)}finally{this.lock.release()}}}const $=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{const t=e=>{if(!e)return;const t=U._cache?.[e];return t?.flavour||e};try{const r=$(e);if(r&&r!==o.DefaultFlavour)return t(r);const a="function"==typeof e?e:e?.constructor,s=a&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(a):void 0;if(s&&s!==o.DefaultFlavour)return t(s);const i=U._currentFlavour;if(i){const e=U._cache?.[i];return e?.flavour?e.flavour:t(i)}}catch(e){return o.DefaultFlavour}};const F=Symbol("AdapterProxyCleanup");function j(e,t,r,a){if(!t)return e;const s=e,i=[],n=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):n.push(e.reason);if(n.length){r.warn(`Bulk ${a} encountered ${n.length} failure(s) while continuing`);const e=new AggregateError(n,`Bulk ${a} failed for ${n.length} item(s)`);throw e.results=s,e}return i}class U extends E{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!U._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return U._baseRepository}transactionLock(...e){return new R(this,...e)}async shutdownProxies(e,...t){e&&"string"!=typeof e&&(t=[e,...t],e=void 0);const{log:r}=this.logCtx(t,this.shutdownProxies);if(!this.proxies)return;if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);const s=async e=>{if(!e)return;const t=e[F];"function"==typeof t&&await t()};if(e)try{await s(this.proxies[e]),delete this.proxies[e]}catch(t){r.error("Failed to cleanup proxied adapter "+e,t)}else for(const e in this.proxies){try{await s(this.proxies[e])}catch(t){r.error("Failed to cleanup proxied adapter "+e,t);continue}delete this.proxies[e]}}async shutdown(...t){const{log:r,ctxArgs:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(e.PersistenceKeys.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:r}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...s),this.dispatch&&await this.dispatch.close(...s)})()}catch(e){throw new a.InternalError("Failed to create shutdown wrapper: "+e)}finally{this.internalLock.release(e.PersistenceKeys.SHUTDOWN)}try{await this.shutdownPromise}catch(e){r.error("Error during proxy shutdown",e)}finally{this.shutdownPromise=void 0}}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.internalLock=new n.Lock,this.alias in U._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);U._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in U._cache||(U._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),U._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),U._currentFlavour=this.alias)}Dispatch(){return new U._baseDispatch}ObserverHandler(){return new k}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new U._baseSequence(e,this,t)}async flags(e,t,r,...n){if("string"==typeof t)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(t)?t.length?t[0]:void 0:t,l=c?""+i.Model.tableName(c):"";r.correlationId=r.correlationId||`${l}|${e}|${N.instance.generate()}`;const d=r.logger||s.Logging.for(this),u=Object.assign({},g.cacheForPopulate,r.cacheForPopulate);return Object.assign({},g,r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,cacheForPopulate:u,args:n,writeOperation:f.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:d})}get Context(){return v}async context(e,t,r,...a){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>i.Model.tableName(e)):i.Model.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let s=a.pop();void 0===s||s instanceof v||(a.push(s),s=void 0);const n=(()=>{if(!s)return!1;try{return!!s.get("allowGenerationOverride")}catch{return!1}})();t=s?Object.assign({},s.toOverrides(),t):t,n&&(t.allowGenerationOverride=!0);const o=await this.flags("string"==typeof e?e:e.name,r,t,...[...a,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}const t=s.getOrUndefined("operation"),a=s.getOrUndefined("affectedTables");if(!t||t!==e||r&&r!==a){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}return s.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),n=t.segregate(),o=Object.entries(n.model).reduce((e,[r,s])=>{if(void 0===s)return e;const n=i.Model.columnName(t.constructor,r);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return e[n]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(o,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:o,id:t[i.Model.pk(t.constructor)],transient:n.transient}}revert(t,r,s,n,...o){const{log:c,ctx:l}=this.logCtx(o,this.revert),d=i.Model.pk(r),u=new r;u[d]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return l.get("rebuildWithTransient")&&n&&(c.verbose("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,r,...s){const{log:n,ctx:o}=this.logCtx(s,this.createAll);if(!t||!r)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new a.ValidationError("Ids and models must have the same length");const c=i.Model.tableName(e);n.debug(`Creating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.create(e,t,r[a],...s,o.override({noEmitSingle:!0})));return j(l?await C(d,!0):await C(d),l,n,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...r){const{log:s,ctx:n}=this.logCtx(r,this.readAll),o=i.Model.tableName(e);s.debug(`Reading ${t.length} entries ${o} table`);const c=!(n.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...r,n.override({noEmitSingle:!0})));return j(c?await C(l,!0):await C(l),c,s,a.BulkCrudOperationKeys.READ_ALL)}async updateAll(e,t,r,...s){const{log:n,ctx:o}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const c=i.Model.tableName(e);n.debug(`Updating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.update(e,t,r[a],...s,o.override({noEmitSingle:!0})));return j(l?await C(d,!0):await C(d),l,n,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return j(n?await C(o,!0):await C(o),n,s,a.BulkCrudOperationKeys.DELETE_ALL)}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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(a&&o||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!U._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return U._currentFlavour}static get current(){return U.get(this.currentFlavour)}static unregister(e){if(!e)return;const t=U._cache[e];t&&(delete U._cache[e],U._currentFlavour===e&&(U._currentFlavour=void 0),t.flavour&&U._cache[t.flavour]&&U._cache[t.flavour]===t&&delete U._cache[t.flavour])}static get(e){if(!e)return U.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e).filter(i.Model.isModel)}catch(e){throw new a.InternalError(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} - ${i.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return Reflect.defineProperty(s,F,{value:async()=>{if(!a)return;const e=["cancel","close","destroy","disconnect"];for(const t of e){const e=a[t];if("function"==typeof e)try{const t=e.call(a);t instanceof Promise&&await t}catch{}}a=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,v]),r.__metadata("design:returntype",Promise)],U.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],U.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],U.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],U.prototype,"client",null);class q extends a.InternalError{constructor(e){super(e,q.name,500)}}class G extends a.InternalError{constructor(e){super(e,G.name,500)}}class z extends i.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):i.Model.fromModel(this,e)}and(e){return z.and(this,e)}or(e){return z.or(this,e)}not(t){return new z(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof z)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof z){if(!(this.comparison instanceof z)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return z.group(t,e.GroupOperator.AND,r)}static or(t,r){return z.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new z(e,t,r)}static attribute(e){return(new z.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new z(this.attr1,this.operator,this.comparison)}catch(e){throw new q(e)}}}}static builder(){return new z.Builder}static from(e){return new z(e)}}var Y,H;r.__decorate([i.required(),r.__metadata("design:type",Object)],z.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],z.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],z.prototype,"comparison",void 0),e.OrderDirection=void 0,(Y=e.OrderDirection||(e.OrderDirection={})).ASC="asc",Y.DSC="desc",e.Cascade=void 0,(H=e.Cascade||(e.Cascade={})).CASCADE="cascade",H.NONE="none";const V={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},Q={Equals:(e,t)=>z.attribute(e).eq(t),Diff:(e,t)=>z.attribute(e).dif(t),LessThan:(e,t)=>z.attribute(e).lt(t),LessThanEqual:(e,t)=>z.attribute(e).lte(t),GreaterThan:(e,t)=>z.attribute(e).gt(t),GreaterThanEqual:(e,t)=>z.attribute(e).gte(t),In:(e,t)=>z.attribute(e).in(t),Matches:(e,t)=>z.attribute(e).regexp(t)},W=e=>e.charAt(0).toLowerCase()+e.slice(1);class J extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(J.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const n=this.extractCore(e,s),o=this.extractSelect(e),c=this.extractGroupBy(e),l=this.buildWhere(n,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,n);return{action:a,select:o,selector:i,where:l,groupBy:c,orderBy:d,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?W(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(W).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(W).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),n=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&n.push(W(r))}return n.length>0?n:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach((t,a)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),c=o?Q[o]:Q.Equals;if(!c)throw Error("Unsupported operator "+o);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);n=0===a?d:i[a-1]===e.QueryClause.AND?n.and(d):n.or(d)}),n}static parseFieldAndOperator(e){for(const t of Object.keys(Q))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:W(r),operator:t}}return{field:W(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(t,r){const a=J.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new q("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new q(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,n=t.slice(i)??[];let o,c,l;if(n.at(-1)instanceof a.Context&&n.pop(),n.length>=1){const t=n[0],r=this.extractOrderByField(e);o=this.getProperlyOrderByOrThrow(r,t)}return 2>n.length||"number"!=typeof n[1]||(c=n[1]),3>n.length||"number"!=typeof n[2]||(l=n[2]),{orderBy:o,limit:c,offset:l}}}function X(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function Z(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(o.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),n=o.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return o.propMetadata(n,c)(a,s)}}function ee(e){return ne(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function te(e){return ne(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function re(e){return ne(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ae(e){return ne(e,f)}function se(e){return ne(e,Object.values(a.OperationKeys))}function ie(e){return ne(e,Object.values(a.BulkCrudOperationKeys))}function ne(e,t){return(r,s,n,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=b.prototype.logCtx(c,ne);return l.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${n}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:o.Metadata.constr(e)===o.Metadata.constr(r))&&t.includes(s)}}const oe={onlyOnCreate:ee,onlyOnUpdate:te,onlyOnDelete:re,onlyOnTransactional:ae,onlyOnSingle:se,onlyOnBulk:ie};function ce(e){const t=Object.assign({},oe);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var le,de,ue,pe,he,ge,fe,ye,me,we,_e;class ve extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=i.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ce(this)}constructor(e,t,r=!1,...s){super(t),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),t&&(ve.register(t,this,this.adapter.alias,r),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t);const i=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(i,i[t+"Prefix"],e,i[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(i,i[this.updateAll.name+"Prefix"],this.updateAll,i[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new k}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.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 a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.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 a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${i.Model.tableName(this.class)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...s),this.adapter.revert(n,this.class,o,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let c=n.map(e=>e.record);return c=await this.adapter.createAll(this.class,o,c,...s),c.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:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(n.silly(`handlerSetting: ${o}, validationSetting: ${c}`),!e.length)return[e,...s];const l=i.Model.sequenceFor(e[0]);let d=[];if(i.Model.generatedBySequence(this.class)?(l.name||(l.name=i.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=r.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.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 a.enforceDBDecorators(this,r,o,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${i.Model.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...s);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,a.BulkCrudOperationKeys.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,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${i.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,c,s)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");n.silly(`handlerSetting: ${o}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=i.Model.merge(d,e,this.class))),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.verbose(`Updating ${e.length} new ${this.class.name} in table ${i.Model.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),...s)).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:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),o=r.get("ignoreHandlers"),c=r.get("ignoreValidation");n.silly(`handlerSetting: ${o}, ignoredValidation: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(d[t],e,this.class)))),o||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let s;n.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s,d]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${i.Model.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...s);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,a.BulkCrudOperationKeys.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=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(...o)}async listBy(t,r,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${i.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...n)}async paginateBy(t,r,a={offset:1,limit:10},...s){a.offset=a.offset||1,a.limit=a.limit||10;const{offset:n,bookmark:o,limit:c}=a;if(!n&&!o)throw new q("PaginateBy needs a page or a bookmark");const{log:l,ctx:d,ctxArgs:u}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let p;if(l.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${c}`),o&&d.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>r===e.OrderDirection.ASC?this.attr(i.Model.pk(this.class)).gt(o):this.attr(i.Model.pk(this.class)).lt(o))()).orderBy([t,r]).paginate(c,...u);else{if(!n)throw new q("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(c,...u)}const h=await p.page(n,o,...u);return p.serialize(h)}async find(t,r=e.OrderDirection.ASC,...a){if("string"!=typeof t)throw new q("Find value must be a string");const s=this.getDefaultQueryAttributes(),{log:n,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.FIND,!0)).for(this.find);n.verbose(`finding ${i.Model.tableName(this.class)} by default attributes ${s.join(", ")}`);const c=this.buildDefaultStartsWithCondition(t,s);return this.select().where(c).orderBy([s[0],r]).execute(...o)}async page(t,r=e.OrderDirection.ASC,a={offset:1,limit:10},...s){if("string"!=typeof t)throw new q("Page value must be a string");const n=a.offset||1,{offset:o,bookmark:c,limit:l}=a;if(!o&&!c)throw new q("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${i.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const f=l??10,y=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let w;if(c&&h.get("paginateByBookmark")){const t=i.Model.pk(this.class),a=r===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);w=await m.select().where(u.and(a)).orderBy([y,r]).paginate(f,...g)}else{if(!o)throw new q("PaginateBy needs a page or a bookmark");w=await m.select().where(u).orderBy([y,r]).paginate(f,...g)}const _=await w.page(n,c,...g);return w.serialize(_)}async findOneBy(t,r,...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);n.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`);const c=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...o);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,r,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...n)}async findByPaginate(t,r,a={direction:e.OrderDirection.DSC,offset:1,limit:10},...s){a.direction=a.direction||e.OrderDirection.DSC,a.offset=a.offset||1,a.limit=a.limit||10;const{direction:n,offset:o,bookmark:c,limit:l}=a;if(!o&&!c)throw new q("FindByPaginate needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);d.verbose(`finding and paginating ${i.Model.tableName(this.class)} with ${t} ${r}`);const h=this.attr(t).eq(r);let g;if(c&&u.get("paginateByBookmark")){const r=i.Model.pk(this.class),a=n===e.OrderDirection.ASC?this.attr(r).gt(c):this.attr(r).lt(c);g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h.and(a)).orderBy([t,n]).paginate(l,...p)}else{if(!o)throw new q("FindByPaginate needs a page or a bookmark");g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h).orderBy([t,n]).paginate(l,...p)}const f=await g.page(o,c,...p);return g.serialize(f)}async countOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return a.verbose(`counting ${i.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${t} in ${i.Model.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${t} in ${i.Model.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating average of ${t} in ${i.Model.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${t} in ${i.Model.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${t} in ${i.Model.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${i.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...r){if(!ve.statements(this,t))throw new q("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const e=i.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new q("No default query attributes defined for "+i.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new q("Default query value must be a string");let r;for(const a of t){const t=this.attr(a).startsWith(e);r=r?r.or(t):t}if(!r)throw new q("No default query attributes available for "+i.Model.tableName(this.class));return r}attr(e){return z.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,t,r,...s)=>"string"==typeof e?e===a:o.Metadata.constr(e)===o.Metadata.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>U._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):U._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,r),...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const c=o.Metadata.registeredFlavour(t),l=c&&c!==o.DefaultFlavour?c:void 0,d=r||l||o.Metadata.flavourOf(t)||U.currentFlavour;try{n=this.get(t,d)}catch(e){n=void 0}const u="function"==typeof n?n:void 0,p=r||l||o.Metadata.flavourOf(t)||u&&o.Metadata.get(u,e.PersistenceKeys.ADAPTER)||U.currentFlavour,h=p?U.get(p):void 0;if(!h)throw new a.InternalError("No registered persistence adapter found flavour "+p);if(n instanceof ve)return n;const g=[i.Model.tableName(t),h.alias].join(a.DefaultSeparator),f=u||h.repository();return delete this._cache[g],new f(h,t,...s)}static get(e,t){const r=i.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r,s=!1){let n=i.Model.tableName(e);if(r&&(n=[n,r].join(a.DefaultSeparator)),n in this._cache&&this._cache[n]instanceof ve&&!s)throw new a.InternalError(n+" already has a registered instance");this._cache[n]=t}static statements(t,r){const a=t instanceof ve?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof ve?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function be(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof i.Model?t.constructor.name:t.name));return i.sf(e.PersistenceKeys.INJECTABLE,r,i.Model.tableName(t))}r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"listBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"paginateBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"find",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"page",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findOneBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findBy",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"findByPaginate",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"countOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(le="undefined"!=typeof K&&K)?le:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"maxOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(de="undefined"!=typeof K&&K)?de:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"minOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ue="undefined"!=typeof K&&K)?ue:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"avgOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(pe="undefined"!=typeof K&&K)?pe:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"sumOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(he="undefined"!=typeof K&&K)?he:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"distinctOf",null),r.__decorate([X(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ge="undefined"!=typeof K&&K)?ge:Object,void 0]),r.__metadata("design:returntype",Promise)],ve.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],ve.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],ve.prototype,"unObserve",null),U&&(U._baseRepository=ve);class Se extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let n;try{n=super.get(r)}catch{}if(!n){let c;if("function"==typeof r?c=i.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=i.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l)||o.Metadata.flavourOf(c);try{let e=d;try{d&&U.get(d)}catch{const t=U.current;t&&t.flavour===d&&(e=t.alias)}if(n=ve.forModel(c,e),n instanceof ve)return n;const r=d||o.Metadata.get(n.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(n,be(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ve.get(c,d);if("function"==typeof t){const e=d?U.get(d):U.current;if(!e)return;return new t(e,c)}}}return n}}e.TaskStatus=void 0,(fe=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",fe.SCHEDULED="scheduled",fe.RUNNING="running",fe.FAILED="failed",fe.SUCCEEDED="succeeded",fe.CANCELED="canceled",fe.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(ye=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",ye.FIXED="fixed",e.JitterStrategy=void 0,(me=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",me.FULL="full",e.TaskEventType=void 0,(we=e.TaskEventType||(e.TaskEventType={})).STATUS="status",we.UPDATE="update",we.LOG="log",we.PROGRESS="progress",we.ALL="all",e.TaskType=void 0,(_e=e.TaskType||(e.TaskType={})).ATOMIC="atomic",_e.COMPOSITE="composite";const Ee="tasks",ke={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};function Te(r,s){return(n,c)=>c?t.inject(o.Metadata.constr(r))(n,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||U.currentFlavour,i.Model.tableName(r)),n),o.metadata(a.DBKeys.REPOSITORY,n.name)(r),s=s||o.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),ve.register(r,n),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(n))}o.Metadata.tasks=(()=>o.Metadata.innerGet(Symbol.for(Ee))).bind(o.Metadata),o.Metadata.taskFor=(e=>{const t=o.Metadata.tasks();return t?t[e]:void 0}).bind(o.Metadata),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],n=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=i.Model.nestedRelations(t)),[...new Set([...n,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??U.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.migrations=(()=>{const t=o.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(t).flat().map(e=>[e.class.name,e.class])}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),i.Model.relations=(e,t)=>o.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&i.Model.relations(t.class)){const s=i.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=i.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]}).bind(i.Model),i.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!i.Model.sequenceFor(r).generated}).bind(i.Model),i.Model.fromTable=(t=>{const r=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!r||!r[t]||!i.Model.get(r[t].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return i.Model.get(r[t].name)}).bind(i.Model),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),i.Model.tableName=t=>{if(!(t instanceof i.Model?i.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof i.Model?t.constructor.name:t.name)},i.Model.columnName=(t,r)=>o.Metadata.get(t instanceof i.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.defaultQueryAttributes=(t,r=!1)=>{const a="function"==typeof t?t:t.constructor;return o.Metadata.get(a,o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||(r?[i.Model.pk(t)]:[])},i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.versionOf=(t=>{const r=o.Metadata.get(t.constructor),s=r?.[e.PersistenceKeys.PERSISTENT_VERSION],i=s&&"object"==typeof s?Object.keys(s)[0]:void 0,n=r?.[a.DBKeys.VERSION],c=n&&"object"==typeof n?Object.keys(n)[0]:void 0,l=i??c;if(!l)throw new a.InternalError("No version found for "+t.constructor.name);const d=t[l];if("number"!=typeof d||1>d)throw new a.InternalError("Invalid version number: "+d);return d}).bind(i.Model),i.Model.sequenceFor=(t,r)=>{const s="function"!=typeof t?t.constructor:t;let n=e.PersistenceKeys.SEQUENCE;const c=i.Model.pk(s);r&&r+""!=c+""||(r=c,n=a.DBKeys.ID),n=o.Metadata.key(n,r);const l=o.Metadata.get(s,n);if(!l)throw new a.InternalError(`No sequence options defined for property ${r+""}. did you use @sequence() or @pk()?`);return l},i.Model.indexes=t=>{const r=o.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})},t.Injectables.services=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY)),i.Model.merge=((e,t,r)=>{const a=e=>Object.entries(e).reduce((e,[t,a])=>{let s=!1;try{"relation.one-to-one"===i.Model.relations(r,t).key&&(s=!0)}catch(e){s=!1}return(void 0!==a||s)&&(e[t]=a),e},{});return new(r=r||e.constructor)(Object.assign({},a(e),a(t)))}).bind(i.Model);class Oe extends a.InternalError{constructor(e){super(e,Oe.name,500)}}var Ae;e.AuthKeys=void 0,(Ae=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Ae.ROLES="roles",Ae.NAMESPACE="namespace";const xe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ce=xe,Me={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},De=Object.assign({},Me,{type:"BigInt"});function Ie(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,i)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,i),{directions:t,compositions:r,name:a})(s,i)),args:[t,r,a]}).apply()}function Pe(e){return"function"==typeof e}function Ne(e,t,r){if(!r.type){const a=o.Metadata.type(e.constructor,t);if(![Number.name,String.name,BigInt.name].includes(a?.name||a))throw Error("Incorrrect option type");r.type=a}switch(r.type){case String.name||String.name.toLowerCase():case String:r.generated=void 0!==r.generated&&r.generated,r.type=String;break;case Number.name||String.name.toLowerCase():case Number:r.generated=void 0===r.generated||r.generated,r.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:r.type=BigInt,r.generated=void 0===r.generated||r.generated;break;case"uuid":case"serial":r.generated=!0;break;default:throw Error("Unsupported type")}void 0===r.generated&&(r.generated=!0)}async function Be(e,t,r,s){if(!t.type||!t.generated||s[r])return;let n;t.name||(t.name=i.Model.sequenceName(s,"pk"));try{n=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var o,c,l;o=s,c=r,l=await n.next(e),Reflect.set(o,c,l)}async function Re(e,t,r,s,n){if(!t.type||!t.generated)return;if(!t.name){const e=i.Model.pk(s,!0);if(null==e)throw new a.InternalError("Cannot generate sequence without an id for "+s.constructor.name);t.name=i.Model.sequenceName(s,e+"",r+"")}let o;try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const c=null!=n,l=void 0!==s[r]&&null!==s[r],d=!!e.get("allowGenerationOverride")&&l;if(l&&await o.ensureAtLeast(s[r],e),c&&!t.update)return;if(d)return;const u=await o.next(e);Reflect.set(s,r,u)}function Le(t,r){return(s,n)=>{var c,l;o.prop()(s,n),Ne(s,n,t),t.name||(t.name=(c=s.constructor,l="pk",Pe(i.Model.sequenceName)?i.Model.sequenceName(c,l):[Pe(i.Model.tableName)?i.Model.tableName(c):c?.name??"",l].filter(Boolean).join("_")));const d=[o.propMetadata(o.Metadata.key(a.DBKeys.ID,n),t),o.propMetadata(o.Metadata.key(e.PersistenceKeys.SEQUENCE,n),t),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),a.onCreate(Be,t,r)];return t.generated&&d.push(a.generated()),o.apply(...d)(s,n)}}function $e(t,r={},s){return(n,c)=>{o.prop()(n,c),Ne(n,c,t);const l=[i.required(),o.propMetadata(o.Metadata.key(e.PersistenceKeys.SEQUENCE,c),t),a.onCreate(Re,{...t,...r},s)];return r.update&&l.push(a.onUpdate(Re,{...t,...r},s)),t.generated&&l.push(a.generated()),o.apply(...l)(n,c)}}function Fe(e){const t=Object.assign({},Ce);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:Le,args:[e,{priority:60}]}).apply()}async function Ke(e,t,r,s,n){const o=t.logger.for(Ke);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=ve.forModel(t,r),o.info("Retrieved "+s.toString())}let c;if(s=n?s.override(n):s,void 0===e[i.Model.pk(s.class)])o.info(`No pk found in ${i.Model.tableName(s.class)} - creating`),c=await s.create(e,t);else{o.info(`pk found in ${i.Model.tableName(s.class)} - attempting update`);try{c=await s.update(e,t),o.info("Updated "+i.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;o.info("update Failed - creating new "+i.Model.tableName(s.class)),c=await s.create(e,t)}o.info("After create update: "+c)}return c}async function je(e,t,r,s){const n=s[r];if(!n)return;if(Ve(s,t),"object"!=typeof n){const t=it(s,r,this.adapter.alias),a=await t.override(this._overrides).read(n,e);return await tt(e,s,r,n,a),void(s[r]=n)}const o="function"!=typeof t.class||t.class.name?t.class:t.class();if(!o)throw new a.InternalError("Could not find model "+t.class);const c=ve.forModel(o,this.adapter.alias),l=await c.override(this._overrides).create(n,e),d=i.Model.pk(l);await tt(e,s,r,l[d],l),s[r]=l[d]}async function Ue(t,r,a,s){const n=s[a];if(!n)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof n){const e=it(s,a,this.adapter.alias),r=await e.override(this._overrides).read(n,t);return await tt(t,s,a,n,r),void(s[a]=n)}const o=await Ke(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(o);await tt(t,s,a,o[c],o),s[a]=o[c]}async function qe(t,r,a,s){const n=s[a];if(null==n)return;if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=it(s,a,this.adapter.alias);let c;c=n instanceof i.Model?await o.delete(s[a][o.pk],t):await o.delete(s[a],t),await tt(t,s,a,c[o.pk],c)}async function Ge(e,t,r,a,s){const n=a[r];if(!n||!n.length)return;Ve(a,t);const o=e.logger.for(Ge),c=it(a,r,this.adapter.alias),l=i.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of n){let s;"object"!=typeof t?(s=await c.override(this._overrides).read(t,e),o.debug("read: "+s[l])):(o.verbose("Creating or updating one-to-many model: "+t[l]),s=await Ke(t,e,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(s)} under ${s[l]}`),await tt(e,a,r,s[l],s),d.add(s[l])}a[r]=[...d]}async function ze(t,r,a,s,i){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return Ge.call(this,t,r,a,s,i)}async function Ye(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ve.forModel(c,this.adapter.alias):it(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await tt(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}async function He(e,t,r,s){const n=s[r];if(!n)return;Ve(s,t);const o=e.logger.for(He);if("object"!=typeof n){const t=it(s,r,this.adapter.alias),a=await t.override(this._overrides).read(n,e);return await tt(e,s,r,n,a),void(s[r]=n)}if(!(t.class instanceof i.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);o.info("Creating or updating many-to-one model: "+JSON.stringify(n));const c=await Ke(n,e,this.adapter.alias,void 0,this._overrides),l=i.Model.pk(c);o.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await tt(e,s,r,c[l],c),s[r]=c[l]}function Ve(t,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=o.Metadata.get(i,e.PersistenceKeys.RELATIONS);if(n&&(s=Object.values(n)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===s?.populate&&!0===r?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Qe(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return He.call(this,t,r,a,s)}async function We(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const n="object"==typeof i,o=n?ve.forModel(i,this.adapter.alias):it(s,a,this.adapter.alias),c=n?i[o.pk]:i,l=await o.override(this._overrides).delete(c);await tt(t,s,a,c,l),s[a]=c}async function Je(e,t,r,s){const n=s[r];if(!n||!n.length)return;Ve(s,t);const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=e.logger.for(Je),l=new Set([...n]);if("object"!==o){const a=it(s,r,this.adapter.alias),i=await a.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<i.length;t++){const a=i[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(a)),await tt(e,a,r,[...l.values()][t],i)}return await Xe.call(this,s,[...n],c,e,t),s[r]=[...l],void c.info("SET MANY TO MANY IDS: "+s[r])}const d=i.Model.pk(n[0].constructor),u=new Set;for(const t of n){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const a=await Ke(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await tt(e,s,r,a[d],a),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=a.id,u.add(a[d])}const p=i.Model.pk(s.constructor);if(void 0===s[p]){const t=await(async(e,t,r)=>{const s=t[i.Model.pk(t.constructor)];if(void 0!==s)return s;const n=i.Model.sequenceFor(t.constructor);let o;n?.name||(n.name=i.Model.sequenceName(t,"pk"));try{return o=await e.adapter.Sequence(n,e._overrides),await o.next(r)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${n.name}: ${e}`)}})(this,s,e);s[p]=t}const h=await Xe.call(this,s,n,c,e,t);c.info("Junction model created: "+h.name),s[r]=[...u]}async function Xe(e,t,r,a,s){const{JunctionModel:n,fkA:o,fkB:c}=Ze(e,t[0],s),l=[];for(const s of t){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(s));const t={[o]:e instanceof i.Model?e[i.Model.pk(e.constructor)]:e,[c]:s instanceof i.Model?s[i.Model.pk(s.constructor)]:s},d=await Ke(new n(t),a,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=ve.forModel(n);await(e?.override(this._overrides).readAll(l))}return n}function Ze(t,r,s){const n=i.Model.tableName(t);let c;if(r instanceof i.Model)c=i.Model.tableName(r);else if(i.Model.isModel(r)&&"function"==typeof r)c=r.name?r.name:r()?.name;else if(s?.class){const e="function"!=typeof s.class||s.class.name?s.class:s.class();c=i.Model.tableName(e)}if(!n||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=s?.joinTable?.name?s?.joinTable?.name:`${n}_${c}`,d=n?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends i.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),Fe({type:Number})(p.prototype,"id"),i.required()(p.prototype,d),i.required()(p.prototype,u);const h=i.model()(p);return o.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function et(t,r,a){return r?[e.PersistenceKeys.POPULATE,t,r,a].join("."):[e.PersistenceKeys.POPULATE,t,a].join(".")}async function tt(e,t,r,a,s){const i=et(t.constructor.name,r,a),n=e.logger.for(tt),o=e.get("cacheForPopulate")||{};let c=o[i],l=e.getOrUndefined("preferFromCache");if(!l)try{n.silly("retrieving from children"),l=e.getFromChildren("preferFromCache")||!1,l&&(c=(e.getFromChildren("cacheForPopulate")||{})[i])}catch(e){l=!1}return l&&n.debug("preferring previous cache: "+!!o[i]),o[i]=l&&c?c:s,e.accumulate({cacheForPopulate:o})}async function rt(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=this,c=await(async(t,r,s,i)=>{let n,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){n=et(r.constructor.name,s,t);try{if(c=u[n],!c)throw Error("Not found in cache")}catch(i){const n=it(r,s,o.adapter.alias);if(!n)throw new a.InternalError("Could not find repo");c=await n.override(o._overrides).read(t,e)}l.push(c)}return l})(e,s,r,n?i:[i]);s[r]=n?c:c[0]}async function at(t,r,s,n,o){if(r.cascade.update!==e.Cascade.CASCADE)return;if(!o)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function c(e){return Array.isArray(e)?e.map(c):"object"!=typeof e?e:e[i.Model.pk(e)]}const l=c(n[s]),d=c(o[s]);if(void 0===d||i.isEqual(l,d))return;if(Array.isArray(l)!==Array.isArray(d))throw new a.InternalError("Cannot cascade update for different array types");const u=(Array.isArray(l)?l:[l]).filter(Boolean),p=(Array.isArray(d)?d:[d]).filter(Boolean).filter(e=>!u.includes(e)),h=it(n,s,this.adapter.alias);if(!h)throw new a.InternalError("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${i.Model.tableName(h.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}const st=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function it(e,t,r){if(!e)throw Error("No model was provided to get repository");let s,n=e instanceof i.Model?e.constructor:e;if(Array.isArray(e[t])||e[t]instanceof Set){const e=o.Metadata.get(n,o.Metadata.key(i.ValidationKeys.REFLECT,t,i.ValidationKeys.LIST))?.clazz;if(!e)throw new a.InternalError("Failed to find types decorators for property "+t);s=(Array.isArray(e)?[...e]:[e]).map(e=>"function"!=typeof e||e.name?e:e())}else s=i.Model.relations(n).includes(t)?o.Metadata.allowedTypes(n,t):o.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;n=s?.find(e=>!st.includes((""+e.name).toLowerCase()));const c=ve.forModel(n,r);if(n!==c.class)throw new a.InternalError("Invalid repository class for "+t);return c}class nt extends a.BadRequestError{constructor(e,t=nt.name,r=401){super(e,t,r)}}class ot extends nt{constructor(e,t=ot.name){super(e,t,403)}}class ct extends a.InternalError{constructor(e){super(e,ct.name,503)}}function lt(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(o.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function dt(t){return o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}async function ut(e,t,r,s){if(s[r]&&(await this.select().where(z.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function pt(e,t,r,a){throw new nt("This adapter does not support user identification")}function ht(){return o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(pt),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function gt(){return o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(pt),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ft(){return a.timestamp([a.OperationKeys.CREATE])}function yt(){return a.timestamp()}async function mt(e,t,r,s){if("??sequence"===i.Model.tableName(s))return;const n=i.Model.pk(s,!0);if(null==n)throw new a.InternalError("Cannot generate persistent version without an id for "+s.constructor.name);const o={name:i.Model.sequenceName(s,n+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},c=await this.adapter.Sequence(o,this._overrides),l=void 0!==s[r]&&null!==s[r],d=!!e.get("allowGenerationOverride")&&l;if(l&&(await c.ensureAtLeast(s[r],e),d))return;const u=await c.next(e);s[r]=u}async function wt(e,t,r,s,n){if("??sequence"===i.Model.tableName(s))return;if(e.get("applyUpdateValidation")&&n&&s[r]!==n[r])throw new a.ValidationError(`Version mismatch: ${s[r]} !== ${n[r]}`);const o=i.Model.pk(s,!0);if(null==o)throw new a.InternalError("Cannot generate persistent version without an id for "+s.constructor.name);const c={name:i.Model.sequenceName(s,o+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},l=await this.adapter.Sequence(c,this._overrides),d=void 0!==s[r]&&null!==s[r],u=!!e.get("allowGenerationOverride")&&d;if(d&&(await l.ensureAtLeast(s[r],e),u))return;const p=await l.next(e);s[r]=p}function _t(){const t=e.PersistenceKeys.PERSISTENT_VERSION;return(e,r)=>o.Decoration.for(t).define(o.prop(),o.propMetadata(o.Metadata.key(t,r),!0),a.generated(t),i.type(Number),a.onCreate(mt,{},{priority:70}),a.onUpdate(wt,{},{priority:70})).apply()(e,r)}function vt(e){return[()=>{const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return(o.Metadata.allowedTypes(t,r)||[])[0]}]}function bt(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function St(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class Et extends i.Model{constructor(e){super(e)}}r.__decorate([ft(),r.__metadata("design:type",Date)],Et.prototype,"createdAt",void 0),r.__decorate([yt(),r.__metadata("design:type",Date)],Et.prototype,"updatedAt",void 0),e.SequenceModel=class extends Et{constructor(e){super(e)}},r.__decorate([Fe({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),Ie(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([lt("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class kt extends s.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,P(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.FIND_BY_PAGINATE}|${e.PreparedStatementKeys.LIST_BY}|${e.PreparedStatementKeys.PAGE_BY}|${e.PreparedStatementKeys.FIND}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof v?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof v||(this._bookmark=r);const n=ve.forModel(this.clazz,this.adapter.alias),o=this.query,{method:c,args:l,params:d}=o;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await n.statement(...r,...i);return this.apply(s)}let u;if(c===e.PreparedStatementKeys.FIND_BY?u=e.PreparedStatementKeys.FIND_BY_PAGINATE:c.startsWith(e.PreparedStatementKeys.FIND_BY)?u=c.replace(e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.PAGE_BY):c===e.PreparedStatementKeys.LIST_BY?u=e.PreparedStatementKeys.PAGE_BY:c!==e.PreparedStatementKeys.PAGE_BY&&c!==e.PreparedStatementKeys.FIND_BY_PAGINATE||(u=c),!u)throw new T(`Method ${c} is not supported for pagination`);const p=[u,...l];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==e.PreparedStatementKeys.PAGE_BY||p.length>2?h={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:p.push(d.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 G("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new G(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new T("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 a.SerializationError(e)}}apply(e){const t="string"==typeof e?kt.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(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 Tt,Ot,At,xt,Ct,Mt,Dt;class It extends b{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=a.get("forcePrepareSimpleQueries"),o=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||c)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(It)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new q("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?i.Model.get(e):e,!this.fromSelector)throw new q("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new q("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new q("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new q("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new q(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new q("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const i=await this.raw(s,...a);if(this.hasAggregation())return i;if(!this.selectSelector){const e=e=>this.processRecord(e,r);if(this.groupBySelectors?.length){const t=this.revertGroupedResults(i,e);return await this.applyAfterHandlersToResult(t,r)}if(Array.isArray(i)){const t=i.map(e);return await this.applyAfterHandlersToResult(t,r)}const t=e(i);return await this.applyAfterHandlersToResult(t,r)}return i}catch(e){throw new q(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ve.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new T("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const i=e=>this.processRecord(e,r);if(Array.isArray(s)){const e=s.map(i);return await this.applyAfterHandlersToResult(e,r)}const n=i(s);return await this.applyAfterHandlersToResult(n,r)}processRecord(e,t){const r=e[i.Model.pk(this.fromSelector)];return this.adapter.revert(e,this.fromSelector,r,void 0,t)}async applyAfterHandlersToResult(e,t){return t.getOrUndefined("afterQueryHandlers")?e instanceof i.Model?(await a.enforceDBDecorators(this.getRepository(),t,e,a.OperationKeys.READ,a.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterHandlersToResult(e,t))),e):e&&"object"==typeof e?(await Promise.all(Object.entries(e).map(([r,a])=>this.applyAfterHandlersToResult(a,t).then(t=>{e[r]=t}))),e):e:e}getRepository(){return ve.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const n={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,n.args=[...n.args||[],...t.args||[]]}if(i instanceof z){const e=this.prepareCondition(i,r);t=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:n.method=a,n.args=[...n.args||[],i];break;case e.Operator.DIFFERENT:n.method=a+" diff",n.args=[...n.args||[],i];break;case e.Operator.REGEXP:n.method=a+" matches",n.args=[...n.args||[],i];break;case e.Operator.BIGGER:n.method=a+" bigger",n.args=[...n.args||[],i];break;case e.Operator.BIGGER_EQ:n.method=a+" bigger than equal";break;case e.Operator.SMALLER:n.method=a+" less",n.args=[...n.args||[],i];break;case e.Operator.SMALLER_EQ:n.method=a+" less than equal",n.args=[...n.args||[],i];break;case e.Operator.IN:n.method=a+" in",n.args=[...n.args||[],i];break;default:throw new q("Unsupported operator "+s)}return n}squash(t){const r=this.matchDefaultQueryCondition();if(r){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[r.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof z)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let a;this.whereCondition&&(a=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:a?[a,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[n,o]=s,c={direction:o};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[n],params:c};return a&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[a,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=i.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const r=Array.from(new Set(t.map(String))),a=Array.from(new Set(e.attributes.map(String)));return r.length===a.length&&r.every(e=>a.includes(e))?{value:e.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof z?this.collectStartsWithAttributes(r):void 0,t=s instanceof z?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof z?this.collectStartsWithAttributes(r):void 0)||(s instanceof z?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},i={class:this.fromSelector,args:r,params:a};let n,o=e.QueryClause.FIND_BY;void 0!==this.countSelector?(o=e.QueryClause.COUNT_BY,n=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(o=e.QueryClause.SUM_BY,n=this.sumSelector):this.avgSelector?(o=e.QueryClause.AVG_BY,n=this.avgSelector):this.minSelector?(o=e.QueryClause.MIN_BY,n=this.minSelector):this.maxSelector?(o=e.QueryClause.MAX_BY,n=this.maxSelector):this.distinctSelector?(o=e.QueryClause.DISTINCT_BY,n=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(o=e.QueryClause.GROUP_BY_PREFIX,n=this.groupBySelectors[0]);const c=[o];if(n&&c.push(n),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&o!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&o===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),i.method=s.toCamelCase(c.join(" ")),i.params=a,this.prepared=i,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelectors&&this.groupBySelectors.length||void 0!==this.countSelector||this.countDistinctSelector||this.maxSelector||this.minSelector||this.sumSelector||this.avgSelector||this.distinctSelector)}hasAggregation(){return void 0!==this.countSelector||void 0!==this.countDistinctSelector||void 0!==this.maxSelector||void 0!==this.minSelector||void 0!==this.sumSelector||void 0!==this.avgSelector||void 0!==this.distinctSelector||(this.groupBySelectors?.length||0)>0}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new q(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],It.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Tt="undefined"!=typeof S&&S)?Tt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ot="undefined"!=typeof S&&S)?Ot:Object]),r.__metadata("design:returntype",Object)],It.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(At="undefined"!=typeof S&&S)?At:Object]),r.__metadata("design:returntype",Object)],It.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(xt="undefined"!=typeof S&&S)?xt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ct="undefined"!=typeof S&&S)?Ct:Object]),r.__metadata("design:returntype",Object)],It.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Mt="undefined"!=typeof S&&S)?Mt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],It.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[z]),r.__metadata("design:returntype",Object)],It.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],It.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],It.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Dt="undefined"!=typeof Key&&Key)?Dt:Object]),r.__metadata("design:returntype",Object)],It.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],It.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],It.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],It.prototype,"execute",null);class Pt extends b{constructor(e){super(),this.name=e,this.observers=[],this.Context=v}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Pt?i.for(e,...t):i instanceof ve?i.override(e):i}})}override(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Pt?i.override(e,...t):i instanceof ve?i.override(e):i}})}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new k,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 a.InternalError("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 a.InternalError("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}-${N.instance.generate()}`;const a=t.logger||s.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},h,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof v||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return b.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const r=x(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...r){let s=r.pop();void 0===s||s instanceof v||(r.push(s),s=void 0);const i=await Pt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new v(s).accumulate({...i,parentContext:s}):(new v).accumulate(i),r=[...r,s];const{log:n,ctxArgs:o}=Pt.prototype.logCtx(r,this.boot),c=t.Injectables.services();for(const[e,r]of Object.entries(c))try{n.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof Nt&&(n.verbose(`Initializing ${r.name} service...`),await s.boot(...o))}catch(e){throw new a.InternalError(`Failed to boot ${r.name} service:${e}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof v||(r.push(s),s=void 0);const i=await Pt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new v(s).accumulate({...i,parentContext:s}):(new v).accumulate(i),r=[...r,s];const{log:n,ctxArgs:o}=Pt.prototype.logCtx(r,this.shutdown),c=t.Injectables.services();for(const[e,r]of Object.entries(c).reverse())try{n.verbose(`Shutting down ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);if(s instanceof Nt){n.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...o)}catch(e){n.error(`Failed to gracefully shutdown ${r.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],Pt.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],Pt.prototype,"unObserve",null);class Nt extends Pt{constructor(){super()}async boot(...t){const{config:r,client:a}=await this.initialize(...t);this._config=r,this._client=a;const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info("Shutting down...")}}function Bt(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&I(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Nt.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Nt.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Nt.prototype,"client",null);const Rt=()=>Bt(a.OperationKeys.CREATE),Lt=()=>Bt(a.OperationKeys.READ),$t=()=>Bt(a.OperationKeys.UPDATE),Ft=()=>Bt(a.OperationKeys.DELETE);function Kt(r){return(a,s,i)=>{i||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=x(r);const n=[];if(i&&"number"==typeof i.value)n.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...n)(a,s,i)}}const jt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ut extends Pt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ve.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=jt(e);try{const e=Pt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}select(e){return this.repo.select(e)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let a;t=jt(t||e);try{a=Ut.get(t)}catch(e){a=void 0}if(a instanceof Ut)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Kt(t),r.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo._adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"create",null),r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"createAll",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"delete",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"deleteAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"read",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"readAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Ut.prototype,"query",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Ut.prototype,"update",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Ut.prototype,"updateAll",null);class qt extends b{isSameObservedAdapter(e){if(!this.adapter)return!1;if(this.adapter===e)return!0;const t=this.adapter,r=e;return r instanceof U&&t.alias===r.alias&&t.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:n,ctx:o}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,l,d]=a,u=await t.call(r,c,l,d,...n),p=[c,i(e),l];return o.get("observeFullResult")&&p.push(Array.isArray(u)?u.map(e=>c(e)):c(u)),this.updateObservers(...p,...n).catch(t=>s.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(...e){}observe(e){if(!(e instanceof U))throw new T("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(e))return()=>this.unObserve(e);throw new T("Dispatch is already observing another adapter")}return this.adapter=e,this.models=U.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(!this.isSameObservedAdapter(e))throw new T("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 a.InternalError("Model must be provided for observer update");const n=e&&"string"==typeof e?e:i.Model.tableName(e);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${n}:${t}`);const{log:o,ctxArgs:c,ctx:l}=this.logCtx(s,this.updateObservers);try{o.debug(`dispatching observer refresh for ${t}:${n}: ${r}${l.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Gt(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await N.instance.generate(s)}function zt(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const n=e.PersistenceKeys.UUID;return o.Decoration.for(n).define({decorator:(t,r,...s)=>{const n={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Gt,n,{priority:54})];return t&&c.push(a.onUpdate(Gt,n,{priority:54})),t||c.push(a.readonly()),o.apply(...c)},args:[t,r,...s]}).apply()}U&&(U._baseDispatch=qt);class Yt extends b{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ve.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.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 a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:n,incrementBy:o,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return Yt.lock.execute(async()=>{const r=t||o;if(r%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof n&&n?.name?n.name:n,d=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(N.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(B.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.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.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new T(`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 a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}async ensureAtLeast(t,...r){const{ctx:s}=(await this.logCtx(r,a.OperationKeys.UPDATE,!0)).for(this.ensureAtLeast),{name:i}=this.options;if(!i)throw new a.InternalError("Sequence name is required");const n=this.parse(t),o=(e,t)=>"bigint"==typeof e||"bigint"==typeof t?BigInt(e)>BigInt(t):"number"==typeof e||"number"==typeof t?Number(e)>Number(t):e+"">t+"";return Yt.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(i,s)}catch(e){if(e instanceof a.NotFoundError)return;throw e}};for(;;)try{const r=await t();if(!r)return await this.repo.create(new e.SequenceModel({id:i,current:n}),s),n;const a=this.parse(r.current);return o(n,a)?(await this.repo.update(new e.SequenceModel({id:i,current:n}),s),n):a}catch(e){if(e instanceof a.ConflictError)continue;throw e}},i)}parse(e){return Yt.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return i.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new T(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Ht(e,...t){let r;if(e instanceof Ut&&(r=e.repo.adapter),e instanceof ve&&(r=e.adapter),e instanceof U&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function Vt(e,...t){return new L(Ht(e,...t))}U._baseSequence=Yt,o.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:(...e)=>(t,r,s)=>{if(!s)throw new a.InternalError("This decorator only applies to methods");return o.method()(t,r,s),o.Metadata.set(t.constructor,o.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,r),{data:e}),s.value=new Proxy(s.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),n=i.getOrUndefined("transactionLock")||Vt(t);let o;i.put("transactionLock",n),await n.acquire();try{o=await e.call(t,...r,i)}catch(e){try{await n.rollback(e)}catch(e){s.error("Failed to rollback transaction",e)}throw e}try{await n.release()}catch(e){throw new a.InternalError("Failed to release transaction: "+e)}return o}}),s}}).apply(),e.TaskBackoffModel=class extends i.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},r.__decorate([i.required(),i.type(String),i.option(e.BackoffStrategy),o.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),o.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),o.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),o.description("optional jitter strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([o.prop(),o.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([o.prop(),o.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([o.prop(),o.description("The error details"),r.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends i.Model{constructor(e){if(super(e),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}},r.__decorate([Fe(),a.composed(["taskId","classification","uuid"],":"),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([dt(),a.readonly(),i.required(),a.transient(),zt(!1),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),r.__decorate([dt(),a.readonly(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),r.__decorate([i.date(),dt(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),r.__decorate([dt(),a.readonly(),i.required(),i.option(e.TaskEventType),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),r.__decorate([o.prop(),dt(),a.serialize(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([lt("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Qt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof z){const r=this.serializePlain(e,...t);return r[i.ModelKeys.ANCHOR]="??condition",r}return i.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const r=this.serializePlain(e,...t),a=this.getMetadata(e.constructor)??e.constructor?.name;return a&&(r[i.ModelKeys.ANCHOR]=a),r}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return o.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[i.ModelKeys.ANCHOR],r=this.rebuildObject(e);return t?"??condition"===t?z.from(r):i.Model.build(r,t):r}rebuildObject(e){const t={};for(const[r,a]of Object.entries(e))r!==i.ModelKeys.ANCHOR&&(t[r]=this.rebuildValue(a));return t}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),r.__decorate([i.required(),i.option(s.LogLevel),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),r.__decorate([i.min(0),r.__metadata("design:type",Number)],e.TaskLogEntryModel.prototype,"step",void 0),r.__decorate([i.required(),o.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends i.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},r.__decorate([Fe(),zt(),o.description("the task id"),r.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),r.__decorate([dt(),i.required(),i.type(String),i.option(e.TaskType),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([dt(),i.required(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([dt(),o.prop(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),r.__decorate([dt(),o.prop(),o.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),r.__metadata("design:type",String)],e.TaskModel.prototype,"lock",void 0),r.__decorate([dt(),i.required(),i.type(String),i.option(e.TaskStatus),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["nextRunAt"]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["leaseExpiry"]),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC],["scheduledTo"]),o.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([o.prop(),dt(),a.serialize(Qt),o.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([o.prop(),dt(),a.serialize(Qt),o.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the error for failed tasks"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),r.__decorate([dt(),i.required(),i.min(0),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([dt(),i.min(1),i.required(),o.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([dt(),i.required(),a.serialize(),o.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),dt(),o.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),dt(),o.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([dt(),a.serialize(),o.description("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"dependencies",void 0),r.__decorate([o.prop(),dt(),o.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),dt(),o.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the various steps definition and inputs - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),r.__decorate([o.prop(),dt(),i.min(0),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([o.prop(),dt(),a.serialize(),o.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([dt(),ft(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([dt(),yt(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([dt(),ht(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([dt(),gt(),Ie([e.OrderDirection.ASC,e.OrderDirection.DSC]),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([o.description("Holds the current step when applicable"),lt("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([o.prop(),o.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([o.prop(),o.description("the error of a failed step"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),e.TaskStepResultModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([i.minlength(1),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"name",void 0),r.__decorate([o.description("optional task step input"),o.prop(),r.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),r.__decorate([o.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),o.prop(),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"lock",void 0),r.__decorate([o.description("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),o.prop(),i.list(()=>String),r.__metadata("design:type",Array)],e.TaskStepSpecModel.prototype,"dependsOn",void 0),e.TaskStepSpecModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class Wt extends i.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,i.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}r.__decorate([i.required(),i.min(1e3),r.__metadata("design:type",Number)],Wt.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],Wt.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],Wt.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],Wt.prototype,"strategy",void 0);class Jt extends i.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Wt,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setLock(e){return this.lock=e,this}setDependencies(e){return this.dependencies=e,this}setDependsOn(e){return this.setDependencies(e)}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,i.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"classification",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],Jt.prototype,"name",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Jt.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],Jt.prototype,"backoff",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],Jt.prototype,"input",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],Jt.prototype,"lock",void 0),r.__decorate([o.prop(),i.list(()=>String),r.__metadata("design:type",Array)],Jt.prototype,"dependencies",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],Jt.prototype,"maxAttempts",void 0);class Xt{constructor(e,t){this.parent=e,this.step=t}setClassification(e){return this.step.classification=e,this}setName(e){return this.step.name=e,this}setInput(e){return this.step.input=e,this}setLock(e){return this.step.lock=e,this}setDependsOn(e){return this.step.dependsOn=e,this}addStep(e,t,r){return this.parent.addStep(e,t,r)}setSteps(e){return this.parent.setSteps(e)}build(){return this.parent}}class Zt extends Jt{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),this}addStep(t,r,a){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,o=n&&"string"==typeof r?r:void 0,c=n?a:i?void 0:r,l=new e.TaskStepSpecModel({classification:t,name:o,input:c,createdAt:s,updatedAt:s});return this.steps.push(l),i?new Xt(this,l):this}}r.__decorate([i.list(()=>e.TaskStepSpecModel),r.__metadata("design:type",Array)],Zt.prototype,"steps",void 0);class er extends E{get type(){if(!this._type){const e=o.Metadata.get(this.constructor,Ee);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}async catch(e,t,r){}}function tr(e){return o.Decoration.for(Ee).define({decorator:e=>t=>{const r={type:e};return o.Metadata.set(Ee,e,t),o.metadata(Ee,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends er{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof z)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=z.attr("status").eq(e.TaskStatus.SUCCEEDED).and(z.attr("updatedAt").lte(t.successfulExpiry)),i=z.attr("status").eq(e.TaskStatus.FAILED).and(z.attr("updatedAt").lte(t.failedExpiry)),n=z.attr("status").eq(e.TaskStatus.CANCELED).and(z.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(n)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${n.length} tasks`),a.debug("deleted tasks:",n),n}catch(e){throw a.error("Error during task cleanup",e),e}}},r.__decorate([Te(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([tr("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class rr{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(s.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}for(e,...t){return new Proxy(this,{get(r,a){if("logger"===a){const s=Reflect.get(r,a);try{return s.for(e,...t)}catch(e){r.error("Failed to bind task logger. received: "+(s&&s.constructor?s.constructor.name:s.name?s.name:"unknown"),e);try{r.trace(JSON.stringify(s,void 0,2))}catch(e){r.trace("unserializable output: "+(s.name||"unknown"))}throw e}}return Reflect.get(r,a)}})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function ar(t,r={logProgress:!0,logStatus:!0,style:!0}){return async i=>{switch(t=t.for(i.taskId,{style:!1}),i.classification){case e.TaskEventType.LOG:{const e=i.payload.map(e=>Array.isArray(e)?e:[e.level,e.msg,e.meta]);for(let[a,i,n]of e){r.style||(i=s.style(i),i=i.clear().toString());const e=[i];a===s.LogLevel.verbose&&e.push(1),e.push(n);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=i.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=i.payload?.status??i.payload;let n=s.style(r);switch(r){case e.TaskStatus.SUCCEEDED:n=n.green.bold;break;case e.TaskStatus.RUNNING:n=n.blue.bold;break;case e.TaskStatus.PENDING:n=n.yellow;break;case e.TaskStatus.WAITING_RETRY:n=n.yellow.bold;break;case e.TaskStatus.FAILED:n=n.red.bold;break;case e.TaskStatus.CANCELED:n=n.magenta.bold;break;case e.TaskStatus.SCHEDULED:n=n.cyan;break;default:throw new a.InternalError("Received unknown task status: "+i.payload)}t.info("### STATUS "+n)}break;default:throw new a.InternalError("Unknown task event classification: "+i.classification)}}}function sr(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function ir(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function nr(e){return new Promise(t=>setTimeout(t,e))}class or extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=or.name,Object.setPrototypeOf(this,or.prototype)}}class cr extends v{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(e){this.cache.put("step",e)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new or({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?ir(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const r=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t));return{afterCurrent:async()=>{const e=this.getOrUndefined("scheduleCompositeSteps");if(!e)throw new a.InternalError("scheduleSteps().afterCurrent() is only available while running a composite task step");await e(r)}}}constructor(e){super(e)}}class lr{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=o.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class dr extends k{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:n}=U.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class ur extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class pr extends ur{constructor(e,t,r){super(pr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class hr extends ur{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(hr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class gr extends ur{constructor(e,t,r){super(gr.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class fr extends ur{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(fr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class yr{constructor(t,r){this.bus=t,this.task=r,this.resolved=!1,this.unregistration=t.observe(this,(t,r,a,...s)=>a.startsWith(this.task.id)&&(t===e.TaskEventModel||t===i.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(ar(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=(r.payload??[]).map(e=>Array.isArray(e)?e:[e.level,`${e.ts} - ${e.msg}`,e.meta]);await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}onUpdate(t){const r=async(r,a)=>{r.classification===e.TaskEventType.UPDATE&&await t(r,a)};return this.pipe(r,e.TaskEventType.UPDATE),()=>{this.pipes?.[e.TaskEventType.UPDATE]?.delete(r)}}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,n);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(t.classification!==e.TaskEventType.STATUS)return;if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new v),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new pr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new gr(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new hr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new fr(this.task.id,r,a);default:return new pr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class mr extends E{get Context(){return cr}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,e.TaskModel,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,e.TaskEventModel,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(e,t){const r=new cr(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1;const t=Object.assign({},ke.autoShutdown,e.autoShutdown);this.config=Object.assign({},ke,e,{autoShutdown:t,bus:e.bus||new dr,registry:e.registry||new lr}),this.idleDelayMs=this.config.pollMsIdle}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const n=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${n.id}`),t?{task:n,tracker:new yr(this.bus,n)}:n}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new yr(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await nr(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const n=await this.tasks.update(s,a);return await this.emitStatus(a,n,e.TaskStatus.CANCELED,i),n}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.idleDelayMs=this.config.pollMsIdle,this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(z.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const n=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(n),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(n),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},a=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),s=r.backoffStepMs??0;for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e)));const i=0===e.length;if(i)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+s,a),this.idleDelayMs>=a)return t.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(t)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const n=i?this.idleDelayMs:this.config.pollMsBusy;await nr(Math.max(n,0))}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=z.attribute("status").eq(e.TaskStatus.PENDING),i=z.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(z.attribute("nextRunAt").lte(a)),n=z.attribute("status").eq(e.TaskStatus.RUNNING).and(z.attribute("leaseExpiry").lte(a)),o=z.attribute("status").eq(e.TaskStatus.SCHEDULED).and(z.attribute("scheduledTo").lte(a)),c=s.or(i).or(n).or(o),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}if(!await this.isRunnable(i,r))return null;const n=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,r)}catch{return null}}isTaskFinished(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t)}parseTaskDependency(e){const t=e?.trim();if(!t)return;const r=t.lastIndexOf(":");if(0>=r||r>=t.length-1)return{taskId:t};const a=t.slice(0,r).trim(),s=t.slice(r+1).trim();return a&&s?{taskId:a,stepRef:s}:{taskId:t}}normalizeDependencies(e){if(!e)return[];let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{t=[t]}return t instanceof Set&&(t=Array.from(t)),Array.isArray(t)?t.filter(e=>"string"==typeof e).map(e=>this.parseTaskDependency(e)).filter(Boolean):[]}resolveDependencyStepIndex(e,t){const r=t.trim();if(!r)return;const a=Number(r);if(Number.isInteger(a)&&a>=0)return a;const s=this.normalizeSteps(e.steps).findIndex(e=>e.name===r||e.classification===r);return 0>s?void 0:s}async areDependenciesSatisfied(e,t){if(!e.length)return!0;const r=Array.from(new Set(e.map(e=>e.taskId))),a=new Map;try{const e=await this.tasks.readAll(r,t);for(const t of e)t?.id&&a.set(t.id,t)}catch{return!1}for(const t of e)try{const e=a.get(t.taskId);if(!e)return!1;if(!t.stepRef){if(!this.isTaskFinished(e.status))return!1;continue}const r=this.resolveDependencyStepIndex(e,t.stepRef);if(null==r)return!1;const s=this.normalizeStepResults(e.stepResults)[r];if(!s||!this.isTaskFinished(s.status))return!1}catch{return!1}return!0}getStepLock(t,r){if(t.atomicity!==e.TaskType.COMPOSITE)return;const a=this.normalizeSteps(t.steps);if(!a.length)return;const s=a[r??0];return s?.lock}async hasLockConflict(t,r,a){const s=[t.lock,this.getStepLock(t,r)].filter(e=>!!e&&"string"==typeof e);if(!s.length)return!1;const i=await this.tasks.select().where(z.attribute("status").eq(e.TaskStatus.RUNNING)).execute(a);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(e=>!!e&&"string"==typeof e).some(e=>s.includes(e)))return!0;return!1}async isRunnable(t,r){const a=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(a,r))return!1;const s=t.atomicity===e.TaskType.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,r)}async executeClaimed(t){const{ctx:r,log:i}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),n=this;let o=Promise.resolve();const c=new cr(r).accumulate({taskId:t.id,logger:new rr(i,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=n.normalizePipeArgs(e);r.length&&(o=o.then(async()=>{const[e,a]=await n.appendLog(this,t,r);Object.assign(t,e),await n.emitLog(this,t.id,a)}),await o)},flush:async()=>c.logger.flush(c.pipe),progress:async e=>{await this.emitProgress(c,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let l,d;await this.emitStatus(c,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,c);try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(l=e,d=t.input,i.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,c),await c.flush(),i.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const s=await this.tasks.update(t,c);Object.assign(t,s),c.logger.info(`task ${t.id} success state ${t.status}`),i.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(c,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{await c.flush()}catch{}try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}if(r instanceof or)return void await this.handleTaskStateChange(r.request,t,c);try{await(l?.catch?.(d,r,c))}catch(e){i.error("task handler catch() hook failed",e)}if(i.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=ir(r);if(a<t.maxAttempts){const o=sr(a,this.normalizeBackoff(t.backoff)),l=new Date(Date.now()+o);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=l,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const d=await this.tasks.update(t,c);Object.assign(t,d),i.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await c.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:l,delayMs:o,attempt:a}),await this.emitStatus(c,t,e.TaskStatus.WAITING_RETRY,n,r)}else{t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const o=await this.tasks.update(t,c);Object.assign(t,o),i.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await c.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(c,t,e.TaskStatus.FAILED,n,r)}}}async handleTaskStateChange(t,r,i){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.CANCELED,a),void await i.pipe(s.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,n=sr(a,this.normalizeBackoff(r.backoff)),o=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+n),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=o,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.WAITING_RETRY,c),void await i.pipe(s.LogLevel.warn,"Retry requested",{nextRunAt:o,delayMs:n,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const n=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=n,r.nextRunAt=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.SCHEDULED,n),void await i.pipe(s.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite);let i=this.normalizeSteps(t.steps),n=t.currentStep??0;const o=this.normalizeStepResults(t.stepResults),c=(e,t)=>{r.cacheResult(e,t),a instanceof cr&&a!==r&&a.cacheResult(e,t)};for(let r=0;r<o.length;r+=1){const a=o[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=i[r];if(!e)continue;const s=`${t.id}:step:${r}`;c(e.classification,a.output),c(s,a.output)}}for(;n<i.length;){r.setStep(n);const l=i[n],d=this.registry.get(l.classification);if(!d)throw Error("No task handler registered for composite step: "+l.classification);const u=this.normalizeDependencies(l.dependsOn);await this.areDependenciesSatisfied(u,r)||r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${n} (${l.classification})`),await this.hasLockConflict(t,n,r)&&r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${n} (${l.classification})`),t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await r.progress({currentStep:n,totalSteps:i.length});const h=n;r.cache.put("scheduleCompositeSteps",async a=>{const s=this.normalizeSteps(a);if(!s.length)return;const n=this.normalizeSteps(t.steps),o=Math.min(h+1,n.length);n.splice(o,0,...s),t.steps=n;const c=await this.tasks.update(t,r);Object.assign(t,c),i=this.normalizeSteps(t.steps);const l=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:h,totalSteps:i.length,output:{added:s.length,insertionIndex:o}});this.bus.emit(l,r)}),await r.pipe([s.LogLevel.info,`Composite step ${n+1}/${i.length}: ${l.classification}`]);try{const a=await d.run(l.input,r);await r.flush();const s=new Date;o[h]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:a,createdAt:s,updatedAt:s});const u=`${t.id}:step:${h}`;c(l.classification,a),c(u,a),n=h+1,t.stepResults=o,t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await this.emitProgress(r,t.id,{currentStep:n,totalSteps:i.length,output:a})}catch(s){try{await(d.catch?.(l.input,s,r))}catch(e){a.logger.warn("composite step catch() hook failed",{error:e})}const i=new Date;o[n]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:ir(s),createdAt:i,updatedAt:i}),t.stepResults=o,t.currentStep=n,t.error=ir(s);const c=await this.tasks.update(t);throw Object.assign(t,c),s}}return{stepResults:o}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=Array.isArray(a)&&Array.isArray(a[0]),i=r.atomicity===e.TaskType.COMPOSITE?t instanceof cr?t.step??r.currentStep:r.currentStep:void 0,n=(s?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a,step:i})),o=[...r.logTail??[],...n].slice(-this.config.logTailMax);r.logTail=o;try{return[await this.tasks.update(r,t),n]}catch{return[r,[]]}}async emitStatus(t,r,a,s,i){t instanceof cr&&await t.flush();const n={status:a};s&&s instanceof e.TaskErrorModel?n.error=s:s&&(n.output=s),r.nextRunAt&&(n.nextRunAt=r.nextRunAt),r.scheduledTo&&(n.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,n),c=void 0!==i?Object.assign({},n,{originalError:i}):n,l=new e.TaskEventModel({...o,payload:c});this.bus.emit(l,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta,step:e.step})));this.bus.emit(s,t)}normalizePipeArgs(e){if(!e.length)return[];if(1===e.length){const t=e[0];return Array.isArray(t)?0===t.length?[]:Array.isArray(t[0])?t.filter(Array.isArray):[t]:[]}const[t,r,a]=e;return"string"!=typeof t||"string"!=typeof r?[]:[[t,r,a]]}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class wr extends Nt{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...e){const t=e.shift();if(!t||t instanceof v)throw new a.InternalError("No/invalid config provided");if(!t.adapter)throw new a.InternalError("No adapter provided");return{client:new(t.engine||mr)(t),config:t}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}select(e){return this.tasks.select(e)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.tasks.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.tasks.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.tasks.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.tasks?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.tasks,s)}async update(e,...t){throw new T("Updates to tasks are not available")}async updateAll(e,...t){throw new T("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...a)}refresh(e,t,r,...a){return this.tasks.refresh(e,t,r,...a)}observe(e,t){return this.tasks.observe(e,t)}unObserve(e){return this.tasks.unObserve(e)}updateObservers(e,t,r,...a){return this.tasks.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.tasks._adapter.logCtx([this.tasks.class,...e],t,r,this.tasks._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}function _r(e,t){return e.reduce((e,r)=>e+(e=>{if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}})(r[t]),0)}function vr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"create",null),r.__decorate([Rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"createAll",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"delete",null),r.__decorate([Ft(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"deleteAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"read",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"readAll",null),r.__decorate([Lt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"query",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"update",null),r.__decorate([$t(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],wr.prototype,"updateAll",null);const br=Object.assign({},g,{persistMigrationSteps:!0});class Sr{constructor(e="migration-task"){this.builder=(new Zt).setClassification("migration-composite").setName(e).setMaxAttempts(1)}addMigrationStep(e){return this.builder.addStep("migration",e),this}addStep(e,t){return this.builder.addStep(e,t),this}build(){return this.builder.build()}}class Er{isVersionHint(e){return!!e}normalize(e,t){return t&&e&&(e.includes(t)||e===t)?t:e||t||"migration"}compare(e,t){return e.localeCompare(t)}gt(e,t){return this.compare(e,t)>0}lte(e,t){return 0>=this.compare(e,t)}}class kr extends Nt{constructor(){super(),this.versioning=new Er,this.queuedTaskChain=[],this.reference=kr.name,this.precedence=null}static async migrateAdapters(e,t={},...r){const s=t.flavours?.length?new Set(t.flavours):void 0,i=e.filter(e=>!s||s.has(e.alias)),n=new Set(e.map(e=>e.alias).filter(Boolean)),o=t.taskService?.client,c=o?.adapter?.alias||o?.adapter?.flavour;if(c&&n.has(c))throw new a.InternalError(`TaskEngine adapter alias "${c}" cannot participate in the migration targets`);const l=[];for(const e of i){const a=e.alias,s=t.handlers?.[a]||t.handlers?.[e.flavour]||{},n=new kr;l.push(n),await n.boot({persistenceFlavour:a,targetVersion:t.toVersion,taskMode:!!t.taskMode,includeGenericInTaskMode:!(t.taskMode&&i.length>1),retrieveLastVersion:s.retrieveLastVersion,setCurrentVersion:s.setCurrentVersion,taskService:t.taskService}),t.taskMode?await n.migrateViaTasks(void 0,void 0,...r):await n.migrateNormally(void 0,void 0,...r)}return l}async initialize(...t){const{log:r,ctx:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);try{Pt.get(e.PersistenceKeys.PERSISTENCE)}catch(e){a.get("ignoreDevSafeGuards")||r.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:br,br);return this.versioning=s.versioning||new Er,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?U.get(s.persistenceFlavour):void 0}}async down(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(s.style("Cleaning up after all migrations").green.bold)}normalizeVersion(e,t){return this.versioning.normalize(e,t)}extractPrecedenceTokens(e){const t=e.precedence;return t?(Array.isArray(t)?t:[t]).map(e=>{if(e&&"string"!=typeof e)return"function"==typeof e?e.name:"string"==typeof e.reference?e.reference:e.constructor?.name?e.constructor.name:void 0}).filter(e=>!!e):[]}referencesMigration(e,t){const r=this.extractPrecedenceTokens(e);return!!r.length&&(r.includes(t.reference)||r.includes(t.migration?.constructor?.name))}precedenceHint(e){return"string"==typeof e.precedence?e.precedence:void 0}compareByPrecedence(e,t){const r=e.migration,a=t.migration,s=this.referencesMigration(r,t),i=this.referencesMigration(a,e);if(s&&!i)return 1;if(i&&!s)return-1;const n=this.extractPrecedenceTokens(r),o=this.extractPrecedenceTokens(a);return n.length!==o.length?n.length-o.length:0}sort(e){const t=[...e].sort((e,t)=>{const r=this.versioning.compare(e.version,t.version);if(0!==r)return r;const a=this.compareByPrecedence(e,t);if(0!==a)return a;const s=e.flavour.localeCompare(t.flavour);return 0!==s?s:e.reference.localeCompare(t.reference)});for(let e=0;e<t.length;e++){const r=t[e],s=t[e+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new a.InternalError(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return t}resolveMigration(t){const r=o.Metadata.get(t.constructor,e.PersistenceKeys.MIGRATION),a=r?.flavour||t.flavour||o.DefaultFlavour,s=r?.reference||t.reference,i=this.precedenceHint(t);return{migration:t,flavour:a,reference:s,version:this.normalizeVersion(s,i)}}shouldIncludeMigration(e,t,r=!0){return!t||e.flavour===t||r&&e.flavour===o.DefaultFlavour}collectMigrations(e,t=!0){const r=o.Metadata.migrations(),s=[];for(const[i,n]of r){let r;try{r=new n}catch(e){throw new a.InternalError(`failed to create migration ${i}: ${e}`)}const o=this.resolveMigration(r);this.shouldIncludeMigration(o,e,t)&&s.push(o)}return s}buildExecutionPlan(e){const t=e?.fromVersion?this.normalizeVersion(e.fromVersion):void 0,r=e?.toVersion?this.normalizeVersion(e.toVersion):void 0;return this.sort(this.collectMigrations(e?.targetFlavour,e?.includeGeneric)).filter(e=>!(t&&!this.versioning.gt(e.version,t)||r&&!this.versioning.lte(e.version,r)))}async executeMigration(e,...t){const r=e.migration;let s,i;try{if(s=U.get(e.flavour),!s)throw new a.InternalError(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(e){throw new a.InternalError(`Failed to load adapter to migrate ${r.reference}: ${e}`)}try{await r.up(i,s,...t)}catch(e){throw new O(`failed to initialize migration ${r.reference}: ${e}`)}try{await r.migrate(i,s,...t)}catch(e){throw new O(`failed to migrate ${r.reference}: ${e}`)}try{await r.down(i,s,...t)}catch(e){throw new O(`failed to conclude migration ${r.reference}: ${e}`)}}buildMigrationTaskForPlan(e,...t){const r=[...t],a=new Sr;return e.forEach(e=>{const t={reference:e.reference,args:r};a.addMigrationStep(t)}),a.build()}buildMigrationTasksForPlan(e,...t){const r=new Map;for(const t of e){const e=r.get(t.version)||[];e.push(t),r.set(t.version,e)}return[...r.entries()].map(([e,r])=>({version:e,task:this.buildMigrationTaskForPlan(r,...t)}))}createMigrationTask(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTaskForPlan(i,...r)}createMigrationTasks(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTasksForPlan(i,...r)}migrationTaskIdsFromContext(e,t){const r=t[t.length-1],a=r?.pending?.()||r?.pending||{},s=a?.[e];return Array.isArray(s)?s.filter(e=>"string"==typeof e):[]}async migrate(e,t,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(t,r,...a){const{ctxArgs:s,log:i}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateNormally),n=this.config,o=n.persistenceFlavour,c=!n.taskMode||(n.includeGenericInTaskMode??!0),l=o?U.get(o):void 0;let d;if(n.retrieveLastVersion&&l){const e=await n.retrieveLastVersion(l,...s);e&&(d=this.normalizeVersion(e))}const u=this.buildExecutionPlan({fromVersion:d,toVersion:n.targetVersion,targetFlavour:o,includeGeneric:c});i.debug("sorted migration before execution: "+u.map(e=>`${e.reference}@${e.version}`));for(const e of u)await this.executeMigration(e,...s);if(n.setCurrentVersion&&l){const e=n.targetVersion||u[u.length-1]?.version||d||void 0;e&&await n.setCurrentVersion(this.normalizeVersion(e),l,...s)}}async migrateViaTasks(t,r,...a){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateViaTasks),o=this.config,c=o.persistenceFlavour,l=o.includeGenericInTaskMode??!0,d=c?U.get(c):void 0;let u;if(o.retrieveLastVersion&&d){const e=await o.retrieveLastVersion(d,...i);e&&(u=this.normalizeVersion(e))}const p=this.buildExecutionPlan({fromVersion:u,toVersion:o.targetVersion,targetFlavour:c,includeGeneric:l});if(n.debug("sorted migration before execution: "+p.map(e=>`${e.reference}@${e.version}`)),this.queuedTaskChain=[],p.length){const t=this.buildMigrationTasksForPlan(p,...i);if(o.taskService){let r;for(const a of t){r&&(a.task.dependencies=[...a.task.dependencies||[],r]);const t=await o.taskService.push(a.task,!1,...i);r=t.id,this.queuedTaskChain.push({id:t.id,version:a.version}),t?.id||n.warn("TaskService.push returned missing id for version "+a.version),s.pushPending(e.PersistenceKeys.MIGRATION,t.id)}}else{for(const e of p)await this.executeMigration(e,...i);if(o.setCurrentVersion&&d){const e=o.targetVersion||p[p.length-1]?.version||u||void 0;e&&await o.setCurrentVersion(this.normalizeVersion(e),d,...i)}}}}async track(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.track),s=this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return;const l=this.queuedTaskChain.reduce((e,t)=>(e[t.id]=t.version,e),{}),d=this.config.persistenceFlavour?U.get(this.config.persistenceFlavour):void 0;for(const e of c){const{tracker:t}=await s.taskService.track(e,...a);await t.wait(),s.setCurrentVersion&&d&&l[e]&&await s.setCurrentVersion(this.normalizeVersion(l[e]),d,...a)}}async retry(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.retry),s=this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...a);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return void await this.migrateViaTasks(void 0,void 0,...a);const l=s.taskService.client.tasks,d="function"==typeof l?.override?l.override({ignoreHandlers:!0}):l;for(const t of c){const r=(await s.taskService.track(t,...a)).task;if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(r.status))continue;const i=new e.TaskModel({...r,status:e.TaskStatus.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await d.update(i,...a)}}async up(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(s.style("Setting up migration process").yellow.bold)}}const Tr=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),o.DefaultFlavour)||[];o.Metadata.set(e.PersistenceKeys.MIGRATION,o.DefaultFlavour,[...Tr,kr]),e.MigrationTask=class extends er{async run(t,r){r.logger.info("Executing migration "+t.reference);const s=o.Metadata.migrations().find(([,r])=>{const a=r?.name,s=o.Metadata.get(r,e.PersistenceKeys.MIGRATION)?.reference;return a===t.reference||s===t.reference});if(!s)throw new a.InternalError(`Migration ${t.reference} is not registered with the metadata layer`);const i=s[1];let n;try{n=new i}catch(e){throw new a.InternalError(`Failed to instantiate migration ${t.reference}: ${e}`)}const c=o.Metadata.get(n.constructor,e.PersistenceKeys.MIGRATION),l=c?.flavour||n.flavour,d=U.get(l);if(!d)throw new a.InternalError("Unable to resolve adapter for migration "+t.reference);const u=d.client,p=t.args??[];try{await n.up(u,d,...p,r)}catch(e){throw r.logger.error(`Up phase for ${t.reference} failed: ${e}`),new O(`Up phase for ${t.reference} failed: ${e}`)}try{await n.migrate(u,d,...p,r)}catch(e){throw r.logger.error(`migration phase for ${t.reference} failed: ${e}`),new O(`Migration phase for ${t.reference} failed: ${e}`)}try{await n.down(u,d,...p,r)}catch(e){throw r.logger.error(`down phase for ${t.reference} failed: ${e}`),new O(`Down phase for ${t.reference} failed: ${e}`)}r.logger.info(`migration ${t.reference} completed`)}},e.MigrationTask=r.__decorate([tr("migration")],e.MigrationTask),t.Injectables.setRegistry(new Se);const Or="##VERSION##",Ar="##PACKAGE##";o.Metadata.registerLibrary(Ar,Or),e.AbsContextual=E,e.AbsMigration=class extends E{get reference(){if(!this._reference){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._reference=t.reference,!this._reference)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._precedence=t.precedence,!this._precedence)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;P(this,e,this.prefix(t))})}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return U.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const e of s)if(!await e(t,r,a))return!1;return!0}prefix(t){return async function(r){let a;r instanceof U?a=this.getQueryRunner(r.client):(a=r,r=this.adapter);const{ctx:s,log:i}=await this.logCtx([t],e.PersistenceKeys.MIGRATION,!0);if(!await this.enforceRules(a,r,s))throw i.verbose(`Skipping migration ${this.constructor.name} due to rules`),new A("Migration skipped for rule enforcement");return[a,r,s]}.bind(this)}},e.Adapter=U,e.AdapterTransaction=R,e.AuthorizationError=nt,e.BaseModel=Et,e.BigIntSequence=De,e.ClientBasedService=Nt,e.CompositeTaskBuilder=Zt,e.Condition=z,e.ConnectionError=ct,e.Context=v,e.ContextLock=L,e.ContextualLoggedClass=b,e.DefaultAdapterFlags=g,e.DefaultCascade=V,e.DefaultContextFlags=h,e.DefaultMigrationConfig=br,e.DefaultRepositoryFilters=oe,e.DefaultSequenceOptions=Ce,e.DefaultTaskEngineConfig=ke,e.Dispatch=qt,e.ForbiddenError=ot,e.InjectablesRegistry=Se,e.MethodQueryBuilder=J,e.MigrationError=O,e.MigrationRuleError=A,e.MigrationService=kr,e.MigrationTaskBuilder=Sr,e.ModelService=Ut,e.MultipleSelectOperationKeys=w,e.NonTransactionOperationKeys=y,e.NoneSequenceOptions=xe,e.NumericSequence=Me,e.ObserverError=Oe,e.ObserverHandler=k,e.OperatorsMap=Q,e.PACKAGE_NAME=Ar,e.PaginationOperationKeys=_,e.Paginator=kt,e.PagingError=G,e.PersistenceService=class extends Nt{constructor(){super()}for(e,...t){throw new T("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof v||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),n=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of n)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:n,config:r}}},e.QueryError=q,e.Repository=ve,e.SelectOperationKeys=m,e.Sequence=Yt,e.Serial=B,e.Service=Pt,e.StandardMigrationVersioning=Er,e.Statement=It,e.TaskBackoffBuilder=Wt,e.TaskBuilder=Jt,e.TaskCancelError=gr,e.TaskContext=cr,e.TaskControlError=ur,e.TaskEngine=mr,e.TaskEventBus=dr,e.TaskEventService=class extends Ut{constructor(){super(e.TaskEventModel)}get repo(){return this._repository||(this._repository=Pt.get(e.TaskModel).events),this._repository}},e.TaskFailError=pr,e.TaskHandler=er,e.TaskHandlerRegistry=lr,e.TaskIOSerializer=Qt,e.TaskLogger=rr,e.TaskRescheduleError=fr,e.TaskRetryError=hr,e.TaskService=wr,e.TaskStepSpecBuilder=Xt,e.TaskTracker=yr,e.TasksKey=Ee,e.TransactionOperationKeys=f,e.UUID=N,e.UnsupportedError=T,e.VERSION=Or,e.allowIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:o}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,n)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...o)}})},e.applyViewDecorator=Z,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return o.Decoration.for(r).define({decorator:e=>o.metadata(r,e),args:[t]}).apply()},e.blockIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:o}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,n)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...o)}})},e.cacheModelForPopulate=tt,e.cascadeDelete=at,e.column=dt,e.computeBackoffMs=sr,e.create=Rt,e.createOrUpdate=Ke,e.createdAt=ft,e.createdBy=ht,e.createdByOnCreateUpdate=pt,e.defaultQueryAttr=()=>(t,r)=>{const a=o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let s=o.Metadata.get(t.constructor,a)||[];return s=[...new Set([...s,r])],o.apply(o.propMetadata(a,s))(t,r)},e.del=Ft,e.generateInjectableNameForRepository=be,e.getAdapterTransaction=Ht,e.getAndConstructJunctionTable=Ze,e.getContextLock=Vt,e.getFilters=ce,e.getLogPipe=ar,e.getPkTypes=vt,e.getPopulateKey=et,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ie,e.injectableServiceKey=x,e.isOperationBlocked=I,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.list([e,...d]),a.onCreate(Je,c),a.onUpdate(ze,c),a.afterAny(rt,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToManyOnCreate=Je,e.manyToManyOnDelete=async function(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n||!n.length)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ve.forModel(c,this.adapter.alias):it(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await tt(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Je.call(this,t,r,a,s)},e.manyToOne=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.type([e,...d]),a.onCreate(He,c),a.onUpdate(Qe,c),a.onDelete(We,c),a.afterAny(rt,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToOneOnCreate=He,e.manyToOneOnDelete=We,e.manyToOneOnUpdate=Qe,e.migration=(t,r,a,s)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(r,a,s)=>i=>{const n=r&&"object"==typeof r&&!("name"in r)?r:void 0,c=n?.precedence,l=n?.flavour,d=n?.rules,u=n?c:r,p=n?l:a,h=n?d:s,g=n?void 0!==c:void 0!==u&&("string"!=typeof u||"string"==typeof u&&"string"==typeof p);let f,y,m=u;"string"==typeof u?"string"==typeof p?(m=u,f=p,y=h):Array.isArray(p)?(m=void 0,f=u,y=p):(m=void 0,f=u,y=h):Array.isArray(p)?y=p:(f=p,y=h),void 0===m&&null!==m&&(m=kr);const w=o.Metadata.flavourOf(i)||o.DefaultFlavour,_=(g&&m===kr&&t&&t!==f?t:f)||w,v=o.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")),_||o.DefaultFlavour)||[];return o.Metadata.set([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-"),_||o.DefaultFlavour,[...v,{class:i}]),o.Metadata.set(e.PersistenceKeys.MIGRATION,t,i),o.metadata(e.PersistenceKeys.MIGRATION,{reference:t||i.name,precedence:m,flavour:_||o.DefaultFlavour,rules:y})(i)},args:[r,a,s]}).apply(),e.noValidateOn=bt,e.noValidateOnCreate=()=>bt(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>bt(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>bt(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.list([e,...d]),a.onCreate(Ge,c,{priority:70}),a.onUpdate(ze,c,{priority:70}),a.onDelete(Ye,c,{priority:70}),a.onUpdate(at,c,{priority:80}),a.afterAny(rt,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToManyOnCreateUpdate=Ge,e.oneToManyOnDelete=Ye,e.oneToManyOnUpdate=ze,e.oneToOne=(t,r=V,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=vt(e),u=[o.prop(),St(l,c),i.type([e,...d]),a.onCreate(je,c,{priority:70}),a.onUpdate(Ue,c,{priority:70}),a.onDelete(qe,c,{priority:70}),a.onUpdate(at,c,{priority:80}),a.afterAny(rt,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToOneOnCreate=je,e.oneToOneOnDelete=qe,e.oneToOneOnUpdate=Ue,e.onlyOnBulk=ie,e.onlyOnCreate=ee,e.onlyOnDelete=re,e.onlyOnFilter=ne,e.onlyOnSingle=se,e.onlyOnTransactional=ae,e.onlyOnUpdate=te,e.persistentVersion=_t,e.pk=Fe,e.pkDec=Le,e.pkOnCreate=Be,e.populate=rt,e.prefixMethod=P,e.prepared=X,e.promiseSequence=C,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>function r(s,i,n){const c=J.getFieldsFromMethodName(i);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,i),{...t,fields:c}),X(),(e=>(t,s,i)=>{i.value=new Proxy(i.value,{async apply(t,s,i){const{action:n,select:o,selector:c,where:l,groupBy:d,orderBy:u,limit:p,offset:h}=J.build(t.name,...i);if(!(s instanceof a.Repository))throw Error("thisArg must be an instance of Repository");const g=s,{ctx:f}=(await g.logCtx(i,r.name,!0)).for(r);let y;switch(n){case"find":case"page":y=g.select(o);break;case"count":y=g.count(c);break;case"sum":y=g.sum(c);break;case"avg":y=g.avg(c);break;case"min":y=g.min(c);break;case"max":y=g.max(c);break;case"distinct":y=g.distinct(c);break;case"group":y=g.select(),c&&(y=y.groupBy(c));break;default:throw new q("Unsupported action: "+n)}if(l&&(y=y.where(l)),d&&d.length>0&&"group"!==n){y=y.groupBy(d[0]);for(let e=1;e<d.length;e++)y=y.thenBy(d[e])}else if(d&&d.length>0&&"group"===n)for(const e of d)y=y.thenBy(e);const{allowLimit:m,allowOffset:w,allowOrderBy:_,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},b=[{key:"orderBy",value:(u||[])[0],allowed:_},{key:"limit",value:p,allowed:m},{key:"offset",value:h,allowed:w}];for(const e of b)if(void 0!==e.value){if(!e.allowed&&v)throw new q(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(y=y[e.key](e.value))}if("page"===n){const e=i[i.length-1],t="number"==typeof e?e:e?.limit??10;return y.paginate(t,f)}return y.execute(f)}})})(t))(s,i,n)},args:[t]}).apply(),e.read=Lt,e.relation=St,e.repository=Te,e.repositoryFromTypeMetadata=it,e.resolveBulkSequenceResult=j,e.roles=t=>o.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return o.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const n={path:r,httpMethod:t,handler:i};return o.apply(o.methodMetadata(o.Metadata.key(a,s),n))(e,s,i)},args:[]}).apply()},e.sequence=(t,r)=>{const a=Object.assign({},Ce);delete a.generated,t=Object.assign({},a,t);const s="boolean"==typeof r?{update:r}:r||{};return o.Decoration.for(e.PersistenceKeys.SEQUENCE).define({decorator:$e,args:[t,s,{priority:70}]}).apply()},e.sequenceDec=$e,e.sequenceOnCreateUpdate=Re,e.serializeError=ir,e.service=Kt,e.sleep=nr,e.table=lt,e.task=tr,e.throttle=(t={count:1},r=0)=>function s(i,n,c){return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.THROTTLE,n),t),(i,n,o)=>{o.value=new Proxy(o.value,{async apply(i,o,c){const l=c,d=(()=>{try{return"function"==typeof t?t(...l):t}catch(e){throw new a.InternalError("Failed to obtain throttling configuration from handler: "+e)}})(),{log:u,ctx:p}=(await o.logCtx(c,e.PersistenceKeys.THROTTLE,!0)).for(s),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttling() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(r);if(!h.length)throw new a.InternalError("@throttling() expects at least one argument index to throttle");h.forEach(e=>{if(e>=l.length)throw new a.InternalError(`@throttling() requires argument index ${e} but only ${l.length} provided`);if(!Array.isArray(l[e]))throw new a.InternalError(`@throttling() expects argument at index ${e} to be an array`)});const g=h.map(e=>l[e]),f=g[0].length;if(!g.every(e=>e.length===f))throw new a.InternalError("@throttling() requires all targeted arguments to have the same length");if(0===f)return i.apply(o,l);const y=((e,t,r)=>{if("count"in r){if(0>=r.count)throw new a.InternalError("@throttling() configuration 'count' must be greater than zero");const t=[];for(let a=0;e>a;a+=r.count)t.push({start:a,end:Math.min(e,a+r.count)});return t}if("bufferSize"in r){if(0>=r.bufferSize)throw new a.InternalError("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let a=0;e>a;a++){const e=_r(t,a);n>0&&n+e>r.bufferSize?(s.push({start:i,end:a}),i=a,n=e):n+=e}return i>=e&&s.length||s.push({start:i,end:e}),s}return[{start:0,end:e}]})(f,g,d),m=y.map(({start:e,end:t})=>l.map((r,a)=>{const s=h.indexOf(a);return-1===s?r:g[s].slice(e,t)})),w=p.get("breakOnSingleFailureInBulk")??!0,_=[],v=[];for(const e of m){try{vr(await i.apply(o,e),_)}catch(e){if(w)throw e;v.push(e)}d.delayMs&&await new Promise(e=>setTimeout(e,d.delayMs))}if(v.length){u.warn(`${n+""} throttled execution continued with ${v.length} failure(s)`);const e=new AggregateError(v,`Throttled ${n+""} failed for ${v.length} chunk(s)`);throw e.results=_,e}return _}})})(i,n,c)},e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(i.async(),a.onCreateUpdate(ut),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=ut,e.update=$t,e.updatedAt=yt,e.updatedBy=gt,e.uuid=zt,e.uuidCreateUpdateHandler=Gt,e.validBidirectionalRelation=Ve,e.version=(e=!1)=>e?_t():a.version(),e.view=t=>o.Decoration.for(e.Operator.VIEW).define({decorator:t=>Z(e.Operator.VIEW,"view",t),args:[t]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/transactional-decorators","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsTransactionalDecorators,e.decafTsDecoration);
2
2
  //# sourceMappingURL=core.cjs.map