@decaf-ts/core 0.8.30 → 0.8.32
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/README.md +1 -1
- 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/identity/decorators.js +1 -1
- package/lib/esm/identity/decorators.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/model/SequenceModel.js +2 -1
- package/lib/esm/model/SequenceModel.js.map +1 -1
- package/lib/esm/model/construction.d.ts +13 -0
- package/lib/esm/model/construction.js +286 -1
- package/lib/esm/model/construction.js.map +1 -1
- package/lib/esm/model/decorators.d.ts +1 -20
- package/lib/esm/model/decorators.js +9 -41
- package/lib/esm/model/decorators.js.map +1 -1
- package/lib/esm/model/index.d.ts +1 -0
- package/lib/esm/model/index.js +1 -0
- package/lib/esm/model/index.js.map +1 -1
- package/lib/esm/model/indexing.d.ts +20 -0
- package/lib/esm/model/indexing.js +37 -0
- package/lib/esm/model/indexing.js.map +1 -0
- package/lib/esm/persistence/Adapter.js +4 -2
- package/lib/esm/persistence/Adapter.js.map +1 -1
- package/lib/esm/repository/decorators.js +2 -1
- package/lib/esm/repository/decorators.js.map +1 -1
- package/lib/esm/tasks/TaskEngine.js +12 -5
- package/lib/esm/tasks/TaskEngine.js.map +1 -1
- package/lib/esm/tasks/TaskTracker.d.ts +2 -0
- package/lib/esm/tasks/TaskTracker.js +26 -3
- package/lib/esm/tasks/TaskTracker.js.map +1 -1
- package/lib/esm/tasks/builder.d.ts +3 -1
- package/lib/esm/tasks/builder.js +11 -3
- package/lib/esm/tasks/builder.js.map +1 -1
- package/lib/esm/tasks/models/TaskIOSerializer.d.ts +8 -2
- package/lib/esm/tasks/models/TaskIOSerializer.js +70 -30
- package/lib/esm/tasks/models/TaskIOSerializer.js.map +1 -1
- package/lib/esm/tasks/models/TaskModel.d.ts +1 -0
- package/lib/esm/tasks/models/TaskModel.js +5 -0
- package/lib/esm/tasks/models/TaskModel.js.map +1 -1
- package/lib/identity/decorators.cjs +2 -2
- package/lib/identity/decorators.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/model/SequenceModel.cjs +2 -1
- package/lib/model/SequenceModel.js.map +1 -1
- package/lib/model/construction.cjs +293 -0
- package/lib/model/construction.d.ts +13 -0
- package/lib/model/construction.js.map +1 -1
- package/lib/model/decorators.cjs +7 -40
- package/lib/model/decorators.d.ts +1 -20
- package/lib/model/decorators.js.map +1 -1
- package/lib/model/index.cjs +1 -0
- package/lib/model/index.d.ts +1 -0
- package/lib/model/index.js.map +1 -1
- package/lib/model/indexing.cjs +40 -0
- package/lib/model/indexing.d.ts +20 -0
- package/lib/model/indexing.js.map +1 -0
- package/lib/persistence/Adapter.cjs +4 -2
- package/lib/persistence/Adapter.js.map +1 -1
- package/lib/repository/decorators.cjs +4 -3
- package/lib/repository/decorators.js.map +1 -1
- package/lib/tasks/TaskEngine.cjs +12 -5
- package/lib/tasks/TaskEngine.js.map +1 -1
- package/lib/tasks/TaskTracker.cjs +26 -3
- package/lib/tasks/TaskTracker.d.ts +2 -0
- package/lib/tasks/TaskTracker.js.map +1 -1
- package/lib/tasks/builder.cjs +10 -2
- package/lib/tasks/builder.d.ts +3 -1
- package/lib/tasks/builder.js.map +1 -1
- package/lib/tasks/models/TaskIOSerializer.cjs +70 -30
- package/lib/tasks/models/TaskIOSerializer.d.ts +8 -2
- package/lib/tasks/models/TaskIOSerializer.js.map +1 -1
- package/lib/tasks/models/TaskModel.cjs +5 -0
- package/lib/tasks/models/TaskModel.d.ts +1 -0
- package/lib/tasks/models/TaskModel.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,generated as v,onCreate as x,onUpdate as A,readonly as E,BadRequestError as O,ConflictError as C,onCreateUpdate as T,timestamp as N,onDelete as k,afterUpdate as B,afterAny as _,SerializationError as D,prefixMethod as R,composed as I,transient as $,serialize as P,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 H,hashObj as q,required as z,sf as Q,isEqual as V,ValidationKeys as W,async as X,type as J,list as Z,model 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}from"@decaf-ts/transactional-decorators";import{Metadata as lt,Decoration as ut,DefaultFlavour as dt,propMetadata as ht,apply as pt,methodMetadata as gt,DecorationKeys as ft,uses as yt,metadata as mt,prop as wt,description as bt}from"@decaf-ts/decoration";var vt,xt,At,Et,St;(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"})(vt||(vt={})),(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.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(xt||(xt={})),(t=>{t.AND="AND",t.OR="OR"})(At||(At={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",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"})(Et||(Et={})),(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"})(St||(St={}));const Ot=Object.assign({},{ignoreDevSafeGuards:!1}),Ct=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),Tt=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Nt=[a.READ,c.READ_ALL],kt=[St.STATEMENT,Et.FIND_ONE_BY],Bt=[St.QUERY,Et.PAGE_BY,Et.LIST_BY,Et.FIND_BY],_t=[Et.PAGE_BY];class Dt extends at{constructor(){super()}}class Rt 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){const e=this.getOrUndefined(t);if(e)return e;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map((e=>e.getFromChildren(t))).flat().reduce(((t,e)=>Object.assign(t,e)),{}):void 0}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 It extends F{logCtx(t,e,r=!1,s){return It.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 Rt;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 It{constructor(){super(),this._Context=Rt}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 Rt||(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 Pt{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}=It.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 Lt extends u{constructor(t){super(t,Lt.name,500)}}class Ft extends u{constructor(t,e=Ft.name){super(t,e,500)}}class jt extends Ft{constructor(t){super(t,jt.name)}}function Ut(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):lt.Symbol(lt.constr(t)).toString().replaceAll(".","-")}function Mt(t){return t.reduce(((t,e)=>t.then((async t=>[...t,await e()]))),Promise.resolve([]))}function Yt(t,e){const{handler:r,args:s}=lt.get(t,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function Gt(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 jt)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 qt{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 qt._instance||(qt._instance=new qt),qt._instance}}class zt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return zt._instance||(zt._instance=new zt),zt._instance}}const Qt=ut.flavourResolver.bind(ut);ut.flavourResolver=t=>{try{const e=Qt(t);if(e&&e!==dt)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof lt.registeredFlavour?lt.registeredFlavour(r):void 0;if(s&&s!==dt)return s;const i=Vt._currentFlavour;if(i){const t=Vt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return dt}};class Vt extends $t{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Vt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return Vt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(...t){(await this.logCtx(t,St.SHUTDOWN,!0)).for(this.shutdown),await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.alias in Vt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Vt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Vt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Vt._currentFlavour=this.alias)}Dispatch(){return new Vt._baseDispatch}ObserverHandler(){return new Pt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new Vt._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?H.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${qt.instance.generate()}`;const o=r.logger||j.for(this);return Object.assign({},Ct,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:Tt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?lt.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}get Context(){return Rt}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=>H.tableName(t))):H.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 Rt||(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.get("operation"),s=i.getOrUndefined("affectedTables");if(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=H.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[St.METADATA]&&(r.silly("Passing along persistence metadata for "+t[St.METADATA]),Object.defineProperty(i,St.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[St.METADATA]})),{record:i,id:t[H.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=H.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[St.METADATA],d=Object.keys(c).filter((t=>t!==a)).reduce(((r,s)=>(r[s]=t[H.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,St.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=H.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Mt(e.map(((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})))))}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=H.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Mt(e.map((e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0})))))}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=H.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Mt(e.map(((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})))))}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${e.length} entries from ${t} table`),Mt(e.map((e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})))))}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 lt.flavourOf(t)}static get currentFlavour(){if(!Vt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return Vt._currentFlavour}static get current(){return Vt.get(this.currentFlavour)}static get(t){if(!t)return Vt.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 lt.flavouredAs(t).filter(H.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} - ${q(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 this.proxies[r]=i,i}migrations(){return lt.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",[String]),n("design:returntype",Promise)],Vt.prototype,"shutdownProxies",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,Rt]),n("design:returntype",Promise)],Vt.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Vt.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Vt.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Vt.prototype,"client",null);class Wt extends u{constructor(t){super(t,Wt.name,500)}}class Xt extends u{constructor(t){super(t,Xt.name,500)}}class Jt extends H{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):H.fromModel(this,t)}and(t){return Jt.and(this,t)}or(t){return Jt.or(this,t)}not(t){return new Jt(this,xt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Jt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(xt).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===xt.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 Jt){if(!(this.comparison instanceof Jt)&&this.operator!==xt.NOT)return{comparison:{condition:t}};if(-1===Object.values(At).indexOf(this.operator)&&this.operator!==xt.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 Jt.group(t,At.AND,e)}static or(t,e){return Jt.group(t,At.OR,e)}static group(t,e,r){return new Jt(t,e,r)}static attribute(t){return(new Jt.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(xt.EQUAL,t)}dif(t){return this.setOp(xt.DIFFERENT,t)}gt(t){return this.setOp(xt.BIGGER,t)}lt(t){return this.setOp(xt.SMALLER,t)}gte(t){return this.setOp(xt.BIGGER_EQ,t)}lte(t){return this.setOp(xt.SMALLER_EQ,t)}in(t){return this.setOp(xt.IN,t)}regexp(t){return this.setOp(xt.REGEXP,RegExp(t).source)}between(t,e){return this.setOp(xt.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Jt(this.attr1,this.operator,this.comparison)}catch(t){throw new Wt(t)}}}}static builder(){return new Jt.Builder}static from(t){return new Jt(t)}}var Kt,Zt;i([z(),n("design:type",Object)],Jt.prototype,"attr1",void 0),i([z(),n("design:type",String)],Jt.prototype,"operator",void 0),i([z(),n("design:type",Object)],Jt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(Kt||(Kt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Zt||(Zt={}));const te={update:Zt.CASCADE,delete:Zt.NONE},ee={Equals:(t,e)=>Jt.attribute(t).eq(e),Diff:(t,e)=>Jt.attribute(t).dif(e),LessThan:(t,e)=>Jt.attribute(t).lt(e),LessThanEqual:(t,e)=>Jt.attribute(t).lte(e),GreaterThan:(t,e)=>Jt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Jt.attribute(t).gte(e),In:(t,e)=>Jt.attribute(t).in(e),Matches:(t,e)=>Jt.attribute(t).regexp(e)},re=t=>t.charAt(0).toLowerCase()+t.slice(1);class se extends F{static get log(){return this._logger||(this._logger=j.for(se.name)),this._logger}static{this.prefixMap={[vt.FIND_BY]:"find",[vt.PAGE_BY]:"page",[vt.COUNT_BY]:"count",[vt.SUM_BY]:"sum",[vt.AVG_BY]:"avg",[vt.MIN_BY]:"min",[vt.MAX_BY]:"max",[vt.DISTINCT_BY]:"distinct",[vt.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?re(i):void 0}static extractCore(t,e=vt.FIND_BY){const r=t.substring(e.length);if(e!==vt.FIND_BY&&e!==vt.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||vt.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(vt.SELECT);if(-1===e)return;const r=t.substring(e+vt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(vt.AND).map(re).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(vt.GROUP_BY);if(-1!==e)return t.substring(e+vt.GROUP_BY.length).split(vt.ORDER_BY)[0].split(vt.THEN_BY).map(re).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(vt.THEN_BY);if(-1===s)return;const i=e.substring(s+vt.THEN_BY.length).split(vt.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(re(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?ee[o]:ee.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]===vt.AND?n.and(l):n.or(l)})),n}static parseFieldAndOperator(t){for(const e of Object.keys(ee))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:re(r),operator:e}}return{field:re(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=se.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new Wt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(Kt).includes(e))throw new Wt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(Kt).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 ie(){return ut.for(St.STATEMENT).define({decorator:()=>(t,e,r)=>pt(gt(lt.key(St.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function ne(t={}){return ut.for(St.QUERY).define({decorator:t=>(e,r,s)=>{const i=se.getFieldsFromMethodName(r);return pt(gt(lt.key(St.QUERY,r),{...t,fields:i}),ie(),(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}=se.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 Wt("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 Wt(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 oe(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(lt.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=lt.key(t,i,n),a={...r||{},kind:e,attribute:i};return ht(o,a)(s,i)}}function ae(t){return ut.for(xt.VIEW).define({decorator:t=>oe(xt.VIEW,"view",t),args:[t]}).apply()}function ce(t){return ge(t,[a.CREATE,c.CREATE_ALL])}function le(t){return ge(t,[a.UPDATE,c.UPDATE_ALL])}function ue(t){return ge(t,[a.DELETE,c.DELETE_ALL])}function de(t){return ge(t,Tt)}function he(t){return ge(t,Object.values(a))}function pe(t){return ge(t,Object.values(c))}function ge(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}=It.prototype.logCtx(n,ge);return o.silly(`filtering ${s} event for${r?" "+(H.tableName(r)||r):""} ${i}`),("string"==typeof r?r===H.tableName(t)||r===t.constructor.name:lt.constr(t)===lt.constr(r))&&e.includes(s)}}const fe={onlyOnCreate:ce,onlyOnUpdate:le,onlyOnDelete:ue,onlyOnTransactional:de,onlyOnSingle:he,onlyOnBulk:pe};function ye(t){const e=Object.assign({},fe);return Object.entries(e).forEach((([r,s])=>{e[r]=s(t.class)})),e}var me,we,be,ve,xe,Ae,Ee,Se,Oe,Ce,Te;class Ne 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=H.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ye(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&&(Ne.register(e,this,this.adapter.alias),t)&<.get(e,ft.FLAVOUR)===dt&&yt(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 Pt}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 ${H.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 ${H.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=H.sequenceFor(t[0]);let h=[];if(H.generatedBySequence(this.class)?(l.name||(l.name=H.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l)).range(t.length,...s)):H.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 ${H.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 ${H.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 ${H.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=H.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 ${H.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)=>H.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 ${H.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 ${H.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=Kt.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,St.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,Et.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${H.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 Wt("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Et.PAGE_BY,!0)).for(this.paginateBy);let d;if(c.verbose(`paginating ${H.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Kt.ASC?this.attr(H.pk(this.class)).gt(o):this.attr(H.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new Wt("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 findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Et.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${H.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,Et.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${H.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,Et.COUNT_OF,!0)).for(this.countOf);return r.verbose(`counting ${H.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.MAX_OF,!0)).for(this.maxOf);return r.verbose(`finding max of ${t} in ${H.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.MIN_OF,!0)).for(this.minOf);return r.verbose(`finding min of ${t} in ${H.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.AVG_OF,!0)).for(this.avgOf);return r.verbose(`calculating average of ${t} in ${H.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.SUM_OF,!0)).for(this.sumOf);return r.verbose(`calculating sum of ${t} in ${H.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.DISTINCT_OF,!0)).for(this.distinctOf);return r.verbose(`finding distinct values of ${t} in ${H.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.GROUP_OF,!0)).for(this.groupOf);return r.verbose(`grouping ${H.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...e){if(!Ne.statements(this,t))throw new Wt("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,St.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}attr(t){return Jt.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:lt.constr(t)===lt.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=>Vt._baseSequence.parseValue(H.sequenceFor(this.class).type,t))):Vt._baseSequence.parseValue(H.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||lt.flavourOf(t)||Vt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ne)return s;const n=e||lt.flavourOf(t)||s&<.get(s,St.ADAPTER)||Vt.currentFlavour,o=n?Vt.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=H.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=H.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof Ne)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ne?t.constructor:t,s=lt.get(r,e?lt.key(St.STATEMENT,e):St.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ne?t.constructor:t;return lt.get(r,e?lt.key(St.QUERY,e):St.QUERY)}}function ke(t,e){if(!(e||(e=ut.flavourResolver(t instanceof H?t.constructor:t))&&e!==dt))throw new u("Could not retrieve flavour from model "+(t instanceof H?t.constructor.name:t.name));return Q(St.INJECTABLE,e,H.tableName(t))}i([ie(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ne.prototype,"listBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"paginateBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"findOneBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"findBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"countOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(me="undefined"!=typeof K&&K)?me:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"maxOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(we="undefined"!=typeof K&&K)?we:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"minOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(be="undefined"!=typeof K&&K)?be:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"avgOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ve="undefined"!=typeof K&&K)?ve:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"sumOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(xe="undefined"!=typeof K&&K)?xe:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"distinctOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ae="undefined"!=typeof K&&K)?Ae:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"groupOf",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Ne.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ne.prototype,"unObserve",null),Vt&&(Vt._baseRepository=Ne);class Be 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=H.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=H.get(t.toString())),!n)return;const o=St.ADAPTER,a=r||lt.get(n,o);try{let t=a;try{a&&Vt.get(a)}catch{const e=Vt.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ne.forModel(n,t),i instanceof Ne)return i;const r=a||lt.get(i.constructor,o)||lt.get(n,o);e.register(i,ke(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=Ne.get(n,a);if("function"==typeof e){const t=a?Vt.get(a):Vt.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"})(Ee||(Ee={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(Se||(Se={})),(t=>{t.NONE="none",t.FULL="full"})(Oe||(Oe={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Ce||(Ce={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Te||(Te={}));const _e="tasks",De={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};lt.tasks=(()=>lt.innerGet(Symbol.for(_e))).bind(lt),lt.taskFor=(t=>{const e=lt.tasks();return e?e[t]:void 0}).bind(lt),lt.validationExceptions=((t,e)=>{const r=lt.get(t,St.NO_VALIDATE)||[],s=Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t));let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=H.nestedRelations(t)),[...new Set([...s,...i])]}).bind(lt),lt.migrationsFor=(t=>{if(!(t=t??Vt.current))throw new u("Could not get adapter for migrations");return lt.innerGet(Symbol.for(St.MIGRATION),t.alias).map((t=>t.class))}).bind(lt),lt.migrations=(()=>{const t=lt.innerGet(Symbol.for([St.MIGRATION,St.BY_KEY].join("-")));return Object.values(t).flat().map((t=>[t.class.name,t.class]))}).bind(lt),lt.relations=((t,e)=>{const r=lt.get(t,St.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(lt),H.relations=(t,e)=>lt.relations(t instanceof H?t.constructor:t,e)||[],H.nestedRelations=((t,e=[])=>{let r=[];const s=lt.get(t,St.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&H.relations(i.class)){const s=H.relations(i.class).map((e=>`${t}.${e}`));e=[...e,...s],r=H.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(H),H.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!H.sequenceFor(r).generated}).bind(H),H.fromTable=(t=>{const e=lt.innerGet(Symbol.for(St.TABLE));if(!e||!e[t]||!H.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return H.get(e[t].name)}).bind(H),lt.createdBy=(t=>{const e=lt.get("function"!=typeof t?t.constructor:t,St.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(lt),lt.updatedBy=(t=>{const e=lt.get("function"!=typeof t?t.constructor:t,St.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(lt),H.tableName=t=>{if(!(t instanceof H?H.get(t.constructor.name):t))throw new u("Unable to find model "+t);return lt.get(t instanceof H?t.constructor:t,St.TABLE)||(t instanceof H?t.constructor.name:t.name)},H.columnName=(t,e)=>lt.get(t instanceof H?t.constructor:t,lt.key(St.COLUMN,e))||e,H.sequenceName=(t,...e)=>[H.tableName(t),...e].join("_"),H.sequenceFor=(t,e)=>{if(e)throw new Lt("not currently supported");const r=H.pkProps(t instanceof H?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},H.indexes=t=>{const e=lt.get(t instanceof H?t.constructor:t,St.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[St.INDEX]:e[r]},t)),{})},e.services=()=>lt.innerGet(Symbol.for(St.SERVICE)),e.repositories=()=>lt.innerGet(Symbol.for(b.REPOSITORY));class Re extends It{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,St.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(){}observe(t){if(!(t instanceof Vt))throw new Lt("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=Vt.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 Lt("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:H.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 Ie(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 qt.instance.generate(i)}function $e(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=St.UUID;return ut.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[z(),v(St.UUID),x(Ie,s,{priority:54})];return t&&i.push(A(Ie,s,{priority:54})),t||i.push(E()),pt(...i)},args:[t,e,...r]}).apply()}async function Pe(t,e,r,s,i){const n=e.logger.for(Pe);if(!s){const e=H.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=Ne.forModel(e,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===t[H.pk(s.class)])n.info(`No pk found in ${H.tableName(s.class)} - creating`),o=await s.create(t,e);else{n.info(`pk found in ${H.tableName(s.class)} - attempting update`);try{o=await s.update(t,e),n.info("Updated "+H.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+H.tableName(s.class)),o=await s.create(t,e)}n.info("After create update: "+o)}return o}async function Le(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=We(s,r,this.adapter.alias),n=await e.read(i,t);return await qe(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=Ne.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=H.pk(a);await qe(t,s,r,a[c],a),s[r]=a[c]}async function Fe(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;if("object"!=typeof i){const e=We(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await qe(t,s,r,i,n),void(s[r]=i)}const n=await Pe(s[r],t,this.adapter.alias,void 0,this._overrides),o=H.pk(n);await qe(t,s,r,n[o],n),s[r]=n[o]}async function je(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;const n=We(s,r,this.adapter.alias);let o;o=i instanceof H?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await qe(t,s,r,o[n.pk],o)}async function Ue(t,e,r,s){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=t.logger.for(Ue),a=new Set([...i]);if("object"!==n){const e=We(s,r,this.adapter.alias),i=await e.readAll([...a.values()],t);for(let e=0;e<i.length;e++){const s=i[e];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await qe(t,s,r,[...a.values()][e],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=H.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Pe(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await qe(t,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(e)),l.add(i[c])}s[r]=[...l]}async function Me(t,e,r,s){const{cascade:i}=e;if(i.update===Zt.CASCADE)return Ue.call(this,t,e,r,s)}async function Ye(t,e,r,s){if(e.cascade.delete!==Zt.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?Ne.forModel(o,this.adapter.alias):We(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.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 qe(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 Ge(t,e,r){return[St.POPULATE,t,e,r].join(".")}function He(t,e,r){return[St.TAG_FOR_DELETION,t,r].join(".")}async function qe(t,e,r,s,i){const n=Ge(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function ze(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=await(async(e,r,s,i)=>{let n,o;const a=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=Ge(r.constructor.name,s,e);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=We(r,s);if(!n)throw new u("Could not find repo");o=await n.read(e,t)}a.push(o)}return a})(t,s,r,n?i:[i]);s[r]=n?o:o[0]}async function Qe(t,e,r,s,i){if(e.cascade.update!==Zt.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[H.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=We(s,r);if(!h)throw new u("Could not find repo");try{const e=await h.deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${H.tableName(h.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}Vt&&(Vt._baseDispatch=Re);const Ve=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function We(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=lt.get(t instanceof H?t.constructor:t,lt.key(W.REFLECT,e,W.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=lt.getPropDesignTypes(t instanceof H?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!Ve.includes((""+t.name).toLowerCase())));return Ne.forModel(i,r)}class Xe extends O{constructor(t,e=Xe.name,r=401){super(t,e,r)}}class Je extends Xe{constructor(t,e=Je.name){super(t,e,403)}}class Ke extends u{constructor(t){super(t,Ke.name,503)}}function Ze(t){return ut.for(St.TABLE).define({decorator:t=>e=>(lt.set(St.TABLE,t||e.name.toLowerCase(),e),mt(St.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function tr(t){return ut.for(St.COLUMN).define({decorator:t=>(e,r)=>ht(lt.key(St.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function er(t,e,r){return ut.for(St.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=>![Kt.ASC,Kt.DSC].includes(t)))&&(e=t,t=void 0),ht(lt.key(`${St.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function rr(t,e,r,s){if(s[r]&&(await this.select().where(Jt.attribute(r).eq(s[r])).execute()).length)throw new C(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function sr(){const t=St.UNIQUE;return ut.for(t).define(X(),T(rr),ht(t,{})).apply()}async function ir(t,e,r,s){throw new Xe("This adapter does not support user identification")}function nr(){return ut.for(St.CREATED_BY).define({decorator:()=>(t,e)=>pt(x(ir),ht(St.CREATED_BY,e),v(St.CREATED_BY))(t,e),args:[]}).apply()}function or(){return ut.for(St.UPDATED_BY).define({decorator:()=>(t,e)=>pt(A(ir),ht(St.UPDATED_BY,e),v(St.UPDATED_BY))(t,e),args:[]}).apply()}function ar(){return N([a.CREATE])}function cr(){return N()}function lr(t){const e="function"==typeof t&&t.name?t:t(),r=H.pk(e);return lt.allowedTypes(e,r)||[]}function ur(t,e=te,r=!0,s,i){const n=St.ONE_TO_ONE;return ut.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=lr(t),c=[wt(),wr(n,o),J([t,...a]),x(Le,o,{priority:70}),A(Fe,o,{priority:70}),k(je,o,{priority:70}),B(Qe,o,{priority:70}),_(ze,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function dr(t,e=te,r=!0,s,i){const n=St.ONE_TO_MANY;return ut.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=lr(t),c=[wt(),wr(n,o),Z([t,...a]),x(Ue,o,{priority:70}),A(Me,o,{priority:70}),k(Ye,o,{priority:70}),B(Qe,o,{priority:70}),_(ze,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function hr(t,e=te,r=!0,s,i){const n=St.MANY_TO_ONE;return ut.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=lr(t),c=[wt(),wr(n,o),J([t,...a])];return pt(...c)},args:[t,e,r,s,i]}).apply()}function pr(t,e=te,r=!0,s,i){const n=St.MANY_TO_MANY;return ut.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=lr(t),c=[wt(),wr(n,o),Z([t,...a])];return pt(...c)},args:[t,e,r,s,i]}).apply()}function gr(...t){return(e,r)=>{const s=lt.get(e,lt.key(St.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return pt(mt(lt.key(St.NO_VALIDATE,r),i))(e,r)}}function fr(){return gr(a.CREATE)}function yr(){return gr(a.UPDATE)}function mr(){return gr(a.UPDATE,a.CREATE)}function wr(t,e){return ut.for(St.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ht(t,e)(r,s),ht(lt.key(St.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class br extends H{constructor(t){super(t)}}i([ar(),n("design:type",Date)],br.prototype,"createdAt",void 0),i([cr(),n("design:type",Date)],br.prototype,"updatedAt",void 0);const vr={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},xr=vr,Ar={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Er=Object.assign({},Ar,{type:"BigInt"});async function Sr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=H.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 Or(t,e){return(r,s)=>{if(wt()(r,s),!t.type){const e=lt.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=[wt(),er([Kt.ASC,Kt.DSC]),z(),E(),ht(lt.key(b.ID,s),t),x(Sr,t,e)];return t.generated&&i.push(v()),pt(...i)(r,s)}}function Cr(t){const e=Object.assign({},xr);return delete e.generated,t=Object.assign({},e,t),ut.for(b.ID).define({decorator:Or,args:[t,{priority:60}]}).apply()}let Tr=class extends br{constructor(t){super(t)}};i([Cr({type:String,generated:!1}),n("design:type",String)],Tr.prototype,"id",void 0),i([z(),er(),n("design:type",Object)],Tr.prototype,"current",void 0),Tr=i([Ze("??sequence"),tt(),n("design:paramtypes",[Object])],Tr);class Nr extends It{static{this.lock=new ct}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ne.forModel(Tr,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 Nr.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 Tr({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 Tr({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(qt.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 C)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(zt.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 Lt(`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 Nr.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([Tr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return H.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 Lt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function kr(t,e){return(i,n)=>n?r(lt.constr(t))(i,n):(lt.set(b.REPOSITORY,lt.key(e||Vt.currentFlavour,H.tableName(t)),i),mt(b.REPOSITORY,i.name)(t),e=e||lt.get(i.constructor,St.ADAPTER),Ne.register(t,i,e),s(lt.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}Vt._baseSequence=Nr;class Br extends u{constructor(t){super(t,Br.name,500)}}class _r 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(`${Et.FIND_BY}|${Et.LIST_BY}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Et.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 Rt?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof Rt||(this._bookmark=e);const n=Ne.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,u=RegExp(`^${Et.FIND_BY}|${Et.LIST_BY}`,"gi");if(!a.match(u))throw new Lt(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,Et.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Et.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 Xt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new Xt(`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 Lt("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 D(t)}}apply(t){const e="string"==typeof t?_r.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new D(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 Dr,Rr,Ir,$r,Pr,Lr,Fr;class jr extends It{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?Et.PAGE_BY:St.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(jr)}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 Wt("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?H.get(t):t,!this.fromSelector)throw new Wt("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 Wt("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new Wt("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 Wt("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===Kt.ASC)return Kt.ASC;if(e===Kt.DSC)return Kt.DSC;throw new Wt(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Kt).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new Wt("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=H.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 Wt(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=Ne.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 Lt("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=H.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 At.AND:case At.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 Jt){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case xt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case xt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case xt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case xt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case xt.BIGGER_EQ:n.method=r+" bigger than equal";break;case xt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case xt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case xt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Wt("Unsupported operator "+s)}return n}squash(t){if(this.whereCondition&&this.whereCondition.comparison instanceof Jt)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Et.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Et.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Et.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Et.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Et.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Et.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Et.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 e;this.whereCondition&&(e=this.whereCondition.attr1);const r=this.orderBySelectors?.[0]?this.orderBySelectors[0]:e?[e,Kt.DSC]:[H.pk(this.fromSelector),Kt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:Et.LIST_BY,args:[s],params:n};return e&&(o.method=Et.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}async prepare(t){if(t=t||await this.adapter.context(St.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=vt.FIND_BY;void 0!==this.countSelector?(n=vt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=vt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=vt.AVG_BY,i=this.avgSelector):this.minSelector?(n=vt.MIN_BY,i=this.minSelector):this.maxSelector?(n=vt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=vt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=vt.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(vt.SELECT,this.selectSelector.join(` ${vt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;o.push(vt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map((([t,e])=>[t,e])),e.forEach((([t])=>{o.push(vt.THEN_BY,t)})))}if(this.groupBySelectors?.length&&n!==vt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;o.push(vt.GROUP_BY,t),e.forEach((t=>o.push(vt.THEN_BY,t)))}else this.groupBySelectors?.length&&n===vt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach((t=>o.push(vt.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 Wt(t)}}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],jr.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Dr="undefined"!=typeof S&&S)?Dr:Object]),n("design:returntype",Object)],jr.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Rr="undefined"!=typeof S&&S)?Rr:Object]),n("design:returntype",Object)],jr.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ir="undefined"!=typeof S&&S)?Ir:Object]),n("design:returntype",Object)],jr.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof($r="undefined"!=typeof S&&S)?$r:Object]),n("design:returntype",Object)],jr.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Pr="undefined"!=typeof S&&S)?Pr:Object]),n("design:returntype",Object)],jr.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Lr="undefined"!=typeof S&&S)?Lr:Object]),n("design:returntype",Object)],jr.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],jr.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[Jt]),n("design:returntype",Object)],jr.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],jr.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],jr.prototype,"thenBy",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Fr="undefined"!=typeof Key&&Key)?Fr:Object]),n("design:returntype",Object)],jr.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],jr.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],jr.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],jr.prototype,"execute",null);class Ur extends It{constructor(t){super(),this.name=t,this.observers=[],this.Context=Rt}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Pt,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}-${qt.instance.generate()}`;const s=e.logger||j.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Ot,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 Rt||(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 It.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=Ut(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 Rt||(t.push(r),r=void 0);const s=await Ur.prototype.flags(St.INITIALIZATION,{},...t);r=r?new Rt(r).accumulate({...s,parentContext:r}):(new Rt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Ur.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 Mr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new u(`Failed to boot ${t} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof Rt||(t.push(r),r=void 0);const s=await Ur.prototype.flags(St.SHUTDOWN,{},...t);r=r?new Rt(r).accumulate({...s,parentContext:r}):(new Rt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Ur.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 Mr){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)],Ur.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ur.prototype,"unObserve",null);class Mr extends Ur{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,St.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 ${this.name} service...`)}}function Yr(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Yt(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)],Mr.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Mr.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Mr.prototype,"client",null);const Gr=()=>Yr(a.CREATE),Hr=()=>Yr(a.READ),qr=()=>Yr(a.UPDATE),zr=()=>Yr(a.DELETE);function Qr(t){return(e,i,n)=>{n||i?(wt()(e,i),t=t||lt.type(e.constructor,i)):t=t||e,t=Ut(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 lt.set(St.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 Vr(t){const e=St.AUTH;return ut.for(e).define({decorator:t=>mt(e,t),args:[t]}).apply()}const Wr=t=>mt(St.AUTH_ROLE,t);function Xr(t,e){const r=St.DECAF_ROUTE;return ut.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return pt(gt(lt.key(r,i),o))(s,i,n)},args:[]}).apply()}const Jr=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Kr extends Ur{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ne.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=Jr(t);try{const t=Ur.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.override(t,...e):Reflect.get(r,s,i)})}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,St.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,Et.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,Et.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,Et.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,Et.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,St.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=Jr(e||t);try{r=Kr.get(e)}catch(t){r=void 0}if(r instanceof Kr)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Qr(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([Gr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Kr.prototype,"create",null),i([Gr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Kr.prototype,"createAll",null),i([zr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Kr.prototype,"delete",null),i([zr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Kr.prototype,"deleteAll",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Kr.prototype,"read",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Kr.prototype,"readAll",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Kr.prototype,"query",null),i([qr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Kr.prototype,"update",null),i([qr(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Kr.prototype,"updateAll",null);class Zr extends Mr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof Rt||!e.every((t=>Array.isArray(t))))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,St.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 ts=class extends H{constructor(t){super(t),this.strategy=Se.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=Oe.FULL}};i([z(),J(String),et(Se),bt("the backoff strategy"),n("design:type",String)],ts.prototype,"strategy",void 0),i([z(),bt("base interval between attempts"),n("design:type",Number)],ts.prototype,"baseMs",void 0),i([z(),bt("max interval"),n("design:type",Number)],ts.prototype,"maxMs",void 0),i([J(String),et(Oe),bt("optional jitter strategy"),n("design:type",String)],ts.prototype,"jitter",void 0),ts=i([tt(),n("design:paramtypes",[Object])],ts);let es=class extends H{constructor(t){super(t)}};i([z(),bt("The error message"),n("design:type",String)],es.prototype,"message",void 0),i([wt(),bt("The error stack"),n("design:type",String)],es.prototype,"stack",void 0),i([wt(),bt("The error code"),n("design:type",String)],es.prototype,"code",void 0),i([wt(),bt("The error details"),n("design:type",Object)],es.prototype,"details",void 0),es=i([tt(),n("design:paramtypes",[Object])],es);let rs=class extends H{constructor(t){super(t),this.ts=new Date}};i([I(["taskId","classification","uuid"],":"),Cr(),n("design:type",String)],rs.prototype,"id",void 0),i([E(),z(),$(),$e(!1),n("design:type",String)],rs.prototype,"uuid",void 0),i([E(),z(),n("design:type",String)],rs.prototype,"taskId",void 0),i([rt(),z(),n("design:type",Date)],rs.prototype,"ts",void 0),i([E(),z(),et(Ce),n("design:type",String)],rs.prototype,"classification",void 0),i([wt(),E(),n("design:type",Object)],rs.prototype,"payload",void 0),rs=i([Ze("task_event"),tt(),n("design:paramtypes",[Object])],rs);class ss extends st{constructor(){super()}preSerialize(t,...e){if(null===t||"object"!=typeof t)return t;const r=Object.assign({},t);if(t instanceof Jt)return r[it.ANCHOR]="??condition",r;if(H.isModel(t)){let e;try{e=lt.modelName(t.constructor)}catch(t){e=void 0}e&&(r[it.ANCHOR]=e)}return r}deserialize(t,...e){const r=JSON.parse(t),s=r[it.ANCHOR];return s?"??condition"===s?Jt.from(r):H.build(r,s):r}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let is=class extends H{constructor(t){super(t),this.ts=new Date}};i([rt(),z(),n("design:type",Date)],is.prototype,"ts",void 0),i([z(),et(Y),n("design:type",String)],is.prototype,"level",void 0),i([z(),wt(),n("design:type",String)],is.prototype,"msg",void 0),i([wt(),n("design:type",Object)],is.prototype,"meta",void 0),is=i([tt(),n("design:paramtypes",[Object])],is);let ns=class extends H{constructor(t){super(t),this.atomicity=Te.ATOMIC,this.status=Ee.PENDING,this.attempt=0,this.logTail=[]}};i([Cr({type:"uuid"}),bt("the task id"),n("design:type",String)],ns.prototype,"id",void 0),i([z(),J(String),et(Te),bt("defines a single or composite task"),n("design:type",String)],ns.prototype,"atomicity",void 0),i([z(),bt("Holds task classification - must match @task()"),n("design:type",String)],ns.prototype,"classification",void 0),i([z(),J(String),et(Ee),bt("Holds the task current status"),n("design:type",String)],ns.prototype,"status",void 0),i([wt(),P(ss),bt("Holds task input"),n("design:type",Object)],ns.prototype,"input",void 0),i([wt(),P(ss),bt("Holds the task output when successfully completed"),n("design:type",Object)],ns.prototype,"output",void 0),i([wt(),P(),bt("Holds the error for failed tasks"),n("design:type",es)],ns.prototype,"error",void 0),i([z(),nt(0),bt("Holds the current attempt"),n("design:type",Number)],ns.prototype,"attempt",void 0),i([nt(1),z(),bt("max attempts for the task"),n("design:type",Number)],ns.prototype,"maxAttempts",void 0),i([z(),P(),bt("backoff configuration"),n("design:type",ts)],ns.prototype,"backoff",void 0),i([rt(),bt("Next execution timestamp"),n("design:type",Date)],ns.prototype,"nextRunAt",void 0),i([rt(),bt("Task scheduled timestamp"),n("design:type",Date)],ns.prototype,"scheduledTo",void 0),i([wt(),bt("Task lease owner identifier"),n("design:type",String)],ns.prototype,"leaseOwner",void 0),i([rt(),bt("Task lease expiration timestamp"),n("design:type",Date)],ns.prototype,"leaseExpiry",void 0),i([wt(),P(),bt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],ns.prototype,"steps",void 0),i([nt(0),wt(),bt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],ns.prototype,"currentStep",void 0),i([wt(),P(),bt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],ns.prototype,"stepResults",void 0),i([wt(),P(),bt("Holds the task log entries"),n("design:type",Array)],ns.prototype,"logTail",void 0),i([tr(),ar(),bt("timestamp of creation"),n("design:type",Date)],ns.prototype,"createdAt",void 0),i([tr(),cr(),bt("timestamp of last update"),n("design:type",Date)],ns.prototype,"updatedAt",void 0),i([tr(),nr(),bt("Holds the creator of the task"),n("design:type",String)],ns.prototype,"createdBy",void 0),i([tr(),or(),bt("Holds the creator of the task"),n("design:type",String)],ns.prototype,"updatedBy",void 0),ns=i([bt("Holds the current step when applicable"),Ze("tasks"),tt(),n("design:paramtypes",[Object])],ns);let os=class extends H{constructor(t){super(t)}};i([z(),bt("The status of a step"),n("design:type",String)],os.prototype,"status",void 0),i([wt(),bt("The result of a successful step"),n("design:type",Object)],os.prototype,"output",void 0),i([wt(),bt("the error of a failed step"),n("design:type",es)],os.prototype,"error",void 0),os=i([tt(),n("design:paramtypes",[Object])],os);let as=class extends H{constructor(t){super(t)}};i([z(),wt(),bt("task handler type"),n("design:type",String)],as.prototype,"classification",void 0),i([bt("optional task step input"),wt(),n("design:type",Object)],as.prototype,"input",void 0),as=i([tt(),n("design:paramtypes",[Object])],as);class cs extends H{constructor(t){super(t),this.baseMs=1e3,this.jitter=Oe.FULL,this.maxMs=6e4,this.strategy=Se.EXPONENTIAL,H.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 ts(this)}}i([z(),nt(1e3),n("design:type",Number)],cs.prototype,"baseMs",void 0),i([z(),et(Oe),n("design:type",String)],cs.prototype,"jitter",void 0),i([ot("baseMs"),nt(1e3),z(),n("design:type",Number)],cs.prototype,"maxMs",void 0),i([z(),et(Se),n("design:type",String)],cs.prototype,"strategy",void 0);class ls extends H{setClassification(t){return this.classification=t,this}setStatus(t){return this.status=t,this}setAtomicity(t){return this.atomicity=t,this}setBackoff(t){if(t)return this.backoff=t,this;const e=new cs,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=Ee.PENDING,this.atomicity=Te.ATOMIC,this.backoff=new ts,this.maxAttempts=1,H.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new ns(this)}}i([z(),n("design:type",String)],ls.prototype,"classification",void 0),i([z(),n("design:type",String)],ls.prototype,"status",void 0),i([z(),n("design:type",String)],ls.prototype,"atomicity",void 0),i([z(),n("design:type",ts)],ls.prototype,"backoff",void 0),i([wt(),n("design:type",Object)],ls.prototype,"input",void 0),i([nt(1),z(),n("design:type",Number)],ls.prototype,"maxAttempts",void 0);class us extends ls{constructor(t){super(t),this.stepResults=[],H.fromModel(this,t),this.atomicity=Te.COMPOSITE}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new as({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([Z((()=>as)),n("design:type",Array)],us.prototype,"steps",void 0);class ds extends $t{get type(){if(!this._type){const t=lt.get(this.constructor,_e);"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 hs(t){return ut.for(_e).define({decorator:t=>e=>{const r={type:t};return lt.set(_e,t,e),mt(_e,r)(e)},args:[t]}).apply()}let ps=class extends ds{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof Jt)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=Jt.attr("status").eq(Ee.SUCCEEDED).and(Jt.attr("updatedAt").lte(t.successfulExpiry)),i=Jt.attr("status").eq(Ee.FAILED).and(Jt.attr("updatedAt").lte(t.failedExpiry)),n=Jt.attr("status").eq(Ee.CANCELED).and(Jt.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([kr(ns),n("design:type",Object)],ps.prototype,"tasks",void 0),ps=i([hs("cleanup-task"),n("design:paramtypes",[])],ps);class gs{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)=>"logger"===s?Reflect.get(r,s).for(t,...e):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 fs(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 Ce.LOG:{const s=r.payload;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 Ce.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Ce.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=G(e);switch(e){case Ee.SUCCEEDED:s=s.green.bold;break;case Ee.RUNNING:s=s.blue.bold;break;case Ee.PENDING:s=s.yellow;break;case Ee.WAITING_RETRY:s=s.yellow.bold;break;case Ee.FAILED:s=s.red.bold;break;case Ee.CANCELED:s=s.magenta.bold;break;case Ee.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 ys(t,e){const r=e.strategy===Se.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===Oe.FULL?Math.floor(Math.random()*s):s}function ms(t){return new es({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function ws(t){return new Promise((e=>setTimeout(e,t)))}class bs extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=bs.name,Object.setPrototypeOf(this,bs.prototype)}}class vs extends Rt{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 bs({status:t,...e})}cancel(t,e){this.changeState(Ee.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(Ee.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(Ee.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof es?t:t instanceof Error?ms(t):new es({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class xs{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=lt.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 As extends Pt{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(rs,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=Vt.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}`)}))}}class Es extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class Ss extends Es{constructor(t,e,r){super(Ss.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class Os extends Es{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(Os.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class Cs extends Es{constructor(t,e,r){super(Cs.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class Ts extends Es{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(Ts.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class Ns{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===rs||t===H.tableName(rs)))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([Ee.SUCCEEDED,Ee.FAILED,Ee.CANCELED,Ee.WAITING_RETRY,Ee.SCHEDULED])}wait(){return this.awaitStatusTerminal([Ee.SUCCEEDED,Ee.FAILED,Ee.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(fs(t,e))}logs(t){this.pipe((async e=>{if(e.classification!==Ce.LOG)return;const r=e.payload;await t(r)}),Ce.LOG)}pipe(t,e=Ce.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(Ee.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(Ee.FAILED,t)}onCancel(t){return this.registerStatusHandler(Ee.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===Ee.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.buildMeta(e,t.payload);return this.createTaskControlError(e,t.payload?.error??this.task.error,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[Ee.SUCCEEDED,Ee.CANCELED,Ee.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!==Ee.SUCCEEDED?(r===Ee.FAILED&&this.fail(),r===Ee.CANCELED&&this.cancel(t),r===Ee.WAITING_RETRY&&this.retry(),r===Ee.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,Ce.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Ce.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new Rt),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===Ee.SUCCEEDED&&(e.output=this.task.output),t!==Ee.FAILED&&t!==Ee.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 rs({classification:Ce.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case Ee.FAILED:return new Ss(this.task.id,e,r);case Ee.CANCELED:return new Cs(this.task.id,e,r);case Ee.WAITING_RETRY:return new Os(this.task.id,e,r);case Ee.SCHEDULED:return new Ts(this.task.id,e,r);default:return new Ss(this.task.id,e,r)}}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===Ee.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[Ce.ALL]?[...this.pipes[Ce.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 ks extends $t{get Context(){return vs}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=Ne.forModel(ns,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=Ne.forModel(rs,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new at,this.running=!1,this.config=Object.assign({},De,t,{bus:t.bus||new As,registry:t.registry||new xs})}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 Ns(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=Ee.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 Ns(this.bus,i)}}async ensureTaskError(t,e){if(![Ee.FAILED,Ee.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await ws(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===Ee.SUCCEEDED||s.status===Ee.FAILED)return s;s.status=Ee.CANCELED;const i=new es({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,Ee.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,St.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(Jt.attr("status").eq(Ee.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 ws(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=Jt.attribute("status").eq(Ee.PENDING),i=Jt.attribute("status").eq(Ee.WAITING_RETRY).and(Jt.attribute("nextRunAt").lte(r)),n=Jt.attribute("status").eq(Ee.RUNNING).and(Jt.attribute("leaseExpiry").lte(r)),o=Jt.attribute("status").eq(Ee.SCHEDULED).and(Jt.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 ns({...i,status:Ee.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 vs(e).accumulate({taskId:t.id,logger:new gs(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,Ee.RUNNING);try{let e;if(t.atomicity===Te.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=Ee.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,Ee.SUCCEEDED,e)}catch(e){try{t=await this.tasks.read(t.id,s)}catch{}if(e instanceof bs)return void await this.handleTaskStateChange(e.request,t,s);if(r.error("task execution error",e),t.atomicity===Te.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex((t=>t.status===Ee.FAILED));0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=ms(e);if(i<t.maxAttempts){const e=ys(i,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+e);t.attempt=i,t.status=Ee.WAITING_RETRY,t.nextRunAt=o,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 this.emitStatus(s,t,Ee.WAITING_RETRY),await s.pipe(Y.warn,"Retry scheduled",{nextRunAt:o,delayMs:e,attempt:i})}else t.attempt=i,t.status=Ee.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 this.emitStatus(s,t,Ee.FAILED,n),await s.pipe(Y.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case Ee.CANCELED:{const s=t.error??new es({message:`Task ${e.id} canceled`});return e.status=Ee.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ee.CANCELED,s),void await r.pipe(Y.warn,"Task canceled via context")}case Ee.WAITING_RETRY:{const s=(e.attempt??0)+1,i=ys(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new es({message:`Task ${e.id} requested retry`});return e.status=Ee.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,Ee.WAITING_RETRY,o),void await r.pipe(Y.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case Ee.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new es({message:`Task ${e.id} rescheduled`});return e.status=Ee.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ee.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 vs&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===Ee.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 os({status:Ee.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 os({status:Ee.FAILED,error:ms(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=ms(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(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)}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 as)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new as(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 os)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new os(e)})):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map((([t,e,r])=>new is({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){t instanceof vs&&await t.flush();const i={status:r};s&&s instanceof es?i.error=s:s&&(i.output=s),e.nextRunAt&&(i.nextRunAt=e.nextRunAt),e.scheduledTo&&(i.scheduledTo=e.scheduledTo);const n=await this.persistEvent(t,e.id,Ce.STATUS,i);this.bus.emit(n,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Ce.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,Ce.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new rs({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,ns,...r)}}class Bs extends Mr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof Rt)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,St.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new ks(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,St.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 Lt("Updates to tasks are not available")}async updateAll(t,...e){throw new Lt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Et.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,Et.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,Et.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,Et.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,St.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,St.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")}}i([kr(ns),n("design:type",Object)],Bs.prototype,"repo",void 0),i([Gr(),n("design:type",Function),n("design:paramtypes",[ns,void 0]),n("design:returntype",Promise)],Bs.prototype,"create",null),i([Gr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Bs.prototype,"createAll",null),i([zr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Bs.prototype,"delete",null),i([zr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Bs.prototype,"deleteAll",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Bs.prototype,"read",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Bs.prototype,"readAll",null),i([Hr(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],Bs.prototype,"query",null),i([qr(),n("design:type",Function),n("design:paramtypes",[ns,void 0]),n("design:returntype",Promise)],Bs.prototype,"update",null),i([qr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Bs.prototype,"updateAll",null),e.setRegistry(new Be);const _s="##VERSION##",Ds="##PACKAGE##";lt.registerLibrary(Ds,_s);export{$t as AbsContextual,Vt as Adapter,Xe as AuthorizationError,Se as BackoffStrategy,br as BaseModel,Er as BigIntSequence,Zt as Cascade,ps as CleanUpTask,Mr as ClientBasedService,us as CompositeTaskBuilder,Jt as Condition,Ke as ConnectionError,Rt as Context,Dt as ContextLock,It as ContextualLoggedClass,Ct as DefaultAdapterFlags,te as DefaultCascade,Ot as DefaultContextFlags,fe as DefaultRepositoryFilters,xr as DefaultSequenceOptions,De as DefaultTaskEngineConfig,Re as Dispatch,Je as ForbiddenError,At as GroupOperator,Be as InjectablesRegistry,Oe as JitterStrategy,se as MethodQueryBuilder,Ft as MigrationError,jt as MigrationRuleError,Kr as ModelService,Bt as MultipleSelectOperationKeys,Nt as NonTransactionOperationKeys,vr as NoneSequenceOptions,Ar as NumericSequence,Br as ObserverError,Pt as ObserverHandler,xt as Operator,ee as OperatorsMap,Kt as OrderDirection,Ds as PACKAGE_NAME,_t as PaginationOperationKeys,_r as Paginator,Xt as PagingError,St as PersistenceKeys,Zr as PersistenceService,Et as PreparedStatementKeys,vt as QueryClause,Wt as QueryError,Ne as Repository,kt as SelectOperationKeys,Nr as Sequence,Tr as SequenceModel,zt as Serial,Ur as Service,jr as Statement,cs as TaskBackoffBuilder,ts as TaskBackoffModel,ls as TaskBuilder,Cs as TaskCancelError,vs as TaskContext,Es as TaskControlError,ks as TaskEngine,es as TaskErrorModel,As as TaskEventBus,rs as TaskEventModel,Ce as TaskEventType,Ss as TaskFailError,ds as TaskHandler,xs as TaskHandlerRegistry,ss as TaskIOSerializer,is as TaskLogEntryModel,gs as TaskLogger,ns as TaskModel,Ts as TaskRescheduleError,Os as TaskRetryError,Bs as TaskService,Ee as TaskStatus,os as TaskStepResultModel,as as TaskStepSpecModel,Ns as TaskTracker,Te as TaskType,_e as TasksKey,Tt as TransactionOperationKeys,qt as UUID,Lt as UnsupportedError,_s as VERSION,oe as applyViewDecorator,Vr as auth,qe as cacheModelForPopulate,Qe as cascadeDelete,tr as column,ys as computeBackoffMs,Gr as create,Pe as createOrUpdate,ar as createdAt,nr as createdBy,ir as createdByOnCreateUpdate,zr as del,ke as generateInjectableNameForRepository,ye as getFilters,fs as getLogPipe,lr as getPkTypes,Ge as getPopulateKey,He as getTagForDeleteKey,er as index,Ut as injectableServiceKey,Yt as isOperationBlocked,pr as manyToMany,hr as manyToOne,gr as noValidateOn,fr as noValidateOnCreate,mr as noValidateOnCreateUpdate,yr as noValidateOnUpdate,Gt as normalizeImport,dr as oneToMany,Ue as oneToManyOnCreate,Ye as oneToManyOnDelete,Me as oneToManyOnUpdate,ur as oneToOne,Le as oneToOneOnCreate,je as oneToOneOnDelete,Fe as oneToOneOnUpdate,pe as onlyOnBulk,ce as onlyOnCreate,ue as onlyOnDelete,ge as onlyOnFilter,he as onlyOnSingle,de as onlyOnTransactional,le as onlyOnUpdate,Cr as pk,Or as pkDec,Sr as pkOnCreate,ze as populate,Ht as prefixMethod,ie as prepared,Mt as promiseSequence,ne as query,Hr as read,wr as relation,kr as repository,We as repositoryFromTypeMetadata,Wr as roles,Xr as route,ms as serializeError,Qr as service,ws as sleep,Ze as table,hs as task,sr as unique,rr as uniqueOnCreateUpdate,qr as update,cr as updatedAt,or as updatedBy,$e as uuid,Ie as uuidCreateUpdateHandler,ae 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 N,onDelete as k,afterUpdate as B,afterAny as _,SerializationError as D,prefixMethod as R,composed as $,transient as I,serialize as P,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 z,hashObj as H,required as q,sf as V,model as Q,isEqual as W,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}from"@decaf-ts/transactional-decorators";import{Metadata as lt,Decoration as ut,DefaultFlavour as dt,propMetadata as ht,apply as pt,methodMetadata as gt,DecorationKeys as ft,uses as yt,metadata as mt,prop as wt,description as bt}from"@decaf-ts/decoration";var vt,At,xt,Et,St;(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"})(vt||(vt={})),(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.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(At||(At={})),(t=>{t.AND="AND",t.OR="OR"})(xt||(xt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",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"})(Et||(Et={})),(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"})(St||(St={}));const Ot=Object.assign({},{ignoreDevSafeGuards:!1}),Ct=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),Tt=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Nt=[a.READ,c.READ_ALL],kt=[St.STATEMENT,Et.FIND_ONE_BY],Bt=[St.QUERY,Et.PAGE_BY,Et.LIST_BY,Et.FIND_BY],_t=[Et.PAGE_BY];class Dt extends at{constructor(){super()}}class Rt 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){const e=this.getOrUndefined(t);if(e)return e;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map((e=>e.getFromChildren(t))).flat().reduce(((t,e)=>Object.assign(t,e)),{}):void 0}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 $t extends F{logCtx(t,e,r=!1,s){return $t.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 Rt;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 It extends $t{constructor(){super(),this._Context=Rt}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 Rt||(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 Pt{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}=$t.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 Lt extends u{constructor(t){super(t,Lt.name,500)}}class Ft extends u{constructor(t,e=Ft.name){super(t,e,500)}}class jt extends Ft{constructor(t){super(t,jt.name)}}function Ut(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):lt.Symbol(lt.constr(t)).toString().replaceAll(".","-")}function Mt(t){return t.reduce(((t,e)=>t.then((async t=>[...t,await e()]))),Promise.resolve([]))}function Yt(t,e){const{handler:r,args:s}=lt.get(t,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function Gt(t){return t.then((t=>t.default||t))}function zt(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 jt)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 Ht{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 Ht._instance||(Ht._instance=new Ht),Ht._instance}}class qt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return qt._instance||(qt._instance=new qt),qt._instance}}const Vt=ut.flavourResolver.bind(ut);ut.flavourResolver=t=>{try{const e=Vt(t);if(e&&e!==dt)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof lt.registeredFlavour?lt.registeredFlavour(r):void 0;if(s&&s!==dt)return s;const i=Qt._currentFlavour;if(i){const t=Qt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return dt}};class Qt extends It{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!Qt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return Qt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(...t){(await this.logCtx(t,St.SHUTDOWN,!0)).for(this.shutdown),await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.alias in Qt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);Qt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),Qt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),Qt._currentFlavour=this.alias)}Dispatch(){return new Qt._baseDispatch}ObserverHandler(){return new Pt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new Qt._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?z.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${Ht.instance.generate()}`;const o=r.logger||j.for(this);return Object.assign({},Ct,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:Tt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?lt.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}get Context(){return Rt}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=>z.tableName(t))):z.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 Rt||(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=z.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[St.METADATA]&&(r.silly("Passing along persistence metadata for "+t[St.METADATA]),Object.defineProperty(i,St.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[St.METADATA]})),{record:i,id:t[z.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=z.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[St.METADATA],d=Object.keys(c).filter((t=>t!==a)).reduce(((r,s)=>(r[s]=t[z.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,St.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=z.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Mt(e.map(((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})))))}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=z.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Mt(e.map((e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0})))))}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=z.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Mt(e.map(((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})))))}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${e.length} entries from ${t} table`),Mt(e.map((e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})))))}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 lt.flavourOf(t)}static get currentFlavour(){if(!Qt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return Qt._currentFlavour}static get current(){return Qt.get(this.currentFlavour)}static get(t){if(!t)return Qt.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 lt.flavouredAs(t).filter(z.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 this.proxies[r]=i,i}migrations(){return lt.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",[String]),n("design:returntype",Promise)],Qt.prototype,"shutdownProxies",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,Rt]),n("design:returntype",Promise)],Qt.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Qt.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Qt.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Qt.prototype,"client",null);class Wt extends u{constructor(t){super(t,Wt.name,500)}}class Jt extends u{constructor(t){super(t,Jt.name,500)}}class Xt extends z{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):z.fromModel(this,t)}and(t){return Xt.and(this,t)}or(t){return Xt.or(this,t)}not(t){return new Xt(this,At.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Xt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(At).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===At.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 Xt){if(!(this.comparison instanceof Xt)&&this.operator!==At.NOT)return{comparison:{condition:t}};if(-1===Object.values(xt).indexOf(this.operator)&&this.operator!==At.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 Xt.group(t,xt.AND,e)}static or(t,e){return Xt.group(t,xt.OR,e)}static group(t,e,r){return new Xt(t,e,r)}static attribute(t){return(new Xt.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(At.EQUAL,t)}dif(t){return this.setOp(At.DIFFERENT,t)}gt(t){return this.setOp(At.BIGGER,t)}lt(t){return this.setOp(At.SMALLER,t)}gte(t){return this.setOp(At.BIGGER_EQ,t)}lte(t){return this.setOp(At.SMALLER_EQ,t)}in(t){return this.setOp(At.IN,t)}regexp(t){return this.setOp(At.REGEXP,RegExp(t).source)}between(t,e){return this.setOp(At.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Xt(this.attr1,this.operator,this.comparison)}catch(t){throw new Wt(t)}}}}static builder(){return new Xt.Builder}static from(t){return new Xt(t)}}var Kt,Zt;i([q(),n("design:type",Object)],Xt.prototype,"attr1",void 0),i([q(),n("design:type",String)],Xt.prototype,"operator",void 0),i([q(),n("design:type",Object)],Xt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(Kt||(Kt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Zt||(Zt={}));const te={update:Zt.CASCADE,delete:Zt.NONE},ee={Equals:(t,e)=>Xt.attribute(t).eq(e),Diff:(t,e)=>Xt.attribute(t).dif(e),LessThan:(t,e)=>Xt.attribute(t).lt(e),LessThanEqual:(t,e)=>Xt.attribute(t).lte(e),GreaterThan:(t,e)=>Xt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Xt.attribute(t).gte(e),In:(t,e)=>Xt.attribute(t).in(e),Matches:(t,e)=>Xt.attribute(t).regexp(e)},re=t=>t.charAt(0).toLowerCase()+t.slice(1);class se extends F{static get log(){return this._logger||(this._logger=j.for(se.name)),this._logger}static{this.prefixMap={[vt.FIND_BY]:"find",[vt.PAGE_BY]:"page",[vt.COUNT_BY]:"count",[vt.SUM_BY]:"sum",[vt.AVG_BY]:"avg",[vt.MIN_BY]:"min",[vt.MAX_BY]:"max",[vt.DISTINCT_BY]:"distinct",[vt.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?re(i):void 0}static extractCore(t,e=vt.FIND_BY){const r=t.substring(e.length);if(e!==vt.FIND_BY&&e!==vt.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||vt.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(vt.SELECT);if(-1===e)return;const r=t.substring(e+vt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(vt.AND).map(re).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(vt.GROUP_BY);if(-1!==e)return t.substring(e+vt.GROUP_BY.length).split(vt.ORDER_BY)[0].split(vt.THEN_BY).map(re).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(vt.THEN_BY);if(-1===s)return;const i=e.substring(s+vt.THEN_BY.length).split(vt.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(re(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?ee[o]:ee.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]===vt.AND?n.and(l):n.or(l)})),n}static parseFieldAndOperator(t){for(const e of Object.keys(ee))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:re(r),operator:e}}return{field:re(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=se.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new Wt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(Kt).includes(e))throw new Wt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(Kt).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 ie(){return ut.for(St.STATEMENT).define({decorator:()=>(t,e,r)=>pt(gt(lt.key(St.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function ne(t={}){return ut.for(St.QUERY).define({decorator:t=>(e,r,s)=>{const i=se.getFieldsFromMethodName(r);return pt(gt(lt.key(St.QUERY,r),{...t,fields:i}),ie(),(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}=se.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 Wt("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 Wt(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 oe(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(lt.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=lt.key(t,i,n),a={...r||{},kind:e,attribute:i};return ht(o,a)(s,i)}}function ae(t){return ut.for(At.VIEW).define({decorator:t=>oe(At.VIEW,"view",t),args:[t]}).apply()}function ce(t){return ge(t,[a.CREATE,c.CREATE_ALL])}function le(t){return ge(t,[a.UPDATE,c.UPDATE_ALL])}function ue(t){return ge(t,[a.DELETE,c.DELETE_ALL])}function de(t){return ge(t,Tt)}function he(t){return ge(t,Object.values(a))}function pe(t){return ge(t,Object.values(c))}function ge(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}=$t.prototype.logCtx(n,ge);return o.silly(`filtering ${s} event for${r?" "+(z.tableName(r)||r):""} ${i}`),("string"==typeof r?r===z.tableName(t)||r===t.constructor.name:lt.constr(t)===lt.constr(r))&&e.includes(s)}}const fe={onlyOnCreate:ce,onlyOnUpdate:le,onlyOnDelete:ue,onlyOnTransactional:de,onlyOnSingle:he,onlyOnBulk:pe};function ye(t){const e=Object.assign({},fe);return Object.entries(e).forEach((([r,s])=>{e[r]=s(t.class)})),e}var me,we,be,ve,Ae,xe,Ee,Se,Oe,Ce,Te;class Ne 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=z.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ye(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&&(Ne.register(e,this,this.adapter.alias),t)&<.get(e,ft.FLAVOUR)===dt&&yt(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 Pt}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 ${z.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 ${z.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=z.sequenceFor(t[0]);let h=[];if(z.generatedBySequence(this.class)?(l.name||(l.name=z.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l)).range(t.length,...s)):z.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 ${z.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 ${z.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 ${z.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=z.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 ${z.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)=>z.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 ${z.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 ${z.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=Kt.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,St.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,Et.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${z.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 Wt("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Et.PAGE_BY,!0)).for(this.paginateBy);let d;if(c.verbose(`paginating ${z.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Kt.ASC?this.attr(z.pk(this.class)).gt(o):this.attr(z.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new Wt("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 findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Et.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${z.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,Et.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${z.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,Et.COUNT_OF,!0)).for(this.countOf);return r.verbose(`counting ${z.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.MAX_OF,!0)).for(this.maxOf);return r.verbose(`finding max of ${t} in ${z.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.MIN_OF,!0)).for(this.minOf);return r.verbose(`finding min of ${t} in ${z.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.AVG_OF,!0)).for(this.avgOf);return r.verbose(`calculating average of ${t} in ${z.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.SUM_OF,!0)).for(this.sumOf);return r.verbose(`calculating sum of ${t} in ${z.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.DISTINCT_OF,!0)).for(this.distinctOf);return r.verbose(`finding distinct values of ${t} in ${z.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Et.GROUP_OF,!0)).for(this.groupOf);return r.verbose(`grouping ${z.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...e){if(!Ne.statements(this,t))throw new Wt("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,St.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}attr(t){return Xt.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:lt.constr(t)===lt.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=>Qt._baseSequence.parseValue(z.sequenceFor(this.class).type,t))):Qt._baseSequence.parseValue(z.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||lt.flavourOf(t)||Qt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ne)return s;const n=e||lt.flavourOf(t)||s&<.get(s,St.ADAPTER)||Qt.currentFlavour,o=n?Qt.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=z.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=z.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof Ne)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ne?t.constructor:t,s=lt.get(r,e?lt.key(St.STATEMENT,e):St.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ne?t.constructor:t;return lt.get(r,e?lt.key(St.QUERY,e):St.QUERY)}}function ke(t,e){if(!(e||(e=ut.flavourResolver(t instanceof z?t.constructor:t))&&e!==dt))throw new u("Could not retrieve flavour from model "+(t instanceof z?t.constructor.name:t.name));return V(St.INJECTABLE,e,z.tableName(t))}i([ie(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ne.prototype,"listBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"paginateBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"findOneBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"findBy",null),i([ie(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"countOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(me="undefined"!=typeof K&&K)?me:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"maxOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(we="undefined"!=typeof K&&K)?we:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"minOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(be="undefined"!=typeof K&&K)?be:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"avgOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ve="undefined"!=typeof K&&K)?ve:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"sumOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ae="undefined"!=typeof K&&K)?Ae:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"distinctOf",null),i([ie(),n("design:type",Function),n("design:paramtypes",["function"==typeof(xe="undefined"!=typeof K&&K)?xe:Object,void 0]),n("design:returntype",Promise)],Ne.prototype,"groupOf",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Ne.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ne.prototype,"unObserve",null),Qt&&(Qt._baseRepository=Ne);class Be 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=z.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=z.get(t.toString())),!n)return;const o=St.ADAPTER,a=r||lt.get(n,o);try{let t=a;try{a&&Qt.get(a)}catch{const e=Qt.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ne.forModel(n,t),i instanceof Ne)return i;const r=a||lt.get(i.constructor,o)||lt.get(n,o);e.register(i,ke(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=Ne.get(n,a);if("function"==typeof e){const t=a?Qt.get(a):Qt.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"})(Ee||(Ee={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(Se||(Se={})),(t=>{t.NONE="none",t.FULL="full"})(Oe||(Oe={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Ce||(Ce={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Te||(Te={}));const _e="tasks",De={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};function Re(t,e){return(i,n)=>n?r(lt.constr(t))(i,n):(lt.set(b.REPOSITORY,lt.key(e||Qt.currentFlavour,z.tableName(t)),i),mt(b.REPOSITORY,i.name)(t),e=e||lt.get(i.constructor,St.ADAPTER),Ne.register(t,i,e),s(lt.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}lt.tasks=(()=>lt.innerGet(Symbol.for(_e))).bind(lt),lt.taskFor=(t=>{const e=lt.tasks();return e?e[t]:void 0}).bind(lt),lt.validationExceptions=((t,e)=>{const r=lt.get(t,St.NO_VALIDATE)||[],s=Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t));let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=z.nestedRelations(t)),[...new Set([...s,...i])]}).bind(lt),lt.migrationsFor=(t=>{if(!(t=t??Qt.current))throw new u("Could not get adapter for migrations");return lt.innerGet(Symbol.for(St.MIGRATION),t.alias).map((t=>t.class))}).bind(lt),lt.migrations=(()=>{const t=lt.innerGet(Symbol.for([St.MIGRATION,St.BY_KEY].join("-")));return Object.values(t).flat().map((t=>[t.class.name,t.class]))}).bind(lt),lt.relations=((t,e)=>{const r=lt.get(t,St.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(lt),z.relations=(t,e)=>lt.relations(t instanceof z?t.constructor:t,e)||[],z.nestedRelations=((t,e=[])=>{let r=[];const s=lt.get(t,St.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&z.relations(i.class)){const s=z.relations(i.class).map((e=>`${t}.${e}`));e=[...e,...s],r=z.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(z),z.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!z.sequenceFor(r).generated}).bind(z),z.fromTable=(t=>{const e=lt.innerGet(Symbol.for(St.TABLE));if(!e||!e[t]||!z.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return z.get(e[t].name)}).bind(z),lt.createdBy=(t=>{const e=lt.get("function"!=typeof t?t.constructor:t,St.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(lt),lt.updatedBy=(t=>{const e=lt.get("function"!=typeof t?t.constructor:t,St.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(lt),z.tableName=t=>{if(!(t instanceof z?z.get(t.constructor.name):t))throw new u("Unable to find model "+t);return lt.get(t instanceof z?t.constructor:t,St.TABLE)||(t instanceof z?t.constructor.name:t.name)},z.columnName=(t,e)=>lt.get(t instanceof z?t.constructor:t,lt.key(St.COLUMN,e))||e,z.sequenceName=(t,...e)=>[z.tableName(t),...e].join("_"),z.sequenceFor=(t,e)=>{if(e)throw new Lt("not currently supported");const r=z.pkProps(t instanceof z?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},z.indexes=t=>{const e=lt.get(t instanceof z?t.constructor:t,St.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[St.INDEX]:e[r]},t)),{})},e.services=()=>lt.innerGet(Symbol.for(St.SERVICE)),e.repositories=()=>lt.innerGet(Symbol.for(b.REPOSITORY));class $e extends u{constructor(t){super(t,$e.name,500)}}const Ie={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Pe=Ie,Le={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Fe=Object.assign({},Le,{type:"BigInt"});function je(t,e,r){return ut.for(St.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=>![Kt.ASC,Kt.DSC].includes(t)))&&(e=t,t=void 0),ht(lt.key(`${St.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Ue(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=z.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 Me(t,e){return(r,s)=>{if(wt()(r,s),!t.type){const e=lt.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=[wt(),je([Kt.ASC,Kt.DSC]),q(),v(),ht(lt.key(b.ID,s),t),A(Ue,t,e)];return t.generated&&i.push(x()),pt(...i)(r,s)}}function Ye(t){const e=Object.assign({},Pe);return delete e.generated,t=Object.assign({},e,t),ut.for(b.ID).define({decorator:Me,args:[t,{priority:60}]}).apply()}async function Ge(t,e,r,s,i){const n=e.logger.for(Ge);if(!s){const e=z.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=Ne.forModel(e,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===t[z.pk(s.class)])n.info(`No pk found in ${z.tableName(s.class)} - creating`),o=await s.create(t,e);else{n.info(`pk found in ${z.tableName(s.class)} - attempting update`);try{o=await s.update(t,e),n.info("Updated "+z.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+z.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(Xe(s,e),"object"!=typeof i){const e=dr(s,r,this.adapter.alias),n=await e.read(i,t);return await ar(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=Ne.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=z.pk(a);await ar(t,s,r,a[c],a),s[r]=a[c]}async function He(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;if("object"!=typeof i){const e=dr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await ar(t,s,r,i,n),void(s[r]=i)}const n=await Ge(s[r],t,this.adapter.alias,void 0,this._overrides),o=z.pk(n);await ar(t,s,r,n[o],n),s[r]=n[o]}async function qe(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;const n=dr(s,r,this.adapter.alias);let o;o=i instanceof z?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await ar(t,s,r,o[n.pk],o)}async function Ve(t,e,r,s){const i=s[r];if(!i||!i.length)return;Xe(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(Ve),a=new Set([...i]);if("object"!==n){const e=dr(s,r,this.adapter.alias),i=await e.readAll([...a.values()],t);for(let e=0;e<i.length;e++){const s=i[e];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await ar(t,s,r,[...a.values()][e],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=z.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Ge(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await ar(t,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(e)),l.add(i[c])}s[r]=[...l]}async function Qe(t,e,r,s){const{cascade:i}=e;if(i.update===Zt.CASCADE)return Ve.call(this,t,e,r,s)}async function We(t,e,r,s){if(e.cascade.delete!==Zt.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?Ne.forModel(o,this.adapter.alias):dr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.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 ar(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 Je(t,e,r,s){const i=s[r];if(!i)return;Xe(s,e);const n=t.logger.for(Je);if("object"!=typeof i){const e=dr(s,r,this.adapter.alias),n=await e.read(i);return await ar(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof z?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 Ge(i,t,this.adapter.alias),a=z.pk(o);n.info(`caching: ${JSON.stringify(o)} under ${o[a]}`),await ar(t,s,r,o[a],o),s[r]=o[a]}function Xe(t,e){let r;const s="function"==typeof e.class&&e.class.name?e.class:e.class(),i=lt.get(s,St.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 Ke(t,e,r,s){const{cascade:i}=e;if(i.update===Zt.CASCADE)return Je.call(this,t,e,r,s)}async function Ze(t,e,r,s){if(e.cascade.delete!==Zt.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,o=n?Ne.forModel(i,this.adapter.alias):dr(s,r,this.adapter.alias),a=n?i[o.pk]:i,c=await o.delete(a);await ar(t,s,r,a,c),s[r]=a}async function tr(t,e,r,s){const i=s[r];if(!i||!i.length)return;Xe(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(tr),a=new Set([...i]);if("object"!==n){const n=dr(s,r,this.adapter.alias),c=await n.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 ar(t,s,r,[...a.values()][e],c)}return await er.call(this,s,[...i],o,t,e),s[r]=[...a],void o.info("SET MANY TO MANY IDS: "+s[r])}const c=z.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 Ge(e,t,this.adapter.alias);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await ar(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=z.pk(s.constructor);if(void 0===s[d]){const e=await(async(t,e,r)=>{const s=e[z.pk(e.constructor)];if(void 0!==s)return s;const i=z.sequenceFor(e.constructor);let n;i?.name||(i.name=z.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i),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 er.call(this,s,i,o,t,e);o.info("Junction model created: "+h.name),s[r]=[...l]}async function er(t,e,r,s,i){const{JunctionModel:n,fkA:o,fkB:a}=rr(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 z?t[z.pk(t.constructor)]:t,[a]:i instanceof z?i[z.pk(i.constructor)]:i},l=await Ge(new n(e),s,this.adapter.alias);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Ne.forModel(n);await(t?.readAll(c))}return n}function rr(t,e,r){const s=z.tableName(t);let i;if(e instanceof z)i=z.tableName(e);else if(z.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=z.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 z{constructor(t){super(t)}};Object.defineProperty(c,"name",{value:n,writable:!1}),Ye({type:Number})(c.prototype,"id"),q()(c.prototype,o),q()(c.prototype,a);const l=Q()(c);return lt.set(c,St.TABLE,n),{fkA:o,fkB:a,JunctionModel:l}}async function sr(t,e,r,s){const{cascade:i}=e;if(i.update===Zt.CASCADE)return tr.call(this,t,e,r,s)}async function ir(t,e,r,s){if(e.cascade.delete!==Zt.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?Ne.forModel(o,this.adapter.alias):dr(s,r,this.adapter.alias),l=[...new Set([...a?i.map((t=>t[c.pk])):i]).values()];let d,h;try{d=await c.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 ar(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 nr(t,e,r){return[St.POPULATE,t,e,r].join(".")}function or(t,e,r){return[St.TAG_FOR_DELETION,t,r].join(".")}async function ar(t,e,r,s,i){const n=nr(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function cr(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=await(async(e,r,s,i)=>{let n,o;const a=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=nr(r.constructor.name,s,e);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=dr(r,s);if(!n)throw new u("Could not find repo");o=await n.read(e,t)}a.push(o)}return a})(t,s,r,n?i:[i]);s[r]=n?o:o[0]}async function lr(t,e,r,s,i){if(e.cascade.update!==Zt.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[z.pk(t)]}const a=o(s[r]),c=o(i[r]);if(void 0===c||W(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=dr(s,r);if(!h)throw new u("Could not find repo");try{const e=await h.deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${z.tableName(h.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}const ur=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function dr(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=lt.get(t instanceof z?t.constructor:t,lt.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=lt.getPropDesignTypes(t instanceof z?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!ur.includes((""+t.name).toLowerCase())));return Ne.forModel(i,r)}class hr extends E{constructor(t,e=hr.name,r=401){super(t,e,r)}}class pr extends hr{constructor(t,e=pr.name){super(t,e,403)}}class gr extends u{constructor(t){super(t,gr.name,503)}}function fr(t){return ut.for(St.TABLE).define({decorator:t=>e=>(lt.set(St.TABLE,t||e.name.toLowerCase(),e),mt(St.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function yr(t){return ut.for(St.COLUMN).define({decorator:t=>(e,r)=>ht(lt.key(St.COLUMN,r),t||r)(e,r),args:[t]}).apply()}async function mr(t,e,r,s){if(s[r]&&(await this.select().where(Xt.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 wr(){const t=St.UNIQUE;return ut.for(t).define(X(),C(mr),ht(t,{})).apply()}async function br(t,e,r,s){throw new hr("This adapter does not support user identification")}function vr(){return ut.for(St.CREATED_BY).define({decorator:()=>(t,e)=>pt(A(br),ht(St.CREATED_BY,e),x(St.CREATED_BY))(t,e),args:[]}).apply()}function Ar(){return ut.for(St.UPDATED_BY).define({decorator:()=>(t,e)=>pt(N(br),ht(St.UPDATED_BY,e),x(St.UPDATED_BY))(t,e),args:[]}).apply()}function xr(){return T([a.CREATE])}function Er(){return T()}function Sr(t){const e="function"==typeof t&&t.name?t:t(),r=z.pk(e);return lt.allowedTypes(e,r)||[]}function Or(t,e=te,r=!0,s,i){const n=St.ONE_TO_ONE;return ut.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=Sr(t),c=[wt(),Rr(n,o),Z([t,...a]),A(ze,o,{priority:70}),N(He,o,{priority:70}),k(qe,o,{priority:70}),B(lr,o,{priority:70}),_(cr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Cr(t,e=te,r=!0,s,i){const n=St.ONE_TO_MANY;return ut.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=Sr(t),c=[wt(),Rr(n,o),tt([t,...a]),A(Ve,o,{priority:70}),N(Qe,o,{priority:70}),k(We,o,{priority:70}),B(lr,o,{priority:70}),_(cr,o,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Tr(t,e=te,r=!0,s,i){const n=St.MANY_TO_ONE;return ut.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=Sr(t),c=[wt(),Rr(n,o),Z([t,...a]),A(Je,o),N(Ke,o),k(Ze,o),_(cr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Nr(t,e=te,r=!0,s,i){const n=St.MANY_TO_MANY;return ut.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=Sr(t),c=[wt(),Rr(n,o),tt([t,...a]),A(tr,o),N(Qe,o),_(cr,o)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function kr(...t){return(e,r)=>{const s=lt.get(e,lt.key(St.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return pt(mt(lt.key(St.NO_VALIDATE,r),i))(e,r)}}function Br(){return kr(a.CREATE)}function _r(){return kr(a.UPDATE)}function Dr(){return kr(a.UPDATE,a.CREATE)}function Rr(t,e){return ut.for(St.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ht(t,e)(r,s),ht(lt.key(St.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class $r extends z{constructor(t){super(t)}}i([xr(),n("design:type",Date)],$r.prototype,"createdAt",void 0),i([Er(),n("design:type",Date)],$r.prototype,"updatedAt",void 0);let Ir=class extends $r{constructor(t){super(t)}};i([Ye({type:String,generated:!1}),n("design:type",String)],Ir.prototype,"id",void 0),i([q(),je(),n("design:type",Object)],Ir.prototype,"current",void 0),Ir=i([fr("??sequence"),Q(),n("design:paramtypes",[Object])],Ir);class Pr 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,zt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Et.FIND_BY}|${Et.LIST_BY}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Et.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 Rt?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof Rt||(this._bookmark=e);const n=Ne.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,u=RegExp(`^${Et.FIND_BY}|${Et.LIST_BY}`,"gi");if(!a.match(u))throw new Lt(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,Et.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Et.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 Jt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new Jt(`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 Lt("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 D(t)}}apply(t){const e="string"==typeof t?Pr.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new D(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 Lr,Fr,jr,Ur,Mr,Yr,Gr;class zr extends $t{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?Et.PAGE_BY:St.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 Wt("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?z.get(t):t,!this.fromSelector)throw new Wt("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 Wt("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new Wt("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 Wt("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===Kt.ASC)return Kt.ASC;if(e===Kt.DSC)return Kt.DSC;throw new Wt(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Kt).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new Wt("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=z.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 Wt(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=Ne.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 Lt("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=z.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 xt.AND:case xt.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 Xt){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case At.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case At.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case At.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case At.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case At.BIGGER_EQ:n.method=r+" bigger than equal";break;case At.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case At.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case At.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Wt("Unsupported operator "+s)}return n}squash(t){if(this.whereCondition&&this.whereCondition.comparison instanceof Xt)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Et.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Et.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Et.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Et.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Et.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Et.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Et.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 e;this.whereCondition&&(e=this.whereCondition.attr1);const r=this.orderBySelectors?.[0]?this.orderBySelectors[0]:e?[e,Kt.DSC]:[z.pk(this.fromSelector),Kt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:Et.LIST_BY,args:[s],params:n};return e&&(o.method=Et.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}async prepare(t){if(t=t||await this.adapter.context(St.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=vt.FIND_BY;void 0!==this.countSelector?(n=vt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=vt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=vt.AVG_BY,i=this.avgSelector):this.minSelector?(n=vt.MIN_BY,i=this.minSelector):this.maxSelector?(n=vt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=vt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=vt.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(vt.SELECT,this.selectSelector.join(` ${vt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;o.push(vt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map((([t,e])=>[t,e])),e.forEach((([t])=>{o.push(vt.THEN_BY,t)})))}if(this.groupBySelectors?.length&&n!==vt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;o.push(vt.GROUP_BY,t),e.forEach((t=>o.push(vt.THEN_BY,t)))}else this.groupBySelectors?.length&&n===vt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach((t=>o.push(vt.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 Wt(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(Lr="undefined"!=typeof S&&S)?Lr:Object]),n("design:returntype",Object)],zr.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Fr="undefined"!=typeof S&&S)?Fr:Object]),n("design:returntype",Object)],zr.prototype,"max",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,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ur="undefined"!=typeof S&&S)?Ur:Object]),n("design:returntype",Object)],zr.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Mr="undefined"!=typeof S&&S)?Mr:Object]),n("design:returntype",Object)],zr.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Yr="undefined"!=typeof S&&S)?Yr: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",[Xt]),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(Gr="undefined"!=typeof Key&&Key)?Gr: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 Hr extends $t{constructor(t){super(),this.name=t,this.observers=[],this.Context=Rt}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Pt,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}-${Ht.instance.generate()}`;const s=e.logger||j.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Ot,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 Rt||(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 $t.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=Ut(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 Rt||(t.push(r),r=void 0);const s=await Hr.prototype.flags(St.INITIALIZATION,{},...t);r=r?new Rt(r).accumulate({...s,parentContext:r}):(new Rt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Hr.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 qr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new u(`Failed to boot ${t} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof Rt||(t.push(r),r=void 0);const s=await Hr.prototype.flags(St.SHUTDOWN,{},...t);r=r?new Rt(r).accumulate({...s,parentContext:r}):(new Rt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Hr.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 qr){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)],Hr.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Hr.prototype,"unObserve",null);class qr extends Hr{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,St.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 ${this.name} service...`)}}function Vr(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Yt(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)],qr.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],qr.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],qr.prototype,"client",null);const Qr=()=>Vr(a.CREATE),Wr=()=>Vr(a.READ),Jr=()=>Vr(a.UPDATE),Xr=()=>Vr(a.DELETE);function Kr(t){return(e,i,n)=>{n||i?(wt()(e,i),t=t||lt.type(e.constructor,i)):t=t||e,t=Ut(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 lt.set(St.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 Zr(t){const e=St.AUTH;return ut.for(e).define({decorator:t=>mt(e,t),args:[t]}).apply()}const ts=t=>mt(St.AUTH_ROLE,t);function es(t,e){const r=St.DECAF_ROUTE;return ut.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return pt(gt(lt.key(r,i),o))(s,i,n)},args:[]}).apply()}const rs=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class ss extends Hr{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ne.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=rs(t);try{const t=Hr.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.override(t,...e):Reflect.get(r,s,i)})}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,St.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,Et.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,Et.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,Et.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,Et.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,St.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=rs(e||t);try{r=ss.get(e)}catch(t){r=void 0}if(r instanceof ss)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Kr(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([Qr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ss.prototype,"create",null),i([Qr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ss.prototype,"createAll",null),i([Xr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ss.prototype,"delete",null),i([Xr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ss.prototype,"deleteAll",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ss.prototype,"read",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ss.prototype,"readAll",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],ss.prototype,"query",null),i([Jr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ss.prototype,"update",null),i([Jr(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],ss.prototype,"updateAll",null);class is extends qr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof Rt||!e.every((t=>Array.isArray(t))))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,St.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 ns=class extends z{constructor(t){super(t),this.strategy=Se.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=Oe.FULL}};i([q(),Z(String),et(Se),bt("the backoff strategy"),n("design:type",String)],ns.prototype,"strategy",void 0),i([q(),bt("base interval between attempts"),n("design:type",Number)],ns.prototype,"baseMs",void 0),i([q(),bt("max interval"),n("design:type",Number)],ns.prototype,"maxMs",void 0),i([Z(String),et(Oe),bt("optional jitter strategy"),n("design:type",String)],ns.prototype,"jitter",void 0),ns=i([Q(),n("design:paramtypes",[Object])],ns);let os=class extends z{constructor(t){super(t)}};async function as(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 Ht.instance.generate(i)}function cs(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=St.UUID;return ut.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[q(),x(St.UUID),A(as,s,{priority:54})];return t&&i.push(N(as,s,{priority:54})),t||i.push(v()),pt(...i)},args:[t,e,...r]}).apply()}i([q(),bt("The error message"),n("design:type",String)],os.prototype,"message",void 0),i([wt(),bt("The error stack"),n("design:type",String)],os.prototype,"stack",void 0),i([wt(),bt("The error code"),n("design:type",String)],os.prototype,"code",void 0),i([wt(),bt("The error details"),n("design:type",Object)],os.prototype,"details",void 0),os=i([Q(),n("design:paramtypes",[Object])],os);let ls=class extends z{constructor(t){super(t),this.ts=new Date}};i([$(["taskId","classification","uuid"],":"),Ye(),n("design:type",String)],ls.prototype,"id",void 0),i([v(),q(),I(),cs(!1),n("design:type",String)],ls.prototype,"uuid",void 0),i([v(),q(),n("design:type",String)],ls.prototype,"taskId",void 0),i([rt(),q(),n("design:type",Date)],ls.prototype,"ts",void 0),i([v(),q(),et(Ce),n("design:type",String)],ls.prototype,"classification",void 0),i([wt(),v(),n("design:type",Object)],ls.prototype,"payload",void 0),ls=i([fr("task_event"),Q(),n("design:paramtypes",[Object])],ls);class us 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 Xt){const r=this.serializePlain(t,...e);return r[it.ANCHOR]="??condition",r}return z.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 lt.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?Xt.from(r):z.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 ds=class extends z{constructor(t){super(t),this.ts=new Date}};i([rt(),q(),n("design:type",Date)],ds.prototype,"ts",void 0),i([q(),et(Y),n("design:type",String)],ds.prototype,"level",void 0),i([q(),wt(),n("design:type",String)],ds.prototype,"msg",void 0),i([wt(),n("design:type",Object)],ds.prototype,"meta",void 0),ds=i([Q(),n("design:paramtypes",[Object])],ds);let hs=class extends z{constructor(t){super(t),this.atomicity=Te.ATOMIC,this.status=Ee.PENDING,this.attempt=0,this.logTail=[]}};i([Ye({type:"uuid"}),bt("the task id"),n("design:type",String)],hs.prototype,"id",void 0),i([q(),Z(String),et(Te),bt("defines a single or composite task"),n("design:type",String)],hs.prototype,"atomicity",void 0),i([q(),bt("Holds task classification - must match @task()"),n("design:type",String)],hs.prototype,"classification",void 0),i([wt(),bt("optional task name for ambiguity"),n("design:type",String)],hs.prototype,"name",void 0),i([q(),Z(String),et(Ee),bt("Holds the task current status"),n("design:type",String)],hs.prototype,"status",void 0),i([wt(),P(us),bt("Holds task input"),n("design:type",Object)],hs.prototype,"input",void 0),i([wt(),P(us),bt("Holds the task output when successfully completed"),n("design:type",Object)],hs.prototype,"output",void 0),i([wt(),P(),bt("Holds the error for failed tasks"),n("design:type",os)],hs.prototype,"error",void 0),i([q(),nt(0),bt("Holds the current attempt"),n("design:type",Number)],hs.prototype,"attempt",void 0),i([nt(1),q(),bt("max attempts for the task"),n("design:type",Number)],hs.prototype,"maxAttempts",void 0),i([q(),P(),bt("backoff configuration"),n("design:type",ns)],hs.prototype,"backoff",void 0),i([rt(),bt("Next execution timestamp"),n("design:type",Date)],hs.prototype,"nextRunAt",void 0),i([rt(),bt("Task scheduled timestamp"),n("design:type",Date)],hs.prototype,"scheduledTo",void 0),i([wt(),bt("Task lease owner identifier"),n("design:type",String)],hs.prototype,"leaseOwner",void 0),i([rt(),bt("Task lease expiration timestamp"),n("design:type",Date)],hs.prototype,"leaseExpiry",void 0),i([wt(),P(),bt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],hs.prototype,"steps",void 0),i([nt(0),wt(),bt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],hs.prototype,"currentStep",void 0),i([wt(),P(),bt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],hs.prototype,"stepResults",void 0),i([wt(),P(),bt("Holds the task log entries"),n("design:type",Array)],hs.prototype,"logTail",void 0),i([yr(),xr(),bt("timestamp of creation"),n("design:type",Date)],hs.prototype,"createdAt",void 0),i([yr(),Er(),bt("timestamp of last update"),n("design:type",Date)],hs.prototype,"updatedAt",void 0),i([yr(),vr(),bt("Holds the creator of the task"),n("design:type",String)],hs.prototype,"createdBy",void 0),i([yr(),Ar(),bt("Holds the creator of the task"),n("design:type",String)],hs.prototype,"updatedBy",void 0),hs=i([bt("Holds the current step when applicable"),fr("tasks"),Q(),n("design:paramtypes",[Object])],hs);let ps=class extends z{constructor(t){super(t)}};i([q(),bt("The status of a step"),n("design:type",String)],ps.prototype,"status",void 0),i([wt(),bt("The result of a successful step"),n("design:type",Object)],ps.prototype,"output",void 0),i([wt(),bt("the error of a failed step"),n("design:type",os)],ps.prototype,"error",void 0),ps=i([Q(),n("design:paramtypes",[Object])],ps);let gs=class extends z{constructor(t){super(t)}};i([q(),wt(),bt("task handler type"),n("design:type",String)],gs.prototype,"classification",void 0),i([bt("optional task step input"),wt(),n("design:type",Object)],gs.prototype,"input",void 0),gs=i([Q(),n("design:paramtypes",[Object])],gs);class fs extends z{constructor(t){super(t),this.baseMs=1e3,this.jitter=Oe.FULL,this.maxMs=6e4,this.strategy=Se.EXPONENTIAL,z.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 ns(this)}}i([q(),nt(1e3),n("design:type",Number)],fs.prototype,"baseMs",void 0),i([q(),et(Oe),n("design:type",String)],fs.prototype,"jitter",void 0),i([ot("baseMs"),nt(1e3),q(),n("design:type",Number)],fs.prototype,"maxMs",void 0),i([q(),et(Se),n("design:type",String)],fs.prototype,"strategy",void 0);class ys extends z{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 fs,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=Ee.PENDING,this.atomicity=Te.ATOMIC,this.backoff=new ns,this.maxAttempts=1,z.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new hs(this)}}i([q(),n("design:type",String)],ys.prototype,"classification",void 0),i([wt(),n("design:type",String)],ys.prototype,"name",void 0),i([q(),n("design:type",String)],ys.prototype,"status",void 0),i([q(),n("design:type",String)],ys.prototype,"atomicity",void 0),i([q(),n("design:type",ns)],ys.prototype,"backoff",void 0),i([wt(),n("design:type",Object)],ys.prototype,"input",void 0),i([nt(1),q(),n("design:type",Number)],ys.prototype,"maxAttempts",void 0);class ms extends ys{constructor(t){super(t),this.stepResults=[],z.fromModel(this,t),this.atomicity=Te.COMPOSITE}setAtomicity(t){throw new u("Atomicity locked to "+Te.COMPOSITE)}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new gs({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([tt((()=>gs)),n("design:type",Array)],ms.prototype,"steps",void 0);class ws extends It{get type(){if(!this._type){const t=lt.get(this.constructor,_e);"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 ut.for(_e).define({decorator:t=>e=>{const r={type:t};return lt.set(_e,t,e),mt(_e,r)(e)},args:[t]}).apply()}let vs=class extends ws{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof Xt)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=Xt.attr("status").eq(Ee.SUCCEEDED).and(Xt.attr("updatedAt").lte(t.successfulExpiry)),i=Xt.attr("status").eq(Ee.FAILED).and(Xt.attr("updatedAt").lte(t.failedExpiry)),n=Xt.attr("status").eq(Ee.CANCELED).and(Xt.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([Re(hs),n("design:type",Object)],vs.prototype,"tasks",void 0),vs=i([bs("cleanup-task"),n("design:paramtypes",[])],vs);class As{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)=>"logger"===s?Reflect.get(r,s).for(t,...e):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 xs(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 Ce.LOG:{const s=r.payload;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 Ce.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Ce.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=G(e);switch(e){case Ee.SUCCEEDED:s=s.green.bold;break;case Ee.RUNNING:s=s.blue.bold;break;case Ee.PENDING:s=s.yellow;break;case Ee.WAITING_RETRY:s=s.yellow.bold;break;case Ee.FAILED:s=s.red.bold;break;case Ee.CANCELED:s=s.magenta.bold;break;case Ee.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 Es(t,e){const r=e.strategy===Se.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===Oe.FULL?Math.floor(Math.random()*s):s}function Ss(t){return new os({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Os(t){return new Promise((e=>setTimeout(e,t)))}class Cs extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=Cs.name,Object.setPrototypeOf(this,Cs.prototype)}}class Ts extends Rt{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 Cs({status:t,...e})}cancel(t,e){this.changeState(Ee.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(Ee.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(Ee.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof os?t:t instanceof Error?Ss(t):new os({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class Ns{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=lt.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 ks extends $t{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,St.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(){}observe(t){if(!(t instanceof Qt))throw new Lt("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=Qt.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 Lt("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:z.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"}}Qt&&(Qt._baseDispatch=ks);class Bs extends $t{static{this.lock=new ct}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ne.forModel(Ir,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 Bs.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 Ir({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 Ir({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(Ht.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(qt.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 Lt(`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 Bs.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([Ir,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return z.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 Lt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}Qt._baseSequence=Bs;class _s extends Pt{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(ls,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=Qt.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}`)}))}}class Ds extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class Rs extends Ds{constructor(t,e,r){super(Rs.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class $s extends Ds{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super($s.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class Is extends Ds{constructor(t,e,r){super(Is.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class Ps extends Ds{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(Ps.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class Ls{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===ls||t===z.tableName(ls)))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([Ee.SUCCEEDED,Ee.FAILED,Ee.CANCELED,Ee.SCHEDULED])}wait(){return this.awaitStatusTerminal([Ee.SUCCEEDED,Ee.FAILED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(xs(t,e))}logs(t){this.pipe((async e=>{if(e.classification!==Ce.LOG)return;const r=e.payload;await t(r)}),Ce.LOG)}pipe(t,e=Ce.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(Ee.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(Ee.FAILED,t)}onCancel(t){return this.registerStatusHandler(Ee.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===Ee.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[Ee.SUCCEEDED,Ee.CANCELED,Ee.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!==Ee.SUCCEEDED?(r===Ee.FAILED&&this.fail(),r===Ee.CANCELED&&this.cancel(t),r===Ee.WAITING_RETRY&&this.retry(),r===Ee.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,Ce.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Ce.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new Rt),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===Ee.SUCCEEDED&&(e.output=this.task.output),t!==Ee.FAILED&&t!==Ee.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 ls({classification:Ce.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case Ee.FAILED:return new Rs(this.task.id,e,r);case Ee.CANCELED:return new Is(this.task.id,e,r);case Ee.WAITING_RETRY:return new $s(this.task.id,e,r);case Ee.SCHEDULED:return new Ps(this.task.id,e,r);default:return new Rs(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case Ee.CANCELED:return"cancelled";case Ee.WAITING_RETRY:return"retry";case Ee.SCHEDULED:return"reschedule";case Ee.FAILED:return"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===Ee.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[Ce.ALL]?[...this.pipes[Ce.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 Fs extends It{get Context(){return Ts}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=Ne.forModel(hs,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=Ne.forModel(ls,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new at,this.running=!1,this.config=Object.assign({},De,t,{bus:t.bus||new _s,registry:t.registry||new Ns})}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 Ls(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=Ee.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 Ls(this.bus,i)}}async ensureTaskError(t,e){if(![Ee.FAILED,Ee.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await Os(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===Ee.SUCCEEDED||s.status===Ee.FAILED)return s;s.status=Ee.CANCELED;const i=new os({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,Ee.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,St.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(Xt.attr("status").eq(Ee.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 Os(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=Xt.attribute("status").eq(Ee.PENDING),i=Xt.attribute("status").eq(Ee.WAITING_RETRY).and(Xt.attribute("nextRunAt").lte(r)),n=Xt.attribute("status").eq(Ee.RUNNING).and(Xt.attribute("leaseExpiry").lte(r)),o=Xt.attribute("status").eq(Ee.SCHEDULED).and(Xt.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 hs({...i,status:Ee.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 Ts(e).accumulate({taskId:t.id,logger:new As(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,Ee.RUNNING);try{let e;if(t.atomicity===Te.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=Ee.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,Ee.SUCCEEDED,e)}catch(e){try{t=await this.tasks.read(t.id,s)}catch{}if(e instanceof Cs)return void await this.handleTaskStateChange(e.request,t,s);if(r.error("task execution error",e),t.atomicity===Te.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex((t=>t.status===Ee.FAILED));0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=Ss(e);if(i<t.maxAttempts){const o=Es(i,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+o);t.attempt=i,t.status=Ee.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,Ee.WAITING_RETRY,n,e)}else t.attempt=i,t.status=Ee.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,Ee.FAILED,n,e)}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case Ee.CANCELED:{const s=t.error??new os({message:`Task ${e.id} canceled`});return e.status=Ee.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ee.CANCELED,s),void await r.pipe(Y.warn,"Task canceled via context")}case Ee.WAITING_RETRY:{const s=(e.attempt??0)+1,i=Es(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new os({message:`Task ${e.id} requested retry`});return e.status=Ee.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,Ee.WAITING_RETRY,o),void await r.pipe(Y.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case Ee.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new os({message:`Task ${e.id} rescheduled`});return e.status=Ee.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Ee.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 Ts&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===Ee.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 ps({status:Ee.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 ps({status:Ee.FAILED,error:Ss(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=Ss(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof ns)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new ns(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 gs)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new gs(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 ps)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new ps(e)})):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map((([t,e,r])=>new ds({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 Ts&&await t.flush();const n={status:r};s&&s instanceof os?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,Ce.STATUS,n),a=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new ls({...o,payload:a});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Ce.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,Ce.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new ls({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,hs,...r)}}class js extends qr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof Rt)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,St.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new Fs(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,St.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 Lt("Updates to tasks are not available")}async updateAll(t,...e){throw new Lt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Et.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,Et.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,Et.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,Et.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,St.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,St.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")}}i([Re(hs),n("design:type",Object)],js.prototype,"repo",void 0),i([Qr(),n("design:type",Function),n("design:paramtypes",[hs,void 0]),n("design:returntype",Promise)],js.prototype,"create",null),i([Qr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],js.prototype,"createAll",null),i([Xr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],js.prototype,"delete",null),i([Xr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],js.prototype,"deleteAll",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],js.prototype,"read",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],js.prototype,"readAll",null),i([Wr(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],js.prototype,"query",null),i([Jr(),n("design:type",Function),n("design:paramtypes",[hs,void 0]),n("design:returntype",Promise)],js.prototype,"update",null),i([Jr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],js.prototype,"updateAll",null),e.setRegistry(new Be);const Us="##VERSION##",Ms="##PACKAGE##";lt.registerLibrary(Ms,Us);export{It as AbsContextual,Qt as Adapter,hr as AuthorizationError,Se as BackoffStrategy,$r as BaseModel,Fe as BigIntSequence,Zt as Cascade,vs as CleanUpTask,qr as ClientBasedService,ms as CompositeTaskBuilder,Xt as Condition,gr as ConnectionError,Rt as Context,Dt as ContextLock,$t as ContextualLoggedClass,Ct as DefaultAdapterFlags,te as DefaultCascade,Ot as DefaultContextFlags,fe as DefaultRepositoryFilters,Pe as DefaultSequenceOptions,De as DefaultTaskEngineConfig,ks as Dispatch,pr as ForbiddenError,xt as GroupOperator,Be as InjectablesRegistry,Oe as JitterStrategy,se as MethodQueryBuilder,Ft as MigrationError,jt as MigrationRuleError,ss as ModelService,Bt as MultipleSelectOperationKeys,Nt as NonTransactionOperationKeys,Ie as NoneSequenceOptions,Le as NumericSequence,$e as ObserverError,Pt as ObserverHandler,At as Operator,ee as OperatorsMap,Kt as OrderDirection,Ms as PACKAGE_NAME,_t as PaginationOperationKeys,Pr as Paginator,Jt as PagingError,St as PersistenceKeys,is as PersistenceService,Et as PreparedStatementKeys,vt as QueryClause,Wt as QueryError,Ne as Repository,kt as SelectOperationKeys,Bs as Sequence,Ir as SequenceModel,qt as Serial,Hr as Service,zr as Statement,fs as TaskBackoffBuilder,ns as TaskBackoffModel,ys as TaskBuilder,Is as TaskCancelError,Ts as TaskContext,Ds as TaskControlError,Fs as TaskEngine,os as TaskErrorModel,_s as TaskEventBus,ls as TaskEventModel,Ce as TaskEventType,Rs as TaskFailError,ws as TaskHandler,Ns as TaskHandlerRegistry,us as TaskIOSerializer,ds as TaskLogEntryModel,As as TaskLogger,hs as TaskModel,Ps as TaskRescheduleError,$s as TaskRetryError,js as TaskService,Ee as TaskStatus,ps as TaskStepResultModel,gs as TaskStepSpecModel,Ls as TaskTracker,Te as TaskType,_e as TasksKey,Tt as TransactionOperationKeys,Ht as UUID,Lt as UnsupportedError,Us as VERSION,oe as applyViewDecorator,Zr as auth,ar as cacheModelForPopulate,lr as cascadeDelete,yr as column,Es as computeBackoffMs,Qr as create,Ge as createOrUpdate,xr as createdAt,vr as createdBy,br as createdByOnCreateUpdate,Xr as del,ke as generateInjectableNameForRepository,rr as getAndConstructJunctionTable,ye as getFilters,xs as getLogPipe,Sr as getPkTypes,nr as getPopulateKey,or as getTagForDeleteKey,je as index,Ut as injectableServiceKey,Yt as isOperationBlocked,Nr as manyToMany,tr as manyToManyOnCreate,ir as manyToManyOnDelete,sr as manyToManyOnUpdate,Tr as manyToOne,Je as manyToOneOnCreate,Ze as manyToOneOnDelete,Ke as manyToOneOnUpdate,kr as noValidateOn,Br as noValidateOnCreate,Dr as noValidateOnCreateUpdate,_r as noValidateOnUpdate,Gt as normalizeImport,Cr as oneToMany,Ve as oneToManyOnCreate,We as oneToManyOnDelete,Qe as oneToManyOnUpdate,Or as oneToOne,ze as oneToOneOnCreate,qe as oneToOneOnDelete,He as oneToOneOnUpdate,pe as onlyOnBulk,ce as onlyOnCreate,ue as onlyOnDelete,ge as onlyOnFilter,he as onlyOnSingle,de as onlyOnTransactional,le as onlyOnUpdate,Ye as pk,Me as pkDec,Ue as pkOnCreate,cr as populate,zt as prefixMethod,ie as prepared,Mt as promiseSequence,ne as query,Wr as read,Rr as relation,Re as repository,dr as repositoryFromTypeMetadata,ts as roles,es as route,Ss as serializeError,Kr as service,Os as sleep,fr as table,bs as task,wr as unique,mr as uniqueOnCreateUpdate,Jr as update,Er as updatedAt,Ar as updatedBy,cs as uuid,as as uuidCreateUpdateHandler,Xe as validBidirectionalRelation,ae as view};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|