@decaf-ts/core 0.10.0 → 0.10.2

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.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/dist/core.cjs +1 -1
  3. package/dist/core.cjs.map +1 -1
  4. package/dist/core.js +1 -1
  5. package/dist/core.js.map +1 -1
  6. package/lib/esm/identity/decorators.d.ts +7 -2
  7. package/lib/esm/identity/decorators.js +49 -18
  8. package/lib/esm/identity/decorators.js.map +1 -1
  9. package/lib/esm/index.d.ts +1 -1
  10. package/lib/esm/index.js +1 -1
  11. package/lib/esm/model/decorators.d.ts +2 -0
  12. package/lib/esm/model/decorators.js +81 -1
  13. package/lib/esm/model/decorators.js.map +1 -1
  14. package/lib/esm/overrides/overrides.js +28 -4
  15. package/lib/esm/overrides/overrides.js.map +1 -1
  16. package/lib/esm/persistence/Adapter.js +20 -3
  17. package/lib/esm/persistence/Adapter.js.map +1 -1
  18. package/lib/esm/persistence/Context.d.ts +5 -1
  19. package/lib/esm/persistence/Context.js +19 -1
  20. package/lib/esm/persistence/Context.js.map +1 -1
  21. package/lib/esm/persistence/Sequence.d.ts +7 -0
  22. package/lib/esm/persistence/Sequence.js +54 -0
  23. package/lib/esm/persistence/Sequence.js.map +1 -1
  24. package/lib/esm/persistence/constants.d.ts +1 -0
  25. package/lib/esm/persistence/constants.js +1 -0
  26. package/lib/esm/persistence/constants.js.map +1 -1
  27. package/lib/esm/tasks/builder.d.ts +10 -0
  28. package/lib/esm/tasks/builder.js +5 -1
  29. package/lib/esm/tasks/builder.js.map +1 -1
  30. package/lib/esm/utils/ContextualLoggedClass.js +13 -1
  31. package/lib/esm/utils/ContextualLoggedClass.js.map +1 -1
  32. package/lib/identity/decorators.cjs +49 -17
  33. package/lib/identity/decorators.d.ts +7 -2
  34. package/lib/identity/decorators.js.map +1 -1
  35. package/lib/index.cjs +1 -1
  36. package/lib/index.d.ts +1 -1
  37. package/lib/model/decorators.cjs +82 -0
  38. package/lib/model/decorators.d.ts +2 -0
  39. package/lib/model/decorators.js.map +1 -1
  40. package/lib/overrides/overrides.cjs +28 -4
  41. package/lib/overrides/overrides.js.map +1 -1
  42. package/lib/persistence/Adapter.cjs +20 -3
  43. package/lib/persistence/Adapter.js.map +1 -1
  44. package/lib/persistence/Context.cjs +18 -0
  45. package/lib/persistence/Context.d.ts +5 -1
  46. package/lib/persistence/Context.js.map +1 -1
  47. package/lib/persistence/Sequence.cjs +54 -0
  48. package/lib/persistence/Sequence.d.ts +7 -0
  49. package/lib/persistence/Sequence.js.map +1 -1
  50. package/lib/persistence/constants.cjs +1 -0
  51. package/lib/persistence/constants.d.ts +1 -0
  52. package/lib/persistence/constants.js.map +1 -1
  53. package/lib/tasks/builder.cjs +5 -1
  54. package/lib/tasks/builder.d.ts +10 -0
  55. package/lib/tasks/builder.js.map +1 -1
  56. package/lib/utils/ContextualLoggedClass.cjs +13 -1
  57. package/lib/utils/ContextualLoggedClass.js.map +1 -1
  58. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,OperationKeys as o,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as h,wrapMethodWithContext as p,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,readonly as v,onCreate as A,generated as x,BadRequestError as E,timestamp as O,onUpdate as C,onCreateUpdate as T,ConflictError as k,afterAny as N,onDelete as D,SerializationError as _,prefixMethod as B,composed as R,transient as P,serialize as I,BaseError as $}from"@decaf-ts/db-decorators";import{LoggedClass as L,Logging as F,final as j,toCamelCase as U,LogLevel as M,style as Y}from"@decaf-ts/logging";import{Model as H,hashObj as G,required as q,sf as z,isEqual as Q,model as W,ValidationKeys as V,async as J,list as X,type as Z,option as tt,date as et,JSONSerializer as rt,ModelKeys as st,min as it,minlength as nt,gt as at}from"@decaf-ts/decorator-validation";import{Lock as ot,MultiLock as ct,TransactionalKeys as lt}from"@decaf-ts/transactional-decorators";import{Metadata as ut,Decoration as dt,DefaultFlavour as ht,apply as pt,methodMetadata as gt,propMetadata as ft,DecorationKeys as yt,uses as mt,metadata as wt,prop as bt,method as vt,description as At}from"@decaf-ts/decoration";var xt,Et,St,Ot,Ct;(t=>{t.FIND_BY="findBy",t.PAGE_BY="pageBy",t.COUNT_BY="countBy",t.SUM_BY="sumBy",t.AVG_BY="avgBy",t.MIN_BY="minBy",t.MAX_BY="maxBy",t.DISTINCT_BY="distinctBy",t.GROUP_BY_PREFIX="groupBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(xt||(xt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.STARTS_WITH="STARTS_WITH",t.ENDS_WITH="ENDS_WITH",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct",t.VIEW="view"})(Et||(Et={})),(t=>{t.AND="AND",t.OR="OR"})(St||(St={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ot||(Ot={})),(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.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.DEFAULT_QUERY_ATTR="default-query-attr"})(Ct||(Ct={}));const Tt=Object.assign({},{ignoreDevSafeGuards:!1}),kt=Object.assign({},a,{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}),Nt=[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Dt=[o.READ,c.READ_ALL],_t=[Ct.STATEMENT,Ot.FIND_ONE_BY],Bt=[Ct.QUERY,Ot.PAGE_BY,Ot.LIST_BY,Ot.FIND_BY,Ot.FIND,Ot.PAGE],Rt=[Ot.PAGE_BY,Ot.PAGE];class Pt extends l{constructor(t){super(t)}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter(t=>!e.has(t)),s.length)){const r=s.map(r=>r.getFromChildren(t,e)).reduce((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t),[]).filter(t=>null!=t);if(!r.length)return;return r.some(t=>"object"!=typeof t)?r[0]:r.reduce((t,e)=>Object.assign(t,e),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce((t,e)=>(t[e]=this.get(e),t),{})}accumulate(t){return super.accumulate(t)}}class It extends L{logCtx(t,e,r=!1,s){return It.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||F.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 Pt;if(n&&!a&&(s.push(n),n=void 0),!r&&!a)throw new u("No context provided");if(a&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t))}}class $t extends It{constructor(){super(),this._Context=Pt}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 Pt||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(e):new this.Context(s).accumulate(e)}}class Lt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=It.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 Ft extends u{constructor(t){super(t,Ft.name,500)}}class jt extends u{constructor(t,e=jt.name){super(t,e,500)}}class Ut extends jt{constructor(t){super(t,Ut.name)}}function Mt(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ut.Symbol(ut.constr(t)).toString().replaceAll(".","-")}async function Yt(t,e=!1){if(!e){const e=[];for(const r of t)e.push(await r());return e}const r=[];for(const e of t)try{r.push({status:"fulfilled",value:await e()})}catch(t){r.push({status:"rejected",reason:t})}return r}const Ht=[o.CREATE,o.READ,o.UPDATE,o.DELETE];function Gt(t){return Ht.includes(t)}function qt(t,e,r){const s=ut.get(t,o.REFLECT+o.BLOCK)||{};if(!s?.handler)return!1;const i=void 0===r&&Gt(e)?"crud":e,n=void 0===r&&Gt(e)?e:r,a=s.args?.[0]||[];return s.handler(a,i,n)??!1}async function zt(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 Ut)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class Wt{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 Wt._instance||(Wt._instance=new Wt),Wt._instance}}class Vt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Vt._instance||(Vt._instance=new Vt),Vt._instance}}class Jt{constructor(t,...e){this.adapter=t}async begin(...t){}async commit(...t){}async rollback(...t){}}class Xt extends ot{constructor(t){super(),this.adapterTransaction=t,this.acquireCount=0,this.lock=new ot}async acquire(...t){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...t)):this.lock.release()}async release(...t){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...t)}catch(e){await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+e),...t)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(t,...e){await this.lock.acquire();try{await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+t),...e)}catch(t){throw new u("Failed to rollback transaction: "+t)}finally{this.lock.release()}}}const Kt=dt.flavourResolver.bind(dt);dt.flavourResolver=t=>{try{const e=Kt(t);if(e&&e!==ht)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ut.registeredFlavour?ut.registeredFlavour(r):void 0;if(s&&s!==ht)return s;const i=ee._currentFlavour;if(i){const t=ee._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return ht}};const Zt=Symbol("AdapterProxyCleanup");function te(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 ee extends $t{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ee._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return ee._baseRepository}transactionLock(...t){return new Jt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[Zt];"function"==typeof e&&await e()};if(t)try{await s(this.proxies[t]),delete this.proxies[t]}catch(e){r.error("Failed to cleanup proxied adapter "+t,e)}else for(const t in this.proxies){try{await s(this.proxies[t])}catch(e){r.error("Failed to cleanup proxied adapter "+t,e);continue}delete this.proxies[t]}}async shutdown(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(Ct.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:e}=(await this.logCtx(t,Ct.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...r),this.dispatch&&await this.dispatch.close(...r)})()}catch(t){throw new u("Failed to create shutdown wrapper: "+t)}finally{this.internalLock.release(Ct.SHUTDOWN)}try{await this.shutdownPromise}catch(t){e.error("Error during proxy shutdown",t)}finally{this.shutdownPromise=void 0}}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.internalLock=new ot,this.alias in ee._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ee._cache[this.alias]=this,this.alias!==this.flavour&&(ee._cache[this.flavour]=this),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ee._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ee._currentFlavour=this.alias)}Dispatch(){return new ee._baseDispatch}ObserverHandler(){return new Lt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new ee._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?""+H.tableName(i):"";r.correlationId=r.correlationId||`${n}|${t}|${Wt.instance.generate()}`;const a=r.logger||F.for(this),o=Object.assign({},kt.cacheForPopulate,r.cacheForPopulate);return Object.assign({},kt,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,cacheForPopulate:o,args:s,writeOperation:Nt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ut.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:a})}get Context(){return Pt}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 Pt||(s.push(i),i=void 0),e=i?Object.assign({},i.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}const e=i.getOrUndefined("operation"),s=i.getOrUndefined("affectedTables");if(!e||e!==t||r&&r!==s){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=H.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[Ct.METADATA]&&(r.silly("Passing along persistence metadata for "+t[Ct.METADATA]),Object.defineProperty(i,Ct.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[Ct.METADATA]})),{record:i,id:t[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[Ct.METADATA],d=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 d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,Ct.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const a=H.tableName(t);i.debug(`Creating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})));return te(o?await Yt(l,!0):await Yt(l),o,i,c.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 te(a?await Yt(o,!0):await Yt(o),a,s,c.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const a=H.tableName(t);i.debug(`Updating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})));return te(o?await Yt(l,!0):await Yt(l),o,i,c.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})));return te(n?await Yt(a,!0):await Yt(a),n,s,c.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.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 u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),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(t){return ut.flavourOf(t)}static get currentFlavour(){if(!ee._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return ee._currentFlavour}static get current(){return ee.get(this.currentFlavour)}static unregister(t){if(!t)return;const e=ee._cache[t];e&&(delete ee._cache[t],ee._currentFlavour===t&&(ee._currentFlavour=void 0),e.flavour&&ee._cache[e.flavour]&&ee._cache[e.flavour]===e&&delete ee._cache[e.flavour])}static get(t){if(!t)return ee.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return ut.flavouredAs(t).filter(H.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${G(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,Zt,{value:async()=>{if(!s)return;const t=["cancel","close","destroy","disconnect"];for(const e of t){const t=s[e];if("function"==typeof t)try{const e=t.call(s);e instanceof Promise&&await e}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[r]=i,i}migrations(){return ut.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([j(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,Pt]),n("design:returntype",Promise)],ee.prototype,"context",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],ee.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ee.prototype,"unObserve",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],ee.prototype,"client",null);class re extends u{constructor(t){super(t,re.name,500)}}class se extends u{constructor(t){super(t,se.name,500)}}class ie 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 ie.and(this,t)}or(t){return ie.or(this,t)}not(t){return new ie(this,Et.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof ie)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 ie){if(!(this.comparison instanceof ie)&&this.operator!==Et.NOT)return{comparison:{condition:t}};if(-1===Object.values(St).indexOf(this.operator)&&this.operator!==Et.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return ie.group(t,St.AND,e)}static or(t,e){return ie.group(t,St.OR,e)}static group(t,e,r){return new ie(t,e,r)}static attribute(t){return(new ie.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 ie(this.attr1,this.operator,this.comparison)}catch(t){throw new re(t)}}}}static builder(){return new ie.Builder}static from(t){return new ie(t)}}var ne,ae;i([q(),n("design:type",Object)],ie.prototype,"attr1",void 0),i([q(),n("design:type",String)],ie.prototype,"operator",void 0),i([q(),n("design:type",Object)],ie.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(ne||(ne={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(ae||(ae={}));const oe={update:ae.CASCADE,delete:ae.NONE},ce={Equals:(t,e)=>ie.attribute(t).eq(e),Diff:(t,e)=>ie.attribute(t).dif(e),LessThan:(t,e)=>ie.attribute(t).lt(e),LessThanEqual:(t,e)=>ie.attribute(t).lte(e),GreaterThan:(t,e)=>ie.attribute(t).gt(e),GreaterThanEqual:(t,e)=>ie.attribute(t).gte(e),In:(t,e)=>ie.attribute(t).in(e),Matches:(t,e)=>ie.attribute(t).regexp(e)},le=t=>t.charAt(0).toLowerCase()+t.slice(1);class ue extends L{static get log(){return this._logger||(this._logger=F.for(ue.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?le(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(le).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(le).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(le(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?ce[a]:ce.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(ce))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:le(r),operator:e}}return{field:le(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=ue.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new re("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(ne).includes(e))throw new re(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(ne).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 l&&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 de(){return(t,e)=>{const r=ut.key(Ct.DEFAULT_QUERY_ATTR);let s=ut.get(t.constructor,r)||[];return s=[...new Set([...s,e])],pt(ft(r,s))(t,e)}}function he(){return dt.for(Ct.STATEMENT).define({decorator:()=>(t,e,r)=>pt(gt(ut.key(Ct.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function pe(t={}){return dt.for(Ct.QUERY).define({decorator:t=>(e,r,s)=>{const i=ue.getFieldsFromMethodName(r);return pt(gt(ut.key(Ct.QUERY,r),{...t,fields:i}),he(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{action:i,select:n,selector:a,where:o,groupBy:c,orderBy:l,limit:u,offset:d}=ue.build(e.name,...s),h=r;let p;switch(i){case"find":case"page":p=h.select(n);break;case"count":p=h.count(a);break;case"sum":p=h.sum(a);break;case"avg":p=h.avg(a);break;case"min":p=h.min(a);break;case"max":p=h.max(a);break;case"distinct":p=h.distinct(a);break;case"group":p=h.select(),a&&(p=p.groupBy(a));break;default:throw new re("Unsupported action: "+i)}if(o&&(p=p.where(o)),c&&c.length>0&&"group"!==i){p=p.groupBy(c[0]);for(let t=1;t<c.length;t++)p=p.thenBy(c[t])}else if(c&&c.length>0&&"group"===i)for(const t of c)p=p.thenBy(t);const{allowLimit:g,allowOffset:f,allowOrderBy:y,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},w=[{key:"orderBy",value:(l||[])[0],allowed:y},{key:"limit",value:u,allowed:g},{key:"offset",value:d,allowed:f}];for(const t of w)if(void 0!==t.value){if(!t.allowed&&m)throw new re(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(p=p[t.key](t.value))}if("page"===i){const t=s[s.length-1],e="number"==typeof t?t:t?.limit??10;return p.paginate(e)}return p.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function ge(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(ut.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),a=ut.key(t,i,n),o={...r||{},kind:e,attribute:i};return ft(a,o)(s,i)}}function fe(t){return dt.for(Et.VIEW).define({decorator:t=>ge(Et.VIEW,"view",t),args:[t]}).apply()}function ye(t){return xe(t,[o.CREATE,c.CREATE_ALL])}function me(t){return xe(t,[o.UPDATE,c.UPDATE_ALL])}function we(t){return xe(t,[o.DELETE,c.DELETE_ALL])}function be(t){return xe(t,Nt)}function ve(t){return xe(t,Object.values(o))}function Ae(t){return xe(t,Object.values(c))}function xe(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:a}=It.prototype.logCtx(n,xe);return a.silly(`filtering ${s} event for${r?" "+(H.tableName(r)||r):""} ${i}`),("string"==typeof r?r===H.tableName(t)||r===t.constructor.name:ut.constr(t)===ut.constr(r))&&e.includes(s)}}const Ee={onlyOnCreate:ye,onlyOnUpdate:me,onlyOnDelete:we,onlyOnTransactional:be,onlyOnSingle:ve,onlyOnBulk:Ae};function Se(t){const e=Object.assign({},Ee);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}var Oe,Ce,Te,ke,Ne,De,_e,Be,Re,Pe,Ie;class $e extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new u("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=H.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return Se(this)}constructor(t,e,r=!1,...s){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},t&&(this._adapter=t),e&&($e.register(e,this,this.adapter.alias,r),t)&&ut.get(e,yt.FLAVOUR)===ht&&mt(t.flavour)(e);const i=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;p(i,i[e+"Prefix"],t,i[e+"Suffix"])}),g(i,i[this.updateAll.name+"Prefix"],this.updateAll,i[this.updateAll.name+"Suffix"])}logCtx(t,e,r=!1,s){const i=this.adapter.logCtx([this.class,...t],e,r,Object.assign({},s||{},this._overrides||{}));function n(t){return t.ctxArgs.shift(),t}return i instanceof Promise?i.then(n):n(i)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new Lt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.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 f(this,r,t,o.CREATE,o.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 d(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${H.tableName(this.class)}`);let{record:n,id: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,c.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 l=H.sequenceFor(t[0]);let h=[];if(H.generatedBySequence(this.class)?(l.name||(l.name=H.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l,this._overrides)).range(t.length,...s)):H.generated(this.class,this.pk)||(h=t.map((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?h[e]:""+t[this.pk]),n||await f(this,r,t,o.CREATE,o.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=y(s);if(n)throw new d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.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 f(this,r,a,o.READ,o.ON),[t,...s]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${H.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,o.READ,o.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,o.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${a}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=H.merge(l,t,this.class))),n||await f(this,r,t,o.UPDATE,o.ON,l),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${H.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${a}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let h;if(r.get("applyUpdateValidation")&&(h=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>H.merge(h[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,o.UPDATE,o.ON,h?h[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(h[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new d(n)}return[t,...s,h]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,o.DELETE,o.ON)}return[t,...s]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${H.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map(async t=>f(this,r,t,o.DELETE,o.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=ne.ASC,s,i,...n){const{ctxArgs:a}=(await this.logCtx(n,Ct.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,Ot.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 re("PaginateBy needs a page or a bookmark");const{log:o,ctx:c,ctxArgs:l}=(await this.logCtx(s,Ot.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===ne.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 re("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,...l);return u.serialize(d)}async find(t,e=ne.ASC,...r){if("string"!=typeof t)throw new re("Find value must be a string");const s=this.getDefaultQueryAttributes(),i=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:a}=(await this.logCtx(r,Ot.FIND,!0)).for(this.find);return n.verbose(`finding ${H.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(i).orderBy([s[0],e]).execute(...a)}async page(t,e=ne.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new re("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new re("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:h}=(await this.logCtx(s,Ot.PAGE,!0)).for(this.page);u.verbose(`paging ${H.tableName(this.class)} by default attributes ${c.join(", ")}`);const p=o??10,g=c[0],f=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let y;if(a&&d.get("paginateByBookmark")){const t=H.pk(this.class),r=e===ne.ASC?this.attr(t).gt(a):this.attr(t).lt(a);y=await f.select().where(l.and(r)).orderBy([g,e]).paginate(p,...h)}else{if(!n)throw new re("PaginateBy needs a page or a bookmark");y=await f.select().where(l).orderBy([g,e]).paginate(p,...h)}const m=await y.page(i,a,...h);return y.serialize(m)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${H.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${H.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ot.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,Ot.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,Ot.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,Ot.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,Ot.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,Ot.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,Ot.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(!$e.statements(this,t))throw new re("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const t=H.defaultQueryAttributes(this.class);if(!t||!t.length)throw new re("No default query attributes defined for "+H.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new re("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 re("No default query attributes available for "+H.tableName(this.class));return r}attr(t){return ie.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:ut.constr(t)===ut.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ee._baseSequence.parseValue(H.sequenceFor(this.class).type,t)):ee._baseSequence.parseValue(H.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||ut.flavourOf(t)||ee.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}const n="function"==typeof s?s:void 0,a=e||ut.flavourOf(t)||n&&ut.get(n,Ct.ADAPTER)||ee.currentFlavour,o=a?ee.get(a):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+a);if(s instanceof $e)return s;const c=[H.tableName(t),o.alias].join(w),l=n||o.repository();return delete this._cache[c],new l(o,t,...r)}static get(t,e){const r=H.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r,s=!1){let i=H.tableName(t);if(r&&(i=[i,r].join(w)),i in this._cache&&this._cache[i]instanceof $e&&!s)throw new u(i+" already has a registered instance");this._cache[i]=e}static statements(t,e){const r=t instanceof $e?t.constructor:t,s=ut.get(r,e?ut.key(Ct.STATEMENT,e):Ct.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof $e?t.constructor:t;return ut.get(r,e?ut.key(Ct.QUERY,e):Ct.QUERY)}}function Le(t,e){if(!(e||(e=dt.flavourResolver(t instanceof H?t.constructor:t))&&e!==ht))throw new u("Could not retrieve flavour from model "+(t instanceof H?t.constructor.name:t.name));return z(Ct.INJECTABLE,e,H.tableName(t))}i([he(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],$e.prototype,"listBy",null),i([he(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],$e.prototype,"paginateBy",null),i([he(),n("design:type",Function),n("design:paramtypes",[String,String,void 0]),n("design:returntype",Promise)],$e.prototype,"find",null),i([he(),n("design:type",Function),n("design:paramtypes",[String,String,Object,void 0]),n("design:returntype",Promise)],$e.prototype,"page",null),i([he(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],$e.prototype,"findOneBy",null),i([he(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],$e.prototype,"findBy",null),i([he(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],$e.prototype,"countOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Oe="undefined"!=typeof K&&K)?Oe:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"maxOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ce="undefined"!=typeof K&&K)?Ce:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"minOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Te="undefined"!=typeof K&&K)?Te:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"avgOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ke="undefined"!=typeof K&&K)?ke:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"sumOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ne="undefined"!=typeof K&&K)?Ne:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"distinctOf",null),i([he(),n("design:type",Function),n("design:paramtypes",["function"==typeof(De="undefined"!=typeof K&&K)?De:Object,void 0]),n("design:returntype",Promise)],$e.prototype,"groupOf",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],$e.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],$e.prototype,"unObserve",null),ee&&(ee._baseRepository=$e);class Fe extends t{get log(){return this.logger||(this.logger=F.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=H.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=H.get(t.toString())),!n)return;const a=Ct.ADAPTER,o=r||ut.get(n,a)||ut.flavourOf(n);try{let t=o;try{o&&ee.get(o)}catch{const e=ee.current;e&&e.flavour===o&&(t=e.alias)}if(i=$e.forModel(n,t),i instanceof $e)return i;const r=o||ut.get(i.constructor,a)||ut.get(n,a);e.register(i,Le(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=$e.get(n,o);if("function"==typeof e){const t=o?ee.get(o):ee.current;if(!t)return;return new e(t,n)}}}return i}}(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(_e||(_e={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(Be||(Be={})),(t=>{t.NONE="none",t.FULL="full"})(Re||(Re={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Pe||(Pe={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Ie||(Ie={}));const je="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}};function Me(t,e){return(i,n)=>n?r(ut.constr(t))(i,n):(ut.set(b.REPOSITORY,ut.key(e||ee.currentFlavour,H.tableName(t)),i),wt(b.REPOSITORY,i.name)(t),e=e||ut.get(i.constructor,Ct.ADAPTER),$e.register(t,i),s(ut.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut.tasks=(()=>ut.innerGet(Symbol.for(je))).bind(ut),ut.taskFor=(t=>{const e=ut.tasks();return e?e[t]:void 0}).bind(ut),ut.validationExceptions=((t,e)=>{const r=ut.get(t,Ct.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==o.CREATE&&e!==o.UPDATE||(i=H.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ut),ut.migrationsFor=(t=>{if(!(t=t??ee.current))throw new u("Could not get adapter for migrations");return ut.innerGet(Symbol.for(Ct.MIGRATION),t.alias).map(t=>t.class)}).bind(ut),ut.migrations=(()=>{const t=ut.innerGet(Symbol.for([Ct.MIGRATION,Ct.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(ut),ut.relations=((t,e)=>{const r=ut.get(t,Ct.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(ut),H.relations=(t,e)=>ut.relations(t instanceof H?t.constructor:t,e)||[],H.nestedRelations=((t,e=[])=>{let r=[];const s=ut.get(t,Ct.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&H.relations(i.class)){const s=H.relations(i.class).map(e=>`${t}.${e}`);e=[...e,...s],r=H.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(H),H.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!H.sequenceFor(r).generated}).bind(H),H.fromTable=(t=>{const e=ut.innerGet(Symbol.for(Ct.TABLE));if(!e||!e[t]||!H.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return H.get(e[t].name)}).bind(H),ut.createdBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(ut),ut.updatedBy=(t=>{const e=ut.get("function"!=typeof t?t.constructor:t,Ct.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(ut),H.tableName=t=>{if(!(t instanceof H?H.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ut.get(t instanceof H?t.constructor:t,Ct.TABLE)||(t instanceof H?t.constructor.name:t.name)},H.columnName=(t,e)=>ut.get(t instanceof H?t.constructor:t,ut.key(Ct.COLUMN,e))||e,H.defaultQueryAttributes=(t,e=!1)=>{const r="function"==typeof t?t:t.constructor;return ut.get(r,ut.key(Ct.DEFAULT_QUERY_ATTR))||(e?[H.pk(t)]:[])},H.sequenceName=(t,...e)=>[H.tableName(t),...e].join("_"),H.sequenceFor=(t,e)=>{const r="function"!=typeof t?t.constructor:t;e||(e=H.pk(t));const s=ut.get(r,ut.key(Ct.SEQUENCE,e));if(!s)throw new u(`No sequence options defined for property ${e+""}. did you use @sequence()?`);return s},H.indexes=t=>{const e=ut.get(t instanceof H?t.constructor:t,Ct.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[Ct.INDEX]:e[r]},t),{})},e.services=()=>ut.innerGet(Symbol.for(Ct.SERVICE)),e.repositories=()=>ut.innerGet(Symbol.for(b.REPOSITORY)),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 Ye extends u{constructor(t){super(t,Ye.name,500)}}var He;function Ge(t,...e){return(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:a}=await s.logCtx(i,r.name,!0);let o;try{o=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(o)throw o;return r.call(s,...a)}})}}function qe(t,...e){return(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:a}=await s.logCtx(i,r.name,!0);let o;try{o=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(o)throw o;return r.call(s,...a)}})}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(He||(He={}));const ze={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Qe=ze,We={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Ve=Object.assign({},We,{type:"BigInt"});function Je(t,e,r){return dt.for(Ct.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![ne.ASC,ne.DSC].includes(t))&&(e=t,t=void 0),ft(ut.key(`${Ct.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}function Xe(t){return"function"==typeof t}function Ke(t,e){return Xe(H.sequenceName)?H.sequenceName(t,e):[Xe(H.tableName)?H.tableName(t):t?.name??"",e||"pk"].filter(Boolean).join("_")}function Ze(t,e,r){if(!r.type){const s=ut.type(t.constructor,e);if(![Number.name,String.name,BigInt.name].includes(s?.name||s))throw Error("Incorrrect option type");r.type=s}switch(r.type){case String.name||String.name.toLowerCase():case String:r.generated=void 0!==r.generated&&r.generated,r.type=String;break;case Number.name||String.name.toLowerCase():case Number:r.generated=void 0===r.generated||r.generated,r.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:r.type=BigInt,r.generated=void 0===r.generated||r.generated;break;case"uuid":case"serial":r.generated=!0;break;default:throw Error("Unsupported type")}void 0===r.generated&&(r.generated=!0)}async function tr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=H.sequenceName(s,r));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`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)}function er(t,e){return(r,s)=>{bt()(r,s),Ze(r,s,t),t.name||(t.name=Ke(r.constructor,"pk"));const i=[ft(ut.key(b.ID,s),t),ft(ut.key(Ct.SEQUENCE,s),t),Je([ne.ASC,ne.DSC]),q(),v(),A(tr,t,e)];return t.generated&&i.push(x()),pt(...i)(r,s)}}function rr(t,e){return(r,s)=>{if(bt()(r,s),Ze(r,s,t),!t.name){const e=(t=>"string"==typeof t?t:"symbol"==typeof t?t.description||t.toString():t+"")(s);t.name=Ke(r.constructor,e)}const i=[q(),v(),ft(ut.key(Ct.SEQUENCE,s),t),A(tr,t,e)];return t.generated&&i.push(x()),pt(...i)(r,s)}}function sr(t){const e=Object.assign({},Qe);return delete e.generated,t=Object.assign({},e,t),dt.for(b.ID).define({decorator:er,args:[t,{priority:60}]}).apply()}function ir(t){const e=Object.assign({},Qe);return delete e.generated,t=Object.assign({},e,t),dt.for(Ct.SEQUENCE).define({decorator:rr,args:[t,{priority:60}]}).apply()}async function nr(t,e,r,s,i){const n=e.logger.for(nr);if(!s){const e=H.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=$e.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 m))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 ar(t,e,r,s){const i=s[r];if(!i)return;if(pr(s,e),"object"!=typeof i){const e=Tr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Er(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const a=$e.forModel(n,this.adapter.alias),o=await a.override(this._overrides).create(i,t),c=H.pk(o);await Er(t,s,r,o[c],o),s[r]=o[c]}async function or(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ae.CASCADE)return;if("object"!=typeof i){const e=Tr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Er(t,s,r,i,n),void(s[r]=i)}const n=await nr(s[r],t,this.adapter.alias,void 0,this._overrides),a=H.pk(n);await Er(t,s,r,n[a],n),s[r]=n[a]}async function cr(t,e,r,s){const i=s[r];if(null==i)return;if(e.cascade.delete!==ae.CASCADE)return;const n=Tr(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 Er(t,s,r,a[n.pk],a)}async function lr(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;pr(s,e);const a=t.logger.for(lr),o=Tr(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 nr(e,t,this.adapter.alias,void 0,this._overrides)),a.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await Er(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function ur(t,e,r,s,i){const{cascade:n}=e;if(n.update===ae.CASCADE)return lr.call(this,t,e,r,s,i)}async function dr(t,e,r,s){if(e.cascade.delete!==ae.CASCADE)return;const i=s[r];if(!i)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?$e.forModel(a,this.adapter.alias):Tr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await Er(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}async function hr(t,e,r,s){const i=s[r];if(!i)return;pr(s,e);const n=t.logger.for(hr);if("object"!=typeof i){const e=Tr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Er(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof H?e.class.constructor:e.class))throw new u("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const a=await nr(i,t,this.adapter.alias,void 0,this._overrides),o=H.pk(a);n.info(`caching: ${JSON.stringify(a)} under ${a[o]}`),await Er(t,s,r,a[o],a),s[r]=a[o]}function pr(t,e){let r;const s="function"==typeof e.class&&e.class.name?e.class:e.class(),i=ut.get(s,Ct.RELATIONS);if(i&&(r=Object.values(i)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===r?.populate&&!0===e?.populate)throw new u("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function gr(t,e,r,s){const{cascade:i}=e;if(i.update===ae.CASCADE)return hr.call(this,t,e,r,s)}async function fr(t,e,r,s){if(e.cascade.delete!==ae.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,a=n?$e.forModel(i,this.adapter.alias):Tr(s,r,this.adapter.alias),o=n?i[a.pk]:i,c=await a.override(this._overrides).delete(o);await Er(t,s,r,o,c),s[r]=o}async function yr(t,e,r,s){const i=s[r];if(!i||!i.length)return;pr(s,e);const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a=t.logger.for(yr),o=new Set([...i]);if("object"!==n){const n=Tr(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 Er(t,s,r,[...o.values()][e],c)}return await mr.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 nr(e,t,this.adapter.alias,void 0,this._overrides);a.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Er(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 d=H.pk(s.constructor);if(void 0===s[d]){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 u(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[d]=e}const h=await mr.call(this,s,i,a,t,e);a.info("Junction model created: "+h.name),s[r]=[...l]}async function mr(t,e,r,s,i){const{JunctionModel:n,fkA:a,fkB:o}=wr(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 nr(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=$e.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function wr(t,e,r){const s=H.tableName(t);let i;if(e instanceof H)i=H.tableName(e);else if(H.isModel(e)&&"function"==typeof e)i=e.name?e.name:e()?.name;else if(r?.class){const t="function"!=typeof r.class||r.class.name?r.class:r.class();i=H.tableName(t)}if(!s||!i)throw new u("Missing tablenames to create junction table");const n=r?.joinTable?.name?r?.joinTable?.name:`${s}_${i}`,a=s?.toLowerCase()+"_fk",o=i?.toLowerCase()+"_fk",c=class extends H{constructor(t){super(t)}};Object.defineProperty(c,"name",{value:n,writable:!1}),sr({type:Number})(c.prototype,"id"),q()(c.prototype,a),q()(c.prototype,o);const l=W()(c);return ut.set(c,Ct.TABLE,n),{fkA:a,fkB:o,JunctionModel:l}}async function br(t,e,r,s){const{cascade:i}=e;if(i.update===ae.CASCADE)return yr.call(this,t,e,r,s)}async function vr(t,e,r,s){if(e.cascade.delete!==ae.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?$e.forModel(a,this.adapter.alias):Tr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await Er(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function Ar(t,e,r){return e?[Ct.POPULATE,t,e,r].join("."):[Ct.POPULATE,t,r].join(".")}function xr(t,e,r){return[Ct.TAG_FOR_DELETION,t,r].join(".")}async function Er(t,e,r,s,i){const n=Ar(e.constructor.name,r,s),a=t.logger.for(Er),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 Sr(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,l=await(async(e,r,s,i)=>{let n,l;const d=[];let h;try{h=e.get("operation")}catch(t){h=void 0}const p=h===o.READ||h===c.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=Ar(r.constructor.name,s,e);try{if(l=p[n],!l)throw Error("Not found in cache")}catch(i){const n=Tr(r,s,a.adapter.alias);if(!n)throw new u("Could not find repo");l=await n.override(a._overrides).read(e,t)}d.push(l)}return d})(t,s,r,n?i:[i]);s[r]=n?l:l[0]}async function Or(t,e,r,s,i){if(e.cascade.update!==ae.CASCADE)return;if(!i)throw new u("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||Q(a,o))return;if(Array.isArray(a)!==Array.isArray(o))throw new u("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)),d=Tr(s,r,this.adapter.alias);if(!d)throw new u("Could not find repo");try{const e=await d.override(this._overrides).deleteAll(l,t);t.logger.debug(`Deleted ${e.length} entries from table ${H.tableName(d.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}const Cr=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Tr(t,e,r){if(!t)throw Error("No model was provided to get repository");let s,i=t instanceof H?t.constructor:t;if(Array.isArray(t[e])||t[e]instanceof Set){const t=ut.get(i,ut.key(V.REFLECT,e,V.LIST))?.clazz;if(!t)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(t)?[...t]:[t]).map(t=>"function"!=typeof t||t.name?t:t())}else s=H.relations(i).includes(e)?ut.allowedTypes(i,e):ut.getPropDesignTypes(t instanceof H?t.constructor:t,e)?.designTypes;i=s?.find(t=>!Cr.includes((""+t.name).toLowerCase()));const n=$e.forModel(i,r);if(i!==n.class)throw new u("Invalid repository class for "+e);return n}class kr extends E{constructor(t,e=kr.name,r=401){super(t,e,r)}}class Nr extends kr{constructor(t,e=Nr.name){super(t,e,403)}}class Dr extends u{constructor(t){super(t,Dr.name,503)}}function _r(t){return dt.for(Ct.TABLE).define({decorator:t=>e=>(ut.set(Ct.TABLE,t||e.name.toLowerCase(),e),wt(Ct.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function Br(t){return dt.for(Ct.COLUMN).define({decorator:t=>(e,r)=>ft(ut.key(Ct.COLUMN,r),t||r)(e,r),args:[t]}).apply()}async function Rr(t,e,r,s){if(s[r]&&(await this.select().where(ie.attribute(r).eq(s[r])).execute()).length)throw new k(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Pr(){const t=Ct.UNIQUE;return dt.for(t).define(J(),T(Rr),ft(t,{})).apply()}async function Ir(t,e,r,s){throw new kr("This adapter does not support user identification")}function $r(){return dt.for(Ct.CREATED_BY).define({decorator:()=>(t,e)=>pt(A(Ir),ft(Ct.CREATED_BY,e),x(Ct.CREATED_BY))(t,e),args:[]}).apply()}function Lr(){return dt.for(Ct.UPDATED_BY).define({decorator:()=>(t,e)=>pt(C(Ir),ft(Ct.UPDATED_BY,e),x(Ct.UPDATED_BY))(t,e),args:[]}).apply()}function Fr(){return O([o.CREATE])}function jr(){return O()}function Ur(t){return[()=>{const e="function"==typeof t&&t.name?t:t(),r=H.pk(e);return(ut.allowedTypes(e,r)||[])[0]}]}function Mr(t,e=oe,r=!0,s,i){const n=Ct.ONE_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ur(t),c=[bt(),Vr(n,a),Z([t,...o]),A(ar,a,{priority:70}),C(or,a,{priority:70}),D(cr,a,{priority:70}),C(Or,a,{priority:80}),N(Sr,a,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Yr(t,e=oe,r=!0,s,i){const n=Ct.ONE_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ur(t),c=[bt(),Vr(n,a),X([t,...o]),A(lr,a,{priority:70}),C(ur,a,{priority:70}),D(dr,a,{priority:70}),C(Or,a,{priority:80}),N(Sr,a,{priority:70})];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Hr(t,e=oe,r=!0,s,i){const n=Ct.MANY_TO_ONE;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ur(t),c=[bt(),Vr(n,a),Z([t,...o]),A(hr,a),C(gr,a),D(fr,a),N(Sr,a)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function Gr(t,e=oe,r=!0,s,i){const n=Ct.MANY_TO_MANY;return dt.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ur(t),c=[bt(),Vr(n,a),X([t,...o]),A(yr,a),C(ur,a),N(Sr,a)];return pt(...c)},args:[t,e,r,s,i]}).apply()}function qr(...t){return(e,r)=>{const s=ut.get(e,ut.key(Ct.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return pt(wt(ut.key(Ct.NO_VALIDATE,r),i))(e,r)}}function zr(){return qr(o.CREATE)}function Qr(){return qr(o.UPDATE)}function Wr(){return qr(o.UPDATE,o.CREATE)}function Vr(t,e){return dt.for(Ct.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ft(t,e)(r,s),ft(ut.key(Ct.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class Jr extends H{constructor(t){super(t)}}i([Fr(),n("design:type",Date)],Jr.prototype,"createdAt",void 0),i([jr(),n("design:type",Date)],Jr.prototype,"updatedAt",void 0);let Xr=class extends Jr{constructor(t){super(t)}};i([sr({type:String,generated:!1}),n("design:type",String)],Xr.prototype,"id",void 0),i([q(),Je(),n("design:type",Object)],Xr.prototype,"current",void 0),Xr=i([_r("??sequence"),W(),n("design:paramtypes",[Object])],Xr);class Kr extends L{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(`${Ot.FIND_BY}|${Ot.LIST_BY}|${Ot.FIND}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],Ot.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[t,...r]}async pagePrepared(t,e,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!e||e instanceof Pt?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof Pt||(this._bookmark=e);const n=$e.forModel(this.clazz,this.adapter.alias),a=this.query,{method:o,args:c,params:l}=a;if(o===Ot.FIND){const e=[Ot.PAGE,...c],r={limit:this.size,offset:t,bookmark:this._bookmark};e.push(r);const s=await n.statement(...e,...i);return this.apply(s)}const u=RegExp(`^${Ot.FIND_BY}|${Ot.LIST_BY}`,"gi");if(!o.match(u))throw new Ft(`Method ${o} is not supported for pagination`);u.lastIndex=0;const d=o.replace(u,Ot.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Ot.PAGE_BY||h.length>2?p={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(p);const g=await n.statement(...h,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new se("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new se(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,e,...r){const{ctxArgs:s}=this.adapter.logCtx([e,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...s);throw new Ft("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new _(t)}}apply(t){const e="string"==typeof t?Kr.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 _(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var Zr,ts,es,rs,ss,is,ns;class as extends It{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach(t=>{B(this,t,(...e)=>this.executionPrefix(t,...e),t.name)})}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?Ot.PAGE_BY:Ct.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),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(as)}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 re("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 re("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 re("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new re("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 re("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===ne.ASC)return ne.ASC;if(e===ne.DSC)return ne.DSC;throw new re(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ne).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new re("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 re(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=$e.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new Ft("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(this.hasAggregation())return i;if(!this.selectSelector)return i;const n=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 f(this.getRepository(),e,t,o.READ,o.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 $e.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case St.AND:case St.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 ie){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 re("Unsupported operator "+s)}return n}squash(t){const e=this.matchDefaultQueryCondition();if(e){const t=this.getOrderDirection();return{class:this.fromSelector,method:Ot.FIND,args:[e.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof ie)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:Ot.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:Ot.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:Ot.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:Ot.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:Ot.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:Ot.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:Ot.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let r;this.whereCondition&&(r=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,ne.DSC]:[H.pk(this.fromSelector),ne.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:Ot.LIST_BY,args:[i],params:a};return r&&(o.method=Ot.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===St.OR){const t=e instanceof ie?this.collectStartsWithAttributes(e):void 0,r=s instanceof ie?this.collectStartsWithAttributes(s):void 0;return t&&r&&t.value===r.value?{attributes:[...t.attributes,...r.attributes],value:t.value}:void 0}return r===St.AND?(e instanceof ie?this.collectStartsWithAttributes(e):void 0)||(s instanceof ie?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??ne.ASC}async prepare(t){if(t=t||await this.adapter.context(Ct.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r};let i,n=xt.FIND_BY;void 0!==this.countSelector?(n=xt.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=xt.SUM_BY,i=this.sumSelector):this.avgSelector?(n=xt.AVG_BY,i=this.avgSelector):this.minSelector?(n=xt.MIN_BY,i=this.minSelector):this.maxSelector?(n=xt.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=xt.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=xt.GROUP_BY_PREFIX,i=this.groupBySelectors[0]);const 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=U(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 re(t)}}toString(){return this.adapter.flavour+" statement"}}i([j(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],as.prototype,"select",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Zr="undefined"!=typeof S&&S)?Zr:Object]),n("design:returntype",Object)],as.prototype,"distinct",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ts="undefined"!=typeof S&&S)?ts:Object]),n("design:returntype",Object)],as.prototype,"max",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(es="undefined"!=typeof S&&S)?es:Object]),n("design:returntype",Object)],as.prototype,"min",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(rs="undefined"!=typeof S&&S)?rs:Object]),n("design:returntype",Object)],as.prototype,"sum",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ss="undefined"!=typeof S&&S)?ss:Object]),n("design:returntype",Object)],as.prototype,"avg",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(is="undefined"!=typeof S&&S)?is:Object]),n("design:returntype",Object)],as.prototype,"count",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],as.prototype,"from",null),i([j(),n("design:type",Function),n("design:paramtypes",[ie]),n("design:returntype",Object)],as.prototype,"where",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],as.prototype,"orderBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],as.prototype,"thenBy",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ns="undefined"!=typeof Key&&Key)?ns:Object]),n("design:returntype",Object)],as.prototype,"groupBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],as.prototype,"limit",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],as.prototype,"offset",null),i([j(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],as.prototype,"execute",null);class os extends It{constructor(t){super(),this.name=t,this.observers=[],this.Context=Pt}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 os?n.for(t,...e):n instanceof $e?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Lt,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${Wt.instance.generate()}`;const s=e.logger||F.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Tt,e,{args:r,timestamp:new Date,operation:t,logger:s})}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}async context(t,e,...r){this.log.for(this.context).silly(`creating new context for ${t} operation with flag overrides: ${JSON.stringify(e)}`);let s=r.pop();void 0===s||s instanceof Pt||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return It.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new u("No name provided");const r=Mt(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof Pt||(t.push(r),r=void 0);const s=await os.prototype.flags(Ct.INITIALIZATION,{},...t);r=r?new Pt(r).accumulate({...s,parentContext:r}):(new Pt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=os.prototype.logCtx(t,this.boot),a=e.services();for(const[t,r]of Object.entries(a))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof cs&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new u(`Failed to boot ${r.name} service:${t}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof Pt||(t.push(r),r=void 0);const s=await os.prototype.flags(Ct.SHUTDOWN,{},...t);r=r?new Pt(r).accumulate({...s,parentContext:r}):(new Pt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=os.prototype.logCtx(t,this.shutdown),a=e.services();for(const[t,r]of Object.entries(a).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof cs){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],os.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],os.prototype,"unObserve",null);class cs extends os{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,Ct.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function ls(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&qt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],cs.prototype,"boot",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],cs.prototype,"config",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],cs.prototype,"client",null);const us=()=>ls(o.CREATE),ds=()=>ls(o.READ),hs=()=>ls(o.UPDATE),ps=()=>ls(o.DELETE);function gs(t){return(e,i,n)=>{n||i?(bt()(e,i),t=t||ut.type(e.constructor,i)):t=t||e,t=Mt(t);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else ut.set(Ct.SERVICE,t,e),a.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return pt(...a)(e,i,n)}}function fs(t){const e=Ct.AUTH;return dt.for(e).define({decorator:t=>wt(e,t),args:[t]}).apply()}const ys=t=>wt(Ct.AUTH_ROLE,t);function ms(t,e){const r=Ct.DECAF_ROUTE;return dt.for(r).define({decorator:()=>(s,i,n)=>{const a={path:e,httpMethod:t,handler:n};return pt(gt(ut.key(r,i),a))(s,i,n)},args:[]}).apply()}const ws=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class bs extends os{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=$e.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=ws(t);try{const t=os.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}select(t){return this.repo.select(t)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=ws(e||t);try{r=bs.get(e)}catch(t){r=void 0}if(r instanceof bs)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([gs(e),n("design:paramtypes",[])],a),new a}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo._adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([us(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],bs.prototype,"create",null),i([us(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],bs.prototype,"createAll",null),i([ps(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],bs.prototype,"delete",null),i([ps(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],bs.prototype,"deleteAll",null),i([ds(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],bs.prototype,"read",null),i([ds(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],bs.prototype,"readAll",null),i([ds(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],bs.prototype,"query",null),i([hs(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],bs.prototype,"update",null),i([hs(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],bs.prototype,"updateAll",null);class vs extends It{constructor(){super(),this.initialized=!1}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");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,Ct.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const r=this.adapter;[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return o.CREATE;case c.UPDATE_ALL:return o.UPDATE;case c.DELETE_ALL:return o.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 ee))throw new Ft("Only Adapters can be observed by dispatch");return this.adapter?()=>this.unObserve(this.adapter):(this.adapter=t,this.models=ee.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t))}unObserve(t){if(this.adapter!==t)throw new Ft("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){if(!t)throw new u("Model must be provided for observer update");const i=t&&"string"==typeof t?t: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 u("Failed to refresh dispatch: "+t)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function As(t,e,r,s){if(t.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=e;i&&"function"==typeof i&&(i=i(s,...n||[],t)),s[r]=await Wt.instance.generate(i)}function xs(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=Ct.UUID;return dt.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[q(),x(Ct.UUID),A(As,s,{priority:54})];return t&&i.push(C(As,s,{priority:54})),t||i.push(v()),pt(...i)},args:[t,e,...r]}).apply()}ee&&(ee._baseDispatch=vs);class Es extends It{static{this.lock=new ct}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=$e.forModel(Xr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,o.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:a}=this.options;if(!a)throw new u("Sequence name is required");return Es.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new Xr({id:a,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${a} current=${c} next=${t}`),this.repo.create(new Xr({id:a,current:t}),s);throw e}};if("uuid"===o)for(;;){const t=await Promise.resolve(Wt.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 k)continue;throw t}}const d=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(Vt.instance.generate(t));default:throw new u("Should never happen")}})(c),h=await l(d);return r.debug(`Sequence.increment ${a} current=${c} next=${d}`),h.current},a)}async next(...t){const{ctx:e}=(await this.logCtx(t,o.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ft(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),a=await this.increment(this.parse(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(a-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==a&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return Es.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([Xr,...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 Ft(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ss(t,...e){let r;if(t instanceof bs&&(r=t.repo.adapter),t instanceof $e&&(r=t.adapter),t instanceof ee&&(r=t),!r)throw new u("Could not find adapter to extract transaction");return r.transactionLock(...e)}function Os(t,...e){return new Xt(Ss(t,...e))}ee._baseSequence=Es,dt.for(lt.TRANSACTIONAL).define({decorator:(...t)=>(e,r,s)=>{if(!s)throw new u("This decorator only applies to methods");return vt()(e,r,s),ut.set(e.constructor,ut.key(lt.TRANSACTIONAL,r),{data:t}),s.value=new Proxy(s.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock")||Os(e);let a;i.put("transactionLock",n),await n.acquire();try{a=await t.call(e,...r,i)}catch(t){try{await n.rollback(t)}catch(t){s.error("Failed to rollback transaction",t)}throw t}try{await n.release()}catch(t){throw new u("Failed to release transaction: "+t)}return a}}),s}}).apply();class Cs extends cs{constructor(){super()}for(t,...e){throw new Ft("Persistence service cannot be overridden")}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof Pt||!e.every(t=>Array.isArray(t)))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,Ct.INITIALIZATION,!0)).for(this.initialize),i=e.map(([t,e,...s])=>{try{r.silly(`Initializing ${t.name} with config: ${JSON.stringify(e)}`);const i=new t(e,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(e){throw new u(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Ts=class extends H{constructor(t){super(t),this.strategy=Be.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=Re.FULL}};i([q(),Z(String),tt(Be),At("the backoff strategy"),n("design:type",String)],Ts.prototype,"strategy",void 0),i([q(),At("base interval between attempts"),n("design:type",Number)],Ts.prototype,"baseMs",void 0),i([q(),At("max interval"),n("design:type",Number)],Ts.prototype,"maxMs",void 0),i([Z(String),tt(Re),At("optional jitter strategy"),n("design:type",String)],Ts.prototype,"jitter",void 0),Ts=i([W(),n("design:paramtypes",[Object])],Ts);let ks=class extends H{constructor(t){super(t)}};i([q(),At("The error message"),n("design:type",String)],ks.prototype,"message",void 0),i([bt(),At("The error stack"),n("design:type",String)],ks.prototype,"stack",void 0),i([bt(),At("The error code"),n("design:type",String)],ks.prototype,"code",void 0),i([bt(),At("The error details"),n("design:type",Object)],ks.prototype,"details",void 0),ks=i([W(),n("design:paramtypes",[Object])],ks);let Ns=class extends H{constructor(t){if(super(t),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}};i([sr(),R(["taskId","classification","uuid"],":"),n("design:type",String)],Ns.prototype,"id",void 0),i([Br(),v(),q(),P(),xs(!1),n("design:type",String)],Ns.prototype,"uuid",void 0),i([Br(),v(),q(),Je([ne.ASC,ne.DSC]),n("design:type",String)],Ns.prototype,"taskId",void 0),i([et(),Br(),q(),Je([ne.ASC,ne.DSC]),n("design:type",Date)],Ns.prototype,"ts",void 0),i([Br(),v(),q(),tt(Pe),Je([ne.ASC,ne.DSC]),n("design:type",String)],Ns.prototype,"classification",void 0),i([bt(),Br(),I(),v(),n("design:type",Object)],Ns.prototype,"payload",void 0),Ns=i([_r("task_event"),W(),n("design:paramtypes",[Object])],Ns);class Ds extends rt{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 ie){const r=this.serializePlain(t,...e);return r[st.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[st.ANCHOR]=s),r}serializePlain(t,...e){const r={};for(const[s,i]of Object.entries(t))r[s]=this.serializeValue(i,...e);return r}getMetadata(t){try{return ut.modelName(t)}catch{return}}rebuildValue(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>this.rebuildValue(t));const e=t[st.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?ie.from(r):H.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==st.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let _s=class extends H{constructor(t){super(t),this.ts=new Date}};i([et(),q(),n("design:type",Date)],_s.prototype,"ts",void 0),i([q(),tt(M),n("design:type",String)],_s.prototype,"level",void 0),i([it(0),n("design:type",Number)],_s.prototype,"step",void 0),i([q(),bt(),n("design:type",String)],_s.prototype,"msg",void 0),i([bt(),n("design:type",Object)],_s.prototype,"meta",void 0),_s=i([W(),n("design:paramtypes",[Object])],_s);let Bs=class extends H{constructor(t){super(t),this.atomicity=Ie.ATOMIC,this.status=_e.PENDING,this.attempt=0,this.logTail=[]}};i([sr(),xs(),At("the task id"),n("design:type",String)],Bs.prototype,"id",void 0),i([Br(),q(),Z(String),tt(Ie),Je([ne.ASC,ne.DSC]),At("defines a single or composite task"),n("design:type",String)],Bs.prototype,"atomicity",void 0),i([Br(),q(),Je([ne.ASC,ne.DSC]),At("Holds task classification - must match @task()"),n("design:type",String)],Bs.prototype,"classification",void 0),i([Br(),bt(),Je([ne.ASC,ne.DSC]),At("optional task name for ambiguity"),n("design:type",String)],Bs.prototype,"name",void 0),i([Br(),q(),Z(String),tt(_e),Je([ne.ASC,ne.DSC]),At("Holds the task current status"),n("design:type",String)],Bs.prototype,"status",void 0),i([bt(),Br(),I(Ds),At("Holds task input"),n("design:type",Object)],Bs.prototype,"input",void 0),i([bt(),Br(),I(Ds),At("Holds the task output when successfully completed"),n("design:type",Object)],Bs.prototype,"output",void 0),i([bt(),Br(),I(),At("Holds the error for failed tasks"),n("design:type",ks)],Bs.prototype,"error",void 0),i([Br(),q(),it(0),Je([ne.ASC,ne.DSC]),At("Holds the current attempt"),n("design:type",Number)],Bs.prototype,"attempt",void 0),i([Br(),it(1),q(),At("max attempts for the task"),n("design:type",Number)],Bs.prototype,"maxAttempts",void 0),i([Br(),q(),I(),At("backoff configuration"),n("design:type",Ts)],Bs.prototype,"backoff",void 0),i([et(),Br(),At("Next execution timestamp"),n("design:type",Date)],Bs.prototype,"nextRunAt",void 0),i([et(),Br(),At("Task scheduled timestamp"),n("design:type",Date)],Bs.prototype,"scheduledTo",void 0),i([bt(),Br(),At("Task lease owner identifier"),n("design:type",String)],Bs.prototype,"leaseOwner",void 0),i([et(),Br(),At("Task lease expiration timestamp"),n("design:type",Date)],Bs.prototype,"leaseExpiry",void 0),i([bt(),Br(),I(),At("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Bs.prototype,"steps",void 0),i([bt(),Br(),it(0),Je([ne.ASC,ne.DSC]),At("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Bs.prototype,"currentStep",void 0),i([bt(),Br(),I(),At("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Bs.prototype,"stepResults",void 0),i([bt(),Br(),I(),At("Holds the task log entries"),n("design:type",Array)],Bs.prototype,"logTail",void 0),i([Br(),Fr(),Je([ne.ASC,ne.DSC]),At("timestamp of creation"),n("design:type",Date)],Bs.prototype,"createdAt",void 0),i([Br(),jr(),Je([ne.ASC,ne.DSC]),At("timestamp of last update"),n("design:type",Date)],Bs.prototype,"updatedAt",void 0),i([Br(),$r(),Je([ne.ASC,ne.DSC]),At("Holds the creator of the task"),n("design:type",String)],Bs.prototype,"createdBy",void 0),i([Br(),Lr(),Je([ne.ASC,ne.DSC]),At("Holds the creator of the task"),n("design:type",String)],Bs.prototype,"updatedBy",void 0),Bs=i([At("Holds the current step when applicable"),_r("tasks"),W(),n("design:paramtypes",[Object])],Bs);let Rs=class extends H{constructor(t){super(t)}};i([q(),At("The status of a step"),n("design:type",String)],Rs.prototype,"status",void 0),i([bt(),At("The result of a successful step"),n("design:type",Object)],Rs.prototype,"output",void 0),i([bt(),At("the error of a failed step"),n("design:type",ks)],Rs.prototype,"error",void 0),Rs=i([W(),n("design:paramtypes",[Object])],Rs);let Ps=class extends H{constructor(t){super(t)}};i([q(),At("task handler type"),n("design:type",String)],Ps.prototype,"classification",void 0),i([nt(1),At("optional task name for ambiguity"),n("design:type",String)],Ps.prototype,"name",void 0),i([At("optional task step input"),bt(),n("design:type",Object)],Ps.prototype,"input",void 0),Ps=i([W(),n("design:paramtypes",[Object])],Ps);class Is extends H{constructor(t){super(t),this.baseMs=1e3,this.jitter=Re.FULL,this.maxMs=6e4,this.strategy=Be.EXPONENTIAL,H.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new d(t);return new Ts(this)}}i([q(),it(1e3),n("design:type",Number)],Is.prototype,"baseMs",void 0),i([q(),tt(Re),n("design:type",String)],Is.prototype,"jitter",void 0),i([at("baseMs"),it(1e3),q(),n("design:type",Number)],Is.prototype,"maxMs",void 0),i([q(),tt(Be),n("design:type",String)],Is.prototype,"strategy",void 0);class $s 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 Is,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=_e.PENDING,this.atomicity=Ie.ATOMIC,this.backoff=new Ts,this.maxAttempts=1,H.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Bs(this)}}i([q(),n("design:type",String)],$s.prototype,"classification",void 0),i([bt(),n("design:type",String)],$s.prototype,"name",void 0),i([q(),n("design:type",String)],$s.prototype,"status",void 0),i([q(),n("design:type",String)],$s.prototype,"atomicity",void 0),i([q(),n("design:type",Ts)],$s.prototype,"backoff",void 0),i([bt(),n("design:type",Object)],$s.prototype,"input",void 0),i([it(1),q(),n("design:type",Number)],$s.prototype,"maxAttempts",void 0);class Ls extends $s{constructor(t){super(t),this.stepResults=[],H.fromModel(this,t),this.atomicity=Ie.COMPOSITE}setAtomicity(t){throw new u("Atomicity locked to "+Ie.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof Ps?t:new Ps(t)),this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Ps({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([X(()=>Ps),n("design:type",Array)],Ls.prototype,"steps",void 0);class Fs extends $t{get type(){if(!this._type){const t=ut.get(this.constructor,je);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),p(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function js(t){return dt.for(je).define({decorator:t=>e=>{const r={type:t};return ut.set(je,t,e),wt(je,r)(e)},args:[t]}).apply()}let Us=class extends Fs{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof ie)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=ie.attr("status").eq(_e.SUCCEEDED).and(ie.attr("updatedAt").lte(t.successfulExpiry)),i=ie.attr("status").eq(_e.FAILED).and(ie.attr("updatedAt").lte(t.failedExpiry)),n=ie.attr("status").eq(_e.CANCELED).and(ie.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(t=>t.id),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([Me(Bs),n("design:type",Object)],Us.prototype,"tasks",void 0),Us=i([js("cleanup-task"),n("design:paramtypes",[])],Us);class Ms{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(M).forEach(t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})})}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch(t=>this.logger.error("Failed to pipe logs",t)).finally(()=>this.history=[]):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Ys(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1}),r.classification){case Pe.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=Y(i),i=i.clear().toString());const s=[i];r===M.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case Pe.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Pe.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=Y(e);switch(e){case _e.SUCCEEDED:s=s.green.bold;break;case _e.RUNNING:s=s.blue.bold;break;case _e.PENDING:s=s.yellow;break;case _e.WAITING_RETRY:s=s.yellow.bold;break;case _e.FAILED:s=s.red.bold;break;case _e.CANCELED:s=s.magenta.bold;break;case _e.SCHEDULED:s=s.cyan;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}function Hs(t,e){const r=e.strategy===Be.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===Re.FULL?Math.floor(Math.random()*s):s}function Gs(t){return new ks({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function qs(t){return new Promise(e=>setTimeout(e,t))}class zs extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=zs.name,Object.setPrototypeOf(this,zs.prototype)}}class Qs extends Pt{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 zs({status:t,...e})}cancel(t,e){this.changeState(_e.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(_e.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(_e.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof ks?t:t instanceof Error?Gs(t):new ks({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class Ws{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ut.tasks();t&&Object.entries(t).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class Vs extends Lt{constructor(){super(...arguments),this.listeners=new Set}observe(t,e){return super.observe(t,e)}unObserve(t){super.unObserve(t)}emit(t,e){this.updateObservers(Ns,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:a}=ee.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 Js(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class Xs extends ${constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class Ks extends Xs{constructor(t,e,r){super(Ks.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class Zs extends Xs{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(Zs.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class ti extends Xs{constructor(t,e,r){super(ti.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class ei extends Xs{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(ei.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class ri{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===Ns||t===H.tableName(Ns))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([_e.SUCCEEDED,_e.FAILED,_e.CANCELED,_e.SCHEDULED])}wait(){return this.awaitStatusTerminal([_e.SUCCEEDED,_e.FAILED,_e.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Ys(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==Pe.LOG)return;const r=(e.payload??[]).map(t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]);await t(r)},Pe.LOG)}pipe(t,e=Pe.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(_e.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(_e.FAILED,t)}onCancel(t){return this.registerStatusHandler(_e.CANCELED,t)}awaitStatusTerminal(t){return new Promise((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===_e.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[_e.SUCCEEDED,_e.CANCELED,_e.FAILED].includes(t)}async track(t,e){if(!t.payload)return;const r=t.payload.status;this.task.status=r,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),r!==_e.SUCCEEDED?(r===_e.FAILED&&this.fail(),r===_e.CANCELED&&this.cancel(t),r===_e.WAITING_RETRY&&this.retry(),r===_e.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,Pe.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Pe.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new Pt),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===_e.SUCCEEDED&&(e.output=this.task.output),t!==_e.FAILED&&t!==_e.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 Ns({classification:Pe.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case _e.FAILED:return new Ks(this.task.id,e,r);case _e.CANCELED:return new ti(this.task.id,e,r);case _e.WAITING_RETRY:return new Zs(this.task.id,e,r);case _e.SCHEDULED:return new ei(this.task.id,e,r);default:return new Ks(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case _e.CANCELED:return _e.CANCELED;case _e.WAITING_RETRY:return _e.WAITING_RETRY;case _e.SCHEDULED:return _e.SCHEDULED;case _e.FAILED:return _e.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===_e.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[Pe.ALL]?[...this.pipes[Pe.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 si extends $t{get Context(){return Qs}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,Bs,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,Ns,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(t,e){const r=new Qs(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new ot,this.running=!1;const e=Object.assign({},Ue.autoShutdown,t.autoShutdown);this.config=Object.assign({},Ue,t,{autoShutdown:e,bus:t.bus||new Vs,registry:t.registry||new Ws}),this.idleDelayMs=this.config.pollMsIdle}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,o.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 ri(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=_e.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,o.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 ri(this.bus,i)}}async ensureTaskError(t,e){if(![_e.FAILED,_e.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await qs(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===_e.SUCCEEDED||s.status===_e.FAILED)return s;s.status=_e.CANCELED;const i=new ks({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,_e.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,Ct.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||r.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(ie.attr("status").eq(_e.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 qs(Math.max(a,0))}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=ie.attribute("status").eq(_e.PENDING),i=ie.attribute("status").eq(_e.WAITING_RETRY).and(ie.attribute("nextRunAt").lte(r)),n=ie.attribute("status").eq(_e.RUNNING).and(ie.attribute("leaseExpiry").lte(r)),a=ie.attribute("status").eq(_e.SCHEDULED).and(ie.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{}const n=new Bs({...i,status:_e.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=this;let i=Promise.resolve();const n=new Qs(e).accumulate({taskId:t.id,logger:new Ms(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{}}}});await this.emitStatus(n,t,_e.RUNNING);try{let e;if(t.atomicity===Ie.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(r.debug(`handler type for ${t.id} is ${s?.constructor?.name??"none"}`),!s)throw new u("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=_e.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,_e.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 zs)return void await this.handleTaskStateChange(e.request,t,n);if(r.error("task execution error",e),t.atomicity===Ie.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===_e.FAILED);0>r||(t.currentStep=r)}}const s=(t.attempt??0)+1,i=Gs(e);if(s<t.maxAttempts){const a=Hs(s,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+a);t.attempt=s,t.status=_e.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(M.warn,"Retry scheduled",{nextRunAt:o,delayMs:a,attempt:s}),await this.emitStatus(n,t,_e.WAITING_RETRY,i,e)}else{t.attempt=s,t.status=_e.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(M.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(n,t,_e.FAILED,i,e)}}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case _e.CANCELED:{const s=t.error??new ks({message:`Task ${e.id} canceled`});return e.status=_e.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,_e.CANCELED,s),void await r.pipe(M.warn,"Task canceled via context")}case _e.WAITING_RETRY:{const s=(e.attempt??0)+1,i=Hs(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),a=t.error??new ks({message:`Task ${e.id} requested retry`});return e.status=_e.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,_e.WAITING_RETRY,a),void await r.pipe(M.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case _e.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new ks({message:`Task ${e.id} rescheduled`});return e.status=_e.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,_e.SCHEDULED,s),void await r.pipe(M.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new u("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),a=(t,s)=>{e.cacheResult(t,s),r instanceof Qs&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===_e.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 r=s[i],o=this.registry.get(r.classification);if(!o)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([M.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await o.run(r.input,e);await e.flush();const l=i,u=new Date;n[l]=new Rs({status:_e.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;a(r.classification,c),a(d,c),i=l+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:c})}catch(e){const r=new Date;n[i]=new Rs({status:_e.FAILED,error:Gs(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=Gs(e);const s=await this.tasks.update(t);throw Object.assign(t,s),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Ts)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Ts(e)}normalizeSteps(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map(t=>{if(t instanceof Ps)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Ps(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 Rs)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Rs(e)}):[]}async appendLog(t,e,r){const s=Array.isArray(r)&&Array.isArray(r[0]),i=e.atomicity===Ie.COMPOSITE?t instanceof Qs?t.step??e.currentStep:e.currentStep:void 0,n=(s?r:[r]).map(([t,e,r])=>new _s({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 Qs&&await t.flush();const n={status:r};s&&s instanceof ks?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,Pe.STATUS,n),o=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new Ns({...a,payload:o});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Pe.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,Pe.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Ns({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,Bs,...r)}}class ii extends bs{constructor(){super(Ns)}get repo(){return this._repository||(this._repository=os.get(Bs).events),this._repository}}class ni extends cs{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 Pt)throw new u("No/invalid config provided");if(!e.adapter)throw new u("No adapter provided");return{client:new(e.engine||si)(e),config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,o.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,o.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,o.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,c.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,o.DELETE,!0)).for(this.delete);return this.tasks.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.tasks.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.QUERY,!0)).for(this.query),s=this.tasks?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.tasks,r)}async update(t,...e){throw new Ft("Updates to tasks are not available")}async updateAll(t,...e){throw new Ft("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,Ot.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,Ot.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Ct.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,Ct.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...e),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(r),s.verbose("gracefully shutdown task runner")}}function ai(t={count:1},e=0){return function r(s,i,n){return pt(gt(ut.key(Ct.THROTTLE,i),t),(s,i,n)=>{n.value=new Proxy(n.value,{async apply(s,n,a){const o=a,c=(()=>{try{return"function"==typeof t?t(...o):t}catch(t){throw new u("Failed to obtain throttling configuration from handler: "+t)}})(),{log:l,ctx:d}=(await n.logCtx(a,Ct.THROTTLE,!0)).for(r),h=(t=>{const e=(Array.isArray(t)?t:[t]).map(t=>{if(!Number.isFinite(t)||0>t)throw new u("@throttling() argument indexes must be non-negative integers");return t});return Array.from(new Set(e)).sort((t,e)=>t-e)})(e);if(!h.length)throw new u("@throttling() expects at least one argument index to throttle");h.forEach(t=>{if(t>=o.length)throw new u(`@throttling() requires argument index ${t} but only ${o.length} provided`);if(!Array.isArray(o[t]))throw new u(`@throttling() expects argument at index ${t} to be an array`)});const p=h.map(t=>o[t]),g=p[0].length;if(!p.every(t=>t.length===g))throw new u("@throttling() requires all targeted arguments to have the same length");if(0===g)return s.apply(n,o);const f=((t,e,r)=>{if("count"in r){if(0>=r.count)throw new u("@throttling() configuration 'count' must be greater than zero");const e=[];for(let s=0;t>s;s+=r.count)e.push({start:s,end:Math.min(t,s+r.count)});return e}if("bufferSize"in r){if(0>=r.bufferSize)throw new u("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let a=0;t>a;a++){const t=oi(e,a);n>0&&n+t>r.bufferSize?(s.push({start:i,end:a}),i=a,n=t):n+=t}return i>=t&&s.length||s.push({start:i,end:t}),s}return[{start:0,end:t}]})(g,p,c),y=f.map(({start:t,end:e})=>o.map((r,s)=>{const i=h.indexOf(s);return-1===i?r:p[i].slice(t,e)})),m=d.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const t of y){try{ci(await s.apply(n,t),w)}catch(t){if(m)throw t;b.push(t)}c.delayMs&&await new Promise(t=>setTimeout(t,c.delayMs))}if(b.length){l.warn(`${i+""} throttled execution continued with ${b.length} failure(s)`);const t=new AggregateError(b,`Throttled ${i+""} failed for ${b.length} chunk(s)`);throw t.results=w,t}return w}})})(s,i,n)}}function oi(t,e){return t.reduce((t,r)=>t+(t=>{if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}})(r[e]),0)}function ci(t,e){Array.isArray(t)?e.push(...t):void 0!==t&&e.push(t)}i([us(),n("design:type",Function),n("design:paramtypes",[Bs,void 0]),n("design:returntype",Promise)],ni.prototype,"create",null),i([us(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ni.prototype,"createAll",null),i([ps(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ni.prototype,"delete",null),i([ps(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ni.prototype,"deleteAll",null),i([ds(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ni.prototype,"read",null),i([ds(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ni.prototype,"readAll",null),i([ds(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],ni.prototype,"query",null),i([hs(),n("design:type",Function),n("design:paramtypes",[Bs,void 0]),n("design:returntype",Promise)],ni.prototype,"update",null),i([hs(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ni.prototype,"updateAll",null),e.setRegistry(new Fe);const li="##VERSION##",ui="##PACKAGE##";ut.registerLibrary(ui,li);export{$t as AbsContextual,ee as Adapter,Jt as AdapterTransaction,He as AuthKeys,kr as AuthorizationError,Be as BackoffStrategy,Jr as BaseModel,Ve as BigIntSequence,ae as Cascade,Us as CleanUpTask,cs as ClientBasedService,Ls as CompositeTaskBuilder,ie as Condition,Dr as ConnectionError,Pt as Context,Xt as ContextLock,It as ContextualLoggedClass,kt as DefaultAdapterFlags,oe as DefaultCascade,Tt as DefaultContextFlags,Ee as DefaultRepositoryFilters,Qe as DefaultSequenceOptions,Ue as DefaultTaskEngineConfig,vs as Dispatch,Nr as ForbiddenError,St as GroupOperator,Fe as InjectablesRegistry,Re as JitterStrategy,ue as MethodQueryBuilder,jt as MigrationError,Ut as MigrationRuleError,bs as ModelService,Bt as MultipleSelectOperationKeys,Dt as NonTransactionOperationKeys,ze as NoneSequenceOptions,We as NumericSequence,Ye as ObserverError,Lt as ObserverHandler,Et as Operator,ce as OperatorsMap,ne as OrderDirection,ui as PACKAGE_NAME,Rt as PaginationOperationKeys,Kr as Paginator,se as PagingError,Ct as PersistenceKeys,Cs as PersistenceService,Ot as PreparedStatementKeys,xt as QueryClause,re as QueryError,$e as Repository,_t as SelectOperationKeys,Es as Sequence,Xr as SequenceModel,Vt as Serial,os as Service,as as Statement,Is as TaskBackoffBuilder,Ts as TaskBackoffModel,$s as TaskBuilder,ti as TaskCancelError,Qs as TaskContext,Xs as TaskControlError,si as TaskEngine,ks as TaskErrorModel,Vs as TaskEventBus,Ns as TaskEventModel,ii as TaskEventService,Pe as TaskEventType,Ks as TaskFailError,Fs as TaskHandler,Ws as TaskHandlerRegistry,Ds as TaskIOSerializer,_s as TaskLogEntryModel,Ms as TaskLogger,Bs as TaskModel,ei as TaskRescheduleError,Zs as TaskRetryError,ni as TaskService,_e as TaskStatus,Rs as TaskStepResultModel,Ps as TaskStepSpecModel,ri as TaskTracker,Ie as TaskType,je as TasksKey,Nt as TransactionOperationKeys,Wt as UUID,Ft as UnsupportedError,li as VERSION,Ge as allowIf,ge as applyViewDecorator,fs as auth,qe as blockIf,Er as cacheModelForPopulate,Or as cascadeDelete,Br as column,Hs as computeBackoffMs,us as create,nr as createOrUpdate,Fr as createdAt,$r as createdBy,Ir as createdByOnCreateUpdate,de as defaultQueryAttr,ps as del,Le as generateInjectableNameForRepository,Ss as getAdapterTransaction,wr as getAndConstructJunctionTable,Os as getContextLock,Se as getFilters,Ys as getLogPipe,Ur as getPkTypes,Ar as getPopulateKey,xr as getTagForDeleteKey,Je as index,Mt as injectableServiceKey,qt as isOperationBlocked,Js as isTaskError,Gr as manyToMany,yr as manyToManyOnCreate,vr as manyToManyOnDelete,br as manyToManyOnUpdate,Hr as manyToOne,hr as manyToOneOnCreate,fr as manyToOneOnDelete,gr as manyToOneOnUpdate,qr as noValidateOn,zr as noValidateOnCreate,Wr as noValidateOnCreateUpdate,Qr as noValidateOnUpdate,zt as normalizeImport,Yr as oneToMany,lr as oneToManyOnCreateUpdate,dr as oneToManyOnDelete,ur as oneToManyOnUpdate,Mr as oneToOne,ar as oneToOneOnCreate,cr as oneToOneOnDelete,or as oneToOneOnUpdate,Ae as onlyOnBulk,ye as onlyOnCreate,we as onlyOnDelete,xe as onlyOnFilter,ve as onlyOnSingle,be as onlyOnTransactional,me as onlyOnUpdate,sr as pk,er as pkDec,tr as pkOnCreate,Sr as populate,Qt as prefixMethod,he as prepared,Yt as promiseSequence,pe as query,ds as read,Vr as relation,Me as repository,Tr as repositoryFromTypeMetadata,te as resolveBulkSequenceResult,ys as roles,ms as route,ir as sequence,rr as sequenceDec,Gs as serializeError,gs as service,qs as sleep,_r as table,js as task,ai as throttle,Pr as unique,Rr as uniqueOnCreateUpdate,hs as update,jr as updatedAt,Lr as updatedBy,xs as uuid,As as uuidCreateUpdateHandler,pr as validBidirectionalRelation,fe as view};
1
+ import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,OperationKeys as o,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as h,wrapMethodWithContext as p,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,readonly as v,onCreate as A,generated as x,onUpdate as E,BadRequestError as O,timestamp as C,onCreateUpdate as T,ConflictError as k,version as N,afterAny as D,onDelete as _,SerializationError as B,prefixMethod as R,composed as I,transient as P,serialize as $,BaseError as L}from"@decaf-ts/db-decorators";import{Logging as F,LoggedClass as j,final as U,toCamelCase as M,LogLevel as Y,style as q}from"@decaf-ts/logging";import{Model as G,hashObj as H,required as z,sf as Q,isEqual as W,model as V,ValidationKeys as J,type as X,async as Z,list as tt,option as et,date as rt,JSONSerializer as st,ModelKeys as it,min as nt,minlength as at,gt as ot}from"@decaf-ts/decorator-validation";import{Lock as ct,MultiLock as lt,TransactionalKeys as ut}from"@decaf-ts/transactional-decorators";import{Metadata as dt,Decoration as ht,DefaultFlavour as pt,apply as gt,methodMetadata as ft,propMetadata as yt,DecorationKeys as mt,uses as wt,metadata as bt,prop as vt,method as At,description as xt}from"@decaf-ts/decoration";var Et,St,Ot,Ct,Tt;(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"})(Et||(Et={})),(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"})(St||(St={})),(t=>{t.AND="AND",t.OR="OR"})(Ot||(Ot={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy",t.FIND="find",t.PAGE="page",t.COUNT_OF="countOf",t.MAX_OF="maxOf",t.MIN_OF="minOf",t.AVG_OF="avgOf",t.SUM_OF="sumOf",t.DISTINCT_OF="distinctOf",t.GROUP_OF="groupOf"})(Ct||(Ct={})),(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 kt=Object.assign({},{ignoreDevSafeGuards:!1}),Nt=Object.assign({},a,{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}),Dt=[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],_t=[o.READ,c.READ_ALL],Bt=[Tt.STATEMENT,Ct.FIND_ONE_BY],Rt=[Tt.QUERY,Ct.PAGE_BY,Ct.LIST_BY,Ct.FIND_BY,Ct.FIND,Ct.PAGE],It=[Ct.PAGE_BY,Ct.PAGE];class Pt extends l{constructor(t){super(t)}static{this.factory=t=>(new Pt).accumulate(Object.assign({},t,{timestamp:new Date,logger:t.logger||F.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||F.get()}))}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t,e=new Set){if(e.has(this))return;e.add(this);const r=this.getOrUndefined(t);if(null!=r)return r;let s=this.getOrUndefined("childContexts");if(s&&s.length&&(s=s.filter(t=>!e.has(t)),s.length)){const r=s.map(r=>r.getFromChildren(t,e)).reduce((t,e)=>(Array.isArray(e)?t.push(...e):null!=e&&t.push(e),t),[]).filter(t=>null!=t);if(!r.length)return;return r.some(t=>"object"!=typeof t)?r[0]:r.reduce((t,e)=>Object.assign(t,e),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce((t,e)=>(t[e]=this.get(e),t),{})}accumulate(t){return super.accumulate(t)}}class $t extends j{logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||F.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 Pt||(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 u("No context provided");if(a&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t))}}class Lt extends $t{constructor(){super(),this._Context=Pt}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 Pt||(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 Ft{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=$t.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter: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 u{constructor(t){super(t,jt.name,500)}}class Ut extends u{constructor(t,e=Ut.name){super(t,e,500)}}class Mt extends Ut{constructor(t){super(t,Mt.name)}}function Yt(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):dt.Symbol(dt.constr(t)).toString().replaceAll(".","-")}async function qt(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 Gt=[o.CREATE,o.READ,o.UPDATE,o.DELETE];function Ht(t){return Gt.includes(t)}function zt(t,e,r){const s=dt.get(t,o.REFLECT+o.BLOCK)||{};if(!s?.handler)return!1;const i=void 0===r&&Ht(e)?"crud":e,n=void 0===r&&Ht(e)?e:r,a=s.args?.[0]||[];return s.handler(a,i,n)??!1}async function Qt(t){return t.then(t=>t.default||t)}function Wt(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 Mt)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 Vt{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 Vt._instance||(Vt._instance=new Vt),Vt._instance}}class Jt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return Jt._instance||(Jt._instance=new Jt),Jt._instance}}class Xt{constructor(t,...e){this.adapter=t}async begin(...t){}async commit(...t){}async rollback(...t){}}class Kt extends ct{constructor(t){super(),this.adapterTransaction=t,this.acquireCount=0,this.lock=new ct}async acquire(...t){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...t)):this.lock.release()}async release(...t){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...t)}catch(e){await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+e),...t)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(t,...e){await this.lock.acquire();try{await this.adapterTransaction.rollback(new u("Failed to submit transaction: "+t),...e)}catch(t){throw new u("Failed to rollback transaction: "+t)}finally{this.lock.release()}}}const Zt=ht.flavourResolver.bind(ht);ht.flavourResolver=t=>{try{const e=Zt(t);if(e&&e!==pt)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof dt.registeredFlavour?dt.registeredFlavour(r):void 0;if(s&&s!==pt)return s;const i=re._currentFlavour;if(i){const t=re._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return pt}};const te=Symbol("AdapterProxyCleanup");function ee(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 re extends Lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!re._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return re._baseRepository}transactionLock(...t){return new Xt(this,...t)}async shutdownProxies(t,...e){t&&"string"!=typeof t&&(e=[t,...e],t=void 0);const{log:r}=this.logCtx(e,this.shutdownProxies);if(!this.proxies)return;if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);const s=async t=>{if(!t)return;const e=t[te];"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 u("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 ct,this.alias in re._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);re._cache[this.alias]=this,this.alias!==this.flavour&&(re._cache[this.flavour]=this),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),re._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),re._currentFlavour=this.alias)}Dispatch(){return new re._baseDispatch}ObserverHandler(){return new Ft}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new re._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?""+G.tableName(i):"";r.correlationId=r.correlationId||`${n}|${t}|${Vt.instance.generate()}`;const a=r.logger||F.for(this),o=Object.assign({},Nt.cacheForPopulate,r.cacheForPopulate);return Object.assign({},Nt,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,cacheForPopulate:o,args:s,writeOperation:Dt.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?dt.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:a})}get Context(){return Pt}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=>G.tableName(t)):G.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 Pt||(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=G.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`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[G.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),o=G.pk(e),c=new e;c[o]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[Tt.METADATA],d=Object.keys(c).filter(t=>t!==o).reduce((r,s)=>(r[s]=t[G.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 d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,Tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const a=G.tableName(t);i.debug(`Creating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0})));return ee(o?await qt(l,!0):await qt(l),o,i,c.CREATE_ALL)}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=G.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 ee(a?await qt(o,!0):await qt(o),a,s,c.READ_ALL)}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const a=G.tableName(t);i.debug(`Updating ${e.length} entries ${a} table`);const o=!(n.get("breakOnSingleFailureInBulk")??1),l=e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0})));return ee(o?await qt(l,!0):await qt(l),o,i,c.UPDATE_ALL)}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${e.length} entries from ${t} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),a=e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0})));return ee(n?await qt(a,!0):await qt(a),n,s,c.DELETE_ALL)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.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 u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),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(t){return dt.flavourOf(t)}static get currentFlavour(){if(!re._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return re._currentFlavour}static get current(){return re.get(this.currentFlavour)}static unregister(t){if(!t)return;const e=re._cache[t];e&&(delete re._cache[t],re._currentFlavour===t&&(re._currentFlavour=void 0),e.flavour&&re._cache[e.flavour]&&re._cache[e.flavour]===e&&delete re._cache[e.flavour])}static get(t){if(!t)return re.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return dt.flavouredAs(t).filter(G.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${H(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return Reflect.defineProperty(i,te,{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 dt.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,Pt]),n("design:returntype",Promise)],re.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],re.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],re.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],re.prototype,"client",null);class se extends u{constructor(t){super(t,se.name,500)}}class ie extends u{constructor(t){super(t,ie.name,500)}}class ne extends G{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):G.fromModel(this,t)}and(t){return ne.and(this,t)}or(t){return ne.or(this,t)}not(t){return new ne(this,St.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof ne)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(St).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===St.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 ne){if(!(this.comparison instanceof ne)&&this.operator!==St.NOT)return{comparison:{condition:t}};if(-1===Object.values(Ot).indexOf(this.operator)&&this.operator!==St.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 ne.group(t,Ot.AND,e)}static or(t,e){return ne.group(t,Ot.OR,e)}static group(t,e,r){return new ne(t,e,r)}static attribute(t){return(new ne.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(St.EQUAL,t)}dif(t){return this.setOp(St.DIFFERENT,t)}gt(t){return this.setOp(St.BIGGER,t)}lt(t){return this.setOp(St.SMALLER,t)}gte(t){return this.setOp(St.BIGGER_EQ,t)}lte(t){return this.setOp(St.SMALLER_EQ,t)}in(t){return this.setOp(St.IN,t)}regexp(t){return this.setOp(St.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(St.STARTS_WITH,t)}endsWith(t){return this.setOp(St.ENDS_WITH,t)}between(t,e){return this.setOp(St.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new ne(this.attr1,this.operator,this.comparison)}catch(t){throw new se(t)}}}}static builder(){return new ne.Builder}static from(t){return new ne(t)}}var ae,oe;i([z(),n("design:type",Object)],ne.prototype,"attr1",void 0),i([z(),n("design:type",String)],ne.prototype,"operator",void 0),i([z(),n("design:type",Object)],ne.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(ae||(ae={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(oe||(oe={}));const ce={update:oe.CASCADE,delete:oe.NONE},le={Equals:(t,e)=>ne.attribute(t).eq(e),Diff:(t,e)=>ne.attribute(t).dif(e),LessThan:(t,e)=>ne.attribute(t).lt(e),LessThanEqual:(t,e)=>ne.attribute(t).lte(e),GreaterThan:(t,e)=>ne.attribute(t).gt(e),GreaterThanEqual:(t,e)=>ne.attribute(t).gte(e),In:(t,e)=>ne.attribute(t).in(e),Matches:(t,e)=>ne.attribute(t).regexp(e)},ue=t=>t.charAt(0).toLowerCase()+t.slice(1);class de extends j{static get log(){return this._logger||(this._logger=F.for(de.name)),this._logger}static{this.prefixMap={[Et.FIND_BY]:"find",[Et.PAGE_BY]:"page",[Et.COUNT_BY]:"count",[Et.SUM_BY]:"sum",[Et.AVG_BY]:"avg",[Et.MIN_BY]:"min",[Et.MAX_BY]:"max",[Et.DISTINCT_BY]:"distinct",[Et.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?ue(i):void 0}static extractCore(t,e=Et.FIND_BY){const r=t.substring(e.length);if(e!==Et.FIND_BY&&e!==Et.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||Et.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(Et.SELECT);if(-1===e)return;const r=t.substring(e+Et.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(Et.AND).map(ue).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(Et.GROUP_BY);if(-1!==e)return t.substring(e+Et.GROUP_BY.length).split(Et.ORDER_BY)[0].split(Et.THEN_BY).map(ue).filter(Boolean);const r=this.getActionFromMethodName(t);if("group"===r?.action){const e=t.substring(r.prefix.length),s=e.indexOf(Et.THEN_BY);if(-1===s)return;const i=e.substring(s+Et.THEN_BY.length).split(Et.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(ue(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?le[a]:le.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]===Et.AND?n.and(l):n.or(l)}),n}static parseFieldAndOperator(t){for(const e of Object.keys(le))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:ue(r),operator:e}}return{field:ue(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=de.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new se("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(ae).includes(e))throw new se(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(ae).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 l&&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 he(){return(t,e)=>{const r=dt.key(Tt.DEFAULT_QUERY_ATTR);let s=dt.get(t.constructor,r)||[];return s=[...new Set([...s,e])],gt(yt(r,s))(t,e)}}function pe(){return ht.for(Tt.STATEMENT).define({decorator:()=>(t,e,r)=>gt(ft(dt.key(Tt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function ge(t={}){return ht.for(Tt.QUERY).define({decorator:t=>(e,r,s)=>{const i=de.getFieldsFromMethodName(r);return gt(ft(dt.key(Tt.QUERY,r),{...t,fields:i}),pe(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{action:i,select:n,selector:a,where:o,groupBy:c,orderBy:l,limit:u,offset:d}=de.build(e.name,...s),h=r;let p;switch(i){case"find":case"page":p=h.select(n);break;case"count":p=h.count(a);break;case"sum":p=h.sum(a);break;case"avg":p=h.avg(a);break;case"min":p=h.min(a);break;case"max":p=h.max(a);break;case"distinct":p=h.distinct(a);break;case"group":p=h.select(),a&&(p=p.groupBy(a));break;default:throw new se("Unsupported action: "+i)}if(o&&(p=p.where(o)),c&&c.length>0&&"group"!==i){p=p.groupBy(c[0]);for(let t=1;t<c.length;t++)p=p.thenBy(c[t])}else if(c&&c.length>0&&"group"===i)for(const t of c)p=p.thenBy(t);const{allowLimit:g,allowOffset:f,allowOrderBy:y,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},w=[{key:"orderBy",value:(l||[])[0],allowed:y},{key:"limit",value:u,allowed:g},{key:"offset",value:d,allowed:f}];for(const t of w)if(void 0!==t.value){if(!t.allowed&&m)throw new se(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(p=p[t.key](t.value))}if("page"===i){const t=s[s.length-1],e="number"==typeof t?t:t?.limit??10;return p.paginate(e)}return p.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function fe(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(dt.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),a=dt.key(t,i,n),o={...r||{},kind:e,attribute:i};return yt(a,o)(s,i)}}function ye(t){return ht.for(St.VIEW).define({decorator:t=>fe(St.VIEW,"view",t),args:[t]}).apply()}function me(t){return Ee(t,[o.CREATE,c.CREATE_ALL])}function we(t){return Ee(t,[o.UPDATE,c.UPDATE_ALL])}function be(t){return Ee(t,[o.DELETE,c.DELETE_ALL])}function ve(t){return Ee(t,Dt)}function Ae(t){return Ee(t,Object.values(o))}function xe(t){return Ee(t,Object.values(c))}function Ee(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:a}=$t.prototype.logCtx(n,Ee);return a.silly(`filtering ${s} event for${r?" "+(G.tableName(r)||r):""} ${i}`),("string"==typeof r?r===G.tableName(t)||r===t.constructor.name:dt.constr(t)===dt.constr(r))&&e.includes(s)}}const Se={onlyOnCreate:me,onlyOnUpdate:we,onlyOnDelete:be,onlyOnTransactional:ve,onlyOnSingle:Ae,onlyOnBulk:xe};function Oe(t){const e=Object.assign({},Se);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}var Ce,Te,ke,Ne,De,_e,Be,Re,Ie,Pe,$e;class Le extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new u("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=G.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return Oe(this)}constructor(t,e,r=!1,...s){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},t&&(this._adapter=t),e&&(Le.register(e,this,this.adapter.alias,r),t)&&dt.get(e,mt.FLAVOUR)===pt&&wt(t.flavour)(e);const i=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;p(i,i[e+"Prefix"],t,i[e+"Suffix"])}),g(i,i[this.updateAll.name+"Prefix"],this.updateAll,i[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 Ft}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.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 f(this,r,t,o.CREATE,o.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 d(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${G.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 ${G.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,c.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 l=G.sequenceFor(t[0]);let h=[];if(G.generatedBySequence(this.class)?(l.name||(l.name=G.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l,this._overrides)).range(t.length,...s)):G.generated(this.class,this.pk)||(h=t.map((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?h[e]:""+t[this.pk]),n||await f(this,r,t,o.CREATE,o.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=y(s);if(n)throw new d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.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 f(this,r,a,o.READ,o.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 ${G.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,o.READ,o.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 ${G.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 ${G.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,o.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${a}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=G.merge(l,t,this.class))),n||await f(this,r,t,o.UPDATE,o.ON,l),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${G.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${a}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let h;if(r.get("applyUpdateValidation")&&(h=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>G.merge(h[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,o.UPDATE,o.ON,h?h[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(h[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new d(n)}return[t,...s,h]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,o.DELETE,o.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 ${G.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map(async t=>f(this,r,t,o.DELETE,o.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 ${G.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=ae.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 ${G.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 se("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 ${G.tableName(this.class)} with page size ${a}`),n&&c.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===ae.ASC?this.attr(G.pk(this.class)).gt(n):this.attr(G.pk(this.class)).lt(n))()).orderBy([t,e]).paginate(a,...l);else{if(!i)throw new se("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,...l);return u.serialize(d)}async find(t,e=ae.ASC,...r){if("string"!=typeof t)throw new se("Find value must be a string");const s=this.getDefaultQueryAttributes(),i=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:a}=(await this.logCtx(r,Ct.FIND,!0)).for(this.find);return n.verbose(`finding ${G.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(i).orderBy([s[0],e]).execute(...a)}async page(t,e=ae.ASC,r={offset:1,limit:10},...s){if("string"!=typeof t)throw new se("Page value must be a string");const i=r.offset||1,{offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new se("PaginateBy needs a page or a bookmark");const c=this.getDefaultQueryAttributes(),l=this.buildDefaultStartsWithCondition(t,c),{log:u,ctx:d,ctxArgs:h}=(await this.logCtx(s,Ct.PAGE,!0)).for(this.page);u.verbose(`paging ${G.tableName(this.class)} by default attributes ${c.join(", ")}`);const p=o??10,g=c[0],f=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let y;if(a&&d.get("paginateByBookmark")){const t=G.pk(this.class),r=e===ae.ASC?this.attr(t).gt(a):this.attr(t).lt(a);y=await f.select().where(l.and(r)).orderBy([g,e]).paginate(p,...h)}else{if(!n)throw new se("PaginateBy needs a page or a bookmark");y=await f.select().where(l).orderBy([g,e]).paginate(p,...h)}const m=await y.page(i,a,...h);return y.serialize(m)}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 ${G.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,Ct.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${G.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async countOf(t,...e){const{log:r,ctxArgs:s}=(await this.logCtx(e,Ct.COUNT_OF,!0)).for(this.countOf);return r.verbose(`counting ${G.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 ${G.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 ${G.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 ${G.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 ${G.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 ${G.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 ${G.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...e){if(!Le.statements(this,t))throw new se("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=G.defaultQueryAttributes(this.class);if(!t||!t.length)throw new se("No default query attributes defined for "+G.tableName(this.class));return t}buildDefaultStartsWithCondition(t,e){if("string"!=typeof t)throw new se("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 se("No default query attributes available for "+G.tableName(this.class));return r}attr(t){return ne.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:dt.constr(t)===dt.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>re._baseSequence.parseValue(G.sequenceFor(this.class).type,t)):re._baseSequence.parseValue(G.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||dt.flavourOf(t)||re.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}const n="function"==typeof s?s:void 0,a=e||dt.flavourOf(t)||n&&dt.get(n,Tt.ADAPTER)||re.currentFlavour,o=a?re.get(a):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+a);if(s instanceof Le)return s;const c=[G.tableName(t),o.alias].join(w),l=n||o.repository();return delete this._cache[c],new l(o,t,...r)}static get(t,e){const r=G.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r,s=!1){let i=G.tableName(t);if(r&&(i=[i,r].join(w)),i in this._cache&&this._cache[i]instanceof Le&&!s)throw new u(i+" already has a registered instance");this._cache[i]=e}static statements(t,e){const r=t instanceof Le?t.constructor:t,s=dt.get(r,e?dt.key(Tt.STATEMENT,e):Tt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Le?t.constructor:t;return dt.get(r,e?dt.key(Tt.QUERY,e):Tt.QUERY)}}function Fe(t,e){if(!(e||(e=ht.flavourResolver(t instanceof G?t.constructor:t))&&e!==pt))throw new u("Could not retrieve flavour from model "+(t instanceof G?t.constructor.name:t.name));return Q(Tt.INJECTABLE,e,G.tableName(t))}i([pe(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Le.prototype,"listBy",null),i([pe(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],Le.prototype,"paginateBy",null),i([pe(),n("design:type",Function),n("design:paramtypes",[String,String,void 0]),n("design:returntype",Promise)],Le.prototype,"find",null),i([pe(),n("design:type",Function),n("design:paramtypes",[String,String,Object,void 0]),n("design:returntype",Promise)],Le.prototype,"page",null),i([pe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Le.prototype,"findOneBy",null),i([pe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Le.prototype,"findBy",null),i([pe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Le.prototype,"countOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ce="undefined"!=typeof K&&K)?Ce:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"maxOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Te="undefined"!=typeof K&&K)?Te:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"minOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ke="undefined"!=typeof K&&K)?ke:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"avgOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ne="undefined"!=typeof K&&K)?Ne:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"sumOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(De="undefined"!=typeof K&&K)?De:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"distinctOf",null),i([pe(),n("design:type",Function),n("design:paramtypes",["function"==typeof(_e="undefined"!=typeof K&&K)?_e:Object,void 0]),n("design:returntype",Promise)],Le.prototype,"groupOf",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Le.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Le.prototype,"unObserve",null),re&&(re._baseRepository=Le);class je extends t{get log(){return this.logger||(this.logger=F.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=G.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=G.get(t.toString())),!n)return;const a=Tt.ADAPTER,o=r||dt.get(n,a)||dt.flavourOf(n);try{let t=o;try{o&&re.get(o)}catch{const e=re.current;e&&e.flavour===o&&(t=e.alias)}if(i=Le.forModel(n,t),i instanceof Le)return i;const r=o||dt.get(i.constructor,a)||dt.get(n,a);e.register(i,Fe(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=Le.get(n,o);if("function"==typeof e){const t=o?re.get(o):re.current;if(!t)return;return new e(t,n)}}}return i}}(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(Be||(Be={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(Re||(Re={})),(t=>{t.NONE="none",t.FULL="full"})(Ie||(Ie={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(Pe||(Pe={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})($e||($e={}));const Ue="tasks",Me={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};function Ye(t,e){return(i,n)=>n?r(dt.constr(t))(i,n):(dt.set(b.REPOSITORY,dt.key(e||re.currentFlavour,G.tableName(t)),i),bt(b.REPOSITORY,i.name)(t),e=e||dt.get(i.constructor,Tt.ADAPTER),Le.register(t,i),s(dt.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}dt.tasks=(()=>dt.innerGet(Symbol.for(Ue))).bind(dt),dt.taskFor=(t=>{const e=dt.tasks();return e?e[t]:void 0}).bind(dt),dt.validationExceptions=((t,e)=>{const r=dt.get(t,Tt.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==o.CREATE&&e!==o.UPDATE||(i=G.nestedRelations(t)),[...new Set([...s,...i])]}).bind(dt),dt.migrationsFor=(t=>{if(!(t=t??re.current))throw new u("Could not get adapter for migrations");return dt.innerGet(Symbol.for(Tt.MIGRATION),t.alias).map(t=>t.class)}).bind(dt),dt.migrations=(()=>{const t=dt.innerGet(Symbol.for([Tt.MIGRATION,Tt.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(dt),dt.relations=((t,e)=>{const r=dt.get(t,Tt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(dt),G.relations=(t,e)=>dt.relations(t instanceof G?t.constructor:t,e)||[],G.nestedRelations=((t,e=[])=>{let r=[];const s=dt.get(t,Tt.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&G.relations(i.class)){const s=G.relations(i.class).map(e=>`${t}.${e}`);e=[...e,...s],r=G.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(G),G.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!G.sequenceFor(r).generated}).bind(G),G.fromTable=(t=>{const e=dt.innerGet(Symbol.for(Tt.TABLE));if(!e||!e[t]||!G.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return G.get(e[t].name)}).bind(G),dt.createdBy=(t=>{const e=dt.get("function"!=typeof t?t.constructor:t,Tt.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(dt),dt.updatedBy=(t=>{const e=dt.get("function"!=typeof t?t.constructor:t,Tt.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(dt),G.tableName=t=>{if(!(t instanceof G?G.get(t.constructor.name):t))throw new u("Unable to find model "+t);return dt.get(t instanceof G?t.constructor:t,Tt.TABLE)||(t instanceof G?t.constructor.name:t.name)},G.columnName=(t,e)=>dt.get(t instanceof G?t.constructor:t,dt.key(Tt.COLUMN,e))||e,G.defaultQueryAttributes=(t,e=!1)=>{const r="function"==typeof t?t:t.constructor;return dt.get(r,dt.key(Tt.DEFAULT_QUERY_ATTR))||(e?[G.pk(t)]:[])},G.sequenceName=(t,...e)=>[G.tableName(t),...e].join("_"),G.versionOf=(t=>{const e=dt.get(t.constructor),r=e?.[Tt.PERSISTENT_VERSION],s=r&&"object"==typeof r?Object.keys(r)[0]:void 0,i=e?.[b.VERSION],n=i&&"object"==typeof i?Object.keys(i)[0]:void 0,a=s??n;if(!a)throw new u("No version found for "+t.constructor.name);const o=t[a];if("number"!=typeof o||1>o)throw new u("Invalid version number: "+o);return o}).bind(G),G.sequenceFor=(t,e)=>{const r="function"!=typeof t?t.constructor:t;let s=Tt.SEQUENCE;const i=G.pk(r);e&&e+""!=i+""||(e=i,s=b.ID),s=dt.key(s,e);const n=dt.get(r,s);if(!n)throw new u(`No sequence options defined for property ${e+""}. did you use @sequence() or @pk()?`);return n},G.indexes=t=>{const e=dt.get(t instanceof G?t.constructor:t,Tt.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[Tt.INDEX]:e[r]},t),{})},e.services=()=>dt.innerGet(Symbol.for(Tt.SERVICE)),e.repositories=()=>dt.innerGet(Symbol.for(b.REPOSITORY)),G.merge=((t,e,r)=>{const s=t=>Object.entries(t).reduce((t,[e,s])=>{let i=!1;try{"relation.one-to-one"===G.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(G);class qe extends u{constructor(t){super(t,qe.name,500)}}var Ge;function He(t,...e){return(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:a}=await s.logCtx(i,r.name,!0);let o;try{o=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(o)throw o;return r.call(s,...a)}})}}function ze(t,...e){return(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:n,ctxArgs:a}=await s.logCtx(i,r.name,!0);let o;try{o=t(...i,...e,n)}catch(t){throw new u("Failed to execute auth validation handler: "+t)}if(o)throw o;return r.call(s,...a)}})}}(t=>{t.AUTH="auth",t.ROLES="roles",t.NAMESPACE="namespace"})(Ge||(Ge={}));const Qe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},We=Qe,Ve={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Je=Object.assign({},Ve,{type:"BigInt"});function Xe(t,e,r){return ht.for(Tt.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![ae.ASC,ae.DSC].includes(t))&&(e=t,t=void 0),yt(dt.key(`${Tt.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}function Ke(t){return"function"==typeof t}function Ze(t,e,r){if(!r.type){const s=dt.type(t.constructor,e);if(![Number.name,String.name,BigInt.name].includes(s?.name||s))throw Error("Incorrrect option type");r.type=s}switch(r.type){case String.name||String.name.toLowerCase():case String:r.generated=void 0!==r.generated&&r.generated,r.type=String;break;case Number.name||String.name.toLowerCase():case Number:r.generated=void 0===r.generated||r.generated,r.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:r.type=BigInt,r.generated=void 0===r.generated||r.generated;break;case"uuid":case"serial":r.generated=!0;break;default:throw Error("Unsupported type")}void 0===r.generated&&(r.generated=!0)}async function tr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=G.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,o;n=s,a=r,o=await i.next(t),Reflect.set(n,a,o)}async function er(t,e,r,s,i){if(!e.type||!e.generated)return;if(!e.name){const t=G.pk(s,!0);if(null==t)throw new u("Cannot generate sequence without an id for "+s.constructor.name);e.name=G.sequenceName(s,t+"",r+"")}let n;try{n=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`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 rr(t,e){return(r,s)=>{vt()(r,s),Ze(r,s,t),t.name||(t.name=((t,e)=>Ke(G.sequenceName)?G.sequenceName(t,e):[Ke(G.tableName)?G.tableName(t):t?.name??"",e].filter(Boolean).join("_"))(r.constructor,"pk"));const i=[yt(dt.key(b.ID,s),t),yt(dt.key(Tt.SEQUENCE,s),t),Xe([ae.ASC,ae.DSC]),z(),v(),A(tr,t,e)];return t.generated&&i.push(x()),gt(...i)(r,s)}}function sr(t,e={},r){return(s,i)=>{vt()(s,i),Ze(s,i,t);const n=[z(),yt(dt.key(Tt.SEQUENCE,i),t),A(er,{...t,...e},r)];return e.update&&n.push(E(er,{...t,...e},r)),t.generated&&n.push(x()),gt(...n)(s,i)}}function ir(t){const e=Object.assign({},We);return delete e.generated,t=Object.assign({},e,t),ht.for(b.ID).define({decorator:rr,args:[t,{priority:60}]}).apply()}function nr(t,e){const r=Object.assign({},We);delete r.generated,t=Object.assign({},r,t);const s="boolean"==typeof e?{update:e}:e||{};return ht.for(Tt.SEQUENCE).define({decorator:sr,args:[t,s,{priority:70}]}).apply()}async function ar(t,e,r,s,i){const n=e.logger.for(ar);if(!s){const e=G.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=Le.forModel(e,r),n.info("Retrieved "+s.toString())}let a;if(s=i?s.override(i):s,void 0===t[G.pk(s.class)])n.info(`No pk found in ${G.tableName(s.class)} - creating`),a=await s.create(t,e);else{n.info(`pk found in ${G.tableName(s.class)} - attempting update`);try{a=await s.update(t,e),n.info("Updated "+G.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+G.tableName(s.class)),a=await s.create(t,e)}n.info("After create update: "+a)}return a}async function or(t,e,r,s){const i=s[r];if(!i)return;if(gr(s,e),"object"!=typeof i){const e=kr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Sr(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const a=Le.forModel(n,this.adapter.alias),o=await a.override(this._overrides).create(i,t),c=G.pk(o);await Sr(t,s,r,o[c],o),s[r]=o[c]}async function cr(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==oe.CASCADE)return;if("object"!=typeof i){const e=kr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Sr(t,s,r,i,n),void(s[r]=i)}const n=await ar(s[r],t,this.adapter.alias,void 0,this._overrides),a=G.pk(n);await Sr(t,s,r,n[a],n),s[r]=n[a]}async function lr(t,e,r,s){const i=s[r];if(null==i)return;if(e.cascade.delete!==oe.CASCADE)return;const n=kr(s,r,this.adapter.alias);let a;a=i instanceof G?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Sr(t,s,r,a[n.pk],a)}async function ur(t,e,r,s,i){const n=s[r];if(!n||!n.length)return;gr(s,e);const a=t.logger.for(ur),o=kr(s,r,this.adapter.alias),c=G.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 ar(e,t,this.adapter.alias,void 0,this._overrides)),a.debug(`caching for populate: ${JSON.stringify(i)} under ${i[c]}`),await Sr(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function dr(t,e,r,s,i){const{cascade:n}=e;if(n.update===oe.CASCADE)return ur.call(this,t,e,r,s,i)}async function hr(t,e,r,s){if(e.cascade.delete!==oe.CASCADE)return;const i=s[r];if(!i)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?Le.forModel(a,this.adapter.alias):kr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await Sr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}async function pr(t,e,r,s){const i=s[r];if(!i)return;gr(s,e);const n=t.logger.for(pr);if("object"!=typeof i){const e=kr(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Sr(t,s,r,i,n),void(s[r]=i)}if(!(e.class instanceof G?e.class.constructor:e.class))throw new u("Could not find model "+e.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(i));const a=await ar(i,t,this.adapter.alias,void 0,this._overrides),o=G.pk(a);n.info(`caching: ${JSON.stringify(a)} under ${a[o]}`),await Sr(t,s,r,a[o],a),s[r]=a[o]}function gr(t,e){let r;const s="function"==typeof e.class&&e.class.name?e.class:e.class(),i=dt.get(s,Tt.RELATIONS);if(i&&(r=Object.values(i)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===r?.populate&&!0===e?.populate)throw new u("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function fr(t,e,r,s){const{cascade:i}=e;if(i.update===oe.CASCADE)return pr.call(this,t,e,r,s)}async function yr(t,e,r,s){if(e.cascade.delete!==oe.CASCADE)return;const i=s[r];if(!i)return;const n="object"==typeof i,a=n?Le.forModel(i,this.adapter.alias):kr(s,r,this.adapter.alias),o=n?i[a.pk]:i,c=await a.override(this._overrides).delete(o);await Sr(t,s,r,o,c),s[r]=o}async function mr(t,e,r,s){const i=s[r];if(!i||!i.length)return;gr(s,e);const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a=t.logger.for(mr),o=new Set([...i]);if("object"!==n){const n=kr(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 Sr(t,s,r,[...o.values()][e],c)}return await wr.call(this,s,[...i],a,t,e),s[r]=[...o],void a.info("SET MANY TO MANY IDS: "+s[r])}const c=G.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 ar(e,t,this.adapter.alias,void 0,this._overrides);a.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Sr(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 d=G.pk(s.constructor);if(void 0===s[d]){const e=await(async(t,e,r)=>{const s=e[G.pk(e.constructor)];if(void 0!==s)return s;const i=G.sequenceFor(e.constructor);let n;i?.name||(i.name=G.sequenceName(e,"pk"));try{return n=await t.adapter.Sequence(i,t._overrides),await n.next(r)}catch(t){throw new u(`Failed to instantiate Sequence ${i.name}: ${t}`)}})(this,s,t);s[d]=e}const h=await wr.call(this,s,i,a,t,e);a.info("Junction model created: "+h.name),s[r]=[...l]}async function wr(t,e,r,s,i){const{JunctionModel:n,fkA:a,fkB:o}=br(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 G?t[G.pk(t.constructor)]:t,[o]:i instanceof G?i[G.pk(i.constructor)]:i},l=await ar(new n(e),s,this.adapter.alias,void 0,this._overrides);l?.id&&c.push(l.id)}if(c.length===e?.length){const t=Le.forModel(n);await(t?.override(this._overrides).readAll(c))}return n}function br(t,e,r){const s=G.tableName(t);let i;if(e instanceof G)i=G.tableName(e);else if(G.isModel(e)&&"function"==typeof e)i=e.name?e.name:e()?.name;else if(r?.class){const t="function"!=typeof r.class||r.class.name?r.class:r.class();i=G.tableName(t)}if(!s||!i)throw new u("Missing tablenames to create junction table");const n=r?.joinTable?.name?r?.joinTable?.name:`${s}_${i}`,a=s?.toLowerCase()+"_fk",o=i?.toLowerCase()+"_fk",c=class extends G{constructor(t){super(t)}};Object.defineProperty(c,"name",{value:n,writable:!1}),ir({type:Number})(c.prototype,"id"),z()(c.prototype,a),z()(c.prototype,o);const l=V()(c);return dt.set(c,Tt.TABLE,n),{fkA:a,fkB:o,JunctionModel:l}}async function vr(t,e,r,s){const{cascade:i}=e;if(i.update===oe.CASCADE)return mr.call(this,t,e,r,s)}async function Ar(t,e,r,s){if(e.cascade.delete!==oe.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?Le.forModel(a,this.adapter.alias):kr(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let d,h;try{d=await c.override(this._overrides).deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await Sr(t,s,r,l[e],h)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function xr(t,e,r){return e?[Tt.POPULATE,t,e,r].join("."):[Tt.POPULATE,t,r].join(".")}function Er(t,e,r){return[Tt.TAG_FOR_DELETION,t,r].join(".")}async function Sr(t,e,r,s,i){const n=xr(e.constructor.name,r,s),a=t.logger.for(Sr),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 Or(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,l=await(async(e,r,s,i)=>{let n,l;const d=[];let h;try{h=e.get("operation")}catch(t){h=void 0}const p=h===o.READ||h===c.READ_ALL?{}:e.get("cacheForPopulate")||{};for(const e of i){n=xr(r.constructor.name,s,e);try{if(l=p[n],!l)throw Error("Not found in cache")}catch(i){const n=kr(r,s,a.adapter.alias);if(!n)throw new u("Could not find repo");l=await n.override(a._overrides).read(e,t)}d.push(l)}return d})(t,s,r,n?i:[i]);s[r]=n?l:l[0]}async function Cr(t,e,r,s,i){if(e.cascade.update!==oe.CASCADE)return;if(!i)throw new u("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[G.pk(t)]}const a=n(s[r]),o=n(i[r]);if(void 0===o||W(a,o))return;if(Array.isArray(a)!==Array.isArray(o))throw new u("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)),d=kr(s,r,this.adapter.alias);if(!d)throw new u("Could not find repo");try{const e=await d.override(this._overrides).deleteAll(l,t);t.logger.debug(`Deleted ${e.length} entries from table ${G.tableName(d.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}const Tr=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function kr(t,e,r){if(!t)throw Error("No model was provided to get repository");let s,i=t instanceof G?t.constructor:t;if(Array.isArray(t[e])||t[e]instanceof Set){const t=dt.get(i,dt.key(J.REFLECT,e,J.LIST))?.clazz;if(!t)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(t)?[...t]:[t]).map(t=>"function"!=typeof t||t.name?t:t())}else s=G.relations(i).includes(e)?dt.allowedTypes(i,e):dt.getPropDesignTypes(t instanceof G?t.constructor:t,e)?.designTypes;i=s?.find(t=>!Tr.includes((""+t.name).toLowerCase()));const n=Le.forModel(i,r);if(i!==n.class)throw new u("Invalid repository class for "+e);return n}class Nr extends O{constructor(t,e=Nr.name,r=401){super(t,e,r)}}class Dr extends Nr{constructor(t,e=Dr.name){super(t,e,403)}}class _r extends u{constructor(t){super(t,_r.name,503)}}function Br(t){return ht.for(Tt.TABLE).define({decorator:t=>e=>(dt.set(Tt.TABLE,t||e.name.toLowerCase(),e),bt(Tt.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function Rr(t){return ht.for(Tt.COLUMN).define({decorator:t=>(e,r)=>yt(dt.key(Tt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}async function Ir(t,e,r,s){if(s[r]&&(await this.select().where(ne.attribute(r).eq(s[r])).execute()).length)throw new k(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Pr(){const t=Tt.UNIQUE;return ht.for(t).define(Z(),T(Ir),yt(t,{})).apply()}async function $r(t,e,r,s){throw new Nr("This adapter does not support user identification")}function Lr(){return ht.for(Tt.CREATED_BY).define({decorator:()=>(t,e)=>gt(A($r),yt(Tt.CREATED_BY,e),x(Tt.CREATED_BY))(t,e),args:[]}).apply()}function Fr(){return ht.for(Tt.UPDATED_BY).define({decorator:()=>(t,e)=>gt(E($r),yt(Tt.UPDATED_BY,e),x(Tt.UPDATED_BY))(t,e),args:[]}).apply()}function jr(){return C([o.CREATE])}function Ur(){return C()}async function Mr(t,e,r,s){if("??sequence"===G.tableName(s))return;const i=G.pk(s,!0);if(null==i)throw new u("Cannot generate persistent version without an id for "+s.constructor.name);const n={name:G.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 Yr(t,e,r,s,i){if("??sequence"===G.tableName(s))return;if(t.get("applyUpdateValidation")&&i&&s[r]!==i[r])throw new d(`Version mismatch: ${s[r]} !== ${i[r]}`);const n=G.pk(s,!0);if(null==n)throw new u("Cannot generate persistent version without an id for "+s.constructor.name);const a={name:G.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 h=await o.next(t);s[r]=h}function qr(){const t=Tt.PERSISTENT_VERSION;return(e,r)=>ht.for(t).define(vt(),yt(dt.key(t,r),!0),x(t),X(Number),A(Mr,{},{priority:70}),E(Yr,{},{priority:70})).apply()(e,r)}function Gr(t=!1){return t?qr():N()}function Hr(t){return[()=>{const e="function"==typeof t&&t.name?t:t(),r=G.pk(e);return(dt.allowedTypes(e,r)||[])[0]}]}function zr(t,e=ce,r=!0,s,i){const n=Tt.ONE_TO_ONE;return ht.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Hr(t),c=[vt(),ts(n,a),X([t,...o]),A(or,a,{priority:70}),E(cr,a,{priority:70}),_(lr,a,{priority:70}),E(Cr,a,{priority:80}),D(Or,a,{priority:70})];return gt(...c)},args:[t,e,r,s,i]}).apply()}function Qr(t,e=ce,r=!0,s,i){const n=Tt.ONE_TO_MANY;return ht.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Hr(t),c=[vt(),ts(n,a),tt([t,...o]),A(ur,a,{priority:70}),E(dr,a,{priority:70}),_(hr,a,{priority:70}),E(Cr,a,{priority:80}),D(Or,a,{priority:70})];return gt(...c)},args:[t,e,r,s,i]}).apply()}function Wr(t,e=ce,r=!0,s,i){const n=Tt.MANY_TO_ONE;return ht.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Hr(t),c=[vt(),ts(n,a),X([t,...o]),A(pr,a),E(fr,a),_(yr,a),D(Or,a)];return gt(...c)},args:[t,e,r,s,i]}).apply()}function Vr(t,e=ce,r=!0,s,i){const n=Tt.MANY_TO_MANY;return ht.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Hr(t),c=[vt(),ts(n,a),tt([t,...o]),A(mr,a),E(dr,a),D(Or,a)];return gt(...c)},args:[t,e,r,s,i]}).apply()}function Jr(...t){return(e,r)=>{const s=dt.get(e,dt.key(Tt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return gt(bt(dt.key(Tt.NO_VALIDATE,r),i))(e,r)}}function Xr(){return Jr(o.CREATE)}function Kr(){return Jr(o.UPDATE)}function Zr(){return Jr(o.UPDATE,o.CREATE)}function ts(t,e){return ht.for(Tt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(yt(t,e)(r,s),yt(dt.key(Tt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class es extends G{constructor(t){super(t)}}i([jr(),n("design:type",Date)],es.prototype,"createdAt",void 0),i([Ur(),n("design:type",Date)],es.prototype,"updatedAt",void 0);let rs=class extends es{constructor(t){super(t)}};i([ir({type:String,generated:!1}),n("design:type",String)],rs.prototype,"id",void 0),i([z(),Xe(),n("design:type",Object)],rs.prototype,"current",void 0),rs=i([Br("??sequence"),V(),n("design:paramtypes",[Object])],rs);class ss extends j{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,Wt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${Ct.FIND_BY}|${Ct.LIST_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 Pt?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof Pt||(this._bookmark=e);const n=Le.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)}const u=RegExp(`^${Ct.FIND_BY}|${Ct.LIST_BY}`,"gi");if(!o.match(u))throw new jt(`Method ${o} is not supported for pagination`);u.lastIndex=0;const d=o.replace(u,Ct.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==Ct.PAGE_BY||h.length>2?p={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(p);const g=await n.statement(...h,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new ie("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ie(`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 B(t)}}apply(t){const e="string"==typeof t?ss.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total||this._totalPages,this._recordCount=e.count||this._recordCount,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new B(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var is,ns,as,os,cs,ls,us;class ds extends $t{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach(t=>{R(this,t,(...e)=>this.executionPrefix(t,...e),t.name)})}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?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(ds)}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 se("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?G.get(t):t,!this.fromSelector)throw new se("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 se("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new se("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 se("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===ae.ASC)return ae.ASC;if(e===ae.DSC)return ae.DSC;throw new se(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ae).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new se("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 se(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=Le.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[G.pk(this.fromSelector)];return this.adapter.revert(t,this.fromSelector,r,void 0,e)}async applyAfterHandlersToResult(t,e){return e.getOrUndefined("afterQueryHandlers")?t instanceof G?(await f(this.getRepository(),e,t,o.READ,o.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 Le.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 ne){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case St.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case St.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case St.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case St.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case St.BIGGER_EQ:n.method=r+" bigger than equal";break;case St.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case St.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case St.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new se("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 ne)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,ae.DSC]:[G.pk(this.fromSelector),ae.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=G.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===St.STARTS_WITH){if("string"!=typeof e||"string"!=typeof s)return;return{attributes:[e],value:s}}if(r===Ot.OR){const t=e instanceof ne?this.collectStartsWithAttributes(e):void 0,r=s instanceof ne?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 ne?this.collectStartsWithAttributes(e):void 0)||(s instanceof ne?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??ae.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=Et.FIND_BY;void 0!==this.countSelector?(n=Et.COUNT_BY,i=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=Et.SUM_BY,i=this.sumSelector):this.avgSelector?(n=Et.AVG_BY,i=this.avgSelector):this.minSelector?(n=Et.MIN_BY,i=this.minSelector):this.maxSelector?(n=Et.MAX_BY,i=this.maxSelector):this.distinctSelector?(n=Et.DISTINCT_BY,i=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=Et.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(Et.SELECT,this.selectSelector.join(` ${Et.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;a.push(Et.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map(([t,e])=>[t,e]),e.forEach(([t])=>{a.push(Et.THEN_BY,t)}))}if(this.groupBySelectors?.length&&n!==Et.GROUP_BY_PREFIX){const[t,...e]=this.groupBySelectors;a.push(Et.GROUP_BY,t),e.forEach(t=>a.push(Et.THEN_BY,t))}else this.groupBySelectors?.length&&n===Et.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>a.push(Et.THEN_BY,t));return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=M(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 se(t)}}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],ds.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(is="undefined"!=typeof S&&S)?is:Object]),n("design:returntype",Object)],ds.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ns="undefined"!=typeof S&&S)?ns:Object]),n("design:returntype",Object)],ds.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(as="undefined"!=typeof S&&S)?as:Object]),n("design:returntype",Object)],ds.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(os="undefined"!=typeof S&&S)?os:Object]),n("design:returntype",Object)],ds.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(cs="undefined"!=typeof S&&S)?cs:Object]),n("design:returntype",Object)],ds.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ls="undefined"!=typeof S&&S)?ls:Object]),n("design:returntype",Object)],ds.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],ds.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[ne]),n("design:returntype",Object)],ds.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],ds.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],ds.prototype,"thenBy",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(us="undefined"!=typeof Key&&Key)?us:Object]),n("design:returntype",Object)],ds.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],ds.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],ds.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],ds.prototype,"execute",null);class hs extends $t{constructor(t){super(),this.name=t,this.observers=[],this.Context=Pt}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 hs?n.for(t,...e):n instanceof Le?n.override(t):n}})}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Ft,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${Vt.instance.generate()}`;const s=e.logger||F.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},kt,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 Pt||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new u("No name provided");const r=Yt(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof Pt||(t.push(r),r=void 0);const s=await hs.prototype.flags(Tt.INITIALIZATION,{},...t);r=r?new Pt(r).accumulate({...s,parentContext:r}):(new Pt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=hs.prototype.logCtx(t,this.boot),a=e.services();for(const[t,r]of Object.entries(a))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof ps&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new u(`Failed to boot ${r.name} service:${t}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof Pt||(t.push(r),r=void 0);const s=await hs.prototype.flags(Tt.SHUTDOWN,{},...t);r=r?new Pt(r).accumulate({...s,parentContext:r}):(new Pt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=hs.prototype.logCtx(t,this.shutdown),a=e.services();for(const[t,r]of Object.entries(a).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof ps){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],hs.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],hs.prototype,"unObserve",null);class ps extends hs{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 u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info("Shutting down...")}}function gs(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&zt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],ps.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],ps.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],ps.prototype,"client",null);const fs=()=>gs(o.CREATE),ys=()=>gs(o.READ),ms=()=>gs(o.UPDATE),ws=()=>gs(o.DELETE);function bs(t){return(e,i,n)=>{n||i?(vt()(e,i),t=t||dt.type(e.constructor,i)):t=t||e,t=Yt(t);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else dt.set(Tt.SERVICE,t,e),a.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return gt(...a)(e,i,n)}}function vs(t){const e=Tt.AUTH;return ht.for(e).define({decorator:t=>bt(e,t),args:[t]}).apply()}const As=t=>bt(Tt.AUTH_ROLE,t);function xs(t,e){const r=Tt.DECAF_ROUTE;return ht.for(r).define({decorator:()=>(s,i,n)=>{const a={path:e,httpMethod:t,handler:n};return gt(ft(dt.key(r,i),a))(s,i,n)},args:[]}).apply()}const Es=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Ss extends hs{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Le.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=Es(t);try{const t=hs.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,Tt.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}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 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=Es(e||t);try{r=Ss.get(e)}catch(t){r=void 0}if(r instanceof Ss)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([bs(e),n("design:paramtypes",[])],a),new a}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo._adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([fs(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ss.prototype,"create",null),i([fs(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ss.prototype,"createAll",null),i([ws(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ss.prototype,"delete",null),i([ws(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ss.prototype,"deleteAll",null),i([ys(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ss.prototype,"read",null),i([ys(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ss.prototype,"readAll",null),i([ys(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Ss.prototype,"query",null),i([ms(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ss.prototype,"update",null),i([ms(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Ss.prototype,"updateAll",null);class Os extends $t{constructor(){super(),this.initialized=!1}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");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;[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return o.CREATE;case c.UPDATE_ALL:return o.UPDATE;case c.DELETE_ALL:return o.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 re))throw new jt("Only Adapters can be observed by dispatch");return this.adapter?()=>this.unObserve(this.adapter):(this.adapter=t,this.models=re.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t))}unObserve(t){if(this.adapter!==t)throw new 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 u("Model must be provided for observer update");const i=t&&"string"==typeof t?t:G.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 u("Failed to refresh dispatch: "+t)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Cs(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 Vt.instance.generate(i)}function Ts(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=Tt.UUID;return ht.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[z(),x(Tt.UUID),A(Cs,s,{priority:54})];return t&&i.push(E(Cs,s,{priority:54})),t||i.push(v()),gt(...i)},args:[t,e,...r]}).apply()}re&&(re._baseDispatch=Os);class ks extends $t{static{this.lock=new lt}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=Le.forModel(rs,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,o.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:a}=this.options;if(!a)throw new u("Sequence name is required");return ks.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new rs({id:a,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${a} current=${c} next=${t}`),this.repo.create(new rs({id:a,current:t}),s);throw e}};if("uuid"===o)for(;;){const t=await Promise.resolve(Vt.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 k)continue;throw t}}const d=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(Jt.instance.generate(t));default:throw new u("Should never happen")}})(c),h=await l(d);return r.debug(`Sequence.increment ${a} current=${c} next=${d}`),h.current},a)}async next(...t){const{ctx:e}=(await this.logCtx(t,o.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.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 c=[];for(let e=0;t-1>=e;e++)c.push(a-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==a&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}async ensureAtLeast(t,...e){const{ctx:r}=(await this.logCtx(e,o.UPDATE,!0)).for(this.ensureAtLeast),{name:s}=this.options;if(!s)throw new u("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 ks.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(s,r)}catch(t){if(t instanceof m)return;throw t}};for(;;)try{const e=await t();if(!e)return await this.repo.create(new rs({id:s,current:i}),r),i;const a=this.parse(e.current);return n(i,a)?(await this.repo.update(new rs({id:s,current:i}),r),i):a}catch(t){if(t instanceof k)continue;throw t}},s)}parse(t){return ks.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([rs,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return G.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 Ns(t,...e){let r;if(t instanceof Ss&&(r=t.repo.adapter),t instanceof Le&&(r=t.adapter),t instanceof re&&(r=t),!r)throw new u("Could not find adapter to extract transaction");return r.transactionLock(...e)}function Ds(t,...e){return new Kt(Ns(t,...e))}re._baseSequence=ks,ht.for(ut.TRANSACTIONAL).define({decorator:(...t)=>(e,r,s)=>{if(!s)throw new u("This decorator only applies to methods");return At()(e,r,s),dt.set(e.constructor,dt.key(ut.TRANSACTIONAL,r),{data:t}),s.value=new Proxy(s.value,{async apply(t,e,r){const{log:s,ctx:i}=(await e.logCtx(r,t.name,!0)).for(t),n=i.getOrUndefined("transactionLock")||Ds(e);let a;i.put("transactionLock",n),await n.acquire();try{a=await t.call(e,...r,i)}catch(t){try{await n.rollback(t)}catch(t){s.error("Failed to rollback transaction",t)}throw t}try{await n.release()}catch(t){throw new u("Failed to release transaction: "+t)}return a}}),s}}).apply();class _s extends ps{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 Pt||!e.every(t=>Array.isArray(t)))throw new u("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 u(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Bs=class extends G{constructor(t){super(t),this.strategy=Re.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=Ie.FULL}};i([z(),X(String),et(Re),xt("the backoff strategy"),n("design:type",String)],Bs.prototype,"strategy",void 0),i([z(),xt("base interval between attempts"),n("design:type",Number)],Bs.prototype,"baseMs",void 0),i([z(),xt("max interval"),n("design:type",Number)],Bs.prototype,"maxMs",void 0),i([X(String),et(Ie),xt("optional jitter strategy"),n("design:type",String)],Bs.prototype,"jitter",void 0),Bs=i([V(),n("design:paramtypes",[Object])],Bs);let Rs=class extends G{constructor(t){super(t)}};i([z(),xt("The error message"),n("design:type",String)],Rs.prototype,"message",void 0),i([vt(),xt("The error stack"),n("design:type",String)],Rs.prototype,"stack",void 0),i([vt(),xt("The error code"),n("design:type",String)],Rs.prototype,"code",void 0),i([vt(),xt("The error details"),n("design:type",Object)],Rs.prototype,"details",void 0),Rs=i([V(),n("design:paramtypes",[Object])],Rs);let Is=class extends G{constructor(t){if(super(t),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}};i([ir(),I(["taskId","classification","uuid"],":"),n("design:type",String)],Is.prototype,"id",void 0),i([Rr(),v(),z(),P(),Ts(!1),n("design:type",String)],Is.prototype,"uuid",void 0),i([Rr(),v(),z(),Xe([ae.ASC,ae.DSC]),n("design:type",String)],Is.prototype,"taskId",void 0),i([rt(),Rr(),z(),Xe([ae.ASC,ae.DSC]),n("design:type",Date)],Is.prototype,"ts",void 0),i([Rr(),v(),z(),et(Pe),Xe([ae.ASC,ae.DSC]),n("design:type",String)],Is.prototype,"classification",void 0),i([vt(),Rr(),$(),v(),n("design:type",Object)],Is.prototype,"payload",void 0),Is=i([Br("task_event"),V(),n("design:paramtypes",[Object])],Is);class Ps extends st{constructor(){super()}preSerialize(t,...e){return this.serializeValue(t,...e)}deserialize(t,...e){const r=JSON.parse(t);return this.rebuildValue(r)}serializeValue(t,...e){if(null==t)return t;if("object"!=typeof t)return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.map(t=>this.serializeValue(t,...e));if(t instanceof ne){const r=this.serializePlain(t,...e);return r[it.ANCHOR]="??condition",r}return G.isModel(t)?this.serializeModel(t,...e):this.serializePlain(t,...e)}serializeModel(t,...e){const r=this.serializePlain(t,...e),s=this.getMetadata(t.constructor)??t.constructor?.name;return s&&(r[it.ANCHOR]=s),r}serializePlain(t,...e){const r={};for(const[s,i]of Object.entries(t))r[s]=this.serializeValue(i,...e);return r}getMetadata(t){try{return dt.modelName(t)}catch{return}}rebuildValue(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>this.rebuildValue(t));const e=t[it.ANCHOR],r=this.rebuildObject(t);return e?"??condition"===e?ne.from(r):G.build(r,e):r}rebuildObject(t){const e={};for(const[r,s]of Object.entries(t))r!==it.ANCHOR&&(e[r]=this.rebuildValue(s));return e}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let $s=class extends G{constructor(t){super(t),this.ts=new Date}};i([rt(),z(),n("design:type",Date)],$s.prototype,"ts",void 0),i([z(),et(Y),n("design:type",String)],$s.prototype,"level",void 0),i([nt(0),n("design:type",Number)],$s.prototype,"step",void 0),i([z(),vt(),n("design:type",String)],$s.prototype,"msg",void 0),i([vt(),n("design:type",Object)],$s.prototype,"meta",void 0),$s=i([V(),n("design:paramtypes",[Object])],$s);let Ls=class extends G{constructor(t){super(t),this.atomicity=$e.ATOMIC,this.status=Be.PENDING,this.attempt=0,this.logTail=[]}};i([ir(),Ts(),xt("the task id"),n("design:type",String)],Ls.prototype,"id",void 0),i([Rr(),z(),X(String),et($e),Xe([ae.ASC,ae.DSC]),xt("defines a single or composite task"),n("design:type",String)],Ls.prototype,"atomicity",void 0),i([Rr(),z(),Xe([ae.ASC,ae.DSC]),xt("Holds task classification - must match @task()"),n("design:type",String)],Ls.prototype,"classification",void 0),i([Rr(),vt(),Xe([ae.ASC,ae.DSC]),xt("optional task name for ambiguity"),n("design:type",String)],Ls.prototype,"name",void 0),i([Rr(),z(),X(String),et(Be),Xe([ae.ASC,ae.DSC]),xt("Holds the task current status"),n("design:type",String)],Ls.prototype,"status",void 0),i([vt(),Rr(),$(Ps),xt("Holds task input"),n("design:type",Object)],Ls.prototype,"input",void 0),i([vt(),Rr(),$(Ps),xt("Holds the task output when successfully completed"),n("design:type",Object)],Ls.prototype,"output",void 0),i([vt(),Rr(),$(),xt("Holds the error for failed tasks"),n("design:type",Rs)],Ls.prototype,"error",void 0),i([Rr(),z(),nt(0),Xe([ae.ASC,ae.DSC]),xt("Holds the current attempt"),n("design:type",Number)],Ls.prototype,"attempt",void 0),i([Rr(),nt(1),z(),xt("max attempts for the task"),n("design:type",Number)],Ls.prototype,"maxAttempts",void 0),i([Rr(),z(),$(),xt("backoff configuration"),n("design:type",Bs)],Ls.prototype,"backoff",void 0),i([rt(),Rr(),xt("Next execution timestamp"),n("design:type",Date)],Ls.prototype,"nextRunAt",void 0),i([rt(),Rr(),xt("Task scheduled timestamp"),n("design:type",Date)],Ls.prototype,"scheduledTo",void 0),i([vt(),Rr(),xt("Task lease owner identifier"),n("design:type",String)],Ls.prototype,"leaseOwner",void 0),i([rt(),Rr(),xt("Task lease expiration timestamp"),n("design:type",Date)],Ls.prototype,"leaseExpiry",void 0),i([vt(),Rr(),$(),xt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Ls.prototype,"steps",void 0),i([vt(),Rr(),nt(0),Xe([ae.ASC,ae.DSC]),xt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Ls.prototype,"currentStep",void 0),i([vt(),Rr(),$(),xt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Ls.prototype,"stepResults",void 0),i([vt(),Rr(),$(),xt("Holds the task log entries"),n("design:type",Array)],Ls.prototype,"logTail",void 0),i([Rr(),jr(),Xe([ae.ASC,ae.DSC]),xt("timestamp of creation"),n("design:type",Date)],Ls.prototype,"createdAt",void 0),i([Rr(),Ur(),Xe([ae.ASC,ae.DSC]),xt("timestamp of last update"),n("design:type",Date)],Ls.prototype,"updatedAt",void 0),i([Rr(),Lr(),Xe([ae.ASC,ae.DSC]),xt("Holds the creator of the task"),n("design:type",String)],Ls.prototype,"createdBy",void 0),i([Rr(),Fr(),Xe([ae.ASC,ae.DSC]),xt("Holds the creator of the task"),n("design:type",String)],Ls.prototype,"updatedBy",void 0),Ls=i([xt("Holds the current step when applicable"),Br("tasks"),V(),n("design:paramtypes",[Object])],Ls);let Fs=class extends G{constructor(t){super(t)}};i([z(),xt("The status of a step"),n("design:type",String)],Fs.prototype,"status",void 0),i([vt(),xt("The result of a successful step"),n("design:type",Object)],Fs.prototype,"output",void 0),i([vt(),xt("the error of a failed step"),n("design:type",Rs)],Fs.prototype,"error",void 0),Fs=i([V(),n("design:paramtypes",[Object])],Fs);let js=class extends G{constructor(t){super(t)}};i([z(),xt("task handler type"),n("design:type",String)],js.prototype,"classification",void 0),i([at(1),xt("optional task name for ambiguity"),n("design:type",String)],js.prototype,"name",void 0),i([xt("optional task step input"),vt(),n("design:type",Object)],js.prototype,"input",void 0),js=i([V(),n("design:paramtypes",[Object])],js);class Us extends G{constructor(t){super(t),this.baseMs=1e3,this.jitter=Ie.FULL,this.maxMs=6e4,this.strategy=Re.EXPONENTIAL,G.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new d(t);return new Bs(this)}}i([z(),nt(1e3),n("design:type",Number)],Us.prototype,"baseMs",void 0),i([z(),et(Ie),n("design:type",String)],Us.prototype,"jitter",void 0),i([ot("baseMs"),nt(1e3),z(),n("design:type",Number)],Us.prototype,"maxMs",void 0),i([z(),et(Re),n("design:type",String)],Us.prototype,"strategy",void 0);class Ms extends G{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 Us,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=Be.PENDING,this.atomicity=$e.ATOMIC,this.backoff=new Bs,this.maxAttempts=1,G.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Ls(this)}}i([z(),n("design:type",String)],Ms.prototype,"classification",void 0),i([vt(),n("design:type",String)],Ms.prototype,"name",void 0),i([z(),n("design:type",String)],Ms.prototype,"status",void 0),i([z(),n("design:type",String)],Ms.prototype,"atomicity",void 0),i([z(),n("design:type",Bs)],Ms.prototype,"backoff",void 0),i([vt(),n("design:type",Object)],Ms.prototype,"input",void 0),i([nt(1),z(),n("design:type",Number)],Ms.prototype,"maxAttempts",void 0);class Ys extends Ms{constructor(t){super(t),this.stepResults=[],G.fromModel(this,t),this.atomicity=$e.COMPOSITE}setAtomicity(t){throw new u("Atomicity locked to "+$e.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof js?t:new js(t)),this}addStep(t,e,r){this.steps=this.steps||[];const s=new Date,i=arguments.length>=3,n=i&&"string"==typeof e?e:void 0,a=i?r:e;return this.steps.push(new js({classification:t,name:n,input:a,createdAt:s,updatedAt:s})),this}}i([tt(()=>js),n("design:type",Array)],Ys.prototype,"steps",void 0);class qs extends Lt{get type(){if(!this._type){const t=dt.get(this.constructor,Ue);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),p(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function Gs(t){return ht.for(Ue).define({decorator:t=>e=>{const r={type:t};return dt.set(Ue,t,e),bt(Ue,r)(e)},args:[t]}).apply()}let Hs=class extends qs{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof ne)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=ne.attr("status").eq(Be.SUCCEEDED).and(ne.attr("updatedAt").lte(t.successfulExpiry)),i=ne.attr("status").eq(Be.FAILED).and(ne.attr("updatedAt").lte(t.failedExpiry)),n=ne.attr("status").eq(Be.CANCELED).and(ne.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(t=>t.id),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([Ye(Ls),n("design:type",Object)],Hs.prototype,"tasks",void 0),Hs=i([Gs("cleanup-task"),n("design:paramtypes",[])],Hs);class zs{constructor(t,e=150,r=300,s){this.logger=t,this.bufferSize=e,this.maxBufferSize=r,this.pipe=s,this.history=[],this.root=this.logger.root,Object.values(Y).forEach(t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})})}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch(t=>this.logger.error("Failed to pipe logs",t)).finally(()=>this.history=[]):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get(r,s){if("logger"===s){const i=Reflect.get(r,s);try{return i.for(t,...e)}catch(t){r.error("Failed to bind task logger. received: "+(i&&i.constructor?i.constructor.name:i.name?i.name:"unknown"),t);try{r.trace(JSON.stringify(i,void 0,2))}catch(t){r.trace("unserializable output: "+(i.name||"unknown"))}throw t}}return Reflect.get(r,s)}})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function Qs(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1}),r.classification){case Pe.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=q(i),i=i.clear().toString());const s=[i];r===Y.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case Pe.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case Pe.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=q(e);switch(e){case Be.SUCCEEDED:s=s.green.bold;break;case Be.RUNNING:s=s.blue.bold;break;case Be.PENDING:s=s.yellow;break;case Be.WAITING_RETRY:s=s.yellow.bold;break;case Be.FAILED:s=s.red.bold;break;case Be.CANCELED:s=s.magenta.bold;break;case Be.SCHEDULED:s=s.cyan;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}function Ws(t,e){const r=e.strategy===Re.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===Ie.FULL?Math.floor(Math.random()*s):s}function Vs(t){return new Rs({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Js(t){return new Promise(e=>setTimeout(e,t))}class Xs extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=Xs.name,Object.setPrototypeOf(this,Xs.prototype)}}class Ks extends Pt{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 Xs({status:t,...e})}cancel(t,e){this.changeState(Be.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(Be.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(Be.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof Rs?t:t instanceof Error?Vs(t):new Rs({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class Zs{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=dt.tasks();t&&Object.entries(t).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class ti extends Ft{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(Is,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:a}=re.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 ei(t,e){return t instanceof Error&&"nextAction"in t&&"string"==typeof t.nextAction&&(!e||t instanceof e)}class ri extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class si extends ri{constructor(t,e,r){super(si.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class ii extends ri{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(ii.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class ni extends ri{constructor(t,e,r){super(ni.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class ai extends ri{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(ai.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class oi{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===Is||t===G.tableName(Is))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([Be.SUCCEEDED,Be.FAILED,Be.CANCELED,Be.SCHEDULED])}wait(){return this.awaitStatusTerminal([Be.SUCCEEDED,Be.FAILED,Be.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(Qs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==Pe.LOG)return;const r=(e.payload??[]).map(t=>Array.isArray(t)?t:[t.level,`${t.ts} - ${t.msg}`,t.meta]);await t(r)},Pe.LOG)}pipe(t,e=Pe.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(Be.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(Be.FAILED,t)}onCancel(t){return this.registerStatusHandler(Be.CANCELED,t)}awaitStatusTerminal(t){return new Promise((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===Be.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[Be.SUCCEEDED,Be.CANCELED,Be.FAILED].includes(t)}async track(t,e){if(!t.payload)return;const r=t.payload.status;this.task.status=r,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),r!==Be.SUCCEEDED?(r===Be.FAILED&&this.fail(),r===Be.CANCELED&&this.cancel(t),r===Be.WAITING_RETRY&&this.retry(),r===Be.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,Pe.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[Pe.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new Pt),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===Be.SUCCEEDED&&(e.output=this.task.output),t!==Be.FAILED&&t!==Be.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 Is({classification:Pe.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case Be.FAILED:return new si(this.task.id,e,r);case Be.CANCELED:return new ni(this.task.id,e,r);case Be.WAITING_RETRY:return new ii(this.task.id,e,r);case Be.SCHEDULED:return new ai(this.task.id,e,r);default:return new si(this.task.id,e,r)}}assignNextAction(t,e){return e&&(t.nextAction=e),t}getNextAction(t){switch(t){case Be.CANCELED:return Be.CANCELED;case Be.WAITING_RETRY:return Be.WAITING_RETRY;case Be.SCHEDULED:return Be.SCHEDULED;case Be.FAILED:return Be.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===Be.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[Pe.ALL]?[...this.pipes[Pe.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 ci extends Lt{get Context(){return Ks}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,Ls,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,Is,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(t,e){const r=new Ks(t);return e&&Object.keys(e).length?r.accumulate(e):r}constructor(t){super(),this.config=t,this.lock=new ct,this.running=!1;const e=Object.assign({},Me.autoShutdown,t.autoShutdown);this.config=Object.assign({},Me,t,{autoShutdown:e,bus:t.bus||new ti,registry:t.registry||new Zs}),this.idleDelayMs=this.config.pollMsIdle}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,o.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 oi(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=Be.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,o.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 oi(this.bus,i)}}async ensureTaskError(t,e){if(![Be.FAILED,Be.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await Js(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===Be.SUCCEEDED||s.status===Be.FAILED)return s;s.status=Be.CANCELED;const i=new Rs({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,Be.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(ne.attr("status").eq(Be.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 Js(Math.max(a,0))}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=new Date,s=ne.attribute("status").eq(Be.PENDING),i=ne.attribute("status").eq(Be.WAITING_RETRY).and(ne.attribute("nextRunAt").lte(r)),n=ne.attribute("status").eq(Be.RUNNING).and(ne.attribute("leaseExpiry").lte(r)),a=ne.attribute("status").eq(Be.SCHEDULED).and(ne.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{}const n=new Ls({...i,status:Be.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=this;let i=Promise.resolve();const n=new Ks(e).accumulate({taskId:t.id,logger:new zs(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{}}}});await this.emitStatus(n,t,Be.RUNNING);try{let e;if(t.atomicity===$e.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(r.debug(`handler type for ${t.id} is ${s?.constructor?.name??"none"}`),!s)throw new u("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=Be.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,Be.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 Xs)return void await this.handleTaskStateChange(e.request,t,n);if(r.error("task execution error",e),t.atomicity===$e.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===Be.FAILED);0>r||(t.currentStep=r)}}const s=(t.attempt??0)+1,i=Vs(e);if(s<t.maxAttempts){const a=Ws(s,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+a);t.attempt=s,t.status=Be.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(Y.warn,"Retry scheduled",{nextRunAt:o,delayMs:a,attempt:s}),await this.emitStatus(n,t,Be.WAITING_RETRY,i,e)}else{t.attempt=s,t.status=Be.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(Y.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(n,t,Be.FAILED,i,e)}}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case Be.CANCELED:{const s=t.error??new Rs({message:`Task ${e.id} canceled`});return e.status=Be.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Be.CANCELED,s),void await r.pipe(Y.warn,"Task canceled via context")}case Be.WAITING_RETRY:{const s=(e.attempt??0)+1,i=Ws(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),a=t.error??new Rs({message:`Task ${e.id} requested retry`});return e.status=Be.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,Be.WAITING_RETRY,a),void await r.pipe(Y.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case Be.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new Rs({message:`Task ${e.id} rescheduled`});return e.status=Be.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,Be.SCHEDULED,s),void await r.pipe(Y.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new u("Unsupported task state change requested: "+t.status)}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),a=(t,s)=>{e.cacheResult(t,s),r instanceof Ks&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===Be.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 r=s[i],o=this.registry.get(r.classification);if(!o)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([Y.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await o.run(r.input,e);await e.flush();const l=i,u=new Date;n[l]=new Fs({status:Be.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;a(r.classification,c),a(d,c),i=l+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:c})}catch(e){const r=new Date;n[i]=new Fs({status:Be.FAILED,error:Vs(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=Vs(e);const s=await this.tasks.update(t);throw Object.assign(t,s),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Bs)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Bs(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 js)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new js(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 Fs)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Fs(e)}):[]}async appendLog(t,e,r){const s=Array.isArray(r)&&Array.isArray(r[0]),i=e.atomicity===$e.COMPOSITE?t instanceof Ks?t.step??e.currentStep:e.currentStep:void 0,n=(s?r:[r]).map(([t,e,r])=>new $s({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 Ks&&await t.flush();const n={status:r};s&&s instanceof Rs?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,Pe.STATUS,n),o=void 0!==i?Object.assign({},n,{originalError:i}):n,c=new Is({...a,payload:o});this.bus.emit(c,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,Pe.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,Pe.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Is({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,Ls,...r)}}class li extends Ss{constructor(){super(Is)}get repo(){return this._repository||(this._repository=hs.get(Ls).events),this._repository}}class ui extends ps{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 Pt)throw new u("No/invalid config provided");if(!e.adapter)throw new u("No adapter provided");return{client:new(e.engine||ci)(e),config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,o.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,o.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,o.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,c.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,o.DELETE,!0)).for(this.delete);return this.tasks.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.tasks.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.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 u(`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 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")}}function di(t={count:1},e=0){return function r(s,i,n){return gt(ft(dt.key(Tt.THROTTLE,i),t),(s,i,n)=>{n.value=new Proxy(n.value,{async apply(s,n,a){const o=a,c=(()=>{try{return"function"==typeof t?t(...o):t}catch(t){throw new u("Failed to obtain throttling configuration from handler: "+t)}})(),{log:l,ctx:d}=(await n.logCtx(a,Tt.THROTTLE,!0)).for(r),h=(t=>{const e=(Array.isArray(t)?t:[t]).map(t=>{if(!Number.isFinite(t)||0>t)throw new u("@throttling() argument indexes must be non-negative integers");return t});return Array.from(new Set(e)).sort((t,e)=>t-e)})(e);if(!h.length)throw new u("@throttling() expects at least one argument index to throttle");h.forEach(t=>{if(t>=o.length)throw new u(`@throttling() requires argument index ${t} but only ${o.length} provided`);if(!Array.isArray(o[t]))throw new u(`@throttling() expects argument at index ${t} to be an array`)});const p=h.map(t=>o[t]),g=p[0].length;if(!p.every(t=>t.length===g))throw new u("@throttling() requires all targeted arguments to have the same length");if(0===g)return s.apply(n,o);const f=((t,e,r)=>{if("count"in r){if(0>=r.count)throw new u("@throttling() configuration 'count' must be greater than zero");const e=[];for(let s=0;t>s;s+=r.count)e.push({start:s,end:Math.min(t,s+r.count)});return e}if("bufferSize"in r){if(0>=r.bufferSize)throw new u("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,n=0;for(let a=0;t>a;a++){const t=hi(e,a);n>0&&n+t>r.bufferSize?(s.push({start:i,end:a}),i=a,n=t):n+=t}return i>=t&&s.length||s.push({start:i,end:t}),s}return[{start:0,end:t}]})(g,p,c),y=f.map(({start:t,end:e})=>o.map((r,s)=>{const i=h.indexOf(s);return-1===i?r:p[i].slice(t,e)})),m=d.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const t of y){try{pi(await s.apply(n,t),w)}catch(t){if(m)throw t;b.push(t)}c.delayMs&&await new Promise(t=>setTimeout(t,c.delayMs))}if(b.length){l.warn(`${i+""} throttled execution continued with ${b.length} failure(s)`);const t=new AggregateError(b,`Throttled ${i+""} failed for ${b.length} chunk(s)`);throw t.results=w,t}return w}})})(s,i,n)}}function hi(t,e){return t.reduce((t,r)=>t+(t=>{if(null==t)return 0;try{return Buffer.byteLength(JSON.stringify(t))}catch{return 0}})(r[e]),0)}function pi(t,e){Array.isArray(t)?e.push(...t):void 0!==t&&e.push(t)}i([fs(),n("design:type",Function),n("design:paramtypes",[Ls,void 0]),n("design:returntype",Promise)],ui.prototype,"create",null),i([fs(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ui.prototype,"createAll",null),i([ws(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ui.prototype,"delete",null),i([ws(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ui.prototype,"deleteAll",null),i([ys(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ui.prototype,"read",null),i([ys(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ui.prototype,"readAll",null),i([ys(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],ui.prototype,"query",null),i([ms(),n("design:type",Function),n("design:paramtypes",[Ls,void 0]),n("design:returntype",Promise)],ui.prototype,"update",null),i([ms(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ui.prototype,"updateAll",null),e.setRegistry(new je);const gi="##VERSION##",fi="##PACKAGE##";dt.registerLibrary(fi,gi);export{Lt as AbsContextual,re as Adapter,Xt as AdapterTransaction,Ge as AuthKeys,Nr as AuthorizationError,Re as BackoffStrategy,es as BaseModel,Je as BigIntSequence,oe as Cascade,Hs as CleanUpTask,ps as ClientBasedService,Ys as CompositeTaskBuilder,ne as Condition,_r as ConnectionError,Pt as Context,Kt as ContextLock,$t as ContextualLoggedClass,Nt as DefaultAdapterFlags,ce as DefaultCascade,kt as DefaultContextFlags,Se as DefaultRepositoryFilters,We as DefaultSequenceOptions,Me as DefaultTaskEngineConfig,Os as Dispatch,Dr as ForbiddenError,Ot as GroupOperator,je as InjectablesRegistry,Ie as JitterStrategy,de as MethodQueryBuilder,Ut as MigrationError,Mt as MigrationRuleError,Ss as ModelService,Rt as MultipleSelectOperationKeys,_t as NonTransactionOperationKeys,Qe as NoneSequenceOptions,Ve as NumericSequence,qe as ObserverError,Ft as ObserverHandler,St as Operator,le as OperatorsMap,ae as OrderDirection,fi as PACKAGE_NAME,It as PaginationOperationKeys,ss as Paginator,ie as PagingError,Tt as PersistenceKeys,_s as PersistenceService,Ct as PreparedStatementKeys,Et as QueryClause,se as QueryError,Le as Repository,Bt as SelectOperationKeys,ks as Sequence,rs as SequenceModel,Jt as Serial,hs as Service,ds as Statement,Us as TaskBackoffBuilder,Bs as TaskBackoffModel,Ms as TaskBuilder,ni as TaskCancelError,Ks as TaskContext,ri as TaskControlError,ci as TaskEngine,Rs as TaskErrorModel,ti as TaskEventBus,Is as TaskEventModel,li as TaskEventService,Pe as TaskEventType,si as TaskFailError,qs as TaskHandler,Zs as TaskHandlerRegistry,Ps as TaskIOSerializer,$s as TaskLogEntryModel,zs as TaskLogger,Ls as TaskModel,ai as TaskRescheduleError,ii as TaskRetryError,ui as TaskService,Be as TaskStatus,Fs as TaskStepResultModel,js as TaskStepSpecModel,oi as TaskTracker,$e as TaskType,Ue as TasksKey,Dt as TransactionOperationKeys,Vt as UUID,jt as UnsupportedError,gi as VERSION,He as allowIf,fe as applyViewDecorator,vs as auth,ze as blockIf,Sr as cacheModelForPopulate,Cr as cascadeDelete,Rr as column,Ws as computeBackoffMs,fs as create,ar as createOrUpdate,jr as createdAt,Lr as createdBy,$r as createdByOnCreateUpdate,he as defaultQueryAttr,ws as del,Fe as generateInjectableNameForRepository,Ns as getAdapterTransaction,br as getAndConstructJunctionTable,Ds as getContextLock,Oe as getFilters,Qs as getLogPipe,Hr as getPkTypes,xr as getPopulateKey,Er as getTagForDeleteKey,Xe as index,Yt as injectableServiceKey,zt as isOperationBlocked,ei as isTaskError,Vr as manyToMany,mr as manyToManyOnCreate,Ar as manyToManyOnDelete,vr as manyToManyOnUpdate,Wr as manyToOne,pr as manyToOneOnCreate,yr as manyToOneOnDelete,fr as manyToOneOnUpdate,Jr as noValidateOn,Xr as noValidateOnCreate,Zr as noValidateOnCreateUpdate,Kr as noValidateOnUpdate,Qt as normalizeImport,Qr as oneToMany,ur as oneToManyOnCreateUpdate,hr as oneToManyOnDelete,dr as oneToManyOnUpdate,zr as oneToOne,or as oneToOneOnCreate,lr as oneToOneOnDelete,cr as oneToOneOnUpdate,xe as onlyOnBulk,me as onlyOnCreate,be as onlyOnDelete,Ee as onlyOnFilter,Ae as onlyOnSingle,ve as onlyOnTransactional,we as onlyOnUpdate,qr as persistentVersion,ir as pk,rr as pkDec,tr as pkOnCreate,Or as populate,Wt as prefixMethod,pe as prepared,qt as promiseSequence,ge as query,ys as read,ts as relation,Ye as repository,kr as repositoryFromTypeMetadata,ee as resolveBulkSequenceResult,As as roles,xs as route,nr as sequence,sr as sequenceDec,er as sequenceOnCreateUpdate,Vs as serializeError,bs as service,Js as sleep,Br as table,Gs as task,di as throttle,Pr as unique,Ir as uniqueOnCreateUpdate,ms as update,Ur as updatedAt,Fr as updatedBy,Ts as uuid,Cs as uuidCreateUpdateHandler,gr as validBidirectionalRelation,Gr as version,ye as view};
2
2
  //# sourceMappingURL=core.js.map