@decaf-ts/core 0.28.1 → 0.29.0
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/cjs/index.cjs +3 -3
- package/lib/cjs/tasks/TaskContext.cjs +3 -0
- package/lib/cjs/tasks/TaskContext.cjs.map +1 -1
- package/lib/cjs/tasks/TaskEngine.cjs +148 -69
- package/lib/cjs/tasks/TaskEngine.cjs.map +1 -1
- package/lib/cjs/tasks/builder.cjs +4 -0
- package/lib/cjs/tasks/builder.cjs.map +1 -1
- package/lib/cjs/tasks/constants.cjs +1 -0
- package/lib/cjs/tasks/constants.cjs.map +1 -1
- package/lib/cjs/tasks/models/TaskStepSpecModel.cjs +6 -0
- package/lib/cjs/tasks/models/TaskStepSpecModel.cjs.map +1 -1
- package/lib/esm/index.js +3 -3
- package/lib/esm/tasks/TaskContext.js +3 -0
- package/lib/esm/tasks/TaskContext.js.map +1 -1
- package/lib/esm/tasks/TaskEngine.js +148 -69
- package/lib/esm/tasks/TaskEngine.js.map +1 -1
- package/lib/esm/tasks/builder.js +4 -0
- package/lib/esm/tasks/builder.js.map +1 -1
- package/lib/esm/tasks/constants.js +1 -0
- package/lib/esm/tasks/constants.js.map +1 -1
- package/lib/esm/tasks/models/TaskStepSpecModel.js +6 -0
- package/lib/esm/tasks/models/TaskStepSpecModel.js.map +1 -1
- package/lib/types/index.d.cts +3 -3
- package/lib/types/index.d.mts +3 -3
- package/lib/types/tasks/TaskContext.d.cts +2 -0
- package/lib/types/tasks/TaskContext.d.mts +2 -0
- package/lib/types/tasks/TaskEngine.d.cts +5 -0
- package/lib/types/tasks/TaskEngine.d.mts +5 -0
- package/lib/types/tasks/builder.d.cts +1 -0
- package/lib/types/tasks/builder.d.mts +1 -0
- package/lib/types/tasks/models/TaskStepSpecModel.d.cts +1 -0
- package/lib/types/tasks/models/TaskStepSpecModel.d.mts +1 -0
- package/lib/types/tasks/types.d.cts +4 -0
- package/lib/types/tasks/types.d.mts +4 -0
- package/package.json +1 -1
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Metadata as t,Decoration as e,DefaultFlavour as r,apply as s,methodMetadata as i,propMetadata as n,DecorationKeys as a,uses as o,metadata as c,prop as l,method as u,description as d}from"@decaf-ts/decoration";import{Model as h,hashObj as p,required as g,sf as f,isEqual as y,model as m,ValidationKeys as w,type as v,async as b,list as A,option as x,date as E,JSONSerializer as O,ModelKeys as C,min as k,minlength as T,gt as N}from"@decaf-ts/decorator-validation";import{DefaultRepositoryFlags as D,OperationKeys as _,BulkCrudOperationKeys as I,Context as B,InternalError as P,ValidationError as R,DBKeys as $,Repository as F,wrapMethodWithContext as L,wrapMethodWithContextForUpdate as M,enforceDBDecorators as j,reduceErrorsToPrint as U,NotFoundError as G,DefaultSeparator as Y,readonly as z,onCreate as H,generated as q,onUpdate as V,BadRequestError as W,timestamp as Q,onCreateUpdate as J,ConflictError as X,version as Z,afterAny as tt,onDelete as et,SerializationError as rt,prefixMethod as st,composed as it,transient as nt,serialize as at,BaseError as ot}from"@decaf-ts/db-decorators";import{__decorate as ct,__metadata as lt}from"tslib";import{Logging as ut,LoggedClass as dt,final as ht,toCamelCase as pt,LogLevel as gt,style as ft}from"@decaf-ts/logging";import{Lock as yt,MultiLock as mt,TransactionalKeys as wt}from"@decaf-ts/transactional-decorators";import{Injectables as vt,InjectableRegistryImp as bt,inject as At,injectable as St}from"@decaf-ts/injectable-decorators";var xt,Et,Ot,Ct;(t=>{t.FIND_BY="findBy",t.PAGE_BY="pageBy",t.COUNT_BY="countBy",t.SUM_BY="sumBy",t.AVG_BY="avgBy",t.MIN_BY="minBy",t.MAX_BY="maxBy",t.DISTINCT_BY="distinctBy",t.GROUP_BY_PREFIX="groupBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(xt||(xt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.STARTS_WITH="STARTS_WITH",t.ENDS_WITH="ENDS_WITH",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(Et||(Et={})),(t=>{t.AND="AND",t.OR="OR"})(Ot||(Ot={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_BY_PAGINATE="findByPaginate",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ct||(Ct={}));const kt="__self__";var Tt;(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.SEQUENCE="sequence",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute",t.THROTTLE="throttle",t.PERSISTENT_VERSION="persistent-version",t.DEFAULT_QUERY_ATTR="default-query-attr"})(Tt||(Tt={}));const Nt=Object.assign({},{ignoreDevSafeGuards:!1}),Dt=Object.assign({},D,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1,maxConcurrentTransactions:-1}),_t=[_.CREATE,_.UPDATE,_.DELETE,I.CREATE_ALL,I.UPDATE_ALL,I.DELETE_ALL],It=[_.READ,I.READ_ALL],Bt=[Tt.STATEMENT,Ct.FIND_ONE_BY],Pt=[Tt.QUERY,Ct.PAGE_BY,Ct.FIND_BY_PAGINATE,Ct.LIST_BY,Ct.FIND_BY,Ct.FIND,Ct.PAGE],Rt=[Ct.PAGE_BY,Ct.FIND_BY_PAGINATE,Ct.PAGE];class $t extends B{constructor(t){super(t)}static{this.factory=t=>(new $t).accumulate(Object.assign({},t,{timestamp:new Date,logger:t.logger||ut.get()}))}static async from(t,e,r,...s){return this.factory(Object.assign({},e||{},{operation:t,model:r,affectedTables:r,args:s,logger:e?.logger||ut.get()}))}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new P(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter(t=>!e.has(t)),s.length)){const r=s.map(r=>r.getFromChildren(t,e)).reduce((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t),[]).filter(t=>null!=t);if(!r.length)return;return r.some(t=>"object"!=typeof t)?r[0]:r.reduce((t,e)=>Object.assign(t,e),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new P("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 Ft extends dt{logCtx(t,e,r=!1,s){return Ft.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||ut.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 a=n instanceof $t||(t=>{if(!t||"object"!=typeof t)return!1;const e=t;return"function"==typeof e.get&&"function"==typeof e.accumulate&&"function"==typeof e.override&&"function"==typeof e.toOverrides&&void 0!==e.cache})(n);if(n&&!a&&(s.push(n),n=void 0),!r&&!a)throw new P("No context provided");if(a&&!r){if(!n)throw new P("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 P("No contextual provided");if(!this.context)throw new P("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 Lt extends Ft{constructor(){super(),this._Context=$t}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 $t||(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 Mt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new P("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 P("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=Ft.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(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 jt extends P{constructor(t){super(t,jt.name,500)}}class Ut extends P{constructor(t,e=Ut.name){super(t,e,500)}}class Gt extends Ut{constructor(t){super(t,Gt.name)}}function Yt(e){if(!e)throw new P("No name provided");return"string"==typeof e?e.replaceAll(".","-"):t.Symbol(t.constr(e)).toString().replaceAll(".","-")}async function zt(t,e=!1){if(!e){const e=[];for(const r of t)e.push(await r());return e}const r=[];for(const e of t)try{r.push({status:"fulfilled",value:await e()})}catch(t){r.push({status:"rejected",reason:t})}return r}const Ht=[_.CREATE,_.READ,_.UPDATE,_.DELETE];function qt(t){return Ht.includes(t)}function Vt(e,r,s){const i=t.get(e,_.REFLECT+_.BLOCK)||{};if(!i?.handler)return!1;const n=void 0===s&&qt(r)?"crud":r,a=void 0===s&&qt(r)?r:s,o=i.args?.[0]||[];return i.handler(o,n,a)??!1}async function Wt(t){return t.then(t=>t.default||t)}function Qt(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 Gt)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 Jt{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 Jt._instance||(Jt._instance=new Jt),Jt._instance}}class Xt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Xt._instance||(Xt._instance=new Xt),Xt._instance}}class Kt extends yt{static{this.registry=new WeakMap}static for(t,e){let r=Kt.registry.get(t);return r||(r=new Kt(e),Kt.registry.set(t,r)),r}constructor(t){super(),this.waiters=[],this.permits=t}async acquire(t){if(0>=this.permits)return new Promise(t=>this.waiters.push(t));this.permits--}release(t){const e=this.waiters.shift();e?e():this.permits++}}class Zt{constructor(t,...e){this.adapter=t,this.depth=0}async begin(t){const{log:e,ctx:r}=this.adapter.logCtx([t],this.begin),s=r.getOrUndefined("maxConcurrentTransactions"),i="number"==typeof s?s:Dt.maxConcurrentTransactions;if(0===i)throw e.debug(`Rejecting transaction on adapter "${this.adapter.alias}": transactions are disabled (maxConcurrentTransactions=0)`),new jt(`Transactions are disabled for adapter "${this.adapter.alias}" (maxConcurrentTransactions=0)`);i>0&&(e.silly(`Gating transaction on adapter "${this.adapter.alias}" (maxConcurrentTransactions=${i})`),this.semaphore=Kt.for(this.adapter,i),await this.semaphore.acquire(r))}async commit(t){const{ctx:e}=this.adapter.logCtx([t],this.commit);this.semaphore?.release(e)}async rollback(t,e){const{ctx:r}=this.adapter.logCtx([e],this.rollback);this.semaphore?.release(r)}}const te=e.flavourResolver.bind(e);e.flavourResolver=e=>{const s=t=>{if(!t)return;const e=se._cache?.[t];return e?.flavour||t};try{const i=te(e);if(i&&i!==r)return s(i);const n="function"==typeof e?e:e?.constructor,a=n&&"function"==typeof t.registeredFlavour?t.registeredFlavour(n):void 0;if(a&&a!==r)return s(a);const o=se._currentFlavour;if(o){const t=se._cache?.[o];return t?.flavour?t.flavour:s(o)}}catch(t){return r}};const ee=Symbol("AdapterProxyCleanup");function re(t,e,r,s){if(!e)return t;const i=t,n=[],a=[];for(const t of i)"fulfilled"===t.status?n.push(t.value):a.push(t.reason);if(a.length){r.warn(`Bulk ${s} encountered ${a.length} failure(s) while continuing`);const t=new AggregateError(a,`Bulk ${s} failed for ${a.length} item(s)`);throw t.results=i,t}return n}class se extends Lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!se._baseRepository)throw new P("This should be overridden when necessary. Otherwise it will be replaced lazily");return se._baseRepository}transactionLock(...t){return new Zt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new P("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[ee];"function"==typeof e&&await e()};if(t)try{await s(this.proxies[t]),delete this.proxies[t]}catch(e){r.error("Failed to cleanup proxied adapter "+t,e)}else for(const t in this.proxies){try{await s(this.proxies[t])}catch(e){r.error("Failed to cleanup proxied adapter "+t,e);continue}delete this.proxies[t]}}async shutdown(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Tt.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(Tt.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:e}=(await this.logCtx(t,Tt.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...r),this.dispatch&&await this.dispatch.close(...r)})()}catch(t){throw new P("Failed to create shutdown wrapper: "+t)}finally{this.internalLock.release(Tt.SHUTDOWN)}try{await this.shutdownPromise}catch(t){e.error("Error during proxy shutdown",t)}finally{this.shutdownPromise=void 0}}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.internalLock=new yt,this.alias in se._cache)throw new P(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);se._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in se._cache||(se._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),se._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),se._currentFlavour=this.alias)}Dispatch(){return new se._baseDispatch}ObserverHandler(){return new Mt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new se._baseSequence(t,this,e)}async flags(e,r,s,...i){if("string"==typeof r)throw new P("Model must be a constructor or array of constructors or undefined. this should be impossible");const n=Array.isArray(r)?r.length?r[0]:void 0:r,a=n?""+h.tableName(n):"";s.correlationId=s.correlationId||`${a}|${e}|${Jt.instance.generate()}`;const o=s.logger||ut.for(this),c=Object.assign({},Dt.cacheForPopulate,s.cacheForPopulate);return Object.assign({},Dt,s,{affectedTables:r?[...new Set([...(Array.isArray(r)?r:[r]).filter(Boolean),...s.affectedTables?Array.isArray(s.affectedTables)?s.affectedTables:[s.affectedTables]:[]])]:s.affectedTables,cacheForPopulate:c,args:i,writeOperation:_t.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:r?t.validationExceptions(Array.isArray(r)&&r[0]?r[0]:r,e):[],logger:o})}get Context(){return $t}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 $t||(s.push(i),i=void 0);const n=(()=>{if(!i)return!1;try{return!!i.get("allowGenerationOverride")}catch{return!1}})();e=i?Object.assign({},i.toOverrides(),e):e,n&&(e.allowGenerationOverride=!0);const a=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,...a,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,...a,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(a)}return(new this.Context).accumulate({...a})}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 P(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[Tt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[Tt.METADATA]),Object.defineProperty(i,Tt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[Tt.METADATA]})),{record:i,id:t[h.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),o=h.pk(e),c=new e;c[o]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[Tt.METADATA],u=Object.keys(c).filter(t=>t!==o).reduce((r,s)=>(r[s]=t[h.columnName(e,s)],r),c);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in u&&void 0!==u[t])throw new P(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);u[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(u,Tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),u}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new R("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new R("Ids and models must have the same length");const a=h.tableName(t);i.debug(`Creating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),c=e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})));return re(o?await zt(c,!0):await zt(c),o,i,I.CREATE_ALL)}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=h.tableName(t);s.debug(`Reading ${e.length} entries ${n} table`);const a=!(i.get("breakOnSingleFailureInBulk")??1),o=e.map(e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0})));return re(a?await zt(o,!0):await zt(o),a,s,I.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new P("Ids and models must have the same length");const a=h.tableName(t);i.debug(`Updating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),c=e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})));return re(o?await zt(c,!0):await zt(c),o,i,I.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})));return re(n?await zt(a,!0):await zt(a),n,s,I.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new P("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new P("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),a=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(s&&o||!s&&a)&&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(e){return t.flavourOf(e)}static get currentFlavour(){if(!se._currentFlavour)throw new P("No persistence flavour set. Please initialize your adapter");return se._currentFlavour}static get current(){return se.get(this.currentFlavour)}static unregister(t){if(!t)return;const e=se._cache[t];e&&(delete se._cache[t],se._currentFlavour===t&&(se._currentFlavour=void 0),e.flavour&&se._cache[e.flavour]&&se._cache[e.flavour]===e&&delete se._cache[e.flavour])}static get(t){if(!t)return se.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new P(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(e){try{return t.flavouredAs(e).filter(h.isModel)}catch(t){throw new P(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} - ${p(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return Reflect.defineProperty(i,ee,{value:async()=>{if(!s)return;const t=["cancel","close","destroy","disconnect"];for(const e of t){const t=s[e];if("function"==typeof t)try{const e=t.call(s);e instanceof Promise&&await e}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=i,i}migrations(){return t.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}var ie,ne,ae,oe,ce;ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,Object,$t]),lt("design:returntype",Promise)],se.prototype,"context",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],se.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],se.prototype,"unObserve",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],se.prototype,"client",null),(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(ie||(ie={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(ne||(ne={})),(t=>{t.NONE="none",t.FULL="full"})(ae||(ae={})),(t=>{t.STATUS="status",t.UPDATE="update",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(oe||(oe={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(ce||(ce={}));const le="tasks",ue={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};t.tasks=(()=>t.innerGet(Symbol.for(le))).bind(t),t.taskFor=(e=>{const r=t.tasks();return r?r[e]:void 0}).bind(t),t.validationExceptions=((e,r)=>{const s=t.get(e,Tt.NO_VALIDATE)||[],i=Object.entries(s).filter(([,t])=>t.includes(r)).map(([t])=>t);let n=[];return r!==_.CREATE&&r!==_.UPDATE||(n=h.nestedRelations(e)),[...new Set([...i,...n])]}).bind(t),t.migrationsFor=(e=>{if(!(e=e??se.current))throw new P("Could not get adapter for migrations");return t.innerGet(Symbol.for(Tt.MIGRATION),e.alias).map(t=>t.class)}).bind(t),t.migrations=(()=>{const e=t.innerGet(Symbol.for([Tt.MIGRATION,Tt.BY_KEY].join("-")));return Object.values(e).flat().map(t=>[t.class.name,t.class])}).bind(t),t.relations=((e,r)=>{const s=t.get(e,Tt.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new P("No relations metadata found for property "+r);return s[r]}}).bind(t),h.relations=(e,r)=>t.relations(e instanceof h?e.constructor:e,r)||[],h.nestedRelations=((e,r=[])=>{let s=[];const i=t.get(e,Tt.RELATIONS);if(!i||!Object.keys(i).length)return[...new Set([...r])];for(const t in i){const e=i[t];if(e?.class&&h.relations(e.class)){const i=h.relations(e.class).map(e=>`${t}.${e}`);r=[...r,...i],s=h.nestedRelations(e.class,r)}}return[...new Set([...r,...s])]}).bind(h),h.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!h.sequenceFor(r).generated}).bind(h),h.fromTable=(e=>{const r=t.innerGet(Symbol.for(Tt.TABLE));if(!r||!r[e]||!h.get(r[e].name))throw new P("No table metadata found for model. did you use @table()?");return h.get(r[e].name)}).bind(h),t.createdBy=(e=>{const r=t.get("function"!=typeof e?e.constructor:e,Tt.CREATED_BY);if(!r)throw new P("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(t),t.updatedBy=(e=>{const r=t.get("function"!=typeof e?e.constructor:e,Tt.UPDATED_BY);if(!r)throw new P("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(t),h.tableName=e=>{if(!(e instanceof h?h.get(e.constructor.name):e))throw new P("Unable to find model "+e);return t.get(e instanceof h?e.constructor:e,Tt.TABLE)||(e instanceof h?e.constructor.name:e.name)},h.columnName=(e,r)=>t.get(e instanceof h?e.constructor:e,t.key(Tt.COLUMN,r))||r,h.defaultQueryAttributes=(e,r=!1)=>{const s="function"==typeof e?e:e.constructor;return t.get(s,t.key(Tt.DEFAULT_QUERY_ATTR))||(r?[h.pk(e)]:[])},h.sequenceName=(t,...e)=>[h.tableName(t),...e].join("_"),h.versionOf=(e=>{const r=t.get(e.constructor),s=r?.[Tt.PERSISTENT_VERSION],i=s&&"object"==typeof s?Object.keys(s)[0]:void 0,n=r?.[$.VERSION],a=n&&"object"==typeof n?Object.keys(n)[0]:void 0,o=i??a;if(!o)throw new P("No version found for "+e.constructor.name);const c=e[o];if("number"!=typeof c||1>c)throw new P("Invalid version number: "+c);return c}).bind(h),h.sequenceFor=(e,r)=>{const s="function"!=typeof e?e.constructor:e;let i=Tt.SEQUENCE;const n=h.pk(s);r&&r+""!=n+""||(r=n,i=$.ID),i=t.key(i,r);const a=t.get(s,i);if(!a)throw new P(`No sequence options defined for property ${r+""}. did you use @sequence() or @pk()?`);return a},h.indexes=e=>{const r=t.get(e instanceof h?e.constructor:e,Tt.INDEX);return Object.keys(r||{}).reduce((t,e)=>{const s=r[e]||{};return t[e]=Object.keys(s).reduce((t,e)=>(t[e===kt?Tt.INDEX:`${Tt.INDEX}_${e}`]=s[e],t),{}),t},{})},vt.services=()=>t.innerGet(Symbol.for(Tt.SERVICE)),vt.repositories=()=>t.innerGet(Symbol.for($.REPOSITORY)),h.merge=((t,e,r)=>{const s=t=>Object.entries(t).reduce((t,[e,s])=>{let i=!1;try{"relation.one-to-one"===h.relations(r,e).key&&(i=!0)}catch(t){i=!1}return(void 0!==s||i)&&(t[e]=s),t},{});return new(r=r||t.constructor)(Object.assign({},s(t),s(e)))}).bind(h);class de extends P{constructor(t){super(t,de.name,500)}}class he extends P{constructor(t){super(t,he.name,500)}}class pe 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 pe.and(this,t)}or(t){return pe.or(this,t)}not(t){return new pe(this,Et.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof pe)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(Et).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===Et.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof pe){if(!(this.comparison instanceof pe)&&this.operator!==Et.NOT)return{comparison:{condition:t}};if(-1===Object.values(Ot).indexOf(this.operator)&&this.operator!==Et.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return pe.group(t,Ot.AND,e)}static or(t,e){return pe.group(t,Ot.OR,e)}static group(t,e,r){return new pe(t,e,r)}static attribute(t){return(new pe.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(Et.EQUAL,t)}dif(t){return this.setOp(Et.DIFFERENT,t)}gt(t){return this.setOp(Et.BIGGER,t)}lt(t){return this.setOp(Et.SMALLER,t)}gte(t){return this.setOp(Et.BIGGER_EQ,t)}lte(t){return this.setOp(Et.SMALLER_EQ,t)}in(t){return this.setOp(Et.IN,t)}regexp(t){return this.setOp(Et.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(Et.STARTS_WITH,t)}endsWith(t){return this.setOp(Et.ENDS_WITH,t)}between(t,e){return this.setOp(Et.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new pe(this.attr1,this.operator,this.comparison)}catch(t){throw new de(t)}}}}static builder(){return new pe.Builder}static from(t){return new pe(t)}}var ge,fe;ct([g(),lt("design:type",Object)],pe.prototype,"attr1",void 0),ct([g(),lt("design:type",String)],pe.prototype,"operator",void 0),ct([g(),lt("design:type",Object)],pe.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(ge||(ge={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(fe||(fe={}));const ye={update:fe.CASCADE,delete:fe.NONE},me={Equals:(t,e)=>pe.attribute(t).eq(e),Diff:(t,e)=>pe.attribute(t).dif(e),LessThan:(t,e)=>pe.attribute(t).lt(e),LessThanEqual:(t,e)=>pe.attribute(t).lte(e),GreaterThan:(t,e)=>pe.attribute(t).gt(e),GreaterThanEqual:(t,e)=>pe.attribute(t).gte(e),In:(t,e)=>pe.attribute(t).in(e),Matches:(t,e)=>pe.attribute(t).regexp(e)},we=t=>t.charAt(0).toLowerCase()+t.slice(1);class ve extends dt{static get log(){return this._logger||(this._logger=ut.for(ve.name)),this._logger}static{this.prefixMap={[xt.FIND_BY]:"find",[xt.PAGE_BY]:"page",[xt.COUNT_BY]:"count",[xt.SUM_BY]:"sum",[xt.AVG_BY]:"avg",[xt.MIN_BY]:"min",[xt.MAX_BY]:"max",[xt.DISTINCT_BY]:"distinct",[xt.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(t){for(const[e,r]of Object.entries(this.prefixMap))if(t.startsWith(e))return{action:r,prefix:e}}static build(t,...e){const r=this.getActionFromMethodName(t);if(!r)throw Error("Unsupported method "+t);const{action:s,prefix:i}=r;let n;["count","sum","avg","min","max","distinct","group"].includes(s)&&(n=this.extractAggregationSelector(t,i));const a=this.extractCore(t,i),o=this.extractSelect(t),c=this.extractGroupBy(t),l=this.buildWhere(a,e),{orderBy:u,limit:d,offset:h}=this.extractOrderLimitOffset(t,e,a);return{action:s,select:o,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?we(i):void 0}static extractCore(t,e=xt.FIND_BY){const r=t.substring(e.length);if(e!==xt.FIND_BY&&e!==xt.PAGE_BY){const t=r.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!t)return"";if("And"===t[0]||"Or"===t[0]){const e=r.substring(t.index+t[0].length),s=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return s?e.substring(0,s.index):e}return""}const s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?r.substring(0,s.index):r}static getFieldsFromMethodName(t){const e=this.getActionFromMethodName(t),r=e?.prefix||xt.FIND_BY,s=this.extractCore(t,r);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(t=>t.length>0).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")}):[]}static extractSelect(t){const e=t.indexOf(xt.SELECT);if(-1===e)return;const r=t.substring(e+xt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(xt.AND).map(we).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(xt.GROUP_BY);if(-1!==e)return t.substring(e+xt.GROUP_BY.length).split(xt.ORDER_BY)[0].split(xt.THEN_BY).map(we).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(xt.THEN_BY);if(-1===s)return;const i=e.substring(s+xt.THEN_BY.length).split(xt.THEN_BY),n=[];for(const t of i){const e=t.match(/(OrderBy|Limit|Offset|Select)/),r=e?t.substring(0,e.index):t;r&&n.push(we(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:a}=this.parseFieldAndOperator(t),o=a?me[a]:me.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+s);const l=o(s,c);n=0===r?l:i[r-1]===xt.AND?n.and(l):n.or(l)}),n}static parseFieldAndOperator(t){for(const e of Object.keys(me))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:we(r),operator:e}}return{field:we(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=ve.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new de("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(ge).includes(e))throw new de(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(ge).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 a,o,c;if(n.at(-1)instanceof B&&n.pop(),n.length>=1){const e=n[0],r=this.extractOrderByField(t);a=this.getProperlyOrderByOrThrow(r,e)}return 2>n.length||"number"!=typeof n[1]||(o=n[1]),3>n.length||"number"!=typeof n[2]||(c=n[2]),{orderBy:a,limit:o,offset:c}}}function be(){return(e,r)=>{const i=t.key(Tt.DEFAULT_QUERY_ATTR);let a=t.get(e.constructor,i)||[];return a=[...new Set([...a,r])],s(n(i,a))(e,r)}}function Ae(){return e.for(Tt.STATEMENT).define({decorator:()=>(e,r,n)=>s(i(t.key(Tt.STATEMENT,r),!0))(e,r,n),args:[]}).apply()}function Se(r={}){return e.for(Tt.QUERY).define({decorator:e=>function r(n,a,o){const c=ve.getFieldsFromMethodName(a);return s(i(t.key(Tt.QUERY,a),{...e,fields:c}),Ae(),(t=>(e,s,i)=>{i.value=new Proxy(i.value,{async apply(e,s,i){const{action:n,select:a,selector:o,where:c,groupBy:l,orderBy:u,limit:d,offset:h}=ve.build(e.name,...i);if(!(s instanceof F))throw Error("thisArg must be an instance of Repository");const p=s,{ctx:g}=(await p.logCtx(i,r.name,!0)).for(r);let f;switch(n){case"find":case"page":f=p.select(a);break;case"count":f=p.count(o);break;case"sum":f=p.sum(o);break;case"avg":f=p.avg(o);break;case"min":f=p.min(o);break;case"max":f=p.max(o);break;case"distinct":f=p.distinct(o);break;case"group":f=p.select(),o&&(f=f.groupBy(o));break;default:throw new de("Unsupported action: "+n)}if(c&&(f=f.where(c)),l&&l.length>0&&"group"!==n){f=f.groupBy(l[0]);for(let t=1;t<l.length;t++)f=f.thenBy(l[t])}else if(l&&l.length>0&&"group"===n)for(const t of l)f=f.thenBy(t);const{allowLimit:y,allowOffset:m,allowOrderBy:w,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},b=[{key:"orderBy",value:(u||[])[0],allowed:w},{key:"limit",value:d,allowed:y},{key:"offset",value:h,allowed:m}];for(const t of b)if(void 0!==t.value){if(!t.allowed&&v)throw new de(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(f=f[t.key](t.value))}if("page"===n){const t=i[i.length-1],e="number"==typeof t?t:t?.limit??10;return f.paginate(e,g)}return f.execute(g)}})})(e))(n,a,o)},args:[r]}).apply()}function xe(e,r,s){return(i,a)=>{const o=s?.name||((e,r,s)=>{const i=(t.get(e.constructor,r)||{})[s]||{};return Object.keys(i).length+1+""})(i,e,a),c=t.key(e,a,o),l={...s||{},kind:r,attribute:a};return n(c,l)(i,a)}}function Ee(t){return e.for(Et.VIEW).define({decorator:t=>xe(Et.VIEW,"view",t),args:[t]}).apply()}function Oe(t){return _e(t,[_.CREATE,I.CREATE_ALL])}function Ce(t){return _e(t,[_.UPDATE,I.UPDATE_ALL])}function ke(t){return _e(t,[_.DELETE,I.DELETE_ALL])}function Te(t){return _e(t,_t)}function Ne(t){return _e(t,Object.values(_))}function De(t){return _e(t,Object.values(I))}function _e(e,r){return(s,i,n,...a)=>{if("string"==typeof e)throw new P("clazz cannot be string. This should be impossible");const{log:o}=Ft.prototype.logCtx(a,_e);return o.silly(`filtering ${i} event for${s?" "+(h.tableName(s)||s):""} ${n}`),("string"==typeof s?s===h.tableName(e)||s===e.constructor.name:t.constr(e)===t.constr(s))&&r.includes(i)}}const Ie={onlyOnCreate:Oe,onlyOnUpdate:Ce,onlyOnDelete:ke,onlyOnTransactional:Te,onlyOnSingle:Ne,onlyOnBulk:De};function Be(t){const e=Object.assign({},Ie);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}var Pe,Re,$e,Fe,Le,Me,je;class Ue extends F{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 P("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 Be(this)}constructor(e,s,i=!1,...n){super(s),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),s&&(Ue.register(s,this,this.adapter.alias,i),e)&&t.get(s,a.FLAVOUR)===r&&o(e.flavour)(s);const c=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;L(c,c[e+"Prefix"],t,c[e+"Suffix"])}),M(c,c[this.updateAll.name+"Prefix"],this.updateAll,c[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 Mt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,_.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),t=new this.class(t),n||await j(this,r,t,_.CREATE,_.ON),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new R(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:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,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)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[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,I.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),!t.length)return[t,...s];const o=h.sequenceFor(t[0]);let c=[];if(h.generatedBySequence(this.class)?(o.name||(o.name=h.sequenceName(t[0],"pk")),c=await(await this.adapter.Sequence(o,this._overrides)).range(t.length,...s)):h.generated(this.class,this.pk)||(c=t.map((t,e)=>{if(void 0===t[this.pk])throw new P("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),o.type&&(t[this.pk]="String"!==o.type||o.generated?c[e]:""+t[this.pk]),n||await j(this,r,t,_.CREATE,_.ON),t))),!a){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=U(s);if(n)throw new R(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,_.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const a=new this.class;return a[this.pk]=t,n||await j(this,r,a,_.READ,_.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,I.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,j(this,r,e,_.READ,_.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:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${h.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,_.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${a}`);const o=t[this.pk];if(!o)throw new P("No value for the Id is defined under the property "+this.pk);let c;if(r.get("applyUpdateValidation")&&(c=await this.read(o,r),r.get("mergeForUpdate")&&(t=h.merge(c,t,this.class))),n||await j(this,r,t,_.UPDATE,_.ON,c),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(c,...e));if(s)throw new R(s.toString())}return[t,...s,c]}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,I.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${a}`);const o=t.map(t=>{const e=t[this.pk];if(!e)throw new P("missing id on update operation");return e});let c;if(r.get("applyUpdateValidation")&&(c=await this.readAll(o,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>h.merge(c[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>j(this,r,t,_.UPDATE,_.ON,c?c[e]:void 0))),!a){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(c[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=U(s);if(n)throw new R(n)}return[t,...s,c]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,_.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await j(this,r,e,_.DELETE,_.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,I.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=>j(this,r,t,_.DELETE,_.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=ge.ASC,s,i,...n){const{ctxArgs:a}=(await this.logCtx(n,Tt.QUERY,!0)).for(this.query),o=[e,r],c=this.select().where(t).orderBy(o);return s&&c.limit(s),i&&c.offset(i),c.execute(...a)}async listBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.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){r.offset=r.offset||1,r.limit=r.limit||10;const{offset:i,bookmark:n,limit:a}=r;if(!i&&!n)throw new de("PaginateBy needs a page or a bookmark");const{log:o,ctx:c,ctxArgs:l}=(await this.logCtx(s,Ct.PAGE_BY,!0)).for(this.paginateBy);let u;if(o.verbose(`paginating ${h.tableName(this.class)} with page size ${a}`),n&&c.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===ge.ASC?this.attr(h.pk(this.class)).gt(n):this.attr(h.pk(this.class)).lt(n))()).orderBy([t,e]).paginate(a,...l);else{if(!i)throw new de("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...l)}const d=await u.page(i,n&&!c.get("paginateByBookmark")?n:void 0,...l);return u.serialize(d)}async find(t,e=ge.ASC,...r){if("string"!=typeof t)throw new de("Find value must be a string");const s=this.getDefaultQueryAttributes(),{log:i,ctxArgs:n}=(await this.logCtx(r,Ct.FIND,!0)).for(this.find);i.verbose(`finding ${h.tableName(this.class)} by default attributes ${s.join(", ")}`);const a=this.buildDefaultStartsWithCondition(t,s);return this.select().where(a).orderBy([s[0],e]).execute(...n)}async page(t,e=ge.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new de("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new de("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:p}=(await this.logCtx(s,Ct.PAGE,!0)).for(this.page);u.verbose(`paging ${h.tableName(this.class)} by default attributes ${c.join(", ")}`);const g=o??10,f=c[0],y=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let m;if(a&&d.get("paginateByBookmark")){const t=h.pk(this.class),r=e===ge.ASC?this.attr(t).gt(a):this.attr(t).lt(a);m=await y.select().where(l.and(r)).orderBy([f,e]).paginate(g,...p)}else{if(!n)throw new de("PaginateBy needs a page or a bookmark");m=await y.select().where(l).orderBy([f,e]).paginate(g,...p)}const w=await m.page(i,a&&!d.get("paginateByBookmark")?a:void 0,...p);return m.serialize(w)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.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 G("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.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 findByPaginate(t,e,r={direction:ge.DSC,offset:1,limit:10},...s){r.direction=r.direction||ge.DSC,r.offset=r.offset||1,r.limit=r.limit||10;const{direction:i,offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new de("FindByPaginate needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);c.verbose(`finding and paginating ${h.tableName(this.class)} with ${t} ${e}`);const d=this.attr(t).eq(e);let p;if(a&&l.get("paginateByBookmark")){const e=h.pk(this.class),r=i===ge.ASC?this.attr(e).gt(a):this.attr(e).lt(a);p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(d.and(r)).orderBy([t,i]).paginate(o,...u)}else{if(!n)throw new de("FindByPaginate needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(d).orderBy([t,i]).paginate(o,...u)}const g=await p.page(n,a&&!l.get("paginateByBookmark")?a:void 0,...u);return p.serialize(g)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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(!Ue.statements(this,t))throw new de("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const t=h.defaultQueryAttributes(this.class);if(!t||!t.length)throw new de("No default query attributes defined for "+h.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new de("Default query value must be a string");let r;for(const s of e){const e=this.attr(s).startsWith(t);r=r?r.or(e):e}if(!r)throw new de("No default query attributes available for "+h.tableName(this.class));return r}attr(t){return pe.attr(t)}observe(e,r){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const s=this.log.for(this.observe),i=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,r,s,...n)=>"string"==typeof e?e===i:t.constr(e)===t.constr(this.class)),s.verbose(`now observing ${this.adapter} filtering on table === ${i}`),this.observerHandler.observe(e,r),s.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(t){if(!this.observerHandler)throw new P("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 P("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=>se._baseSequence.parseValue(h.sequenceFor(this.class).type,t)):se._baseSequence.parseValue(h.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(e,s,...i){let n;const a=t.registeredFlavour(e),o=a&&a!==r?a:void 0,c=s||o||t.flavourOf(e)||se.currentFlavour;try{n=this.get(e,c)}catch(t){n=void 0}const l="function"==typeof n?n:void 0,u=s||o||t.flavourOf(e)||l&&t.get(l,Tt.ADAPTER)||se.currentFlavour,d=u?se.get(u):void 0;if(!d)throw new P("No registered persistence adapter found flavour "+u);if(n instanceof Ue)return n;const p=[h.tableName(e),d.alias].join(Y),g=l||d.repository();return delete this._cache[p],new g(d,e,...i)}static get(t,e){const r=h.tableName(t);let s=r;if(e&&(s=[r,e].join(Y)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new P("Could not find repository registered under "+r)}static register(t,e,r,s=!1){let i=h.tableName(t);if(r&&(i=[i,r].join(Y)),i in this._cache&&this._cache[i]instanceof Ue&&!s)throw new P(i+" already has a registered instance");this._cache[i]=e}static statements(e,r){const s=e instanceof Ue?e.constructor:e,i=t.get(s,r?t.key(Tt.STATEMENT,r):Tt.STATEMENT);return(r?i:Object.keys(i))||!1}static queries(e,r){const s=e instanceof Ue?e.constructor:e;return t.get(s,r?t.key(Tt.QUERY,r):Tt.QUERY)}}function Ge(t,s){if(!(s||(s=e.flavourResolver(t instanceof h?t.constructor:t))&&s!==r))throw new P("Could not retrieve flavour from model "+(t instanceof h?t.constructor.name:t.name));return f(Tt.INJECTABLE,s,h.tableName(t))}ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,String,void 0]),lt("design:returntype",Promise)],Ue.prototype,"listBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,String,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"paginateBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[String,String,void 0]),lt("design:returntype",Promise)],Ue.prototype,"find",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[String,String,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"page",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findOneBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findByPaginate",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"countOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Pe="undefined"!=typeof K&&K)?Pe:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"maxOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Re="undefined"!=typeof K&&K)?Re:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"minOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof($e="undefined"!=typeof K&&K)?$e:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"avgOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Fe="undefined"!=typeof K&&K)?Fe:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"sumOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Le="undefined"!=typeof K&&K)?Le:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"distinctOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Me="undefined"!=typeof K&&K)?Me:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"groupOf",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],Ue.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],Ue.prototype,"unObserve",null),se&&(se._baseRepository=Ue);class Ye extends bt{get log(){return this.logger||(this.logger=ut.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=h.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=h.get(e.toString())),!n)return;const a=Tt.ADAPTER,o=r||t.get(n,a)||t.flavourOf(n);try{let e=o;try{o&&se.get(o)}catch{const t=se.current;t&&t.flavour===o&&(e=t.alias)}if(i=Ue.forModel(n,e),i instanceof Ue)return i;const r=o||t.get(i.constructor,a)||t.get(n,a);vt.register(i,Ge(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=Ue.get(n,o);if("function"==typeof e){const t=o?se.get(o):se.current;if(!t)return;return new e(t,n)}}}return i}}function ze(e,r){return(s,i)=>i?At(t.constr(e))(s,i):(t.set($.REPOSITORY,t.key(r||se.currentFlavour,h.tableName(e)),s),c($.REPOSITORY,s.name)(e),r=r||t.get(s.constructor,Tt.ADAPTER),Ue.register(e,s),St(t.constr(e),{callback:t=>(Object.defineProperty(t,$.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(s))}class He extends P{constructor(t){super(t,He.name,500)}}function qe(t,e,r,s,i){i.value=new Proxy(i.value,{async apply(i,n,a){((t,e,r)=>{if("function"!=typeof t?.logCtx)throw new jt(`${e} on ${t?.constructor?.name??"UnknownClass"}.${r} requires a logCtx() method`)})(n,t,s+"");const{ctx:o,ctxArgs:c}=await n.logCtx(a,i.name,!0);let l;try{l=e(...a,...r,o)}catch(t){throw new P("Failed to execute auth validation handler: "+t)}if(l)throw l;return i.call(n,...c)}})}function Ve(t,...e){return(r,s,i)=>{qe("allowIf",t,e,s,i)}}function We(t,...e){return(r,s,i)=>{qe("blockIf",t,e,s,i)}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(je||(je={}));const Qe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Je=Qe,Xe={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Ke=Object.assign({},Xe,{type:"BigInt"});function Ze(r,s,i){return e.for(Tt.INDEX).define({decorator:(e,r,s)=>(i,a)=>{"string"==typeof e&&(s=e,e=void 0,r=void 0),"string"==typeof r&&(s=r,r=void 0),!r&&e&&e.find(t=>![ge.ASC,ge.DSC].includes(t))&&(r=e,e=void 0);const o=r&&r.length?r.join("_"):kt;return n(t.key(Tt.INDEX,a,o),{directions:e,compositions:r,name:s})(i,a)},args:[r,s,i]}).apply()}function tr(t){return"function"==typeof t}function er(e,r,s){if(!s.type){const i=t.type(e.constructor,r);if(![Number.name,String.name,BigInt.name].includes(i?.name||i))throw Error("Incorrrect option type");s.type=i}switch(s.type){case String.name||String.name.toLowerCase():case String:s.generated=void 0!==s.generated&&s.generated,s.type=String;break;case Number.name||String.name.toLowerCase():case Number:s.generated=void 0===s.generated||s.generated,s.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:s.type=BigInt,s.generated=void 0===s.generated||s.generated;break;case"uuid":case"serial":s.generated=!0;break;default:throw Error("Unsupported type")}void 0===s.generated&&(s.generated=!0)}async function rr(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 P(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,o;n=s,a=r,o=await i.next(t),Reflect.set(n,a,o)}async function sr(t,e,r,s,i){if(!e.type||!e.generated)return;if(!e.name){const t=h.pk(s,!0);if(null==t)throw new P("Cannot generate sequence without an id for "+s.constructor.name);e.name=h.sequenceName(s,t+"",r+"")}let n;try{n=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new P(`Failed to instantiate Sequence ${e.name}: ${t}`)}const a=null!=i,o=void 0!==s[r]&&null!==s[r],c=!!t.get("allowGenerationOverride")&&o;if(o&&await n.ensureAtLeast(s[r],t),a&&!e.update)return;if(c)return;const l=await n.next(t);Reflect.set(s,r,l)}function ir(e,r){return(i,a)=>{l()(i,a),er(i,a,e),e.name||(e.name=((t,e)=>tr(h.sequenceName)?h.sequenceName(t,e):[tr(h.tableName)?h.tableName(t):t?.name??"",e].filter(Boolean).join("_"))(i.constructor,"pk"));const o=[n(t.key($.ID,a),e),n(t.key(Tt.SEQUENCE,a),e),Ze([ge.ASC,ge.DSC]),g(),z(),H(rr,e,r)];return e.generated&&o.push(q()),s(...o)(i,a)}}function nr(e,r={},i){return(a,o)=>{l()(a,o),er(a,o,e);const c=[g(),n(t.key(Tt.SEQUENCE,o),e),H(sr,{...e,...r},i)];return r.update&&c.push(V(sr,{...e,...r},i)),e.generated&&c.push(q()),s(...c)(a,o)}}function ar(t){const r=Object.assign({},Je);return delete r.generated,t=Object.assign({},r,t),e.for($.ID).define({decorator:ir,args:[t,{priority:60}]}).apply()}function or(t,r){const s=Object.assign({},Je);delete s.generated,t=Object.assign({},s,t);const i="boolean"==typeof r?{update:r}:r||{};return e.for(Tt.SEQUENCE).define({decorator:nr,args:[t,i,{priority:70}]}).apply()}async function cr(t,e,r,s,i){const n=e.logger.for(cr);if(!s){const e=h.get(t.constructor.name);if(!e)throw new P("Could not find model "+t.constructor.name);s=Ue.forModel(e,r),n.info("Retrieved "+s.toString())}let a;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`),a=await s.create(t,e);else{n.info(`pk found in ${h.tableName(s.class)} - attempting update`);try{a=await s.update(t,e),n.info("Updated "+h.tableName(s.class))}catch(r){if(!(r instanceof G))throw r;n.info("update Failed - creating new "+h.tableName(s.class)),a=await s.create(t,e)}n.info("After create update: "+a)}return a}async function lr(t,e,r,s){const i=s[r];if(!i)return;if(yr(s,e),"object"!=typeof i){const e=Dr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Cr(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 P("Could not find model "+e.class);const a=Ue.forModel(n,this.adapter.alias),o=await a.override(this._overrides).create(i,t),c=h.pk(o);await Cr(t,s,r,o[c],o),s[r]=o[c]}async function ur(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==fe.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 Cr(t,s,r,i,n),void(s[r]=i)}const n=await cr(s[r],t,this.adapter.alias,void 0,this._overrides),a=h.pk(n);await Cr(t,s,r,n[a],n),s[r]=n[a]}async function dr(t,e,r,s){const i=s[r];if(null==i)return;if(e.cascade.delete!==fe.CASCADE)return;const n=Dr(s,r,this.adapter.alias);let a;a=i instanceof h?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Cr(t,s,r,a[n.pk],a)}async function hr(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;yr(s,e);const a=t.logger.for(hr),o=Dr(s,r,this.adapter.alias),c=h.pk("function"!=typeof e.class||e.class.name?e.class:e.class()),l=new Set;for(const e of n){let i;"object"!=typeof e?(i=await o.override(this._overrides).read(e,t),a.debug("read: "+i[c])):(a.verbose("Creating or updating one-to-many model: "+e[c]),i=await cr(e,t,this.adapter.alias,void 0,this._overrides)),a.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await Cr(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function pr(t,e,r,s,i){const{cascade:n}=e;if(n.update===fe.CASCADE)return hr.call(this,t,e,r,s,i)}async function gr(t,e,r,s){if(e.cascade.delete!==fe.CASCADE)return;const i=s[r];if(!i)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new P(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?Ue.forModel(a,this.adapter.alias):Dr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let u,d;try{u=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){d=u[e];try{await Cr(t,s,r,l[e],d)}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 fr(t,e,r,s){const i=s[r];if(!i)return;yr(s,e);const n=t.logger.for(fr);if("object"!=typeof i){const e=Dr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Cr(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof h?e.class.constructor:e.class))throw new P("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const a=await cr(i,t,this.adapter.alias,void 0,this._overrides),o=h.pk(a);n.info(`caching: ${JSON.stringify(a)} under ${a[o]}`),await Cr(t,s,r,a[o],a),s[r]=a[o]}function yr(e,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=t.get(i,Tt.RELATIONS);if(n&&(s=Object.values(n)?.find(t=>{const r="function"==typeof t.class&&t.class.name?t.class:t.class();return e instanceof r})),!0===s?.populate&&!0===r?.populate)throw new P("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function mr(t,e,r,s){const{cascade:i}=e;if(i.update===fe.CASCADE)return fr.call(this,t,e,r,s)}async function wr(t,e,r,s){if(e.cascade.delete!==fe.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,a=n?Ue.forModel(i,this.adapter.alias):Dr(s,r,this.adapter.alias),o=n?i[a.pk]:i,c=await a.override(this._overrides).delete(o);await Cr(t,s,r,o,c),s[r]=o}async function vr(t,e,r,s){const i=s[r];if(!i||!i.length)return;yr(s,e);const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new P(`Invalid operation. All elements of property ${r} must match the same type.`);const a=t.logger.for(vr),o=new Set([...i]);if("object"!==n){const n=Dr(s,r,this.adapter.alias),c=await n.override(this._overrides).readAll([...o.values()],t);for(let e=0;e<c.length;e++){const s=c[e];a.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(s)),await Cr(t,s,r,[...o.values()][e],c)}return await br.call(this,s,[...i],a,t,e),s[r]=[...o],void a.info("SET MANY TO MANY IDS: "+s[r])}const c=h.pk(i[0].constructor),l=new Set;for(const e of i){a.info("Creating or updating many-to-many model: "+JSON.stringify(e));const i=await cr(e,t,this.adapter.alias,void 0,this._overrides);a.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Cr(t,s,r,i[c],i),a.info("Creating or updating many-to-many model: "+JSON.stringify(e)),e.id=i.id,l.add(i[c])}const u=h.pk(s.constructor);if(void 0===s[u]){const e=await(async(t,e,r)=>{const s=e[h.pk(e.constructor)];if(void 0!==s)return s;const i=h.sequenceFor(e.constructor);let n;i?.name||(i.name=h.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i,t._overrides),await n.next(r)}catch(t){throw new P(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[u]=e}const d=await br.call(this,s,i,a,t,e);a.info("Junction model created: "+d.name),s[r]=[...l]}async function br(t,e,r,s,i){const{JunctionModel:n,fkA:a,fkB:o}=Ar(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={[a]:t instanceof h?t[h.pk(t.constructor)]:t,[o]:i instanceof h?i[h.pk(i.constructor)]:i},l=await cr(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Ue.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function Ar(e,r,s){const i=h.tableName(e);let n;if(r instanceof h)n=h.tableName(r);else if(h.isModel(r)&&"function"==typeof r)n=r.name?r.name:r()?.name;else if(s?.class){const t="function"!=typeof s.class||s.class.name?s.class:s.class();n=h.tableName(t)}if(!i||!n)throw new P("Missing tablenames to create junction table");const a=s?.joinTable?.name?s?.joinTable?.name:`${i}_${n}`,o=i?.toLowerCase()+"_fk",c=n?.toLowerCase()+"_fk",l=class extends h{constructor(t){super(t)}};Object.defineProperty(l,"name",{value:a,writable:!1}),ar({type:Number})(l.prototype,"id"),g()(l.prototype,o),g()(l.prototype,c);const u=m()(l);return t.set(l,Tt.TABLE,a),{fkA:o,fkB:c,JunctionModel:u}}async function Sr(t,e,r,s){const{cascade:i}=e;if(i.update===fe.CASCADE)return vr.call(this,t,e,r,s)}async function xr(t,e,r,s){if(e.cascade.delete!==fe.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 P(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?Ue.forModel(a,this.adapter.alias):Dr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let u,d;try{u=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){d=u[e];try{await Cr(t,s,r,l[e],d)}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 Er(t,e,r){return e?[Tt.POPULATE,t,e,r].join("."):[Tt.POPULATE,t,r].join(".")}function Or(t,e,r){return[Tt.TAG_FOR_DELETION,t,r].join(".")}async function Cr(t,e,r,s,i){const n=Er(e.constructor.name,r,s),a=t.logger.for(Cr),o=t.get("cacheForPopulate")||{};let c=o[n],l=t.getOrUndefined("preferFromCache");if(!l)try{a.silly("retrieving from children"),l=t.getFromChildren("preferFromCache")||!1,l&&(c=(t.getFromChildren("cacheForPopulate")||{})[n])}catch(t){l=!1}return l&&a.debug("preferring previous cache: "+!!o[n]),o[n]=l&&c?c:i,t.accumulate({cacheForPopulate:o})}async function kr(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 a=this,o=await(async(e,r,s,i)=>{let n,o;const c=[];let l;try{l=e.get("operation")}catch(t){l=void 0}const u=l===_.READ||l===I.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=Er(r.constructor.name,s,e);try{if(o=u[n],!o)throw Error("Not found in cache")}catch(i){const n=Dr(r,s,a.adapter.alias);if(!n)throw new P("Could not find repo");o=await n.override(a._overrides).read(e,t)}c.push(o)}return c})(t,s,r,n?i:[i]);s[r]=n?o:o[0]}async function Tr(t,e,r,s,i){if(e.cascade.update!==fe.CASCADE)return;if(!i)throw new P("No way to compare old model. do you have updateValidation and mergeModels enabled?");function n(t){return Array.isArray(t)?t.map(n):"object"!=typeof t?t:t[h.pk(t)]}const a=n(s[r]),o=n(i[r]);if(void 0===o||y(a,o))return;if(Array.isArray(a)!==Array.isArray(o))throw new P("Cannot cascade update for different array types");const c=(Array.isArray(a)?a:[a]).filter(Boolean),l=(Array.isArray(o)?o:[o]).filter(Boolean).filter(t=>!c.includes(t)),u=Dr(s,r,this.adapter.alias);if(!u)throw new P("Could not find repo");try{const e=await u.override(this._overrides).deleteAll(l,t);t.logger.debug(`Deleted ${e.length} entries from table ${h.tableName(u.class)} due to cascade rules with `)}catch(t){throw new P("Error deleting cascade entries: "+t)}}const Nr=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Dr(e,r,s){if(!e)throw Error("No model was provided to get repository");let i,n=e instanceof h?e.constructor:e;if(Array.isArray(e[r])||e[r]instanceof Set){const e=t.get(n,t.key(w.REFLECT,r,w.LIST))?.clazz;if(!e)throw new P("Failed to find types decorators for property "+r);i=(Array.isArray(e)?[...e]:[e]).map(t=>"function"!=typeof t||t.name?t:t())}else i=h.relations(n).includes(r)?t.allowedTypes(n,r):t.getPropDesignTypes(e instanceof h?e.constructor:e,r)?.designTypes;n=i?.find(t=>!Nr.includes((""+t.name).toLowerCase()));const a=Ue.forModel(n,s);if(n!==a.class)throw new P("Invalid repository class for "+r);return a}class _r extends W{constructor(t,e=_r.name,r=401){super(t,e,r)}}class Ir extends _r{constructor(t,e=Ir.name){super(t,e,403)}}class Br extends P{constructor(t){super(t,Br.name,503)}}function Pr(r){return e.for(Tt.TABLE).define({decorator:e=>r=>(t.set(Tt.TABLE,e||r.name.toLowerCase(),r),c(Tt.TABLE,e||r.name.toLowerCase())(r)),args:[r]}).apply()}function Rr(r){return e.for(Tt.COLUMN).define({decorator:e=>(r,s)=>n(t.key(Tt.COLUMN,s),e||s)(r,s),args:[r]}).apply()}async function $r(t,e,r,s){if(!s[r])return;const i=await this.select().where(pe.attribute(r).eq(s[r])).execute(),n=h.pk(s),a=s[n];if(i.filter(t=>t[n]!==a).length)throw new X(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Fr(){const t=Tt.UNIQUE;return e.for(t).define(b(),J($r),n(t,{})).apply()}async function Lr(t,e,r,s){throw new _r("This adapter does not support user identification")}function Mr(){return e.for(Tt.CREATED_BY).define({decorator:()=>(t,e)=>s(H(Lr),n(Tt.CREATED_BY,e),q(Tt.CREATED_BY))(t,e),args:[]}).apply()}function jr(){return e.for(Tt.UPDATED_BY).define({decorator:()=>(t,e)=>s(V(Lr),n(Tt.UPDATED_BY,e),q(Tt.UPDATED_BY))(t,e),args:[]}).apply()}function Ur(){return Q([_.CREATE])}function Gr(){return Q()}async function Yr(t,e,r,s){if("??sequence"===h.tableName(s))return;const i=h.pk(s,!0);if(null==i)throw new P("Cannot generate persistent version without an id for "+s.constructor.name);const n={name:h.sequenceName(s,i+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},a=await this.adapter.Sequence(n,this._overrides),o=void 0!==s[r]&&null!==s[r],c=!!t.get("allowGenerationOverride")&&o;if(o&&(await a.ensureAtLeast(s[r],t),c))return;const l=await a.next(t);s[r]=l}async function zr(t,e,r,s,i){if("??sequence"===h.tableName(s))return;if(t.get("applyUpdateValidation")&&i&&s[r]!==i[r])throw new R(`Version mismatch: ${s[r]} !== ${i[r]}`);const n=h.pk(s,!0);if(null==n)throw new P("Cannot generate persistent version without an id for "+s.constructor.name);const a={name:h.sequenceName(s,n+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},o=await this.adapter.Sequence(a,this._overrides),c=void 0!==s[r]&&null!==s[r],l=!!t.get("allowGenerationOverride")&&c;if(c&&(await o.ensureAtLeast(s[r],t),l))return;const u=await o.next(t);s[r]=u}function Hr(){const r=Tt.PERSISTENT_VERSION;return(s,i)=>e.for(r).define(l(),n(t.key(r,i),!0),q(r),v(Number),H(Yr,{},{priority:70}),V(zr,{},{priority:70})).apply()(s,i)}function qr(t=!1){return t?Hr():Z()}function Vr(e){return[()=>{const r="function"==typeof e&&e.name?e:e(),s=h.pk(r);return(t.allowedTypes(r,s)||[])[0]}]}function Wr(t,r=ye,i=!0,n,a){const o=Tt.ONE_TO_ONE;return e.for(o).define({decorator:(t,e,r,i,n)=>{const a={class:t,cascade:e,populate:r};i&&(a.joinTable=i),n&&(a.name=n);const c=Vr(t),u=[l(),rs(o,a),v([t,...c]),H(lr,a,{priority:70}),V(ur,a,{priority:70}),et(dr,a,{priority:70}),V(Tr,a,{priority:80}),tt(kr,a,{priority:70})];return s(...u)},args:[t,r,i,n,a]}).apply()}function Qr(t,r=ye,i=!0,n,a){const o=Tt.ONE_TO_MANY;return e.for(o).define({decorator:(t,e,r,i,n)=>{const a={class:t,cascade:e,populate:r};i&&(a.joinTable=i),n&&(a.name=n);const c=Vr(t),u=[l(),rs(o,a),A([t,...c]),H(hr,a,{priority:70}),V(pr,a,{priority:70}),et(gr,a,{priority:70}),V(Tr,a,{priority:80}),tt(kr,a,{priority:70})];return s(...u)},args:[t,r,i,n,a]}).apply()}function Jr(t,r=ye,i=!0,n,a){const o=Tt.MANY_TO_ONE;return e.for(o).define({decorator:(t,e,r,i,n)=>{const a={class:t,cascade:e,populate:r};i&&(a.joinTable=i),n&&(a.name=n);const c=Vr(t),u=[l(),rs(o,a),v([t,...c]),H(fr,a),V(mr,a),et(wr,a),tt(kr,a)];return s(...u)},args:[t,r,i,n,a]}).apply()}function Xr(t,r=ye,i=!0,n,a){const o=Tt.MANY_TO_MANY;return e.for(o).define({decorator:(t,e,r,i,n)=>{const a={class:t,cascade:e,populate:r};i&&(a.joinTable=i),n&&(a.name=n);const c=Vr(t),u=[l(),rs(o,a),A([t,...c]),H(vr,a),V(pr,a),tt(kr,a)];return s(...u)},args:[t,r,i,n,a]}).apply()}function Kr(...e){return(r,i)=>{const n=t.get(r,t.key(Tt.NO_VALIDATE,i))||[],a=[...new Set([...n,...e])];return s(c(t.key(Tt.NO_VALIDATE,i),a))(r,i)}}function Zr(){return Kr(_.CREATE)}function ts(){return Kr(_.UPDATE)}function es(){return Kr(_.UPDATE,_.CREATE)}function rs(r,s){return e.for(Tt.RELATIONS).define({decorator:(e,r)=>(s,i)=>(n(e,r)(s,i),n(t.key(Tt.RELATIONS,i),Object.assign({},r,{key:e}))(s,i)),args:[r,s]}).apply()}class ss extends h{constructor(t){super(t)}}ct([Ur(),lt("design:type",Date)],ss.prototype,"createdAt",void 0),ct([Gr(),lt("design:type",Date)],ss.prototype,"updatedAt",void 0);let is=class extends ss{constructor(t){super(t)}};ct([ar({type:String,generated:!1}),lt("design:type",String)],is.prototype,"id",void 0),ct([g(),Ze(),lt("design:type",Object)],is.prototype,"current",void 0),is=ct([Pr("??sequence"),m(),lt("design:paramtypes",[Object])],is);class ns extends dt{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,Qt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Ct.FIND_BY}|${Ct.FIND_BY_PAGINATE}|${Ct.LIST_BY}|${Ct.PAGE_BY}|${Ct.FIND}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Ct.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 $t?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof $t||(this._bookmark=e);const n=Ue.forModel(this.clazz,this.adapter.alias),a=this.query,{method:o,args:c,params:l}=a;if(o===Ct.FIND){const e=[Ct.PAGE,...c],r={limit:this.size,offset:t,bookmark:this._bookmark};e.push(r);const s=await n.statement(...e,...i);return this.apply(s)}let u;if(o===Ct.FIND_BY?u=Ct.FIND_BY_PAGINATE:o.startsWith(Ct.FIND_BY)?u=o.replace(Ct.FIND_BY,Ct.PAGE_BY):o===Ct.LIST_BY?u=Ct.PAGE_BY:o!==Ct.PAGE_BY&&o!==Ct.FIND_BY_PAGINATE||(u=o),!u)throw new jt(`Method ${o} is not supported for pagination`);const d=[u,...c];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==Ct.PAGE_BY||d.length>2?h={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:d.push(l.direction),d.push(h);const p=await n.statement(...d,...i);return this.apply(p)}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 he("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new he(`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 jt("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 rt(t)}}apply(t){const e="string"==typeof t?ns.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total||this._totalPages,this._recordCount=e.count||this._recordCount,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new rt(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 as,os,cs,ls,us,ds,hs;class ps extends Ft{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach(t=>{st(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?Ct.PAGE_BY:Tt.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),a=r.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${a}`);const o=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||o)||a)&&(i.silly(`squashing ${a?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${a?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(ps)}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 de("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 de("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 de("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new de("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 de("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===ge.ASC)return ge.ASC;if(e===ge.DSC)return ge.DSC;throw new de(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ge).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new de("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=t=>this.processRecord(t,r);if(this.groupBySelectors?.length){const e=this.revertGroupedResults(n,t);return await this.applyAfterHandlersToResult(e,r)}if(Array.isArray(n)){const e=n.map(t);return await this.applyAfterHandlersToResult(e,r)}const e=t(n);return await this.applyAfterHandlersToResult(e,r)}return n}catch(t){throw new de(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=Ue.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 jt("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=t=>this.processRecord(t,r);if(Array.isArray(i)){const t=i.map(n);return await this.applyAfterHandlersToResult(t,r)}const a=n(i);return await this.applyAfterHandlersToResult(a,r)}processRecord(t,e){const r=t[h.pk(this.fromSelector)];return this.adapter.revert(t,this.fromSelector,r,void 0,e)}async applyAfterHandlersToResult(t,e){return e.getOrUndefined("afterQueryHandlers")?t instanceof h?(await j(this.getRepository(),e,t,_.READ,_.AFTER),t):Array.isArray(t)?(await Promise.all(t.map(t=>this.applyAfterHandlersToResult(t,e))),t):t&&"object"==typeof t?(await Promise.all(Object.entries(t).map(([r,s])=>this.applyAfterHandlersToResult(s,e).then(e=>{t[r]=e}))),t):t:t}getRepository(){return Ue.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case Ot.AND:case Ot.OR:{let t=r,a=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof pe){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case Et.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case Et.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case Et.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case Et.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case Et.BIGGER_EQ:n.method=r+" bigger than equal";break;case Et.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case Et.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case Et.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new de("Unsupported operator "+s)}return n}squash(t){const e=this.matchDefaultQueryCondition();if(e){const t=this.getOrderDirection();return{class:this.fromSelector,method:Ct.FIND,args:[e.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof pe)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Ct.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Ct.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Ct.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Ct.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Ct.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Ct.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Ct.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let r;this.whereCondition&&(r=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,ge.DSC]:[h.pk(this.fromSelector),ge.DSC],[i,n]=s,a={direction:n};this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.offset=this.offsetSelector);const o={class:this.fromSelector,method:Ct.LIST_BY,args:[i],params:a};return r&&(o.method=Ct.FIND_BY,o.args=[r,this.whereCondition.comparison],o.params=a),o}matchDefaultQueryCondition(){if(!this.whereCondition)return;const t=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!t)return;const e=h.defaultQueryAttributes(this.fromSelector);if(!e||!e.length)return;const r=Array.from(new Set(e.map(String))),s=Array.from(new Set(t.attributes.map(String)));return r.length===s.length&&r.every(t=>s.includes(t))?{value:t.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(t){const e=this.collectStartsWithAttributes(t);if(e)return{attributes:Array.from(new Set(e.attributes)),value:e.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:e,operator:r,comparison:s}=t;if(r===Et.STARTS_WITH){if("string"!=typeof e||"string"!=typeof s)return;return{attributes:[e],value:s}}if(r===Ot.OR){const t=e instanceof pe?this.collectStartsWithAttributes(e):void 0,r=s instanceof pe?this.collectStartsWithAttributes(s):void 0;return t&&r&&t.value===r.value?{attributes:[...t.attributes,...r.attributes],value:t.value}:void 0}return r===Ot.AND?(e instanceof pe?this.collectStartsWithAttributes(e):void 0)||(s instanceof pe?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??ge.ASC}async prepare(t){if(t=t||await this.adapter.context(Tt.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r};let i,n=xt.FIND_BY;void 0!==this.countSelector?(n=xt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=xt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=xt.AVG_BY,i=this.avgSelector):this.minSelector?(n=xt.MIN_BY,i=this.minSelector):this.maxSelector?(n=xt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=xt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=xt.GROUP_BY_PREFIX,i=this.groupBySelectors[0]);const a=[n];if(i&&a.push(i),this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);a.push(r.method),r.args&&r.args.length&&e.push(...r.args)}if(this.selectSelector&&a.push(xt.SELECT,this.selectSelector.join(` ${xt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;a.push(xt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map(([t,e])=>[t,e]),e.forEach(([t])=>{a.push(xt.THEN_BY,t)}))}if(this.groupBySelectors?.length&&n!==xt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;a.push(xt.GROUP_BY,t),e.forEach(t=>a.push(xt.THEN_BY,t))}else this.groupBySelectors?.length&&n===xt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>a.push(xt.THEN_BY,t));return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=pt(a.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 de(t)}}toString(){return this.adapter.flavour+" statement"}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Array]),lt("design:returntype",Object)],ps.prototype,"select",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(as="undefined"!=typeof S&&S)?as:Object]),lt("design:returntype",Object)],ps.prototype,"distinct",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(os="undefined"!=typeof S&&S)?os:Object]),lt("design:returntype",Object)],ps.prototype,"max",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(cs="undefined"!=typeof S&&S)?cs:Object]),lt("design:returntype",Object)],ps.prototype,"min",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(ls="undefined"!=typeof S&&S)?ls:Object]),lt("design:returntype",Object)],ps.prototype,"sum",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(us="undefined"!=typeof S&&S)?us:Object]),lt("design:returntype",Object)],ps.prototype,"avg",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(ds="undefined"!=typeof S&&S)?ds:Object]),lt("design:returntype",Object)],ps.prototype,"count",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",Object)],ps.prototype,"from",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[pe]),lt("design:returntype",Object)],ps.prototype,"where",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,String]),lt("design:returntype",Object)],ps.prototype,"orderBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,String]),lt("design:returntype",Object)],ps.prototype,"thenBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(hs="undefined"!=typeof Key&&Key)?hs:Object]),lt("design:returntype",Object)],ps.prototype,"groupBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Number]),lt("design:returntype",Object)],ps.prototype,"limit",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Number]),lt("design:returntype",Object)],ps.prototype,"offset",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[void 0]),lt("design:returntype",Promise)],ps.prototype,"execute",null);class gs extends Ft{constructor(){super(),this.observers=[],this.Context=$t}for(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof gs?n.for(t,...e):n instanceof Ue?n.override(t):n}})}override(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof gs?n.override(t,...e):n instanceof Ue?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Mt,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 P("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 P("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}-${Jt.instance.generate()}`;const s=e.logger||ut.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Nt,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 $t||(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 Ft.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new P("No name provided");const e=Yt(t),r=vt.get(e);if(r)return r;throw new P("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let e=t.pop();void 0===e||e instanceof $t||(t.push(e),e=void 0);const r=await gs.prototype.flags(Tt.INITIALIZATION,{},...t);e=e?new $t(e).accumulate({...r,parentContext:e}):(new $t).accumulate(r),t=[...t,e];const{log:s,ctxArgs:i}=gs.prototype.logCtx(t,this.boot),n=vt.services();if(!n||!Object.keys(n).length)throw new P("No services registered for shutdown");for(const[t,e]of Object.entries(n))try{s.verbose(`Booting ${e.name} service...`);const r=vt.get(e);if(!r)throw new P("Failed to resolve injectable for "+t);r instanceof fs&&(s.verbose(`Initializing ${e.name} service...`),await r.boot(...i))}catch(t){throw new P(`Failed to boot ${e.name} service:${t}`)}}static async shutdown(...t){let e=t.pop();void 0===e||e instanceof $t||(t.push(e),e=void 0);const r=await gs.prototype.flags(Tt.SHUTDOWN,{},...t);e=e?new $t(e).accumulate({...r,parentContext:e}):(new $t).accumulate(r),t=[...t,e];const{log:s,ctxArgs:i}=gs.prototype.logCtx(t,this.shutdown),n=vt.services();if(!n||!Object.keys(n).length)throw new P("No services registered for shutdown");for(const[t,e]of Object.entries(n).reverse())try{s.verbose(`Shutting down ${e.name} service...`);const r=vt.get(e);if(!r)throw new P("Failed to resolve injectable for "+t);if(r instanceof fs){s.verbose(`Gracefully shutting down ${e.name} service...`);try{await r.shutdown(...i)}catch(t){s.error(`Failed to gracefully shutdown ${e.name} service`,t)}}}catch(e){throw new P(`Failed to Shutdown services ${t}: ${e}`)}}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],gs.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],gs.prototype,"unObserve",null);class fs extends gs{constructor(){super()}async boot(...t){const{config:e,client:r}=await this.initialize(...t);this._config=e,this._client=r;const{log:s}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new P("Config not initialized");return this._config}get client(){if(!this._client)throw new P("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function ys(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Vt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",Promise)],fs.prototype,"boot",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],fs.prototype,"config",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],fs.prototype,"client",null);const ms=()=>ys(_.CREATE),ws=()=>ys(_.READ),vs=()=>ys(_.UPDATE),bs=()=>ys(_.DELETE);function As(e){return(r,i,n)=>{n||i?(l()(r,i),e=e||t.type(r.constructor,i)):e=e||r,e=Yt(e);const a=[];if(n&&"number"==typeof n.value)a.push(At(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(At(e))}else t.set(Tt.SERVICE,e,r),a.push(St(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return s(...a)(r,i,n)}}function Ss(t){const r=Tt.AUTH;return e.for(r).define({decorator:t=>c(r,t),args:[t]}).apply()}const xs=t=>c(Tt.AUTH_ROLE,t);function Es(r,n){const a=Tt.DECAF_ROUTE;return e.for(a).define({decorator:()=>(e,o,c)=>{const l={path:n,httpMethod:r,handler:c};return s(i(t.key(a,o),l))(e,o,c)},args:[]}).apply()}const Os=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Cs extends gs{get class(){if(!this.clazz)throw new P("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ue.forModel(this.clazz)),this._repository}constructor(t){super(),this.clazz=t}static getService(t){if(!t)throw new P("No name provided");const e=Os(t);try{const t=gs.get(e);if(t)return t}catch(t){}throw new P("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new P(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}select(t){return this.repo.select(t)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.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,Ct.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,Ct.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,Ct.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async findByPaginate(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,e,r,...i)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=Os(e||t);try{r=Cs.get(e)}catch(t){r=void 0}if(r instanceof Cs)return r;const s=this;let i=class extends s{constructor(){super(t)}};return i=ct([As(e),lt("design:paramtypes",[])],i),new i}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)}}ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"create",null),ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"createAll",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"delete",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"deleteAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"read",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"readAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[String,Object]),lt("design:returntype",Promise)],Cs.prototype,"query",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"update",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Array,Object]),lt("design:returntype",Promise)],Cs.prototype,"updateAll",null);class ks extends Ft{isSameObservedAdapter(t){if(!this.adapter)return!1;if(this.adapter===t)return!0;const e=this.adapter,r=t;return r instanceof se&&e.alias===r.alias&&e.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(t,e,r=!1){if(!this.adapter)throw new P("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");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:e}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const r=this.adapter;[_.CREATE,_.UPDATE,_.DELETE,I.CREATE_ALL,I.UPDATE_ALL,I.DELETE_ALL].forEach(t=>{if(!r[t])throw new P(`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 I.CREATE_ALL:return _.CREATE;case I.UPDATE_ALL:return _.UPDATE;case I.DELETE_ALL:return _.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:a,ctx:o}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...a),h=[c,i(t),l];return o.get("observeFullResult")&&h.push(Array.isArray(d)?d.map(t=>c(t)):c(d)),this.updateObservers(...h,...a).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(...t){}observe(t){if(!(t instanceof se))throw new jt("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(t))return()=>this.unObserve(t);throw new jt("Dispatch is already observing another adapter")}return this.adapter=t,this.models=se.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t)}unObserve(t){if(!this.isSameObservedAdapter(t))throw new jt("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 P("Model must be provided for observer update");const i=t&&"string"==typeof t?t:h.tableName(t);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`);const{log:n,ctxArgs:a,ctx:o}=this.logCtx(s,this.updateObservers);try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${o.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...a)}catch(t){throw new P("Failed to refresh dispatch: "+t)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ts(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 Jt.instance.generate(i)}function Ns(t=!1,r,...i){"function"==typeof t&&(r=t,t=!1);const n=Tt.UUID;return e.for(n).define({decorator:(t,e,...r)=>{const i={update:t,seed:e,args:r},n=[g(),q(Tt.UUID),H(Ts,i,{priority:54})];return t&&n.push(V(Ts,i,{priority:54})),t||n.push(z()),s(...n)},args:[t,r,...i]}).apply()}se&&(se._baseDispatch=ks);class Ds extends Ft{static{this.lock=new mt}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ue.forModel(is,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,_.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 G){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new P("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new P(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new P(`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:a}=this.options;if(!a)throw new P("Sequence name is required");return Ds.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new P("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new is({id:a,current:t}),s)}catch(e){if(e instanceof G)return r.debug(`Sequence create ${a} current=${c} next=${t}`),this.repo.create(new is({id:a,current:t}),s);throw e}};if("uuid"===o)for(;;){const t=await Promise.resolve(Jt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${a} current=${c} next=${t}`),e.current}catch(t){if(t instanceof X)continue;throw t}}const u=await(async t=>{switch(o){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(Xt.instance.generate(t));default:throw new P("Should never happen")}})(c),d=await l(u);return r.debug(`Sequence.increment ${a} current=${c} next=${u}`),d.current},a)}async next(...t){const{ctx:e}=(await this.logCtx(t,_.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,_.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new jt(`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),a=await this.increment(this.parse(t)*n,r);let o=[];for(let e=0;t-1>=e;e++)o.push(a-n*this.parse(e));if(o=o.reverse(),o[o.length-1]!==a&&"String"!==i)throw new P("Miscalculation of range");return s.debug("Calculated range: "+o.join(", ")),o}async ensureAtLeast(t,...e){const{ctx:r}=(await this.logCtx(e,_.UPDATE,!0)).for(this.ensureAtLeast),{name:s}=this.options;if(!s)throw new P("Sequence name is required");const i=this.parse(t),n=(t,e)=>"bigint"==typeof t||"bigint"==typeof e?BigInt(t)>BigInt(e):"number"==typeof t||"number"==typeof e?Number(t)>Number(e):t+"">e+"";return Ds.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(s,r)}catch(t){if(t instanceof G)return;throw t}};for(;;)try{const e=await t();if(!e)return await this.repo.create(new is({id:s,current:i}),r),i;const a=this.parse(e.current);return n(i,a)?(await this.repo.update(new is({id:s,current:i}),r),i):a}catch(t){if(t instanceof X)continue;throw t}},s)}parse(t){return Ds.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([is,...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 jt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function _s(t,...e){let r;if(t instanceof Cs&&(r=t.repo.adapter),t instanceof Ue&&(r=t.adapter),t instanceof se&&(r=t),!r)throw new P("Could not find adapter to extract transaction");return r.transactionLock(...e)}function Is(...e){return(r,s,i)=>{if(!i)throw new P("This decorator only applies to methods");return u()(r,s,i),t.set(r.constructor,t.key(wt.TRANSACTIONAL,s),{data:e}),i.value=new Proxy(i.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock"),a=n||_s(e);let o;a.depth++,n||(await a.begin(i),i.cache.put("transactionLock",a));try{o=await t.call(e,...r,i)}catch(t){const e=0===a.depth;if(a.depth=0,!e)try{await a.rollback(t,i)}catch(t){s.error("Failed to rollback transaction",t)}throw t}if(a.depth--,0===a.depth)try{await a.commit(i)}catch(t){throw new P("Failed to commit transaction: "+t)}return o}}),i}}function Bs(...t){return e.for(wt.TRANSACTIONAL).define({decorator:Is,args:t}).apply()}se._baseSequence=Ds;class Ps extends fs{constructor(){super()}for(t,...e){throw new jt("Persistence service cannot be overridden")}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof $t||!e.every(t=>Array.isArray(t)))throw new P("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,Tt.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 P(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new P(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Rs=class extends h{constructor(t){super(t),this.strategy=ne.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=ae.FULL}};ct([g(),v(String),x(ne),d("the backoff strategy"),lt("design:type",String)],Rs.prototype,"strategy",void 0),ct([g(),d("base interval between attempts"),lt("design:type",Number)],Rs.prototype,"baseMs",void 0),ct([g(),d("max interval"),lt("design:type",Number)],Rs.prototype,"maxMs",void 0),ct([v(String),x(ae),d("optional jitter strategy"),lt("design:type",String)],Rs.prototype,"jitter",void 0),Rs=ct([m(),lt("design:paramtypes",[Object])],Rs);let $s=class extends h{constructor(t){super(t)}};ct([g(),d("The error message"),lt("design:type",String)],$s.prototype,"message",void 0),ct([l(),d("The error stack"),lt("design:type",String)],$s.prototype,"stack",void 0),ct([l(),d("The error code"),lt("design:type",String)],$s.prototype,"code",void 0),ct([l(),d("The error details"),lt("design:type",Object)],$s.prototype,"details",void 0),$s=ct([m(),lt("design:paramtypes",[Object])],$s);let Fs=class extends h{constructor(t){if(super(t),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}};ct([ar(),it(["taskId","classification","uuid"],":"),lt("design:type",String)],Fs.prototype,"id",void 0),ct([Rr(),z(),g(),nt(),Ns(!1),lt("design:type",String)],Fs.prototype,"uuid",void 0),ct([Rr(),z(),g(),Ze([ge.ASC,ge.DSC]),lt("design:type",String)],Fs.prototype,"taskId",void 0),ct([E(),Rr(),g(),Ze([ge.ASC,ge.DSC]),lt("design:type",Date)],Fs.prototype,"ts",void 0),ct([Rr(),z(),g(),x(oe),Ze([ge.ASC,ge.DSC]),lt("design:type",String)],Fs.prototype,"classification",void 0),ct([l(),Rr(),at(),z(),lt("design:type",Object)],Fs.prototype,"payload",void 0),Fs=ct([Pr("task_event"),m(),lt("design:paramtypes",[Object])],Fs);class Ls extends O{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 pe){const r=this.serializePlain(t,...e);return r[C.ANCHOR]="??condition",r}return h.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[C.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(e){try{return t.modelName(e)}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[C.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?pe.from(r):h.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==C.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Ms=class extends h{constructor(t){super(t),this.ts=new Date}};ct([E(),g(),lt("design:type",Date)],Ms.prototype,"ts",void 0),ct([g(),x(gt),lt("design:type",String)],Ms.prototype,"level",void 0),ct([k(0),lt("design:type",Number)],Ms.prototype,"step",void 0),ct([g(),l(),lt("design:type",String)],Ms.prototype,"msg",void 0),ct([l(),lt("design:type",Object)],Ms.prototype,"meta",void 0),Ms=ct([m(),lt("design:paramtypes",[Object])],Ms);let js=class extends h{constructor(t){super(t),this.atomicity=ce.ATOMIC,this.status=ie.PENDING,this.attempt=0,this.logTail=[]}};ct([ar(),Ns(),d("the task id"),lt("design:type",String)],js.prototype,"id",void 0),ct([Rr(),g(),v(String),x(ce),Ze([ge.ASC,ge.DSC]),d("defines a single or composite task"),lt("design:type",String)],js.prototype,"atomicity",void 0),ct([Rr(),g(),Ze([ge.ASC,ge.DSC]),d("Holds task classification - must match @task()"),lt("design:type",String)],js.prototype,"classification",void 0),ct([Rr(),l(),Ze([ge.ASC,ge.DSC]),d("optional task name for ambiguity"),lt("design:type",String)],js.prototype,"name",void 0),ct([Rr(),l(),d("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),lt("design:type",String)],js.prototype,"lock",void 0),ct([Rr(),g(),v(String),x(ie),Ze([ge.ASC,ge.DSC]),Ze([ge.ASC,ge.DSC],["nextRunAt"]),Ze([ge.ASC,ge.DSC],["leaseExpiry"]),Ze([ge.ASC,ge.DSC],["scheduledTo"]),d("Holds the task current status"),lt("design:type",String)],js.prototype,"status",void 0),ct([l(),Rr(),at(Ls),d("Holds task input"),lt("design:type",Object)],js.prototype,"input",void 0),ct([l(),Rr(),at(Ls),d("Holds the task output when successfully completed"),lt("design:type",Object)],js.prototype,"output",void 0),ct([l(),Rr(),at(),d("Holds the error for failed tasks"),lt("design:type",$s)],js.prototype,"error",void 0),ct([Rr(),g(),k(0),Ze([ge.ASC,ge.DSC]),d("Holds the current attempt"),lt("design:type",Number)],js.prototype,"attempt",void 0),ct([Rr(),k(1),g(),d("max attempts for the task"),lt("design:type",Number)],js.prototype,"maxAttempts",void 0),ct([Rr(),g(),at(),d("backoff configuration"),lt("design:type",Rs)],js.prototype,"backoff",void 0),ct([E(),Rr(),d("Next execution timestamp"),lt("design:type",Date)],js.prototype,"nextRunAt",void 0),ct([E(),Rr(),d("Task scheduled timestamp"),lt("design:type",Date)],js.prototype,"scheduledTo",void 0),ct([Rr(),at(),d("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),lt("design:type",Array)],js.prototype,"dependencies",void 0),ct([l(),Rr(),d("Task lease owner identifier"),lt("design:type",String)],js.prototype,"leaseOwner",void 0),ct([E(),Rr(),d("Task lease expiration timestamp"),lt("design:type",Date)],js.prototype,"leaseExpiry",void 0),ct([l(),Rr(),at(),d("Holds the various steps definition and inputs - only for type === 'composite'"),lt("design:type",Array)],js.prototype,"steps",void 0),ct([l(),Rr(),k(0),Ze([ge.ASC,ge.DSC]),d("Holds the current step - only for type === 'composite'"),lt("design:type",Number)],js.prototype,"currentStep",void 0),ct([l(),Rr(),at(),d("Holds the step results - only for type === 'composite'"),lt("design:type",Array)],js.prototype,"stepResults",void 0),ct([l(),Rr(),at(),d("Holds the task log entries"),lt("design:type",Array)],js.prototype,"logTail",void 0),ct([Rr(),Ur(),Ze([ge.ASC,ge.DSC]),d("timestamp of creation"),lt("design:type",Date)],js.prototype,"createdAt",void 0),ct([Rr(),Gr(),Ze([ge.ASC,ge.DSC]),d("timestamp of last update"),lt("design:type",Date)],js.prototype,"updatedAt",void 0),ct([Rr(),Mr(),Ze([ge.ASC,ge.DSC]),d("Holds the creator of the task"),lt("design:type",String)],js.prototype,"createdBy",void 0),ct([Rr(),jr(),Ze([ge.ASC,ge.DSC]),d("Holds the creator of the task"),lt("design:type",String)],js.prototype,"updatedBy",void 0),js=ct([d("Holds the current step when applicable"),Pr("tasks"),m(),lt("design:paramtypes",[Object])],js);let Us=class extends h{constructor(t){super(t)}};ct([g(),d("The status of a step"),lt("design:type",String)],Us.prototype,"status",void 0),ct([l(),d("The result of a successful step"),lt("design:type",Object)],Us.prototype,"output",void 0),ct([l(),d("the error of a failed step"),lt("design:type",$s)],Us.prototype,"error",void 0),ct([l(),k(1),d("Number of attempts taken to complete or fail this step"),lt("design:type",Number)],Us.prototype,"attempt",void 0),Us=ct([m(),lt("design:paramtypes",[Object])],Us);let Gs=class extends h{constructor(t){super(t),this.canFail=!1}};ct([g(),d("task handler type"),lt("design:type",String)],Gs.prototype,"classification",void 0),ct([T(1),d("optional task name for ambiguity"),lt("design:type",String)],Gs.prototype,"name",void 0),ct([d("optional task step input"),l(),lt("design:type",Object)],Gs.prototype,"input",void 0),ct([d("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),l(),lt("design:type",String)],Gs.prototype,"lock",void 0),ct([d("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),l(),A(()=>String),lt("design:type",Array)],Gs.prototype,"dependsOn",void 0),ct([l(),d("Whether a failing step may be tolerated so the composite can continue"),lt("design:type",Boolean)],Gs.prototype,"canFail",void 0),ct([l(),k(1),d("Max attempts for this step. Defaults to 1 (no per-step retry)."),lt("design:type",Number)],Gs.prototype,"maxAttempts",void 0),ct([l(),at(),d("Step-level backoff config. Falls back to the parent task backoff when absent."),lt("design:type",Rs)],Gs.prototype,"backoff",void 0),Gs=ct([m(),lt("design:paramtypes",[Object])],Gs);class Ys extends h{constructor(t){super(t),this.baseMs=1e3,this.jitter=ae.FULL,this.maxMs=6e4,this.strategy=ne.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 R(t);return new Rs(this)}}ct([g(),k(1e3),lt("design:type",Number)],Ys.prototype,"baseMs",void 0),ct([g(),x(ae),lt("design:type",String)],Ys.prototype,"jitter",void 0),ct([N("baseMs"),k(1e3),g(),lt("design:type",Number)],Ys.prototype,"maxMs",void 0),ct([g(),x(ne),lt("design:type",String)],Ys.prototype,"strategy",void 0);class zs extends h{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 Ys,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}setLock(t){return this.lock=t,this}setDependencies(t){return this.dependencies=t,this}setDependsOn(t){return this.setDependencies(t)}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=ie.PENDING,this.atomicity=ce.ATOMIC,this.backoff=new Rs,this.maxAttempts=1,h.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new R(t);return new js(this)}}ct([g(),lt("design:type",String)],zs.prototype,"classification",void 0),ct([l(),lt("design:type",String)],zs.prototype,"name",void 0),ct([g(),lt("design:type",String)],zs.prototype,"status",void 0),ct([g(),lt("design:type",String)],zs.prototype,"atomicity",void 0),ct([g(),lt("design:type",Rs)],zs.prototype,"backoff",void 0),ct([l(),lt("design:type",Object)],zs.prototype,"input",void 0),ct([l(),lt("design:type",String)],zs.prototype,"lock",void 0),ct([l(),A(()=>String),lt("design:type",Array)],zs.prototype,"dependencies",void 0),ct([k(1),g(),lt("design:type",Number)],zs.prototype,"maxAttempts",void 0);class Hs{constructor(t,e){this.parent=t,this.step=e}setClassification(t){return this.step.classification=t,this}setName(t){return this.step.name=t,this}setInput(t){return this.step.input=t,this}setLock(t){return this.step.lock=t,this}setDependsOn(t){return this.step.dependsOn=t,this}setCanFail(t){return this.step.canFail=t,this}setMaxAttempts(t){return this.step.maxAttempts=t,this}setBackoff(t){return this.step.backoff=t,this}addStep(t,e,r,s){return 4>arguments.length?this.parent.addStep(t,e,r):this.parent.addStep(t,e,r,s)}setSteps(t){return this.parent.setSteps(t)}build(){return this.parent}}class qs extends zs{constructor(t){super(t),this.stepResults=[],h.fromModel(this,t),this.atomicity=ce.COMPOSITE}setAtomicity(t){throw new P("Atomicity locked to "+ce.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof Gs?t:new Gs(t)),this}addStep(t,e,r){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,a=arguments.length>=4,o=new Gs({classification:t,name:n&&"string"==typeof e?e:void 0,input:a||n&&"string"==typeof e?r:i?void 0:e,canFail:a?!!arguments[3]:!(!n||"string"==typeof e||!r),createdAt:s,updatedAt:s});return this.steps.push(o),i?new Hs(this,o):this}}ct([A(()=>Gs),lt("design:type",Array)],qs.prototype,"steps",void 0);class Vs extends Lt{get type(){if(!this._type){const e=t.get(this.constructor,le);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new P("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),L(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}async catch(t,e,r){}}function Ws(r){return e.for(le).define({decorator:e=>r=>{const s={type:e};return t.set(le,e,r),c(le,s)(r)},args:[r]}).apply()}let Qs=class extends Vs{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof pe)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=pe.attr("status").eq(ie.SUCCEEDED).and(pe.attr("updatedAt").lte(t.successfulExpiry)),i=pe.attr("status").eq(ie.FAILED).and(pe.attr("updatedAt").lte(t.failedExpiry)),n=pe.attr("status").eq(ie.CANCELED).and(pe.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}}};ct([ze(js),lt("design:type",Object)],Qs.prototype,"tasks",void 0),Qs=ct([Ws("cleanup-task"),lt("design:paramtypes",[])],Qs);class Js{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(gt).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)}fatal(t,e,r){this.logger.fatal(t,e,r)}critical(t,e,r){this.logger.critical(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Xs(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1}),r.classification){case oe.LOG:{const s=r.payload.map(t=>Array.isArray(t)?t:[t.level,t.msg,t.meta]);for(let[r,i,n]of s){e.style||(i=ft(i),i=i.clear().toString());const s=[i];r===gt.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case oe.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case oe.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=ft(e);switch(e){case ie.SUCCEEDED:s=s.green.bold;break;case ie.RUNNING:s=s.blue.bold;break;case ie.PENDING:s=s.yellow;break;case ie.WAITING_RETRY:s=s.yellow.bold;break;case ie.FAILED:s=s.red.bold;break;case ie.CANCELED:s=s.magenta.bold;break;case ie.SCHEDULED:s=s.cyan;break;default:t.warn("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;case oe.UPDATE:if(e.logProgress){const{currentStep:e,totalSteps:s,output:i}=r.payload??{},n=i?.added,a=i?.insertionIndex,o=null!=n?` (+${n} at index ${a})`:"";t.info(`### UPDATE step ${e}/${s}${o}`)}break;default:t.warn("Unhandled task event classification: "+r.classification)}}}function Ks(t,e){const r=e.strategy===ne.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===ae.FULL?Math.floor(Math.random()*s):s}function Zs(t){return new $s({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function ti(t){return new Promise(e=>setTimeout(e,t))}class ei extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=ei.name,Object.setPrototypeOf(this,ei.prototype)}}class ri extends $t{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(t){this.cache.put("step",t)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(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 ei({status:t,...e})}cancel(t,e){this.changeState(ie.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(ie.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(ie.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof $s?t:t instanceof Error?Zs(t):new $s({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const e=(t??[]).map(t=>t instanceof Gs?t:new Gs(t));return{afterCurrent:async t=>{const r=this.getOrUndefined("scheduleCompositeSteps");if(!r)throw new P("scheduleSteps().afterCurrent() is only available while running a composite task step");await r(e,t)},atEnd:async t=>{const r=this.getOrUndefined("scheduleCompositeStepsAtEnd");if(!r)throw new P("scheduleSteps().atEnd() is only available while running a composite task step");await r(e,t)}}}constructor(t){super(t)}}class si{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=t.tasks();e&&Object.entries(e).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new P(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new P("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class ii extends Mt{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(Fs,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:a}=se.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,...a)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...a)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}function ni(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class ai extends ot{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class oi extends ai{constructor(t,e,r){super(oi.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class ci extends ai{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(ci.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class li extends ai{constructor(t,e,r){super(li.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class ui extends ai{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(ui.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class di{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===Fs||t===h.tableName(Fs))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([ie.SUCCEEDED,ie.FAILED,ie.CANCELED,ie.SCHEDULED])}wait(){return this.awaitStatusTerminal([ie.SUCCEEDED,ie.FAILED,ie.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Xs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==oe.LOG)return;const r=(e.payload??[]).map(t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]);await t(r)},oe.LOG)}pipe(t,e=oe.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(ie.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(ie.FAILED,t)}onCancel(t){return this.registerStatusHandler(ie.CANCELED,t)}onUpdate(t){const e=async(e,r)=>{e.classification===oe.UPDATE&&await t(e,r)};return this.pipe(e,oe.UPDATE),()=>{this.pipes?.[oe.UPDATE]?.delete(e)}}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===ie.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[ie.SUCCEEDED,ie.CANCELED,ie.FAILED].includes(t)}async track(t,e){if(t.classification!==oe.STATUS)return;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!==ie.SUCCEEDED?(r===ie.FAILED&&this.fail(),r===ie.CANCELED&&this.cancel(t),r===ie.WAITING_RETRY&&this.retry(),r===ie.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,oe.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[oe.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new $t),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===ie.SUCCEEDED&&(e.output=this.task.output),t!==ie.FAILED&&t!==ie.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 Fs({classification:oe.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case ie.FAILED:return new oi(this.task.id,e,r);case ie.CANCELED:return new li(this.task.id,e,r);case ie.WAITING_RETRY:return new ci(this.task.id,e,r);case ie.SCHEDULED:return new ui(this.task.id,e,r);default:return new oi(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case ie.CANCELED:return ie.CANCELED;case ie.WAITING_RETRY:return ie.WAITING_RETRY;case ie.SCHEDULED:return ie.SCHEDULED;case ie.FAILED:return ie.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===ie.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[oe.ALL]?[...this.pipes[oe.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 hi extends Lt{get Context(){return ri}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,js,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,Fs,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(t,e){const r=new ri(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new yt,this.running=!1;const e=Object.assign({},ue.autoShutdown,t.autoShutdown);this.config=Object.assign({},ue,t,{autoShutdown:e,bus:t.bus||new ii,registry:t.registry||new si}),this.idleDelayMs=this.config.pollMsIdle}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,_.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 di(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=ie.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,_.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 di(this.bus,i)}}async ensureTaskError(t,e){if(![ie.FAILED,ie.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await ti(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===ie.SUCCEEDED||s.status===ie.FAILED)return s;s.status=ie.CANCELED;const i=new $s({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,ie.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.idleDelayMs=this.config.pollMsIdle,this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,Tt.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(pe.attr("status").eq(ie.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((t,n)=>{const a=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(a),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()}).catch(t=>{clearTimeout(a),n(t)})})}async loop(...t){const{ctx:e}=this.logCtx(t,this.loop),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},s=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),i=r.backoffStepMs??0;for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map(t=>this.executeClaimed(t)));const n=0===t.length;if(n)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+i,s),this.idleDelayMs>=s)return e.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(e)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const a=n?this.idleDelayMs:this.config.pollMsBusy;await ti(Math.max(a,0))}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=pe.attribute("status").eq(ie.PENDING),i=pe.attribute("status").eq(ie.WAITING_RETRY).and(pe.attribute("nextRunAt").lte(r)),n=pe.attribute("status").eq(ie.RUNNING).and(pe.attribute("leaseExpiry").lte(r)),a=pe.attribute("status").eq(ie.SCHEDULED).and(pe.attribute("scheduledTo").lte(r)),o=s.or(i).or(n).or(a),c=await this.tasks.select().where(o).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{}if(!await this.isRunnable(i,e))return null;const n=new js({...i,status:ie.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}}isTaskFinished(t){return[ie.SUCCEEDED,ie.FAILED,ie.CANCELED].includes(t)}parseTaskDependency(t){const e=t?.trim();if(!e)return;const r=e.lastIndexOf(":");if(0>=r||r>=e.length-1)return{taskId:e};const s=e.slice(0,r).trim(),i=e.slice(r+1).trim();return s&&i?{taskId:s,stepRef:i}:{taskId:e}}normalizeDependencies(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e=[e]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.filter(t=>"string"==typeof t).map(t=>this.parseTaskDependency(t)).filter(Boolean):[]}resolveDependencyStepIndex(t,e){const r=e.trim();if(!r)return;const s=Number(r);if(Number.isInteger(s)&&s>=0)return s;const i=this.normalizeSteps(t.steps).findIndex(t=>t.name===r||t.classification===r);return 0>i?void 0:i}async areDependenciesSatisfied(t,e){if(!t.length)return!0;const r=Array.from(new Set(t.map(t=>t.taskId))),s=new Map;try{const t=await this.tasks.readAll(r,e);for(const e of t)e?.id&&s.set(e.id,e)}catch{return!1}for(const e of t)try{const t=s.get(e.taskId);if(!t)return!1;if(!e.stepRef){if(!this.isTaskFinished(t.status))return!1;continue}const r=this.resolveDependencyStepIndex(t,e.stepRef);if(null==r)return!1;const i=this.normalizeStepResults(t.stepResults)[r];if(!i||!this.isTaskFinished(i.status))return!1}catch{return!1}return!0}getStepLock(t,e){if(t.atomicity!==ce.COMPOSITE)return;const r=this.normalizeSteps(t.steps);if(!r.length)return;const s=r[e??0];return s?.lock}async hasLockConflict(t,e,r){const s=[t.lock,this.getStepLock(t,e)].filter(t=>!!t&&"string"==typeof t);if(!s.length)return!1;const i=await this.tasks.select().where(pe.attribute("status").eq(ie.RUNNING)).execute(r);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(t=>!!t&&"string"==typeof t).some(t=>s.includes(t)))return!0;return!1}async isRunnable(t,e){const r=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(r,e))return!1;const s=t.atomicity===ce.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,e)}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=this;let i=Promise.resolve();const n=new ri(e).accumulate({taskId:t.id,logger:new Js(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=s.normalizePipeArgs(e);r.length&&(i=i.then(async()=>{const[e,i]=await s.appendLog(this,t,r);Object.assign(t,e),await s.emitLog(this,t.id,i)}),await i)},flush:async()=>n.logger.flush(n.pipe),progress:async e=>{await this.emitProgress(n,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let a,o;await this.emitStatus(n,t,ie.RUNNING);try{let e;if(t.atomicity===ce.COMPOSITE){e=await this.runComposite(t,n);try{const e=await this.tasks.read(t.id,n);Object.assign(t,e)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const s=this.registry.get(t.classification);if(a=s,o=t.input,r.debug(`handler type for ${t.id} is ${s?.constructor?.name??"none"}`),!s)throw new P("No task handler registered for type: "+t.classification);e=await s.run(t.input,n),await n.flush(),r.verbose("handler finished for "+t.id)}t.status=ie.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const s=await this.tasks.update(t,n);Object.assign(t,s),n.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(n,t,ie.SUCCEEDED,e)}catch(e){try{await n.flush()}catch{}try{const e=await this.tasks.read(t.id,n);Object.assign(t,e)}catch{}if(e instanceof ei)return void await this.handleTaskStateChange(e.request,t,n);try{await(a?.catch?.(o,e,n))}catch(t){r.error("task handler catch() hook failed",t)}if(r.error("task execution error",e),t.atomicity===ce.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===ie.FAILED);0>r||(t.currentStep=r)}}const s=(t.attempt??0)+1,i=Zs(e);if(s<t.maxAttempts){const a=Ks(s,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+a);t.attempt=s,t.status=ie.WAITING_RETRY,t.nextRunAt=o,t.error=i,t.leaseOwner=void 0,t.leaseExpiry=void 0;const c=await this.tasks.update(t,n);Object.assign(t,c),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await n.pipe(gt.warn,"Retry scheduled",{nextRunAt:o,delayMs:a,attempt:s}),await this.emitStatus(n,t,ie.WAITING_RETRY,i,e)}else{t.attempt=s,t.status=ie.FAILED,t.error=i,t.leaseOwner=void 0,t.leaseExpiry=void 0;const a=await this.tasks.update(t,n);Object.assign(t,a),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await n.pipe(gt.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(n,t,ie.FAILED,i,e)}}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case ie.CANCELED:{const s=t.error??new $s({message:`Task ${e.id} canceled`});return e.status=ie.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,ie.CANCELED,s),void await r.pipe(gt.warn,"Task canceled via context")}case ie.WAITING_RETRY:{const s=(e.attempt??0)+1,i=Ks(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),a=t.error??new $s({message:`Task ${e.id} requested retry`});return e.status=ie.WAITING_RETRY,e.attempt=s,e.error=a,e.nextRunAt=n,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,ie.WAITING_RETRY,a),void await r.pipe(gt.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case ie.SCHEDULED:{if(!t.scheduledTo)throw new P("Scheduled state requires a target date");const s=t.error??new $s({message:`Task ${e.id} rescheduled`});return e.status=ie.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,ie.SCHEDULED,s),void await r.pipe(gt.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new P("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite);let s=this.normalizeSteps(t.steps),i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),a=(t,s)=>{e.cacheResult(t,s),r instanceof ri&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===ie.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;a(i.classification,r.output),a(n,r.output)}}for(;i<s.length;){e.setStep(i);const o=s[i],c=this.registry.get(o.classification);if(!c)throw Error("No task handler registered for composite step: "+o.classification);const l=this.normalizeDependencies(o.dependsOn);await this.areDependenciesSatisfied(l,e)||e.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${i} (${o.classification})`),await this.hasLockConflict(t,i,e)&&e.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${i} (${o.classification})`),t.currentStep=i;const u=await this.tasks.update(t);Object.assign(t,u),await e.progress({currentStep:i,totalSteps:s.length});const d=i;e.cache.put("scheduleCompositeSteps",async(r,i)=>{const n=i.logger.for("scheduleSteps.afterCurrent"),a=this.normalizeSteps(r);if(!a.length)return;const o=this.normalizeSteps(t.steps),c=Math.min(d+1,o.length);o.splice(c,0,...a),t.steps=o;const l=await this.tasks.update(t,e);Object.assign(t,l),s=this.normalizeSteps(t.steps),n.verbose(`Inserted ${a.length} steps at index ${c}`);const u=await this.persistEvent(e,t.id,oe.UPDATE,{status:"update",currentStep:d,totalSteps:s.length,output:{added:a.length,insertionIndex:c}});this.bus.emit(u,e)}),e.cache.put("scheduleCompositeStepsAtEnd",async(r,i)=>{const n=i.logger.for("scheduleSteps.atEnd"),a=this.normalizeSteps(r);if(!a.length)return;const o=this.normalizeSteps(t.steps),c=o.length;o.push(...a),t.steps=o;const l=await this.tasks.update(t,e);Object.assign(t,l),s=this.normalizeSteps(t.steps),n.verbose(`Appended ${a.length} steps at tail (index ${c})`);const u=await this.persistEvent(e,t.id,oe.UPDATE,{status:"update",currentStep:d,totalSteps:s.length,output:{added:a.length,insertionIndex:c}});this.bus.emit(u,e)}),await e.pipe([gt.info,`Composite step ${i+1}/${s.length}: ${o.classification}`]);const h=o.maxAttempts??1;let p,g=0;for(;h>g;)try{const r=await c.run(o.input,e);await e.flush();const l=new Date;n[d]=new Us({status:ie.SUCCEEDED,output:r,attempt:g+1,createdAt:l,updatedAt:l});const u=`${t.id}:step:${d}`;a(o.classification,r),a(u,r),i=d+1,t.stepResults=n,t.currentStep=i;const h=await this.tasks.update(t);Object.assign(t,h),await this.emitProgress(e,t.id,{currentStep:i,totalSteps:s.length,output:r}),p=void 0;break}catch(r){if(g++,p=r,h>g){const r=Ks(g,this.normalizeBackoff(o.backoff??t.backoff));await e.pipe(gt.warn,`Composite step ${i} attempt ${g}/${h} failed, retrying in ${r}ms`,{classification:o.classification,attempt:g,delay:r}),await ti(r),await e.heartbeat()}}if(p){const s=new Date,a=!0===o.canFail,l=Zs(p);if(n[i]=new Us({status:ie.FAILED,error:l,attempt:g,createdAt:s,updatedAt:s}),a)try{await(c.catch?.(o.input,p,e))}catch(t){r.logger.warn("composite step catch() hook failed",{error:t})}t.stepResults=n,t.error=a?void 0:l,a?(i=d+1,t.currentStep=i):t.currentStep=i;const u=await this.tasks.update(t);if(Object.assign(t,u),!a)throw p}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Rs)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Rs(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 Us)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Us(e)}):[]}async appendLog(t,e,r){const s=Array.isArray(r)&&Array.isArray(r[0]),i=e.atomicity===ce.COMPOSITE?t instanceof ri?t.step??e.currentStep:e.currentStep:void 0,n=(s?r:[r]).map(([t,e,r])=>new Ms({level:t,msg:e,meta:r,step:i})),a=[...e.logTail??[],...n].slice(-this.config.logTailMax);e.logTail=a;try{return[await this.tasks.update(e,t),n]}catch{return[e,[]]}}async emitStatus(t,e,r,s,i){t instanceof ri&&await t.flush();const n={status:r};s&&s instanceof $s?n.error=s:s&&(n.output=s),e.nextRunAt&&(n.nextRunAt=e.nextRunAt),e.scheduledTo&&(n.scheduledTo=e.scheduledTo);const a=await this.persistEvent(t,e.id,oe.STATUS,n),o=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new Fs({...a,payload:o});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,oe.LOG,r.map(t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta,step:t.step})));this.bus.emit(s,t)}normalizePipeArgs(t){if(!t.length)return[];if(1===t.length){const e=t[0];return Array.isArray(e)?0===e.length?[]:Array.isArray(e[0])?e.filter(Array.isArray):[e]:[]}const[e,r,s]=t;return"string"!=typeof e||"string"!=typeof r?[]:[[e,r,s]]}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,oe.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Fs({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,js,...r)}}class pi extends Cs{constructor(){super(Fs)}get repo(){return this._repository||(this._repository=gs.get(js).events),this._repository}}class gi extends fs{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof $t)throw new P("No/invalid config provided");if(!e.adapter)throw new P("No adapter provided");return{client:new(e.engine||hi)(e),config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,_.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,_.CREATE,!0)).for(this.push);return this.client.track(t,...r)}select(t){return this.tasks.select(t)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.CREATE,!0)).for(this.create),s=await this.tasks.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.DELETE,!0)).for(this.delete);return this.tasks.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.READ,!0)).for(this.read);return this.tasks.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.QUERY,!0)).for(this.query),s=this.tasks?.[t];if("function"!=typeof s)throw new P(`Method "${t}" is not implemented`);return s.apply(this.tasks,r)}async update(t,...e){throw new jt("Updates to tasks are not available")}async updateAll(t,...e){throw new jt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,e,...s)}async findByPaginate(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,e,r,...i)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...r)}refresh(t,e,r,...s){return this.tasks.refresh(t,e,r,...s)}observe(t,e){return this.tasks.observe(t,e)}unObserve(t){return this.tasks.unObserve(t)}updateObservers(t,e,r,...s){return this.tasks.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.tasks._adapter.logCtx([this.tasks.class,...t],e,r,this.tasks._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,Tt.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")}}var fi;function yi(t){if(0>=t)throw new P("splitByCount: count must be greater than zero");return e=>{const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}}function mi(t){if(0>=t)throw new P("splitBySize: maxBytes must be greater than zero");return e=>{const r=[];let s=[],i=0;for(const n of e){const e=vi(n);s.length>0&&i+e>t?(r.push(s),s=[n],i=e):(s.push(n),i+=e)}return s.length>0&&r.push(s),r}}function wi(e,r,n){let a,o;if("function"==typeof e)a=e,o=r??{};else{const t="string"==typeof r?r:fi.BY_COUNT;o=("object"!=typeof r||Array.isArray(r)?n:r)??{},a=t===fi.BY_SIZE?mi(e):yi(e)}const{delayMs:c,argIndex:l=0}=o;return(e,r,n)=>s(i(t.key(Tt.THROTTLE,r),o),(t,e,r)=>{r.value=new Proxy(r.value,{async apply(t,r,s){const i=s,{log:n,ctx:u}=(await r.logCtx(s,t.name,!0)).for(wi),d=(t=>{const e=(Array.isArray(t)?t:[t]).map(t=>{if(!Number.isFinite(t)||0>t)throw new P("@throttle() argument indexes must be non-negative integers");return t});return Array.from(new Set(e)).sort((t,e)=>t-e)})(l);if(!d.length)throw new P("@throttle() expects at least one argument index to throttle");d.forEach(t=>{if(t>=i.length)throw new P(`@throttle() requires argument index ${t} but only ${i.length} provided`);if(!Array.isArray(i[t]))throw new P(`@throttle() expects argument at index ${t} to be an array`)});const h=d.map(t=>i[t]),p=h[0].length;if(!h.every(t=>t.length===p))throw new P("@throttle() requires all targeted arguments to have the same length");if(0===p)return t.apply(r,i);const g=((t,e,r,s)=>{let i=0;return t.map(t=>{const n=t.length,a=s.map((s,a)=>{const o=r.indexOf(a);return-1===o?s:0===o?t:e[o].slice(i,i+n)});return i+=n,a})})(a(h[0]),h,d,i),f=o.breakOnSingleFailure??(()=>{try{return u.get("breakOnSingleFailureInBulk")}catch{return}})()??!0,y=[],m=[];for(const e of g){try{bi(await t.apply(r,e),y)}catch(t){if(f)throw t;m.push(t)}c&&await new Promise(t=>setTimeout(t,c))}if(m.length){n.warn(`${e+""} throttled execution continued with ${m.length} failure(s)`);const t=new AggregateError(m,`Throttled ${e+""} failed for ${m.length} chunk(s)`);throw t.results=y,t}return y}})})(e,r,n)}function vi(t){if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}}function bi(t,e){Array.isArray(t)?e.push(...t):void 0!==t&&e.push(t)}ct([ms(),lt("design:type",Function),lt("design:paramtypes",[js,void 0]),lt("design:returntype",Promise)],gi.prototype,"create",null),ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"createAll",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],gi.prototype,"delete",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"deleteAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],gi.prototype,"read",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"readAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[String,void 0]),lt("design:returntype",Promise)],gi.prototype,"query",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[js,void 0]),lt("design:returntype",Promise)],gi.prototype,"update",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"updateAll",null),(t=>{t.BY_COUNT="count",t.BY_SIZE="size"})(fi||(fi={}));const Ai=Object.assign({},Dt,{persistMigrationSteps:!0});class Si{constructor(t="migration-task"){this.builder=(new qs).setClassification("migration-composite").setName(t).setMaxAttempts(1)}addMigrationStep(t){return this.builder.addStep("migration",t),this}addStep(t,e){return this.builder.addStep(t,e),this}build(){return this.builder.build()}}class xi{isVersionHint(t){return!!t}normalize(t,e){return e&&t&&(t.includes(e)||t===e)?e:t||e||"migration"}compare(t,e){return t.localeCompare(e)}gt(t,e){return this.compare(t,e)>0}lte(t,e){return 0>=this.compare(t,e)}}class Ei extends fs{constructor(){super(),this.versioning=new xi,this.allowedReferences=void 0,this.queuedTaskChain=[],this.reference=Ei.name,this.precedence=null}static async migrateAdapters(t,e={},...r){return(Ei.defaultSingleton||=new Ei).migrateAdapters(t,e,...r)}async migrateAdapters(t,e={},...r){const s=e.flavours?.length?new Set(e.flavours):void 0,i=t.filter(t=>!s||s.has(t.alias)),n=new Set(t.map(t=>t.alias).filter(Boolean)),a=e.taskService?.client,o=a?.adapter?.alias||a?.adapter?.flavour;if(o&&n.has(o))throw new P(`TaskEngine adapter alias "${o}" cannot participate in the migration targets`);const c=this;c.versioning=e.versioning||new xi,c.allowedReferences=e.references?.length?new Set(e.references):void 0,c.queuedTaskChain=[],c.orchestrationConfig={...Ai,targetVersion:e.toVersion,taskMode:!!e.taskMode,taskService:e.taskService,versioning:e.versioning,references:e.references};for(const t of i){const s=t.alias,n=e.handlers?.[s]||e.handlers?.[t.flavour]||{},a={...Ai,persistenceFlavour:s,targetVersion:e.toVersion,taskMode:!!e.taskMode,includeGenericInTaskMode:e.includeGenericInTaskMode??!(e.taskMode&&i.length>1),retrieveLastVersion:n.retrieveLastVersion,setCurrentVersion:n.setCurrentVersion,taskService:e.taskService,versioning:e.versioning,references:e.references};e.taskMode?await c.migrateViaTasksWithConfig(a,...r):await c.migrateNormallyWithConfig(a,...r)}return c}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.initialize);try{gs.get(Tt.PERSISTENCE)}catch(t){r.get("ignoreDevSafeGuards")||e.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:Ai,Ai);return this.versioning=s.versioning||new xi,this.allowedReferences=s.references?.length?new Set(s.references):void 0,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?se.get(s.persistenceFlavour):void 0}}async down(t,e,...r){const{log:s}=this.logCtx(r,this.down);s.verbose(ft("Cleaning up after all migrations").green.bold)}normalizeVersion(t,e){return this.versioning.normalize(t,e)}extractPrecedenceTokens(t){const e=t.precedence;return e?(Array.isArray(e)?e:[e]).map(t=>{if(t&&"string"!=typeof t)return"function"==typeof t?t.name:"string"==typeof t.reference?t.reference:t.constructor?.name?t.constructor.name:void 0}).filter(t=>!!t):[]}referencesMigration(t,e){const r=this.extractPrecedenceTokens(t);return!!r.length&&(r.includes(e.reference)||r.includes(e.migration?.constructor?.name))}precedenceHint(t){return"string"==typeof t.precedence?t.precedence:void 0}compareByPrecedence(t,e){const r=t.migration,s=e.migration,i=this.referencesMigration(r,e),n=this.referencesMigration(s,t);if(i&&!n)return 1;if(n&&!i)return-1;const a=this.extractPrecedenceTokens(r),o=this.extractPrecedenceTokens(s);return a.length!==o.length?a.length-o.length:0}sort(t){const e=[...t].sort((t,e)=>{const r=this.versioning.compare(t.version,e.version);if(0!==r)return r;const s=this.compareByPrecedence(t,e);if(0!==s)return s;const i=t.flavour.localeCompare(e.flavour);return 0!==i?i:t.reference.localeCompare(e.reference)});for(let t=0;t<e.length;t++){const r=e[t],s=e[t+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new P(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return e}resolveMigration(e){const s=t.get(e.constructor,Tt.MIGRATION),i=s?.flavour||e.flavour||r,n=s?.reference||e.reference,a=this.precedenceHint(e);return{migration:e,flavour:i,reference:n,version:this.normalizeVersion(n,a)}}shouldIncludeMigration(t,e,s=!0){return!e||t.flavour===e||s&&t.flavour===r}collectMigrations(e,r=!0){const s=t.migrations(),i=[];for(const[t,n]of s){let s;try{s=new n}catch(e){throw new P(`failed to create migration ${t}: ${e}`)}const a=this.resolveMigration(s);this.shouldIncludeMigration(a,e,r)&&i.push(a)}return i}buildExecutionPlan(t){const e=t?.fromVersion?this.normalizeVersion(t.fromVersion):void 0,r=t?.toVersion?this.normalizeVersion(t.toVersion):void 0;return this.sort(this.collectMigrations(t?.targetFlavour,t?.includeGeneric)).filter(t=>!(this.allowedReferences&&!this.allowedReferences.has(t.reference)||e&&!this.versioning.gt(t.version,e)||r&&!this.versioning.lte(t.version,r)))}async executeMigration(t,...e){const r=t.migration;let s,i;try{if(s=se.get(t.flavour),!s)throw new P(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(t){throw new P(`Failed to load adapter to migrate ${r.reference}: ${t}`)}try{await r.up(i,s,...e)}catch(t){throw new Ut(`failed to initialize migration ${r.reference}: ${t}`)}try{await r.migrate(i,s,...e)}catch(t){throw new Ut(`failed to migrate ${r.reference}: ${t}`)}try{await r.down(i,s,...e)}catch(t){throw new Ut(`failed to conclude migration ${r.reference}: ${t}`)}}buildMigrationTaskForPlan(t,...e){const r=[...e],s=new Si;return t.forEach(t=>{const e={reference:t.reference,args:r};s.addMigrationStep(e)}),s.build()}buildMigrationTasksForPlan(t,...e){const r=new Map;for(const e of t){const t=r.get(e.version)||[];t.push(e),r.set(e.version,t)}return[...r.entries()].map(([t,r])=>({version:t,task:this.buildMigrationTaskForPlan(r,...e)}))}createMigrationTask(t,e,...r){const s=this.config,i=!s.taskMode||(s.includeGenericInTaskMode??!0),n=this.buildExecutionPlan({toVersion:t||s.targetVersion,fromVersion:e,targetFlavour:s.persistenceFlavour,includeGeneric:i});return this.buildMigrationTaskForPlan(n,...r)}createMigrationTasks(t,e,...r){const s=this.config,i=!s.taskMode||(s.includeGenericInTaskMode??!0),n=this.buildExecutionPlan({toVersion:t||s.targetVersion,fromVersion:e,targetFlavour:s.persistenceFlavour,includeGeneric:i});return this.buildMigrationTasksForPlan(n,...r)}migrationTaskIdsFromContext(t,e){const r=e[e.length-1],s=r?.pending?.()||r?.pending||{},i=s?.[t];return Array.isArray(i)?i.filter(t=>"string"==typeof t):[]}async migrate(t,e,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(t,e,...r){return this.migrateNormallyWithConfig(this.config,...r)}async migrateNormallyWithConfig(t,...e){const{ctxArgs:r,log:s}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.migrateNormally),i=t.persistenceFlavour,n=!t.taskMode||(t.includeGenericInTaskMode??!0),a=i?se.get(i):void 0;let o;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(a,...r);e&&(o=this.normalizeVersion(e))}const c=this.buildExecutionPlan({fromVersion:o,toVersion:t.targetVersion,targetFlavour:i,includeGeneric:n});s.debug("sorted migration before execution: "+c.map(t=>`${t.reference}@${t.version}`));for(const t of c)await this.executeMigration(t,...r);if(t.setCurrentVersion){const e=t.targetVersion||c[c.length-1]?.version||o||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),a,...r)}}async migrateViaTasks(t,e,...r){return this.queuedTaskChain=[],this.migrateViaTasksWithConfig(this.config,...r)}async migrateViaTasksWithConfig(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.migrateViaTasks),n=t.persistenceFlavour,a=t.includeGenericInTaskMode??!0,o=n?se.get(n):void 0;let c;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(o,...s);e&&(c=this.normalizeVersion(e))}const l=this.buildExecutionPlan({fromVersion:c,toVersion:t.targetVersion,targetFlavour:n,includeGeneric:a});if(i.debug("sorted migration before execution: "+l.map(t=>`${t.reference}@${t.version}`)),l.length){const e=this.buildMigrationTasksForPlan(l,...s);if(t.taskService){let n;for(const a of e){n&&(a.task.dependencies=[...a.task.dependencies||[],n]);const e=await t.taskService.push(a.task,!1,...s);n=e.id,this.queuedTaskChain.push({id:e.id,version:a.version,adapter:o,setCurrentVersion:t.setCurrentVersion}),e?.id||i.warn("TaskService.push returned missing id for version "+a.version),r.pushPending(Tt.MIGRATION,e.id)}}else{for(const t of l)await this.executeMigration(t,...s);if(t.setCurrentVersion){const e=t.targetVersion||l[l.length-1]?.version||c||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),o,...s)}}}}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.track),s=this.orchestrationConfig||this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(t=>t.id),a=this.migrationTaskIdsFromContext(Tt.MIGRATION,r),o=i?.length?i:n.length?n:a;if(!o.length)return;const c=new Map(this.queuedTaskChain.map(t=>[t.id,t])),l=s.persistenceFlavour?se.get(s.persistenceFlavour):void 0;for(const t of o){const{tracker:e}=await s.taskService.track(t,...r);await e.wait();const i=c.get(t),n=i?.setCurrentVersion||s.setCurrentVersion;n&&i?.version&&await n(this.normalizeVersion(i.version),i.adapter||l,...r)}}async retry(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.retry),s=this.orchestrationConfig||this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...r);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(t=>t.id),a=this.migrationTaskIdsFromContext(Tt.MIGRATION,r),o=i?.length?i:n.length?n:a;if(!o.length)return void await this.migrateViaTasks(void 0,void 0,...r);const c=s.taskService.client.tasks,l="function"==typeof c?.override?c.override({ignoreHandlers:!0}):c;for(const t of o){const e=(await s.taskService.track(t,...r)).task;if(![ie.FAILED,ie.CANCELED].includes(e.status))continue;const i=new js({...e,status:ie.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await l.update(i,...r)}}async up(t,e,...r){const{log:s}=this.logCtx(r,this.down);s.verbose(ft("Setting up migration process").yellow.bold)}}const Oi=t.innerGet(Symbol.for(Tt.MIGRATION),r)||[];function Ci(s,i,n,a){return e.for(Tt.MIGRATION).define({decorator:(e,i,n)=>a=>{const o=e&&"object"==typeof e&&!("name"in e)?e:void 0,l=o?.precedence,u=o?.flavour,d=o?.rules,h=o?l:e,p=o?u:i,g=o?d:n,f=o?void 0!==l:void 0!==h&&("string"!=typeof h||"string"==typeof h&&"string"==typeof p);let y,m,w=h;"string"==typeof h?"string"==typeof p?(w=h,y=p,m=g):Array.isArray(p)?(w=void 0,y=h,m=p):(w=void 0,y=h,m=g):Array.isArray(p)?m=p:(y=p,m=g),void 0===w&&null!==w&&(w=Ei);const v=t.flavourOf(a)||r,b=(f&&w===Ei&&s&&s!==y?s:y)||v,A=t.innerGet(Symbol.for([Tt.MIGRATION,Tt.BY_KEY].join("-")),b||r)||[];return t.set([Tt.MIGRATION,Tt.BY_KEY].join("-"),b||r,[...A,{class:a}]),t.set(Tt.MIGRATION,s,a),c(Tt.MIGRATION,{reference:s||a.name,precedence:w,flavour:b||r,rules:m})(a)},args:[i,n,a]}).apply()}t.set(Tt.MIGRATION,r,[...Oi,Ei]);class ki extends Lt{get reference(){if(!this._reference){const e=t.get(this.constructor,Tt.MIGRATION);if(this._reference=e.reference,!this._reference)throw new P(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const e=t.get(this.constructor,Tt.MIGRATION);if(this._precedence=e.precedence,!this._precedence)throw new P(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;Qt(this,t,this.prefix(e))})}get adapter(){const e=t.get(this.constructor,Tt.MIGRATION);if(!e)throw new P("No migration metadata for "+this.constructor.name);const r=e.flavour;return se.get(r)}async enforceRules(e,r,s){const i=t.get(this.constructor,Tt.MIGRATION)?.rules;if(!i||!i.length)return!0;for(const t of i)if(!await t(e,r,s))return!1;return!0}prefix(t){return async function(e,...r){let s;e instanceof se?s=this.getQueryRunner(e.client):(s=e,e=this.adapter);const{ctx:i,log:n}=await this.logCtx([t,...r],Tt.MIGRATION,!0);if(!await this.enforceRules(s,e,i))throw n.verbose(`Skipping migration ${this.constructor.name} due to rules`),new Gt("Migration skipped for rule enforcement");return[s,e,i]}.bind(this)}logCtx(t,e,r=!1,s){let i;try{i=this.adapter}catch{i=void 0}return r&&i?i.context("string"==typeof e?e:e.name,s||{},void 0,...t).then(r=>super.logCtx(["string"==typeof e?e:e.name,...t.slice(0,-1),r],Tt.MIGRATION,!1,s)):super.logCtx(t,e,r,s)}}let Ti=class extends Vs{async run(e,r){r.logger.info("Executing migration "+e.reference);const s=t.migrations().find(([,r])=>{const s=r?.name,i=t.get(r,Tt.MIGRATION)?.reference;return s===e.reference||i===e.reference});if(!s)throw new P(`Migration ${e.reference} is not registered with the metadata layer`);const i=s[1];let n;try{n=new i}catch(t){throw new P(`Failed to instantiate migration ${e.reference}: ${t}`)}const a=t.get(n.constructor,Tt.MIGRATION),o=a?.flavour||n.flavour,c=se.get(o);if(!c)throw new P("Unable to resolve adapter for migration "+e.reference);const l=c.client,u=e.args??[];try{await n.up(l,c,...u,r)}catch(t){throw r.logger.error(`Up phase for ${e.reference} failed: ${t}`),new Ut(`Up phase for ${e.reference} failed: ${t}`)}try{await n.migrate(l,c,...u,r)}catch(t){throw r.logger.error(`migration phase for ${e.reference} failed: ${t}`),new Ut(`Migration phase for ${e.reference} failed: ${t}`)}try{await n.down(l,c,...u,r)}catch(t){throw r.logger.error(`down phase for ${e.reference} failed: ${t}`),new Ut(`Down phase for ${e.reference} failed: ${t}`)}r.logger.info(`migration ${e.reference} completed`)}};Ti=ct([Ws("migration")],Ti),vt.setRegistry(new Ye);const Ni="##VERSION##",Di="##COMMIT##",_i="##FULL_VERSION##",Ii="##PACKAGE##";t.registerLibrary(Ii,Ni);export{Lt as AbsContextual,ki as AbsMigration,se as Adapter,je as AuthKeys,_r as AuthorizationError,ne as BackoffStrategy,ss as BaseModel,Ke as BigIntSequence,Di as COMMIT,fe as Cascade,Qs as CleanUpTask,fs as ClientBasedService,qs as CompositeTaskBuilder,pe as Condition,Br as ConnectionError,$t as Context,Zt as ContextLock,Ft as ContextualLoggedClass,Dt as DefaultAdapterFlags,ye as DefaultCascade,Nt as DefaultContextFlags,Ai as DefaultMigrationConfig,Ie as DefaultRepositoryFilters,Je as DefaultSequenceOptions,ue as DefaultTaskEngineConfig,ks as Dispatch,_i as FULL_VERSION,Ir as ForbiddenError,Ot as GroupOperator,kt as INDEX_SELF,Ye as InjectablesRegistry,ae as JitterStrategy,ve as MethodQueryBuilder,Ut as MigrationError,Gt as MigrationRuleError,Ei as MigrationService,Ti as MigrationTask,Si as MigrationTaskBuilder,Cs as ModelService,Pt as MultipleSelectOperationKeys,It as NonTransactionOperationKeys,Qe as NoneSequenceOptions,Xe as NumericSequence,He as ObserverError,Mt as ObserverHandler,Et as Operator,me as OperatorsMap,ge as OrderDirection,Ii as PACKAGE_NAME,Rt as PaginationOperationKeys,ns as Paginator,he as PagingError,Tt as PersistenceKeys,Ps as PersistenceService,Ct as PreparedStatementKeys,xt as QueryClause,de as QueryError,Ue as Repository,Bt as SelectOperationKeys,Ds as Sequence,is as SequenceModel,Xt as Serial,gs as Service,Kt as SimpleConcurrencyLock,xi as StandardMigrationVersioning,ps as Statement,Ys as TaskBackoffBuilder,Rs as TaskBackoffModel,zs as TaskBuilder,li as TaskCancelError,ri as TaskContext,ai as TaskControlError,hi as TaskEngine,$s as TaskErrorModel,ii as TaskEventBus,Fs as TaskEventModel,pi as TaskEventService,oe as TaskEventType,oi as TaskFailError,Vs as TaskHandler,si as TaskHandlerRegistry,Ls as TaskIOSerializer,Ms as TaskLogEntryModel,Js as TaskLogger,js as TaskModel,ui as TaskRescheduleError,ci as TaskRetryError,gi as TaskService,ie as TaskStatus,Us as TaskStepResultModel,Hs as TaskStepSpecBuilder,Gs as TaskStepSpecModel,di as TaskTracker,ce as TaskType,le as TasksKey,fi as ThrottleMode,_t as TransactionOperationKeys,Jt as UUID,jt as UnsupportedError,Ni as VERSION,Ve as allowIf,xe as applyViewDecorator,Ss as auth,We as blockIf,Cr as cacheModelForPopulate,Tr as cascadeDelete,Rr as column,Ks as computeBackoffMs,ms as create,cr as createOrUpdate,Ur as createdAt,Mr as createdBy,Lr as createdByOnCreateUpdate,be as defaultQueryAttr,bs as del,Ge as generateInjectableNameForRepository,Ar as getAndConstructJunctionTable,Be as getFilters,Xs as getLogPipe,Vr as getPkTypes,Er as getPopulateKey,Or as getTagForDeleteKey,Ze as index,Yt as injectableServiceKey,Vt as isOperationBlocked,ni as isTaskError,Xr as manyToMany,vr as manyToManyOnCreate,xr as manyToManyOnDelete,Sr as manyToManyOnUpdate,Jr as manyToOne,fr as manyToOneOnCreate,wr as manyToOneOnDelete,mr as manyToOneOnUpdate,Ci as migration,Kr as noValidateOn,Zr as noValidateOnCreate,es as noValidateOnCreateUpdate,ts as noValidateOnUpdate,Wt as normalizeImport,Qr as oneToMany,hr as oneToManyOnCreateUpdate,gr as oneToManyOnDelete,pr as oneToManyOnUpdate,Wr as oneToOne,lr as oneToOneOnCreate,dr as oneToOneOnDelete,ur as oneToOneOnUpdate,De as onlyOnBulk,Oe as onlyOnCreate,ke as onlyOnDelete,_e as onlyOnFilter,Ne as onlyOnSingle,Te as onlyOnTransactional,Ce as onlyOnUpdate,Hr as persistentVersion,ar as pk,ir as pkDec,rr as pkOnCreate,kr as populate,Qt as prefixMethod,Ae as prepared,zt as promiseSequence,Se as query,ws as read,rs as relation,ze as repository,Dr as repositoryFromTypeMetadata,re as resolveBulkSequenceResult,_s as resolveTransactionLock,xs as roles,Es as route,or as sequence,nr as sequenceDec,sr as sequenceOnCreateUpdate,Zs as serializeError,As as service,ti as sleep,yi as splitByCount,mi as splitBySize,Pr as table,Ws as task,wi as throttle,Bs as transactional,Fr as unique,$r as uniqueOnCreateUpdate,vs as update,Gr as updatedAt,jr as updatedBy,Ns as uuid,Ts as uuidCreateUpdateHandler,yr as validBidirectionalRelation,qr as version,Ee as view};
|
|
1
|
+
import{Metadata as t,Decoration as e,DefaultFlavour as r,apply as s,methodMetadata as i,propMetadata as n,DecorationKeys as o,uses as a,metadata as c,prop as l,method as u,description as d}from"@decaf-ts/decoration";import{Model as h,hashObj as p,required as g,sf as f,isEqual as y,model as m,ValidationKeys as w,type as v,async as b,list as A,option as x,date as E,JSONSerializer as O,ModelKeys as C,min as k,minlength as T,gt as N}from"@decaf-ts/decorator-validation";import{DefaultRepositoryFlags as D,OperationKeys as I,BulkCrudOperationKeys as _,Context as B,InternalError as P,ValidationError as R,DBKeys as $,Repository as F,wrapMethodWithContext as L,wrapMethodWithContextForUpdate as M,enforceDBDecorators as j,reduceErrorsToPrint as U,NotFoundError as G,DefaultSeparator as Y,readonly as z,onCreate as H,generated as q,onUpdate as V,BadRequestError as W,timestamp as Q,onCreateUpdate as J,ConflictError as X,version as Z,afterAny as tt,onDelete as et,SerializationError as rt,prefixMethod as st,composed as it,transient as nt,serialize as ot,BaseError as at}from"@decaf-ts/db-decorators";import{__decorate as ct,__metadata as lt}from"tslib";import{Logging as ut,LoggedClass as dt,final as ht,toCamelCase as pt,LogLevel as gt,style as ft}from"@decaf-ts/logging";import{Lock as yt,MultiLock as mt,TransactionalKeys as wt}from"@decaf-ts/transactional-decorators";import{Injectables as vt,InjectableRegistryImp as bt,inject as At,injectable as St}from"@decaf-ts/injectable-decorators";var xt,Et,Ot,Ct;(t=>{t.FIND_BY="findBy",t.PAGE_BY="pageBy",t.COUNT_BY="countBy",t.SUM_BY="sumBy",t.AVG_BY="avgBy",t.MIN_BY="minBy",t.MAX_BY="maxBy",t.DISTINCT_BY="distinctBy",t.GROUP_BY_PREFIX="groupBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(xt||(xt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.STARTS_WITH="STARTS_WITH",t.ENDS_WITH="ENDS_WITH",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(Et||(Et={})),(t=>{t.AND="AND",t.OR="OR"})(Ot||(Ot={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_BY_PAGINATE="findByPaginate",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ct||(Ct={}));const kt="__self__";var Tt;(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.SEQUENCE="sequence",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute",t.THROTTLE="throttle",t.PERSISTENT_VERSION="persistent-version",t.DEFAULT_QUERY_ATTR="default-query-attr"})(Tt||(Tt={}));const Nt=Object.assign({},{ignoreDevSafeGuards:!1}),Dt=Object.assign({},D,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1,maxConcurrentTransactions:-1}),It=[I.CREATE,I.UPDATE,I.DELETE,_.CREATE_ALL,_.UPDATE_ALL,_.DELETE_ALL],_t=[I.READ,_.READ_ALL],Bt=[Tt.STATEMENT,Ct.FIND_ONE_BY],Pt=[Tt.QUERY,Ct.PAGE_BY,Ct.FIND_BY_PAGINATE,Ct.LIST_BY,Ct.FIND_BY,Ct.FIND,Ct.PAGE],Rt=[Ct.PAGE_BY,Ct.FIND_BY_PAGINATE,Ct.PAGE];class $t extends B{constructor(t){super(t)}static{this.factory=t=>(new $t).accumulate(Object.assign({},t,{timestamp:new Date,logger:t.logger||ut.get()}))}static async from(t,e,r,...s){return this.factory(Object.assign({},e||{},{operation:t,model:r,affectedTables:r,args:s,logger:e?.logger||ut.get()}))}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new P(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter(t=>!e.has(t)),s.length)){const r=s.map(r=>r.getFromChildren(t,e)).reduce((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t),[]).filter(t=>null!=t);if(!r.length)return;return r.some(t=>"object"!=typeof t)?r[0]:r.reduce((t,e)=>Object.assign(t,e),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new P("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 Ft extends dt{logCtx(t,e,r=!1,s){return Ft.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||ut.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 $t||(t=>{if(!t||"object"!=typeof t)return!1;const e=t;return"function"==typeof e.get&&"function"==typeof e.accumulate&&"function"==typeof e.override&&"function"==typeof e.toOverrides&&void 0!==e.cache})(n);if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new P("No context provided");if(o&&!r){if(!n)throw new P("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 P("No contextual provided");if(!this.context)throw new P("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 Lt extends Ft{constructor(){super(),this._Context=$t}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 $t||(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 Mt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new P("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 P("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=Ft.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 jt extends P{constructor(t){super(t,jt.name,500)}}class Ut extends P{constructor(t,e=Ut.name){super(t,e,500)}}class Gt extends Ut{constructor(t){super(t,Gt.name)}}function Yt(e){if(!e)throw new P("No name provided");return"string"==typeof e?e.replaceAll(".","-"):t.Symbol(t.constr(e)).toString().replaceAll(".","-")}async function zt(t,e=!1){if(!e){const e=[];for(const r of t)e.push(await r());return e}const r=[];for(const e of t)try{r.push({status:"fulfilled",value:await e()})}catch(t){r.push({status:"rejected",reason:t})}return r}const Ht=[I.CREATE,I.READ,I.UPDATE,I.DELETE];function qt(t){return Ht.includes(t)}function Vt(e,r,s){const i=t.get(e,I.REFLECT+I.BLOCK)||{};if(!i?.handler)return!1;const n=void 0===s&&qt(r)?"crud":r,o=void 0===s&&qt(r)?r:s,a=i.args?.[0]||[];return i.handler(a,n,o)??!1}async function Wt(t){return t.then(t=>t.default||t)}function Qt(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 Gt)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 Jt{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 Jt._instance||(Jt._instance=new Jt),Jt._instance}}class Xt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Xt._instance||(Xt._instance=new Xt),Xt._instance}}class Kt extends yt{static{this.registry=new WeakMap}static for(t,e){let r=Kt.registry.get(t);return r||(r=new Kt(e),Kt.registry.set(t,r)),r}constructor(t){super(),this.waiters=[],this.permits=t}async acquire(t){if(0>=this.permits)return new Promise(t=>this.waiters.push(t));this.permits--}release(t){const e=this.waiters.shift();e?e():this.permits++}}class Zt{constructor(t,...e){this.adapter=t,this.depth=0}async begin(t){const{log:e,ctx:r}=this.adapter.logCtx([t],this.begin),s=r.getOrUndefined("maxConcurrentTransactions"),i="number"==typeof s?s:Dt.maxConcurrentTransactions;if(0===i)throw e.debug(`Rejecting transaction on adapter "${this.adapter.alias}": transactions are disabled (maxConcurrentTransactions=0)`),new jt(`Transactions are disabled for adapter "${this.adapter.alias}" (maxConcurrentTransactions=0)`);i>0&&(e.silly(`Gating transaction on adapter "${this.adapter.alias}" (maxConcurrentTransactions=${i})`),this.semaphore=Kt.for(this.adapter,i),await this.semaphore.acquire(r))}async commit(t){const{ctx:e}=this.adapter.logCtx([t],this.commit);this.semaphore?.release(e)}async rollback(t,e){const{ctx:r}=this.adapter.logCtx([e],this.rollback);this.semaphore?.release(r)}}const te=e.flavourResolver.bind(e);e.flavourResolver=e=>{const s=t=>{if(!t)return;const e=se._cache?.[t];return e?.flavour||t};try{const i=te(e);if(i&&i!==r)return s(i);const n="function"==typeof e?e:e?.constructor,o=n&&"function"==typeof t.registeredFlavour?t.registeredFlavour(n):void 0;if(o&&o!==r)return s(o);const a=se._currentFlavour;if(a){const t=se._cache?.[a];return t?.flavour?t.flavour:s(a)}}catch(t){return r}};const ee=Symbol("AdapterProxyCleanup");function re(t,e,r,s){if(!e)return t;const i=t,n=[],o=[];for(const t of i)"fulfilled"===t.status?n.push(t.value):o.push(t.reason);if(o.length){r.warn(`Bulk ${s} encountered ${o.length} failure(s) while continuing`);const t=new AggregateError(o,`Bulk ${s} failed for ${o.length} item(s)`);throw t.results=i,t}return n}class se extends Lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!se._baseRepository)throw new P("This should be overridden when necessary. Otherwise it will be replaced lazily");return se._baseRepository}transactionLock(...t){return new Zt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new P("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[ee];"function"==typeof e&&await e()};if(t)try{await s(this.proxies[t]),delete this.proxies[t]}catch(e){r.error("Failed to cleanup proxied adapter "+t,e)}else for(const t in this.proxies){try{await s(this.proxies[t])}catch(e){r.error("Failed to cleanup proxied adapter "+t,e);continue}delete this.proxies[t]}}async shutdown(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Tt.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(Tt.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:e}=(await this.logCtx(t,Tt.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...r),this.dispatch&&await this.dispatch.close(...r)})()}catch(t){throw new P("Failed to create shutdown wrapper: "+t)}finally{this.internalLock.release(Tt.SHUTDOWN)}try{await this.shutdownPromise}catch(t){e.error("Error during proxy shutdown",t)}finally{this.shutdownPromise=void 0}}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.internalLock=new yt,this.alias in se._cache)throw new P(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);se._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in se._cache||(se._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),se._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),se._currentFlavour=this.alias)}Dispatch(){return new se._baseDispatch}ObserverHandler(){return new Mt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new se._baseSequence(t,this,e)}async flags(e,r,s,...i){if("string"==typeof r)throw new P("Model must be a constructor or array of constructors or undefined. this should be impossible");const n=Array.isArray(r)?r.length?r[0]:void 0:r,o=n?""+h.tableName(n):"";s.correlationId=s.correlationId||`${o}|${e}|${Jt.instance.generate()}`;const a=s.logger||ut.for(this),c=Object.assign({},Dt.cacheForPopulate,s.cacheForPopulate);return Object.assign({},Dt,s,{affectedTables:r?[...new Set([...(Array.isArray(r)?r:[r]).filter(Boolean),...s.affectedTables?Array.isArray(s.affectedTables)?s.affectedTables:[s.affectedTables]:[]])]:s.affectedTables,cacheForPopulate:c,args:i,writeOperation:It.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:r?t.validationExceptions(Array.isArray(r)&&r[0]?r[0]:r,e):[],logger:a})}get Context(){return $t}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 $t||(s.push(i),i=void 0);const n=(()=>{if(!i)return!1;try{return!!i.get("allowGenerationOverride")}catch{return!1}})();e=i?Object.assign({},i.toOverrides(),e):e,n&&(e.allowGenerationOverride=!0);const o=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,...o,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,...o,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(o)}return(new this.Context).accumulate({...o})}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 P(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[Tt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[Tt.METADATA]),Object.defineProperty(i,Tt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[Tt.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[Tt.METADATA],u=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 u&&void 0!==u[t])throw new P(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);u[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(u,Tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),u}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new R("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new R("Ids and models must have the same length");const o=h.tableName(t);i.debug(`Creating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),c=e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})));return re(a?await zt(c,!0):await zt(c),a,i,_.CREATE_ALL)}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=h.tableName(t);s.debug(`Reading ${e.length} entries ${n} table`);const o=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map(e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0})));return re(o?await zt(a,!0):await zt(a),o,s,_.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new P("Ids and models must have the same length");const o=h.tableName(t);i.debug(`Updating ${e.length} entries ${o} table`);const a=!(n.get("breakOnSingleFailureInBulk")??1),c=e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})));return re(a?await zt(c,!0):await zt(c),a,i,_.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})));return re(n?await zt(o,!0):await zt(o),n,s,_.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new P("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new P("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(e){return t.flavourOf(e)}static get currentFlavour(){if(!se._currentFlavour)throw new P("No persistence flavour set. Please initialize your adapter");return se._currentFlavour}static get current(){return se.get(this.currentFlavour)}static unregister(t){if(!t)return;const e=se._cache[t];e&&(delete se._cache[t],se._currentFlavour===t&&(se._currentFlavour=void 0),e.flavour&&se._cache[e.flavour]&&se._cache[e.flavour]===e&&delete se._cache[e.flavour])}static get(t){if(!t)return se.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new P(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(e){try{return t.flavouredAs(e).filter(h.isModel)}catch(t){throw new P(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} - ${p(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return Reflect.defineProperty(i,ee,{value:async()=>{if(!s)return;const t=["cancel","close","destroy","disconnect"];for(const e of t){const t=s[e];if("function"==typeof t)try{const e=t.call(s);e instanceof Promise&&await e}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=i,i}migrations(){return t.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}var ie,ne,oe,ae,ce;ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,Object,$t]),lt("design:returntype",Promise)],se.prototype,"context",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],se.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],se.prototype,"unObserve",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],se.prototype,"client",null),(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(ie||(ie={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(ne||(ne={})),(t=>{t.NONE="none",t.FULL="full"})(oe||(oe={})),(t=>{t.STATUS="status",t.UPDATE="update",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(ae||(ae={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(ce||(ce={}));const le="tasks",ue={workerId:"default-worker",concurrency:10,maxConcurrentCompositeSteps:-1,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};t.tasks=(()=>t.innerGet(Symbol.for(le))).bind(t),t.taskFor=(e=>{const r=t.tasks();return r?r[e]:void 0}).bind(t),t.validationExceptions=((e,r)=>{const s=t.get(e,Tt.NO_VALIDATE)||[],i=Object.entries(s).filter(([,t])=>t.includes(r)).map(([t])=>t);let n=[];return r!==I.CREATE&&r!==I.UPDATE||(n=h.nestedRelations(e)),[...new Set([...i,...n])]}).bind(t),t.migrationsFor=(e=>{if(!(e=e??se.current))throw new P("Could not get adapter for migrations");return t.innerGet(Symbol.for(Tt.MIGRATION),e.alias).map(t=>t.class)}).bind(t),t.migrations=(()=>{const e=t.innerGet(Symbol.for([Tt.MIGRATION,Tt.BY_KEY].join("-")));return Object.values(e).flat().map(t=>[t.class.name,t.class])}).bind(t),t.relations=((e,r)=>{const s=t.get(e,Tt.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new P("No relations metadata found for property "+r);return s[r]}}).bind(t),h.relations=(e,r)=>t.relations(e instanceof h?e.constructor:e,r)||[],h.nestedRelations=((e,r=[])=>{let s=[];const i=t.get(e,Tt.RELATIONS);if(!i||!Object.keys(i).length)return[...new Set([...r])];for(const t in i){const e=i[t];if(e?.class&&h.relations(e.class)){const i=h.relations(e.class).map(e=>`${t}.${e}`);r=[...r,...i],s=h.nestedRelations(e.class,r)}}return[...new Set([...r,...s])]}).bind(h),h.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!h.sequenceFor(r).generated}).bind(h),h.fromTable=(e=>{const r=t.innerGet(Symbol.for(Tt.TABLE));if(!r||!r[e]||!h.get(r[e].name))throw new P("No table metadata found for model. did you use @table()?");return h.get(r[e].name)}).bind(h),t.createdBy=(e=>{const r=t.get("function"!=typeof e?e.constructor:e,Tt.CREATED_BY);if(!r)throw new P("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(t),t.updatedBy=(e=>{const r=t.get("function"!=typeof e?e.constructor:e,Tt.UPDATED_BY);if(!r)throw new P("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(t),h.tableName=e=>{if(!(e instanceof h?h.get(e.constructor.name):e))throw new P("Unable to find model "+e);return t.get(e instanceof h?e.constructor:e,Tt.TABLE)||(e instanceof h?e.constructor.name:e.name)},h.columnName=(e,r)=>t.get(e instanceof h?e.constructor:e,t.key(Tt.COLUMN,r))||r,h.defaultQueryAttributes=(e,r=!1)=>{const s="function"==typeof e?e:e.constructor;return t.get(s,t.key(Tt.DEFAULT_QUERY_ATTR))||(r?[h.pk(e)]:[])},h.sequenceName=(t,...e)=>[h.tableName(t),...e].join("_"),h.versionOf=(e=>{const r=t.get(e.constructor),s=r?.[Tt.PERSISTENT_VERSION],i=s&&"object"==typeof s?Object.keys(s)[0]:void 0,n=r?.[$.VERSION],o=n&&"object"==typeof n?Object.keys(n)[0]:void 0,a=i??o;if(!a)throw new P("No version found for "+e.constructor.name);const c=e[a];if("number"!=typeof c||1>c)throw new P("Invalid version number: "+c);return c}).bind(h),h.sequenceFor=(e,r)=>{const s="function"!=typeof e?e.constructor:e;let i=Tt.SEQUENCE;const n=h.pk(s);r&&r+""!=n+""||(r=n,i=$.ID),i=t.key(i,r);const o=t.get(s,i);if(!o)throw new P(`No sequence options defined for property ${r+""}. did you use @sequence() or @pk()?`);return o},h.indexes=e=>{const r=t.get(e instanceof h?e.constructor:e,Tt.INDEX);return Object.keys(r||{}).reduce((t,e)=>{const s=r[e]||{};return t[e]=Object.keys(s).reduce((t,e)=>(t[e===kt?Tt.INDEX:`${Tt.INDEX}_${e}`]=s[e],t),{}),t},{})},vt.services=()=>t.innerGet(Symbol.for(Tt.SERVICE)),vt.repositories=()=>t.innerGet(Symbol.for($.REPOSITORY)),h.merge=((t,e,r)=>{const s=t=>Object.entries(t).reduce((t,[e,s])=>{let i=!1;try{"relation.one-to-one"===h.relations(r,e).key&&(i=!0)}catch(t){i=!1}return(void 0!==s||i)&&(t[e]=s),t},{});return new(r=r||t.constructor)(Object.assign({},s(t),s(e)))}).bind(h);class de extends P{constructor(t){super(t,de.name,500)}}class he extends P{constructor(t){super(t,he.name,500)}}class pe 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 pe.and(this,t)}or(t){return pe.or(this,t)}not(t){return new pe(this,Et.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof pe)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(Et).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===Et.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof pe){if(!(this.comparison instanceof pe)&&this.operator!==Et.NOT)return{comparison:{condition:t}};if(-1===Object.values(Ot).indexOf(this.operator)&&this.operator!==Et.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return pe.group(t,Ot.AND,e)}static or(t,e){return pe.group(t,Ot.OR,e)}static group(t,e,r){return new pe(t,e,r)}static attribute(t){return(new pe.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(Et.EQUAL,t)}dif(t){return this.setOp(Et.DIFFERENT,t)}gt(t){return this.setOp(Et.BIGGER,t)}lt(t){return this.setOp(Et.SMALLER,t)}gte(t){return this.setOp(Et.BIGGER_EQ,t)}lte(t){return this.setOp(Et.SMALLER_EQ,t)}in(t){return this.setOp(Et.IN,t)}regexp(t){return this.setOp(Et.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(Et.STARTS_WITH,t)}endsWith(t){return this.setOp(Et.ENDS_WITH,t)}between(t,e){return this.setOp(Et.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new pe(this.attr1,this.operator,this.comparison)}catch(t){throw new de(t)}}}}static builder(){return new pe.Builder}static from(t){return new pe(t)}}var ge,fe;ct([g(),lt("design:type",Object)],pe.prototype,"attr1",void 0),ct([g(),lt("design:type",String)],pe.prototype,"operator",void 0),ct([g(),lt("design:type",Object)],pe.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(ge||(ge={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(fe||(fe={}));const ye={update:fe.CASCADE,delete:fe.NONE},me={Equals:(t,e)=>pe.attribute(t).eq(e),Diff:(t,e)=>pe.attribute(t).dif(e),LessThan:(t,e)=>pe.attribute(t).lt(e),LessThanEqual:(t,e)=>pe.attribute(t).lte(e),GreaterThan:(t,e)=>pe.attribute(t).gt(e),GreaterThanEqual:(t,e)=>pe.attribute(t).gte(e),In:(t,e)=>pe.attribute(t).in(e),Matches:(t,e)=>pe.attribute(t).regexp(e)},we=t=>t.charAt(0).toLowerCase()+t.slice(1);class ve extends dt{static get log(){return this._logger||(this._logger=ut.for(ve.name)),this._logger}static{this.prefixMap={[xt.FIND_BY]:"find",[xt.PAGE_BY]:"page",[xt.COUNT_BY]:"count",[xt.SUM_BY]:"sum",[xt.AVG_BY]:"avg",[xt.MIN_BY]:"min",[xt.MAX_BY]:"max",[xt.DISTINCT_BY]:"distinct",[xt.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(t){for(const[e,r]of Object.entries(this.prefixMap))if(t.startsWith(e))return{action:r,prefix:e}}static build(t,...e){const r=this.getActionFromMethodName(t);if(!r)throw Error("Unsupported method "+t);const{action:s,prefix:i}=r;let n;["count","sum","avg","min","max","distinct","group"].includes(s)&&(n=this.extractAggregationSelector(t,i));const o=this.extractCore(t,i),a=this.extractSelect(t),c=this.extractGroupBy(t),l=this.buildWhere(o,e),{orderBy:u,limit:d,offset:h}=this.extractOrderLimitOffset(t,e,o);return{action:s,select:a,selector:n,where:l,groupBy:c,orderBy:u,limit:d,offset:h}}static extractAggregationSelector(t,e){const r=t.substring(e.length),s=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),i=s?r.substring(0,s.index):r;return i?we(i):void 0}static extractCore(t,e=xt.FIND_BY){const r=t.substring(e.length);if(e!==xt.FIND_BY&&e!==xt.PAGE_BY){const t=r.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!t)return"";if("And"===t[0]||"Or"===t[0]){const e=r.substring(t.index+t[0].length),s=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return s?e.substring(0,s.index):e}return""}const s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?r.substring(0,s.index):r}static getFieldsFromMethodName(t){const e=this.getActionFromMethodName(t),r=e?.prefix||xt.FIND_BY,s=this.extractCore(t,r);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(t=>t.length>0).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")}):[]}static extractSelect(t){const e=t.indexOf(xt.SELECT);if(-1===e)return;const r=t.substring(e+xt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(xt.AND).map(we).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(xt.GROUP_BY);if(-1!==e)return t.substring(e+xt.GROUP_BY.length).split(xt.ORDER_BY)[0].split(xt.THEN_BY).map(we).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(xt.THEN_BY);if(-1===s)return;const i=e.substring(s+xt.THEN_BY.length).split(xt.THEN_BY),n=[];for(const t of i){const e=t.match(/(OrderBy|Limit|Offset|Select)/),r=e?t.substring(0,e.index):t;r&&n.push(we(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?me[o]:me.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+s);const l=a(s,c);n=0===r?l:i[r-1]===xt.AND?n.and(l):n.or(l)}),n}static parseFieldAndOperator(t){for(const e of Object.keys(me))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:we(r),operator:e}}return{field:we(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=ve.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new de("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(ge).includes(e))throw new de(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(ge).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 B&&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 be(){return(e,r)=>{const i=t.key(Tt.DEFAULT_QUERY_ATTR);let o=t.get(e.constructor,i)||[];return o=[...new Set([...o,r])],s(n(i,o))(e,r)}}function Ae(){return e.for(Tt.STATEMENT).define({decorator:()=>(e,r,n)=>s(i(t.key(Tt.STATEMENT,r),!0))(e,r,n),args:[]}).apply()}function Se(r={}){return e.for(Tt.QUERY).define({decorator:e=>function r(n,o,a){const c=ve.getFieldsFromMethodName(o);return s(i(t.key(Tt.QUERY,o),{...e,fields:c}),Ae(),(t=>(e,s,i)=>{i.value=new Proxy(i.value,{async apply(e,s,i){const{action:n,select:o,selector:a,where:c,groupBy:l,orderBy:u,limit:d,offset:h}=ve.build(e.name,...i);if(!(s instanceof F))throw Error("thisArg must be an instance of Repository");const p=s,{ctx:g}=(await p.logCtx(i,r.name,!0)).for(r);let f;switch(n){case"find":case"page":f=p.select(o);break;case"count":f=p.count(a);break;case"sum":f=p.sum(a);break;case"avg":f=p.avg(a);break;case"min":f=p.min(a);break;case"max":f=p.max(a);break;case"distinct":f=p.distinct(a);break;case"group":f=p.select(),a&&(f=f.groupBy(a));break;default:throw new de("Unsupported action: "+n)}if(c&&(f=f.where(c)),l&&l.length>0&&"group"!==n){f=f.groupBy(l[0]);for(let t=1;t<l.length;t++)f=f.thenBy(l[t])}else if(l&&l.length>0&&"group"===n)for(const t of l)f=f.thenBy(t);const{allowLimit:y,allowOffset:m,allowOrderBy:w,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},b=[{key:"orderBy",value:(u||[])[0],allowed:w},{key:"limit",value:d,allowed:y},{key:"offset",value:h,allowed:m}];for(const t of b)if(void 0!==t.value){if(!t.allowed&&v)throw new de(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(f=f[t.key](t.value))}if("page"===n){const t=i[i.length-1],e="number"==typeof t?t:t?.limit??10;return f.paginate(e,g)}return f.execute(g)}})})(e))(n,o,a)},args:[r]}).apply()}function xe(e,r,s){return(i,o)=>{const a=s?.name||((e,r,s)=>{const i=(t.get(e.constructor,r)||{})[s]||{};return Object.keys(i).length+1+""})(i,e,o),c=t.key(e,o,a),l={...s||{},kind:r,attribute:o};return n(c,l)(i,o)}}function Ee(t){return e.for(Et.VIEW).define({decorator:t=>xe(Et.VIEW,"view",t),args:[t]}).apply()}function Oe(t){return Ie(t,[I.CREATE,_.CREATE_ALL])}function Ce(t){return Ie(t,[I.UPDATE,_.UPDATE_ALL])}function ke(t){return Ie(t,[I.DELETE,_.DELETE_ALL])}function Te(t){return Ie(t,It)}function Ne(t){return Ie(t,Object.values(I))}function De(t){return Ie(t,Object.values(_))}function Ie(e,r){return(s,i,n,...o)=>{if("string"==typeof e)throw new P("clazz cannot be string. This should be impossible");const{log:a}=Ft.prototype.logCtx(o,Ie);return a.silly(`filtering ${i} event for${s?" "+(h.tableName(s)||s):""} ${n}`),("string"==typeof s?s===h.tableName(e)||s===e.constructor.name:t.constr(e)===t.constr(s))&&r.includes(i)}}const _e={onlyOnCreate:Oe,onlyOnUpdate:Ce,onlyOnDelete:ke,onlyOnTransactional:Te,onlyOnSingle:Ne,onlyOnBulk:De};function Be(t){const e=Object.assign({},_e);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}var Pe,Re,$e,Fe,Le,Me,je;class Ue extends F{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 P("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 Be(this)}constructor(e,s,i=!1,...n){super(s),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),s&&(Ue.register(s,this,this.adapter.alias,i),e)&&t.get(s,o.FLAVOUR)===r&&a(e.flavour)(s);const c=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;L(c,c[e+"Prefix"],t,c[e+"Suffix"])}),M(c,c[this.updateAll.name+"Prefix"],this.updateAll,c[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 Mt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,I.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 j(this,r,t,I.CREATE,I.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 R(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,_.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 a=h.sequenceFor(t[0]);let c=[];if(h.generatedBySequence(this.class)?(a.name||(a.name=h.sequenceName(t[0],"pk")),c=await(await this.adapter.Sequence(a,this._overrides)).range(t.length,...s)):h.generated(this.class,this.pk)||(c=t.map((t,e)=>{if(void 0===t[this.pk])throw new P("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),a.type&&(t[this.pk]="String"!==a.type||a.generated?c[e]:""+t[this.pk]),n||await j(this,r,t,I.CREATE,I.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=U(s);if(n)throw new R(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,I.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 j(this,r,o,I.READ,I.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,_.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,j(this,r,e,I.READ,I.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,I.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const a=t[this.pk];if(!a)throw new P("No value for the Id is defined under the property "+this.pk);let c;if(r.get("applyUpdateValidation")&&(c=await this.read(a,r),r.get("mergeForUpdate")&&(t=h.merge(c,t,this.class))),n||await j(this,r,t,I.UPDATE,I.ON,c),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(c,...e));if(s)throw new R(s.toString())}return[t,...s,c]}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,_.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const a=t.map(t=>{const e=t[this.pk];if(!e)throw new P("missing id on update operation");return e});let c;if(r.get("applyUpdateValidation")&&(c=await this.readAll(a,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>h.merge(c[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>j(this,r,t,I.UPDATE,I.ON,c?c[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(c[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=U(s);if(n)throw new R(n)}return[t,...s,c]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,I.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await j(this,r,e,I.DELETE,I.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,_.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=>j(this,r,t,I.DELETE,I.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=ge.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,Tt.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,Ct.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){r.offset=r.offset||1,r.limit=r.limit||10;const{offset:i,bookmark:n,limit:o}=r;if(!i&&!n)throw new de("PaginateBy needs a page or a bookmark");const{log:a,ctx:c,ctxArgs:l}=(await this.logCtx(s,Ct.PAGE_BY,!0)).for(this.paginateBy);let u;if(a.verbose(`paginating ${h.tableName(this.class)} with page size ${o}`),n&&c.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===ge.ASC?this.attr(h.pk(this.class)).gt(n):this.attr(h.pk(this.class)).lt(n))()).orderBy([t,e]).paginate(o,...l);else{if(!i)throw new de("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(o,...l)}const d=await u.page(i,n&&!c.get("paginateByBookmark")?n:void 0,...l);return u.serialize(d)}async find(t,e=ge.ASC,...r){if("string"!=typeof t)throw new de("Find value must be a string");const s=this.getDefaultQueryAttributes(),{log:i,ctxArgs:n}=(await this.logCtx(r,Ct.FIND,!0)).for(this.find);i.verbose(`finding ${h.tableName(this.class)} by default attributes ${s.join(", ")}`);const o=this.buildDefaultStartsWithCondition(t,s);return this.select().where(o).orderBy([s[0],e]).execute(...n)}async page(t,e=ge.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new de("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new de("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:p}=(await this.logCtx(s,Ct.PAGE,!0)).for(this.page);u.verbose(`paging ${h.tableName(this.class)} by default attributes ${c.join(", ")}`);const g=a??10,f=c[0],y=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let m;if(o&&d.get("paginateByBookmark")){const t=h.pk(this.class),r=e===ge.ASC?this.attr(t).gt(o):this.attr(t).lt(o);m=await y.select().where(l.and(r)).orderBy([f,e]).paginate(g,...p)}else{if(!n)throw new de("PaginateBy needs a page or a bookmark");m=await y.select().where(l).orderBy([f,e]).paginate(g,...p)}const w=await m.page(i,o&&!d.get("paginateByBookmark")?o:void 0,...p);return m.serialize(w)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.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 G("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.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 findByPaginate(t,e,r={direction:ge.DSC,offset:1,limit:10},...s){r.direction=r.direction||ge.DSC,r.offset=r.offset||1,r.limit=r.limit||10;const{direction:i,offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new de("FindByPaginate needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);c.verbose(`finding and paginating ${h.tableName(this.class)} with ${t} ${e}`);const d=this.attr(t).eq(e);let p;if(o&&l.get("paginateByBookmark")){const e=h.pk(this.class),r=i===ge.ASC?this.attr(e).gt(o):this.attr(e).lt(o);p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(d.and(r)).orderBy([t,i]).paginate(a,...u)}else{if(!n)throw new de("FindByPaginate needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(d).orderBy([t,i]).paginate(a,...u)}const g=await p.page(n,o&&!l.get("paginateByBookmark")?o:void 0,...u);return p.serialize(g)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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,Ct.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(!Ue.statements(this,t))throw new de("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const t=h.defaultQueryAttributes(this.class);if(!t||!t.length)throw new de("No default query attributes defined for "+h.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new de("Default query value must be a string");let r;for(const s of e){const e=this.attr(s).startsWith(t);r=r?r.or(e):e}if(!r)throw new de("No default query attributes available for "+h.tableName(this.class));return r}attr(t){return pe.attr(t)}observe(e,r){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const s=this.log.for(this.observe),i=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,r,s,...n)=>"string"==typeof e?e===i:t.constr(e)===t.constr(this.class)),s.verbose(`now observing ${this.adapter} filtering on table === ${i}`),this.observerHandler.observe(e,r),s.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(t){if(!this.observerHandler)throw new P("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 P("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=>se._baseSequence.parseValue(h.sequenceFor(this.class).type,t)):se._baseSequence.parseValue(h.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(e,s,...i){let n;const o=t.registeredFlavour(e),a=o&&o!==r?o:void 0,c=s||a||t.flavourOf(e)||se.currentFlavour;try{n=this.get(e,c)}catch(t){n=void 0}const l="function"==typeof n?n:void 0,u=s||a||t.flavourOf(e)||l&&t.get(l,Tt.ADAPTER)||se.currentFlavour,d=u?se.get(u):void 0;if(!d)throw new P("No registered persistence adapter found flavour "+u);if(n instanceof Ue)return n;const p=[h.tableName(e),d.alias].join(Y),g=l||d.repository();return delete this._cache[p],new g(d,e,...i)}static get(t,e){const r=h.tableName(t);let s=r;if(e&&(s=[r,e].join(Y)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new P("Could not find repository registered under "+r)}static register(t,e,r,s=!1){let i=h.tableName(t);if(r&&(i=[i,r].join(Y)),i in this._cache&&this._cache[i]instanceof Ue&&!s)throw new P(i+" already has a registered instance");this._cache[i]=e}static statements(e,r){const s=e instanceof Ue?e.constructor:e,i=t.get(s,r?t.key(Tt.STATEMENT,r):Tt.STATEMENT);return(r?i:Object.keys(i))||!1}static queries(e,r){const s=e instanceof Ue?e.constructor:e;return t.get(s,r?t.key(Tt.QUERY,r):Tt.QUERY)}}function Ge(t,s){if(!(s||(s=e.flavourResolver(t instanceof h?t.constructor:t))&&s!==r))throw new P("Could not retrieve flavour from model "+(t instanceof h?t.constructor.name:t.name));return f(Tt.INJECTABLE,s,h.tableName(t))}ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,String,void 0]),lt("design:returntype",Promise)],Ue.prototype,"listBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,String,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"paginateBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[String,String,void 0]),lt("design:returntype",Promise)],Ue.prototype,"find",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[String,String,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"page",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findOneBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findBy",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,Object,Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"findByPaginate",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"countOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Pe="undefined"!=typeof K&&K)?Pe:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"maxOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Re="undefined"!=typeof K&&K)?Re:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"minOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof($e="undefined"!=typeof K&&K)?$e:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"avgOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Fe="undefined"!=typeof K&&K)?Fe:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"sumOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Le="undefined"!=typeof K&&K)?Le:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"distinctOf",null),ct([Ae(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(Me="undefined"!=typeof K&&K)?Me:Object,void 0]),lt("design:returntype",Promise)],Ue.prototype,"groupOf",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],Ue.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],Ue.prototype,"unObserve",null),se&&(se._baseRepository=Ue);class Ye extends bt{get log(){return this.logger||(this.logger=ut.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=h.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=h.get(e.toString())),!n)return;const o=Tt.ADAPTER,a=r||t.get(n,o)||t.flavourOf(n);try{let e=a;try{a&&se.get(a)}catch{const t=se.current;t&&t.flavour===a&&(e=t.alias)}if(i=Ue.forModel(n,e),i instanceof Ue)return i;const r=a||t.get(i.constructor,o)||t.get(n,o);vt.register(i,Ge(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=Ue.get(n,a);if("function"==typeof e){const t=a?se.get(a):se.current;if(!t)return;return new e(t,n)}}}return i}}function ze(e,r){return(s,i)=>i?At(t.constr(e))(s,i):(t.set($.REPOSITORY,t.key(r||se.currentFlavour,h.tableName(e)),s),c($.REPOSITORY,s.name)(e),r=r||t.get(s.constructor,Tt.ADAPTER),Ue.register(e,s),St(t.constr(e),{callback:t=>(Object.defineProperty(t,$.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(s))}class He extends P{constructor(t){super(t,He.name,500)}}function qe(t,e,r,s,i){i.value=new Proxy(i.value,{async apply(i,n,o){((t,e,r)=>{if("function"!=typeof t?.logCtx)throw new jt(`${e} on ${t?.constructor?.name??"UnknownClass"}.${r} requires a logCtx() method`)})(n,t,s+"");const{ctx:a,ctxArgs:c}=await n.logCtx(o,i.name,!0);let l;try{l=e(...o,...r,a)}catch(t){throw new P("Failed to execute auth validation handler: "+t)}if(l)throw l;return i.call(n,...c)}})}function Ve(t,...e){return(r,s,i)=>{qe("allowIf",t,e,s,i)}}function We(t,...e){return(r,s,i)=>{qe("blockIf",t,e,s,i)}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(je||(je={}));const Qe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Je=Qe,Xe={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Ke=Object.assign({},Xe,{type:"BigInt"});function Ze(r,s,i){return e.for(Tt.INDEX).define({decorator:(e,r,s)=>(i,o)=>{"string"==typeof e&&(s=e,e=void 0,r=void 0),"string"==typeof r&&(s=r,r=void 0),!r&&e&&e.find(t=>![ge.ASC,ge.DSC].includes(t))&&(r=e,e=void 0);const a=r&&r.length?r.join("_"):kt;return n(t.key(Tt.INDEX,o,a),{directions:e,compositions:r,name:s})(i,o)},args:[r,s,i]}).apply()}function tr(t){return"function"==typeof t}function er(e,r,s){if(!s.type){const i=t.type(e.constructor,r);if(![Number.name,String.name,BigInt.name].includes(i?.name||i))throw Error("Incorrrect option type");s.type=i}switch(s.type){case String.name||String.name.toLowerCase():case String:s.generated=void 0!==s.generated&&s.generated,s.type=String;break;case Number.name||String.name.toLowerCase():case Number:s.generated=void 0===s.generated||s.generated,s.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:s.type=BigInt,s.generated=void 0===s.generated||s.generated;break;case"uuid":case"serial":s.generated=!0;break;default:throw Error("Unsupported type")}void 0===s.generated&&(s.generated=!0)}async function rr(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 P(`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)}async function sr(t,e,r,s,i){if(!e.type||!e.generated)return;if(!e.name){const t=h.pk(s,!0);if(null==t)throw new P("Cannot generate sequence without an id for "+s.constructor.name);e.name=h.sequenceName(s,t+"",r+"")}let n;try{n=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new P(`Failed to instantiate Sequence ${e.name}: ${t}`)}const o=null!=i,a=void 0!==s[r]&&null!==s[r],c=!!t.get("allowGenerationOverride")&&a;if(a&&await n.ensureAtLeast(s[r],t),o&&!e.update)return;if(c)return;const l=await n.next(t);Reflect.set(s,r,l)}function ir(e,r){return(i,o)=>{l()(i,o),er(i,o,e),e.name||(e.name=((t,e)=>tr(h.sequenceName)?h.sequenceName(t,e):[tr(h.tableName)?h.tableName(t):t?.name??"",e].filter(Boolean).join("_"))(i.constructor,"pk"));const a=[n(t.key($.ID,o),e),n(t.key(Tt.SEQUENCE,o),e),Ze([ge.ASC,ge.DSC]),g(),z(),H(rr,e,r)];return e.generated&&a.push(q()),s(...a)(i,o)}}function nr(e,r={},i){return(o,a)=>{l()(o,a),er(o,a,e);const c=[g(),n(t.key(Tt.SEQUENCE,a),e),H(sr,{...e,...r},i)];return r.update&&c.push(V(sr,{...e,...r},i)),e.generated&&c.push(q()),s(...c)(o,a)}}function or(t){const r=Object.assign({},Je);return delete r.generated,t=Object.assign({},r,t),e.for($.ID).define({decorator:ir,args:[t,{priority:60}]}).apply()}function ar(t,r){const s=Object.assign({},Je);delete s.generated,t=Object.assign({},s,t);const i="boolean"==typeof r?{update:r}:r||{};return e.for(Tt.SEQUENCE).define({decorator:nr,args:[t,i,{priority:70}]}).apply()}async function cr(t,e,r,s,i){const n=e.logger.for(cr);if(!s){const e=h.get(t.constructor.name);if(!e)throw new P("Could not find model "+t.constructor.name);s=Ue.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 G))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 lr(t,e,r,s){const i=s[r];if(!i)return;if(yr(s,e),"object"!=typeof i){const e=Dr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Cr(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 P("Could not find model "+e.class);const o=Ue.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=h.pk(a);await Cr(t,s,r,a[c],a),s[r]=a[c]}async function ur(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==fe.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 Cr(t,s,r,i,n),void(s[r]=i)}const n=await cr(s[r],t,this.adapter.alias,void 0,this._overrides),o=h.pk(n);await Cr(t,s,r,n[o],n),s[r]=n[o]}async function dr(t,e,r,s){const i=s[r];if(null==i)return;if(e.cascade.delete!==fe.CASCADE)return;const n=Dr(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 Cr(t,s,r,o[n.pk],o)}async function hr(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;yr(s,e);const o=t.logger.for(hr),a=Dr(s,r,this.adapter.alias),c=h.pk("function"!=typeof e.class||e.class.name?e.class:e.class()),l=new Set;for(const e of n){let i;"object"!=typeof e?(i=await a.override(this._overrides).read(e,t),o.debug("read: "+i[c])):(o.verbose("Creating or updating one-to-many model: "+e[c]),i=await cr(e,t,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await Cr(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function pr(t,e,r,s,i){const{cascade:n}=e;if(n.update===fe.CASCADE)return hr.call(this,t,e,r,s,i)}async function gr(t,e,r,s){if(e.cascade.delete!==fe.CASCADE)return;const i=s[r];if(!i)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new P(`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?Ue.forModel(o,this.adapter.alias):Dr(s,r,this.adapter.alias),l=[...new Set([...a?i.map(t=>t[c.pk]):i]).values()];let u,d;try{u=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){d=u[e];try{await Cr(t,s,r,l[e],d)}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 fr(t,e,r,s){const i=s[r];if(!i)return;yr(s,e);const n=t.logger.for(fr);if("object"!=typeof i){const e=Dr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Cr(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof h?e.class.constructor:e.class))throw new P("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const o=await cr(i,t,this.adapter.alias,void 0,this._overrides),a=h.pk(o);n.info(`caching: ${JSON.stringify(o)} under ${o[a]}`),await Cr(t,s,r,o[a],o),s[r]=o[a]}function yr(e,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=t.get(i,Tt.RELATIONS);if(n&&(s=Object.values(n)?.find(t=>{const r="function"==typeof t.class&&t.class.name?t.class:t.class();return e instanceof r})),!0===s?.populate&&!0===r?.populate)throw new P("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function mr(t,e,r,s){const{cascade:i}=e;if(i.update===fe.CASCADE)return fr.call(this,t,e,r,s)}async function wr(t,e,r,s){if(e.cascade.delete!==fe.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,o=n?Ue.forModel(i,this.adapter.alias):Dr(s,r,this.adapter.alias),a=n?i[o.pk]:i,c=await o.override(this._overrides).delete(a);await Cr(t,s,r,a,c),s[r]=a}async function vr(t,e,r,s){const i=s[r];if(!i||!i.length)return;yr(s,e);const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new P(`Invalid operation. All elements of property ${r} must match the same type.`);const o=t.logger.for(vr),a=new Set([...i]);if("object"!==n){const n=Dr(s,r,this.adapter.alias),c=await n.override(this._overrides).readAll([...a.values()],t);for(let e=0;e<c.length;e++){const s=c[e];o.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(s)),await Cr(t,s,r,[...a.values()][e],c)}return await br.call(this,s,[...i],o,t,e),s[r]=[...a],void o.info("SET MANY 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 many-to-many model: "+JSON.stringify(e));const i=await cr(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Cr(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 u=h.pk(s.constructor);if(void 0===s[u]){const e=await(async(t,e,r)=>{const s=e[h.pk(e.constructor)];if(void 0!==s)return s;const i=h.sequenceFor(e.constructor);let n;i?.name||(i.name=h.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i,t._overrides),await n.next(r)}catch(t){throw new P(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[u]=e}const d=await br.call(this,s,i,o,t,e);o.info("Junction model created: "+d.name),s[r]=[...l]}async function br(t,e,r,s,i){const{JunctionModel:n,fkA:o,fkB:a}=Ar(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 h?t[h.pk(t.constructor)]:t,[a]:i instanceof h?i[h.pk(i.constructor)]:i},l=await cr(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Ue.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function Ar(e,r,s){const i=h.tableName(e);let n;if(r instanceof h)n=h.tableName(r);else if(h.isModel(r)&&"function"==typeof r)n=r.name?r.name:r()?.name;else if(s?.class){const t="function"!=typeof s.class||s.class.name?s.class:s.class();n=h.tableName(t)}if(!i||!n)throw new P("Missing tablenames to create junction table");const o=s?.joinTable?.name?s?.joinTable?.name:`${i}_${n}`,a=i?.toLowerCase()+"_fk",c=n?.toLowerCase()+"_fk",l=class extends h{constructor(t){super(t)}};Object.defineProperty(l,"name",{value:o,writable:!1}),or({type:Number})(l.prototype,"id"),g()(l.prototype,a),g()(l.prototype,c);const u=m()(l);return t.set(l,Tt.TABLE,o),{fkA:a,fkB:c,JunctionModel:u}}async function Sr(t,e,r,s){const{cascade:i}=e;if(i.update===fe.CASCADE)return vr.call(this,t,e,r,s)}async function xr(t,e,r,s){if(e.cascade.delete!==fe.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 P(`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?Ue.forModel(o,this.adapter.alias):Dr(s,r,this.adapter.alias),l=[...new Set([...a?i.map(t=>t[c.pk]):i]).values()];let u,d;try{u=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){d=u[e];try{await Cr(t,s,r,l[e],d)}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 Er(t,e,r){return e?[Tt.POPULATE,t,e,r].join("."):[Tt.POPULATE,t,r].join(".")}function Or(t,e,r){return[Tt.TAG_FOR_DELETION,t,r].join(".")}async function Cr(t,e,r,s,i){const n=Er(e.constructor.name,r,s),o=t.logger.for(Cr),a=t.get("cacheForPopulate")||{};let c=a[n],l=t.getOrUndefined("preferFromCache");if(!l)try{o.silly("retrieving from children"),l=t.getFromChildren("preferFromCache")||!1,l&&(c=(t.getFromChildren("cacheForPopulate")||{})[n])}catch(t){l=!1}return l&&o.debug("preferring previous cache: "+!!a[n]),a[n]=l&&c?c:i,t.accumulate({cacheForPopulate:a})}async function kr(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=this,a=await(async(e,r,s,i)=>{let n,a;const c=[];let l;try{l=e.get("operation")}catch(t){l=void 0}const u=l===I.READ||l===_.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=Er(r.constructor.name,s,e);try{if(a=u[n],!a)throw Error("Not found in cache")}catch(i){const n=Dr(r,s,o.adapter.alias);if(!n)throw new P("Could not find repo");a=await n.override(o._overrides).read(e,t)}c.push(a)}return c})(t,s,r,n?i:[i]);s[r]=n?a:a[0]}async function Tr(t,e,r,s,i){if(e.cascade.update!==fe.CASCADE)return;if(!i)throw new P("No way to compare old model. do you have updateValidation and mergeModels enabled?");function n(t){return Array.isArray(t)?t.map(n):"object"!=typeof t?t:t[h.pk(t)]}const o=n(s[r]),a=n(i[r]);if(void 0===a||y(o,a))return;if(Array.isArray(o)!==Array.isArray(a))throw new P("Cannot cascade update for different array types");const c=(Array.isArray(o)?o:[o]).filter(Boolean),l=(Array.isArray(a)?a:[a]).filter(Boolean).filter(t=>!c.includes(t)),u=Dr(s,r,this.adapter.alias);if(!u)throw new P("Could not find repo");try{const e=await u.override(this._overrides).deleteAll(l,t);t.logger.debug(`Deleted ${e.length} entries from table ${h.tableName(u.class)} due to cascade rules with `)}catch(t){throw new P("Error deleting cascade entries: "+t)}}const Nr=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Dr(e,r,s){if(!e)throw Error("No model was provided to get repository");let i,n=e instanceof h?e.constructor:e;if(Array.isArray(e[r])||e[r]instanceof Set){const e=t.get(n,t.key(w.REFLECT,r,w.LIST))?.clazz;if(!e)throw new P("Failed to find types decorators for property "+r);i=(Array.isArray(e)?[...e]:[e]).map(t=>"function"!=typeof t||t.name?t:t())}else i=h.relations(n).includes(r)?t.allowedTypes(n,r):t.getPropDesignTypes(e instanceof h?e.constructor:e,r)?.designTypes;n=i?.find(t=>!Nr.includes((""+t.name).toLowerCase()));const o=Ue.forModel(n,s);if(n!==o.class)throw new P("Invalid repository class for "+r);return o}class Ir extends W{constructor(t,e=Ir.name,r=401){super(t,e,r)}}class _r extends Ir{constructor(t,e=_r.name){super(t,e,403)}}class Br extends P{constructor(t){super(t,Br.name,503)}}function Pr(r){return e.for(Tt.TABLE).define({decorator:e=>r=>(t.set(Tt.TABLE,e||r.name.toLowerCase(),r),c(Tt.TABLE,e||r.name.toLowerCase())(r)),args:[r]}).apply()}function Rr(r){return e.for(Tt.COLUMN).define({decorator:e=>(r,s)=>n(t.key(Tt.COLUMN,s),e||s)(r,s),args:[r]}).apply()}async function $r(t,e,r,s){if(!s[r])return;const i=await this.select().where(pe.attribute(r).eq(s[r])).execute(),n=h.pk(s),o=s[n];if(i.filter(t=>t[n]!==o).length)throw new X(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Fr(){const t=Tt.UNIQUE;return e.for(t).define(b(),J($r),n(t,{})).apply()}async function Lr(t,e,r,s){throw new Ir("This adapter does not support user identification")}function Mr(){return e.for(Tt.CREATED_BY).define({decorator:()=>(t,e)=>s(H(Lr),n(Tt.CREATED_BY,e),q(Tt.CREATED_BY))(t,e),args:[]}).apply()}function jr(){return e.for(Tt.UPDATED_BY).define({decorator:()=>(t,e)=>s(V(Lr),n(Tt.UPDATED_BY,e),q(Tt.UPDATED_BY))(t,e),args:[]}).apply()}function Ur(){return Q([I.CREATE])}function Gr(){return Q()}async function Yr(t,e,r,s){if("??sequence"===h.tableName(s))return;const i=h.pk(s,!0);if(null==i)throw new P("Cannot generate persistent version without an id for "+s.constructor.name);const n={name:h.sequenceName(s,i+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},o=await this.adapter.Sequence(n,this._overrides),a=void 0!==s[r]&&null!==s[r],c=!!t.get("allowGenerationOverride")&&a;if(a&&(await o.ensureAtLeast(s[r],t),c))return;const l=await o.next(t);s[r]=l}async function zr(t,e,r,s,i){if("??sequence"===h.tableName(s))return;if(t.get("applyUpdateValidation")&&i&&s[r]!==i[r])throw new R(`Version mismatch: ${s[r]} !== ${i[r]}`);const n=h.pk(s,!0);if(null==n)throw new P("Cannot generate persistent version without an id for "+s.constructor.name);const o={name:h.sequenceName(s,n+"",r+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},a=await this.adapter.Sequence(o,this._overrides),c=void 0!==s[r]&&null!==s[r],l=!!t.get("allowGenerationOverride")&&c;if(c&&(await a.ensureAtLeast(s[r],t),l))return;const u=await a.next(t);s[r]=u}function Hr(){const r=Tt.PERSISTENT_VERSION;return(s,i)=>e.for(r).define(l(),n(t.key(r,i),!0),q(r),v(Number),H(Yr,{},{priority:70}),V(zr,{},{priority:70})).apply()(s,i)}function qr(t=!1){return t?Hr():Z()}function Vr(e){return[()=>{const r="function"==typeof e&&e.name?e:e(),s=h.pk(r);return(t.allowedTypes(r,s)||[])[0]}]}function Wr(t,r=ye,i=!0,n,o){const a=Tt.ONE_TO_ONE;return e.for(a).define({decorator:(t,e,r,i,n)=>{const o={class:t,cascade:e,populate:r};i&&(o.joinTable=i),n&&(o.name=n);const c=Vr(t),u=[l(),rs(a,o),v([t,...c]),H(lr,o,{priority:70}),V(ur,o,{priority:70}),et(dr,o,{priority:70}),V(Tr,o,{priority:80}),tt(kr,o,{priority:70})];return s(...u)},args:[t,r,i,n,o]}).apply()}function Qr(t,r=ye,i=!0,n,o){const a=Tt.ONE_TO_MANY;return e.for(a).define({decorator:(t,e,r,i,n)=>{const o={class:t,cascade:e,populate:r};i&&(o.joinTable=i),n&&(o.name=n);const c=Vr(t),u=[l(),rs(a,o),A([t,...c]),H(hr,o,{priority:70}),V(pr,o,{priority:70}),et(gr,o,{priority:70}),V(Tr,o,{priority:80}),tt(kr,o,{priority:70})];return s(...u)},args:[t,r,i,n,o]}).apply()}function Jr(t,r=ye,i=!0,n,o){const a=Tt.MANY_TO_ONE;return e.for(a).define({decorator:(t,e,r,i,n)=>{const o={class:t,cascade:e,populate:r};i&&(o.joinTable=i),n&&(o.name=n);const c=Vr(t),u=[l(),rs(a,o),v([t,...c]),H(fr,o),V(mr,o),et(wr,o),tt(kr,o)];return s(...u)},args:[t,r,i,n,o]}).apply()}function Xr(t,r=ye,i=!0,n,o){const a=Tt.MANY_TO_MANY;return e.for(a).define({decorator:(t,e,r,i,n)=>{const o={class:t,cascade:e,populate:r};i&&(o.joinTable=i),n&&(o.name=n);const c=Vr(t),u=[l(),rs(a,o),A([t,...c]),H(vr,o),V(pr,o),tt(kr,o)];return s(...u)},args:[t,r,i,n,o]}).apply()}function Kr(...e){return(r,i)=>{const n=t.get(r,t.key(Tt.NO_VALIDATE,i))||[],o=[...new Set([...n,...e])];return s(c(t.key(Tt.NO_VALIDATE,i),o))(r,i)}}function Zr(){return Kr(I.CREATE)}function ts(){return Kr(I.UPDATE)}function es(){return Kr(I.UPDATE,I.CREATE)}function rs(r,s){return e.for(Tt.RELATIONS).define({decorator:(e,r)=>(s,i)=>(n(e,r)(s,i),n(t.key(Tt.RELATIONS,i),Object.assign({},r,{key:e}))(s,i)),args:[r,s]}).apply()}class ss extends h{constructor(t){super(t)}}ct([Ur(),lt("design:type",Date)],ss.prototype,"createdAt",void 0),ct([Gr(),lt("design:type",Date)],ss.prototype,"updatedAt",void 0);let is=class extends ss{constructor(t){super(t)}};ct([or({type:String,generated:!1}),lt("design:type",String)],is.prototype,"id",void 0),ct([g(),Ze(),lt("design:type",Object)],is.prototype,"current",void 0),is=ct([Pr("??sequence"),m(),lt("design:paramtypes",[Object])],is);class ns extends dt{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,Qt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Ct.FIND_BY}|${Ct.FIND_BY_PAGINATE}|${Ct.LIST_BY}|${Ct.PAGE_BY}|${Ct.FIND}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Ct.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 $t?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof $t||(this._bookmark=e);const n=Ue.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o;if(a===Ct.FIND){const e=[Ct.PAGE,...c],r={limit:this.size,offset:t,bookmark:this._bookmark};e.push(r);const s=await n.statement(...e,...i);return this.apply(s)}let u;if(a===Ct.FIND_BY?u=Ct.FIND_BY_PAGINATE:a.startsWith(Ct.FIND_BY)?u=a.replace(Ct.FIND_BY,Ct.PAGE_BY):a===Ct.LIST_BY?u=Ct.PAGE_BY:a!==Ct.PAGE_BY&&a!==Ct.FIND_BY_PAGINATE||(u=a),!u)throw new jt(`Method ${a} is not supported for pagination`);const d=[u,...c];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==Ct.PAGE_BY||d.length>2?h={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:d.push(l.direction),d.push(h);const p=await n.statement(...d,...i);return this.apply(p)}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 he("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new he(`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 jt("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 rt(t)}}apply(t){const e="string"==typeof t?ns.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total||this._totalPages,this._recordCount=e.count||this._recordCount,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new rt(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 os,as,cs,ls,us,ds,hs;class ps extends Ft{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach(t=>{st(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?Ct.PAGE_BY:Tt.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(ps)}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 de("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 de("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 de("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new de("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 de("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===ge.ASC)return ge.ASC;if(e===ge.DSC)return ge.DSC;throw new de(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ge).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new de("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=t=>this.processRecord(t,r);if(this.groupBySelectors?.length){const e=this.revertGroupedResults(n,t);return await this.applyAfterHandlersToResult(e,r)}if(Array.isArray(n)){const e=n.map(t);return await this.applyAfterHandlersToResult(e,r)}const e=t(n);return await this.applyAfterHandlersToResult(e,r)}return n}catch(t){throw new de(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=Ue.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 jt("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=t=>this.processRecord(t,r);if(Array.isArray(i)){const t=i.map(n);return await this.applyAfterHandlersToResult(t,r)}const o=n(i);return await this.applyAfterHandlersToResult(o,r)}processRecord(t,e){const r=t[h.pk(this.fromSelector)];return this.adapter.revert(t,this.fromSelector,r,void 0,e)}async applyAfterHandlersToResult(t,e){return e.getOrUndefined("afterQueryHandlers")?t instanceof h?(await j(this.getRepository(),e,t,I.READ,I.AFTER),t):Array.isArray(t)?(await Promise.all(t.map(t=>this.applyAfterHandlersToResult(t,e))),t):t&&"object"==typeof t?(await Promise.all(Object.entries(t).map(([r,s])=>this.applyAfterHandlersToResult(s,e).then(e=>{t[r]=e}))),t):t:t}getRepository(){return Ue.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case Ot.AND:case Ot.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 pe){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case Et.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case Et.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case Et.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case Et.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case Et.BIGGER_EQ:n.method=r+" bigger than equal";break;case Et.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case Et.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case Et.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new de("Unsupported operator "+s)}return n}squash(t){const e=this.matchDefaultQueryCondition();if(e){const t=this.getOrderDirection();return{class:this.fromSelector,method:Ct.FIND,args:[e.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof pe)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Ct.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Ct.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Ct.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Ct.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Ct.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Ct.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Ct.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let r;this.whereCondition&&(r=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,ge.DSC]:[h.pk(this.fromSelector),ge.DSC],[i,n]=s,o={direction:n};this.limitSelector&&(o.limit=this.limitSelector),this.offsetSelector&&(o.offset=this.offsetSelector);const a={class:this.fromSelector,method:Ct.LIST_BY,args:[i],params:o};return r&&(a.method=Ct.FIND_BY,a.args=[r,this.whereCondition.comparison],a.params=o),a}matchDefaultQueryCondition(){if(!this.whereCondition)return;const t=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!t)return;const e=h.defaultQueryAttributes(this.fromSelector);if(!e||!e.length)return;const r=Array.from(new Set(e.map(String))),s=Array.from(new Set(t.attributes.map(String)));return r.length===s.length&&r.every(t=>s.includes(t))?{value:t.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(t){const e=this.collectStartsWithAttributes(t);if(e)return{attributes:Array.from(new Set(e.attributes)),value:e.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:e,operator:r,comparison:s}=t;if(r===Et.STARTS_WITH){if("string"!=typeof e||"string"!=typeof s)return;return{attributes:[e],value:s}}if(r===Ot.OR){const t=e instanceof pe?this.collectStartsWithAttributes(e):void 0,r=s instanceof pe?this.collectStartsWithAttributes(s):void 0;return t&&r&&t.value===r.value?{attributes:[...t.attributes,...r.attributes],value:t.value}:void 0}return r===Ot.AND?(e instanceof pe?this.collectStartsWithAttributes(e):void 0)||(s instanceof pe?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??ge.ASC}async prepare(t){if(t=t||await this.adapter.context(Tt.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r};let i,n=xt.FIND_BY;void 0!==this.countSelector?(n=xt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=xt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=xt.AVG_BY,i=this.avgSelector):this.minSelector?(n=xt.MIN_BY,i=this.minSelector):this.maxSelector?(n=xt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=xt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=xt.GROUP_BY_PREFIX,i=this.groupBySelectors[0]);const o=[n];if(i&&o.push(i),this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);o.push(r.method),r.args&&r.args.length&&e.push(...r.args)}if(this.selectSelector&&o.push(xt.SELECT,this.selectSelector.join(` ${xt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;o.push(xt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map(([t,e])=>[t,e]),e.forEach(([t])=>{o.push(xt.THEN_BY,t)}))}if(this.groupBySelectors?.length&&n!==xt.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;o.push(xt.GROUP_BY,t),e.forEach(t=>o.push(xt.THEN_BY,t))}else this.groupBySelectors?.length&&n===xt.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>o.push(xt.THEN_BY,t));return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=pt(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 de(t)}}toString(){return this.adapter.flavour+" statement"}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Array]),lt("design:returntype",Object)],ps.prototype,"select",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(os="undefined"!=typeof S&&S)?os:Object]),lt("design:returntype",Object)],ps.prototype,"distinct",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(as="undefined"!=typeof S&&S)?as:Object]),lt("design:returntype",Object)],ps.prototype,"max",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(cs="undefined"!=typeof S&&S)?cs:Object]),lt("design:returntype",Object)],ps.prototype,"min",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(ls="undefined"!=typeof S&&S)?ls:Object]),lt("design:returntype",Object)],ps.prototype,"sum",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(us="undefined"!=typeof S&&S)?us:Object]),lt("design:returntype",Object)],ps.prototype,"avg",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(ds="undefined"!=typeof S&&S)?ds:Object]),lt("design:returntype",Object)],ps.prototype,"count",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",Object)],ps.prototype,"from",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[pe]),lt("design:returntype",Object)],ps.prototype,"where",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,String]),lt("design:returntype",Object)],ps.prototype,"orderBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,String]),lt("design:returntype",Object)],ps.prototype,"thenBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",["function"==typeof(hs="undefined"!=typeof Key&&Key)?hs:Object]),lt("design:returntype",Object)],ps.prototype,"groupBy",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Number]),lt("design:returntype",Object)],ps.prototype,"limit",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Number]),lt("design:returntype",Object)],ps.prototype,"offset",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[void 0]),lt("design:returntype",Promise)],ps.prototype,"execute",null);class gs extends Ft{constructor(){super(),this.observers=[],this.Context=$t}for(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof gs?n.for(t,...e):n instanceof Ue?n.override(t):n}})}override(t,...e){return new Proxy(this,{get(r,s,i){const n=Reflect.get(r,s,i);return"object"!=typeof n?n:n instanceof gs?n.override(t,...e):n instanceof Ue?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Mt,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 P("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 P("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}-${Jt.instance.generate()}`;const s=e.logger||ut.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Nt,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 $t||(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 Ft.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new P("No name provided");const e=Yt(t),r=vt.get(e);if(r)return r;throw new P("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let e=t.pop();void 0===e||e instanceof $t||(t.push(e),e=void 0);const r=await gs.prototype.flags(Tt.INITIALIZATION,{},...t);e=e?new $t(e).accumulate({...r,parentContext:e}):(new $t).accumulate(r),t=[...t,e];const{log:s,ctxArgs:i}=gs.prototype.logCtx(t,this.boot),n=vt.services();if(!n||!Object.keys(n).length)throw new P("No services registered for shutdown");for(const[t,e]of Object.entries(n))try{s.verbose(`Booting ${e.name} service...`);const r=vt.get(e);if(!r)throw new P("Failed to resolve injectable for "+t);r instanceof fs&&(s.verbose(`Initializing ${e.name} service...`),await r.boot(...i))}catch(t){throw new P(`Failed to boot ${e.name} service:${t}`)}}static async shutdown(...t){let e=t.pop();void 0===e||e instanceof $t||(t.push(e),e=void 0);const r=await gs.prototype.flags(Tt.SHUTDOWN,{},...t);e=e?new $t(e).accumulate({...r,parentContext:e}):(new $t).accumulate(r),t=[...t,e];const{log:s,ctxArgs:i}=gs.prototype.logCtx(t,this.shutdown),n=vt.services();if(!n||!Object.keys(n).length)throw new P("No services registered for shutdown");for(const[t,e]of Object.entries(n).reverse())try{s.verbose(`Shutting down ${e.name} service...`);const r=vt.get(e);if(!r)throw new P("Failed to resolve injectable for "+t);if(r instanceof fs){s.verbose(`Gracefully shutting down ${e.name} service...`);try{await r.shutdown(...i)}catch(t){s.error(`Failed to gracefully shutdown ${e.name} service`,t)}}}catch(e){throw new P(`Failed to Shutdown services ${t}: ${e}`)}}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object,Function]),lt("design:returntype",Function)],gs.prototype,"observe",null),ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",void 0)],gs.prototype,"unObserve",null);class fs extends gs{constructor(){super()}async boot(...t){const{config:e,client:r}=await this.initialize(...t);this._config=e,this._client=r;const{log:s}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new P("Config not initialized");return this._config}get client(){if(!this._client)throw new P("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function ys(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Vt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}ct([ht(),lt("design:type",Function),lt("design:paramtypes",[Object]),lt("design:returntype",Promise)],fs.prototype,"boot",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],fs.prototype,"config",null),ct([ht(),lt("design:type",Object),lt("design:paramtypes",[])],fs.prototype,"client",null);const ms=()=>ys(I.CREATE),ws=()=>ys(I.READ),vs=()=>ys(I.UPDATE),bs=()=>ys(I.DELETE);function As(e){return(r,i,n)=>{n||i?(l()(r,i),e=e||t.type(r.constructor,i)):e=e||r,e=Yt(e);const o=[];if(n&&"number"==typeof n.value)o.push(At(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(At(e))}else t.set(Tt.SERVICE,e,r),o.push(St(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return s(...o)(r,i,n)}}function Ss(t){const r=Tt.AUTH;return e.for(r).define({decorator:t=>c(r,t),args:[t]}).apply()}const xs=t=>c(Tt.AUTH_ROLE,t);function Es(r,n){const o=Tt.DECAF_ROUTE;return e.for(o).define({decorator:()=>(e,a,c)=>{const l={path:n,httpMethod:r,handler:c};return s(i(t.key(o,a),l))(e,a,c)},args:[]}).apply()}const Os=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Cs extends gs{get class(){if(!this.clazz)throw new P("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ue.forModel(this.clazz)),this._repository}constructor(t){super(),this.clazz=t}static getService(t){if(!t)throw new P("No name provided");const e=Os(t);try{const t=gs.get(e);if(t)return t}catch(t){}throw new P("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new P(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}select(t){return this.repo.select(t)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.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,Ct.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,Ct.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,Ct.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async findByPaginate(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,e,r,...i)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=Os(e||t);try{r=Cs.get(e)}catch(t){r=void 0}if(r instanceof Cs)return r;const s=this;let i=class extends s{constructor(){super(t)}};return i=ct([As(e),lt("design:paramtypes",[])],i),new i}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)}}ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"create",null),ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"createAll",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"delete",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"deleteAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"read",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],Cs.prototype,"readAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[String,Object]),lt("design:returntype",Promise)],Cs.prototype,"query",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],Cs.prototype,"update",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Array,Object]),lt("design:returntype",Promise)],Cs.prototype,"updateAll",null);class ks extends Ft{isSameObservedAdapter(t){if(!this.adapter)return!1;if(this.adapter===t)return!0;const e=this.adapter,r=t;return r instanceof se&&e.alias===r.alias&&e.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(t,e,r=!1){if(!this.adapter)throw new P("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");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:e}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const r=this.adapter;[I.CREATE,I.UPDATE,I.DELETE,_.CREATE_ALL,_.UPDATE_ALL,_.DELETE_ALL].forEach(t=>{if(!r[t])throw new P(`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 _.CREATE_ALL:return I.CREATE;case _.UPDATE_ALL:return I.UPDATE;case _.DELETE_ALL:return I.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...o),h=[c,i(t),l];return a.get("observeFullResult")&&h.push(Array.isArray(d)?d.map(t=>c(t)):c(d)),this.updateObservers(...h,...o).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(...t){}observe(t){if(!(t instanceof se))throw new jt("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(t))return()=>this.unObserve(t);throw new jt("Dispatch is already observing another adapter")}return this.adapter=t,this.models=se.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t)}unObserve(t){if(!this.isSameObservedAdapter(t))throw new jt("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 P("Model must be provided for observer update");const i=t&&"string"==typeof t?t:h.tableName(t);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`);const{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);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 P("Failed to refresh dispatch: "+t)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ts(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 Jt.instance.generate(i)}function Ns(t=!1,r,...i){"function"==typeof t&&(r=t,t=!1);const n=Tt.UUID;return e.for(n).define({decorator:(t,e,...r)=>{const i={update:t,seed:e,args:r},n=[g(),q(Tt.UUID),H(Ts,i,{priority:54})];return t&&n.push(V(Ts,i,{priority:54})),t||n.push(z()),s(...n)},args:[t,r,...i]}).apply()}se&&(se._baseDispatch=ks);class Ds extends Ft{static{this.lock=new mt}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Ue.forModel(is,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,I.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 G){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new P("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new P(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new P(`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 P("Sequence name is required");return Ds.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new P("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 is({id:o,current:t}),s)}catch(e){if(e instanceof G)return r.debug(`Sequence create ${o} current=${c} next=${t}`),this.repo.create(new is({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(Jt.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 X)continue;throw t}}const u=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(Xt.instance.generate(t));default:throw new P("Should never happen")}})(c),d=await l(u);return r.debug(`Sequence.increment ${o} current=${c} next=${u}`),d.current},o)}async next(...t){const{ctx:e}=(await this.logCtx(t,I.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,I.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new jt(`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 a=[];for(let e=0;t-1>=e;e++)a.push(o-n*this.parse(e));if(a=a.reverse(),a[a.length-1]!==o&&"String"!==i)throw new P("Miscalculation of range");return s.debug("Calculated range: "+a.join(", ")),a}async ensureAtLeast(t,...e){const{ctx:r}=(await this.logCtx(e,I.UPDATE,!0)).for(this.ensureAtLeast),{name:s}=this.options;if(!s)throw new P("Sequence name is required");const i=this.parse(t),n=(t,e)=>"bigint"==typeof t||"bigint"==typeof e?BigInt(t)>BigInt(e):"number"==typeof t||"number"==typeof e?Number(t)>Number(e):t+"">e+"";return Ds.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(s,r)}catch(t){if(t instanceof G)return;throw t}};for(;;)try{const e=await t();if(!e)return await this.repo.create(new is({id:s,current:i}),r),i;const o=this.parse(e.current);return n(i,o)?(await this.repo.update(new is({id:s,current:i}),r),i):o}catch(t){if(t instanceof X)continue;throw t}},s)}parse(t){return Ds.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([is,...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 jt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Is(t,...e){let r;if(t instanceof Cs&&(r=t.repo.adapter),t instanceof Ue&&(r=t.adapter),t instanceof se&&(r=t),!r)throw new P("Could not find adapter to extract transaction");return r.transactionLock(...e)}function _s(...e){return(r,s,i)=>{if(!i)throw new P("This decorator only applies to methods");return u()(r,s,i),t.set(r.constructor,t.key(wt.TRANSACTIONAL,s),{data:e}),i.value=new Proxy(i.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock"),o=n||Is(e);let a;o.depth++,n||(await o.begin(i),i.cache.put("transactionLock",o));try{a=await t.call(e,...r,i)}catch(t){const e=0===o.depth;if(o.depth=0,!e)try{await o.rollback(t,i)}catch(t){s.error("Failed to rollback transaction",t)}throw t}if(o.depth--,0===o.depth)try{await o.commit(i)}catch(t){throw new P("Failed to commit transaction: "+t)}return a}}),i}}function Bs(...t){return e.for(wt.TRANSACTIONAL).define({decorator:_s,args:t}).apply()}se._baseSequence=Ds;class Ps extends fs{constructor(){super()}for(t,...e){throw new jt("Persistence service cannot be overridden")}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof $t||!e.every(t=>Array.isArray(t)))throw new P("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,Tt.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 P(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new P(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Rs=class extends h{constructor(t){super(t),this.strategy=ne.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=oe.FULL}};ct([g(),v(String),x(ne),d("the backoff strategy"),lt("design:type",String)],Rs.prototype,"strategy",void 0),ct([g(),d("base interval between attempts"),lt("design:type",Number)],Rs.prototype,"baseMs",void 0),ct([g(),d("max interval"),lt("design:type",Number)],Rs.prototype,"maxMs",void 0),ct([v(String),x(oe),d("optional jitter strategy"),lt("design:type",String)],Rs.prototype,"jitter",void 0),Rs=ct([m(),lt("design:paramtypes",[Object])],Rs);let $s=class extends h{constructor(t){super(t)}};ct([g(),d("The error message"),lt("design:type",String)],$s.prototype,"message",void 0),ct([l(),d("The error stack"),lt("design:type",String)],$s.prototype,"stack",void 0),ct([l(),d("The error code"),lt("design:type",String)],$s.prototype,"code",void 0),ct([l(),d("The error details"),lt("design:type",Object)],$s.prototype,"details",void 0),$s=ct([m(),lt("design:paramtypes",[Object])],$s);let Fs=class extends h{constructor(t){if(super(t),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}};ct([or(),it(["taskId","classification","uuid"],":"),lt("design:type",String)],Fs.prototype,"id",void 0),ct([Rr(),z(),g(),nt(),Ns(!1),lt("design:type",String)],Fs.prototype,"uuid",void 0),ct([Rr(),z(),g(),Ze([ge.ASC,ge.DSC]),lt("design:type",String)],Fs.prototype,"taskId",void 0),ct([E(),Rr(),g(),Ze([ge.ASC,ge.DSC]),lt("design:type",Date)],Fs.prototype,"ts",void 0),ct([Rr(),z(),g(),x(ae),Ze([ge.ASC,ge.DSC]),lt("design:type",String)],Fs.prototype,"classification",void 0),ct([l(),Rr(),ot(),z(),lt("design:type",Object)],Fs.prototype,"payload",void 0),Fs=ct([Pr("task_event"),m(),lt("design:paramtypes",[Object])],Fs);class Ls extends O{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 pe){const r=this.serializePlain(t,...e);return r[C.ANCHOR]="??condition",r}return h.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[C.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(e){try{return t.modelName(e)}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[C.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?pe.from(r):h.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==C.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Ms=class extends h{constructor(t){super(t),this.ts=new Date}};ct([E(),g(),lt("design:type",Date)],Ms.prototype,"ts",void 0),ct([g(),x(gt),lt("design:type",String)],Ms.prototype,"level",void 0),ct([k(0),lt("design:type",Number)],Ms.prototype,"step",void 0),ct([g(),l(),lt("design:type",String)],Ms.prototype,"msg",void 0),ct([l(),lt("design:type",Object)],Ms.prototype,"meta",void 0),Ms=ct([m(),lt("design:paramtypes",[Object])],Ms);let js=class extends h{constructor(t){super(t),this.atomicity=ce.ATOMIC,this.status=ie.PENDING,this.attempt=0,this.logTail=[]}};ct([or(),Ns(),d("the task id"),lt("design:type",String)],js.prototype,"id",void 0),ct([Rr(),g(),v(String),x(ce),Ze([ge.ASC,ge.DSC]),d("defines a single or composite task"),lt("design:type",String)],js.prototype,"atomicity",void 0),ct([Rr(),g(),Ze([ge.ASC,ge.DSC]),d("Holds task classification - must match @task()"),lt("design:type",String)],js.prototype,"classification",void 0),ct([Rr(),l(),Ze([ge.ASC,ge.DSC]),d("optional task name for ambiguity"),lt("design:type",String)],js.prototype,"name",void 0),ct([Rr(),l(),d("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),lt("design:type",String)],js.prototype,"lock",void 0),ct([Rr(),g(),v(String),x(ie),Ze([ge.ASC,ge.DSC]),Ze([ge.ASC,ge.DSC],["nextRunAt"]),Ze([ge.ASC,ge.DSC],["leaseExpiry"]),Ze([ge.ASC,ge.DSC],["scheduledTo"]),d("Holds the task current status"),lt("design:type",String)],js.prototype,"status",void 0),ct([l(),Rr(),ot(Ls),d("Holds task input"),lt("design:type",Object)],js.prototype,"input",void 0),ct([l(),Rr(),ot(Ls),d("Holds the task output when successfully completed"),lt("design:type",Object)],js.prototype,"output",void 0),ct([l(),Rr(),ot(),d("Holds the error for failed tasks"),lt("design:type",$s)],js.prototype,"error",void 0),ct([Rr(),g(),k(0),Ze([ge.ASC,ge.DSC]),d("Holds the current attempt"),lt("design:type",Number)],js.prototype,"attempt",void 0),ct([Rr(),k(1),g(),d("max attempts for the task"),lt("design:type",Number)],js.prototype,"maxAttempts",void 0),ct([Rr(),g(),ot(),d("backoff configuration"),lt("design:type",Rs)],js.prototype,"backoff",void 0),ct([E(),Rr(),d("Next execution timestamp"),lt("design:type",Date)],js.prototype,"nextRunAt",void 0),ct([E(),Rr(),d("Task scheduled timestamp"),lt("design:type",Date)],js.prototype,"scheduledTo",void 0),ct([Rr(),ot(),d("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),lt("design:type",Array)],js.prototype,"dependencies",void 0),ct([l(),Rr(),d("Task lease owner identifier"),lt("design:type",String)],js.prototype,"leaseOwner",void 0),ct([E(),Rr(),d("Task lease expiration timestamp"),lt("design:type",Date)],js.prototype,"leaseExpiry",void 0),ct([l(),Rr(),ot(),d("Holds the various steps definition and inputs - only for type === 'composite'"),lt("design:type",Array)],js.prototype,"steps",void 0),ct([l(),Rr(),k(0),Ze([ge.ASC,ge.DSC]),d("Holds the current step - only for type === 'composite'"),lt("design:type",Number)],js.prototype,"currentStep",void 0),ct([l(),Rr(),ot(),d("Holds the step results - only for type === 'composite'"),lt("design:type",Array)],js.prototype,"stepResults",void 0),ct([l(),Rr(),ot(),d("Holds the task log entries"),lt("design:type",Array)],js.prototype,"logTail",void 0),ct([Rr(),Ur(),Ze([ge.ASC,ge.DSC]),d("timestamp of creation"),lt("design:type",Date)],js.prototype,"createdAt",void 0),ct([Rr(),Gr(),Ze([ge.ASC,ge.DSC]),d("timestamp of last update"),lt("design:type",Date)],js.prototype,"updatedAt",void 0),ct([Rr(),Mr(),Ze([ge.ASC,ge.DSC]),d("Holds the creator of the task"),lt("design:type",String)],js.prototype,"createdBy",void 0),ct([Rr(),jr(),Ze([ge.ASC,ge.DSC]),d("Holds the creator of the task"),lt("design:type",String)],js.prototype,"updatedBy",void 0),js=ct([d("Holds the current step when applicable"),Pr("tasks"),m(),lt("design:paramtypes",[Object])],js);let Us=class extends h{constructor(t){super(t)}};ct([g(),d("The status of a step"),lt("design:type",String)],Us.prototype,"status",void 0),ct([l(),d("The result of a successful step"),lt("design:type",Object)],Us.prototype,"output",void 0),ct([l(),d("the error of a failed step"),lt("design:type",$s)],Us.prototype,"error",void 0),ct([l(),k(1),d("Number of attempts taken to complete or fail this step"),lt("design:type",Number)],Us.prototype,"attempt",void 0),Us=ct([m(),lt("design:paramtypes",[Object])],Us);let Gs=class extends h{constructor(t){super(t),this.allowConcurrent=!1,this.canFail=!1}};ct([g(),d("task handler type"),lt("design:type",String)],Gs.prototype,"classification",void 0),ct([T(1),d("optional task name for ambiguity"),lt("design:type",String)],Gs.prototype,"name",void 0),ct([d("optional task step input"),l(),lt("design:type",Object)],Gs.prototype,"input",void 0),ct([d("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),l(),lt("design:type",String)],Gs.prototype,"lock",void 0),ct([l(),d("When true, compatible steps that share the same lock may run concurrently"),lt("design:type",Boolean)],Gs.prototype,"allowConcurrent",void 0),ct([d("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),l(),A(()=>String),lt("design:type",Array)],Gs.prototype,"dependsOn",void 0),ct([l(),d("Whether a failing step may be tolerated so the composite can continue"),lt("design:type",Boolean)],Gs.prototype,"canFail",void 0),ct([l(),k(1),d("Max attempts for this step. Defaults to 1 (no per-step retry)."),lt("design:type",Number)],Gs.prototype,"maxAttempts",void 0),ct([l(),ot(),d("Step-level backoff config. Falls back to the parent task backoff when absent."),lt("design:type",Rs)],Gs.prototype,"backoff",void 0),Gs=ct([m(),lt("design:paramtypes",[Object])],Gs);class Ys extends h{constructor(t){super(t),this.baseMs=1e3,this.jitter=oe.FULL,this.maxMs=6e4,this.strategy=ne.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 R(t);return new Rs(this)}}ct([g(),k(1e3),lt("design:type",Number)],Ys.prototype,"baseMs",void 0),ct([g(),x(oe),lt("design:type",String)],Ys.prototype,"jitter",void 0),ct([N("baseMs"),k(1e3),g(),lt("design:type",Number)],Ys.prototype,"maxMs",void 0),ct([g(),x(ne),lt("design:type",String)],Ys.prototype,"strategy",void 0);class zs extends h{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 Ys,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}setLock(t){return this.lock=t,this}setDependencies(t){return this.dependencies=t,this}setDependsOn(t){return this.setDependencies(t)}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=ie.PENDING,this.atomicity=ce.ATOMIC,this.backoff=new Rs,this.maxAttempts=1,h.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new R(t);return new js(this)}}ct([g(),lt("design:type",String)],zs.prototype,"classification",void 0),ct([l(),lt("design:type",String)],zs.prototype,"name",void 0),ct([g(),lt("design:type",String)],zs.prototype,"status",void 0),ct([g(),lt("design:type",String)],zs.prototype,"atomicity",void 0),ct([g(),lt("design:type",Rs)],zs.prototype,"backoff",void 0),ct([l(),lt("design:type",Object)],zs.prototype,"input",void 0),ct([l(),lt("design:type",String)],zs.prototype,"lock",void 0),ct([l(),A(()=>String),lt("design:type",Array)],zs.prototype,"dependencies",void 0),ct([k(1),g(),lt("design:type",Number)],zs.prototype,"maxAttempts",void 0);class Hs{constructor(t,e){this.parent=t,this.step=e}setClassification(t){return this.step.classification=t,this}setName(t){return this.step.name=t,this}setInput(t){return this.step.input=t,this}setLock(t){return this.step.lock=t,this}setAllowConcurrent(t=!1){return this.step.allowConcurrent=t,this}setDependsOn(t){return this.step.dependsOn=t,this}setCanFail(t){return this.step.canFail=t,this}setMaxAttempts(t){return this.step.maxAttempts=t,this}setBackoff(t){return this.step.backoff=t,this}addStep(t,e,r,s){return 4>arguments.length?this.parent.addStep(t,e,r):this.parent.addStep(t,e,r,s)}setSteps(t){return this.parent.setSteps(t)}build(){return this.parent}}class qs extends zs{constructor(t){super(t),this.stepResults=[],h.fromModel(this,t),this.atomicity=ce.COMPOSITE}setAtomicity(t){throw new P("Atomicity locked to "+ce.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof Gs?t:new Gs(t)),this}addStep(t,e,r){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,o=arguments.length>=4,a=new Gs({classification:t,name:n&&"string"==typeof e?e:void 0,input:o||n&&"string"==typeof e?r:i?void 0:e,canFail:o?!!arguments[3]:!(!n||"string"==typeof e||!r),createdAt:s,updatedAt:s});return this.steps.push(a),i?new Hs(this,a):this}}ct([A(()=>Gs),lt("design:type",Array)],qs.prototype,"steps",void 0);class Vs extends Lt{get type(){if(!this._type){const e=t.get(this.constructor,le);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new P("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),L(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}async catch(t,e,r){}}function Ws(r){return e.for(le).define({decorator:e=>r=>{const s={type:e};return t.set(le,e,r),c(le,s)(r)},args:[r]}).apply()}let Qs=class extends Vs{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof pe)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=pe.attr("status").eq(ie.SUCCEEDED).and(pe.attr("updatedAt").lte(t.successfulExpiry)),i=pe.attr("status").eq(ie.FAILED).and(pe.attr("updatedAt").lte(t.failedExpiry)),n=pe.attr("status").eq(ie.CANCELED).and(pe.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}}};ct([ze(js),lt("design:type",Object)],Qs.prototype,"tasks",void 0),Qs=ct([Ws("cleanup-task"),lt("design:paramtypes",[])],Qs);class Js{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(gt).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)}fatal(t,e,r){this.logger.fatal(t,e,r)}critical(t,e,r){this.logger.critical(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Xs(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1}),r.classification){case ae.LOG:{const s=r.payload.map(t=>Array.isArray(t)?t:[t.level,t.msg,t.meta]);for(let[r,i,n]of s){e.style||(i=ft(i),i=i.clear().toString());const s=[i];r===gt.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case ae.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case ae.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=ft(e);switch(e){case ie.SUCCEEDED:s=s.green.bold;break;case ie.RUNNING:s=s.blue.bold;break;case ie.PENDING:s=s.yellow;break;case ie.WAITING_RETRY:s=s.yellow.bold;break;case ie.FAILED:s=s.red.bold;break;case ie.CANCELED:s=s.magenta.bold;break;case ie.SCHEDULED:s=s.cyan;break;default:t.warn("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;case ae.UPDATE:if(e.logProgress){const{currentStep:e,totalSteps:s,output:i}=r.payload??{},n=i?.added,o=i?.insertionIndex,a=null!=n?` (+${n} at index ${o})`:"";t.info(`### UPDATE step ${e}/${s}${a}`)}break;default:t.warn("Unhandled task event classification: "+r.classification)}}}function Ks(t,e){const r=e.strategy===ne.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 Zs(t){return new $s({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function ti(t){return new Promise(e=>setTimeout(e,t))}class ei extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=ei.name,Object.setPrototypeOf(this,ei.prototype)}}class ri extends $t{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(t){this.cache.put("step",t)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}get stepWriteLock(){return this.get("stepWriteLock")}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 ei({status:t,...e})}cancel(t,e){this.changeState(ie.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(ie.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(ie.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof $s?t:t instanceof Error?Zs(t):new $s({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const e=(t??[]).map(t=>t instanceof Gs?t:new Gs(t));return{afterCurrent:async t=>{const r=this.getOrUndefined("scheduleCompositeSteps");if(!r)throw new P("scheduleSteps().afterCurrent() is only available while running a composite task step");await r(e,t)},atEnd:async t=>{const r=this.getOrUndefined("scheduleCompositeStepsAtEnd");if(!r)throw new P("scheduleSteps().atEnd() is only available while running a composite task step");await r(e,t)}}}constructor(t){super(t)}}class si{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=t.tasks();e&&Object.entries(e).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new P(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new P("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class ii extends Mt{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(Fs,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=se.logCtx(this.updateObservers,void 0,!1,...i);(await Promise.allSettled(this.observers.filter(s=>{const{filter:i}=s;if(!i)return!0;try{return i(t,e,r,...o)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...o)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}function ni(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class oi extends at{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class ai extends oi{constructor(t,e,r){super(ai.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class ci extends oi{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(ci.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class li extends oi{constructor(t,e,r){super(li.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class ui extends oi{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(ui.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class di{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===Fs||t===h.tableName(Fs))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([ie.SUCCEEDED,ie.FAILED,ie.CANCELED,ie.SCHEDULED])}wait(){return this.awaitStatusTerminal([ie.SUCCEEDED,ie.FAILED,ie.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Xs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==ae.LOG)return;const r=(e.payload??[]).map(t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]);await t(r)},ae.LOG)}pipe(t,e=ae.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(ie.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(ie.FAILED,t)}onCancel(t){return this.registerStatusHandler(ie.CANCELED,t)}onUpdate(t){const e=async(e,r)=>{e.classification===ae.UPDATE&&await t(e,r)};return this.pipe(e,ae.UPDATE),()=>{this.pipes?.[ae.UPDATE]?.delete(e)}}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===ie.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[ie.SUCCEEDED,ie.CANCELED,ie.FAILED].includes(t)}async track(t,e){if(t.classification!==ae.STATUS)return;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!==ie.SUCCEEDED?(r===ie.FAILED&&this.fail(),r===ie.CANCELED&&this.cancel(t),r===ie.WAITING_RETRY&&this.retry(),r===ie.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,ae.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[ae.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new $t),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===ie.SUCCEEDED&&(e.output=this.task.output),t!==ie.FAILED&&t!==ie.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 Fs({classification:ae.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case ie.FAILED:return new ai(this.task.id,e,r);case ie.CANCELED:return new li(this.task.id,e,r);case ie.WAITING_RETRY:return new ci(this.task.id,e,r);case ie.SCHEDULED:return new ui(this.task.id,e,r);default:return new ai(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case ie.CANCELED:return ie.CANCELED;case ie.WAITING_RETRY:return ie.WAITING_RETRY;case ie.SCHEDULED:return ie.SCHEDULED;case ie.FAILED:return ie.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===ie.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[ae.ALL]?[...this.pipes[ae.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 hi extends Lt{get Context(){return ri}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,js,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,Fs,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(t,e){const r=new ri(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new yt,this.running=!1;const e=Object.assign({},ue.autoShutdown,t.autoShutdown);this.config=Object.assign({},ue,t,{autoShutdown:e,bus:t.bus||new ii,registry:t.registry||new si}),this.idleDelayMs=this.config.pollMsIdle}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,I.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 di(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=ie.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,I.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 di(this.bus,i)}}async ensureTaskError(t,e){if(![ie.FAILED,ie.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await ti(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===ie.SUCCEEDED||s.status===ie.FAILED)return s;s.status=ie.CANCELED;const i=new $s({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,ie.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.idleDelayMs=this.config.pollMsIdle,this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,Tt.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(pe.attr("status").eq(ie.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),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},s=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),i=r.backoffStepMs??0;for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map(t=>this.executeClaimed(t)));const n=0===t.length;if(n)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+i,s),this.idleDelayMs>=s)return e.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(e)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const o=n?this.idleDelayMs:this.config.pollMsBusy;await ti(Math.max(o,0))}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=pe.attribute("status").eq(ie.PENDING),i=pe.attribute("status").eq(ie.WAITING_RETRY).and(pe.attribute("nextRunAt").lte(r)),n=pe.attribute("status").eq(ie.RUNNING).and(pe.attribute("leaseExpiry").lte(r)),o=pe.attribute("status").eq(ie.SCHEDULED).and(pe.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{}if(!await this.isRunnable(i,e))return null;const n=new js({...i,status:ie.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}}isTaskFinished(t){return[ie.SUCCEEDED,ie.FAILED,ie.CANCELED].includes(t)}parseTaskDependency(t){const e=t?.trim();if(!e)return;const r=e.lastIndexOf(":");if(0>=r||r>=e.length-1)return{taskId:e};const s=e.slice(0,r).trim(),i=e.slice(r+1).trim();return s&&i?{taskId:s,stepRef:i}:{taskId:e}}normalizeDependencies(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e=[e]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.filter(t=>"string"==typeof t).map(t=>this.parseTaskDependency(t)).filter(Boolean):[]}resolveDependencyStepIndex(t,e){const r=e.trim();if(!r)return;const s=Number(r);if(Number.isInteger(s)&&s>=0)return s;const i=this.normalizeSteps(t.steps).findIndex(t=>t.name===r||t.classification===r);return 0>i?void 0:i}async areDependenciesSatisfied(t,e){if(!t.length)return!0;const r=Array.from(new Set(t.map(t=>t.taskId))),s=new Map;try{const t=await this.tasks.readAll(r,e);for(const e of t)e?.id&&s.set(e.id,e)}catch{return!1}for(const e of t)try{const t=s.get(e.taskId);if(!t)return!1;if(!e.stepRef){if(!this.isTaskFinished(t.status))return!1;continue}const r=this.resolveDependencyStepIndex(t,e.stepRef);if(null==r)return!1;const i=this.normalizeStepResults(t.stepResults)[r];if(!i||!this.isTaskFinished(i.status))return!1}catch{return!1}return!0}getStepLock(t,e){if(t.atomicity!==ce.COMPOSITE)return;const r=this.normalizeSteps(t.steps);if(!r.length)return;const s=r[e??0];return s?.lock}async hasLockConflict(t,e,r){const s=[t.lock,this.getStepLock(t,e)].filter(t=>!!t&&"string"==typeof t);if(!s.length)return!1;const i=await this.tasks.select().where(pe.attribute("status").eq(ie.RUNNING)).execute(r);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(t=>!!t&&"string"==typeof t).some(t=>s.includes(t)))return!0;return!1}async isRunnable(t,e){const r=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(r,e))return!1;const s=t.atomicity===ce.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,e)}getCompositeStepConcurrencyLimit(){const t=this.config.maxConcurrentCompositeSteps??-1;return 0===t?1:0>t?1/0:Math.max(1,t)}isConcurrentCompositeStep(t){return!(!t.allowConcurrent||!t.lock)}createCompositeStepContext(t,e){return hi.createTaskContext(t,{step:e})}async withStepWriteLock(t,e){const r=t.stepWriteLock;await r.acquire();try{return await e()}finally{r.release()}}recalculateCompositeCurrentStep(t,e){let r=0;for(;r<t.length;){const s=e[r];if(!s)break;if(s.status===ie.FAILED&&!t[r]?.canFail)break;r+=1}return r}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=this;let i=Promise.resolve();const n=new ri(e).accumulate({taskId:t.id,stepWriteLock:new yt,logger:new Js(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=s.normalizePipeArgs(e);r.length&&(i=i.then(async()=>{const[e,i]=await s.appendLog(this,t,r);Object.assign(t,e),await s.emitLog(this,t.id,i)}),await i)},flush:async()=>n.logger.flush(n.pipe),progress:async e=>{await this.emitProgress(n,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let o,a;await this.emitStatus(n,t,ie.RUNNING);try{let e;if(t.atomicity===ce.COMPOSITE){e=await this.runComposite(t,n);try{const e=await this.tasks.read(t.id,n);Object.assign(t,e)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const s=this.registry.get(t.classification);if(o=s,a=t.input,r.debug(`handler type for ${t.id} is ${s?.constructor?.name??"none"}`),!s)throw new P("No task handler registered for type: "+t.classification);e=await s.run(t.input,n),await n.flush(),r.verbose("handler finished for "+t.id)}t.status=ie.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const s=await this.tasks.update(t,n);Object.assign(t,s),n.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(n,t,ie.SUCCEEDED,e)}catch(e){try{await n.flush()}catch{}try{const e=await this.tasks.read(t.id,n);Object.assign(t,e)}catch{}if(e instanceof ei)return void await this.handleTaskStateChange(e.request,t,n);try{await(o?.catch?.(a,e,n))}catch(t){r.error("task handler catch() hook failed",t)}if(r.error("task execution error",e),t.atomicity===ce.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===ie.FAILED);0>r||(t.currentStep=r)}}const s=(t.attempt??0)+1,i=Zs(e);if(s<t.maxAttempts){const o=Ks(s,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+o);t.attempt=s,t.status=ie.WAITING_RETRY,t.nextRunAt=a,t.error=i,t.leaseOwner=void 0,t.leaseExpiry=void 0;const c=await this.tasks.update(t,n);Object.assign(t,c),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await n.pipe(gt.warn,"Retry scheduled",{nextRunAt:a,delayMs:o,attempt:s}),await this.emitStatus(n,t,ie.WAITING_RETRY,i,e)}else{t.attempt=s,t.status=ie.FAILED,t.error=i,t.leaseOwner=void 0,t.leaseExpiry=void 0;const o=await this.tasks.update(t,n);Object.assign(t,o),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await n.pipe(gt.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(n,t,ie.FAILED,i,e)}}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case ie.CANCELED:{const s=t.error??new $s({message:`Task ${e.id} canceled`});return e.status=ie.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,ie.CANCELED,s),void await r.pipe(gt.warn,"Task canceled via context")}case ie.WAITING_RETRY:{const s=(e.attempt??0)+1,i=Ks(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new $s({message:`Task ${e.id} requested retry`});return e.status=ie.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,ie.WAITING_RETRY,o),void await r.pipe(gt.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case ie.SCHEDULED:{if(!t.scheduledTo)throw new P("Scheduled state requires a target date");const s=t.error??new $s({message:`Task ${e.id} rescheduled`});return e.status=ie.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,ie.SCHEDULED,s),void await r.pipe(gt.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new P("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite);let s=this.normalizeSteps(t.steps),i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),o=this.getCompositeStepConcurrencyLimit(),a=o>1,c=(t,s)=>{e.cacheResult(t,s),r instanceof ri&&r!==e&&r.cacheResult(t,s)},l=()=>{s=this.normalizeSteps(t.steps);for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===ie.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;c(i.classification,r.output),c(n,r.output)}}},u=(r,i)=>{i.cache.put("scheduleCompositeSteps",async(i,n)=>{const o=n.logger.for("scheduleSteps.afterCurrent"),a=this.normalizeSteps(i);if(!a.length)return;const c=this.normalizeSteps(t.steps),u=Math.min(r+1,c.length);c.splice(u,0,...a),t.steps=c;const d=await this.tasks.update(t,e);Object.assign(t,d),l(),o.verbose(`Inserted ${a.length} steps at index ${u}`);const h=await this.persistEvent(e,t.id,ae.UPDATE,{status:"update",currentStep:r,totalSteps:s.length,output:{added:a.length,insertionIndex:u}});this.bus.emit(h,e)}),i.cache.put("scheduleCompositeStepsAtEnd",async(i,n)=>{const o=n.logger.for("scheduleSteps.atEnd"),a=this.normalizeSteps(i);if(!a.length)return;const c=this.normalizeSteps(t.steps),u=c.length;c.push(...a),t.steps=c;const d=await this.tasks.update(t,e);Object.assign(t,d),l(),o.verbose(`Appended ${a.length} steps at tail (index ${u})`);const h=await this.persistEvent(e,t.id,ae.UPDATE,{status:"update",currentStep:r,totalSteps:s.length,output:{added:a.length,insertionIndex:u}});this.bus.emit(h,e)})},d=async i=>{const o=s[i],a=this.registry.get(o.classification);if(!a)throw Error("No task handler registered for composite step: "+o.classification);const l=this.createCompositeStepContext(e,i);u(i,l);const d=this.normalizeDependencies(o.dependsOn);await this.areDependenciesSatisfied(d,l)||l.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${i} (${o.classification})`),await this.hasLockConflict(t,i,l)&&l.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${i} (${o.classification})`),await this.withStepWriteLock(l,async()=>{t.currentStep=i;const r=await this.tasks.update(t,e);Object.assign(t,r)}),await l.progress({currentStep:i,totalSteps:s.length}),await l.pipe([gt.info,`Composite step ${i+1}/${s.length}: ${o.classification}`]);const h=o.maxAttempts??1;let p,g=0;for(;h>g;)try{const r=await a.run(o.input,l);await l.flush();const u=new Date;n[i]=new Us({status:ie.SUCCEEDED,output:r,attempt:g+1,createdAt:u,updatedAt:u});const d=`${t.id}:step:${i}`;c(o.classification,r),c(d,r),await this.withStepWriteLock(l,async()=>{t.stepResults=n,t.currentStep=this.recalculateCompositeCurrentStep(s,n);const r=await this.tasks.update(t,e);Object.assign(t,r)}),await this.emitProgress(l,t.id,{currentStep:t.currentStep??i+1,totalSteps:s.length,output:r}),p=void 0;break}catch(e){if(g+=1,p=e,h>g){const e=Ks(g,this.normalizeBackoff(o.backoff??t.backoff));await l.pipe(gt.warn,`Composite step ${i} attempt ${g}/${h} failed, retrying in ${e}ms`,{classification:o.classification,attempt:g,delay:e}),await ti(e),await l.heartbeat()}}if(p){const c=new Date,u=!0===o.canFail,d=Zs(p);if(n[i]=new Us({status:ie.FAILED,error:d,attempt:g,createdAt:c,updatedAt:c}),u)try{await(a.catch?.(o.input,p,l))}catch(t){r.logger.warn("composite step catch() hook failed",{error:t})}if(await this.withStepWriteLock(l,async()=>{t.stepResults=n,t.error=u?void 0:d,t.currentStep=this.recalculateCompositeCurrentStep(s,n);const r=await this.tasks.update(t,e);Object.assign(t,r)}),!u)throw p}},h=async t=>{const e=t.map(t=>d(t)),r=(await Promise.allSettled(e)).find(t=>"rejected"===t.status);if(r&&"rejected"===r.status)throw r.reason};for(l();i<s.length;){const e=s[i];if(this.isConcurrentCompositeStep(e)&&a){const r=e.lock,a=[i];for(let t=i+1;t<s.length&&a.length<o;t+=1){const e=s[t];if(!this.isConcurrentCompositeStep(e))break;if(e.lock!==r)break;if(e.dependsOn?.length)break;a.push(t)}if(a.length>1){await h(a),s=this.normalizeSteps(t.steps),i=this.recalculateCompositeCurrentStep(s,n);continue}}await d(i),s=this.normalizeSteps(t.steps),i=this.recalculateCompositeCurrentStep(s,n)}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Rs)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Rs(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 Us)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Us(e)}):[]}async appendLog(t,e,r){const s=Array.isArray(r)&&Array.isArray(r[0]),i=e.atomicity===ce.COMPOSITE?t instanceof ri?t.step??e.currentStep:e.currentStep:void 0,n=(s?r:[r]).map(([t,e,r])=>new Ms({level:t,msg:e,meta:r,step:i}));try{return await this.withStepWriteLock(t,async()=>{const r=[...e.logTail??[],...n].slice(-this.config.logTailMax);return e.logTail=r,[await this.tasks.update(e,t),n]})}catch{return[e,[]]}}async emitStatus(t,e,r,s,i){t instanceof ri&&await t.flush();const n={status:r};s&&s instanceof $s?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,ae.STATUS,n),a=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new Fs({...o,payload:a});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,ae.LOG,r.map(t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta,step:t.step})));this.bus.emit(s,t)}normalizePipeArgs(t){if(!t.length)return[];if(1===t.length){const e=t[0];return Array.isArray(e)?0===e.length?[]:Array.isArray(e[0])?e.filter(Array.isArray):[e]:[]}const[e,r,s]=t;return"string"!=typeof e||"string"!=typeof r?[]:[[e,r,s]]}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,ae.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Fs({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,js,...r)}}class pi extends Cs{constructor(){super(Fs)}get repo(){return this._repository||(this._repository=gs.get(js).events),this._repository}}class gi extends fs{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof $t)throw new P("No/invalid config provided");if(!e.adapter)throw new P("No adapter provided");return{client:new(e.engine||hi)(e),config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,I.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,I.CREATE,!0)).for(this.push);return this.client.track(t,...r)}select(t){return this.tasks.select(t)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.CREATE,!0)).for(this.create),s=await this.tasks.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.DELETE,!0)).for(this.delete);return this.tasks.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,I.READ,!0)).for(this.read);return this.tasks.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,_.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.QUERY,!0)).for(this.query),s=this.tasks?.[t];if("function"!=typeof s)throw new P(`Method "${t}" is not implemented`);return s.apply(this.tasks,r)}async update(t,...e){throw new jt("Updates to tasks are not available")}async updateAll(t,...e){throw new jt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ct.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,e,...s)}async findByPaginate(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ct.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,e,r,...i)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...r)}refresh(t,e,r,...s){return this.tasks.refresh(t,e,r,...s)}observe(t,e){return this.tasks.observe(t,e)}unObserve(t){return this.tasks.unObserve(t)}updateObservers(t,e,r,...s){return this.tasks.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.tasks._adapter.logCtx([this.tasks.class,...t],e,r,this.tasks._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,Tt.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")}}var fi;function yi(t){if(0>=t)throw new P("splitByCount: count must be greater than zero");return e=>{const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}}function mi(t){if(0>=t)throw new P("splitBySize: maxBytes must be greater than zero");return e=>{const r=[];let s=[],i=0;for(const n of e){const e=vi(n);s.length>0&&i+e>t?(r.push(s),s=[n],i=e):(s.push(n),i+=e)}return s.length>0&&r.push(s),r}}function wi(e,r,n){let o,a;if("function"==typeof e)o=e,a=r??{};else{const t="string"==typeof r?r:fi.BY_COUNT;a=("object"!=typeof r||Array.isArray(r)?n:r)??{},o=t===fi.BY_SIZE?mi(e):yi(e)}const{delayMs:c,argIndex:l=0}=a;return(e,r,n)=>s(i(t.key(Tt.THROTTLE,r),a),(t,e,r)=>{r.value=new Proxy(r.value,{async apply(t,r,s){const i=s,{log:n,ctx:u}=(await r.logCtx(s,t.name,!0)).for(wi),d=(t=>{const e=(Array.isArray(t)?t:[t]).map(t=>{if(!Number.isFinite(t)||0>t)throw new P("@throttle() argument indexes must be non-negative integers");return t});return Array.from(new Set(e)).sort((t,e)=>t-e)})(l);if(!d.length)throw new P("@throttle() expects at least one argument index to throttle");d.forEach(t=>{if(t>=i.length)throw new P(`@throttle() requires argument index ${t} but only ${i.length} provided`);if(!Array.isArray(i[t]))throw new P(`@throttle() expects argument at index ${t} to be an array`)});const h=d.map(t=>i[t]),p=h[0].length;if(!h.every(t=>t.length===p))throw new P("@throttle() requires all targeted arguments to have the same length");if(0===p)return t.apply(r,i);const g=((t,e,r,s)=>{let i=0;return t.map(t=>{const n=t.length,o=s.map((s,o)=>{const a=r.indexOf(o);return-1===a?s:0===a?t:e[a].slice(i,i+n)});return i+=n,o})})(o(h[0]),h,d,i),f=a.breakOnSingleFailure??(()=>{try{return u.get("breakOnSingleFailureInBulk")}catch{return}})()??!0,y=[],m=[];for(const e of g){try{bi(await t.apply(r,e),y)}catch(t){if(f)throw t;m.push(t)}c&&await new Promise(t=>setTimeout(t,c))}if(m.length){n.warn(`${e+""} throttled execution continued with ${m.length} failure(s)`);const t=new AggregateError(m,`Throttled ${e+""} failed for ${m.length} chunk(s)`);throw t.results=y,t}return y}})})(e,r,n)}function vi(t){if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}}function bi(t,e){Array.isArray(t)?e.push(...t):void 0!==t&&e.push(t)}ct([ms(),lt("design:type",Function),lt("design:paramtypes",[js,void 0]),lt("design:returntype",Promise)],gi.prototype,"create",null),ct([ms(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"createAll",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],gi.prototype,"delete",null),ct([bs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"deleteAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Object,void 0]),lt("design:returntype",Promise)],gi.prototype,"read",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"readAll",null),ct([ws(),lt("design:type",Function),lt("design:paramtypes",[String,void 0]),lt("design:returntype",Promise)],gi.prototype,"query",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[js,void 0]),lt("design:returntype",Promise)],gi.prototype,"update",null),ct([vs(),lt("design:type",Function),lt("design:paramtypes",[Array,void 0]),lt("design:returntype",Promise)],gi.prototype,"updateAll",null),(t=>{t.BY_COUNT="count",t.BY_SIZE="size"})(fi||(fi={}));const Ai=Object.assign({},Dt,{persistMigrationSteps:!0});class Si{constructor(t="migration-task"){this.builder=(new qs).setClassification("migration-composite").setName(t).setMaxAttempts(1)}addMigrationStep(t){return this.builder.addStep("migration",t),this}addStep(t,e){return this.builder.addStep(t,e),this}build(){return this.builder.build()}}class xi{isVersionHint(t){return!!t}normalize(t,e){return e&&t&&(t.includes(e)||t===e)?e:t||e||"migration"}compare(t,e){return t.localeCompare(e)}gt(t,e){return this.compare(t,e)>0}lte(t,e){return 0>=this.compare(t,e)}}class Ei extends fs{constructor(){super(),this.versioning=new xi,this.allowedReferences=void 0,this.queuedTaskChain=[],this.reference=Ei.name,this.precedence=null}static async migrateAdapters(t,e={},...r){return(Ei.defaultSingleton||=new Ei).migrateAdapters(t,e,...r)}async migrateAdapters(t,e={},...r){const s=e.flavours?.length?new Set(e.flavours):void 0,i=t.filter(t=>!s||s.has(t.alias)),n=new Set(t.map(t=>t.alias).filter(Boolean)),o=e.taskService?.client,a=o?.adapter?.alias||o?.adapter?.flavour;if(a&&n.has(a))throw new P(`TaskEngine adapter alias "${a}" cannot participate in the migration targets`);const c=this;c.versioning=e.versioning||new xi,c.allowedReferences=e.references?.length?new Set(e.references):void 0,c.queuedTaskChain=[],c.orchestrationConfig={...Ai,targetVersion:e.toVersion,taskMode:!!e.taskMode,taskService:e.taskService,versioning:e.versioning,references:e.references};for(const t of i){const s=t.alias,n=e.handlers?.[s]||e.handlers?.[t.flavour]||{},o={...Ai,persistenceFlavour:s,targetVersion:e.toVersion,taskMode:!!e.taskMode,includeGenericInTaskMode:e.includeGenericInTaskMode??!(e.taskMode&&i.length>1),retrieveLastVersion:n.retrieveLastVersion,setCurrentVersion:n.setCurrentVersion,taskService:e.taskService,versioning:e.versioning,references:e.references};e.taskMode?await c.migrateViaTasksWithConfig(o,...r):await c.migrateNormallyWithConfig(o,...r)}return c}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,Tt.INITIALIZATION,!0)).for(this.initialize);try{gs.get(Tt.PERSISTENCE)}catch(t){r.get("ignoreDevSafeGuards")||e.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:Ai,Ai);return this.versioning=s.versioning||new xi,this.allowedReferences=s.references?.length?new Set(s.references):void 0,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?se.get(s.persistenceFlavour):void 0}}async down(t,e,...r){const{log:s}=this.logCtx(r,this.down);s.verbose(ft("Cleaning up after all migrations").green.bold)}normalizeVersion(t,e){return this.versioning.normalize(t,e)}extractPrecedenceTokens(t){const e=t.precedence;return e?(Array.isArray(e)?e:[e]).map(t=>{if(t&&"string"!=typeof t)return"function"==typeof t?t.name:"string"==typeof t.reference?t.reference:t.constructor?.name?t.constructor.name:void 0}).filter(t=>!!t):[]}referencesMigration(t,e){const r=this.extractPrecedenceTokens(t);return!!r.length&&(r.includes(e.reference)||r.includes(e.migration?.constructor?.name))}precedenceHint(t){return"string"==typeof t.precedence?t.precedence:void 0}compareByPrecedence(t,e){const r=t.migration,s=e.migration,i=this.referencesMigration(r,e),n=this.referencesMigration(s,t);if(i&&!n)return 1;if(n&&!i)return-1;const o=this.extractPrecedenceTokens(r),a=this.extractPrecedenceTokens(s);return o.length!==a.length?o.length-a.length:0}sort(t){const e=[...t].sort((t,e)=>{const r=this.versioning.compare(t.version,e.version);if(0!==r)return r;const s=this.compareByPrecedence(t,e);if(0!==s)return s;const i=t.flavour.localeCompare(e.flavour);return 0!==i?i:t.reference.localeCompare(e.reference)});for(let t=0;t<e.length;t++){const r=e[t],s=e[t+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new P(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return e}resolveMigration(e){const s=t.get(e.constructor,Tt.MIGRATION),i=s?.flavour||e.flavour||r,n=s?.reference||e.reference,o=this.precedenceHint(e);return{migration:e,flavour:i,reference:n,version:this.normalizeVersion(n,o)}}shouldIncludeMigration(t,e,s=!0){return!e||t.flavour===e||s&&t.flavour===r}collectMigrations(e,r=!0){const s=t.migrations(),i=[];for(const[t,n]of s){let s;try{s=new n}catch(e){throw new P(`failed to create migration ${t}: ${e}`)}const o=this.resolveMigration(s);this.shouldIncludeMigration(o,e,r)&&i.push(o)}return i}buildExecutionPlan(t){const e=t?.fromVersion?this.normalizeVersion(t.fromVersion):void 0,r=t?.toVersion?this.normalizeVersion(t.toVersion):void 0;return this.sort(this.collectMigrations(t?.targetFlavour,t?.includeGeneric)).filter(t=>!(this.allowedReferences&&!this.allowedReferences.has(t.reference)||e&&!this.versioning.gt(t.version,e)||r&&!this.versioning.lte(t.version,r)))}async executeMigration(t,...e){const r=t.migration;let s,i;try{if(s=se.get(t.flavour),!s)throw new P(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(t){throw new P(`Failed to load adapter to migrate ${r.reference}: ${t}`)}try{await r.up(i,s,...e)}catch(t){throw new Ut(`failed to initialize migration ${r.reference}: ${t}`)}try{await r.migrate(i,s,...e)}catch(t){throw new Ut(`failed to migrate ${r.reference}: ${t}`)}try{await r.down(i,s,...e)}catch(t){throw new Ut(`failed to conclude migration ${r.reference}: ${t}`)}}buildMigrationTaskForPlan(t,...e){const r=[...e],s=new Si;return t.forEach(t=>{const e={reference:t.reference,args:r};s.addMigrationStep(e)}),s.build()}buildMigrationTasksForPlan(t,...e){const r=new Map;for(const e of t){const t=r.get(e.version)||[];t.push(e),r.set(e.version,t)}return[...r.entries()].map(([t,r])=>({version:t,task:this.buildMigrationTaskForPlan(r,...e)}))}createMigrationTask(t,e,...r){const s=this.config,i=!s.taskMode||(s.includeGenericInTaskMode??!0),n=this.buildExecutionPlan({toVersion:t||s.targetVersion,fromVersion:e,targetFlavour:s.persistenceFlavour,includeGeneric:i});return this.buildMigrationTaskForPlan(n,...r)}createMigrationTasks(t,e,...r){const s=this.config,i=!s.taskMode||(s.includeGenericInTaskMode??!0),n=this.buildExecutionPlan({toVersion:t||s.targetVersion,fromVersion:e,targetFlavour:s.persistenceFlavour,includeGeneric:i});return this.buildMigrationTasksForPlan(n,...r)}migrationTaskIdsFromContext(t,e){const r=e[e.length-1],s=r?.pending?.()||r?.pending||{},i=s?.[t];return Array.isArray(i)?i.filter(t=>"string"==typeof t):[]}async migrate(t,e,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(t,e,...r){return this.migrateNormallyWithConfig(this.config,...r)}async migrateNormallyWithConfig(t,...e){const{ctxArgs:r,log:s}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.migrateNormally),i=t.persistenceFlavour,n=!t.taskMode||(t.includeGenericInTaskMode??!0),o=i?se.get(i):void 0;let a;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(o,...r);e&&(a=this.normalizeVersion(e))}const c=this.buildExecutionPlan({fromVersion:a,toVersion:t.targetVersion,targetFlavour:i,includeGeneric:n});s.debug("sorted migration before execution: "+c.map(t=>`${t.reference}@${t.version}`));for(const t of c)await this.executeMigration(t,...r);if(t.setCurrentVersion){const e=t.targetVersion||c[c.length-1]?.version||a||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),o,...r)}}async migrateViaTasks(t,e,...r){return this.queuedTaskChain=[],this.migrateViaTasksWithConfig(this.config,...r)}async migrateViaTasksWithConfig(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.migrateViaTasks),n=t.persistenceFlavour,o=t.includeGenericInTaskMode??!0,a=n?se.get(n):void 0;let c;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(a,...s);e&&(c=this.normalizeVersion(e))}const l=this.buildExecutionPlan({fromVersion:c,toVersion:t.targetVersion,targetFlavour:n,includeGeneric:o});if(i.debug("sorted migration before execution: "+l.map(t=>`${t.reference}@${t.version}`)),l.length){const e=this.buildMigrationTasksForPlan(l,...s);if(t.taskService){let n;for(const o of e){n&&(o.task.dependencies=[...o.task.dependencies||[],n]);const e=await t.taskService.push(o.task,!1,...s);n=e.id,this.queuedTaskChain.push({id:e.id,version:o.version,adapter:a,setCurrentVersion:t.setCurrentVersion}),e?.id||i.warn("TaskService.push returned missing id for version "+o.version),r.pushPending(Tt.MIGRATION,e.id)}}else{for(const t of l)await this.executeMigration(t,...s);if(t.setCurrentVersion){const e=t.targetVersion||l[l.length-1]?.version||c||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),a,...s)}}}}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.track),s=this.orchestrationConfig||this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(t=>t.id),o=this.migrationTaskIdsFromContext(Tt.MIGRATION,r),a=i?.length?i:n.length?n:o;if(!a.length)return;const c=new Map(this.queuedTaskChain.map(t=>[t.id,t])),l=s.persistenceFlavour?se.get(s.persistenceFlavour):void 0;for(const t of a){const{tracker:e}=await s.taskService.track(t,...r);await e.wait();const i=c.get(t),n=i?.setCurrentVersion||s.setCurrentVersion;n&&i?.version&&await n(this.normalizeVersion(i.version),i.adapter||l,...r)}}async retry(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.MIGRATION,!0)).for(this.retry),s=this.orchestrationConfig||this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...r);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(t=>t.id),o=this.migrationTaskIdsFromContext(Tt.MIGRATION,r),a=i?.length?i:n.length?n:o;if(!a.length)return void await this.migrateViaTasks(void 0,void 0,...r);const c=s.taskService.client.tasks,l="function"==typeof c?.override?c.override({ignoreHandlers:!0}):c;for(const t of a){const e=(await s.taskService.track(t,...r)).task;if(![ie.FAILED,ie.CANCELED].includes(e.status))continue;const i=new js({...e,status:ie.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await l.update(i,...r)}}async up(t,e,...r){const{log:s}=this.logCtx(r,this.down);s.verbose(ft("Setting up migration process").yellow.bold)}}const Oi=t.innerGet(Symbol.for(Tt.MIGRATION),r)||[];function Ci(s,i,n,o){return e.for(Tt.MIGRATION).define({decorator:(e,i,n)=>o=>{const a=e&&"object"==typeof e&&!("name"in e)?e:void 0,l=a?.precedence,u=a?.flavour,d=a?.rules,h=a?l:e,p=a?u:i,g=a?d:n,f=a?void 0!==l:void 0!==h&&("string"!=typeof h||"string"==typeof h&&"string"==typeof p);let y,m,w=h;"string"==typeof h?"string"==typeof p?(w=h,y=p,m=g):Array.isArray(p)?(w=void 0,y=h,m=p):(w=void 0,y=h,m=g):Array.isArray(p)?m=p:(y=p,m=g),void 0===w&&null!==w&&(w=Ei);const v=t.flavourOf(o)||r,b=(f&&w===Ei&&s&&s!==y?s:y)||v,A=t.innerGet(Symbol.for([Tt.MIGRATION,Tt.BY_KEY].join("-")),b||r)||[];return t.set([Tt.MIGRATION,Tt.BY_KEY].join("-"),b||r,[...A,{class:o}]),t.set(Tt.MIGRATION,s,o),c(Tt.MIGRATION,{reference:s||o.name,precedence:w,flavour:b||r,rules:m})(o)},args:[i,n,o]}).apply()}t.set(Tt.MIGRATION,r,[...Oi,Ei]);class ki extends Lt{get reference(){if(!this._reference){const e=t.get(this.constructor,Tt.MIGRATION);if(this._reference=e.reference,!this._reference)throw new P(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const e=t.get(this.constructor,Tt.MIGRATION);if(this._precedence=e.precedence,!this._precedence)throw new P(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;Qt(this,t,this.prefix(e))})}get adapter(){const e=t.get(this.constructor,Tt.MIGRATION);if(!e)throw new P("No migration metadata for "+this.constructor.name);const r=e.flavour;return se.get(r)}async enforceRules(e,r,s){const i=t.get(this.constructor,Tt.MIGRATION)?.rules;if(!i||!i.length)return!0;for(const t of i)if(!await t(e,r,s))return!1;return!0}prefix(t){return async function(e,...r){let s;e instanceof se?s=this.getQueryRunner(e.client):(s=e,e=this.adapter);const{ctx:i,log:n}=await this.logCtx([t,...r],Tt.MIGRATION,!0);if(!await this.enforceRules(s,e,i))throw n.verbose(`Skipping migration ${this.constructor.name} due to rules`),new Gt("Migration skipped for rule enforcement");return[s,e,i]}.bind(this)}logCtx(t,e,r=!1,s){let i;try{i=this.adapter}catch{i=void 0}return r&&i?i.context("string"==typeof e?e:e.name,s||{},void 0,...t).then(r=>super.logCtx(["string"==typeof e?e:e.name,...t.slice(0,-1),r],Tt.MIGRATION,!1,s)):super.logCtx(t,e,r,s)}}let Ti=class extends Vs{async run(e,r){r.logger.info("Executing migration "+e.reference);const s=t.migrations().find(([,r])=>{const s=r?.name,i=t.get(r,Tt.MIGRATION)?.reference;return s===e.reference||i===e.reference});if(!s)throw new P(`Migration ${e.reference} is not registered with the metadata layer`);const i=s[1];let n;try{n=new i}catch(t){throw new P(`Failed to instantiate migration ${e.reference}: ${t}`)}const o=t.get(n.constructor,Tt.MIGRATION),a=o?.flavour||n.flavour,c=se.get(a);if(!c)throw new P("Unable to resolve adapter for migration "+e.reference);const l=c.client,u=e.args??[];try{await n.up(l,c,...u,r)}catch(t){throw r.logger.error(`Up phase for ${e.reference} failed: ${t}`),new Ut(`Up phase for ${e.reference} failed: ${t}`)}try{await n.migrate(l,c,...u,r)}catch(t){throw r.logger.error(`migration phase for ${e.reference} failed: ${t}`),new Ut(`Migration phase for ${e.reference} failed: ${t}`)}try{await n.down(l,c,...u,r)}catch(t){throw r.logger.error(`down phase for ${e.reference} failed: ${t}`),new Ut(`Down phase for ${e.reference} failed: ${t}`)}r.logger.info(`migration ${e.reference} completed`)}};Ti=ct([Ws("migration")],Ti),vt.setRegistry(new Ye);const Ni="##VERSION##",Di="##COMMIT##",Ii="##FULL_VERSION##",_i="##PACKAGE##";t.registerLibrary(_i,Ni);export{Lt as AbsContextual,ki as AbsMigration,se as Adapter,je as AuthKeys,Ir as AuthorizationError,ne as BackoffStrategy,ss as BaseModel,Ke as BigIntSequence,Di as COMMIT,fe as Cascade,Qs as CleanUpTask,fs as ClientBasedService,qs as CompositeTaskBuilder,pe as Condition,Br as ConnectionError,$t as Context,Zt as ContextLock,Ft as ContextualLoggedClass,Dt as DefaultAdapterFlags,ye as DefaultCascade,Nt as DefaultContextFlags,Ai as DefaultMigrationConfig,_e as DefaultRepositoryFilters,Je as DefaultSequenceOptions,ue as DefaultTaskEngineConfig,ks as Dispatch,Ii as FULL_VERSION,_r as ForbiddenError,Ot as GroupOperator,kt as INDEX_SELF,Ye as InjectablesRegistry,oe as JitterStrategy,ve as MethodQueryBuilder,Ut as MigrationError,Gt as MigrationRuleError,Ei as MigrationService,Ti as MigrationTask,Si as MigrationTaskBuilder,Cs as ModelService,Pt as MultipleSelectOperationKeys,_t as NonTransactionOperationKeys,Qe as NoneSequenceOptions,Xe as NumericSequence,He as ObserverError,Mt as ObserverHandler,Et as Operator,me as OperatorsMap,ge as OrderDirection,_i as PACKAGE_NAME,Rt as PaginationOperationKeys,ns as Paginator,he as PagingError,Tt as PersistenceKeys,Ps as PersistenceService,Ct as PreparedStatementKeys,xt as QueryClause,de as QueryError,Ue as Repository,Bt as SelectOperationKeys,Ds as Sequence,is as SequenceModel,Xt as Serial,gs as Service,Kt as SimpleConcurrencyLock,xi as StandardMigrationVersioning,ps as Statement,Ys as TaskBackoffBuilder,Rs as TaskBackoffModel,zs as TaskBuilder,li as TaskCancelError,ri as TaskContext,oi as TaskControlError,hi as TaskEngine,$s as TaskErrorModel,ii as TaskEventBus,Fs as TaskEventModel,pi as TaskEventService,ae as TaskEventType,ai as TaskFailError,Vs as TaskHandler,si as TaskHandlerRegistry,Ls as TaskIOSerializer,Ms as TaskLogEntryModel,Js as TaskLogger,js as TaskModel,ui as TaskRescheduleError,ci as TaskRetryError,gi as TaskService,ie as TaskStatus,Us as TaskStepResultModel,Hs as TaskStepSpecBuilder,Gs as TaskStepSpecModel,di as TaskTracker,ce as TaskType,le as TasksKey,fi as ThrottleMode,It as TransactionOperationKeys,Jt as UUID,jt as UnsupportedError,Ni as VERSION,Ve as allowIf,xe as applyViewDecorator,Ss as auth,We as blockIf,Cr as cacheModelForPopulate,Tr as cascadeDelete,Rr as column,Ks as computeBackoffMs,ms as create,cr as createOrUpdate,Ur as createdAt,Mr as createdBy,Lr as createdByOnCreateUpdate,be as defaultQueryAttr,bs as del,Ge as generateInjectableNameForRepository,Ar as getAndConstructJunctionTable,Be as getFilters,Xs as getLogPipe,Vr as getPkTypes,Er as getPopulateKey,Or as getTagForDeleteKey,Ze as index,Yt as injectableServiceKey,Vt as isOperationBlocked,ni as isTaskError,Xr as manyToMany,vr as manyToManyOnCreate,xr as manyToManyOnDelete,Sr as manyToManyOnUpdate,Jr as manyToOne,fr as manyToOneOnCreate,wr as manyToOneOnDelete,mr as manyToOneOnUpdate,Ci as migration,Kr as noValidateOn,Zr as noValidateOnCreate,es as noValidateOnCreateUpdate,ts as noValidateOnUpdate,Wt as normalizeImport,Qr as oneToMany,hr as oneToManyOnCreateUpdate,gr as oneToManyOnDelete,pr as oneToManyOnUpdate,Wr as oneToOne,lr as oneToOneOnCreate,dr as oneToOneOnDelete,ur as oneToOneOnUpdate,De as onlyOnBulk,Oe as onlyOnCreate,ke as onlyOnDelete,Ie as onlyOnFilter,Ne as onlyOnSingle,Te as onlyOnTransactional,Ce as onlyOnUpdate,Hr as persistentVersion,or as pk,ir as pkDec,rr as pkOnCreate,kr as populate,Qt as prefixMethod,Ae as prepared,zt as promiseSequence,Se as query,ws as read,rs as relation,ze as repository,Dr as repositoryFromTypeMetadata,re as resolveBulkSequenceResult,Is as resolveTransactionLock,xs as roles,Es as route,ar as sequence,nr as sequenceDec,sr as sequenceOnCreateUpdate,Zs as serializeError,As as service,ti as sleep,yi as splitByCount,mi as splitBySize,Pr as table,Ws as task,wi as throttle,Bs as transactional,Fr as unique,$r as uniqueOnCreateUpdate,vs as update,Gr as updatedAt,jr as updatedBy,Ns as uuid,Ts as uuidCreateUpdateHandler,yr as validBidirectionalRelation,qr as version,Ee as view};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|