@decaf-ts/core 0.8.66 → 0.8.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/services/ModelService.js +1 -1
- package/lib/esm/services/ModelService.js.map +1 -1
- package/lib/esm/tasks/TaskService.js +1 -1
- package/lib/esm/tasks/TaskService.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/services/ModelService.cjs +1 -1
- package/lib/services/ModelService.js.map +1 -1
- package/lib/tasks/TaskService.cjs +1 -1
- package/lib/tasks/TaskService.js.map +1 -1
- package/package.json +1 -1
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as h,wrapMethodWithContext as p,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,readonly as v,onCreate as A,generated as x,BadRequestError as E,ConflictError as O,onCreateUpdate as C,timestamp as T,onUpdate as k,onDelete as N,afterUpdate as D,afterAny as _,SerializationError as B,prefixMethod as R,composed as I,transient as P,serialize as $,BaseError as L}from"@decaf-ts/db-decorators";import{LoggedClass as F,Logging as j,final as U,toCamelCase as M,LogLevel as Y,style as G}from"@decaf-ts/logging";import{Model as q,hashObj as H,required as z,sf as W,model as Q,isEqual as V,ValidationKeys as J,async as X,type as Z,list as tt,option as et,date as rt,JSONSerializer as st,ModelKeys as it,min as nt,gt as ot}from"@decaf-ts/decorator-validation";import{Lock as at,MultiLock as ct,TransactionalKeys as lt}from"@decaf-ts/transactional-decorators";import{Metadata as ut,Decoration as dt,DefaultFlavour as ht,apply as pt,propMetadata as gt,methodMetadata as ft,DecorationKeys as yt,uses as mt,metadata as wt,prop as bt,method as vt,description as At}from"@decaf-ts/decoration";var xt,Et,St,Ot,Ct;(t=>{t.FIND_BY="findBy",t.PAGE_BY="pageBy",t.COUNT_BY="countBy",t.SUM_BY="sumBy",t.AVG_BY="avgBy",t.MIN_BY="minBy",t.MAX_BY="maxBy",t.DISTINCT_BY="distinctBy",t.GROUP_BY_PREFIX="groupBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(xt||(xt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.STARTS_WITH="STARTS_WITH",t.ENDS_WITH="ENDS_WITH",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(Et||(Et={})),(t=>{t.AND="AND",t.OR="OR"})(St||(St={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ot||(Ot={})),(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute",t.THROTTLE="throttle",t.DEFAULT_QUERY_ATTR="default-query-attr"})(Ct||(Ct={}));const Tt=Object.assign({},{ignoreDevSafeGuards:!1}),kt=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),Nt=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Dt=[a.READ,c.READ_ALL],_t=[Ct.STATEMENT,Ot.FIND_ONE_BY],Bt=[Ct.QUERY,Ot.PAGE_BY,Ot.LIST_BY,Ot.FIND_BY,Ot.FIND,Ot.PAGE],Rt=[Ot.PAGE_BY,Ot.PAGE];class It extends l{constructor(t){super(t)}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter((t=>!e.has(t))),s.length)){const r=s.map((r=>r.getFromChildren(t,e))).reduce(((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t)),[]).filter((t=>null!=t));if(!r.length)return;return r.some((t=>"object"!=typeof t))?r[0]:r.reduce(((t,e)=>Object.assign(t,e)),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce(((t,e)=>(t[e]=this.get(e),t)),{})}accumulate(t){return super.accumulate(t)}}class Pt extends F{logCtx(t,e,r=!1,s){return Pt.logCtx.call(this,e,s||{},r,...t.filter((t=>void 0!==t)))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||j.get();return e.log=t.context?s.clear().for(t):s.for(t),"string"==typeof r?e.for=t=>Object.assign(e,{log:e.log.for(t)}):e.log=e.log.for(r),e};let n=s.pop();const o=n instanceof It;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new u("No context provided");if(o&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then((e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t)))}}class $t extends Pt{constructor(){super(),this._Context=It}get Context(){return this._Context}async context(t,e,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof t?t:t.name} operation with flag overrides: ${Object.keys(e)}`);let s=r.pop();return s instanceof It||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(e):new this.Context(s).accumulate(e)}}class Lt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map((t=>t.observer)).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map((t=>t.observer)).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=Pt.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter((s=>{const{filter:o}=s;if(!o)return!0;try{return o(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((s=>{s.observer.refresh(t,e,r,...n)})))).forEach(((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}class Ft extends u{constructor(t){super(t,Ft.name,500)}}class jt extends u{constructor(t,e=jt.name){super(t,e,500)}}class Ut extends jt{constructor(t){super(t,Ut.name)}}function Mt(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ut.Symbol(ut.constr(t)).toString().replaceAll(".","-")}async function Yt(t,e=!1){if(!e){const e=[];for(const r of t)e.push(await r());return e}const r=[];for(const e of t)try{r.push({status:"fulfilled",value:await e()})}catch(t){r.push({status:"rejected",reason:t})}return r}function Gt(t,e){const{handler:r,args:s}=ut.get(t,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function qt(t){return t.then((t=>t.default||t))}function Ht(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof Ut)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class zt{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}))}static get instance(){return zt._instance||(zt._instance=new zt),zt._instance}}class Wt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Wt._instance||(Wt._instance=new Wt),Wt._instance}}class Qt{constructor(t,...e){this.adapter=t}async begin(...t){}async commit(...t){}async rollback(...t){}}class Vt extends at{constructor(t){super(),this.adapterTransaction=t,this.acquireCount=0,this.lock=new at}async acquire(...t){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...t)):this.lock.release()}async release(...t){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...t)}catch(e){await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+e),...t)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(t,...e){await this.lock.acquire();try{await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+t),...e)}catch(t){throw new u("Failed to rollback transaction: "+t)}finally{this.lock.release()}}}const Jt=dt.flavourResolver.bind(dt);dt.flavourResolver=t=>{try{const e=Jt(t);if(e&&e!==ht)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ut.registeredFlavour?ut.registeredFlavour(r):void 0;if(s&&s!==ht)return s;const i=Zt._currentFlavour;if(i){const t=Zt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return ht}};const Xt=Symbol("AdapterProxyCleanup");function Kt(t,e,r,s){if(!e)return t;const i=t,n=[],o=[];for(const t of i)"fulfilled"===t.status?n.push(t.value):o.push(t.reason);if(o.length){r.warn(`Bulk ${s} encountered ${o.length} failure(s) while continuing`);const t=new AggregateError(o,`Bulk ${s} failed for ${o.length} item(s)`);throw t.results=i,t}return n}class Zt extends $t{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Zt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return Zt._baseRepository}transactionLock(...t){return new Qt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[Xt];"function"==typeof e&&await e()};if(t)try{await s(this.proxies[t]),delete this.proxies[t]}catch(e){r.error("Failed to cleanup proxied adapter "+t,e)}else for(const t in this.proxies){try{await s(this.proxies[t])}catch(e){r.error("Failed to cleanup proxied adapter "+t,e);continue}delete this.proxies[t]}}async shutdown(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(Ct.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:e}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...r),this.dispatch&&await this.dispatch.close(...r)})()}catch(t){throw new u("Failed to create shutdown wrapper: "+t)}finally{this.internalLock.release(Ct.SHUTDOWN)}try{await this.shutdownPromise}catch(t){e.error("Error during proxy shutdown",t)}finally{this.shutdownPromise=void 0}}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.internalLock=new at,this.alias in Zt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Zt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Zt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Zt._currentFlavour=this.alias)}Dispatch(){return new Zt._baseDispatch}ObserverHandler(){return new Lt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new Zt._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?q.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${zt.instance.generate()}`;const o=r.logger||j.for(this);return Object.assign({},kt,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:Nt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ut.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}get Context(){return It}async context(t,e,r,...s){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map((t=>q.tableName(t))):q.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof It||(s.push(i),i=void 0),e=i?Object.assign({},i.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}const e=i.getOrUndefined("operation"),s=i.getOrUndefined("affectedTables");if(!e||e!==t||r&&r!==s){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce(((e,[r,s])=>{if(void 0===s)return e;const i=q.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[Ct.METADATA]&&(r.silly("Passing along persistence metadata for "+t[Ct.METADATA]),Object.defineProperty(i,Ct.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[Ct.METADATA]})),{record:i,id:t[q.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=q.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[Ct.METADATA],d=Object.keys(c).filter((t=>t!==a)).reduce(((r,s)=>(r[s]=t[q.columnName(e,s)],r)),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach((([t,e])=>{if(t in d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e}))),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,Ct.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const o=q.tableName(t);i.debug(`Creating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map(((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0}))));return Kt(a?await Yt(l,!0):await Yt(l),a,i,c.CREATE_ALL)}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=q.tableName(t);s.debug(`Reading ${e.length} entries ${n} table`);const o=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map((e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0}))));return Kt(o?await Yt(a,!0):await Yt(a),o,s,c.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const o=q.tableName(t);i.debug(`Updating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map(((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0}))));return Kt(a?await Yt(l,!0):await Yt(l),a,i,c.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=e.map((e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0}))));return Kt(n?await Yt(o,!0):await Yt(o),n,s,c.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&await this.observerHandler.updateObservers(t,e,r,...n)}}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return ut.flavourOf(t)}static get currentFlavour(){if(!Zt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return Zt._currentFlavour}static get current(){return Zt.get(this.currentFlavour)}static get(t){if(!t)return Zt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return ut.flavouredAs(t).filter(q.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${H(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return Reflect.defineProperty(i,Xt,{value:async()=>{if(!s)return;const t=["cancel","close","destroy","disconnect"];for(const e of t){const t=s[e];if("function"==typeof t)try{const e=t.call(s);e instanceof Promise&&await e}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=i,i}migrations(){return ut.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,It]),n("design:returntype",Promise)],Zt.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Zt.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Zt.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Zt.prototype,"client",null);class te extends u{constructor(t){super(t,te.name,500)}}class ee extends u{constructor(t){super(t,ee.name,500)}}class re extends q{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):q.fromModel(this,t)}and(t){return re.and(this,t)}or(t){return re.or(this,t)}not(t){return new re(this,Et.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof re)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(Et).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===Et.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 re){if(!(this.comparison instanceof re)&&this.operator!==Et.NOT)return{comparison:{condition:t}};if(-1===Object.values(St).indexOf(this.operator)&&this.operator!==Et.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return re.group(t,St.AND,e)}static or(t,e){return re.group(t,St.OR,e)}static group(t,e,r){return new re(t,e,r)}static attribute(t){return(new re.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(Et.EQUAL,t)}dif(t){return this.setOp(Et.DIFFERENT,t)}gt(t){return this.setOp(Et.BIGGER,t)}lt(t){return this.setOp(Et.SMALLER,t)}gte(t){return this.setOp(Et.BIGGER_EQ,t)}lte(t){return this.setOp(Et.SMALLER_EQ,t)}in(t){return this.setOp(Et.IN,t)}regexp(t){return this.setOp(Et.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(Et.STARTS_WITH,t)}endsWith(t){return this.setOp(Et.ENDS_WITH,t)}between(t,e){return this.setOp(Et.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new re(this.attr1,this.operator,this.comparison)}catch(t){throw new te(t)}}}}static builder(){return new re.Builder}static from(t){return new re(t)}}var se,ie;i([z(),n("design:type",Object)],re.prototype,"attr1",void 0),i([z(),n("design:type",String)],re.prototype,"operator",void 0),i([z(),n("design:type",Object)],re.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(se||(se={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(ie||(ie={}));const ne={update:ie.CASCADE,delete:ie.NONE},oe={Equals:(t,e)=>re.attribute(t).eq(e),Diff:(t,e)=>re.attribute(t).dif(e),LessThan:(t,e)=>re.attribute(t).lt(e),LessThanEqual:(t,e)=>re.attribute(t).lte(e),GreaterThan:(t,e)=>re.attribute(t).gt(e),GreaterThanEqual:(t,e)=>re.attribute(t).gte(e),In:(t,e)=>re.attribute(t).in(e),Matches:(t,e)=>re.attribute(t).regexp(e)},ae=t=>t.charAt(0).toLowerCase()+t.slice(1);class ce extends F{static get log(){return this._logger||(this._logger=j.for(ce.name)),this._logger}static{this.prefixMap={[xt.FIND_BY]:"find",[xt.PAGE_BY]:"page",[xt.COUNT_BY]:"count",[xt.SUM_BY]:"sum",[xt.AVG_BY]:"avg",[xt.MIN_BY]:"min",[xt.MAX_BY]:"max",[xt.DISTINCT_BY]:"distinct",[xt.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(t){for(const[e,r]of Object.entries(this.prefixMap))if(t.startsWith(e))return{action:r,prefix:e}}static build(t,...e){const r=this.getActionFromMethodName(t);if(!r)throw Error("Unsupported method "+t);const{action:s,prefix:i}=r;let n;["count","sum","avg","min","max","distinct","group"].includes(s)&&(n=this.extractAggregationSelector(t,i));const o=this.extractCore(t,i),a=this.extractSelect(t),c=this.extractGroupBy(t),l=this.buildWhere(o,e),{orderBy:u,limit:d,offset:h}=this.extractOrderLimitOffset(t,e,o);return{action:s,select:a,selector:n,where:l,groupBy:c,orderBy:u,limit:d,offset:h}}static extractAggregationSelector(t,e){const r=t.substring(e.length),s=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),i=s?r.substring(0,s.index):r;return i?ae(i):void 0}static extractCore(t,e=xt.FIND_BY){const r=t.substring(e.length);if(e!==xt.FIND_BY&&e!==xt.PAGE_BY){const t=r.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!t)return"";if("And"===t[0]||"Or"===t[0]){const e=r.substring(t.index+t[0].length),s=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return s?e.substring(0,s.index):e}return""}const s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?r.substring(0,s.index):r}static getFieldsFromMethodName(t){const e=this.getActionFromMethodName(t),r=e?.prefix||xt.FIND_BY,s=this.extractCore(t,r);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter((t=>t.length>0)).map((t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})):[]}static extractSelect(t){const e=t.indexOf(xt.SELECT);if(-1===e)return;const r=t.substring(e+xt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(xt.AND).map(ae).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(xt.GROUP_BY);if(-1!==e)return t.substring(e+xt.GROUP_BY.length).split(xt.ORDER_BY)[0].split(xt.THEN_BY).map(ae).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(xt.THEN_BY);if(-1===s)return;const i=e.substring(s+xt.THEN_BY.length).split(xt.THEN_BY),n=[];for(const t of i){const e=t.match(/(OrderBy|Limit|Offset|Select)/),r=e?t.substring(0,e.index):t;r&&n.push(ae(r))}return n.length>0?n:void 0}}static buildWhere(t,e){if(!t)return;const r=t.split(/OrderBy|GroupBy/)[0]||"";if(!r)return;const s=r.split(/And|Or/).filter((t=>t.length>0));if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach(((t,r)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),a=o?oe[o]:oe.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+s);const l=a(s,c);n=0===r?l:i[r-1]===xt.AND?n.and(l):n.or(l)})),n}static parseFieldAndOperator(t){for(const e of Object.keys(oe))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:ae(r),operator:e}}return{field:ae(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=ce.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new te("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(se).includes(e))throw new te(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(se).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e,r){const s=r??this.extractCore(t),i=s?s.split(/And|Or/).filter((t=>t.length>0)).length:0,n=e.slice(i)??[];let o,a,c;if(n.at(-1)instanceof l&&n.pop(),n.length>=1){const e=n[0],r=this.extractOrderByField(t);o=this.getProperlyOrderByOrThrow(r,e)}return 2>n.length||"number"!=typeof n[1]||(a=n[1]),3>n.length||"number"!=typeof n[2]||(c=n[2]),{orderBy:o,limit:a,offset:c}}}function le(){return(t,e)=>{const r=ut.key(Ct.DEFAULT_QUERY_ATTR);let s=ut.get(t.constructor,r)||[];return s=[...new Set([...s,e])],pt(gt(r,s))(t,e)}}function ue(){return dt.for(Ct.STATEMENT).define({decorator:()=>(t,e,r)=>pt(ft(ut.key(Ct.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function de(t={}){return dt.for(Ct.QUERY).define({decorator:t=>(e,r,s)=>{const i=ce.getFieldsFromMethodName(r);return pt(ft(ut.key(Ct.QUERY,r),{...t,fields:i}),ue(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{action:i,select:n,selector:o,where:a,groupBy:c,orderBy:l,limit:u,offset:d}=ce.build(e.name,...s),h=r;let p;switch(i){case"find":case"page":p=h.select(n);break;case"count":p=h.count(o);break;case"sum":p=h.sum(o);break;case"avg":p=h.avg(o);break;case"min":p=h.min(o);break;case"max":p=h.max(o);break;case"distinct":p=h.distinct(o);break;case"group":p=h.select(),o&&(p=p.groupBy(o));break;default:throw new te("Unsupported action: "+i)}if(a&&(p=p.where(a)),c&&c.length>0&&"group"!==i){p=p.groupBy(c[0]);for(let t=1;t<c.length;t++)p=p.thenBy(c[t])}else if(c&&c.length>0&&"group"===i)for(const t of c)p=p.thenBy(t);const{allowLimit:g,allowOffset:f,allowOrderBy:y,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},w=[{key:"orderBy",value:(l||[])[0],allowed:y},{key:"limit",value:u,allowed:g},{key:"offset",value:d,allowed:f}];for(const t of w)if(void 0!==t.value){if(!t.allowed&&m)throw new te(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(p=p[t.key](t.value))}if("page"===i){const t=s[s.length-1],e="number"==typeof t?t:t?.limit??10;return p.paginate(e)}return p.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function he(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(ut.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=ut.key(t,i,n),a={...r||{},kind:e,attribute:i};return gt(o,a)(s,i)}}function pe(t){return dt.for(Et.VIEW).define({decorator:t=>he(Et.VIEW,"view",t),args:[t]}).apply()}function ge(t){return ve(t,[a.CREATE,c.CREATE_ALL])}function fe(t){return ve(t,[a.UPDATE,c.UPDATE_ALL])}function ye(t){return ve(t,[a.DELETE,c.DELETE_ALL])}function me(t){return ve(t,Nt)}function we(t){return ve(t,Object.values(a))}function be(t){return ve(t,Object.values(c))}function ve(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:o}=Pt.prototype.logCtx(n,ve);return o.silly(`filtering ${s} event for${r?" "+(q.tableName(r)||r):""} ${i}`),("string"==typeof r?r===q.tableName(t)||r===t.constructor.name:ut.constr(t)===ut.constr(r))&&e.includes(s)}}const Ae={onlyOnCreate:ge,onlyOnUpdate:fe,onlyOnDelete:ye,onlyOnTransactional:me,onlyOnSingle:we,onlyOnBulk:be};function xe(t){const e=Object.assign({},Ae);return Object.entries(e).forEach((([r,s])=>{e[r]=s(t.class)})),e}var Ee,Se,Oe,Ce,Te,ke,Ne,De,_e,Be,Re;class Ie extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new u("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=q.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return xe(this)}constructor(t,e,...r){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},t&&(this._adapter=t),e&&(Ie.register(e,this,this.adapter.alias),t)&&ut.get(e,yt.FLAVOUR)===ht&&mt(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach((t=>{const e=t.name;p(s,s[e+"Prefix"],t,s[e+"Suffix"])})),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(t,e,r=!1,s){const i=this.adapter.logCtx([this.class,...t],e,r,Object.assign({},s||{},this._overrides||{}));function n(t){return t.ctxArgs.shift(),t}return i instanceof Promise?i.then(n):n(i)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new Lt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),t=new this.class(t),n||await f(this,r,t,a.CREATE,a.ON),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new d(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${q.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${q.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r))),o=n.map((t=>t.id));let a=n.map((t=>t.record));return a=await this.adapter.createAll(this.class,o,a,...i),a.map(((t,e)=>this.adapter.revert(t,this.class,o[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!t.length)return[t,...s];const l=q.sequenceFor(t[0]);let h=[];if(q.generatedBySequence(this.class)?(l.name||(l.name=q.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l,this._overrides)).range(t.length,...s)):q.generated(this.class,this.pk)||(h=t.map(((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]}))),t=await Promise.all(t.map((async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?h[e]:""+t[this.pk]),n||await f(this,r,t,a.CREATE,a.ON),t)))),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),n=y(s);if(n)throw new d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=t,n||await f(this,r,o,a.READ,a.ON),[t,...s]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${q.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map((async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,a.READ,a.ON)}))),[t,...s]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${q.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${q.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=q.merge(l,t,this.class))),n||await f(this,r,t,a.UPDATE,a.ON,l),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${q.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,n.map((t=>t.id)),n.map((t=>t.record)),...i)).map(((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const l=t.map((t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e}));let h;if(r.get("applyUpdateValidation")&&(h=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map(((t,e)=>q.merge(h[e],t,this.class))))),n||await Promise.all(t.map(((t,e)=>f(this,r,t,a.UPDATE,a.ON,h?h[e]:void 0)))),!o){const e=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+e),s=r.get("applyUpdateValidation")?await Promise.all(t.map(((t,r)=>Promise.resolve(t.hasErrors(h[r],...e))))):await Promise.resolve(t.map((t=>t.hasErrors(...e))));const n=y(s);if(n)throw new d(n)}return[t,...s,h]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,a.DELETE,a.ON)}return[t,...s]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${q.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map((async t=>f(this,r,t,a.DELETE,a.ON))))}return[t,...s]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${q.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}count(t){return this.adapter.Statement(this._overrides).count(t).from(this.class)}min(t){return this.adapter.Statement(this._overrides).min(t).from(this.class)}max(t){return this.adapter.Statement(this._overrides).max(t).from(this.class)}sum(t){return this.adapter.Statement(this._overrides).sum(t).from(this.class)}avg(t){return this.adapter.Statement(this._overrides).avg(t).from(this.class)}distinct(t){return this.adapter.Statement(this._overrides).distinct(t).from(this.class)}async query(t,e,r=se.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,Ct.QUERY,!0)).for(this.query),a=[e,r],c=this.select().where(t).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${q.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new te("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);let d;if(c.verbose(`paginating ${q.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===se.ASC?this.attr(q.pk(this.class)).gt(o):this.attr(q.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new te("PaginateBy needs a page or a bookmark");d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...u)}const h=await d.page(i,o,...u);return d.serialize(h)}async find(t,e=se.ASC,...r){if("string"!=typeof t)throw new te("Find value must be a string");const s=this.getDefaultQueryAttributes(),i=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:o}=(await this.logCtx(r,Ot.FIND,!0)).for(this.find);return n.verbose(`finding ${q.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(i).orderBy([s[0],e]).execute(...o)}async page(t,e=se.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new te("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new te("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:h}=(await this.logCtx(s,Ot.PAGE,!0)).for(this.page);u.verbose(`paging ${q.tableName(this.class)} by default attributes ${c.join(", ")}`);const p=a??10,g=c[0],f=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let y;if(o&&d.get("paginateByBookmark")){const t=q.pk(this.class),r=e===se.ASC?this.attr(t).gt(o):this.attr(t).lt(o);y=await f.select().where(l.and(r)).orderBy([g,e]).paginate(p,...h)}else{if(!n)throw new te("PaginateBy needs a page or a bookmark");y=await f.select().where(l).orderBy([g,e]).paginate(p,...h)}const m=await y.page(i,o,...h);return y.serialize(m)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${q.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${q.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.COUNT_OF,!0)).for(this.countOf);return r.verbose(`counting ${q.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.MAX_OF,!0)).for(this.maxOf);return r.verbose(`finding max of ${t} in ${q.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.MIN_OF,!0)).for(this.minOf);return r.verbose(`finding min of ${t} in ${q.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.AVG_OF,!0)).for(this.avgOf);return r.verbose(`calculating average of ${t} in ${q.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.SUM_OF,!0)).for(this.sumOf);return r.verbose(`calculating sum of ${t} in ${q.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.DISTINCT_OF,!0)).for(this.distinctOf);return r.verbose(`finding distinct values of ${t} in ${q.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.GROUP_OF,!0)).for(this.groupOf);return r.verbose(`grouping ${q.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...e){if(!Ie.statements(this,t))throw new te("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const t=q.defaultQueryAttributes(this.class);if(!t||!t.length)throw new te("No default query attributes defined for "+q.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new te("Default query value must be a string");let r;for(const s of e){const e=this.attr(s).startsWith(t);r=r?r.or(e):e}if(!r)throw new te("No default query attributes available for "+q.tableName(this.class));return r}attr(t){return re.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=this.class.name;return this.adapter.observe(this,((t,e,r,...i)=>"string"==typeof t?t===s:ut.constr(t)===ut.constr(this.class))),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.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(t,e,r,...s){if(!this.observerHandler)throw new u("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(t,e,Array.isArray(r)?r.map((t=>Zt._baseSequence.parseValue(q.sequenceFor(this.class).type,t))):Zt._baseSequence.parseValue(q.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||ut.flavourOf(t)||Zt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ie)return s;const n=e||ut.flavourOf(t)||s&&ut.get(s,Ct.ADAPTER)||Zt.currentFlavour,o=n?Zt.get(n):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=q.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r){let s=q.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof Ie)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ie?t.constructor:t,s=ut.get(r,e?ut.key(Ct.STATEMENT,e):Ct.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ie?t.constructor:t;return ut.get(r,e?ut.key(Ct.QUERY,e):Ct.QUERY)}}function Pe(t,e){if(!(e||(e=dt.flavourResolver(t instanceof q?t.constructor:t))&&e!==ht))throw new u("Could not retrieve flavour from model "+(t instanceof q?t.constructor.name:t.name));return W(Ct.INJECTABLE,e,q.tableName(t))}i([ue(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ie.prototype,"listBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"paginateBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[String,String,void 0]),n("design:returntype",Promise)],Ie.prototype,"find",null),i([ue(),n("design:type",Function),n("design:paramtypes",[String,String,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"page",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"findOneBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"findBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"countOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ee="undefined"!=typeof K&&K)?Ee:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"maxOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Se="undefined"!=typeof K&&K)?Se:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"minOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Oe="undefined"!=typeof K&&K)?Oe:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"avgOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ce="undefined"!=typeof K&&K)?Ce:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"sumOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Te="undefined"!=typeof K&&K)?Te:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"distinctOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ke="undefined"!=typeof K&&K)?ke:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"groupOf",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Ie.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ie.prototype,"unObserve",null),Zt&&(Zt._baseRepository=Ie);class $e extends t{get log(){return this.logger||(this.logger=j.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=q.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=q.get(t.toString())),!n)return;const o=Ct.ADAPTER,a=r||ut.get(n,o);try{let t=a;try{a&&Zt.get(a)}catch{const e=Zt.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ie.forModel(n,t),i instanceof Ie)return i;const r=a||ut.get(i.constructor,o)||ut.get(n,o);e.register(i,Pe(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Ie.get(n,a);if("function"==typeof e){const t=a?Zt.get(a):Zt.current;if(!t)return;return new e(t,n)}}}return i}}(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(Ne||(Ne={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(De||(De={})),(t=>{t.NONE="none",t.FULL="full"})(_e||(_e={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Be||(Be={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Re||(Re={}));const Le="tasks",Fe={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};function je(t,e){return(i,n)=>n?r(ut.constr(t))(i,n):(ut.set(b.REPOSITORY,ut.key(e||Zt.currentFlavour,q.tableName(t)),i),wt(b.REPOSITORY,i.name)(t),e=e||ut.get(i.constructor,Ct.ADAPTER),Ie.register(t,i,e),s(ut.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut.tasks=(()=>ut.innerGet(Symbol.for(Le))).bind(ut),ut.taskFor=(t=>{const e=ut.tasks();return e?e[t]:void 0}).bind(ut),ut.validationExceptions=((t,e)=>{const r=ut.get(t,Ct.NO_VALIDATE)||[],s=Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t));let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=q.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ut),ut.migrationsFor=(t=>{if(!(t=t??Zt.current))throw new u("Could not get adapter for migrations");return ut.innerGet(Symbol.for(Ct.MIGRATION),t.alias).map((t=>t.class))}).bind(ut),ut.migrations=(()=>{const t=ut.innerGet(Symbol.for([Ct.MIGRATION,Ct.BY_KEY].join("-")));return Object.values(t).flat().map((t=>[t.class.name,t.class]))}).bind(ut),ut.relations=((t,e)=>{const r=ut.get(t,Ct.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(ut),q.relations=(t,e)=>ut.relations(t instanceof q?t.constructor:t,e)||[],q.nestedRelations=((t,e=[])=>{let r=[];const s=ut.get(t,Ct.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&q.relations(i.class)){const s=q.relations(i.class).map((e=>`${t}.${e}`));e=[...e,...s],r=q.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(q),q.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!q.sequenceFor(r).generated}).bind(q),q.fromTable=(t=>{const e=ut.innerGet(Symbol.for(Ct.TABLE));if(!e||!e[t]||!q.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return q.get(e[t].name)}).bind(q),ut.createdBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(ut),ut.updatedBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(ut),q.tableName=t=>{if(!(t instanceof q?q.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ut.get(t instanceof q?t.constructor:t,Ct.TABLE)||(t instanceof q?t.constructor.name:t.name)},q.columnName=(t,e)=>ut.get(t instanceof q?t.constructor:t,ut.key(Ct.COLUMN,e))||e,q.defaultQueryAttributes=t=>{const e="function"==typeof t?t:t.constructor;return ut.get(e,ut.key(Ct.DEFAULT_QUERY_ATTR))||[q.pk(t)]},q.sequenceName=(t,...e)=>[q.tableName(t),...e].join("_"),q.sequenceFor=(t,e)=>{if(e)throw new Ft("not currently supported");const r=q.pkProps(t instanceof q?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},q.indexes=t=>{const e=ut.get(t instanceof q?t.constructor:t,Ct.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[Ct.INDEX]:e[r]},t)),{})},e.services=()=>ut.innerGet(Symbol.for(Ct.SERVICE)),e.repositories=()=>ut.innerGet(Symbol.for(b.REPOSITORY));class Ue extends u{constructor(t){super(t,Ue.name,500)}}var Me;function Ye(t,...e){return(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 a;try{a=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(a)throw a;return r.call(s,...o)}})}}function Ge(t,...e){return(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 a;try{a=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(a)throw a;return r.call(s,...o)}})}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(Me||(Me={}));const qe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},He=qe,ze={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},We=Object.assign({},ze,{type:"BigInt"});function Qe(t,e,r){return dt.for(Ct.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find((t=>![se.ASC,se.DSC].includes(t)))&&(e=t,t=void 0),gt(ut.key(`${Ct.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Ve(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=q.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,a;n=s,o=r,a=await i.next(t),Reflect.set(n,o,a)}function Je(t,e){return(r,s)=>{if(bt()(r,s),!t.type){const e=ut.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[bt(),Qe([se.ASC,se.DSC]),z(),v(),gt(ut.key(b.ID,s),t),A(Ve,t,e)];return t.generated&&i.push(x()),pt(...i)(r,s)}}function Xe(t){const e=Object.assign({},He);return delete e.generated,t=Object.assign({},e,t),dt.for(b.ID).define({decorator:Je,args:[t,{priority:60}]}).apply()}async function Ke(t,e,r,s,i){const n=e.logger.for(Ke);if(!s){const e=q.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=Ie.forModel(e,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===t[q.pk(s.class)])n.info(`No pk found in ${q.tableName(s.class)} - creating`),o=await s.create(t,e);else{n.info(`pk found in ${q.tableName(s.class)} - attempting update`);try{o=await s.update(t,e),n.info("Updated "+q.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+q.tableName(s.class)),o=await s.create(t,e)}n.info("After create update: "+o)}return o}async function Ze(t,e,r,s){const i=s[r];if(!i)return;if(or(s,e),"object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const o=Ie.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=q.pk(a);await yr(t,s,r,a[c],a),s[r]=a[c]}async function tr(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ie.CASCADE)return;if("object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}const n=await Ke(s[r],t,this.adapter.alias,void 0,this._overrides),o=q.pk(n);await yr(t,s,r,n[o],n),s[r]=n[o]}async function er(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ie.CASCADE)return;const n=vr(s,r,this.adapter.alias);let o;o=i instanceof q?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await yr(t,s,r,o[n.pk],o)}async function rr(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;or(s,e);const o=t.logger.for(rr),a=vr(s,r,this.adapter.alias),c=q.pk("function"!=typeof e.class||e.class.name?e.class:e.class()),l=new Set;for(const e of n){let i;"object"!=typeof e?(i=await a.override(this._overrides).read(e,t),o.debug("read: "+i[c])):(o.verbose("Creating or updating one-to-many model: "+e[c]),i=await Ke(e,t,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await yr(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function sr(t,e,r,s,i){const{cascade:n}=e;if(n.update===ie.CASCADE)return rr.call(this,t,e,r,s,i)}async function ir(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?Ie.forModel(o,this.adapter.alias):vr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await yr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}async function nr(t,e,r,s){const i=s[r];if(!i)return;or(s,e);const n=t.logger.for(nr);if("object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof q?e.class.constructor:e.class))throw new u("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const o=await Ke(i,t,this.adapter.alias,void 0,this._overrides),a=q.pk(o);n.info(`caching: ${JSON.stringify(o)} under ${o[a]}`),await yr(t,s,r,o[a],o),s[r]=o[a]}function or(t,e){let r;const s="function"==typeof e.class&&e.class.name?e.class:e.class(),i=ut.get(s,Ct.RELATIONS);if(i&&(r=Object.values(i)?.find((e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r}))),!0===r?.populate&&!0===e?.populate)throw new u("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function ar(t,e,r,s){const{cascade:i}=e;if(i.update===ie.CASCADE)return nr.call(this,t,e,r,s)}async function cr(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,o=n?Ie.forModel(i,this.adapter.alias):vr(s,r,this.adapter.alias),a=n?i[o.pk]:i,c=await o.override(this._overrides).delete(a);await yr(t,s,r,a,c),s[r]=a}async function lr(t,e,r,s){const i=s[r];if(!i||!i.length)return;or(s,e);const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o=t.logger.for(lr),a=new Set([...i]);if("object"!==n){const n=vr(s,r,this.adapter.alias),c=await n.override(this._overrides).readAll([...a.values()],t);for(let e=0;e<c.length;e++){const s=c[e];o.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(s)),await yr(t,s,r,[...a.values()][e],c)}return await ur.call(this,s,[...i],o,t,e),s[r]=[...a],void o.info("SET MANY TO MANY IDS: "+s[r])}const c=q.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating many-to-many model: "+JSON.stringify(e));const i=await Ke(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await yr(t,s,r,i[c],i),o.info("Creating or updating many-to-many model: "+JSON.stringify(e)),e.id=i.id,l.add(i[c])}const d=q.pk(s.constructor);if(void 0===s[d]){const e=await(async(t,e,r)=>{const s=e[q.pk(e.constructor)];if(void 0!==s)return s;const i=q.sequenceFor(e.constructor);let n;i?.name||(i.name=q.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i,t._overrides),await n.next(r)}catch(t){throw new u(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[d]=e}const h=await ur.call(this,s,i,o,t,e);o.info("Junction model created: "+h.name),s[r]=[...l]}async function ur(t,e,r,s,i){const{JunctionModel:n,fkA:o,fkB:a}=dr(t,e[0],i),c=[];for(const i of e){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(i));const e={[o]:t instanceof q?t[q.pk(t.constructor)]:t,[a]:i instanceof q?i[q.pk(i.constructor)]:i},l=await Ke(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Ie.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function dr(t,e,r){const s=q.tableName(t);let i;if(e instanceof q)i=q.tableName(e);else if(q.isModel(e)&&"function"==typeof e)i=e.name?e.name:e()?.name;else if(r?.class){const t="function"!=typeof r.class||r.class.name?r.class:r.class();i=q.tableName(t)}if(!s||!i)throw new u("Missing tablenames to create junction table");const n=r?.joinTable?.name?r?.joinTable?.name:`${s}_${i}`,o=s?.toLowerCase()+"_fk",a=i?.toLowerCase()+"_fk",c=class extends q{constructor(t){super(t)}};Object.defineProperty(c,"name",{value:n,writable:!1}),Xe({type:Number})(c.prototype,"id"),z()(c.prototype,o),z()(c.prototype,a);const l=Q()(c);return ut.set(c,Ct.TABLE,n),{fkA:o,fkB:a,JunctionModel:l}}async function hr(t,e,r,s){const{cascade:i}=e;if(i.update===ie.CASCADE)return lr.call(this,t,e,r,s)}async function pr(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?Ie.forModel(o,this.adapter.alias):vr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await yr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function gr(t,e,r){return[Ct.POPULATE,t,e,r].join(".")}function fr(t,e,r){return[Ct.TAG_FOR_DELETION,t,r].join(".")}async function yr(t,e,r,s,i){const n=gr(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function mr(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=this,l=await(async(e,r,s,i)=>{let n,l;const d=[];let h;try{h=e.get("operation")}catch(t){h=void 0}const p=h===a.READ||h===c.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=gr(r.constructor.name,s,e);try{if(l=p[n],!l)throw Error("Not found in cache")}catch(i){const n=vr(r,s);if(!n)throw new u("Could not find repo");l=await n.override(o._overrides).read(e,t)}d.push(l)}return d})(t,s,r,n?i:[i]);s[r]=n?l:l[0]}async function wr(t,e,r,s,i){if(e.cascade.update!==ie.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new u("No way to compare old model. do you have updateValidation and mergeModels enabled?");function o(t){return Array.isArray(t)?t.map(o):"object"!=typeof t?t:t[q.pk(t)]}const a=o(s[r]),c=o(i[r]);if(void 0===c||V(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(a)?a:[a]).filter(Boolean),d=(Array.isArray(c)?c:[c]).filter(Boolean).filter((t=>!l.includes(t))),h=vr(s,r);if(!h)throw new u("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${q.tableName(h.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}const br=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function vr(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=ut.get(t instanceof q?t.constructor:t,ut.key(J.REFLECT,e,J.LIST))?.clazz;if(!r)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map((t=>"function"!=typeof t||t.name?t:t()))}else s=ut.getPropDesignTypes(t instanceof q?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!br.includes((""+t.name).toLowerCase())));return Ie.forModel(i,r)}class Ar extends E{constructor(t,e=Ar.name,r=401){super(t,e,r)}}class xr extends Ar{constructor(t,e=xr.name){super(t,e,403)}}class Er extends u{constructor(t){super(t,Er.name,503)}}function Sr(t){return dt.for(Ct.TABLE).define({decorator:t=>e=>(ut.set(Ct.TABLE,t||e.name.toLowerCase(),e),wt(Ct.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function Or(t){return dt.for(Ct.COLUMN).define({decorator:t=>(e,r)=>gt(ut.key(Ct.COLUMN,r),t||r)(e,r),args:[t]}).apply()}async function Cr(t,e,r,s){if(s[r]&&(await this.select().where(re.attribute(r).eq(s[r])).execute()).length)throw new O(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Tr(){const t=Ct.UNIQUE;return dt.for(t).define(X(),C(Cr),gt(t,{})).apply()}async function kr(t,e,r,s){throw new Ar("This adapter does not support user identification")}function Nr(){return dt.for(Ct.CREATED_BY).define({decorator:()=>(t,e)=>pt(A(kr),gt(Ct.CREATED_BY,e),x(Ct.CREATED_BY))(t,e),args:[]}).apply()}function Dr(){return dt.for(Ct.UPDATED_BY).define({decorator:()=>(t,e)=>pt(k(kr),gt(Ct.UPDATED_BY,e),x(Ct.UPDATED_BY))(t,e),args:[]}).apply()}function _r(){return T([a.CREATE])}function Br(){return T()}function Rr(t){return[()=>{const e="function"==typeof t&&t.name?t:t(),r=q.pk(e);return(ut.allowedTypes(e,r)||[])[0]}]}function Ir(t,e=ne,r=!0,s,i){const n=Ct.ONE_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),Z([t,...a]),A(Ze,o,{priority:70}),k(tr,o,{priority:70}),N(er,o,{priority:70}),D(wr,o,{priority:70}),_(mr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Pr(t,e=ne,r=!0,s,i){const n=Ct.ONE_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),tt([t,...a]),A(rr,o,{priority:70}),k(sr,o,{priority:70}),N(ir,o,{priority:70}),D(wr,o,{priority:70}),_(mr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function $r(t,e=ne,r=!0,s,i){const n=Ct.MANY_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),Z([t,...a]),A(nr,o),k(ar,o),N(cr,o),_(mr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Lr(t,e=ne,r=!0,s,i){const n=Ct.MANY_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),tt([t,...a]),A(lr,o),k(sr,o),_(mr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Fr(...t){return(e,r)=>{const s=ut.get(e,ut.key(Ct.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return pt(wt(ut.key(Ct.NO_VALIDATE,r),i))(e,r)}}function jr(){return Fr(a.CREATE)}function Ur(){return Fr(a.UPDATE)}function Mr(){return Fr(a.UPDATE,a.CREATE)}function Yr(t,e){return dt.for(Ct.RELATIONS).define({decorator:(t,e)=>(r,s)=>(gt(t,e)(r,s),gt(ut.key(Ct.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class Gr extends q{constructor(t){super(t)}}i([_r(),n("design:type",Date)],Gr.prototype,"createdAt",void 0),i([Br(),n("design:type",Date)],Gr.prototype,"updatedAt",void 0);let qr=class extends Gr{constructor(t){super(t)}};i([Xe({type:String,generated:!1}),n("design:type",String)],qr.prototype,"id",void 0),i([z(),Qe(),n("design:type",Object)],qr.prototype,"current",void 0),qr=i([Sr("??sequence"),Q(),n("design:paramtypes",[Object])],qr);class Hr extends F{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(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,Ht(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Ot.FIND_BY}|${Ot.LIST_BY}|${Ot.FIND}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Ot.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[t,...r]}async pagePrepared(t,e,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!e||e instanceof It?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof It||(this._bookmark=e);const n=Ie.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o;if(a===Ot.FIND){const e=[Ot.PAGE,...c],r={limit:this.size,offset:t,bookmark:this._bookmark};e.push(r);const s=await n.statement(...e,...i);return this.apply(s)}const u=RegExp(`^${Ot.FIND_BY}|${Ot.LIST_BY}`,"gi");if(!a.match(u))throw new Ft(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,Ot.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Ot.PAGE_BY||h.length>2?p={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(p);const g=await n.statement(...h,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new ee("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ee(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,e,...r){const{ctxArgs:s}=this.adapter.logCtx([e,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...s);throw new Ft("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new B(t)}}apply(t){const e="string"==typeof t?Hr.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total||this._totalPages,this._recordCount=e.count||this._recordCount,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new B(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var zr,Wr,Qr,Vr,Jr,Xr,Kr;class Zr extends Pt{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach((t=>{R(this,t,((...e)=>this.executionPrefix(t,...e)),t.name)}))}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?Ot.PAGE_BY:Ct.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const a=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||a)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Zr)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!t)throw new te("distinct() requires a selector when not chained after count()");return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}sum(t){return this.sumSelector=t,this}avg(t){return this.avgSelector=t,this}count(t){return this.countSelector=t??null,this._inCountMode=!0,this}from(t){if(this.fromSelector="string"==typeof t?q.get(t):t,!this.fromSelector)throw new te("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t,e){return this.orderBySelectors=[this.normalizeOrderCriterion(t,e)],this}thenBy(t,e){if(Array.isArray(t)||void 0!==e){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new te("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new te("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(t),this}normalizeOrderCriterion(t,e){if(Array.isArray(t)){const[e,r]=t;return[e,this.normalizeOrderDirection(r)]}return[t,this.normalizeOrderDirection(e)]}normalizeOrderDirection(t){if(!t)throw new te("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===se.ASC)return se.ASC;if(e===se.DSC)return se.DSC;throw new te(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(se).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new te("groupBy must be called before orderBy.");return this.groupBySelectors=[t],this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const{log:e,ctx:r,ctxArgs:s}=this.logCtx(t,this.execute);try{if(this.prepared)return this.executePrepared(...t);e.silly("Building raw statement...");const i=this.build();e.silly("executing raw statement");const n=await this.raw(i,...s);if(this.hasAggregation())return n;if(!this.selectSelector){const t=q.pk(this.fromSelector),e=function(e){const s=e[t];return this.adapter.revert(e,this.fromSelector,s,void 0,r)}.bind(this);return this.groupBySelectors?.length?this.revertGroupedResults(n,e):Array.isArray(n)?n.map(e):e(n)}return n}catch(t){throw new te(t)}}revertGroupedResults(t,e){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.entries(t).reduce(((t,[r,s])=>(t[r]=this.revertGroupedResults(s,e),t)),{}):t}async executePrepared(...t){const e=Ie.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new Ft("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(this.hasAggregation())return i;if(!this.selectSelector)return i;const n=q.pk(this.fromSelector),o=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case St.AND:case St.OR:{let t=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof re){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case Et.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case Et.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case Et.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case Et.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case Et.BIGGER_EQ:n.method=r+" bigger than equal";break;case Et.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case Et.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case Et.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new te("Unsupported operator "+s)}return n}squash(t){const e=this.matchDefaultQueryCondition();if(e){const t=this.getOrderDirection();return{class:this.fromSelector,method:Ot.FIND,args:[e.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof re)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Ot.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Ot.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Ot.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Ot.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Ot.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Ot.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Ot.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 r;this.whereCondition&&(r=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,se.DSC]:[q.pk(this.fromSelector),se.DSC],[i,n]=s,o={direction:n};this.limitSelector&&(o.limit=this.limitSelector),this.offsetSelector&&(o.offset=this.offsetSelector);const a={class:this.fromSelector,method:Ot.LIST_BY,args:[i],params:o};return r&&(a.method=Ot.FIND_BY,a.args=[r,this.whereCondition.comparison],a.params=o),a}matchDefaultQueryCondition(){if(!this.whereCondition)return;const t=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!t)return;const e=q.defaultQueryAttributes(this.fromSelector);if(!e||!e.length)return;const r=Array.from(new Set(e.map(String))),s=Array.from(new Set(t.attributes.map(String)));return r.length===s.length&&r.every((t=>s.includes(t)))?{value:t.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(t){const e=this.collectStartsWithAttributes(t);if(e)return{attributes:Array.from(new Set(e.attributes)),value:e.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:e,operator:r,comparison:s}=t;if(r===Et.STARTS_WITH){if("string"!=typeof e||"string"!=typeof s)return;return{attributes:[e],value:s}}if(r===St.OR){const t=e instanceof re?this.collectStartsWithAttributes(e):void 0,r=s instanceof re?this.collectStartsWithAttributes(s):void 0;return t&&r&&t.value===r.value?{attributes:[...t.attributes,...r.attributes],value:t.value}:void 0}return r===St.AND?(e instanceof re?this.collectStartsWithAttributes(e):void 0)||(s instanceof re?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??se.ASC}async prepare(t){if(t=t||await this.adapter.context(Ct.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 e=[],r={},s={class:this.fromSelector,args:e,params:r};let i,n=xt.FIND_BY;void 0!==this.countSelector?(n=xt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=xt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=xt.AVG_BY,i=this.avgSelector):this.minSelector?(n=xt.MIN_BY,i=this.minSelector):this.maxSelector?(n=xt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=xt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=xt.GROUP_BY_PREFIX,i=this.groupBySelectors[0]);const o=[n];if(i&&o.push(i),this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);o.push(r.method),r.args&&r.args.length&&e.push(...r.args)}if(this.selectSelector&&o.push(xt.SELECT,this.selectSelector.join(` ${xt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;o.push(xt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map((([t,e])=>[t,e])),e.forEach((([t])=>{o.push(xt.THEN_BY,t)})))}if(this.groupBySelectors?.length&&n!==xt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;o.push(xt.GROUP_BY,t),e.forEach((t=>o.push(xt.THEN_BY,t)))}else this.groupBySelectors?.length&&n===xt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach((t=>o.push(xt.THEN_BY,t)));return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=M(o.join(" ")),s.params=r,this.prepared=s,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(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new te(t)}}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Zr.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(zr="undefined"!=typeof S&&S)?zr:Object]),n("design:returntype",Object)],Zr.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Wr="undefined"!=typeof S&&S)?Wr:Object]),n("design:returntype",Object)],Zr.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Qr="undefined"!=typeof S&&S)?Qr:Object]),n("design:returntype",Object)],Zr.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Vr="undefined"!=typeof S&&S)?Vr:Object]),n("design:returntype",Object)],Zr.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Jr="undefined"!=typeof S&&S)?Jr:Object]),n("design:returntype",Object)],Zr.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Xr="undefined"!=typeof S&&S)?Xr:Object]),n("design:returntype",Object)],Zr.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Zr.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[re]),n("design:returntype",Object)],Zr.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Zr.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Zr.prototype,"thenBy",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Kr="undefined"!=typeof Key&&Key)?Kr:Object]),n("design:returntype",Object)],Zr.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Zr.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Zr.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Zr.prototype,"execute",null);class ts extends Pt{constructor(t){super(),this.name=t,this.observers=[],this.Context=It}for(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof ts?n.for(t,...e):n instanceof Ie?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Lt,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("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(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${zt.instance.generate()}`;const s=e.logger||j.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Tt,e,{args:r,timestamp:new Date,operation:t,logger:s})}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}async context(t,e,...r){this.log.for(this.context).silly(`creating new context for ${t} operation with flag overrides: ${JSON.stringify(e)}`);let s=r.pop();void 0===s||s instanceof It||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return Pt.logCtx.call(this,e,s||{},r,...t.filter((t=>void 0!==t)))}static get(t){if(!t)throw new u("No name provided");const r=Mt(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof It||(t.push(r),r=void 0);const s=await ts.prototype.flags(Ct.INITIALIZATION,{},...t);r=r?new It(r).accumulate({...s,parentContext:r}):(new It).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=ts.prototype.logCtx(t,this.boot),o=e.services();for(const[t,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof es&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new u(`Failed to boot ${r.name} service:${t}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof It||(t.push(r),r=void 0);const s=await ts.prototype.flags(Ct.SHUTDOWN,{},...t);r=r?new It(r).accumulate({...s,parentContext:r}):(new It).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=ts.prototype.logCtx(t,this.shutdown),o=e.services();for(const[t,r]of Object.entries(o).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof es){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],ts.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ts.prototype,"unObserve",null);class es extends ts{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.boot);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function rs(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Gt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],es.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],es.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],es.prototype,"client",null);const ss=()=>rs(a.CREATE),is=()=>rs(a.READ),ns=()=>rs(a.UPDATE),os=()=>rs(a.DELETE);function as(t){return(e,i,n)=>{n||i?(bt()(e,i),t=t||ut.type(e.constructor,i)):t=t||e,t=Mt(t);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else ut.set(Ct.SERVICE,t,e),o.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return pt(...o)(e,i,n)}}function cs(t){const e=Ct.AUTH;return dt.for(e).define({decorator:t=>wt(e,t),args:[t]}).apply()}const ls=t=>wt(Ct.AUTH_ROLE,t);function us(t,e){const r=Ct.DECAF_ROUTE;return dt.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return pt(ft(ut.key(r,i),o))(s,i,n)},args:[]}).apply()}const ds=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class hs extends ts{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ie.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=ds(t);try{const t=ts.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=ds(e||t);try{r=hs.get(e)}catch(t){r=void 0}if(r instanceof hs)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([as(e),n("design:paramtypes",[])],o),new o}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([ss(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"create",null),i([ss(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"createAll",null),i([os(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"delete",null),i([os(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"deleteAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"read",null),i([is(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"readAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],hs.prototype,"query",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"update",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],hs.prototype,"updateAll",null);class ps extends Pt{constructor(){super()}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:e}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach((t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...o),h=[c,i(t),l];return a.get("observeFullResult")&&h.push(Array.isArray(d)?d.map((t=>c(t))):c(d)),this.updateObservers(...h,...o).catch((e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`))),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)}))}async close(...t){}observe(t){if(!(t instanceof Zt))throw new Ft("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=Zt.models(this.adapter.alias),this.initialize().then((()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))),()=>this.unObserve(t)}unObserve(t){if(this.adapter!==t)throw new Ft("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){if(!t)throw new u("Model must be provided for observer update");const i=t&&"string"==typeof t?t:q.tableName(t),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new u("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function gs(t,e,r,s){if(t.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=e;i&&"function"==typeof i&&(i=i(s,...n||[],t)),s[r]=await zt.instance.generate(i)}function fs(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=Ct.UUID;return dt.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[z(),x(Ct.UUID),A(gs,s,{priority:54})];return t&&i.push(k(gs,s,{priority:54})),t||i.push(v()),pt(...i)},args:[t,e,...r]}).apply()}Zt&&(Zt._baseDispatch=ps);class ys extends Pt{static{this.lock=new ct}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ie.forModel(qr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,a.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new u("Sequence name is required");return ys.lock.execute((async()=>{const e=t||n;if(e%n!=0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new qr({id:o,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${t}`),this.repo.create(new qr({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(zt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${o} current=${c} next=${t}`),e.current}catch(t){if(t instanceof O)continue;throw t}}const d=await(async t=>{switch(a){case Number.name:return this.parse(t)+e;case BigInt.name:return this.parse(t)+BigInt(e);case String.name:return this.parse(t);case"serial":return await Promise.resolve(Wt.instance.generate(t));default:throw new u("Should never happen")}})(c),h=await l(d);return r.debug(`Sequence.increment ${o} current=${c} next=${d}`),h.current}),o)}async next(...t){const{ctx:e}=(await this.logCtx(t,a.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ft(`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(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(o-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return ys.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([qr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return q.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new Ft(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function ms(t,...e){let r;if(t instanceof hs&&(r=t.repo.adapter),t instanceof Ie&&(r=t.adapter),t instanceof Zt&&(r=t),!r)throw new u("Could not find adapter to extract transaction");return r.transactionLock(...e)}function ws(t,...e){return new Vt(ms(t,...e))}Zt._baseSequence=ys,dt.for(lt.TRANSACTIONAL).define({decorator:(...t)=>(e,r,s)=>{if(!s)throw new u("This decorator only applies to methods");return vt()(e,r,s),ut.set(e.constructor,ut.key(lt.TRANSACTIONAL,r),{data:t}),s.value=new Proxy(s.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock")||ws(e);let o;i.put("transactionLock",n),await n.acquire();try{o=await t.call(e,...r,i)}catch(t){try{await n.rollback(t)}catch(t){s.error("Failed to rollback transaction",t)}throw t}try{await n.release()}catch(t){throw new u("Failed to release transaction: "+t)}return o}}),s}}).apply();class bs extends es{constructor(){super()}for(t,...e){throw new Ft("Persistence service cannot be overridden")}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof It||!e.every((t=>Array.isArray(t))))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize),i=e.map((([t,e,...s])=>{try{r.silly(`Initializing ${t.name} with config: ${JSON.stringify(e)}`);const i=new t(e,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(e){throw new u(`Failed to initialize ${t.name}: ${e}`)}}));for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let vs=class extends q{constructor(t){super(t),this.strategy=De.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=_e.FULL}};i([z(),Z(String),et(De),At("the backoff strategy"),n("design:type",String)],vs.prototype,"strategy",void 0),i([z(),At("base interval between attempts"),n("design:type",Number)],vs.prototype,"baseMs",void 0),i([z(),At("max interval"),n("design:type",Number)],vs.prototype,"maxMs",void 0),i([Z(String),et(_e),At("optional jitter strategy"),n("design:type",String)],vs.prototype,"jitter",void 0),vs=i([Q(),n("design:paramtypes",[Object])],vs);let As=class extends q{constructor(t){super(t)}};i([z(),At("The error message"),n("design:type",String)],As.prototype,"message",void 0),i([bt(),At("The error stack"),n("design:type",String)],As.prototype,"stack",void 0),i([bt(),At("The error code"),n("design:type",String)],As.prototype,"code",void 0),i([bt(),At("The error details"),n("design:type",Object)],As.prototype,"details",void 0),As=i([Q(),n("design:paramtypes",[Object])],As);let xs=class extends q{constructor(t){super(t),this.ts=new Date}};i([Xe(),I(["taskId","classification","uuid"],":"),n("design:type",String)],xs.prototype,"id",void 0),i([Or(),v(),z(),P(),fs(!1),n("design:type",String)],xs.prototype,"uuid",void 0),i([Or(),v(),z(),Qe([se.ASC,se.DSC]),n("design:type",String)],xs.prototype,"taskId",void 0),i([rt(),Or(),z(),Qe([se.ASC,se.DSC]),n("design:type",Date)],xs.prototype,"ts",void 0),i([Or(),v(),z(),et(Be),Qe([se.ASC,se.DSC]),n("design:type",String)],xs.prototype,"classification",void 0),i([bt(),Or(),$(),v(),n("design:type",Object)],xs.prototype,"payload",void 0),xs=i([Sr("task_event"),Q(),n("design:paramtypes",[Object])],xs);class Es extends st{constructor(){super()}preSerialize(t,...e){return this.serializeValue(t,...e)}deserialize(t,...e){const r=JSON.parse(t);return this.rebuildValue(r)}serializeValue(t,...e){if(null==t)return t;if("object"!=typeof t)return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.map((t=>this.serializeValue(t,...e)));if(t instanceof re){const r=this.serializePlain(t,...e);return r[it.ANCHOR]="??condition",r}return q.isModel(t)?this.serializeModel(t,...e):this.serializePlain(t,...e)}serializeModel(t,...e){const r=this.serializePlain(t,...e),s=this.getMetadata(t.constructor)??t.constructor?.name;return s&&(r[it.ANCHOR]=s),r}serializePlain(t,...e){const r={};for(const[s,i]of Object.entries(t))r[s]=this.serializeValue(i,...e);return r}getMetadata(t){try{return ut.modelName(t)}catch{return}}rebuildValue(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map((t=>this.rebuildValue(t)));const e=t[it.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?re.from(r):q.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==it.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Ss=class extends q{constructor(t){super(t),this.ts=new Date}};i([rt(),z(),n("design:type",Date)],Ss.prototype,"ts",void 0),i([z(),et(Y),n("design:type",String)],Ss.prototype,"level",void 0),i([z(),bt(),n("design:type",String)],Ss.prototype,"msg",void 0),i([bt(),n("design:type",Object)],Ss.prototype,"meta",void 0),Ss=i([Q(),n("design:paramtypes",[Object])],Ss);let Os=class extends q{constructor(t){super(t),this.atomicity=Re.ATOMIC,this.status=Ne.PENDING,this.attempt=0,this.logTail=[]}};i([Xe(),fs(),At("the task id"),n("design:type",String)],Os.prototype,"id",void 0),i([Or(),z(),Z(String),et(Re),Qe([se.ASC,se.DSC]),At("defines a single or composite task"),n("design:type",String)],Os.prototype,"atomicity",void 0),i([Or(),z(),Qe([se.ASC,se.DSC]),At("Holds task classification - must match @task()"),n("design:type",String)],Os.prototype,"classification",void 0),i([Or(),bt(),Qe([se.ASC,se.DSC]),At("optional task name for ambiguity"),n("design:type",String)],Os.prototype,"name",void 0),i([Or(),z(),Z(String),et(Ne),Qe([se.ASC,se.DSC]),At("Holds the task current status"),n("design:type",String)],Os.prototype,"status",void 0),i([bt(),Or(),$(Es),At("Holds task input"),n("design:type",Object)],Os.prototype,"input",void 0),i([bt(),Or(),$(Es),At("Holds the task output when successfully completed"),n("design:type",Object)],Os.prototype,"output",void 0),i([bt(),Or(),$(),At("Holds the error for failed tasks"),n("design:type",As)],Os.prototype,"error",void 0),i([Or(),z(),nt(0),Qe([se.ASC,se.DSC]),At("Holds the current attempt"),n("design:type",Number)],Os.prototype,"attempt",void 0),i([Or(),nt(1),z(),At("max attempts for the task"),n("design:type",Number)],Os.prototype,"maxAttempts",void 0),i([Or(),z(),$(),At("backoff configuration"),n("design:type",vs)],Os.prototype,"backoff",void 0),i([rt(),Or(),At("Next execution timestamp"),n("design:type",Date)],Os.prototype,"nextRunAt",void 0),i([rt(),Or(),At("Task scheduled timestamp"),n("design:type",Date)],Os.prototype,"scheduledTo",void 0),i([bt(),Or(),At("Task lease owner identifier"),n("design:type",String)],Os.prototype,"leaseOwner",void 0),i([rt(),Or(),At("Task lease expiration timestamp"),n("design:type",Date)],Os.prototype,"leaseExpiry",void 0),i([bt(),Or(),$(),At("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Os.prototype,"steps",void 0),i([bt(),Or(),nt(0),Qe([se.ASC,se.DSC]),At("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Os.prototype,"currentStep",void 0),i([bt(),Or(),$(),At("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Os.prototype,"stepResults",void 0),i([bt(),Or(),$(),At("Holds the task log entries"),n("design:type",Array)],Os.prototype,"logTail",void 0),i([Or(),_r(),Qe([se.ASC,se.DSC]),At("timestamp of creation"),n("design:type",Date)],Os.prototype,"createdAt",void 0),i([Or(),Br(),Qe([se.ASC,se.DSC]),At("timestamp of last update"),n("design:type",Date)],Os.prototype,"updatedAt",void 0),i([Or(),Nr(),Qe([se.ASC,se.DSC]),At("Holds the creator of the task"),n("design:type",String)],Os.prototype,"createdBy",void 0),i([Or(),Dr(),Qe([se.ASC,se.DSC]),At("Holds the creator of the task"),n("design:type",String)],Os.prototype,"updatedBy",void 0),Os=i([At("Holds the current step when applicable"),Sr("tasks"),Q(),n("design:paramtypes",[Object])],Os);let Cs=class extends q{constructor(t){super(t)}};i([z(),At("The status of a step"),n("design:type",String)],Cs.prototype,"status",void 0),i([bt(),At("The result of a successful step"),n("design:type",Object)],Cs.prototype,"output",void 0),i([bt(),At("the error of a failed step"),n("design:type",As)],Cs.prototype,"error",void 0),Cs=i([Q(),n("design:paramtypes",[Object])],Cs);let Ts=class extends q{constructor(t){super(t)}};i([z(),bt(),At("task handler type"),n("design:type",String)],Ts.prototype,"classification",void 0),i([At("optional task step input"),bt(),n("design:type",Object)],Ts.prototype,"input",void 0),Ts=i([Q(),n("design:paramtypes",[Object])],Ts);class ks extends q{constructor(t){super(t),this.baseMs=1e3,this.jitter=_e.FULL,this.maxMs=6e4,this.strategy=De.EXPONENTIAL,q.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new d(t);return new vs(this)}}i([z(),nt(1e3),n("design:type",Number)],ks.prototype,"baseMs",void 0),i([z(),et(_e),n("design:type",String)],ks.prototype,"jitter",void 0),i([ot("baseMs"),nt(1e3),z(),n("design:type",Number)],ks.prototype,"maxMs",void 0),i([z(),et(De),n("design:type",String)],ks.prototype,"strategy",void 0);class Ns extends q{setClassification(t){return this.classification=t,this}setName(t){return this.name=t,this}setAtomicity(t){return this.atomicity=t,this}setBackoff(t){if(t)return this.backoff=t,this;const e=new ks,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=Ne.PENDING,this.atomicity=Re.ATOMIC,this.backoff=new vs,this.maxAttempts=1,q.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Os(this)}}i([z(),n("design:type",String)],Ns.prototype,"classification",void 0),i([bt(),n("design:type",String)],Ns.prototype,"name",void 0),i([z(),n("design:type",String)],Ns.prototype,"status",void 0),i([z(),n("design:type",String)],Ns.prototype,"atomicity",void 0),i([z(),n("design:type",vs)],Ns.prototype,"backoff",void 0),i([bt(),n("design:type",Object)],Ns.prototype,"input",void 0),i([nt(1),z(),n("design:type",Number)],Ns.prototype,"maxAttempts",void 0);class Ds extends Ns{constructor(t){super(t),this.stepResults=[],q.fromModel(this,t),this.atomicity=Re.COMPOSITE}setAtomicity(t){throw new u("Atomicity locked to "+Re.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map((t=>t instanceof Ts?t:new Ts(t))),this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Ts({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([tt((()=>Ts)),n("design:type",Array)],Ds.prototype,"steps",void 0);class _s extends $t{get type(){if(!this._type){const t=ut.get(this.constructor,Le);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),p(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function Bs(t){return dt.for(Le).define({decorator:t=>e=>{const r={type:t};return ut.set(Le,t,e),wt(Le,r)(e)},args:[t]}).apply()}let Rs=class extends _s{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof re)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=re.attr("status").eq(Ne.SUCCEEDED).and(re.attr("updatedAt").lte(t.successfulExpiry)),i=re.attr("status").eq(Ne.FAILED).and(re.attr("updatedAt").lte(t.failedExpiry)),n=re.attr("status").eq(Ne.CANCELED).and(re.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map((t=>t.id)),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([je(Os),n("design:type",Object)],Rs.prototype,"tasks",void 0),Rs=i([Bs("cleanup-task"),n("design:paramtypes",[])],Rs);class Is{constructor(t,e=150,r=300,s){this.logger=t,this.bufferSize=e,this.maxBufferSize=r,this.pipe=s,this.history=[],this.root=this.logger.root,Object.values(Y).forEach((t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})}))}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch((t=>this.logger.error("Failed to pipe logs",t))).finally((()=>this.history=[])):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Ps(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1,timestamp:!1,logLevel:!1}),r.classification){case Be.LOG:{let s=r.payload;s=s.map((t=>Array.isArray(t)?t:[t.level,t.ts+" - "+t.message,t.meta]));for(let[r,i,n]of s){e.style||(i=G(i),i=i.clear().toString());const s=[i];r===Y.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case Be.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Be.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=G(e);switch(e){case Ne.SUCCEEDED:s=s.green.bold;break;case Ne.RUNNING:s=s.blue.bold;break;case Ne.PENDING:s=s.yellow;break;case Ne.WAITING_RETRY:s=s.yellow.bold;break;case Ne.FAILED:s=s.red.bold;break;case Ne.CANCELED:s=s.magenta.bold;break;case Ne.SCHEDULED:s=s.cyan;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}function $s(t,e){const r=e.strategy===De.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===_e.FULL?Math.floor(Math.random()*s):s}function Ls(t){return new As({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Fs(t){return new Promise((e=>setTimeout(e,t)))}class js extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=js.name,Object.setPrototypeOf(this,js.prototype)}}class Us extends It{get taskId(){return this.get("taskId")}get logger(){return super.logger}get pipe(){return this.get("pipe")}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(t,e){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[t]=e,this.cache.put("resultCache",r)}changeState(t,e){throw new js({status:t,...e})}cancel(t,e){this.changeState(Ne.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(Ne.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(Ne.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof As?t:t instanceof Error?Ls(t):new As({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class Ms{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ut.tasks();t&&Object.entries(t).forEach((([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)}))}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class Ys extends Lt{constructor(){super(...arguments),this.listeners=new Set}observe(t,e){return super.observe(t,e)}unObserve(t){super.unObserve(t)}emit(t,e){this.updateObservers(xs,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=Zt.logCtx(this.updateObservers,void 0,!1,...i);(await Promise.allSettled(this.observers.filter((s=>{const{filter:i}=s;if(!i)return!0;try{return i(t,e,r,...o)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((t=>{t.observer.refresh(s,...o)})))).forEach(((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}function Gs(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class qs extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class Hs extends qs{constructor(t,e,r){super(Hs.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class zs extends qs{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(zs.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class Ws extends qs{constructor(t,e,r){super(Ws.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class Qs extends qs{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(Qs.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class Vs{constructor(t,e){this.bus=t,this.task=e,this.resolved=!1,this.unregistration=t.observe(this,((t,e,r,...s)=>r.startsWith(this.task.id)&&(t===xs||t===q.tableName(xs)))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([Ne.SUCCEEDED,Ne.FAILED,Ne.CANCELED,Ne.SCHEDULED])}wait(){return this.awaitStatusTerminal([Ne.SUCCEEDED,Ne.FAILED,Ne.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Ps(t,e))}logs(t){this.pipe((async e=>{if(e.classification!==Be.LOG)return;const r=(e.payload??[]).map((t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]));await t(r)}),Be.LOG)}pipe(t,e=Be.ALL){this.pipes=this.pipes||{},this.pipes[e]=this.pipes[e]||new Set,this.pipes[e].add(t)}succeed(t){this.complete()}fail(t){this.complete()}cancel(t){t.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(Ne.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(Ne.FAILED,t)}onCancel(t){return this.registerStatusHandler(Ne.CANCELED,t)}awaitStatusTerminal(t){return new Promise(((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===Ne.SUCCEEDED?e(this.extractOutput(t)):r(this.extractError(t))}catch(t){r(t)}}};t.forEach((t=>{const e=this.registerStatusHandler(t,n);s.push(e)}))}))}extractOutput(t){return void 0!==t.payload?.output?t.payload.output:this.task.output}extractError(t){const e=t.payload?.status??this.task.status,r=this.getNextAction(e),s=t.payload?.originalError;if(s instanceof Error)return this.assignNextAction(s,r);const i=this.buildMeta(e,t.payload),n=this.createTaskControlError(e,t.payload?.error??this.task.error,i);return this.assignNextAction(n,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[Ne.SUCCEEDED,Ne.CANCELED,Ne.FAILED].includes(t)}async track(t,e){if(!t.payload)return;const r=t.payload.status;this.task.status=r,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),r!==Ne.SUCCEEDED?(r===Ne.FAILED&&this.fail(),r===Ne.CANCELED&&this.cancel(t),r===Ne.WAITING_RETRY&&this.retry(),r===Ne.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,e){const r=async(r,s)=>{r.payload?.status===t&&await e(r,s)};if(this.pipe(r,Be.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Be.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new It),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===Ne.SUCCEEDED&&(e.output=this.task.output),t!==Ne.FAILED&&t!==Ne.CANCELED||!this.task.error||(e.error=this.task.error),this.task.nextRunAt&&(e.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(e.scheduledTo=this.task.scheduledTo),new xs({classification:Be.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case Ne.FAILED:return new Hs(this.task.id,e,r);case Ne.CANCELED:return new Ws(this.task.id,e,r);case Ne.WAITING_RETRY:return new zs(this.task.id,e,r);case Ne.SCHEDULED:return new Qs(this.task.id,e,r);default:return new Hs(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case Ne.CANCELED:return Ne.CANCELED;case Ne.WAITING_RETRY:return Ne.WAITING_RETRY;case Ne.SCHEDULED:return Ne.SCHEDULED;case Ne.FAILED:return Ne.FAILED;default:return}}buildMeta(t,e){const r={};if(e?.nextRunAt&&(r.nextRunAt=e.nextRunAt),e?.scheduledTo&&(r.scheduledTo=e.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===Ne.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,e){if(!this.pipes)return;const r=this.pipes[Be.ALL]?[...this.pipes[Be.ALL].values()]:[];r.push(...this.pipes[t.classification]?.values()||[]);for(const s of r)try{await s(t,e)}catch(r){e.logger.error(`Failed to trigger pipe ${s.name} for event ${t.classification}. discarding event`,r)}}}class Js extends $t{get Context(){return Us}get adapter(){return this.config.adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=Ie.forModel(Os,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=Ie.forModel(xs,this.config.adapter.alias)),this._events}static createTaskContext(t,e){const r=new Us(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new at,this.running=!1,this.config=Object.assign({},Fe,t,{bus:t.bus||new Ys,registry:t.registry||new Ms})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.CREATE,!0)).for(this.push);i.verbose("pushing task "+t.classification);const n=await this.tasks.create(t,s);return i.info(`${t.classification} task registered under ${n.id}`),e?{task:n,tracker:new Vs(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=Ne.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,e,...r)}}}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.READ,!0)).for(this.track);s.verbose("tracking task "+t);let i=await this.tasks.read(t,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${t}`),{task:i,tracker:new Vs(this.bus,i)}}async ensureTaskError(t,e){if(![Ne.FAILED,Ne.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await Fs(20);try{const t=await this.tasks.read(r.id,e);if(t.error)return t;r=t}catch{break}}return r}async cancel(t,...e){const{ctx:r}=(await this.logCtx(e,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,r);if(s.status===Ne.SUCCEEDED||s.status===Ne.FAILED)return s;s.status=Ne.CANCELED;const i=new As({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,r);return await this.emitStatus(r,n,Ne.CANCELED,i),n}async isRunning(){await this.lock.acquire();const t=this.running;return this.lock.release(),t}async start(...t){const{ctx:e}=(await this.logCtx(t,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||r.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(re.attr("status").eq(Ne.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise(((t,n)=>{const o=setTimeout((()=>{r.error(`Graceful shutdown interrupted after ${i} ms...`),t()}),i);Promise.allSettled(s.map((({id:t})=>new Promise(((r,s)=>{this.track(t,e).then((({tracker:t})=>{t.resolve().then(r)})).catch(s)}))))).then((e=>{clearTimeout(o),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()})).catch((t=>{clearTimeout(o),n(t)}))}))}async loop(...t){const{ctx:e}=this.logCtx(t,this.loop);for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map((t=>this.executeClaimed(t)))),await Fs(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=re.attribute("status").eq(Ne.PENDING),i=re.attribute("status").eq(Ne.WAITING_RETRY).and(re.attribute("nextRunAt").lte(r)),n=re.attribute("status").eq(Ne.RUNNING).and(re.attribute("leaseExpiry").lte(r)),o=re.attribute("status").eq(Ne.SCHEDULED).and(re.attribute("scheduledTo").lte(r)),a=s.or(i).or(n).or(o),c=await this.tasks.select().where(a).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+c.length);const l=[];for(const e of c){const r=await this.tryClaim(e,t);if(r&&l.push(r),l.length>=this.config.concurrency)break}return e.verbose("claimBatch claimed:"+l.length),l}async tryClaim(t,e){const r=e.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,e)}catch{}const n=new Os({...i,status:Ne.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=new Us(e).accumulate({taskId:t.id,logger:new Is(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(s,t,e);await this.emitLog(s,t.id,r)},flush:async()=>s.logger.flush(s.pipe),progress:async e=>{await this.emitProgress(s,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{}}}});await this.emitStatus(s,t,Ne.RUNNING);try{let e;if(t.atomicity===Re.COMPOSITE){e=await this.runComposite(t,s);try{t=await this.tasks.read(t.id,s)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const i=this.registry.get(t.classification);if(r.debug(`handler type for ${t.id} is ${i?.constructor?.name??"none"}`),!i)throw new u("No task handler registered for type: "+t.classification);e=await i.run(t.input,s),r.verbose("handler finished for "+t.id)}t.status=Ne.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),s.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,Ne.SUCCEEDED,e)}catch(e){try{t=await this.tasks.read(t.id,s)}catch{}if(e instanceof js)return void await this.handleTaskStateChange(e.request,t,s);if(r.error("task execution error",e),t.atomicity===Re.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex((t=>t.status===Ne.FAILED));0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=Ls(e);if(i<t.maxAttempts){const o=$s(i,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+o);t.attempt=i,t.status=Ne.WAITING_RETRY,t.nextRunAt=a,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await s.pipe(Y.warn,"Retry scheduled",{nextRunAt:a,delayMs:o,attempt:i}),await this.emitStatus(s,t,Ne.WAITING_RETRY,n,e)}else t.attempt=i,t.status=Ne.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await s.pipe(Y.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(s,t,Ne.FAILED,n,e)}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case Ne.CANCELED:{const s=t.error??new As({message:`Task ${e.id} canceled`});return e.status=Ne.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.CANCELED,s),void await r.pipe(Y.warn,"Task canceled via context")}case Ne.WAITING_RETRY:{const s=(e.attempt??0)+1,i=$s(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new As({message:`Task ${e.id} requested retry`});return e.status=Ne.WAITING_RETRY,e.attempt=s,e.error=o,e.nextRunAt=n,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.WAITING_RETRY,o),void await r.pipe(Y.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case Ne.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new As({message:`Task ${e.id} rescheduled`});return e.status=Ne.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.SCHEDULED,s),void await r.pipe(Y.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new u("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),o=(t,s)=>{e.cacheResult(t,s),r instanceof Us&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===Ne.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;o(i.classification,r.output),o(n,r.output)}}for(;i<s.length;){const r=s[i],a=this.registry.get(r.classification);if(!a)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([Y.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await a.run(r.input,e),l=i,u=new Date;n[l]=new Cs({status:Ne.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;o(r.classification,c),o(d,c),i=l+1,t.stepResults=n,t.currentStep=i,t=await this.tasks.update(t),await this.emitProgress(e,t.id,{currentStep:i,totalSteps:s.length,output:c})}catch(e){const r=new Date;throw n[i]=new Cs({status:Ne.FAILED,error:Ls(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=Ls(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof vs)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new vs(e)}normalizeSteps(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map((t=>{if(t instanceof Ts)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Ts(e)})):[]}normalizeStepResults(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map((t=>{if(t instanceof Cs)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Cs(e)})):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map((([t,e,r])=>new Ss({level:t,msg:e,meta:r}))),i=[...e.logTail??[],...s].slice(-this.config.logTailMax);e.logTail=i;try{return[await this.tasks.update(e,t),s]}catch{return[e,[]]}}async emitStatus(t,e,r,s,i){t instanceof Us&&await t.flush();const n={status:r};s&&s instanceof As?n.error=s:s&&(n.output=s),e.nextRunAt&&(n.nextRunAt=e.nextRunAt),e.scheduledTo&&(n.scheduledTo=e.scheduledTo);const o=await this.persistEvent(t,e.id,Be.STATUS,n),a=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new xs({...o,payload:a});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Be.LOG,r.map((t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta}))));this.bus.emit(s,t)}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,Be.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new xs({taskId:e,classification:r,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,e,...r){return this.adapter.context(t,e,Os,...r)}}class Xs extends es{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof It)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new(e.engine||Js)(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.CREATE,!0)).for(this.push),i=await this.client.push(t,e,...s);return await this.client.isRunning()||this.client.start(),i}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.create),s=await this.repo.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){throw new Ft("Updates to tasks are not available")}async updateAll(t,...e){throw new Ft("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}async shutdown(...t){const{ctxArgs:e,ctx:r,log:s}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...e),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(r),s.verbose("gracefully shutdown task runner")}}function Ks(t={count:1},e=0){return function r(s,i,n){return pt(ft(ut.key(Ct.THROTTLE,i),t),((s,i,n)=>{n.value=new Proxy(n.value,{async apply(s,n,o){const a=o,c=(()=>{try{return"function"==typeof t?t(...a):t}catch(t){throw new u("Failed to obtain throttling configuration from handler: "+t)}})(),{log:l,ctx:d}=(await n.logCtx(o,Ct.THROTTLE,!0)).for(r),h=(t=>{const e=(Array.isArray(t)?t:[t]).map((t=>{if(!Number.isFinite(t)||0>t)throw new u("@throttling() argument indexes must be non-negative integers");return t}));return Array.from(new Set(e)).sort(((t,e)=>t-e))})(e);if(!h.length)throw new u("@throttling() expects at least one argument index to throttle");h.forEach((t=>{if(t>=a.length)throw new u(`@throttling() requires argument index ${t} but only ${a.length} provided`);if(!Array.isArray(a[t]))throw new u(`@throttling() expects argument at index ${t} to be an array`)}));const p=h.map((t=>a[t])),g=p[0].length;if(!p.every((t=>t.length===g)))throw new u("@throttling() requires all targeted arguments to have the same length");if(0===g)return s.apply(n,a);const f=((t,e,r)=>{if("count"in r){if(0>=r.count)throw new u("@throttling() configuration 'count' must be greater than zero");const e=[];for(let s=0;t>s;s+=r.count)e.push({start:s,end:Math.min(t,s+r.count)});return e}if("bufferSize"in r){if(0>=r.bufferSize)throw new u("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let o=0;t>o;o++){const t=Zs(e,o);n>0&&n+t>r.bufferSize?(s.push({start:i,end:o}),i=o,n=t):n+=t}return i>=t&&s.length||s.push({start:i,end:t}),s}return[{start:0,end:t}]})(g,p,c),y=f.map((({start:t,end:e})=>a.map(((r,s)=>{const i=h.indexOf(s);return-1===i?r:p[i].slice(t,e)})))),m=d.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const t of y){try{v=await s.apply(n,t),A=w,Array.isArray(v)?A.push(...v):void 0!==v&&A.push(v)}catch(t){if(m)throw t;b.push(t)}c.delayMs&&await new Promise((t=>setTimeout(t,c.delayMs)))}var v,A;if(b.length){l.warn(`${i+""} throttled execution continued with ${b.length} failure(s)`);const t=new AggregateError(b,`Throttled ${i+""} failed for ${b.length} chunk(s)`);throw t.results=w,t}return w}})}))(s,i,n)}}function Zs(t,e){return t.reduce(((t,r)=>t+(t=>{if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}})(r[e])),0)}i([je(Os),n("design:type",Object)],Xs.prototype,"repo",void 0),i([ss(),n("design:type",Function),n("design:paramtypes",[Os,void 0]),n("design:returntype",Promise)],Xs.prototype,"create",null),i([ss(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"createAll",null),i([os(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Xs.prototype,"delete",null),i([os(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"deleteAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Xs.prototype,"read",null),i([is(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"readAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],Xs.prototype,"query",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Os,void 0]),n("design:returntype",Promise)],Xs.prototype,"update",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"updateAll",null),e.setRegistry(new $e);const ti="##VERSION##",ei="##PACKAGE##";ut.registerLibrary(ei,ti);export{$t as AbsContextual,Zt as Adapter,Qt as AdapterTransaction,Me as AuthKeys,Ar as AuthorizationError,De as BackoffStrategy,Gr as BaseModel,We as BigIntSequence,ie as Cascade,Rs as CleanUpTask,es as ClientBasedService,Ds as CompositeTaskBuilder,re as Condition,Er as ConnectionError,It as Context,Vt as ContextLock,Pt as ContextualLoggedClass,kt as DefaultAdapterFlags,ne as DefaultCascade,Tt as DefaultContextFlags,Ae as DefaultRepositoryFilters,He as DefaultSequenceOptions,Fe as DefaultTaskEngineConfig,ps as Dispatch,xr as ForbiddenError,St as GroupOperator,$e as InjectablesRegistry,_e as JitterStrategy,ce as MethodQueryBuilder,jt as MigrationError,Ut as MigrationRuleError,hs as ModelService,Bt as MultipleSelectOperationKeys,Dt as NonTransactionOperationKeys,qe as NoneSequenceOptions,ze as NumericSequence,Ue as ObserverError,Lt as ObserverHandler,Et as Operator,oe as OperatorsMap,se as OrderDirection,ei as PACKAGE_NAME,Rt as PaginationOperationKeys,Hr as Paginator,ee as PagingError,Ct as PersistenceKeys,bs as PersistenceService,Ot as PreparedStatementKeys,xt as QueryClause,te as QueryError,Ie as Repository,_t as SelectOperationKeys,ys as Sequence,qr as SequenceModel,Wt as Serial,ts as Service,Zr as Statement,ks as TaskBackoffBuilder,vs as TaskBackoffModel,Ns as TaskBuilder,Ws as TaskCancelError,Us as TaskContext,qs as TaskControlError,Js as TaskEngine,As as TaskErrorModel,Ys as TaskEventBus,xs as TaskEventModel,Be as TaskEventType,Hs as TaskFailError,_s as TaskHandler,Ms as TaskHandlerRegistry,Es as TaskIOSerializer,Ss as TaskLogEntryModel,Is as TaskLogger,Os as TaskModel,Qs as TaskRescheduleError,zs as TaskRetryError,Xs as TaskService,Ne as TaskStatus,Cs as TaskStepResultModel,Ts as TaskStepSpecModel,Vs as TaskTracker,Re as TaskType,Le as TasksKey,Nt as TransactionOperationKeys,zt as UUID,Ft as UnsupportedError,ti as VERSION,Ye as allowIf,he as applyViewDecorator,cs as auth,Ge as blockIf,yr as cacheModelForPopulate,wr as cascadeDelete,Or as column,$s as computeBackoffMs,ss as create,Ke as createOrUpdate,_r as createdAt,Nr as createdBy,kr as createdByOnCreateUpdate,le as defaultQueryAttr,os as del,Pe as generateInjectableNameForRepository,ms as getAdapterTransaction,dr as getAndConstructJunctionTable,ws as getContextLock,xe as getFilters,Ps as getLogPipe,Rr as getPkTypes,gr as getPopulateKey,fr as getTagForDeleteKey,Qe as index,Mt as injectableServiceKey,Gt as isOperationBlocked,Gs as isTaskError,Lr as manyToMany,lr as manyToManyOnCreate,pr as manyToManyOnDelete,hr as manyToManyOnUpdate,$r as manyToOne,nr as manyToOneOnCreate,cr as manyToOneOnDelete,ar as manyToOneOnUpdate,Fr as noValidateOn,jr as noValidateOnCreate,Mr as noValidateOnCreateUpdate,Ur as noValidateOnUpdate,qt as normalizeImport,Pr as oneToMany,rr as oneToManyOnCreateUpdate,ir as oneToManyOnDelete,sr as oneToManyOnUpdate,Ir as oneToOne,Ze as oneToOneOnCreate,er as oneToOneOnDelete,tr as oneToOneOnUpdate,be as onlyOnBulk,ge as onlyOnCreate,ye as onlyOnDelete,ve as onlyOnFilter,we as onlyOnSingle,me as onlyOnTransactional,fe as onlyOnUpdate,Xe as pk,Je as pkDec,Ve as pkOnCreate,mr as populate,Ht as prefixMethod,ue as prepared,Yt as promiseSequence,de as query,is as read,Yr as relation,je as repository,vr as repositoryFromTypeMetadata,ls as roles,us as route,Ls as serializeError,as as service,Fs as sleep,Sr as table,Bs as task,Ks as throttle,Tr as unique,Cr as uniqueOnCreateUpdate,ns as update,Br as updatedAt,Dr as updatedBy,fs as uuid,gs as uuidCreateUpdateHandler,or as validBidirectionalRelation,pe as view};
|
|
1
|
+
import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as h,wrapMethodWithContext as p,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,readonly as v,onCreate as A,generated as x,BadRequestError as E,ConflictError as O,onCreateUpdate as C,timestamp as T,onUpdate as k,onDelete as N,afterUpdate as D,afterAny as _,SerializationError as B,prefixMethod as R,composed as I,transient as P,serialize as $,BaseError as L}from"@decaf-ts/db-decorators";import{LoggedClass as F,Logging as j,final as U,toCamelCase as M,LogLevel as Y,style as G}from"@decaf-ts/logging";import{Model as q,hashObj as H,required as z,sf as W,model as Q,isEqual as V,ValidationKeys as J,async as X,type as Z,list as tt,option as et,date as rt,JSONSerializer as st,ModelKeys as it,min as nt,gt as ot}from"@decaf-ts/decorator-validation";import{Lock as at,MultiLock as ct,TransactionalKeys as lt}from"@decaf-ts/transactional-decorators";import{Metadata as ut,Decoration as dt,DefaultFlavour as ht,apply as pt,propMetadata as gt,methodMetadata as ft,DecorationKeys as yt,uses as mt,metadata as wt,prop as bt,method as vt,description as At}from"@decaf-ts/decoration";var xt,Et,St,Ot,Ct;(t=>{t.FIND_BY="findBy",t.PAGE_BY="pageBy",t.COUNT_BY="countBy",t.SUM_BY="sumBy",t.AVG_BY="avgBy",t.MIN_BY="minBy",t.MAX_BY="maxBy",t.DISTINCT_BY="distinctBy",t.GROUP_BY_PREFIX="groupBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(xt||(xt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.STARTS_WITH="STARTS_WITH",t.ENDS_WITH="ENDS_WITH",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(Et||(Et={})),(t=>{t.AND="AND",t.OR="OR"})(St||(St={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ot||(Ot={})),(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute",t.THROTTLE="throttle",t.DEFAULT_QUERY_ATTR="default-query-attr"})(Ct||(Ct={}));const Tt=Object.assign({},{ignoreDevSafeGuards:!1}),kt=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),Nt=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Dt=[a.READ,c.READ_ALL],_t=[Ct.STATEMENT,Ot.FIND_ONE_BY],Bt=[Ct.QUERY,Ot.PAGE_BY,Ot.LIST_BY,Ot.FIND_BY,Ot.FIND,Ot.PAGE],Rt=[Ot.PAGE_BY,Ot.PAGE];class It extends l{constructor(t){super(t)}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter((t=>!e.has(t))),s.length)){const r=s.map((r=>r.getFromChildren(t,e))).reduce(((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t)),[]).filter((t=>null!=t));if(!r.length)return;return r.some((t=>"object"!=typeof t))?r[0]:r.reduce(((t,e)=>Object.assign(t,e)),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce(((t,e)=>(t[e]=this.get(e),t)),{})}accumulate(t){return super.accumulate(t)}}class Pt extends F{logCtx(t,e,r=!1,s){return Pt.logCtx.call(this,e,s||{},r,...t.filter((t=>void 0!==t)))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||j.get();return e.log=t.context?s.clear().for(t):s.for(t),"string"==typeof r?e.for=t=>Object.assign(e,{log:e.log.for(t)}):e.log=e.log.for(r),e};let n=s.pop();const o=n instanceof It;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new u("No context provided");if(o&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then((e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t)))}}class $t extends Pt{constructor(){super(),this._Context=It}get Context(){return this._Context}async context(t,e,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof t?t:t.name} operation with flag overrides: ${Object.keys(e)}`);let s=r.pop();return s instanceof It||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(e):new this.Context(s).accumulate(e)}}class Lt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map((t=>t.observer)).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map((t=>t.observer)).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=Pt.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter((s=>{const{filter:o}=s;if(!o)return!0;try{return o(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((s=>{s.observer.refresh(t,e,r,...n)})))).forEach(((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}class Ft extends u{constructor(t){super(t,Ft.name,500)}}class jt extends u{constructor(t,e=jt.name){super(t,e,500)}}class Ut extends jt{constructor(t){super(t,Ut.name)}}function Mt(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ut.Symbol(ut.constr(t)).toString().replaceAll(".","-")}async function Yt(t,e=!1){if(!e){const e=[];for(const r of t)e.push(await r());return e}const r=[];for(const e of t)try{r.push({status:"fulfilled",value:await e()})}catch(t){r.push({status:"rejected",reason:t})}return r}function Gt(t,e){const{handler:r,args:s}=ut.get(t,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function qt(t){return t.then((t=>t.default||t))}function Ht(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof Ut)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class zt{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}))}static get instance(){return zt._instance||(zt._instance=new zt),zt._instance}}class Wt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Wt._instance||(Wt._instance=new Wt),Wt._instance}}class Qt{constructor(t,...e){this.adapter=t}async begin(...t){}async commit(...t){}async rollback(...t){}}class Vt extends at{constructor(t){super(),this.adapterTransaction=t,this.acquireCount=0,this.lock=new at}async acquire(...t){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...t)):this.lock.release()}async release(...t){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...t)}catch(e){await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+e),...t)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(t,...e){await this.lock.acquire();try{await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+t),...e)}catch(t){throw new u("Failed to rollback transaction: "+t)}finally{this.lock.release()}}}const Jt=dt.flavourResolver.bind(dt);dt.flavourResolver=t=>{try{const e=Jt(t);if(e&&e!==ht)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ut.registeredFlavour?ut.registeredFlavour(r):void 0;if(s&&s!==ht)return s;const i=Zt._currentFlavour;if(i){const t=Zt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return ht}};const Xt=Symbol("AdapterProxyCleanup");function Kt(t,e,r,s){if(!e)return t;const i=t,n=[],o=[];for(const t of i)"fulfilled"===t.status?n.push(t.value):o.push(t.reason);if(o.length){r.warn(`Bulk ${s} encountered ${o.length} failure(s) while continuing`);const t=new AggregateError(o,`Bulk ${s} failed for ${o.length} item(s)`);throw t.results=i,t}return n}class Zt extends $t{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Zt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return Zt._baseRepository}transactionLock(...t){return new Qt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[Xt];"function"==typeof e&&await e()};if(t)try{await s(this.proxies[t]),delete this.proxies[t]}catch(e){r.error("Failed to cleanup proxied adapter "+t,e)}else for(const t in this.proxies){try{await s(this.proxies[t])}catch(e){r.error("Failed to cleanup proxied adapter "+t,e);continue}delete this.proxies[t]}}async shutdown(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(Ct.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:e}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...r),this.dispatch&&await this.dispatch.close(...r)})()}catch(t){throw new u("Failed to create shutdown wrapper: "+t)}finally{this.internalLock.release(Ct.SHUTDOWN)}try{await this.shutdownPromise}catch(t){e.error("Error during proxy shutdown",t)}finally{this.shutdownPromise=void 0}}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.internalLock=new at,this.alias in Zt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Zt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Zt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Zt._currentFlavour=this.alias)}Dispatch(){return new Zt._baseDispatch}ObserverHandler(){return new Lt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new Zt._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?q.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${zt.instance.generate()}`;const o=r.logger||j.for(this);return Object.assign({},kt,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:Nt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ut.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}get Context(){return It}async context(t,e,r,...s){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map((t=>q.tableName(t))):q.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof It||(s.push(i),i=void 0),e=i?Object.assign({},i.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}const e=i.getOrUndefined("operation"),s=i.getOrUndefined("affectedTables");if(!e||e!==t||r&&r!==s){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce(((e,[r,s])=>{if(void 0===s)return e;const i=q.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[Ct.METADATA]&&(r.silly("Passing along persistence metadata for "+t[Ct.METADATA]),Object.defineProperty(i,Ct.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[Ct.METADATA]})),{record:i,id:t[q.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=q.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[Ct.METADATA],d=Object.keys(c).filter((t=>t!==a)).reduce(((r,s)=>(r[s]=t[q.columnName(e,s)],r)),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach((([t,e])=>{if(t in d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e}))),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,Ct.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const o=q.tableName(t);i.debug(`Creating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map(((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0}))));return Kt(a?await Yt(l,!0):await Yt(l),a,i,c.CREATE_ALL)}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=q.tableName(t);s.debug(`Reading ${e.length} entries ${n} table`);const o=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map((e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0}))));return Kt(o?await Yt(a,!0):await Yt(a),o,s,c.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const o=q.tableName(t);i.debug(`Updating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map(((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0}))));return Kt(a?await Yt(l,!0):await Yt(l),a,i,c.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=e.map((e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0}))));return Kt(n?await Yt(o,!0):await Yt(o),n,s,c.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&await this.observerHandler.updateObservers(t,e,r,...n)}}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return ut.flavourOf(t)}static get currentFlavour(){if(!Zt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return Zt._currentFlavour}static get current(){return Zt.get(this.currentFlavour)}static get(t){if(!t)return Zt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return ut.flavouredAs(t).filter(q.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${H(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return Reflect.defineProperty(i,Xt,{value:async()=>{if(!s)return;const t=["cancel","close","destroy","disconnect"];for(const e of t){const t=s[e];if("function"==typeof t)try{const e=t.call(s);e instanceof Promise&&await e}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=i,i}migrations(){return ut.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,It]),n("design:returntype",Promise)],Zt.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Zt.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Zt.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Zt.prototype,"client",null);class te extends u{constructor(t){super(t,te.name,500)}}class ee extends u{constructor(t){super(t,ee.name,500)}}class re extends q{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):q.fromModel(this,t)}and(t){return re.and(this,t)}or(t){return re.or(this,t)}not(t){return new re(this,Et.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof re)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(Et).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===Et.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 re){if(!(this.comparison instanceof re)&&this.operator!==Et.NOT)return{comparison:{condition:t}};if(-1===Object.values(St).indexOf(this.operator)&&this.operator!==Et.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return re.group(t,St.AND,e)}static or(t,e){return re.group(t,St.OR,e)}static group(t,e,r){return new re(t,e,r)}static attribute(t){return(new re.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(Et.EQUAL,t)}dif(t){return this.setOp(Et.DIFFERENT,t)}gt(t){return this.setOp(Et.BIGGER,t)}lt(t){return this.setOp(Et.SMALLER,t)}gte(t){return this.setOp(Et.BIGGER_EQ,t)}lte(t){return this.setOp(Et.SMALLER_EQ,t)}in(t){return this.setOp(Et.IN,t)}regexp(t){return this.setOp(Et.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(Et.STARTS_WITH,t)}endsWith(t){return this.setOp(Et.ENDS_WITH,t)}between(t,e){return this.setOp(Et.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new re(this.attr1,this.operator,this.comparison)}catch(t){throw new te(t)}}}}static builder(){return new re.Builder}static from(t){return new re(t)}}var se,ie;i([z(),n("design:type",Object)],re.prototype,"attr1",void 0),i([z(),n("design:type",String)],re.prototype,"operator",void 0),i([z(),n("design:type",Object)],re.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(se||(se={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(ie||(ie={}));const ne={update:ie.CASCADE,delete:ie.NONE},oe={Equals:(t,e)=>re.attribute(t).eq(e),Diff:(t,e)=>re.attribute(t).dif(e),LessThan:(t,e)=>re.attribute(t).lt(e),LessThanEqual:(t,e)=>re.attribute(t).lte(e),GreaterThan:(t,e)=>re.attribute(t).gt(e),GreaterThanEqual:(t,e)=>re.attribute(t).gte(e),In:(t,e)=>re.attribute(t).in(e),Matches:(t,e)=>re.attribute(t).regexp(e)},ae=t=>t.charAt(0).toLowerCase()+t.slice(1);class ce extends F{static get log(){return this._logger||(this._logger=j.for(ce.name)),this._logger}static{this.prefixMap={[xt.FIND_BY]:"find",[xt.PAGE_BY]:"page",[xt.COUNT_BY]:"count",[xt.SUM_BY]:"sum",[xt.AVG_BY]:"avg",[xt.MIN_BY]:"min",[xt.MAX_BY]:"max",[xt.DISTINCT_BY]:"distinct",[xt.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(t){for(const[e,r]of Object.entries(this.prefixMap))if(t.startsWith(e))return{action:r,prefix:e}}static build(t,...e){const r=this.getActionFromMethodName(t);if(!r)throw Error("Unsupported method "+t);const{action:s,prefix:i}=r;let n;["count","sum","avg","min","max","distinct","group"].includes(s)&&(n=this.extractAggregationSelector(t,i));const o=this.extractCore(t,i),a=this.extractSelect(t),c=this.extractGroupBy(t),l=this.buildWhere(o,e),{orderBy:u,limit:d,offset:h}=this.extractOrderLimitOffset(t,e,o);return{action:s,select:a,selector:n,where:l,groupBy:c,orderBy:u,limit:d,offset:h}}static extractAggregationSelector(t,e){const r=t.substring(e.length),s=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),i=s?r.substring(0,s.index):r;return i?ae(i):void 0}static extractCore(t,e=xt.FIND_BY){const r=t.substring(e.length);if(e!==xt.FIND_BY&&e!==xt.PAGE_BY){const t=r.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!t)return"";if("And"===t[0]||"Or"===t[0]){const e=r.substring(t.index+t[0].length),s=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return s?e.substring(0,s.index):e}return""}const s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?r.substring(0,s.index):r}static getFieldsFromMethodName(t){const e=this.getActionFromMethodName(t),r=e?.prefix||xt.FIND_BY,s=this.extractCore(t,r);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter((t=>t.length>0)).map((t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})):[]}static extractSelect(t){const e=t.indexOf(xt.SELECT);if(-1===e)return;const r=t.substring(e+xt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(xt.AND).map(ae).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(xt.GROUP_BY);if(-1!==e)return t.substring(e+xt.GROUP_BY.length).split(xt.ORDER_BY)[0].split(xt.THEN_BY).map(ae).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(xt.THEN_BY);if(-1===s)return;const i=e.substring(s+xt.THEN_BY.length).split(xt.THEN_BY),n=[];for(const t of i){const e=t.match(/(OrderBy|Limit|Offset|Select)/),r=e?t.substring(0,e.index):t;r&&n.push(ae(r))}return n.length>0?n:void 0}}static buildWhere(t,e){if(!t)return;const r=t.split(/OrderBy|GroupBy/)[0]||"";if(!r)return;const s=r.split(/And|Or/).filter((t=>t.length>0));if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach(((t,r)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),a=o?oe[o]:oe.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+s);const l=a(s,c);n=0===r?l:i[r-1]===xt.AND?n.and(l):n.or(l)})),n}static parseFieldAndOperator(t){for(const e of Object.keys(oe))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:ae(r),operator:e}}return{field:ae(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=ce.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new te("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(se).includes(e))throw new te(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(se).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e,r){const s=r??this.extractCore(t),i=s?s.split(/And|Or/).filter((t=>t.length>0)).length:0,n=e.slice(i)??[];let o,a,c;if(n.at(-1)instanceof l&&n.pop(),n.length>=1){const e=n[0],r=this.extractOrderByField(t);o=this.getProperlyOrderByOrThrow(r,e)}return 2>n.length||"number"!=typeof n[1]||(a=n[1]),3>n.length||"number"!=typeof n[2]||(c=n[2]),{orderBy:o,limit:a,offset:c}}}function le(){return(t,e)=>{const r=ut.key(Ct.DEFAULT_QUERY_ATTR);let s=ut.get(t.constructor,r)||[];return s=[...new Set([...s,e])],pt(gt(r,s))(t,e)}}function ue(){return dt.for(Ct.STATEMENT).define({decorator:()=>(t,e,r)=>pt(ft(ut.key(Ct.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function de(t={}){return dt.for(Ct.QUERY).define({decorator:t=>(e,r,s)=>{const i=ce.getFieldsFromMethodName(r);return pt(ft(ut.key(Ct.QUERY,r),{...t,fields:i}),ue(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{action:i,select:n,selector:o,where:a,groupBy:c,orderBy:l,limit:u,offset:d}=ce.build(e.name,...s),h=r;let p;switch(i){case"find":case"page":p=h.select(n);break;case"count":p=h.count(o);break;case"sum":p=h.sum(o);break;case"avg":p=h.avg(o);break;case"min":p=h.min(o);break;case"max":p=h.max(o);break;case"distinct":p=h.distinct(o);break;case"group":p=h.select(),o&&(p=p.groupBy(o));break;default:throw new te("Unsupported action: "+i)}if(a&&(p=p.where(a)),c&&c.length>0&&"group"!==i){p=p.groupBy(c[0]);for(let t=1;t<c.length;t++)p=p.thenBy(c[t])}else if(c&&c.length>0&&"group"===i)for(const t of c)p=p.thenBy(t);const{allowLimit:g,allowOffset:f,allowOrderBy:y,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},w=[{key:"orderBy",value:(l||[])[0],allowed:y},{key:"limit",value:u,allowed:g},{key:"offset",value:d,allowed:f}];for(const t of w)if(void 0!==t.value){if(!t.allowed&&m)throw new te(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(p=p[t.key](t.value))}if("page"===i){const t=s[s.length-1],e="number"==typeof t?t:t?.limit??10;return p.paginate(e)}return p.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function he(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(ut.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=ut.key(t,i,n),a={...r||{},kind:e,attribute:i};return gt(o,a)(s,i)}}function pe(t){return dt.for(Et.VIEW).define({decorator:t=>he(Et.VIEW,"view",t),args:[t]}).apply()}function ge(t){return ve(t,[a.CREATE,c.CREATE_ALL])}function fe(t){return ve(t,[a.UPDATE,c.UPDATE_ALL])}function ye(t){return ve(t,[a.DELETE,c.DELETE_ALL])}function me(t){return ve(t,Nt)}function we(t){return ve(t,Object.values(a))}function be(t){return ve(t,Object.values(c))}function ve(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:o}=Pt.prototype.logCtx(n,ve);return o.silly(`filtering ${s} event for${r?" "+(q.tableName(r)||r):""} ${i}`),("string"==typeof r?r===q.tableName(t)||r===t.constructor.name:ut.constr(t)===ut.constr(r))&&e.includes(s)}}const Ae={onlyOnCreate:ge,onlyOnUpdate:fe,onlyOnDelete:ye,onlyOnTransactional:me,onlyOnSingle:we,onlyOnBulk:be};function xe(t){const e=Object.assign({},Ae);return Object.entries(e).forEach((([r,s])=>{e[r]=s(t.class)})),e}var Ee,Se,Oe,Ce,Te,ke,Ne,De,_e,Be,Re;class Ie extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new u("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=q.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return xe(this)}constructor(t,e,...r){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},t&&(this._adapter=t),e&&(Ie.register(e,this,this.adapter.alias),t)&&ut.get(e,yt.FLAVOUR)===ht&&mt(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach((t=>{const e=t.name;p(s,s[e+"Prefix"],t,s[e+"Suffix"])})),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(t,e,r=!1,s){const i=this.adapter.logCtx([this.class,...t],e,r,Object.assign({},s||{},this._overrides||{}));function n(t){return t.ctxArgs.shift(),t}return i instanceof Promise?i.then(n):n(i)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new Lt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),t=new this.class(t),n||await f(this,r,t,a.CREATE,a.ON),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new d(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${q.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${q.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r))),o=n.map((t=>t.id));let a=n.map((t=>t.record));return a=await this.adapter.createAll(this.class,o,a,...i),a.map(((t,e)=>this.adapter.revert(t,this.class,o[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!t.length)return[t,...s];const l=q.sequenceFor(t[0]);let h=[];if(q.generatedBySequence(this.class)?(l.name||(l.name=q.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l,this._overrides)).range(t.length,...s)):q.generated(this.class,this.pk)||(h=t.map(((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]}))),t=await Promise.all(t.map((async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?h[e]:""+t[this.pk]),n||await f(this,r,t,a.CREATE,a.ON),t)))),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),n=y(s);if(n)throw new d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=t,n||await f(this,r,o,a.READ,a.ON),[t,...s]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${q.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map((async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,a.READ,a.ON)}))),[t,...s]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${q.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${q.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=q.merge(l,t,this.class))),n||await f(this,r,t,a.UPDATE,a.ON,l),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${q.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,n.map((t=>t.id)),n.map((t=>t.record)),...i)).map(((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const l=t.map((t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e}));let h;if(r.get("applyUpdateValidation")&&(h=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map(((t,e)=>q.merge(h[e],t,this.class))))),n||await Promise.all(t.map(((t,e)=>f(this,r,t,a.UPDATE,a.ON,h?h[e]:void 0)))),!o){const e=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+e),s=r.get("applyUpdateValidation")?await Promise.all(t.map(((t,r)=>Promise.resolve(t.hasErrors(h[r],...e))))):await Promise.resolve(t.map((t=>t.hasErrors(...e))));const n=y(s);if(n)throw new d(n)}return[t,...s,h]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,a.DELETE,a.ON)}return[t,...s]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${q.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map((async t=>f(this,r,t,a.DELETE,a.ON))))}return[t,...s]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${q.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}count(t){return this.adapter.Statement(this._overrides).count(t).from(this.class)}min(t){return this.adapter.Statement(this._overrides).min(t).from(this.class)}max(t){return this.adapter.Statement(this._overrides).max(t).from(this.class)}sum(t){return this.adapter.Statement(this._overrides).sum(t).from(this.class)}avg(t){return this.adapter.Statement(this._overrides).avg(t).from(this.class)}distinct(t){return this.adapter.Statement(this._overrides).distinct(t).from(this.class)}async query(t,e,r=se.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,Ct.QUERY,!0)).for(this.query),a=[e,r],c=this.select().where(t).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${q.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new te("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);let d;if(c.verbose(`paginating ${q.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===se.ASC?this.attr(q.pk(this.class)).gt(o):this.attr(q.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new te("PaginateBy needs a page or a bookmark");d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...u)}const h=await d.page(i,o,...u);return d.serialize(h)}async find(t,e=se.ASC,...r){if("string"!=typeof t)throw new te("Find value must be a string");const s=this.getDefaultQueryAttributes(),i=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:o}=(await this.logCtx(r,Ot.FIND,!0)).for(this.find);return n.verbose(`finding ${q.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(i).orderBy([s[0],e]).execute(...o)}async page(t,e=se.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new te("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new te("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:h}=(await this.logCtx(s,Ot.PAGE,!0)).for(this.page);u.verbose(`paging ${q.tableName(this.class)} by default attributes ${c.join(", ")}`);const p=a??10,g=c[0],f=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let y;if(o&&d.get("paginateByBookmark")){const t=q.pk(this.class),r=e===se.ASC?this.attr(t).gt(o):this.attr(t).lt(o);y=await f.select().where(l.and(r)).orderBy([g,e]).paginate(p,...h)}else{if(!n)throw new te("PaginateBy needs a page or a bookmark");y=await f.select().where(l).orderBy([g,e]).paginate(p,...h)}const m=await y.page(i,o,...h);return y.serialize(m)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${q.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${q.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.COUNT_OF,!0)).for(this.countOf);return r.verbose(`counting ${q.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.MAX_OF,!0)).for(this.maxOf);return r.verbose(`finding max of ${t} in ${q.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.MIN_OF,!0)).for(this.minOf);return r.verbose(`finding min of ${t} in ${q.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.AVG_OF,!0)).for(this.avgOf);return r.verbose(`calculating average of ${t} in ${q.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.SUM_OF,!0)).for(this.sumOf);return r.verbose(`calculating sum of ${t} in ${q.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.DISTINCT_OF,!0)).for(this.distinctOf);return r.verbose(`finding distinct values of ${t} in ${q.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.GROUP_OF,!0)).for(this.groupOf);return r.verbose(`grouping ${q.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...e){if(!Ie.statements(this,t))throw new te("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const t=q.defaultQueryAttributes(this.class);if(!t||!t.length)throw new te("No default query attributes defined for "+q.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new te("Default query value must be a string");let r;for(const s of e){const e=this.attr(s).startsWith(t);r=r?r.or(e):e}if(!r)throw new te("No default query attributes available for "+q.tableName(this.class));return r}attr(t){return re.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=this.class.name;return this.adapter.observe(this,((t,e,r,...i)=>"string"==typeof t?t===s:ut.constr(t)===ut.constr(this.class))),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.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(t,e,r,...s){if(!this.observerHandler)throw new u("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(t,e,Array.isArray(r)?r.map((t=>Zt._baseSequence.parseValue(q.sequenceFor(this.class).type,t))):Zt._baseSequence.parseValue(q.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||ut.flavourOf(t)||Zt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ie)return s;const n=e||ut.flavourOf(t)||s&&ut.get(s,Ct.ADAPTER)||Zt.currentFlavour,o=n?Zt.get(n):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=q.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r){let s=q.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof Ie)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ie?t.constructor:t,s=ut.get(r,e?ut.key(Ct.STATEMENT,e):Ct.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ie?t.constructor:t;return ut.get(r,e?ut.key(Ct.QUERY,e):Ct.QUERY)}}function Pe(t,e){if(!(e||(e=dt.flavourResolver(t instanceof q?t.constructor:t))&&e!==ht))throw new u("Could not retrieve flavour from model "+(t instanceof q?t.constructor.name:t.name));return W(Ct.INJECTABLE,e,q.tableName(t))}i([ue(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ie.prototype,"listBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"paginateBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[String,String,void 0]),n("design:returntype",Promise)],Ie.prototype,"find",null),i([ue(),n("design:type",Function),n("design:paramtypes",[String,String,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"page",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"findOneBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"findBy",null),i([ue(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"countOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ee="undefined"!=typeof K&&K)?Ee:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"maxOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Se="undefined"!=typeof K&&K)?Se:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"minOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Oe="undefined"!=typeof K&&K)?Oe:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"avgOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ce="undefined"!=typeof K&&K)?Ce:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"sumOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Te="undefined"!=typeof K&&K)?Te:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"distinctOf",null),i([ue(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ke="undefined"!=typeof K&&K)?ke:Object,void 0]),n("design:returntype",Promise)],Ie.prototype,"groupOf",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Ie.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ie.prototype,"unObserve",null),Zt&&(Zt._baseRepository=Ie);class $e extends t{get log(){return this.logger||(this.logger=j.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=q.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=q.get(t.toString())),!n)return;const o=Ct.ADAPTER,a=r||ut.get(n,o);try{let t=a;try{a&&Zt.get(a)}catch{const e=Zt.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ie.forModel(n,t),i instanceof Ie)return i;const r=a||ut.get(i.constructor,o)||ut.get(n,o);e.register(i,Pe(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Ie.get(n,a);if("function"==typeof e){const t=a?Zt.get(a):Zt.current;if(!t)return;return new e(t,n)}}}return i}}(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(Ne||(Ne={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(De||(De={})),(t=>{t.NONE="none",t.FULL="full"})(_e||(_e={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Be||(Be={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Re||(Re={}));const Le="tasks",Fe={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};function je(t,e){return(i,n)=>n?r(ut.constr(t))(i,n):(ut.set(b.REPOSITORY,ut.key(e||Zt.currentFlavour,q.tableName(t)),i),wt(b.REPOSITORY,i.name)(t),e=e||ut.get(i.constructor,Ct.ADAPTER),Ie.register(t,i,e),s(ut.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut.tasks=(()=>ut.innerGet(Symbol.for(Le))).bind(ut),ut.taskFor=(t=>{const e=ut.tasks();return e?e[t]:void 0}).bind(ut),ut.validationExceptions=((t,e)=>{const r=ut.get(t,Ct.NO_VALIDATE)||[],s=Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t));let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=q.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ut),ut.migrationsFor=(t=>{if(!(t=t??Zt.current))throw new u("Could not get adapter for migrations");return ut.innerGet(Symbol.for(Ct.MIGRATION),t.alias).map((t=>t.class))}).bind(ut),ut.migrations=(()=>{const t=ut.innerGet(Symbol.for([Ct.MIGRATION,Ct.BY_KEY].join("-")));return Object.values(t).flat().map((t=>[t.class.name,t.class]))}).bind(ut),ut.relations=((t,e)=>{const r=ut.get(t,Ct.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(ut),q.relations=(t,e)=>ut.relations(t instanceof q?t.constructor:t,e)||[],q.nestedRelations=((t,e=[])=>{let r=[];const s=ut.get(t,Ct.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&q.relations(i.class)){const s=q.relations(i.class).map((e=>`${t}.${e}`));e=[...e,...s],r=q.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(q),q.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!q.sequenceFor(r).generated}).bind(q),q.fromTable=(t=>{const e=ut.innerGet(Symbol.for(Ct.TABLE));if(!e||!e[t]||!q.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return q.get(e[t].name)}).bind(q),ut.createdBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(ut),ut.updatedBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(ut),q.tableName=t=>{if(!(t instanceof q?q.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ut.get(t instanceof q?t.constructor:t,Ct.TABLE)||(t instanceof q?t.constructor.name:t.name)},q.columnName=(t,e)=>ut.get(t instanceof q?t.constructor:t,ut.key(Ct.COLUMN,e))||e,q.defaultQueryAttributes=t=>{const e="function"==typeof t?t:t.constructor;return ut.get(e,ut.key(Ct.DEFAULT_QUERY_ATTR))||[q.pk(t)]},q.sequenceName=(t,...e)=>[q.tableName(t),...e].join("_"),q.sequenceFor=(t,e)=>{if(e)throw new Ft("not currently supported");const r=q.pkProps(t instanceof q?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},q.indexes=t=>{const e=ut.get(t instanceof q?t.constructor:t,Ct.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[Ct.INDEX]:e[r]},t)),{})},e.services=()=>ut.innerGet(Symbol.for(Ct.SERVICE)),e.repositories=()=>ut.innerGet(Symbol.for(b.REPOSITORY));class Ue extends u{constructor(t){super(t,Ue.name,500)}}var Me;function Ye(t,...e){return(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 a;try{a=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(a)throw a;return r.call(s,...o)}})}}function Ge(t,...e){return(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 a;try{a=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(a)throw a;return r.call(s,...o)}})}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(Me||(Me={}));const qe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},He=qe,ze={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},We=Object.assign({},ze,{type:"BigInt"});function Qe(t,e,r){return dt.for(Ct.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find((t=>![se.ASC,se.DSC].includes(t)))&&(e=t,t=void 0),gt(ut.key(`${Ct.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Ve(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=q.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,a;n=s,o=r,a=await i.next(t),Reflect.set(n,o,a)}function Je(t,e){return(r,s)=>{if(bt()(r,s),!t.type){const e=ut.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[bt(),Qe([se.ASC,se.DSC]),z(),v(),gt(ut.key(b.ID,s),t),A(Ve,t,e)];return t.generated&&i.push(x()),pt(...i)(r,s)}}function Xe(t){const e=Object.assign({},He);return delete e.generated,t=Object.assign({},e,t),dt.for(b.ID).define({decorator:Je,args:[t,{priority:60}]}).apply()}async function Ke(t,e,r,s,i){const n=e.logger.for(Ke);if(!s){const e=q.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=Ie.forModel(e,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===t[q.pk(s.class)])n.info(`No pk found in ${q.tableName(s.class)} - creating`),o=await s.create(t,e);else{n.info(`pk found in ${q.tableName(s.class)} - attempting update`);try{o=await s.update(t,e),n.info("Updated "+q.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+q.tableName(s.class)),o=await s.create(t,e)}n.info("After create update: "+o)}return o}async function Ze(t,e,r,s){const i=s[r];if(!i)return;if(or(s,e),"object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const o=Ie.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=q.pk(a);await yr(t,s,r,a[c],a),s[r]=a[c]}async function tr(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ie.CASCADE)return;if("object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}const n=await Ke(s[r],t,this.adapter.alias,void 0,this._overrides),o=q.pk(n);await yr(t,s,r,n[o],n),s[r]=n[o]}async function er(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ie.CASCADE)return;const n=vr(s,r,this.adapter.alias);let o;o=i instanceof q?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await yr(t,s,r,o[n.pk],o)}async function rr(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;or(s,e);const o=t.logger.for(rr),a=vr(s,r,this.adapter.alias),c=q.pk("function"!=typeof e.class||e.class.name?e.class:e.class()),l=new Set;for(const e of n){let i;"object"!=typeof e?(i=await a.override(this._overrides).read(e,t),o.debug("read: "+i[c])):(o.verbose("Creating or updating one-to-many model: "+e[c]),i=await Ke(e,t,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await yr(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function sr(t,e,r,s,i){const{cascade:n}=e;if(n.update===ie.CASCADE)return rr.call(this,t,e,r,s,i)}async function ir(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?Ie.forModel(o,this.adapter.alias):vr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await yr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}async function nr(t,e,r,s){const i=s[r];if(!i)return;or(s,e);const n=t.logger.for(nr);if("object"!=typeof i){const e=vr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await yr(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof q?e.class.constructor:e.class))throw new u("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const o=await Ke(i,t,this.adapter.alias,void 0,this._overrides),a=q.pk(o);n.info(`caching: ${JSON.stringify(o)} under ${o[a]}`),await yr(t,s,r,o[a],o),s[r]=o[a]}function or(t,e){let r;const s="function"==typeof e.class&&e.class.name?e.class:e.class(),i=ut.get(s,Ct.RELATIONS);if(i&&(r=Object.values(i)?.find((e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r}))),!0===r?.populate&&!0===e?.populate)throw new u("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function ar(t,e,r,s){const{cascade:i}=e;if(i.update===ie.CASCADE)return nr.call(this,t,e,r,s)}async function cr(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,o=n?Ie.forModel(i,this.adapter.alias):vr(s,r,this.adapter.alias),a=n?i[o.pk]:i,c=await o.override(this._overrides).delete(a);await yr(t,s,r,a,c),s[r]=a}async function lr(t,e,r,s){const i=s[r];if(!i||!i.length)return;or(s,e);const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o=t.logger.for(lr),a=new Set([...i]);if("object"!==n){const n=vr(s,r,this.adapter.alias),c=await n.override(this._overrides).readAll([...a.values()],t);for(let e=0;e<c.length;e++){const s=c[e];o.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(s)),await yr(t,s,r,[...a.values()][e],c)}return await ur.call(this,s,[...i],o,t,e),s[r]=[...a],void o.info("SET MANY TO MANY IDS: "+s[r])}const c=q.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating many-to-many model: "+JSON.stringify(e));const i=await Ke(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await yr(t,s,r,i[c],i),o.info("Creating or updating many-to-many model: "+JSON.stringify(e)),e.id=i.id,l.add(i[c])}const d=q.pk(s.constructor);if(void 0===s[d]){const e=await(async(t,e,r)=>{const s=e[q.pk(e.constructor)];if(void 0!==s)return s;const i=q.sequenceFor(e.constructor);let n;i?.name||(i.name=q.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i,t._overrides),await n.next(r)}catch(t){throw new u(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[d]=e}const h=await ur.call(this,s,i,o,t,e);o.info("Junction model created: "+h.name),s[r]=[...l]}async function ur(t,e,r,s,i){const{JunctionModel:n,fkA:o,fkB:a}=dr(t,e[0],i),c=[];for(const i of e){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(i));const e={[o]:t instanceof q?t[q.pk(t.constructor)]:t,[a]:i instanceof q?i[q.pk(i.constructor)]:i},l=await Ke(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Ie.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function dr(t,e,r){const s=q.tableName(t);let i;if(e instanceof q)i=q.tableName(e);else if(q.isModel(e)&&"function"==typeof e)i=e.name?e.name:e()?.name;else if(r?.class){const t="function"!=typeof r.class||r.class.name?r.class:r.class();i=q.tableName(t)}if(!s||!i)throw new u("Missing tablenames to create junction table");const n=r?.joinTable?.name?r?.joinTable?.name:`${s}_${i}`,o=s?.toLowerCase()+"_fk",a=i?.toLowerCase()+"_fk",c=class extends q{constructor(t){super(t)}};Object.defineProperty(c,"name",{value:n,writable:!1}),Xe({type:Number})(c.prototype,"id"),z()(c.prototype,o),z()(c.prototype,a);const l=Q()(c);return ut.set(c,Ct.TABLE,n),{fkA:o,fkB:a,JunctionModel:l}}async function hr(t,e,r,s){const{cascade:i}=e;if(i.update===ie.CASCADE)return lr.call(this,t,e,r,s)}async function pr(t,e,r,s){if(e.cascade.delete!==ie.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?Ie.forModel(o,this.adapter.alias):vr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await yr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function gr(t,e,r){return[Ct.POPULATE,t,e,r].join(".")}function fr(t,e,r){return[Ct.TAG_FOR_DELETION,t,r].join(".")}async function yr(t,e,r,s,i){const n=gr(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function mr(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=this,l=await(async(e,r,s,i)=>{let n,l;const d=[];let h;try{h=e.get("operation")}catch(t){h=void 0}const p=h===a.READ||h===c.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=gr(r.constructor.name,s,e);try{if(l=p[n],!l)throw Error("Not found in cache")}catch(i){const n=vr(r,s);if(!n)throw new u("Could not find repo");l=await n.override(o._overrides).read(e,t)}d.push(l)}return d})(t,s,r,n?i:[i]);s[r]=n?l:l[0]}async function wr(t,e,r,s,i){if(e.cascade.update!==ie.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new u("No way to compare old model. do you have updateValidation and mergeModels enabled?");function o(t){return Array.isArray(t)?t.map(o):"object"!=typeof t?t:t[q.pk(t)]}const a=o(s[r]),c=o(i[r]);if(void 0===c||V(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(a)?a:[a]).filter(Boolean),d=(Array.isArray(c)?c:[c]).filter(Boolean).filter((t=>!l.includes(t))),h=vr(s,r);if(!h)throw new u("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${q.tableName(h.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}const br=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function vr(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=ut.get(t instanceof q?t.constructor:t,ut.key(J.REFLECT,e,J.LIST))?.clazz;if(!r)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map((t=>"function"!=typeof t||t.name?t:t()))}else s=ut.getPropDesignTypes(t instanceof q?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!br.includes((""+t.name).toLowerCase())));return Ie.forModel(i,r)}class Ar extends E{constructor(t,e=Ar.name,r=401){super(t,e,r)}}class xr extends Ar{constructor(t,e=xr.name){super(t,e,403)}}class Er extends u{constructor(t){super(t,Er.name,503)}}function Sr(t){return dt.for(Ct.TABLE).define({decorator:t=>e=>(ut.set(Ct.TABLE,t||e.name.toLowerCase(),e),wt(Ct.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function Or(t){return dt.for(Ct.COLUMN).define({decorator:t=>(e,r)=>gt(ut.key(Ct.COLUMN,r),t||r)(e,r),args:[t]}).apply()}async function Cr(t,e,r,s){if(s[r]&&(await this.select().where(re.attribute(r).eq(s[r])).execute()).length)throw new O(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Tr(){const t=Ct.UNIQUE;return dt.for(t).define(X(),C(Cr),gt(t,{})).apply()}async function kr(t,e,r,s){throw new Ar("This adapter does not support user identification")}function Nr(){return dt.for(Ct.CREATED_BY).define({decorator:()=>(t,e)=>pt(A(kr),gt(Ct.CREATED_BY,e),x(Ct.CREATED_BY))(t,e),args:[]}).apply()}function Dr(){return dt.for(Ct.UPDATED_BY).define({decorator:()=>(t,e)=>pt(k(kr),gt(Ct.UPDATED_BY,e),x(Ct.UPDATED_BY))(t,e),args:[]}).apply()}function _r(){return T([a.CREATE])}function Br(){return T()}function Rr(t){return[()=>{const e="function"==typeof t&&t.name?t:t(),r=q.pk(e);return(ut.allowedTypes(e,r)||[])[0]}]}function Ir(t,e=ne,r=!0,s,i){const n=Ct.ONE_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),Z([t,...a]),A(Ze,o,{priority:70}),k(tr,o,{priority:70}),N(er,o,{priority:70}),D(wr,o,{priority:70}),_(mr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Pr(t,e=ne,r=!0,s,i){const n=Ct.ONE_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),tt([t,...a]),A(rr,o,{priority:70}),k(sr,o,{priority:70}),N(ir,o,{priority:70}),D(wr,o,{priority:70}),_(mr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function $r(t,e=ne,r=!0,s,i){const n=Ct.MANY_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),Z([t,...a]),A(nr,o),k(ar,o),N(cr,o),_(mr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Lr(t,e=ne,r=!0,s,i){const n=Ct.MANY_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Rr(t),c=[bt(),Yr(n,o),tt([t,...a]),A(lr,o),k(sr,o),_(mr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Fr(...t){return(e,r)=>{const s=ut.get(e,ut.key(Ct.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return pt(wt(ut.key(Ct.NO_VALIDATE,r),i))(e,r)}}function jr(){return Fr(a.CREATE)}function Ur(){return Fr(a.UPDATE)}function Mr(){return Fr(a.UPDATE,a.CREATE)}function Yr(t,e){return dt.for(Ct.RELATIONS).define({decorator:(t,e)=>(r,s)=>(gt(t,e)(r,s),gt(ut.key(Ct.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class Gr extends q{constructor(t){super(t)}}i([_r(),n("design:type",Date)],Gr.prototype,"createdAt",void 0),i([Br(),n("design:type",Date)],Gr.prototype,"updatedAt",void 0);let qr=class extends Gr{constructor(t){super(t)}};i([Xe({type:String,generated:!1}),n("design:type",String)],qr.prototype,"id",void 0),i([z(),Qe(),n("design:type",Object)],qr.prototype,"current",void 0),qr=i([Sr("??sequence"),Q(),n("design:paramtypes",[Object])],qr);class Hr extends F{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(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,Ht(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Ot.FIND_BY}|${Ot.LIST_BY}|${Ot.FIND}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Ot.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[t,...r]}async pagePrepared(t,e,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!e||e instanceof It?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof It||(this._bookmark=e);const n=Ie.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o;if(a===Ot.FIND){const e=[Ot.PAGE,...c],r={limit:this.size,offset:t,bookmark:this._bookmark};e.push(r);const s=await n.statement(...e,...i);return this.apply(s)}const u=RegExp(`^${Ot.FIND_BY}|${Ot.LIST_BY}`,"gi");if(!a.match(u))throw new Ft(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,Ot.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Ot.PAGE_BY||h.length>2?p={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(p);const g=await n.statement(...h,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new ee("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ee(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,e,...r){const{ctxArgs:s}=this.adapter.logCtx([e,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...s);throw new Ft("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new B(t)}}apply(t){const e="string"==typeof t?Hr.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total||this._totalPages,this._recordCount=e.count||this._recordCount,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new B(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var zr,Wr,Qr,Vr,Jr,Xr,Kr;class Zr extends Pt{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach((t=>{R(this,t,((...e)=>this.executionPrefix(t,...e)),t.name)}))}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?Ot.PAGE_BY:Ct.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const a=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||a)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Zr)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!t)throw new te("distinct() requires a selector when not chained after count()");return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}sum(t){return this.sumSelector=t,this}avg(t){return this.avgSelector=t,this}count(t){return this.countSelector=t??null,this._inCountMode=!0,this}from(t){if(this.fromSelector="string"==typeof t?q.get(t):t,!this.fromSelector)throw new te("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t,e){return this.orderBySelectors=[this.normalizeOrderCriterion(t,e)],this}thenBy(t,e){if(Array.isArray(t)||void 0!==e){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new te("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new te("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(t),this}normalizeOrderCriterion(t,e){if(Array.isArray(t)){const[e,r]=t;return[e,this.normalizeOrderDirection(r)]}return[t,this.normalizeOrderDirection(e)]}normalizeOrderDirection(t){if(!t)throw new te("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===se.ASC)return se.ASC;if(e===se.DSC)return se.DSC;throw new te(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(se).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new te("groupBy must be called before orderBy.");return this.groupBySelectors=[t],this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const{log:e,ctx:r,ctxArgs:s}=this.logCtx(t,this.execute);try{if(this.prepared)return this.executePrepared(...t);e.silly("Building raw statement...");const i=this.build();e.silly("executing raw statement");const n=await this.raw(i,...s);if(this.hasAggregation())return n;if(!this.selectSelector){const t=q.pk(this.fromSelector),e=function(e){const s=e[t];return this.adapter.revert(e,this.fromSelector,s,void 0,r)}.bind(this);return this.groupBySelectors?.length?this.revertGroupedResults(n,e):Array.isArray(n)?n.map(e):e(n)}return n}catch(t){throw new te(t)}}revertGroupedResults(t,e){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.entries(t).reduce(((t,[r,s])=>(t[r]=this.revertGroupedResults(s,e),t)),{}):t}async executePrepared(...t){const e=Ie.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new Ft("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(this.hasAggregation())return i;if(!this.selectSelector)return i;const n=q.pk(this.fromSelector),o=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case St.AND:case St.OR:{let t=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof re){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case Et.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case Et.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case Et.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case Et.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case Et.BIGGER_EQ:n.method=r+" bigger than equal";break;case Et.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case Et.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case Et.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new te("Unsupported operator "+s)}return n}squash(t){const e=this.matchDefaultQueryCondition();if(e){const t=this.getOrderDirection();return{class:this.fromSelector,method:Ot.FIND,args:[e.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof re)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Ot.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Ot.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Ot.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Ot.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Ot.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Ot.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Ot.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 r;this.whereCondition&&(r=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,se.DSC]:[q.pk(this.fromSelector),se.DSC],[i,n]=s,o={direction:n};this.limitSelector&&(o.limit=this.limitSelector),this.offsetSelector&&(o.offset=this.offsetSelector);const a={class:this.fromSelector,method:Ot.LIST_BY,args:[i],params:o};return r&&(a.method=Ot.FIND_BY,a.args=[r,this.whereCondition.comparison],a.params=o),a}matchDefaultQueryCondition(){if(!this.whereCondition)return;const t=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!t)return;const e=q.defaultQueryAttributes(this.fromSelector);if(!e||!e.length)return;const r=Array.from(new Set(e.map(String))),s=Array.from(new Set(t.attributes.map(String)));return r.length===s.length&&r.every((t=>s.includes(t)))?{value:t.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(t){const e=this.collectStartsWithAttributes(t);if(e)return{attributes:Array.from(new Set(e.attributes)),value:e.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:e,operator:r,comparison:s}=t;if(r===Et.STARTS_WITH){if("string"!=typeof e||"string"!=typeof s)return;return{attributes:[e],value:s}}if(r===St.OR){const t=e instanceof re?this.collectStartsWithAttributes(e):void 0,r=s instanceof re?this.collectStartsWithAttributes(s):void 0;return t&&r&&t.value===r.value?{attributes:[...t.attributes,...r.attributes],value:t.value}:void 0}return r===St.AND?(e instanceof re?this.collectStartsWithAttributes(e):void 0)||(s instanceof re?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??se.ASC}async prepare(t){if(t=t||await this.adapter.context(Ct.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 e=[],r={},s={class:this.fromSelector,args:e,params:r};let i,n=xt.FIND_BY;void 0!==this.countSelector?(n=xt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=xt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=xt.AVG_BY,i=this.avgSelector):this.minSelector?(n=xt.MIN_BY,i=this.minSelector):this.maxSelector?(n=xt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=xt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=xt.GROUP_BY_PREFIX,i=this.groupBySelectors[0]);const o=[n];if(i&&o.push(i),this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);o.push(r.method),r.args&&r.args.length&&e.push(...r.args)}if(this.selectSelector&&o.push(xt.SELECT,this.selectSelector.join(` ${xt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;o.push(xt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map((([t,e])=>[t,e])),e.forEach((([t])=>{o.push(xt.THEN_BY,t)})))}if(this.groupBySelectors?.length&&n!==xt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;o.push(xt.GROUP_BY,t),e.forEach((t=>o.push(xt.THEN_BY,t)))}else this.groupBySelectors?.length&&n===xt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach((t=>o.push(xt.THEN_BY,t)));return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=M(o.join(" ")),s.params=r,this.prepared=s,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(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new te(t)}}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Zr.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(zr="undefined"!=typeof S&&S)?zr:Object]),n("design:returntype",Object)],Zr.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Wr="undefined"!=typeof S&&S)?Wr:Object]),n("design:returntype",Object)],Zr.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Qr="undefined"!=typeof S&&S)?Qr:Object]),n("design:returntype",Object)],Zr.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Vr="undefined"!=typeof S&&S)?Vr:Object]),n("design:returntype",Object)],Zr.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Jr="undefined"!=typeof S&&S)?Jr:Object]),n("design:returntype",Object)],Zr.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Xr="undefined"!=typeof S&&S)?Xr:Object]),n("design:returntype",Object)],Zr.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Zr.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[re]),n("design:returntype",Object)],Zr.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Zr.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Zr.prototype,"thenBy",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Kr="undefined"!=typeof Key&&Key)?Kr:Object]),n("design:returntype",Object)],Zr.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Zr.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Zr.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Zr.prototype,"execute",null);class ts extends Pt{constructor(t){super(),this.name=t,this.observers=[],this.Context=It}for(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof ts?n.for(t,...e):n instanceof Ie?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Lt,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("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(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${zt.instance.generate()}`;const s=e.logger||j.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Tt,e,{args:r,timestamp:new Date,operation:t,logger:s})}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}async context(t,e,...r){this.log.for(this.context).silly(`creating new context for ${t} operation with flag overrides: ${JSON.stringify(e)}`);let s=r.pop();void 0===s||s instanceof It||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return Pt.logCtx.call(this,e,s||{},r,...t.filter((t=>void 0!==t)))}static get(t){if(!t)throw new u("No name provided");const r=Mt(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof It||(t.push(r),r=void 0);const s=await ts.prototype.flags(Ct.INITIALIZATION,{},...t);r=r?new It(r).accumulate({...s,parentContext:r}):(new It).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=ts.prototype.logCtx(t,this.boot),o=e.services();for(const[t,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof es&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new u(`Failed to boot ${r.name} service:${t}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof It||(t.push(r),r=void 0);const s=await ts.prototype.flags(Ct.SHUTDOWN,{},...t);r=r?new It(r).accumulate({...s,parentContext:r}):(new It).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=ts.prototype.logCtx(t,this.shutdown),o=e.services();for(const[t,r]of Object.entries(o).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof es){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],ts.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ts.prototype,"unObserve",null);class es extends ts{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.boot);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function rs(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Gt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],es.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],es.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],es.prototype,"client",null);const ss=()=>rs(a.CREATE),is=()=>rs(a.READ),ns=()=>rs(a.UPDATE),os=()=>rs(a.DELETE);function as(t){return(e,i,n)=>{n||i?(bt()(e,i),t=t||ut.type(e.constructor,i)):t=t||e,t=Mt(t);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else ut.set(Ct.SERVICE,t,e),o.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return pt(...o)(e,i,n)}}function cs(t){const e=Ct.AUTH;return dt.for(e).define({decorator:t=>wt(e,t),args:[t]}).apply()}const ls=t=>wt(Ct.AUTH_ROLE,t);function us(t,e){const r=Ct.DECAF_ROUTE;return dt.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return pt(ft(ut.key(r,i),o))(s,i,n)},args:[]}).apply()}const ds=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class hs extends ts{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ie.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=ds(t);try{const t=ts.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=ds(e||t);try{r=hs.get(e)}catch(t){r=void 0}if(r instanceof hs)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([as(e),n("design:paramtypes",[])],o),new o}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo._adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([ss(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"create",null),i([ss(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"createAll",null),i([os(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"delete",null),i([os(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"deleteAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"read",null),i([is(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"readAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],hs.prototype,"query",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"update",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],hs.prototype,"updateAll",null);class ps extends Pt{constructor(){super()}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:e}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach((t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...o),h=[c,i(t),l];return a.get("observeFullResult")&&h.push(Array.isArray(d)?d.map((t=>c(t))):c(d)),this.updateObservers(...h,...o).catch((e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`))),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)}))}async close(...t){}observe(t){if(!(t instanceof Zt))throw new Ft("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=Zt.models(this.adapter.alias),this.initialize().then((()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))),()=>this.unObserve(t)}unObserve(t){if(this.adapter!==t)throw new Ft("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){if(!t)throw new u("Model must be provided for observer update");const i=t&&"string"==typeof t?t:q.tableName(t),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new u("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function gs(t,e,r,s){if(t.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=e;i&&"function"==typeof i&&(i=i(s,...n||[],t)),s[r]=await zt.instance.generate(i)}function fs(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=Ct.UUID;return dt.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[z(),x(Ct.UUID),A(gs,s,{priority:54})];return t&&i.push(k(gs,s,{priority:54})),t||i.push(v()),pt(...i)},args:[t,e,...r]}).apply()}Zt&&(Zt._baseDispatch=ps);class ys extends Pt{static{this.lock=new ct}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ie.forModel(qr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,a.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new u("Sequence name is required");return ys.lock.execute((async()=>{const e=t||n;if(e%n!=0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new qr({id:o,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${t}`),this.repo.create(new qr({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(zt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${o} current=${c} next=${t}`),e.current}catch(t){if(t instanceof O)continue;throw t}}const d=await(async t=>{switch(a){case Number.name:return this.parse(t)+e;case BigInt.name:return this.parse(t)+BigInt(e);case String.name:return this.parse(t);case"serial":return await Promise.resolve(Wt.instance.generate(t));default:throw new u("Should never happen")}})(c),h=await l(d);return r.debug(`Sequence.increment ${o} current=${c} next=${d}`),h.current}),o)}async next(...t){const{ctx:e}=(await this.logCtx(t,a.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ft(`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(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(o-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return ys.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([qr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return q.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new Ft(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function ms(t,...e){let r;if(t instanceof hs&&(r=t.repo.adapter),t instanceof Ie&&(r=t.adapter),t instanceof Zt&&(r=t),!r)throw new u("Could not find adapter to extract transaction");return r.transactionLock(...e)}function ws(t,...e){return new Vt(ms(t,...e))}Zt._baseSequence=ys,dt.for(lt.TRANSACTIONAL).define({decorator:(...t)=>(e,r,s)=>{if(!s)throw new u("This decorator only applies to methods");return vt()(e,r,s),ut.set(e.constructor,ut.key(lt.TRANSACTIONAL,r),{data:t}),s.value=new Proxy(s.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock")||ws(e);let o;i.put("transactionLock",n),await n.acquire();try{o=await t.call(e,...r,i)}catch(t){try{await n.rollback(t)}catch(t){s.error("Failed to rollback transaction",t)}throw t}try{await n.release()}catch(t){throw new u("Failed to release transaction: "+t)}return o}}),s}}).apply();class bs extends es{constructor(){super()}for(t,...e){throw new Ft("Persistence service cannot be overridden")}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof It||!e.every((t=>Array.isArray(t))))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize),i=e.map((([t,e,...s])=>{try{r.silly(`Initializing ${t.name} with config: ${JSON.stringify(e)}`);const i=new t(e,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(e){throw new u(`Failed to initialize ${t.name}: ${e}`)}}));for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let vs=class extends q{constructor(t){super(t),this.strategy=De.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=_e.FULL}};i([z(),Z(String),et(De),At("the backoff strategy"),n("design:type",String)],vs.prototype,"strategy",void 0),i([z(),At("base interval between attempts"),n("design:type",Number)],vs.prototype,"baseMs",void 0),i([z(),At("max interval"),n("design:type",Number)],vs.prototype,"maxMs",void 0),i([Z(String),et(_e),At("optional jitter strategy"),n("design:type",String)],vs.prototype,"jitter",void 0),vs=i([Q(),n("design:paramtypes",[Object])],vs);let As=class extends q{constructor(t){super(t)}};i([z(),At("The error message"),n("design:type",String)],As.prototype,"message",void 0),i([bt(),At("The error stack"),n("design:type",String)],As.prototype,"stack",void 0),i([bt(),At("The error code"),n("design:type",String)],As.prototype,"code",void 0),i([bt(),At("The error details"),n("design:type",Object)],As.prototype,"details",void 0),As=i([Q(),n("design:paramtypes",[Object])],As);let xs=class extends q{constructor(t){super(t),this.ts=new Date}};i([Xe(),I(["taskId","classification","uuid"],":"),n("design:type",String)],xs.prototype,"id",void 0),i([Or(),v(),z(),P(),fs(!1),n("design:type",String)],xs.prototype,"uuid",void 0),i([Or(),v(),z(),Qe([se.ASC,se.DSC]),n("design:type",String)],xs.prototype,"taskId",void 0),i([rt(),Or(),z(),Qe([se.ASC,se.DSC]),n("design:type",Date)],xs.prototype,"ts",void 0),i([Or(),v(),z(),et(Be),Qe([se.ASC,se.DSC]),n("design:type",String)],xs.prototype,"classification",void 0),i([bt(),Or(),$(),v(),n("design:type",Object)],xs.prototype,"payload",void 0),xs=i([Sr("task_event"),Q(),n("design:paramtypes",[Object])],xs);class Es extends st{constructor(){super()}preSerialize(t,...e){return this.serializeValue(t,...e)}deserialize(t,...e){const r=JSON.parse(t);return this.rebuildValue(r)}serializeValue(t,...e){if(null==t)return t;if("object"!=typeof t)return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.map((t=>this.serializeValue(t,...e)));if(t instanceof re){const r=this.serializePlain(t,...e);return r[it.ANCHOR]="??condition",r}return q.isModel(t)?this.serializeModel(t,...e):this.serializePlain(t,...e)}serializeModel(t,...e){const r=this.serializePlain(t,...e),s=this.getMetadata(t.constructor)??t.constructor?.name;return s&&(r[it.ANCHOR]=s),r}serializePlain(t,...e){const r={};for(const[s,i]of Object.entries(t))r[s]=this.serializeValue(i,...e);return r}getMetadata(t){try{return ut.modelName(t)}catch{return}}rebuildValue(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map((t=>this.rebuildValue(t)));const e=t[it.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?re.from(r):q.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==it.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Ss=class extends q{constructor(t){super(t),this.ts=new Date}};i([rt(),z(),n("design:type",Date)],Ss.prototype,"ts",void 0),i([z(),et(Y),n("design:type",String)],Ss.prototype,"level",void 0),i([z(),bt(),n("design:type",String)],Ss.prototype,"msg",void 0),i([bt(),n("design:type",Object)],Ss.prototype,"meta",void 0),Ss=i([Q(),n("design:paramtypes",[Object])],Ss);let Os=class extends q{constructor(t){super(t),this.atomicity=Re.ATOMIC,this.status=Ne.PENDING,this.attempt=0,this.logTail=[]}};i([Xe(),fs(),At("the task id"),n("design:type",String)],Os.prototype,"id",void 0),i([Or(),z(),Z(String),et(Re),Qe([se.ASC,se.DSC]),At("defines a single or composite task"),n("design:type",String)],Os.prototype,"atomicity",void 0),i([Or(),z(),Qe([se.ASC,se.DSC]),At("Holds task classification - must match @task()"),n("design:type",String)],Os.prototype,"classification",void 0),i([Or(),bt(),Qe([se.ASC,se.DSC]),At("optional task name for ambiguity"),n("design:type",String)],Os.prototype,"name",void 0),i([Or(),z(),Z(String),et(Ne),Qe([se.ASC,se.DSC]),At("Holds the task current status"),n("design:type",String)],Os.prototype,"status",void 0),i([bt(),Or(),$(Es),At("Holds task input"),n("design:type",Object)],Os.prototype,"input",void 0),i([bt(),Or(),$(Es),At("Holds the task output when successfully completed"),n("design:type",Object)],Os.prototype,"output",void 0),i([bt(),Or(),$(),At("Holds the error for failed tasks"),n("design:type",As)],Os.prototype,"error",void 0),i([Or(),z(),nt(0),Qe([se.ASC,se.DSC]),At("Holds the current attempt"),n("design:type",Number)],Os.prototype,"attempt",void 0),i([Or(),nt(1),z(),At("max attempts for the task"),n("design:type",Number)],Os.prototype,"maxAttempts",void 0),i([Or(),z(),$(),At("backoff configuration"),n("design:type",vs)],Os.prototype,"backoff",void 0),i([rt(),Or(),At("Next execution timestamp"),n("design:type",Date)],Os.prototype,"nextRunAt",void 0),i([rt(),Or(),At("Task scheduled timestamp"),n("design:type",Date)],Os.prototype,"scheduledTo",void 0),i([bt(),Or(),At("Task lease owner identifier"),n("design:type",String)],Os.prototype,"leaseOwner",void 0),i([rt(),Or(),At("Task lease expiration timestamp"),n("design:type",Date)],Os.prototype,"leaseExpiry",void 0),i([bt(),Or(),$(),At("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Os.prototype,"steps",void 0),i([bt(),Or(),nt(0),Qe([se.ASC,se.DSC]),At("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Os.prototype,"currentStep",void 0),i([bt(),Or(),$(),At("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Os.prototype,"stepResults",void 0),i([bt(),Or(),$(),At("Holds the task log entries"),n("design:type",Array)],Os.prototype,"logTail",void 0),i([Or(),_r(),Qe([se.ASC,se.DSC]),At("timestamp of creation"),n("design:type",Date)],Os.prototype,"createdAt",void 0),i([Or(),Br(),Qe([se.ASC,se.DSC]),At("timestamp of last update"),n("design:type",Date)],Os.prototype,"updatedAt",void 0),i([Or(),Nr(),Qe([se.ASC,se.DSC]),At("Holds the creator of the task"),n("design:type",String)],Os.prototype,"createdBy",void 0),i([Or(),Dr(),Qe([se.ASC,se.DSC]),At("Holds the creator of the task"),n("design:type",String)],Os.prototype,"updatedBy",void 0),Os=i([At("Holds the current step when applicable"),Sr("tasks"),Q(),n("design:paramtypes",[Object])],Os);let Cs=class extends q{constructor(t){super(t)}};i([z(),At("The status of a step"),n("design:type",String)],Cs.prototype,"status",void 0),i([bt(),At("The result of a successful step"),n("design:type",Object)],Cs.prototype,"output",void 0),i([bt(),At("the error of a failed step"),n("design:type",As)],Cs.prototype,"error",void 0),Cs=i([Q(),n("design:paramtypes",[Object])],Cs);let Ts=class extends q{constructor(t){super(t)}};i([z(),bt(),At("task handler type"),n("design:type",String)],Ts.prototype,"classification",void 0),i([At("optional task step input"),bt(),n("design:type",Object)],Ts.prototype,"input",void 0),Ts=i([Q(),n("design:paramtypes",[Object])],Ts);class ks extends q{constructor(t){super(t),this.baseMs=1e3,this.jitter=_e.FULL,this.maxMs=6e4,this.strategy=De.EXPONENTIAL,q.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new d(t);return new vs(this)}}i([z(),nt(1e3),n("design:type",Number)],ks.prototype,"baseMs",void 0),i([z(),et(_e),n("design:type",String)],ks.prototype,"jitter",void 0),i([ot("baseMs"),nt(1e3),z(),n("design:type",Number)],ks.prototype,"maxMs",void 0),i([z(),et(De),n("design:type",String)],ks.prototype,"strategy",void 0);class Ns extends q{setClassification(t){return this.classification=t,this}setName(t){return this.name=t,this}setAtomicity(t){return this.atomicity=t,this}setBackoff(t){if(t)return this.backoff=t,this;const e=new ks,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=Ne.PENDING,this.atomicity=Re.ATOMIC,this.backoff=new vs,this.maxAttempts=1,q.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Os(this)}}i([z(),n("design:type",String)],Ns.prototype,"classification",void 0),i([bt(),n("design:type",String)],Ns.prototype,"name",void 0),i([z(),n("design:type",String)],Ns.prototype,"status",void 0),i([z(),n("design:type",String)],Ns.prototype,"atomicity",void 0),i([z(),n("design:type",vs)],Ns.prototype,"backoff",void 0),i([bt(),n("design:type",Object)],Ns.prototype,"input",void 0),i([nt(1),z(),n("design:type",Number)],Ns.prototype,"maxAttempts",void 0);class Ds extends Ns{constructor(t){super(t),this.stepResults=[],q.fromModel(this,t),this.atomicity=Re.COMPOSITE}setAtomicity(t){throw new u("Atomicity locked to "+Re.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map((t=>t instanceof Ts?t:new Ts(t))),this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Ts({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([tt((()=>Ts)),n("design:type",Array)],Ds.prototype,"steps",void 0);class _s extends $t{get type(){if(!this._type){const t=ut.get(this.constructor,Le);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),p(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function Bs(t){return dt.for(Le).define({decorator:t=>e=>{const r={type:t};return ut.set(Le,t,e),wt(Le,r)(e)},args:[t]}).apply()}let Rs=class extends _s{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof re)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=re.attr("status").eq(Ne.SUCCEEDED).and(re.attr("updatedAt").lte(t.successfulExpiry)),i=re.attr("status").eq(Ne.FAILED).and(re.attr("updatedAt").lte(t.failedExpiry)),n=re.attr("status").eq(Ne.CANCELED).and(re.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map((t=>t.id)),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([je(Os),n("design:type",Object)],Rs.prototype,"tasks",void 0),Rs=i([Bs("cleanup-task"),n("design:paramtypes",[])],Rs);class Is{constructor(t,e=150,r=300,s){this.logger=t,this.bufferSize=e,this.maxBufferSize=r,this.pipe=s,this.history=[],this.root=this.logger.root,Object.values(Y).forEach((t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})}))}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch((t=>this.logger.error("Failed to pipe logs",t))).finally((()=>this.history=[])):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Ps(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1,timestamp:!1,logLevel:!1}),r.classification){case Be.LOG:{let s=r.payload;s=s.map((t=>Array.isArray(t)?t:[t.level,t.ts+" - "+t.message,t.meta]));for(let[r,i,n]of s){e.style||(i=G(i),i=i.clear().toString());const s=[i];r===Y.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case Be.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Be.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=G(e);switch(e){case Ne.SUCCEEDED:s=s.green.bold;break;case Ne.RUNNING:s=s.blue.bold;break;case Ne.PENDING:s=s.yellow;break;case Ne.WAITING_RETRY:s=s.yellow.bold;break;case Ne.FAILED:s=s.red.bold;break;case Ne.CANCELED:s=s.magenta.bold;break;case Ne.SCHEDULED:s=s.cyan;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}function $s(t,e){const r=e.strategy===De.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===_e.FULL?Math.floor(Math.random()*s):s}function Ls(t){return new As({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Fs(t){return new Promise((e=>setTimeout(e,t)))}class js extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=js.name,Object.setPrototypeOf(this,js.prototype)}}class Us extends It{get taskId(){return this.get("taskId")}get logger(){return super.logger}get pipe(){return this.get("pipe")}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(t,e){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[t]=e,this.cache.put("resultCache",r)}changeState(t,e){throw new js({status:t,...e})}cancel(t,e){this.changeState(Ne.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(Ne.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(Ne.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof As?t:t instanceof Error?Ls(t):new As({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class Ms{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ut.tasks();t&&Object.entries(t).forEach((([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)}))}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class Ys extends Lt{constructor(){super(...arguments),this.listeners=new Set}observe(t,e){return super.observe(t,e)}unObserve(t){super.unObserve(t)}emit(t,e){this.updateObservers(xs,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=Zt.logCtx(this.updateObservers,void 0,!1,...i);(await Promise.allSettled(this.observers.filter((s=>{const{filter:i}=s;if(!i)return!0;try{return i(t,e,r,...o)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((t=>{t.observer.refresh(s,...o)})))).forEach(((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}function Gs(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class qs extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class Hs extends qs{constructor(t,e,r){super(Hs.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class zs extends qs{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(zs.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class Ws extends qs{constructor(t,e,r){super(Ws.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class Qs extends qs{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(Qs.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class Vs{constructor(t,e){this.bus=t,this.task=e,this.resolved=!1,this.unregistration=t.observe(this,((t,e,r,...s)=>r.startsWith(this.task.id)&&(t===xs||t===q.tableName(xs)))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([Ne.SUCCEEDED,Ne.FAILED,Ne.CANCELED,Ne.SCHEDULED])}wait(){return this.awaitStatusTerminal([Ne.SUCCEEDED,Ne.FAILED,Ne.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Ps(t,e))}logs(t){this.pipe((async e=>{if(e.classification!==Be.LOG)return;const r=(e.payload??[]).map((t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]));await t(r)}),Be.LOG)}pipe(t,e=Be.ALL){this.pipes=this.pipes||{},this.pipes[e]=this.pipes[e]||new Set,this.pipes[e].add(t)}succeed(t){this.complete()}fail(t){this.complete()}cancel(t){t.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(Ne.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(Ne.FAILED,t)}onCancel(t){return this.registerStatusHandler(Ne.CANCELED,t)}awaitStatusTerminal(t){return new Promise(((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===Ne.SUCCEEDED?e(this.extractOutput(t)):r(this.extractError(t))}catch(t){r(t)}}};t.forEach((t=>{const e=this.registerStatusHandler(t,n);s.push(e)}))}))}extractOutput(t){return void 0!==t.payload?.output?t.payload.output:this.task.output}extractError(t){const e=t.payload?.status??this.task.status,r=this.getNextAction(e),s=t.payload?.originalError;if(s instanceof Error)return this.assignNextAction(s,r);const i=this.buildMeta(e,t.payload),n=this.createTaskControlError(e,t.payload?.error??this.task.error,i);return this.assignNextAction(n,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[Ne.SUCCEEDED,Ne.CANCELED,Ne.FAILED].includes(t)}async track(t,e){if(!t.payload)return;const r=t.payload.status;this.task.status=r,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),r!==Ne.SUCCEEDED?(r===Ne.FAILED&&this.fail(),r===Ne.CANCELED&&this.cancel(t),r===Ne.WAITING_RETRY&&this.retry(),r===Ne.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,e){const r=async(r,s)=>{r.payload?.status===t&&await e(r,s)};if(this.pipe(r,Be.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Be.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new It),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===Ne.SUCCEEDED&&(e.output=this.task.output),t!==Ne.FAILED&&t!==Ne.CANCELED||!this.task.error||(e.error=this.task.error),this.task.nextRunAt&&(e.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(e.scheduledTo=this.task.scheduledTo),new xs({classification:Be.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case Ne.FAILED:return new Hs(this.task.id,e,r);case Ne.CANCELED:return new Ws(this.task.id,e,r);case Ne.WAITING_RETRY:return new zs(this.task.id,e,r);case Ne.SCHEDULED:return new Qs(this.task.id,e,r);default:return new Hs(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case Ne.CANCELED:return Ne.CANCELED;case Ne.WAITING_RETRY:return Ne.WAITING_RETRY;case Ne.SCHEDULED:return Ne.SCHEDULED;case Ne.FAILED:return Ne.FAILED;default:return}}buildMeta(t,e){const r={};if(e?.nextRunAt&&(r.nextRunAt=e.nextRunAt),e?.scheduledTo&&(r.scheduledTo=e.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===Ne.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,e){if(!this.pipes)return;const r=this.pipes[Be.ALL]?[...this.pipes[Be.ALL].values()]:[];r.push(...this.pipes[t.classification]?.values()||[]);for(const s of r)try{await s(t,e)}catch(r){e.logger.error(`Failed to trigger pipe ${s.name} for event ${t.classification}. discarding event`,r)}}}class Js extends $t{get Context(){return Us}get adapter(){return this.config.adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=Ie.forModel(Os,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=Ie.forModel(xs,this.config.adapter.alias)),this._events}static createTaskContext(t,e){const r=new Us(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new at,this.running=!1,this.config=Object.assign({},Fe,t,{bus:t.bus||new Ys,registry:t.registry||new Ms})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.CREATE,!0)).for(this.push);i.verbose("pushing task "+t.classification);const n=await this.tasks.create(t,s);return i.info(`${t.classification} task registered under ${n.id}`),e?{task:n,tracker:new Vs(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=Ne.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,e,...r)}}}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.READ,!0)).for(this.track);s.verbose("tracking task "+t);let i=await this.tasks.read(t,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${t}`),{task:i,tracker:new Vs(this.bus,i)}}async ensureTaskError(t,e){if(![Ne.FAILED,Ne.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await Fs(20);try{const t=await this.tasks.read(r.id,e);if(t.error)return t;r=t}catch{break}}return r}async cancel(t,...e){const{ctx:r}=(await this.logCtx(e,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,r);if(s.status===Ne.SUCCEEDED||s.status===Ne.FAILED)return s;s.status=Ne.CANCELED;const i=new As({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,r);return await this.emitStatus(r,n,Ne.CANCELED,i),n}async isRunning(){await this.lock.acquire();const t=this.running;return this.lock.release(),t}async start(...t){const{ctx:e}=(await this.logCtx(t,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||r.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(re.attr("status").eq(Ne.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise(((t,n)=>{const o=setTimeout((()=>{r.error(`Graceful shutdown interrupted after ${i} ms...`),t()}),i);Promise.allSettled(s.map((({id:t})=>new Promise(((r,s)=>{this.track(t,e).then((({tracker:t})=>{t.resolve().then(r)})).catch(s)}))))).then((e=>{clearTimeout(o),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()})).catch((t=>{clearTimeout(o),n(t)}))}))}async loop(...t){const{ctx:e}=this.logCtx(t,this.loop);for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map((t=>this.executeClaimed(t)))),await Fs(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=re.attribute("status").eq(Ne.PENDING),i=re.attribute("status").eq(Ne.WAITING_RETRY).and(re.attribute("nextRunAt").lte(r)),n=re.attribute("status").eq(Ne.RUNNING).and(re.attribute("leaseExpiry").lte(r)),o=re.attribute("status").eq(Ne.SCHEDULED).and(re.attribute("scheduledTo").lte(r)),a=s.or(i).or(n).or(o),c=await this.tasks.select().where(a).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+c.length);const l=[];for(const e of c){const r=await this.tryClaim(e,t);if(r&&l.push(r),l.length>=this.config.concurrency)break}return e.verbose("claimBatch claimed:"+l.length),l}async tryClaim(t,e){const r=e.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,e)}catch{}const n=new Os({...i,status:Ne.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=new Us(e).accumulate({taskId:t.id,logger:new Is(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(s,t,e);await this.emitLog(s,t.id,r)},flush:async()=>s.logger.flush(s.pipe),progress:async e=>{await this.emitProgress(s,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{}}}});await this.emitStatus(s,t,Ne.RUNNING);try{let e;if(t.atomicity===Re.COMPOSITE){e=await this.runComposite(t,s);try{t=await this.tasks.read(t.id,s)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const i=this.registry.get(t.classification);if(r.debug(`handler type for ${t.id} is ${i?.constructor?.name??"none"}`),!i)throw new u("No task handler registered for type: "+t.classification);e=await i.run(t.input,s),r.verbose("handler finished for "+t.id)}t.status=Ne.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),s.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,Ne.SUCCEEDED,e)}catch(e){try{t=await this.tasks.read(t.id,s)}catch{}if(e instanceof js)return void await this.handleTaskStateChange(e.request,t,s);if(r.error("task execution error",e),t.atomicity===Re.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex((t=>t.status===Ne.FAILED));0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=Ls(e);if(i<t.maxAttempts){const o=$s(i,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+o);t.attempt=i,t.status=Ne.WAITING_RETRY,t.nextRunAt=a,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await s.pipe(Y.warn,"Retry scheduled",{nextRunAt:a,delayMs:o,attempt:i}),await this.emitStatus(s,t,Ne.WAITING_RETRY,n,e)}else t.attempt=i,t.status=Ne.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await s.pipe(Y.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(s,t,Ne.FAILED,n,e)}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case Ne.CANCELED:{const s=t.error??new As({message:`Task ${e.id} canceled`});return e.status=Ne.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.CANCELED,s),void await r.pipe(Y.warn,"Task canceled via context")}case Ne.WAITING_RETRY:{const s=(e.attempt??0)+1,i=$s(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new As({message:`Task ${e.id} requested retry`});return e.status=Ne.WAITING_RETRY,e.attempt=s,e.error=o,e.nextRunAt=n,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.WAITING_RETRY,o),void await r.pipe(Y.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case Ne.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new As({message:`Task ${e.id} rescheduled`});return e.status=Ne.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ne.SCHEDULED,s),void await r.pipe(Y.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new u("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),o=(t,s)=>{e.cacheResult(t,s),r instanceof Us&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===Ne.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;o(i.classification,r.output),o(n,r.output)}}for(;i<s.length;){const r=s[i],a=this.registry.get(r.classification);if(!a)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([Y.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await a.run(r.input,e),l=i,u=new Date;n[l]=new Cs({status:Ne.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;o(r.classification,c),o(d,c),i=l+1,t.stepResults=n,t.currentStep=i,t=await this.tasks.update(t),await this.emitProgress(e,t.id,{currentStep:i,totalSteps:s.length,output:c})}catch(e){const r=new Date;throw n[i]=new Cs({status:Ne.FAILED,error:Ls(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=Ls(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof vs)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new vs(e)}normalizeSteps(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map((t=>{if(t instanceof Ts)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Ts(e)})):[]}normalizeStepResults(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map((t=>{if(t instanceof Cs)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Cs(e)})):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map((([t,e,r])=>new Ss({level:t,msg:e,meta:r}))),i=[...e.logTail??[],...s].slice(-this.config.logTailMax);e.logTail=i;try{return[await this.tasks.update(e,t),s]}catch{return[e,[]]}}async emitStatus(t,e,r,s,i){t instanceof Us&&await t.flush();const n={status:r};s&&s instanceof As?n.error=s:s&&(n.output=s),e.nextRunAt&&(n.nextRunAt=e.nextRunAt),e.scheduledTo&&(n.scheduledTo=e.scheduledTo);const o=await this.persistEvent(t,e.id,Be.STATUS,n),a=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new xs({...o,payload:a});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Be.LOG,r.map((t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta}))));this.bus.emit(s,t)}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,Be.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new xs({taskId:e,classification:r,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,e,...r){return this.adapter.context(t,e,Os,...r)}}class Xs extends es{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof It)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new(e.engine||Js)(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.CREATE,!0)).for(this.push),i=await this.client.push(t,e,...s);return await this.client.isRunning()||this.client.start(),i}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.CREATE,!0)).for(this.create),s=await this.repo.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){throw new Ft("Updates to tasks are not available")}async updateAll(t,...e){throw new Ft("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo._adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}async shutdown(...t){const{ctxArgs:e,ctx:r,log:s}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...e),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(r),s.verbose("gracefully shutdown task runner")}}function Ks(t={count:1},e=0){return function r(s,i,n){return pt(ft(ut.key(Ct.THROTTLE,i),t),((s,i,n)=>{n.value=new Proxy(n.value,{async apply(s,n,o){const a=o,c=(()=>{try{return"function"==typeof t?t(...a):t}catch(t){throw new u("Failed to obtain throttling configuration from handler: "+t)}})(),{log:l,ctx:d}=(await n.logCtx(o,Ct.THROTTLE,!0)).for(r),h=(t=>{const e=(Array.isArray(t)?t:[t]).map((t=>{if(!Number.isFinite(t)||0>t)throw new u("@throttling() argument indexes must be non-negative integers");return t}));return Array.from(new Set(e)).sort(((t,e)=>t-e))})(e);if(!h.length)throw new u("@throttling() expects at least one argument index to throttle");h.forEach((t=>{if(t>=a.length)throw new u(`@throttling() requires argument index ${t} but only ${a.length} provided`);if(!Array.isArray(a[t]))throw new u(`@throttling() expects argument at index ${t} to be an array`)}));const p=h.map((t=>a[t])),g=p[0].length;if(!p.every((t=>t.length===g)))throw new u("@throttling() requires all targeted arguments to have the same length");if(0===g)return s.apply(n,a);const f=((t,e,r)=>{if("count"in r){if(0>=r.count)throw new u("@throttling() configuration 'count' must be greater than zero");const e=[];for(let s=0;t>s;s+=r.count)e.push({start:s,end:Math.min(t,s+r.count)});return e}if("bufferSize"in r){if(0>=r.bufferSize)throw new u("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let o=0;t>o;o++){const t=Zs(e,o);n>0&&n+t>r.bufferSize?(s.push({start:i,end:o}),i=o,n=t):n+=t}return i>=t&&s.length||s.push({start:i,end:t}),s}return[{start:0,end:t}]})(g,p,c),y=f.map((({start:t,end:e})=>a.map(((r,s)=>{const i=h.indexOf(s);return-1===i?r:p[i].slice(t,e)})))),m=d.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const t of y){try{v=await s.apply(n,t),A=w,Array.isArray(v)?A.push(...v):void 0!==v&&A.push(v)}catch(t){if(m)throw t;b.push(t)}c.delayMs&&await new Promise((t=>setTimeout(t,c.delayMs)))}var v,A;if(b.length){l.warn(`${i+""} throttled execution continued with ${b.length} failure(s)`);const t=new AggregateError(b,`Throttled ${i+""} failed for ${b.length} chunk(s)`);throw t.results=w,t}return w}})}))(s,i,n)}}function Zs(t,e){return t.reduce(((t,r)=>t+(t=>{if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}})(r[e])),0)}i([je(Os),n("design:type",Object)],Xs.prototype,"repo",void 0),i([ss(),n("design:type",Function),n("design:paramtypes",[Os,void 0]),n("design:returntype",Promise)],Xs.prototype,"create",null),i([ss(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"createAll",null),i([os(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Xs.prototype,"delete",null),i([os(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"deleteAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Xs.prototype,"read",null),i([is(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"readAll",null),i([is(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],Xs.prototype,"query",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Os,void 0]),n("design:returntype",Promise)],Xs.prototype,"update",null),i([ns(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Xs.prototype,"updateAll",null),e.setRegistry(new $e);const ti="##VERSION##",ei="##PACKAGE##";ut.registerLibrary(ei,ti);export{$t as AbsContextual,Zt as Adapter,Qt as AdapterTransaction,Me as AuthKeys,Ar as AuthorizationError,De as BackoffStrategy,Gr as BaseModel,We as BigIntSequence,ie as Cascade,Rs as CleanUpTask,es as ClientBasedService,Ds as CompositeTaskBuilder,re as Condition,Er as ConnectionError,It as Context,Vt as ContextLock,Pt as ContextualLoggedClass,kt as DefaultAdapterFlags,ne as DefaultCascade,Tt as DefaultContextFlags,Ae as DefaultRepositoryFilters,He as DefaultSequenceOptions,Fe as DefaultTaskEngineConfig,ps as Dispatch,xr as ForbiddenError,St as GroupOperator,$e as InjectablesRegistry,_e as JitterStrategy,ce as MethodQueryBuilder,jt as MigrationError,Ut as MigrationRuleError,hs as ModelService,Bt as MultipleSelectOperationKeys,Dt as NonTransactionOperationKeys,qe as NoneSequenceOptions,ze as NumericSequence,Ue as ObserverError,Lt as ObserverHandler,Et as Operator,oe as OperatorsMap,se as OrderDirection,ei as PACKAGE_NAME,Rt as PaginationOperationKeys,Hr as Paginator,ee as PagingError,Ct as PersistenceKeys,bs as PersistenceService,Ot as PreparedStatementKeys,xt as QueryClause,te as QueryError,Ie as Repository,_t as SelectOperationKeys,ys as Sequence,qr as SequenceModel,Wt as Serial,ts as Service,Zr as Statement,ks as TaskBackoffBuilder,vs as TaskBackoffModel,Ns as TaskBuilder,Ws as TaskCancelError,Us as TaskContext,qs as TaskControlError,Js as TaskEngine,As as TaskErrorModel,Ys as TaskEventBus,xs as TaskEventModel,Be as TaskEventType,Hs as TaskFailError,_s as TaskHandler,Ms as TaskHandlerRegistry,Es as TaskIOSerializer,Ss as TaskLogEntryModel,Is as TaskLogger,Os as TaskModel,Qs as TaskRescheduleError,zs as TaskRetryError,Xs as TaskService,Ne as TaskStatus,Cs as TaskStepResultModel,Ts as TaskStepSpecModel,Vs as TaskTracker,Re as TaskType,Le as TasksKey,Nt as TransactionOperationKeys,zt as UUID,Ft as UnsupportedError,ti as VERSION,Ye as allowIf,he as applyViewDecorator,cs as auth,Ge as blockIf,yr as cacheModelForPopulate,wr as cascadeDelete,Or as column,$s as computeBackoffMs,ss as create,Ke as createOrUpdate,_r as createdAt,Nr as createdBy,kr as createdByOnCreateUpdate,le as defaultQueryAttr,os as del,Pe as generateInjectableNameForRepository,ms as getAdapterTransaction,dr as getAndConstructJunctionTable,ws as getContextLock,xe as getFilters,Ps as getLogPipe,Rr as getPkTypes,gr as getPopulateKey,fr as getTagForDeleteKey,Qe as index,Mt as injectableServiceKey,Gt as isOperationBlocked,Gs as isTaskError,Lr as manyToMany,lr as manyToManyOnCreate,pr as manyToManyOnDelete,hr as manyToManyOnUpdate,$r as manyToOne,nr as manyToOneOnCreate,cr as manyToOneOnDelete,ar as manyToOneOnUpdate,Fr as noValidateOn,jr as noValidateOnCreate,Mr as noValidateOnCreateUpdate,Ur as noValidateOnUpdate,qt as normalizeImport,Pr as oneToMany,rr as oneToManyOnCreateUpdate,ir as oneToManyOnDelete,sr as oneToManyOnUpdate,Ir as oneToOne,Ze as oneToOneOnCreate,er as oneToOneOnDelete,tr as oneToOneOnUpdate,be as onlyOnBulk,ge as onlyOnCreate,ye as onlyOnDelete,ve as onlyOnFilter,we as onlyOnSingle,me as onlyOnTransactional,fe as onlyOnUpdate,Xe as pk,Je as pkDec,Ve as pkOnCreate,mr as populate,Ht as prefixMethod,ue as prepared,Yt as promiseSequence,de as query,is as read,Yr as relation,je as repository,vr as repositoryFromTypeMetadata,ls as roles,us as route,Ls as serializeError,as as service,Fs as sleep,Sr as table,Bs as task,Ks as throttle,Tr as unique,Cr as uniqueOnCreateUpdate,ns as update,Br as updatedAt,Dr as updatedBy,fs as uuid,gs as uuidCreateUpdateHandler,or as validBidirectionalRelation,pe as view};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|