@decaf-ts/core 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +2 -2
  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/cjs/index.cjs +3 -3
  7. package/lib/cjs/migrations/Migration.cjs +16 -2
  8. package/lib/cjs/migrations/Migration.cjs.map +1 -1
  9. package/lib/cjs/migrations/MigrationService.cjs +48 -25
  10. package/lib/cjs/migrations/MigrationService.cjs.map +1 -1
  11. package/lib/cjs/tasks/TaskContext.cjs +3 -0
  12. package/lib/cjs/tasks/TaskContext.cjs.map +1 -1
  13. package/lib/cjs/tasks/TaskEngine.cjs +148 -69
  14. package/lib/cjs/tasks/TaskEngine.cjs.map +1 -1
  15. package/lib/cjs/tasks/builder.cjs +4 -0
  16. package/lib/cjs/tasks/builder.cjs.map +1 -1
  17. package/lib/cjs/tasks/constants.cjs +1 -0
  18. package/lib/cjs/tasks/constants.cjs.map +1 -1
  19. package/lib/cjs/tasks/models/TaskStepSpecModel.cjs +6 -0
  20. package/lib/cjs/tasks/models/TaskStepSpecModel.cjs.map +1 -1
  21. package/lib/esm/index.js +3 -3
  22. package/lib/esm/migrations/Migration.js +17 -3
  23. package/lib/esm/migrations/Migration.js.map +1 -1
  24. package/lib/esm/migrations/MigrationService.js +48 -25
  25. package/lib/esm/migrations/MigrationService.js.map +1 -1
  26. package/lib/esm/tasks/TaskContext.js +3 -0
  27. package/lib/esm/tasks/TaskContext.js.map +1 -1
  28. package/lib/esm/tasks/TaskEngine.js +148 -69
  29. package/lib/esm/tasks/TaskEngine.js.map +1 -1
  30. package/lib/esm/tasks/builder.js +4 -0
  31. package/lib/esm/tasks/builder.js.map +1 -1
  32. package/lib/esm/tasks/constants.js +1 -0
  33. package/lib/esm/tasks/constants.js.map +1 -1
  34. package/lib/esm/tasks/models/TaskStepSpecModel.js +6 -0
  35. package/lib/esm/tasks/models/TaskStepSpecModel.js.map +1 -1
  36. package/lib/types/index.d.cts +3 -3
  37. package/lib/types/index.d.mts +3 -3
  38. package/lib/types/migrations/Migration.d.cts +6 -2
  39. package/lib/types/migrations/Migration.d.mts +6 -2
  40. package/lib/types/migrations/MigrationService.d.cts +13 -5
  41. package/lib/types/migrations/MigrationService.d.mts +13 -5
  42. package/lib/types/migrations/types.d.cts +1 -0
  43. package/lib/types/migrations/types.d.mts +1 -0
  44. package/lib/types/tasks/TaskContext.d.cts +2 -0
  45. package/lib/types/tasks/TaskContext.d.mts +2 -0
  46. package/lib/types/tasks/TaskEngine.d.cts +5 -0
  47. package/lib/types/tasks/TaskEngine.d.mts +5 -0
  48. package/lib/types/tasks/builder.d.cts +1 -0
  49. package/lib/types/tasks/builder.d.mts +1 -0
  50. package/lib/types/tasks/models/TaskStepSpecModel.d.cts +1 -0
  51. package/lib/types/tasks/models/TaskStepSpecModel.d.mts +1 -0
  52. package/lib/types/tasks/types.d.cts +4 -0
  53. package/lib/types/tasks/types.d.mts +4 -0
  54. package/package.json +1 -1
package/dist/core.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,s,i,n,o){"use strict";var c,l,d,u;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_BY_PAGINATE="findByPaginate",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.FIND="find",u.PAGE="page",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf";const p="__self__";var h;e.PersistenceKeys=void 0,(h=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",h.INDEX="index",h.SEQUENCE="sequence",h.UNIQUE="unique",h.ADAPTER="adapter",h.INJECTABLE="decaf_{0}_adapter_for_{1}",h.SERVICE="service",h.TABLE="table",h.COLUMN="column",h.METADATA="__metadata",h.OWNERSHIP="ownership",h.CREATED_BY="ownership.created-by",h.UPDATED_BY="ownership.updated-by",h.RELATIONS="__relations",h.RELATION="relation",h.ONE_TO_ONE="relation.one-to-one",h.ONE_TO_MANY="relation.one-to-many",h.MANY_TO_ONE="relation.many-to-one",h.MANY_TO_MANY="relation.many-to-many",h.POPULATE="populate",h.NO_VALIDATE="no-validate",h.MIGRATION="migration",h.STATEMENT="statement",h.QUERY="query",h.UUID="uuid",h.TAG_FOR_DELETION="tag_for_deletion",h.INITIALIZATION="initialization",h.SHUTDOWN="shutdown",h.BY_KEY="by-key",h.AUTH="auth",h.AUTH_ROLE="auth-role",h.DECAF_ROUTE="DecafRoute",h.THROTTLE="throttle",h.PERSISTENT_VERSION="persistent-version",h.DEFAULT_QUERY_ATTR="default-query-attr";const g=Object.assign({},{ignoreDevSafeGuards:!1}),f=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1,maxConcurrentTransactions:-1}),y=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],m=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],_=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],w=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],v=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.PAGE];class b extends a.Context{constructor(e){super(e)}static{this.factory=e=>(new b).accumulate(Object.assign({},e,{timestamp:new Date,logger:e.logger||i.Logging.get()}))}static async from(e,t,r,...a){return this.factory(Object.assign({},t||{},{operation:e,model:r,affectedTables:r,args:a,logger:t?.logger||i.Logging.get()}))}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).reduce((e,t)=>(Array.isArray(t)?e.push(...t):null!=t&&e.push(t),e),[]).filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(e){try{return this.get(e)}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const n=i[0];if(!n)throw new a.InternalError("Invalid property access to overridden context: "+n);return n in e?e[n]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class E extends i.LoggedClass{logCtx(e,t,r=!1,a){return E.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...s){const n=(e,t,r)=>{const a=t.log||i.Logging.get();return t.log=e.context?a.clear().for(e):a.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let o=s.pop();const c=o instanceof b||(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"function"==typeof t.get&&"function"==typeof t.accumulate&&"function"==typeof t.override&&"function"==typeof t.toOverrides&&void 0!==t.cache})(o);if(o&&!c&&(s.push(o),o=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!o)throw new a.InternalError("Missing context. should be impossible");return n(this,{log:o.logger,ctx:o,ctxArgs:[...s,o]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,o].filter(Boolean)).then(t=>n(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class k extends E{constructor(){super(),this._Context=b}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let a=r.pop();return a instanceof b||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class T{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=E.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:n}=a;if(!n)return!0;try{return n(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>a.observer.refresh(e,t,r,...i)))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class O extends a.InternalError{constructor(e){super(e,O.name,500)}}class A extends a.InternalError{constructor(e,t=A.name){super(e,t,500)}}class x extends A{constructor(e){super(e,x.name)}}function C(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):t.Metadata.Symbol(t.Metadata.constr(e)).toString().replaceAll(".","-")}async function M(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}const D=[a.OperationKeys.CREATE,a.OperationKeys.READ,a.OperationKeys.UPDATE,a.OperationKeys.DELETE];function I(e){return D.includes(e)}function P(e,r,s){const i=t.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};if(!i?.handler)return!1;const n=void 0===s&&I(r)?"crud":r,o=void 0===s&&I(r)?r:s,c=i.args?.[0]||[];return i.handler(c,n,o)??!1}function N(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof x)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class B{generate(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})}static get instance(){return B._instance||(B._instance=new B),B._instance}}class R{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return R._instance||(R._instance=new R),R._instance}}class $ extends n.Lock{static{this.registry=new WeakMap}static for(e,t){let r=$.registry.get(e);return r||(r=new $(t),$.registry.set(e,r)),r}constructor(e){super(),this.waiters=[],this.permits=e}async acquire(e){if(0>=this.permits)return new Promise(e=>this.waiters.push(e));this.permits--}release(e){const t=this.waiters.shift();t?t():this.permits++}}class L{constructor(e,...t){this.adapter=e,this.depth=0}async begin(e){const{log:t,ctx:r}=this.adapter.logCtx([e],this.begin),a=r.getOrUndefined("maxConcurrentTransactions"),s="number"==typeof a?a:f.maxConcurrentTransactions;if(0===s)throw t.debug(`Rejecting transaction on adapter "${this.adapter.alias}": transactions are disabled (maxConcurrentTransactions=0)`),new O(`Transactions are disabled for adapter "${this.adapter.alias}" (maxConcurrentTransactions=0)`);s>0&&(t.silly(`Gating transaction on adapter "${this.adapter.alias}" (maxConcurrentTransactions=${s})`),this.semaphore=$.for(this.adapter,s),await this.semaphore.acquire(r))}async commit(e){const{ctx:t}=this.adapter.logCtx([e],this.commit);this.semaphore?.release(t)}async rollback(e,t){const{ctx:r}=this.adapter.logCtx([t],this.rollback);this.semaphore?.release(r)}}const F=t.Decoration.flavourResolver.bind(t.Decoration);t.Decoration.flavourResolver=e=>{const r=e=>{if(!e)return;const t=q._cache?.[e];return t?.flavour||e};try{const a=F(e);if(a&&a!==t.DefaultFlavour)return r(a);const s="function"==typeof e?e:e?.constructor,i=s&&"function"==typeof t.Metadata.registeredFlavour?t.Metadata.registeredFlavour(s):void 0;if(i&&i!==t.DefaultFlavour)return r(i);const n=q._currentFlavour;if(n){const e=q._cache?.[n];return e?.flavour?e.flavour:r(n)}}catch(e){return t.DefaultFlavour}};const j=Symbol("AdapterProxyCleanup");function U(e,t,r,a){if(!t)return e;const s=e,i=[],n=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):n.push(e.reason);if(n.length){r.warn(`Bulk ${a} encountered ${n.length} failure(s) while continuing`);const e=new AggregateError(n,`Bulk ${a} failed for ${n.length} item(s)`);throw e.results=s,e}return i}class q extends k{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!q._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return q._baseRepository}transactionLock(...e){return new L(this,...e)}async shutdownProxies(e,...t){e&&"string"!=typeof e&&(t=[e,...t],e=void 0);const{log:r}=this.logCtx(t,this.shutdownProxies);if(!this.proxies)return;if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);const s=async e=>{if(!e)return;const t=e[j];"function"==typeof t&&await t()};if(e)try{await s(this.proxies[e]),delete this.proxies[e]}catch(t){r.error("Failed to cleanup proxied adapter "+e,t)}else for(const e in this.proxies){try{await s(this.proxies[e])}catch(t){r.error("Failed to cleanup proxied adapter "+e,t);continue}delete this.proxies[e]}}async shutdown(...t){const{log:r,ctxArgs:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(e.PersistenceKeys.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:r}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...s),this.dispatch&&await this.dispatch.close(...s)})()}catch(e){throw new a.InternalError("Failed to create shutdown wrapper: "+e)}finally{this.internalLock.release(e.PersistenceKeys.SHUTDOWN)}try{await this.shutdownPromise}catch(e){r.error("Error during proxy shutdown",e)}finally{this.shutdownPromise=void 0}}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.internalLock=new n.Lock,this.alias in q._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);q._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in q._cache||(q._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),q._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),q._currentFlavour=this.alias)}Dispatch(){return new q._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new q._baseSequence(e,this,t)}async flags(e,s,n,...o){if("string"==typeof s)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(s)?s.length?s[0]:void 0:s,l=c?""+r.Model.tableName(c):"";n.correlationId=n.correlationId||`${l}|${e}|${B.instance.generate()}`;const d=n.logger||i.Logging.for(this),u=Object.assign({},f.cacheForPopulate,n.cacheForPopulate);return Object.assign({},f,n,{affectedTables:s?[...new Set([...(Array.isArray(s)?s:[s]).filter(Boolean),...n.affectedTables?Array.isArray(n.affectedTables)?n.affectedTables:[n.affectedTables]:[]])]:n.affectedTables,cacheForPopulate:u,args:o,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:s?t.Metadata.validationExceptions(Array.isArray(s)&&s[0]?s[0]:s,e):[],logger:d})}get Context(){return b}async context(e,t,a,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${a?Array.isArray(a)?a.map(e=>r.Model.tableName(e)):r.Model.tableName(a):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof b||(s.push(i),i=void 0);const n=(()=>{if(!i)return!1;try{return!!i.get("allowGenerationOverride")}catch{return!1}})();t=i?Object.assign({},i.toOverrides(),t):t,n&&(t.allowGenerationOverride=!0);const o=await this.flags("string"==typeof e?e:e.name,a,t,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const e=(new this.Context).accumulate({...i.cache,...o,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],e]}),e}const t=i.getOrUndefined("operation"),r=i.getOrUndefined("affectedTables");if(!t||t!==e||a&&a!==r){const e=(new this.Context).accumulate({...i.cache,...o,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],e]}),e}return i.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...s){const{log:i}=this.logCtx(s,this.prepare),n=t.segregate(),o=Object.entries(n.model).reduce((e,[s,i])=>{if(void 0===i)return e;const n=r.Model.columnName(t.constructor,s);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return e[n]=i,e},{});return t[e.PersistenceKeys.METADATA]&&(i.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(o,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:o,id:t[r.Model.pk(t.constructor)],transient:n.transient}}revert(t,s,i,n,...o){const{log:c,ctx:l}=this.logCtx(o,this.revert),d=r.Model.pk(s),u=new s;u[d]=i,c.silly(`Rebuilding model ${u.constructor.name} id ${i}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[r.Model.columnName(s,a)],e),u);return l.get("rebuildWithTransient")&&n&&(c.verbose("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${i}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.createAll);if(!t||!s)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==s.length)throw new a.ValidationError("Ids and models must have the same length");const c=r.Model.tableName(e);n.debug(`Creating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,r)=>()=>this.create(e,t,s[r],...i,o.override({noEmitSingle:!0})));return U(l?await M(d,!0):await M(d),l,n,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...s){const{log:i,ctx:n}=this.logCtx(s,this.readAll),o=r.Model.tableName(e);i.debug(`Reading ${t.length} entries ${o} table`);const c=!(n.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...s,n.override({noEmitSingle:!0})));return U(c?await M(l,!0):await M(l),c,i,a.BulkCrudOperationKeys.READ_ALL)}async updateAll(e,t,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.updateAll);if(t.length!==s.length)throw new a.InternalError("Ids and models must have the same length");const c=r.Model.tableName(e);n.debug(`Updating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,r)=>()=>this.update(e,t,s[r],...i,o.override({noEmitSingle:!0})));return U(l?await M(d,!0):await M(d),l,n,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return U(n?await M(o,!0):await M(o),n,s,a.BulkCrudOperationKeys.DELETE_ALL)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t);const r=this.log.for(this.observe);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(a&&o||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return t.Metadata.flavourOf(e)}static get currentFlavour(){if(!q._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return q._currentFlavour}static get current(){return q.get(this.currentFlavour)}static unregister(e){if(!e)return;const t=q._cache[e];t&&(delete q._cache[e],q._currentFlavour===e&&(q._currentFlavour=void 0),t.flavour&&q._cache[t.flavour]&&q._cache[t.flavour]===t&&delete q._cache[t.flavour])}static get(e){if(!e)return q.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return t.Metadata.flavouredAs(e).filter(r.Model.isModel)}catch(e){throw new a.InternalError(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const a=`${this.alias} - ${r.hashObj(e)}`;if(a in this.proxies)return this.proxies[a];let s;const i=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,a)},set:(e,t,r,a)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,a)});return Reflect.defineProperty(i,j,{value:async()=>{if(!s)return;const e=["cancel","close","destroy","disconnect"];for(const t of e){const e=s[t];if("function"==typeof e)try{const t=e.call(s);t instanceof Promise&&await t}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[a]=i,i}migrations(){return t.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}var G,z,Y,H,V;s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,b]),s.__metadata("design:returntype",Promise)],q.prototype,"context",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],q.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],q.prototype,"unObserve",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],q.prototype,"client",null),e.TaskStatus=void 0,(G=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",G.SCHEDULED="scheduled",G.RUNNING="running",G.FAILED="failed",G.SUCCEEDED="succeeded",G.CANCELED="canceled",G.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(z=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",z.FIXED="fixed",e.JitterStrategy=void 0,(Y=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",Y.FULL="full",e.TaskEventType=void 0,(H=e.TaskEventType||(e.TaskEventType={})).STATUS="status",H.UPDATE="update",H.LOG="log",H.PROGRESS="progress",H.ALL="all",e.TaskType=void 0,(V=e.TaskType||(e.TaskType={})).ATOMIC="atomic",V.COMPOSITE="composite";const Q="tasks",W={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};t.Metadata.tasks=(()=>t.Metadata.innerGet(Symbol.for(Q))).bind(t.Metadata),t.Metadata.taskFor=(e=>{const r=t.Metadata.tasks();return r?r[e]:void 0}).bind(t.Metadata),t.Metadata.validationExceptions=((s,i)=>{const n=t.Metadata.get(s,e.PersistenceKeys.NO_VALIDATE)||[],o=Object.entries(n).filter(([,e])=>e.includes(i)).map(([e])=>e);let c=[];return i!==a.OperationKeys.CREATE&&i!==a.OperationKeys.UPDATE||(c=r.Model.nestedRelations(s)),[...new Set([...o,...c])]}).bind(t.Metadata),t.Metadata.migrationsFor=(r=>{if(!(r=r??q.current))throw new a.InternalError("Could not get adapter for migrations");return t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),r.alias).map(e=>e.class)}).bind(t.Metadata),t.Metadata.migrations=(()=>{const r=t.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(r).flat().map(e=>[e.class.name,e.class])}).bind(t.Metadata),t.Metadata.relations=((r,s)=>{const i=t.Metadata.get(r,e.PersistenceKeys.RELATIONS);if(i){if(!s)return Object.keys(i);if(!i[s])throw new a.InternalError("No relations metadata found for property "+s);return i[s]}}).bind(t.Metadata),r.Model.relations=(e,a)=>t.Metadata.relations(e instanceof r.Model?e.constructor:e,a)||[],r.Model.nestedRelations=((a,s=[])=>{let i=[];const n=t.Metadata.get(a,e.PersistenceKeys.RELATIONS);if(!n||!Object.keys(n).length)return[...new Set([...s])];for(const e in n){const t=n[e];if(t?.class&&r.Model.relations(t.class)){const a=r.Model.relations(t.class).map(t=>`${e}.${t}`);s=[...s,...a],i=r.Model.nestedRelations(t.class,s)}}return[...new Set([...s,...i])]}).bind(r.Model),r.Model.generatedBySequence=((e,t)=>{const a="function"!=typeof e?e.constructor:e;return!!r.Model.sequenceFor(a).generated}).bind(r.Model),r.Model.fromTable=(s=>{const i=t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!i||!i[s]||!r.Model.get(i[s].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return r.Model.get(i[s].name)}).bind(r.Model),t.Metadata.createdBy=(r=>{const s=t.Metadata.get("function"!=typeof r?r.constructor:r,e.PersistenceKeys.CREATED_BY);if(!s)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return s}).bind(t.Metadata),t.Metadata.updatedBy=(r=>{const s=t.Metadata.get("function"!=typeof r?r.constructor:r,e.PersistenceKeys.UPDATED_BY);if(!s)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return s}).bind(t.Metadata),r.Model.tableName=s=>{if(!(s instanceof r.Model?r.Model.get(s.constructor.name):s))throw new a.InternalError("Unable to find model "+s);return t.Metadata.get(s instanceof r.Model?s.constructor:s,e.PersistenceKeys.TABLE)||(s instanceof r.Model?s.constructor.name:s.name)},r.Model.columnName=(a,s)=>t.Metadata.get(a instanceof r.Model?a.constructor:a,t.Metadata.key(e.PersistenceKeys.COLUMN,s))||s,r.Model.defaultQueryAttributes=(a,s=!1)=>{const i="function"==typeof a?a:a.constructor;return t.Metadata.get(i,t.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||(s?[r.Model.pk(a)]:[])},r.Model.sequenceName=(e,...t)=>[r.Model.tableName(e),...t].join("_"),r.Model.versionOf=(r=>{const s=t.Metadata.get(r.constructor),i=s?.[e.PersistenceKeys.PERSISTENT_VERSION],n=i&&"object"==typeof i?Object.keys(i)[0]:void 0,o=s?.[a.DBKeys.VERSION],c=o&&"object"==typeof o?Object.keys(o)[0]:void 0,l=n??c;if(!l)throw new a.InternalError("No version found for "+r.constructor.name);const d=r[l];if("number"!=typeof d||1>d)throw new a.InternalError("Invalid version number: "+d);return d}).bind(r.Model),r.Model.sequenceFor=(s,i)=>{const n="function"!=typeof s?s.constructor:s;let o=e.PersistenceKeys.SEQUENCE;const c=r.Model.pk(n);i&&i+""!=c+""||(i=c,o=a.DBKeys.ID),o=t.Metadata.key(o,i);const l=t.Metadata.get(n,o);if(!l)throw new a.InternalError(`No sequence options defined for property ${i+""}. did you use @sequence() or @pk()?`);return l},r.Model.indexes=a=>{const s=t.Metadata.get(a instanceof r.Model?a.constructor:a,e.PersistenceKeys.INDEX);return Object.keys(s||{}).reduce((t,r)=>{const a=s[r]||{};return t[r]=Object.keys(a).reduce((t,r)=>(t[r===p?e.PersistenceKeys.INDEX:`${e.PersistenceKeys.INDEX}_${r}`]=a[r],t),{}),t},{})},o.Injectables.services=()=>t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),o.Injectables.repositories=()=>t.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY)),r.Model.merge=((e,t,a)=>{const s=e=>Object.entries(e).reduce((e,[t,s])=>{let i=!1;try{"relation.one-to-one"===r.Model.relations(a,t).key&&(i=!0)}catch(e){i=!1}return(void 0!==s||i)&&(e[t]=s),e},{});return new(a=a||e.constructor)(Object.assign({},s(e),s(t)))}).bind(r.Model);class J extends a.InternalError{constructor(e){super(e,J.name,500)}}class X extends a.InternalError{constructor(e){super(e,X.name,500)}}class Z extends r.Model{constructor(e,t,a){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||a?(this.attr1=e,this.operator=t,this.comparison=a):r.Model.fromModel(this,e)}and(e){return Z.and(this,e)}or(e){return Z.or(this,e)}not(t){return new Z(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Z)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof Z){if(!(this.comparison instanceof Z)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return Z.group(t,e.GroupOperator.AND,r)}static or(t,r){return Z.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new Z(e,t,r)}static attribute(e){return(new Z.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Z(this.attr1,this.operator,this.comparison)}catch(e){throw new J(e)}}}}static builder(){return new Z.Builder}static from(e){return new Z(e)}}var ee,te;s.__decorate([r.required(),s.__metadata("design:type",Object)],Z.prototype,"attr1",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Z.prototype,"operator",void 0),s.__decorate([r.required(),s.__metadata("design:type",Object)],Z.prototype,"comparison",void 0),e.OrderDirection=void 0,(ee=e.OrderDirection||(e.OrderDirection={})).ASC="asc",ee.DSC="desc",e.Cascade=void 0,(te=e.Cascade||(e.Cascade={})).CASCADE="cascade",te.NONE="none";const re={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},ae={Equals:(e,t)=>Z.attribute(e).eq(t),Diff:(e,t)=>Z.attribute(e).dif(t),LessThan:(e,t)=>Z.attribute(e).lt(t),LessThanEqual:(e,t)=>Z.attribute(e).lte(t),GreaterThan:(e,t)=>Z.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Z.attribute(e).gte(t),In:(e,t)=>Z.attribute(e).in(t),Matches:(e,t)=>Z.attribute(e).regexp(t)},se=e=>e.charAt(0).toLowerCase()+e.slice(1);class ie extends i.LoggedClass{static get log(){return this._logger||(this._logger=i.Logging.for(ie.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const n=this.extractCore(e,s),o=this.extractSelect(e),c=this.extractGroupBy(e),l=this.buildWhere(n,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,n);return{action:a,select:o,selector:i,where:l,groupBy:c,orderBy:d,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?se(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(se).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(se).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),n=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&n.push(se(r))}return n.length>0?n:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach((t,a)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),c=o?ae[o]:ae.Equals;if(!c)throw Error("Unsupported operator "+o);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);n=0===a?d:i[a-1]===e.QueryClause.AND?n.and(d):n.or(d)}),n}static parseFieldAndOperator(e){for(const t of Object.keys(ae))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:se(r),operator:t}}return{field:se(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,r){const a=ie.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new J("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new J(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,n=t.slice(i)??[];let o,c,l;if(n.at(-1)instanceof a.Context&&n.pop(),n.length>=1){const t=n[0],r=this.extractOrderByField(e);o=this.getProperlyOrderByOrThrow(r,t)}return 2>n.length||"number"!=typeof n[1]||(c=n[1]),3>n.length||"number"!=typeof n[2]||(l=n[2]),{orderBy:o,limit:c,offset:l}}}function ne(){return t.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(r,a,s)=>t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.STATEMENT,a),!0))(r,a,s),args:[]}).apply()}function oe(e,r,a){return(s,i)=>{const n=a?.name||((e,r,a)=>{const s=(t.Metadata.get(e.constructor,r)||{})[a]||{};return Object.keys(s).length+1+""})(s,e,i),o=t.Metadata.key(e,i,n),c={...a||{},kind:r,attribute:i};return t.propMetadata(o,c)(s,i)}}function ce(e){return ge(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function le(e){return ge(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function de(e){return ge(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ue(e){return ge(e,y)}function pe(e){return ge(e,Object.values(a.OperationKeys))}function he(e){return ge(e,Object.values(a.BulkCrudOperationKeys))}function ge(e,s){return(i,n,o,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=E.prototype.logCtx(c,ge);return l.silly(`filtering ${n} event for${i?" "+(r.Model.tableName(i)||i):""} ${o}`),("string"==typeof i?i===r.Model.tableName(e)||i===e.constructor.name:t.Metadata.constr(e)===t.Metadata.constr(i))&&s.includes(n)}}const fe={onlyOnCreate:ce,onlyOnUpdate:le,onlyOnDelete:de,onlyOnTransactional:ue,onlyOnSingle:pe,onlyOnBulk:he};function ye(e){const t=Object.assign({},fe);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var me,_e,we,ve,Se,be,Ee;class ke extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=r.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ye(this)}constructor(e,r,s=!1,...i){super(r),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),r&&(ke.register(r,this,this.adapter.alias,s),e)&&t.Metadata.get(r,t.DecorationKeys.FLAVOUR)===t.DefaultFlavour&&t.uses(e.flavour)(r);const n=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(n,n[t+"Prefix"],e,n[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(n,n[this.updateAll.name+"Prefix"],this.updateAll,n[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new T}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,a);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,c,a)}async createAll(e,...t){if(!e.length)return e;const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,a)),o=n.map(e=>e.id);let c=n.map(e=>e.record);return c=await this.adapter.createAll(this.class,o,c,...i),c.map((e,t)=>this.adapter.revert(e,this.class,o[t],a.get("rebuildWithTransient")?n[t].transient:void 0,a))}async createAllPrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");if(n.silly(`handlerSetting: ${o}, validationSetting: ${c}`),!e.length)return[e,...i];const l=r.Model.sequenceFor(e[0]);let d=[];if(r.Model.generatedBySequence(this.class)?(l.name||(l.name=r.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...i)):r.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),o||await a.enforceDBDecorators(this,s,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=s.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const r=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(r);if(i)throw new a.ValidationError(i)}return[e,...i]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await a.enforceDBDecorators(this,r,o,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${r.Model.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,a)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${r.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}async update(e,...t){const{ctxArgs:a,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...a),this.adapter.revert(n,this.class,o,c,i)}async updatePrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");n.silly(`handlerSetting: ${o}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(s.get("applyUpdateValidation")&&(d=await this.read(l,s),s.get("mergeForUpdate")&&(e=r.Model.merge(d,e,this.class))),o||await a.enforceDBDecorators(this,s,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=s.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const r=await Promise.resolve(e.hasErrors(d,...t));if(r)throw new a.ValidationError(r.toString())}return[e,...i,d]}async updateAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,a));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,a.get("rebuildWithTransient")?n[t].transient:void 0,a))}async updateAllPrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");n.silly(`handlerSetting: ${o}, ignoredValidation: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(s.get("applyUpdateValidation")&&(d=await this.readAll(l,s),s.get("mergeForUpdate")&&(e=e.map((e,t)=>r.Model.merge(d[t],e,this.class)))),o||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,s,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[t]:void 0))),!c){const t=s.get("ignoredValidationProperties")||[];let r;n.silly("ignored validation properties: "+t),r=s.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(r);if(i)throw new a.ValidationError(i)}return[e,...i,d]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${r.Model.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,a)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${r.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(...o)}async listBy(t,a,...s){const{log:i,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return i.verbose(`listing ${r.Model.tableName(this.class)} by ${t} ${a}`),this.select().orderBy([t,a]).execute(...n)}async paginateBy(t,a,s={offset:1,limit:10},...i){s.offset=s.offset||1,s.limit=s.limit||10;const{offset:n,bookmark:o,limit:c}=s;if(!n&&!o)throw new J("PaginateBy needs a page or a bookmark");const{log:l,ctx:d,ctxArgs:u}=(await this.logCtx(i,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let p;if(l.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${c}`),o&&d.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>a===e.OrderDirection.ASC?this.attr(r.Model.pk(this.class)).gt(o):this.attr(r.Model.pk(this.class)).lt(o))()).orderBy([t,a]).paginate(c,...u);else{if(!n)throw new J("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,a]).paginate(c,...u)}const h=await p.page(n,o&&!d.get("paginateByBookmark")?o:void 0,...u);return p.serialize(h)}async find(t,a=e.OrderDirection.ASC,...s){if("string"!=typeof t)throw new J("Find value must be a string");const i=this.getDefaultQueryAttributes(),{log:n,ctxArgs:o}=(await this.logCtx(s,e.PreparedStatementKeys.FIND,!0)).for(this.find);n.verbose(`finding ${r.Model.tableName(this.class)} by default attributes ${i.join(", ")}`);const c=this.buildDefaultStartsWithCondition(t,i);return this.select().where(c).orderBy([i[0],a]).execute(...o)}async page(t,a=e.OrderDirection.ASC,s={offset:1,limit:10},...i){if("string"!=typeof t)throw new J("Page value must be a string");const n=s.offset||1,{offset:o,bookmark:c,limit:l}=s;if(!o&&!c)throw new J("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(i,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${r.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const f=l??10,y=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let _;if(c&&h.get("paginateByBookmark")){const t=r.Model.pk(this.class),s=a===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);_=await m.select().where(u.and(s)).orderBy([y,a]).paginate(f,...g)}else{if(!o)throw new J("PaginateBy needs a page or a bookmark");_=await m.select().where(u).orderBy([y,a]).paginate(f,...g)}const w=await _.page(n,c&&!h.get("paginateByBookmark")?c:void 0,...g);return _.serialize(w)}async findOneBy(t,s,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);n.verbose(`finding ${r.Model.tableName(this.class)} with ${t} ${s}`);const c=await this.select().where(this.attr(t).eq(s)).limit(1).execute(...o);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,a,...s){const{log:i,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return i.verbose(`finding ${r.Model.tableName(this.class)} with ${t} ${a}`),this.select().where(this.attr(t).eq(a)).execute(...n)}async findByPaginate(t,a,s={direction:e.OrderDirection.DSC,offset:1,limit:10},...i){s.direction=s.direction||e.OrderDirection.DSC,s.offset=s.offset||1,s.limit=s.limit||10;const{direction:n,offset:o,bookmark:c,limit:l}=s;if(!o&&!c)throw new J("FindByPaginate needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(i,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);d.verbose(`finding and paginating ${r.Model.tableName(this.class)} with ${t} ${a}`);const h=this.attr(t).eq(a);let g;if(c&&u.get("paginateByBookmark")){const a=r.Model.pk(this.class),s=n===e.OrderDirection.ASC?this.attr(a).gt(c):this.attr(a).lt(c);g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h.and(s)).orderBy([t,n]).paginate(l,...p)}else{if(!o)throw new J("FindByPaginate needs a page or a bookmark");g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h).orderBy([t,n]).paginate(l,...p)}const f=await g.page(o,c&&!u.get("paginateByBookmark")?c:void 0,...p);return g.serialize(f)}async countOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return s.verbose(`counting ${r.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...i)}async maxOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return s.verbose(`finding max of ${t} in ${r.Model.tableName(this.class)}`),this.max(t).execute(...i)}async minOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return s.verbose(`finding min of ${t} in ${r.Model.tableName(this.class)}`),this.min(t).execute(...i)}async avgOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return s.verbose(`calculating average of ${t} in ${r.Model.tableName(this.class)}`),this.avg(t).execute(...i)}async sumOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return s.verbose(`calculating sum of ${t} in ${r.Model.tableName(this.class)}`),this.sum(t).execute(...i)}async distinctOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return s.verbose(`finding distinct values of ${t} in ${r.Model.tableName(this.class)}`),this.distinct(t).execute(...i)}async groupOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return s.verbose(`grouping ${r.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...i)}async statement(t,...r){if(!ke.statements(this,t))throw new J("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const e=r.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new J("No default query attributes defined for "+r.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new J("Default query value must be a string");let a;for(const r of t){const t=this.attr(r).startsWith(e);a=a?a.or(t):t}if(!a)throw new J("No default query attributes available for "+r.Model.tableName(this.class));return a}attr(e){return Z.attr(e)}observe(e,r){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const a=this.log.for(this.observe),s=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,r,a,...i)=>"string"==typeof e?e===s:t.Metadata.constr(e)===t.Metadata.constr(this.class)),a.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,r),a.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,s,...i){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=this.logCtx(i,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(s)?s.map(e=>q._baseSequence.parseValue(r.Model.sequenceFor(this.class).type,e)):q._baseSequence.parseValue(r.Model.sequenceFor(this.class).type,s),...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(s,i,...n){let o;const c=t.Metadata.registeredFlavour(s),l=c&&c!==t.DefaultFlavour?c:void 0,d=i||l||t.Metadata.flavourOf(s)||q.currentFlavour;try{o=this.get(s,d)}catch(e){o=void 0}const u="function"==typeof o?o:void 0,p=i||l||t.Metadata.flavourOf(s)||u&&t.Metadata.get(u,e.PersistenceKeys.ADAPTER)||q.currentFlavour,h=p?q.get(p):void 0;if(!h)throw new a.InternalError("No registered persistence adapter found flavour "+p);if(o instanceof ke)return o;const g=[r.Model.tableName(s),h.alias].join(a.DefaultSeparator),f=u||h.repository();return delete this._cache[g],new f(h,s,...n)}static get(e,t){const s=r.Model.tableName(e);let i=s;if(t&&(i=[s,t].join(a.DefaultSeparator)),i in this._cache)return this._cache[i];if(s in this._cache)return this._cache[s];throw new a.InternalError("Could not find repository registered under "+s)}static register(e,t,s,i=!1){let n=r.Model.tableName(e);if(s&&(n=[n,s].join(a.DefaultSeparator)),n in this._cache&&this._cache[n]instanceof ke&&!i)throw new a.InternalError(n+" already has a registered instance");this._cache[n]=t}static statements(r,a){const s=r instanceof ke?r.constructor:r,i=t.Metadata.get(s,a?t.Metadata.key(e.PersistenceKeys.STATEMENT,a):e.PersistenceKeys.STATEMENT);return(a?i:Object.keys(i))||!1}static queries(r,a){const s=r instanceof ke?r.constructor:r;return t.Metadata.get(s,a?t.Metadata.key(e.PersistenceKeys.QUERY,a):e.PersistenceKeys.QUERY)}}function Te(s,i){if(!(i||(i=t.Decoration.flavourResolver(s instanceof r.Model?s.constructor:s))&&i!==t.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(s instanceof r.Model?s.constructor.name:s.name));return r.sf(e.PersistenceKeys.INJECTABLE,i,r.Model.tableName(s))}s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"listBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"paginateBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"find",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"page",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findOneBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findByPaginate",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"countOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(me="undefined"!=typeof K&&K)?me:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"maxOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(_e="undefined"!=typeof K&&K)?_e:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"minOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(we="undefined"!=typeof K&&K)?we:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"avgOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(ve="undefined"!=typeof K&&K)?ve:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"sumOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Se="undefined"!=typeof K&&K)?Se:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"distinctOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(be="undefined"!=typeof K&&K)?be:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"groupOf",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],ke.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],ke.prototype,"unObserve",null),q&&(q._baseRepository=ke);class Oe extends o.InjectableRegistryImp{get log(){return this.logger||(this.logger=i.Logging.for(this)),this.logger}constructor(){super()}get(a,s){const i=this.log.for(this.get);let n;try{n=super.get(a)}catch{}if(!n){let c;if("function"==typeof a?c=r.Model.get(a.name)||a:"symbol"!=typeof a&&"string"!=typeof a||(c=r.Model.get(a.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=s||t.Metadata.get(c,l)||t.Metadata.flavourOf(c);try{let e=d;try{d&&q.get(d)}catch{const t=q.current;t&&t.flavour===d&&(e=t.alias)}if(n=ke.forModel(c,e),n instanceof ke)return n;const r=d||t.Metadata.get(n.constructor,l)||t.Metadata.get(c,l);o.Injectables.register(n,Te(c,r))}catch(e){i.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ke.get(c,d);if("function"==typeof t){const e=d?q.get(d):q.current;if(!e)return;return new t(e,c)}}}return n}}function Ae(s,i){return(n,c)=>c?o.inject(t.Metadata.constr(s))(n,c):(t.Metadata.set(a.DBKeys.REPOSITORY,t.Metadata.key(i||q.currentFlavour,r.Model.tableName(s)),n),t.metadata(a.DBKeys.REPOSITORY,n.name)(s),i=i||t.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),ke.register(s,n),o.injectable(t.Metadata.constr(s),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:s}),e)})(n))}class xe extends a.InternalError{constructor(e){super(e,xe.name,500)}}function Ce(e,t,r,s,i){i.value=new Proxy(i.value,{async apply(i,n,o){((e,t,r)=>{if("function"!=typeof e?.logCtx)throw new O(`${t} on ${e?.constructor?.name??"UnknownClass"}.${r} requires a logCtx() method`)})(n,e,s+"");const{ctx:c,ctxArgs:l}=await n.logCtx(o,i.name,!0);let d;try{d=t(...o,...r,c)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(d)throw d;return i.call(n,...l)}})}e.AuthKeys=void 0,(Ee=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Ee.ROLES="roles",Ee.NAMESPACE="namespace";const Me={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},De=Me,Ie={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Pe=Object.assign({},Ie,{type:"BigInt"});function Ne(r,a,s){return t.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(r,a,s)=>(i,n)=>{"string"==typeof r&&(s=r,r=void 0,a=void 0),"string"==typeof a&&(s=a,a=void 0),!a&&r&&r.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(a=r,r=void 0);const o=a&&a.length?a.join("_"):p;return t.propMetadata(t.Metadata.key(e.PersistenceKeys.INDEX,n,o),{directions:r,compositions:a,name:s})(i,n)},args:[r,a,s]}).apply()}function Be(e){return"function"==typeof e}function Re(e,r,a){if(!a.type){const s=t.Metadata.type(e.constructor,r);if(![Number.name,String.name,BigInt.name].includes(s?.name||s))throw Error("Incorrrect option type");a.type=s}switch(a.type){case String.name||String.name.toLowerCase():case String:a.generated=void 0!==a.generated&&a.generated,a.type=String;break;case Number.name||String.name.toLowerCase():case Number:a.generated=void 0===a.generated||a.generated,a.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:a.type=BigInt,a.generated=void 0===a.generated||a.generated;break;case"uuid":case"serial":a.generated=!0;break;default:throw Error("Unsupported type")}void 0===a.generated&&(a.generated=!0)}async function $e(e,t,s,i){if(!t.type||!t.generated||i[s])return;let n;t.name||(t.name=r.Model.sequenceName(i,"pk"));try{n=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var o,c,l;o=i,c=s,l=await n.next(e),Reflect.set(o,c,l)}async function Le(e,t,s,i,n){if(!t.type||!t.generated)return;if(!t.name){const e=r.Model.pk(i,!0);if(null==e)throw new a.InternalError("Cannot generate sequence without an id for "+i.constructor.name);t.name=r.Model.sequenceName(i,e+"",s+"")}let o;try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const c=null!=n,l=void 0!==i[s]&&null!==i[s],d=!!e.get("allowGenerationOverride")&&l;if(l&&await o.ensureAtLeast(i[s],e),c&&!t.update)return;if(d)return;const u=await o.next(e);Reflect.set(i,s,u)}function Fe(s,i){return(n,o)=>{var c,l;t.prop()(n,o),Re(n,o,s),s.name||(s.name=(c=n.constructor,l="pk",Be(r.Model.sequenceName)?r.Model.sequenceName(c,l):[Be(r.Model.tableName)?r.Model.tableName(c):c?.name??"",l].filter(Boolean).join("_")));const d=[t.propMetadata(t.Metadata.key(a.DBKeys.ID,o),s),t.propMetadata(t.Metadata.key(e.PersistenceKeys.SEQUENCE,o),s),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.required(),a.readonly(),a.onCreate($e,s,i)];return s.generated&&d.push(a.generated()),t.apply(...d)(n,o)}}function Ke(s,i={},n){return(o,c)=>{t.prop()(o,c),Re(o,c,s);const l=[r.required(),t.propMetadata(t.Metadata.key(e.PersistenceKeys.SEQUENCE,c),s),a.onCreate(Le,{...s,...i},n)];return i.update&&l.push(a.onUpdate(Le,{...s,...i},n)),s.generated&&l.push(a.generated()),t.apply(...l)(o,c)}}function je(e){const r=Object.assign({},De);return delete r.generated,e=Object.assign({},r,e),t.Decoration.for(a.DBKeys.ID).define({decorator:Fe,args:[e,{priority:60}]}).apply()}async function Ue(e,t,s,i,n){const o=t.logger.for(Ue);if(!i){const t=r.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);i=ke.forModel(t,s),o.info("Retrieved "+i.toString())}let c;if(i=n?i.override(n):i,void 0===e[r.Model.pk(i.class)])o.info(`No pk found in ${r.Model.tableName(i.class)} - creating`),c=await i.create(e,t);else{o.info(`pk found in ${r.Model.tableName(i.class)} - attempting update`);try{c=await i.update(e,t),o.info("Updated "+r.Model.tableName(i.class))}catch(s){if(!(s instanceof a.NotFoundError))throw s;o.info("update Failed - creating new "+r.Model.tableName(i.class)),c=await i.create(e,t)}o.info("After create update: "+c)}return c}async function qe(e,t,s,i){const n=i[s];if(!n)return;if(We(i,t),"object"!=typeof n){const t=ot(i,s,this.adapter.alias),r=await t.override(this._overrides).read(n,e);return await at(e,i,s,n,r),void(i[s]=n)}const o="function"!=typeof t.class||t.class.name?t.class:t.class();if(!o)throw new a.InternalError("Could not find model "+t.class);const c=ke.forModel(o,this.adapter.alias),l=await c.override(this._overrides).create(n,e),d=r.Model.pk(l);await at(e,i,s,l[d],l),i[s]=l[d]}async function Ge(t,a,s,i){const n=i[s];if(!n)return;if(a.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof n){const e=ot(i,s,this.adapter.alias),r=await e.override(this._overrides).read(n,t);return await at(t,i,s,n,r),void(i[s]=n)}const o=await Ue(i[s],t,this.adapter.alias,void 0,this._overrides),c=r.Model.pk(o);await at(t,i,s,o[c],o),i[s]=o[c]}async function ze(t,a,s,i){const n=i[s];if(null==n)return;if(a.cascade.delete!==e.Cascade.CASCADE)return;const o=ot(i,s,this.adapter.alias);let c;c=n instanceof r.Model?await o.delete(i[s][o.pk],t):await o.delete(i[s],t),await at(t,i,s,c[o.pk],c)}async function Ye(e,t,a,s,i){const n=s[a];if(!n||!n.length)return;We(s,t);const o=e.logger.for(Ye),c=ot(s,a,this.adapter.alias),l=r.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of n){let r;"object"!=typeof t?(r=await c.override(this._overrides).read(t,e),o.debug("read: "+r[l])):(o.verbose("Creating or updating one-to-many model: "+t[l]),r=await Ue(t,e,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(r)} under ${r[l]}`),await at(e,s,a,r[l],r),d.add(r[l])}s[a]=[...d]}async function He(t,r,a,s,i){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return Ye.call(this,t,r,a,s,i)}async function Ve(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ke.forModel(c,this.adapter.alias):ot(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await at(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}async function Qe(e,t,s,i){const n=i[s];if(!n)return;We(i,t);const o=e.logger.for(Qe);if("object"!=typeof n){const t=ot(i,s,this.adapter.alias),r=await t.override(this._overrides).read(n,e);return await at(e,i,s,n,r),void(i[s]=n)}if(!(t.class instanceof r.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);o.info("Creating or updating many-to-one model: "+JSON.stringify(n));const c=await Ue(n,e,this.adapter.alias,void 0,this._overrides),l=r.Model.pk(c);o.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await at(e,i,s,c[l],c),i[s]=c[l]}function We(r,s){let i;const n="function"==typeof s.class&&s.class.name?s.class:s.class(),o=t.Metadata.get(n,e.PersistenceKeys.RELATIONS);if(o&&(i=Object.values(o)?.find(e=>{const t="function"==typeof e.class&&e.class.name?e.class:e.class();return r instanceof t})),!0===i?.populate&&!0===s?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Je(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Qe.call(this,t,r,a,s)}async function Xe(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const n="object"==typeof i,o=n?ke.forModel(i,this.adapter.alias):ot(s,a,this.adapter.alias),c=n?i[o.pk]:i,l=await o.override(this._overrides).delete(c);await at(t,s,a,c,l),s[a]=c}async function Ze(e,t,s,i){const n=i[s];if(!n||!n.length)return;We(i,t);const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c=e.logger.for(Ze),l=new Set([...n]);if("object"!==o){const r=ot(i,s,this.adapter.alias),a=await r.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<a.length;t++){const r=a[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(r)),await at(e,r,s,[...l.values()][t],a)}return await et.call(this,i,[...n],c,e,t),i[s]=[...l],void c.info("SET MANY TO MANY IDS: "+i[s])}const d=r.Model.pk(n[0].constructor),u=new Set;for(const t of n){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const r=await Ue(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(r)} under ${r[d]}`),await at(e,i,s,r[d],r),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=r.id,u.add(r[d])}const p=r.Model.pk(i.constructor);if(void 0===i[p]){const t=await(async(e,t,s)=>{const i=t[r.Model.pk(t.constructor)];if(void 0!==i)return i;const n=r.Model.sequenceFor(t.constructor);let o;n?.name||(n.name=r.Model.sequenceName(t,"pk"));try{return o=await e.adapter.Sequence(n,e._overrides),await o.next(s)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${n.name}: ${e}`)}})(this,i,e);i[p]=t}const h=await et.call(this,i,n,c,e,t);c.info("Junction model created: "+h.name),i[s]=[...u]}async function et(e,t,a,s,i){const{JunctionModel:n,fkA:o,fkB:c}=tt(e,t[0],i),l=[];for(const i of t){a.info("Creating or updating many-to-many junction model: "+JSON.stringify(i));const t={[o]:e instanceof r.Model?e[r.Model.pk(e.constructor)]:e,[c]:i instanceof r.Model?i[r.Model.pk(i.constructor)]:i},d=await Ue(new n(t),s,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=ke.forModel(n);await(e?.override(this._overrides).readAll(l))}return n}function tt(s,i,n){const o=r.Model.tableName(s);let c;if(i instanceof r.Model)c=r.Model.tableName(i);else if(r.Model.isModel(i)&&"function"==typeof i)c=i.name?i.name:i()?.name;else if(n?.class){const e="function"!=typeof n.class||n.class.name?n.class:n.class();c=r.Model.tableName(e)}if(!o||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=n?.joinTable?.name?n?.joinTable?.name:`${o}_${c}`,d=o?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends r.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),je({type:Number})(p.prototype,"id"),r.required()(p.prototype,d),r.required()(p.prototype,u);const h=r.model()(p);return t.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function rt(t,r,a){return r?[e.PersistenceKeys.POPULATE,t,r,a].join("."):[e.PersistenceKeys.POPULATE,t,a].join(".")}async function at(e,t,r,a,s){const i=rt(t.constructor.name,r,a),n=e.logger.for(at),o=e.get("cacheForPopulate")||{};let c=o[i],l=e.getOrUndefined("preferFromCache");if(!l)try{n.silly("retrieving from children"),l=e.getFromChildren("preferFromCache")||!1,l&&(c=(e.getFromChildren("cacheForPopulate")||{})[i])}catch(e){l=!1}return l&&n.debug("preferring previous cache: "+!!o[i]),o[i]=l&&c?c:s,e.accumulate({cacheForPopulate:o})}async function st(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=this,c=await(async(t,r,s,i)=>{let n,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){n=rt(r.constructor.name,s,t);try{if(c=u[n],!c)throw Error("Not found in cache")}catch(i){const n=ot(r,s,o.adapter.alias);if(!n)throw new a.InternalError("Could not find repo");c=await n.override(o._overrides).read(t,e)}l.push(c)}return l})(e,s,r,n?i:[i]);s[r]=n?c:c[0]}async function it(t,s,i,n,o){if(s.cascade.update!==e.Cascade.CASCADE)return;if(!o)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function c(e){return Array.isArray(e)?e.map(c):"object"!=typeof e?e:e[r.Model.pk(e)]}const l=c(n[i]),d=c(o[i]);if(void 0===d||r.isEqual(l,d))return;if(Array.isArray(l)!==Array.isArray(d))throw new a.InternalError("Cannot cascade update for different array types");const u=(Array.isArray(l)?l:[l]).filter(Boolean),p=(Array.isArray(d)?d:[d]).filter(Boolean).filter(e=>!u.includes(e)),h=ot(n,i,this.adapter.alias);if(!h)throw new a.InternalError("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${r.Model.tableName(h.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}const nt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function ot(e,s,i){if(!e)throw Error("No model was provided to get repository");let n,o=e instanceof r.Model?e.constructor:e;if(Array.isArray(e[s])||e[s]instanceof Set){const e=t.Metadata.get(o,t.Metadata.key(r.ValidationKeys.REFLECT,s,r.ValidationKeys.LIST))?.clazz;if(!e)throw new a.InternalError("Failed to find types decorators for property "+s);n=(Array.isArray(e)?[...e]:[e]).map(e=>"function"!=typeof e||e.name?e:e())}else n=r.Model.relations(o).includes(s)?t.Metadata.allowedTypes(o,s):t.Metadata.getPropDesignTypes(e instanceof r.Model?e.constructor:e,s)?.designTypes;o=n?.find(e=>!nt.includes((""+e.name).toLowerCase()));const c=ke.forModel(o,i);if(o!==c.class)throw new a.InternalError("Invalid repository class for "+s);return c}class ct extends a.BadRequestError{constructor(e,t=ct.name,r=401){super(e,t,r)}}class lt extends ct{constructor(e,t=lt.name){super(e,t,403)}}class dt extends a.InternalError{constructor(e){super(e,dt.name,503)}}function ut(r){return t.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:r=>a=>(t.Metadata.set(e.PersistenceKeys.TABLE,r||a.name.toLowerCase(),a),t.metadata(e.PersistenceKeys.TABLE,r||a.name.toLowerCase())(a)),args:[r]}).apply()}function pt(r){return t.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:r=>(a,s)=>t.propMetadata(t.Metadata.key(e.PersistenceKeys.COLUMN,s),r||s)(a,s),args:[r]}).apply()}async function ht(e,t,s,i){if(!i[s])return;const n=await this.select().where(Z.attribute(s).eq(i[s])).execute(),o=r.Model.pk(i),c=i[o];if(n.filter(e=>e[o]!==c).length)throw new a.ConflictError(`model already exists with property ${s} equal to ${JSON.stringify(i[s],void 0,2)}`)}async function gt(e,t,r,a){throw new ct("This adapter does not support user identification")}function ft(){return t.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(r,s)=>t.apply(a.onCreate(gt),t.propMetadata(e.PersistenceKeys.CREATED_BY,s),a.generated(e.PersistenceKeys.CREATED_BY))(r,s),args:[]}).apply()}function yt(){return t.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(r,s)=>t.apply(a.onUpdate(gt),t.propMetadata(e.PersistenceKeys.UPDATED_BY,s),a.generated(e.PersistenceKeys.UPDATED_BY))(r,s),args:[]}).apply()}function mt(){return a.timestamp([a.OperationKeys.CREATE])}function _t(){return a.timestamp()}async function wt(e,t,s,i){if("??sequence"===r.Model.tableName(i))return;const n=r.Model.pk(i,!0);if(null==n)throw new a.InternalError("Cannot generate persistent version without an id for "+i.constructor.name);const o={name:r.Model.sequenceName(i,n+"",s+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},c=await this.adapter.Sequence(o,this._overrides),l=void 0!==i[s]&&null!==i[s],d=!!e.get("allowGenerationOverride")&&l;if(l&&(await c.ensureAtLeast(i[s],e),d))return;const u=await c.next(e);i[s]=u}async function vt(e,t,s,i,n){if("??sequence"===r.Model.tableName(i))return;if(e.get("applyUpdateValidation")&&n&&i[s]!==n[s])throw new a.ValidationError(`Version mismatch: ${i[s]} !== ${n[s]}`);const o=r.Model.pk(i,!0);if(null==o)throw new a.InternalError("Cannot generate persistent version without an id for "+i.constructor.name);const c={name:r.Model.sequenceName(i,o+"",s+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},l=await this.adapter.Sequence(c,this._overrides),d=void 0!==i[s]&&null!==i[s],u=!!e.get("allowGenerationOverride")&&d;if(d&&(await l.ensureAtLeast(i[s],e),u))return;const p=await l.next(e);i[s]=p}function St(){const s=e.PersistenceKeys.PERSISTENT_VERSION;return(e,i)=>t.Decoration.for(s).define(t.prop(),t.propMetadata(t.Metadata.key(s,i),!0),a.generated(s),r.type(Number),a.onCreate(wt,{},{priority:70}),a.onUpdate(vt,{},{priority:70})).apply()(e,i)}function bt(e){return[()=>{const a="function"==typeof e&&e.name?e:e(),s=r.Model.pk(a);return(t.Metadata.allowedTypes(a,s)||[])[0]}]}function Et(...r){return(a,s)=>{const i=t.Metadata.get(a,t.Metadata.key(e.PersistenceKeys.NO_VALIDATE,s))||[],n=[...new Set([...i,...r])];return t.apply(t.metadata(t.Metadata.key(e.PersistenceKeys.NO_VALIDATE,s),n))(a,s)}}function kt(r,a){return t.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(r,a)=>(s,i)=>(t.propMetadata(r,a)(s,i),t.propMetadata(t.Metadata.key(e.PersistenceKeys.RELATIONS,i),Object.assign({},a,{key:r}))(s,i)),args:[r,a]}).apply()}class Tt extends r.Model{constructor(e){super(e)}}s.__decorate([mt(),s.__metadata("design:type",Date)],Tt.prototype,"createdAt",void 0),s.__decorate([_t(),s.__metadata("design:type",Date)],Tt.prototype,"updatedAt",void 0),e.SequenceModel=class extends Tt{constructor(e){super(e)}},s.__decorate([je({type:String,generated:!1}),s.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),s.__decorate([r.required(),Ne(),s.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=s.__decorate([ut("??sequence"),r.model(),s.__metadata("design:paramtypes",[Object])],e.SequenceModel);class Ot extends i.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,N(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.FIND_BY_PAGINATE}|${e.PreparedStatementKeys.LIST_BY}|${e.PreparedStatementKeys.PAGE_BY}|${e.PreparedStatementKeys.FIND}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof b?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof b||(this._bookmark=r);const n=ke.forModel(this.clazz,this.adapter.alias),o=this.query,{method:c,args:l,params:d}=o;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await n.statement(...r,...i);return this.apply(s)}let u;if(c===e.PreparedStatementKeys.FIND_BY?u=e.PreparedStatementKeys.FIND_BY_PAGINATE:c.startsWith(e.PreparedStatementKeys.FIND_BY)?u=c.replace(e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.PAGE_BY):c===e.PreparedStatementKeys.LIST_BY?u=e.PreparedStatementKeys.PAGE_BY:c!==e.PreparedStatementKeys.PAGE_BY&&c!==e.PreparedStatementKeys.FIND_BY_PAGINATE||(u=c),!u)throw new O(`Method ${c} is not supported for pagination`);const p=[u,...l];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==e.PreparedStatementKeys.PAGE_BY||p.length>2?h={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:p.push(d.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new X("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new X(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new O("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new a.SerializationError(e)}}apply(e){const t="string"==typeof e?Ot.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var At,xt,Ct,Mt,Dt,It,Pt;class Nt extends E{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=a.get("forcePrepareSimpleQueries"),o=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||c)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Nt)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new J("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?r.Model.get(e):e,!this.fromSelector)throw new J("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new J("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new J("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new J("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new J(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new J("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const i=await this.raw(s,...a);if(this.hasAggregation())return i;if(!this.selectSelector){const e=e=>this.processRecord(e,r);if(this.groupBySelectors?.length){const t=this.revertGroupedResults(i,e);return await this.applyAfterHandlersToResult(t,r)}if(Array.isArray(i)){const t=i.map(e);return await this.applyAfterHandlersToResult(t,r)}const t=e(i);return await this.applyAfterHandlersToResult(t,r)}return i}catch(e){throw new J(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ke.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new O("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const i=e=>this.processRecord(e,r);if(Array.isArray(s)){const e=s.map(i);return await this.applyAfterHandlersToResult(e,r)}const n=i(s);return await this.applyAfterHandlersToResult(n,r)}processRecord(e,t){const a=e[r.Model.pk(this.fromSelector)];return this.adapter.revert(e,this.fromSelector,a,void 0,t)}async applyAfterHandlersToResult(e,t){return t.getOrUndefined("afterQueryHandlers")?e instanceof r.Model?(await a.enforceDBDecorators(this.getRepository(),t,e,a.OperationKeys.READ,a.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterHandlersToResult(e,t))),e):e&&"object"==typeof e?(await Promise.all(Object.entries(e).map(([r,a])=>this.applyAfterHandlersToResult(a,t).then(t=>{e[r]=t}))),e):e:e}getRepository(){return ke.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const n={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,n.args=[...n.args||[],...t.args||[]]}if(i instanceof Z){const e=this.prepareCondition(i,r);t=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:n.method=a,n.args=[...n.args||[],i];break;case e.Operator.DIFFERENT:n.method=a+" diff",n.args=[...n.args||[],i];break;case e.Operator.REGEXP:n.method=a+" matches",n.args=[...n.args||[],i];break;case e.Operator.BIGGER:n.method=a+" bigger",n.args=[...n.args||[],i];break;case e.Operator.BIGGER_EQ:n.method=a+" bigger than equal";break;case e.Operator.SMALLER:n.method=a+" less",n.args=[...n.args||[],i];break;case e.Operator.SMALLER_EQ:n.method=a+" less than equal",n.args=[...n.args||[],i];break;case e.Operator.IN:n.method=a+" in",n.args=[...n.args||[],i];break;default:throw new J("Unsupported operator "+s)}return n}squash(t){const a=this.matchDefaultQueryCondition();if(a){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[a.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof Z)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let s;this.whereCondition&&(s=this.whereCondition.attr1);const i=this.orderBySelectors?.[0]?this.orderBySelectors[0]:s?[s,e.OrderDirection.DSC]:[r.Model.pk(this.fromSelector),e.OrderDirection.DSC],[n,o]=i,c={direction:o};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[n],params:c};return s&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[s,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=r.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const a=Array.from(new Set(t.map(String))),s=Array.from(new Set(e.attributes.map(String)));return a.length===s.length&&a.every(e=>s.includes(e))?{value:e.value,attributes:a}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof Z?this.collectStartsWithAttributes(r):void 0,t=s instanceof Z?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof Z?this.collectStartsWithAttributes(r):void 0)||(s instanceof Z?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},s={class:this.fromSelector,args:r,params:a};let n,o=e.QueryClause.FIND_BY;void 0!==this.countSelector?(o=e.QueryClause.COUNT_BY,n=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(o=e.QueryClause.SUM_BY,n=this.sumSelector):this.avgSelector?(o=e.QueryClause.AVG_BY,n=this.avgSelector):this.minSelector?(o=e.QueryClause.MIN_BY,n=this.minSelector):this.maxSelector?(o=e.QueryClause.MAX_BY,n=this.maxSelector):this.distinctSelector?(o=e.QueryClause.DISTINCT_BY,n=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(o=e.QueryClause.GROUP_BY_PREFIX,n=this.groupBySelectors[0]);const c=[o];if(n&&c.push(n),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&o!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&o===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),s.method=i.toCamelCase(c.join(" ")),s.params=a,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(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new J(e)}}toString(){return this.adapter.flavour+" statement"}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array]),s.__metadata("design:returntype",Object)],Nt.prototype,"select",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(At="undefined"!=typeof S&&S)?At:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"distinct",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(xt="undefined"!=typeof S&&S)?xt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"max",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Ct="undefined"!=typeof S&&S)?Ct:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"min",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Mt="undefined"!=typeof S&&S)?Mt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"sum",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Dt="undefined"!=typeof S&&S)?Dt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"avg",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(It="undefined"!=typeof S&&S)?It:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"count",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"from",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Z]),s.__metadata("design:returntype",Object)],Nt.prototype,"where",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String]),s.__metadata("design:returntype",Object)],Nt.prototype,"orderBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String]),s.__metadata("design:returntype",Object)],Nt.prototype,"thenBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Pt="undefined"!=typeof Key&&Key)?Pt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"groupBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Number]),s.__metadata("design:returntype",Object)],Nt.prototype,"limit",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Number]),s.__metadata("design:returntype",Object)],Nt.prototype,"offset",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[void 0]),s.__metadata("design:returntype",Promise)],Nt.prototype,"execute",null);class Bt extends E{constructor(){super(),this.observers=[],this.Context=b}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Bt?i.for(e,...t):i instanceof ke?i.override(e):i}})}override(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Bt?i.override(e,...t):i instanceof ke?i.override(e):i}})}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new T,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${B.instance.generate()}`;const a=t.logger||i.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},g,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof b||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return E.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const t=C(e),r=o.Injectables.get(t);if(r)return r;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof b||(t.push(r),r=void 0);const s=await Bt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...t);r=r?new b(r).accumulate({...s,parentContext:r}):(new b).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Bt.prototype.logCtx(t,this.boot),c=o.Injectables.services();if(!c||!Object.keys(c).length)throw new a.InternalError("No services registered for shutdown");for(const[e,t]of Object.entries(c))try{i.verbose(`Booting ${t.name} service...`);const r=o.Injectables.get(t);if(!r)throw new a.InternalError("Failed to resolve injectable for "+e);r instanceof Rt&&(i.verbose(`Initializing ${t.name} service...`),await r.boot(...n))}catch(e){throw new a.InternalError(`Failed to boot ${t.name} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof b||(t.push(r),r=void 0);const s=await Bt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...t);r=r?new b(r).accumulate({...s,parentContext:r}):(new b).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Bt.prototype.logCtx(t,this.shutdown),c=o.Injectables.services();if(!c||!Object.keys(c).length)throw new a.InternalError("No services registered for shutdown");for(const[e,t]of Object.entries(c).reverse())try{i.verbose(`Shutting down ${t.name} service...`);const r=o.Injectables.get(t);if(!r)throw new a.InternalError("Failed to resolve injectable for "+e);if(r instanceof Rt){i.verbose(`Gracefully shutting down ${t.name} service...`);try{await r.shutdown(...n)}catch(e){i.error(`Failed to gracefully shutdown ${t.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],Bt.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],Bt.prototype,"unObserve",null);class Rt extends Bt{constructor(){super()}async boot(...t){const{config:r,client:a}=await this.initialize(...t);this._config=r,this._client=a;const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info("Shutting down...")}}function $t(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&P(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",Promise)],Rt.prototype,"boot",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],Rt.prototype,"config",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],Rt.prototype,"client",null);const Lt=()=>$t(a.OperationKeys.CREATE),Ft=()=>$t(a.OperationKeys.READ),Kt=()=>$t(a.OperationKeys.UPDATE),jt=()=>$t(a.OperationKeys.DELETE);function Ut(r){return(a,s,i)=>{i||s?(t.prop()(a,s),r=r||t.Metadata.type(a.constructor,s)):r=r||a,r=C(r);const n=[];if(i&&"number"==typeof i.value)n.push(o.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(o.inject(r))}else t.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(o.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return t.apply(...n)(a,s,i)}}const qt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Gt extends Bt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ke.forModel(this.clazz)),this._repository}constructor(e){super(),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=qt(e);try{const e=Bt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}select(e){return this.repo.select(e)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let r;t=qt(t||e);try{r=Gt.get(t)}catch(e){r=void 0}if(r instanceof Gt)return r;const a=this;let i=class extends a{constructor(){super(e)}};return i=s.__decorate([Ut(t),s.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo._adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}s.__decorate([Lt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"create",null),s.__decorate([Lt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"createAll",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"delete",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"deleteAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"read",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"readAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,Object]),s.__metadata("design:returntype",Promise)],Gt.prototype,"query",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"update",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,Object]),s.__metadata("design:returntype",Promise)],Gt.prototype,"updateAll",null);class zt extends E{isSameObservedAdapter(e){if(!this.adapter)return!1;if(this.adapter===e)return!0;const t=this.adapter,r=e;return r instanceof q&&t.alias===r.alias&&t.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:n,ctx:o}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,l,d]=a,u=await t.call(r,c,l,d,...n),p=[c,i(e),l];return o.get("observeFullResult")&&p.push(Array.isArray(u)?u.map(e=>c(e)):c(u)),this.updateObservers(...p,...n).catch(t=>s.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(...e){}observe(e){if(!(e instanceof q))throw new O("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(e))return()=>this.unObserve(e);throw new O("Dispatch is already observing another adapter")}return this.adapter=e,this.models=q.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(!this.isSameObservedAdapter(e))throw new O("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,s,...i){if(!e)throw new a.InternalError("Model must be provided for observer update");const n=e&&"string"==typeof e?e:r.Model.tableName(e);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${n}:${t}`);const{log:o,ctxArgs:c,ctx:l}=this.logCtx(i,this.updateObservers);try{o.debug(`dispatching observer refresh for ${t}:${n}: ${s}${l.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,s,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Yt(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await B.instance.generate(s)}function Ht(s=!1,i,...n){"function"==typeof s&&(i=s,s=!1);const o=e.PersistenceKeys.UUID;return t.Decoration.for(o).define({decorator:(s,i,...n)=>{const o={update:s,seed:i,args:n},c=[r.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Yt,o,{priority:54})];return s&&c.push(a.onUpdate(Yt,o,{priority:54})),s||c.push(a.readonly()),t.apply(...c)},args:[s,i,...n]}).apply()}q&&(q._baseDispatch=zt);class Vt extends E{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ke.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:n,incrementBy:o,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return Vt.lock.execute(async()=>{const r=t||o;if(r%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof n&&n?.name?n.name:n,d=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(B.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(R.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new O(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}async ensureAtLeast(t,...r){const{ctx:s}=(await this.logCtx(r,a.OperationKeys.UPDATE,!0)).for(this.ensureAtLeast),{name:i}=this.options;if(!i)throw new a.InternalError("Sequence name is required");const n=this.parse(t),o=(e,t)=>"bigint"==typeof e||"bigint"==typeof t?BigInt(e)>BigInt(t):"number"==typeof e||"number"==typeof t?Number(e)>Number(t):e+"">t+"";return Vt.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(i,s)}catch(e){if(e instanceof a.NotFoundError)return;throw e}};for(;;)try{const r=await t();if(!r)return await this.repo.create(new e.SequenceModel({id:i,current:n}),s),n;const a=this.parse(r.current);return o(n,a)?(await this.repo.update(new e.SequenceModel({id:i,current:n}),s),n):a}catch(e){if(e instanceof a.ConflictError)continue;throw e}},i)}parse(e){return Vt.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return r.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new O(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Qt(e,...t){let r;if(e instanceof Gt&&(r=e.repo.adapter),e instanceof ke&&(r=e.adapter),e instanceof q&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function Wt(...e){return(r,s,i)=>{if(!i)throw new a.InternalError("This decorator only applies to methods");return t.method()(r,s,i),t.Metadata.set(r.constructor,t.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,s),{data:e}),i.value=new Proxy(i.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),n=i.getOrUndefined("transactionLock"),o=n||Qt(t);let c;o.depth++,n||(await o.begin(i),i.cache.put("transactionLock",o));try{c=await e.call(t,...r,i)}catch(e){const t=0===o.depth;if(o.depth=0,!t)try{await o.rollback(e,i)}catch(e){s.error("Failed to rollback transaction",e)}throw e}if(o.depth--,0===o.depth)try{await o.commit(i)}catch(e){throw new a.InternalError("Failed to commit transaction: "+e)}return c}}),i}}q._baseSequence=Vt,e.TaskBackoffModel=class extends r.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},s.__decorate([r.required(),r.type(String),r.option(e.BackoffStrategy),t.description("the backoff strategy"),s.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),s.__decorate([r.required(),t.description("base interval between attempts"),s.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),s.__decorate([r.required(),t.description("max interval"),s.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),s.__decorate([r.type(String),r.option(e.JitterStrategy),t.description("optional jitter strategy"),s.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([r.required(),t.description("The error message"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),s.__decorate([t.prop(),t.description("The error stack"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),s.__decorate([t.prop(),t.description("The error code"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),s.__decorate([t.prop(),t.description("The error details"),s.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends r.Model{constructor(e){if(super(e),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}},s.__decorate([je(),a.composed(["taskId","classification","uuid"],":"),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),s.__decorate([pt(),a.readonly(),r.required(),a.transient(),Ht(!1),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),s.__decorate([pt(),a.readonly(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),s.__decorate([r.date(),pt(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),s.__decorate([pt(),a.readonly(),r.required(),r.option(e.TaskEventType),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),s.__decorate([t.prop(),pt(),a.serialize(),a.readonly(),s.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=s.__decorate([ut("task_event"),r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Jt extends r.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof Z){const a=this.serializePlain(e,...t);return a[r.ModelKeys.ANCHOR]="??condition",a}return r.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const a=this.serializePlain(e,...t),s=this.getMetadata(e.constructor)??e.constructor?.name;return s&&(a[r.ModelKeys.ANCHOR]=s),a}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return t.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[r.ModelKeys.ANCHOR],a=this.rebuildObject(e);return t?"??condition"===t?Z.from(a):r.Model.build(a,t):a}rebuildObject(e){const t={};for(const[a,s]of Object.entries(e))a!==r.ModelKeys.ANCHOR&&(t[a]=this.rebuildValue(s));return t}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends r.Model{constructor(e){super(e),this.ts=new Date}},s.__decorate([r.date(),r.required(),s.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),s.__decorate([r.required(),r.option(i.LogLevel),s.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],e.TaskLogEntryModel.prototype,"step",void 0),s.__decorate([r.required(),t.prop(),s.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),s.__decorate([t.prop(),s.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends r.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},s.__decorate([je(),Ht(),t.description("the task id"),s.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),s.__decorate([pt(),r.required(),r.type(String),r.option(e.TaskType),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("defines a single or composite task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),s.__decorate([pt(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds task classification - must match @task()"),s.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),s.__decorate([pt(),t.prop(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("optional task name for ambiguity"),s.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),s.__decorate([pt(),t.prop(),t.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),s.__metadata("design:type",String)],e.TaskModel.prototype,"lock",void 0),s.__decorate([pt(),r.required(),r.type(String),r.option(e.TaskStatus),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["nextRunAt"]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["leaseExpiry"]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["scheduledTo"]),t.description("Holds the task current status"),s.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),s.__decorate([t.prop(),pt(),a.serialize(Jt),t.description("Holds task input"),s.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),s.__decorate([t.prop(),pt(),a.serialize(Jt),t.description("Holds the task output when successfully completed"),s.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the error for failed tasks"),s.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),s.__decorate([pt(),r.required(),r.min(0),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the current attempt"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),s.__decorate([pt(),r.min(1),r.required(),t.description("max attempts for the task"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),s.__decorate([pt(),r.required(),a.serialize(),t.description("backoff configuration"),s.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),s.__decorate([r.date(),pt(),t.description("Next execution timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),s.__decorate([r.date(),pt(),t.description("Task scheduled timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),s.__decorate([pt(),a.serialize(),t.description("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"dependencies",void 0),s.__decorate([t.prop(),pt(),t.description("Task lease owner identifier"),s.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),s.__decorate([r.date(),pt(),t.description("Task lease expiration timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the various steps definition and inputs - only for type === 'composite'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),s.__decorate([t.prop(),pt(),r.min(0),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the current step - only for type === 'composite'"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the step results - only for type === 'composite'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the task log entries"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),s.__decorate([pt(),mt(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("timestamp of creation"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),s.__decorate([pt(),_t(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("timestamp of last update"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),s.__decorate([pt(),ft(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the creator of the task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),s.__decorate([pt(),yt(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the creator of the task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=s.__decorate([t.description("Holds the current step when applicable"),ut("tasks"),r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([r.required(),t.description("The status of a step"),s.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),s.__decorate([t.prop(),t.description("The result of a successful step"),s.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),s.__decorate([t.prop(),t.description("the error of a failed step"),s.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),s.__decorate([t.prop(),r.min(1),t.description("Number of attempts taken to complete or fail this step"),s.__metadata("design:type",Number)],e.TaskStepResultModel.prototype,"attempt",void 0),e.TaskStepResultModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends r.Model{constructor(e){super(e),this.canFail=!1}},s.__decorate([r.required(),t.description("task handler type"),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),s.__decorate([r.minlength(1),t.description("optional task name for ambiguity"),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"name",void 0),s.__decorate([t.description("optional task step input"),t.prop(),s.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),s.__decorate([t.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),t.prop(),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"lock",void 0),s.__decorate([t.description("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),t.prop(),r.list(()=>String),s.__metadata("design:type",Array)],e.TaskStepSpecModel.prototype,"dependsOn",void 0),s.__decorate([t.prop(),t.description("Whether a failing step may be tolerated so the composite can continue"),s.__metadata("design:type",Boolean)],e.TaskStepSpecModel.prototype,"canFail",void 0),s.__decorate([t.prop(),r.min(1),t.description("Max attempts for this step. Defaults to 1 (no per-step retry)."),s.__metadata("design:type",Number)],e.TaskStepSpecModel.prototype,"maxAttempts",void 0),s.__decorate([t.prop(),a.serialize(),t.description("Step-level backoff config. Falls back to the parent task backoff when absent."),s.__metadata("design:type",e.TaskBackoffModel)],e.TaskStepSpecModel.prototype,"backoff",void 0),e.TaskStepSpecModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class Xt extends r.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,r.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}s.__decorate([r.required(),r.min(1e3),s.__metadata("design:type",Number)],Xt.prototype,"baseMs",void 0),s.__decorate([r.required(),r.option(e.JitterStrategy),s.__metadata("design:type",String)],Xt.prototype,"jitter",void 0),s.__decorate([r.gt("baseMs"),r.min(1e3),r.required(),s.__metadata("design:type",Number)],Xt.prototype,"maxMs",void 0),s.__decorate([r.required(),r.option(e.BackoffStrategy),s.__metadata("design:type",String)],Xt.prototype,"strategy",void 0);class Zt extends r.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Xt,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setLock(e){return this.lock=e,this}setDependencies(e){return this.dependencies=e,this}setDependsOn(e){return this.setDependencies(e)}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,r.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"classification",void 0),s.__decorate([t.prop(),s.__metadata("design:type",String)],Zt.prototype,"name",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"status",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"atomicity",void 0),s.__decorate([r.required(),s.__metadata("design:type",e.TaskBackoffModel)],Zt.prototype,"backoff",void 0),s.__decorate([t.prop(),s.__metadata("design:type",Object)],Zt.prototype,"input",void 0),s.__decorate([t.prop(),s.__metadata("design:type",String)],Zt.prototype,"lock",void 0),s.__decorate([t.prop(),r.list(()=>String),s.__metadata("design:type",Array)],Zt.prototype,"dependencies",void 0),s.__decorate([r.min(1),r.required(),s.__metadata("design:type",Number)],Zt.prototype,"maxAttempts",void 0);class er{constructor(e,t){this.parent=e,this.step=t}setClassification(e){return this.step.classification=e,this}setName(e){return this.step.name=e,this}setInput(e){return this.step.input=e,this}setLock(e){return this.step.lock=e,this}setDependsOn(e){return this.step.dependsOn=e,this}setCanFail(e){return this.step.canFail=e,this}setMaxAttempts(e){return this.step.maxAttempts=e,this}setBackoff(e){return this.step.backoff=e,this}addStep(e,t,r,a){return 4>arguments.length?this.parent.addStep(e,t,r):this.parent.addStep(e,t,r,a)}setSteps(e){return this.parent.setSteps(e)}build(){return this.parent}}class tr extends Zt{constructor(t){super(t),this.stepResults=[],r.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),this}addStep(t,r,a){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,o=arguments.length>=4,c=n&&"string"==typeof r?r:void 0,l=o||n&&"string"==typeof r?a:i?void 0:r,d=o?!!arguments[3]:!(!n||"string"==typeof r||!a),u=new e.TaskStepSpecModel({classification:t,name:c,input:l,canFail:d,createdAt:s,updatedAt:s});return this.steps.push(u),i?new er(this,u):this}}s.__decorate([r.list(()=>e.TaskStepSpecModel),s.__metadata("design:type",Array)],tr.prototype,"steps",void 0);class rr extends k{get type(){if(!this._type){const e=t.Metadata.get(this.constructor,Q);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}async catch(e,t,r){}}function ar(e){return t.Decoration.for(Q).define({decorator:e=>r=>{const a={type:e};return t.Metadata.set(Q,e,r),t.metadata(Q,a)(r)},args:[e]}).apply()}e.CleanUpTask=class extends rr{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof Z)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=Z.attr("status").eq(e.TaskStatus.SUCCEEDED).and(Z.attr("updatedAt").lte(t.successfulExpiry)),i=Z.attr("status").eq(e.TaskStatus.FAILED).and(Z.attr("updatedAt").lte(t.failedExpiry)),n=Z.attr("status").eq(e.TaskStatus.CANCELED).and(Z.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(n)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${n.length} tasks`),a.debug("deleted tasks:",n),n}catch(e){throw a.error("Error during task cleanup",e),e}}},s.__decorate([Ae(e.TaskModel),s.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=s.__decorate([ar("cleanup-task"),s.__metadata("design:paramtypes",[])],e.CleanUpTask);class sr{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(i.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}fatal(e,t,r){this.logger.fatal(e,t,r)}critical(e,t,r){this.logger.critical(e,t,r)}for(e,...t){return new Proxy(this,{get(r,a){if("logger"===a){const s=Reflect.get(r,a);try{return s.for(e,...t)}catch(e){r.error("Failed to bind task logger. received: "+(s&&s.constructor?s.constructor.name:s.name?s.name:"unknown"),e);try{r.trace(JSON.stringify(s,void 0,2))}catch(e){r.trace("unserializable output: "+(s.name||"unknown"))}throw e}}return Reflect.get(r,a)}})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function ir(t,r={logProgress:!0,logStatus:!0,style:!0}){return async a=>{switch(t=t.for(a.taskId,{style:!1}),a.classification){case e.TaskEventType.LOG:{const e=a.payload.map(e=>Array.isArray(e)?e:[e.level,e.msg,e.meta]);for(let[a,s,n]of e){r.style||(s=i.style(s),s=s.clear().toString());const e=[s];a===i.LogLevel.verbose&&e.push(1),e.push(n);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=a.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=a.payload?.status??a.payload;let s=i.style(r);switch(r){case e.TaskStatus.SUCCEEDED:s=s.green.bold;break;case e.TaskStatus.RUNNING:s=s.blue.bold;break;case e.TaskStatus.PENDING:s=s.yellow;break;case e.TaskStatus.WAITING_RETRY:s=s.yellow.bold;break;case e.TaskStatus.FAILED:s=s.red.bold;break;case e.TaskStatus.CANCELED:s=s.magenta.bold;break;case e.TaskStatus.SCHEDULED:s=s.cyan;break;default:t.warn("Received unknown task status: "+a.payload)}t.info("### STATUS "+s)}break;case e.TaskEventType.UPDATE:if(r.logProgress){const{currentStep:e,totalSteps:r,output:s}=a.payload??{},i=s?.added,n=s?.insertionIndex,o=null!=i?` (+${i} at index ${n})`:"";t.info(`### UPDATE step ${e}/${r}${o}`)}break;default:t.warn("Unhandled task event classification: "+a.classification)}}}function nr(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function or(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function cr(e){return new Promise(t=>setTimeout(t,e))}class lr extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=lr.name,Object.setPrototypeOf(this,lr.prototype)}}class dr extends b{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(e){this.cache.put("step",e)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new lr({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?or(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const r=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t));return{afterCurrent:async e=>{const t=this.getOrUndefined("scheduleCompositeSteps");if(!t)throw new a.InternalError("scheduleSteps().afterCurrent() is only available while running a composite task step");await t(r,e)},atEnd:async e=>{const t=this.getOrUndefined("scheduleCompositeStepsAtEnd");if(!t)throw new a.InternalError("scheduleSteps().atEnd() is only available while running a composite task step");await t(r,e)}}}constructor(e){super(e)}}class ur{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=t.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class pr extends T{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:n}=q.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class hr extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class gr extends hr{constructor(e,t,r){super(gr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class fr extends hr{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(fr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class yr extends hr{constructor(e,t,r){super(yr.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class mr extends hr{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(mr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class _r{constructor(t,a){this.bus=t,this.task=a,this.resolved=!1,this.unregistration=t.observe(this,(t,a,s,...i)=>s.startsWith(this.task.id)&&(t===e.TaskEventModel||t===r.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(ir(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=(r.payload??[]).map(e=>Array.isArray(e)?e:[e.level,`${e.ts} - ${e.msg}`,e.meta]);await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}onUpdate(t){const r=async(r,a)=>{r.classification===e.TaskEventType.UPDATE&&await t(r,a)};return this.pipe(r,e.TaskEventType.UPDATE),()=>{this.pipes?.[e.TaskEventType.UPDATE]?.delete(r)}}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,n);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(t.classification!==e.TaskEventType.STATUS)return;if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new b),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new gr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new yr(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new fr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new mr(this.task.id,r,a);default:return new gr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class wr extends k{get Context(){return dr}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,e.TaskModel,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,e.TaskEventModel,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(e,t){const r=new dr(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1;const t=Object.assign({},W.autoShutdown,e.autoShutdown);this.config=Object.assign({},W,e,{autoShutdown:t,bus:e.bus||new pr,registry:e.registry||new ur}),this.idleDelayMs=this.config.pollMsIdle}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const n=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${n.id}`),t?{task:n,tracker:new _r(this.bus,n)}:n}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new _r(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await cr(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const n=await this.tasks.update(s,a);return await this.emitStatus(a,n,e.TaskStatus.CANCELED,i),n}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.idleDelayMs=this.config.pollMsIdle,this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(Z.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const n=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(n),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(n),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},a=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),s=r.backoffStepMs??0;for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e)));const i=0===e.length;if(i)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+s,a),this.idleDelayMs>=a)return t.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(t)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const n=i?this.idleDelayMs:this.config.pollMsBusy;await cr(Math.max(n,0))}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=Z.attribute("status").eq(e.TaskStatus.PENDING),i=Z.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(Z.attribute("nextRunAt").lte(a)),n=Z.attribute("status").eq(e.TaskStatus.RUNNING).and(Z.attribute("leaseExpiry").lte(a)),o=Z.attribute("status").eq(e.TaskStatus.SCHEDULED).and(Z.attribute("scheduledTo").lte(a)),c=s.or(i).or(n).or(o),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}if(!await this.isRunnable(i,r))return null;const n=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,r)}catch{return null}}isTaskFinished(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t)}parseTaskDependency(e){const t=e?.trim();if(!t)return;const r=t.lastIndexOf(":");if(0>=r||r>=t.length-1)return{taskId:t};const a=t.slice(0,r).trim(),s=t.slice(r+1).trim();return a&&s?{taskId:a,stepRef:s}:{taskId:t}}normalizeDependencies(e){if(!e)return[];let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{t=[t]}return t instanceof Set&&(t=Array.from(t)),Array.isArray(t)?t.filter(e=>"string"==typeof e).map(e=>this.parseTaskDependency(e)).filter(Boolean):[]}resolveDependencyStepIndex(e,t){const r=t.trim();if(!r)return;const a=Number(r);if(Number.isInteger(a)&&a>=0)return a;const s=this.normalizeSteps(e.steps).findIndex(e=>e.name===r||e.classification===r);return 0>s?void 0:s}async areDependenciesSatisfied(e,t){if(!e.length)return!0;const r=Array.from(new Set(e.map(e=>e.taskId))),a=new Map;try{const e=await this.tasks.readAll(r,t);for(const t of e)t?.id&&a.set(t.id,t)}catch{return!1}for(const t of e)try{const e=a.get(t.taskId);if(!e)return!1;if(!t.stepRef){if(!this.isTaskFinished(e.status))return!1;continue}const r=this.resolveDependencyStepIndex(e,t.stepRef);if(null==r)return!1;const s=this.normalizeStepResults(e.stepResults)[r];if(!s||!this.isTaskFinished(s.status))return!1}catch{return!1}return!0}getStepLock(t,r){if(t.atomicity!==e.TaskType.COMPOSITE)return;const a=this.normalizeSteps(t.steps);if(!a.length)return;const s=a[r??0];return s?.lock}async hasLockConflict(t,r,a){const s=[t.lock,this.getStepLock(t,r)].filter(e=>!!e&&"string"==typeof e);if(!s.length)return!1;const i=await this.tasks.select().where(Z.attribute("status").eq(e.TaskStatus.RUNNING)).execute(a);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(e=>!!e&&"string"==typeof e).some(e=>s.includes(e)))return!0;return!1}async isRunnable(t,r){const a=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(a,r))return!1;const s=t.atomicity===e.TaskType.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,r)}async executeClaimed(t){const{ctx:r,log:s}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),n=this;let o=Promise.resolve();const c=new dr(r).accumulate({taskId:t.id,logger:new sr(s,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=n.normalizePipeArgs(e);r.length&&(o=o.then(async()=>{const[e,a]=await n.appendLog(this,t,r);Object.assign(t,e),await n.emitLog(this,t.id,a)}),await o)},flush:async()=>c.logger.flush(c.pipe),progress:async e=>{await this.emitProgress(c,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let l,d;await this.emitStatus(c,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,c);try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(l=e,d=t.input,s.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,c),await c.flush(),s.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const i=await this.tasks.update(t,c);Object.assign(t,i),c.logger.info(`task ${t.id} success state ${t.status}`),s.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(c,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{await c.flush()}catch{}try{const e=await this.tasks.read(t.id,c);Object.assign(t,e)}catch{}if(r instanceof lr)return void await this.handleTaskStateChange(r.request,t,c);try{await(l?.catch?.(d,r,c))}catch(e){s.error("task handler catch() hook failed",e)}if(s.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=or(r);if(a<t.maxAttempts){const o=nr(a,this.normalizeBackoff(t.backoff)),l=new Date(Date.now()+o);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=l,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const d=await this.tasks.update(t,c);Object.assign(t,d),s.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await c.pipe(i.LogLevel.warn,"Retry scheduled",{nextRunAt:l,delayMs:o,attempt:a}),await this.emitStatus(c,t,e.TaskStatus.WAITING_RETRY,n,r)}else{t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const o=await this.tasks.update(t,c);Object.assign(t,o),s.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await c.pipe(i.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(c,t,e.TaskStatus.FAILED,n,r)}}}async handleTaskStateChange(t,r,s){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.CANCELED,a),void await s.pipe(i.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,n=nr(a,this.normalizeBackoff(r.backoff)),o=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+n),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=o,r.scheduledTo=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.WAITING_RETRY,c),void await s.pipe(i.LogLevel.warn,"Retry requested",{nextRunAt:o,delayMs:n,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const n=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=n,r.nextRunAt=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.SCHEDULED,n),void await s.pipe(i.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite);let s=this.normalizeSteps(t.steps),n=t.currentStep??0;const o=this.normalizeStepResults(t.stepResults),c=(e,t)=>{r.cacheResult(e,t),a instanceof dr&&a!==r&&a.cacheResult(e,t)};for(let r=0;r<o.length;r+=1){const a=o[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=s[r];if(!e)continue;const i=`${t.id}:step:${r}`;c(e.classification,a.output),c(i,a.output)}}for(;n<s.length;){r.setStep(n);const l=s[n],d=this.registry.get(l.classification);if(!d)throw Error("No task handler registered for composite step: "+l.classification);const u=this.normalizeDependencies(l.dependsOn);await this.areDependenciesSatisfied(u,r)||r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${n} (${l.classification})`),await this.hasLockConflict(t,n,r)&&r.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${n} (${l.classification})`),t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await r.progress({currentStep:n,totalSteps:s.length});const h=n;r.cache.put("scheduleCompositeSteps",async(a,i)=>{const n=i.logger.for("scheduleSteps.afterCurrent"),o=this.normalizeSteps(a);if(!o.length)return;const c=this.normalizeSteps(t.steps),l=Math.min(h+1,c.length);c.splice(l,0,...o),t.steps=c;const d=await this.tasks.update(t,r);Object.assign(t,d),s=this.normalizeSteps(t.steps),n.verbose(`Inserted ${o.length} steps at index ${l}`);const u=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:h,totalSteps:s.length,output:{added:o.length,insertionIndex:l}});this.bus.emit(u,r)}),r.cache.put("scheduleCompositeStepsAtEnd",async(a,i)=>{const n=i.logger.for("scheduleSteps.atEnd"),o=this.normalizeSteps(a);if(!o.length)return;const c=this.normalizeSteps(t.steps),l=c.length;c.push(...o),t.steps=c;const d=await this.tasks.update(t,r);Object.assign(t,d),s=this.normalizeSteps(t.steps),n.verbose(`Appended ${o.length} steps at tail (index ${l})`);const u=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:h,totalSteps:s.length,output:{added:o.length,insertionIndex:l}});this.bus.emit(u,r)}),await r.pipe([i.LogLevel.info,`Composite step ${n+1}/${s.length}: ${l.classification}`]);const g=l.maxAttempts??1;let f,y=0;for(;g>y;)try{const a=await d.run(l.input,r);await r.flush();const i=new Date;o[h]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:a,attempt:y+1,createdAt:i,updatedAt:i});const u=`${t.id}:step:${h}`;c(l.classification,a),c(u,a),n=h+1,t.stepResults=o,t.currentStep=n;const p=await this.tasks.update(t);Object.assign(t,p),await this.emitProgress(r,t.id,{currentStep:n,totalSteps:s.length,output:a}),f=void 0;break}catch(e){if(y++,f=e,g>y){const e=nr(y,this.normalizeBackoff(l.backoff??t.backoff));await r.pipe(i.LogLevel.warn,`Composite step ${n} attempt ${y}/${g} failed, retrying in ${e}ms`,{classification:l.classification,attempt:y,delay:e}),await cr(e),await r.heartbeat()}}if(f){const s=new Date,i=!0===l.canFail,c=or(f);if(o[n]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:c,attempt:y,createdAt:s,updatedAt:s}),i)try{await(d.catch?.(l.input,f,r))}catch(e){a.logger.warn("composite step catch() hook failed",{error:e})}t.stepResults=o,t.error=i?void 0:c,i?(n=h+1,t.currentStep=n):t.currentStep=n;const u=await this.tasks.update(t);if(Object.assign(t,u),!i)throw f}}return{stepResults:o}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=Array.isArray(a)&&Array.isArray(a[0]),i=r.atomicity===e.TaskType.COMPOSITE?t instanceof dr?t.step??r.currentStep:r.currentStep:void 0,n=(s?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a,step:i})),o=[...r.logTail??[],...n].slice(-this.config.logTailMax);r.logTail=o;try{return[await this.tasks.update(r,t),n]}catch{return[r,[]]}}async emitStatus(t,r,a,s,i){t instanceof dr&&await t.flush();const n={status:a};s&&s instanceof e.TaskErrorModel?n.error=s:s&&(n.output=s),r.nextRunAt&&(n.nextRunAt=r.nextRunAt),r.scheduledTo&&(n.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,n),c=void 0!==i?Object.assign({},n,{originalError:i}):n,l=new e.TaskEventModel({...o,payload:c});this.bus.emit(l,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta,step:e.step})));this.bus.emit(s,t)}normalizePipeArgs(e){if(!e.length)return[];if(1===e.length){const t=e[0];return Array.isArray(t)?0===t.length?[]:Array.isArray(t[0])?t.filter(Array.isArray):[t]:[]}const[t,r,a]=e;return"string"!=typeof t||"string"!=typeof r?[]:[[t,r,a]]}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class vr extends Rt{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...e){const t=e.shift();if(!t||t instanceof b)throw new a.InternalError("No/invalid config provided");if(!t.adapter)throw new a.InternalError("No adapter provided");return{client:new(t.engine||wr)(t),config:t}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}select(e){return this.tasks.select(e)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.tasks.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.tasks.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.tasks.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.tasks?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.tasks,s)}async update(e,...t){throw new O("Updates to tasks are not available")}async updateAll(e,...t){throw new O("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...a)}refresh(e,t,r,...a){return this.tasks.refresh(e,t,r,...a)}observe(e,t){return this.tasks.observe(e,t)}unObserve(e){return this.tasks.unObserve(e)}updateObservers(e,t,r,...a){return this.tasks.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.tasks._adapter.logCtx([this.tasks.class,...e],t,r,this.tasks._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}var Sr;function br(e){if(0>=e)throw new a.InternalError("splitByCount: count must be greater than zero");return t=>{const r=[];for(let a=0;a<t.length;a+=e)r.push(t.slice(a,a+e));return r}}function Er(e){if(0>=e)throw new a.InternalError("splitBySize: maxBytes must be greater than zero");return t=>{const r=[];let a=[],s=0;for(const i of t){const t=kr(i);a.length>0&&s+t>e?(r.push(a),a=[i],s=t):(a.push(i),s+=t)}return a.length>0&&r.push(a),r}}function kr(e){if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}}function Tr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}s.__decorate([Lt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[e.TaskModel,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"create",null),s.__decorate([Lt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"createAll",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"delete",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"deleteAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"read",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"readAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"query",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[e.TaskModel,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"update",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"updateAll",null),e.ThrottleMode=void 0,(Sr=e.ThrottleMode||(e.ThrottleMode={})).BY_COUNT="count",Sr.BY_SIZE="size";const Or=Object.assign({},f,{persistMigrationSteps:!0});class Ar{constructor(e="migration-task"){this.builder=(new tr).setClassification("migration-composite").setName(e).setMaxAttempts(1)}addMigrationStep(e){return this.builder.addStep("migration",e),this}addStep(e,t){return this.builder.addStep(e,t),this}build(){return this.builder.build()}}class xr{isVersionHint(e){return!!e}normalize(e,t){return t&&e&&(e.includes(t)||e===t)?t:e||t||"migration"}compare(e,t){return e.localeCompare(t)}gt(e,t){return this.compare(e,t)>0}lte(e,t){return 0>=this.compare(e,t)}}class Cr extends Rt{constructor(){super(),this.versioning=new xr,this.allowedReferences=void 0,this.queuedTaskChain=[],this.reference=Cr.name,this.precedence=null}static async migrateAdapters(e,t={},...r){const s=t.flavours?.length?new Set(t.flavours):void 0,i=e.filter(e=>!s||s.has(e.alias)),n=new Set(e.map(e=>e.alias).filter(Boolean)),o=t.taskService?.client,c=o?.adapter?.alias||o?.adapter?.flavour;if(c&&n.has(c))throw new a.InternalError(`TaskEngine adapter alias "${c}" cannot participate in the migration targets`);const l=[];for(const e of i){const a=e.alias,s=t.handlers?.[a]||t.handlers?.[e.flavour]||{},n=new Cr;l.push(n),await n.boot({persistenceFlavour:a,targetVersion:t.toVersion,taskMode:!!t.taskMode,includeGenericInTaskMode:!(t.taskMode&&i.length>1),retrieveLastVersion:s.retrieveLastVersion,setCurrentVersion:s.setCurrentVersion,taskService:t.taskService,versioning:t.versioning,references:t.references}),t.taskMode?await n.migrateViaTasks(void 0,void 0,...r):await n.migrateNormally(void 0,void 0,...r)}return l}async initialize(...t){const{log:r,ctx:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);try{Bt.get(e.PersistenceKeys.PERSISTENCE)}catch(e){a.get("ignoreDevSafeGuards")||r.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:Or,Or);return this.versioning=s.versioning||new xr,this.allowedReferences=s.references?.length?new Set(s.references):void 0,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?q.get(s.persistenceFlavour):void 0}}async down(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(i.style("Cleaning up after all migrations").green.bold)}normalizeVersion(e,t){return this.versioning.normalize(e,t)}extractPrecedenceTokens(e){const t=e.precedence;return t?(Array.isArray(t)?t:[t]).map(e=>{if(e&&"string"!=typeof e)return"function"==typeof e?e.name:"string"==typeof e.reference?e.reference:e.constructor?.name?e.constructor.name:void 0}).filter(e=>!!e):[]}referencesMigration(e,t){const r=this.extractPrecedenceTokens(e);return!!r.length&&(r.includes(t.reference)||r.includes(t.migration?.constructor?.name))}precedenceHint(e){return"string"==typeof e.precedence?e.precedence:void 0}compareByPrecedence(e,t){const r=e.migration,a=t.migration,s=this.referencesMigration(r,t),i=this.referencesMigration(a,e);if(s&&!i)return 1;if(i&&!s)return-1;const n=this.extractPrecedenceTokens(r),o=this.extractPrecedenceTokens(a);return n.length!==o.length?n.length-o.length:0}sort(e){const t=[...e].sort((e,t)=>{const r=this.versioning.compare(e.version,t.version);if(0!==r)return r;const a=this.compareByPrecedence(e,t);if(0!==a)return a;const s=e.flavour.localeCompare(t.flavour);return 0!==s?s:e.reference.localeCompare(t.reference)});for(let e=0;e<t.length;e++){const r=t[e],s=t[e+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new a.InternalError(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return t}resolveMigration(r){const a=t.Metadata.get(r.constructor,e.PersistenceKeys.MIGRATION),s=a?.flavour||r.flavour||t.DefaultFlavour,i=a?.reference||r.reference,n=this.precedenceHint(r);return{migration:r,flavour:s,reference:i,version:this.normalizeVersion(i,n)}}shouldIncludeMigration(e,r,a=!0){return!r||e.flavour===r||a&&e.flavour===t.DefaultFlavour}collectMigrations(e,r=!0){const s=t.Metadata.migrations(),i=[];for(const[t,n]of s){let s;try{s=new n}catch(e){throw new a.InternalError(`failed to create migration ${t}: ${e}`)}const o=this.resolveMigration(s);this.shouldIncludeMigration(o,e,r)&&i.push(o)}return i}buildExecutionPlan(e){const t=e?.fromVersion?this.normalizeVersion(e.fromVersion):void 0,r=e?.toVersion?this.normalizeVersion(e.toVersion):void 0;return this.sort(this.collectMigrations(e?.targetFlavour,e?.includeGeneric)).filter(e=>!(this.allowedReferences&&!this.allowedReferences.has(e.reference)||t&&!this.versioning.gt(e.version,t)||r&&!this.versioning.lte(e.version,r)))}async executeMigration(e,...t){const r=e.migration;let s,i;try{if(s=q.get(e.flavour),!s)throw new a.InternalError(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(e){throw new a.InternalError(`Failed to load adapter to migrate ${r.reference}: ${e}`)}try{await r.up(i,s,...t)}catch(e){throw new A(`failed to initialize migration ${r.reference}: ${e}`)}try{await r.migrate(i,s,...t)}catch(e){throw new A(`failed to migrate ${r.reference}: ${e}`)}try{await r.down(i,s,...t)}catch(e){throw new A(`failed to conclude migration ${r.reference}: ${e}`)}}buildMigrationTaskForPlan(e,...t){const r=[...t],a=new Ar;return e.forEach(e=>{const t={reference:e.reference,args:r};a.addMigrationStep(t)}),a.build()}buildMigrationTasksForPlan(e,...t){const r=new Map;for(const t of e){const e=r.get(t.version)||[];e.push(t),r.set(t.version,e)}return[...r.entries()].map(([e,r])=>({version:e,task:this.buildMigrationTaskForPlan(r,...t)}))}createMigrationTask(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTaskForPlan(i,...r)}createMigrationTasks(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTasksForPlan(i,...r)}migrationTaskIdsFromContext(e,t){const r=t[t.length-1],a=r?.pending?.()||r?.pending||{},s=a?.[e];return Array.isArray(s)?s.filter(e=>"string"==typeof e):[]}async migrate(e,t,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(t,r,...a){const{ctxArgs:s,log:i}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateNormally),n=this.config,o=n.persistenceFlavour,c=!n.taskMode||(n.includeGenericInTaskMode??!0),l=o?q.get(o):void 0;let d;if(n.retrieveLastVersion){const e=await n.retrieveLastVersion(l,...s);e&&(d=this.normalizeVersion(e))}const u=this.buildExecutionPlan({fromVersion:d,toVersion:n.targetVersion,targetFlavour:o,includeGeneric:c});i.debug("sorted migration before execution: "+u.map(e=>`${e.reference}@${e.version}`));for(const e of u)await this.executeMigration(e,...s);if(n.setCurrentVersion){const e=n.targetVersion||u[u.length-1]?.version||d||void 0;e&&await n.setCurrentVersion(this.normalizeVersion(e),l,...s)}}async migrateViaTasks(t,r,...a){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(a,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateViaTasks),o=this.config,c=o.persistenceFlavour,l=o.includeGenericInTaskMode??!0,d=c?q.get(c):void 0;let u;if(o.retrieveLastVersion){const e=await o.retrieveLastVersion(d,...i);e&&(u=this.normalizeVersion(e))}const p=this.buildExecutionPlan({fromVersion:u,toVersion:o.targetVersion,targetFlavour:c,includeGeneric:l});if(n.debug("sorted migration before execution: "+p.map(e=>`${e.reference}@${e.version}`)),this.queuedTaskChain=[],p.length){const t=this.buildMigrationTasksForPlan(p,...i);if(o.taskService){let r;for(const a of t){r&&(a.task.dependencies=[...a.task.dependencies||[],r]);const t=await o.taskService.push(a.task,!1,...i);r=t.id,this.queuedTaskChain.push({id:t.id,version:a.version}),t?.id||n.warn("TaskService.push returned missing id for version "+a.version),s.pushPending(e.PersistenceKeys.MIGRATION,t.id)}}else{for(const e of p)await this.executeMigration(e,...i);if(o.setCurrentVersion){const e=o.targetVersion||p[p.length-1]?.version||u||void 0;e&&await o.setCurrentVersion(this.normalizeVersion(e),d,...i)}}}}async track(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.track),s=this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return;const l=this.queuedTaskChain.reduce((e,t)=>(e[t.id]=t.version,e),{}),d=this.config.persistenceFlavour?q.get(this.config.persistenceFlavour):void 0;for(const e of c){const{tracker:t}=await s.taskService.track(e,...a);await t.wait(),s.setCurrentVersion&&l[e]&&await s.setCurrentVersion(this.normalizeVersion(l[e]),d,...a)}}async retry(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.retry),s=this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...a);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return void await this.migrateViaTasks(void 0,void 0,...a);const l=s.taskService.client.tasks,d="function"==typeof l?.override?l.override({ignoreHandlers:!0}):l;for(const t of c){const r=(await s.taskService.track(t,...a)).task;if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(r.status))continue;const i=new e.TaskModel({...r,status:e.TaskStatus.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await d.update(i,...a)}}async up(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(i.style("Setting up migration process").yellow.bold)}}const Mr=t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.DefaultFlavour)||[];t.Metadata.set(e.PersistenceKeys.MIGRATION,t.DefaultFlavour,[...Mr,Cr]),e.MigrationTask=class extends rr{async run(r,s){s.logger.info("Executing migration "+r.reference);const i=t.Metadata.migrations().find(([,a])=>{const s=a?.name,i=t.Metadata.get(a,e.PersistenceKeys.MIGRATION)?.reference;return s===r.reference||i===r.reference});if(!i)throw new a.InternalError(`Migration ${r.reference} is not registered with the metadata layer`);const n=i[1];let o;try{o=new n}catch(e){throw new a.InternalError(`Failed to instantiate migration ${r.reference}: ${e}`)}const c=t.Metadata.get(o.constructor,e.PersistenceKeys.MIGRATION),l=c?.flavour||o.flavour,d=q.get(l);if(!d)throw new a.InternalError("Unable to resolve adapter for migration "+r.reference);const u=d.client,p=r.args??[];try{await o.up(u,d,...p,s)}catch(e){throw s.logger.error(`Up phase for ${r.reference} failed: ${e}`),new A(`Up phase for ${r.reference} failed: ${e}`)}try{await o.migrate(u,d,...p,s)}catch(e){throw s.logger.error(`migration phase for ${r.reference} failed: ${e}`),new A(`Migration phase for ${r.reference} failed: ${e}`)}try{await o.down(u,d,...p,s)}catch(e){throw s.logger.error(`down phase for ${r.reference} failed: ${e}`),new A(`Down phase for ${r.reference} failed: ${e}`)}s.logger.info(`migration ${r.reference} completed`)}},e.MigrationTask=s.__decorate([ar("migration")],e.MigrationTask),o.Injectables.setRegistry(new Oe);const Dr="##VERSION##",Ir="##PACKAGE##";t.Metadata.registerLibrary(Ir,Dr),e.AbsContextual=k,e.AbsMigration=class extends k{get reference(){if(!this._reference){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._reference=r.reference,!this._reference)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._precedence=r.precedence,!this._precedence)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;N(this,e,this.prefix(t))})}get adapter(){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!r)throw new a.InternalError("No migration metadata for "+this.constructor.name);const s=r.flavour;return q.get(s)}async enforceRules(r,a,s){const i=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!i||!i.length)return!0;for(const e of i)if(!await e(r,a,s))return!1;return!0}prefix(t){return async function(r){let a;r instanceof q?a=this.getQueryRunner(r.client):(a=r,r=this.adapter);const{ctx:s,log:i}=await this.logCtx([t],e.PersistenceKeys.MIGRATION,!0);if(!await this.enforceRules(a,r,s))throw i.verbose(`Skipping migration ${this.constructor.name} due to rules`),new x("Migration skipped for rule enforcement");return[a,r,s]}.bind(this)}},e.Adapter=q,e.AuthorizationError=ct,e.BaseModel=Tt,e.BigIntSequence=Pe,e.COMMIT="63a97aa",e.ClientBasedService=Rt,e.CompositeTaskBuilder=tr,e.Condition=Z,e.ConnectionError=dt,e.Context=b,e.ContextLock=L,e.ContextualLoggedClass=E,e.DefaultAdapterFlags=f,e.DefaultCascade=re,e.DefaultContextFlags=g,e.DefaultMigrationConfig=Or,e.DefaultRepositoryFilters=fe,e.DefaultSequenceOptions=De,e.DefaultTaskEngineConfig=W,e.Dispatch=zt,e.FULL_VERSION="0.27.5-63a97aa",e.ForbiddenError=lt,e.INDEX_SELF=p,e.InjectablesRegistry=Oe,e.MethodQueryBuilder=ie,e.MigrationError=A,e.MigrationRuleError=x,e.MigrationService=Cr,e.MigrationTaskBuilder=Ar,e.ModelService=Gt,e.MultipleSelectOperationKeys=w,e.NonTransactionOperationKeys=m,e.NoneSequenceOptions=Me,e.NumericSequence=Ie,e.ObserverError=xe,e.ObserverHandler=T,e.OperatorsMap=ae,e.PACKAGE_NAME=Ir,e.PaginationOperationKeys=v,e.Paginator=Ot,e.PagingError=X,e.PersistenceService=class extends Rt{constructor(){super()}for(e,...t){throw new O("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof b||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),n=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of n)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:n,config:r}}},e.QueryError=J,e.Repository=ke,e.SelectOperationKeys=_,e.Sequence=Vt,e.Serial=R,e.Service=Bt,e.SimpleConcurrencyLock=$,e.StandardMigrationVersioning=xr,e.Statement=Nt,e.TaskBackoffBuilder=Xt,e.TaskBuilder=Zt,e.TaskCancelError=yr,e.TaskContext=dr,e.TaskControlError=hr,e.TaskEngine=wr,e.TaskEventBus=pr,e.TaskEventService=class extends Gt{constructor(){super(e.TaskEventModel)}get repo(){return this._repository||(this._repository=Bt.get(e.TaskModel).events),this._repository}},e.TaskFailError=gr,e.TaskHandler=rr,e.TaskHandlerRegistry=ur,e.TaskIOSerializer=Jt,e.TaskLogger=sr,e.TaskRescheduleError=mr,e.TaskRetryError=fr,e.TaskService=vr,e.TaskStepSpecBuilder=er,e.TaskTracker=_r,e.TasksKey=Q,e.TransactionOperationKeys=y,e.UUID=B,e.UnsupportedError=O,e.VERSION=Dr,e.allowIf=(e,...t)=>(r,a,s)=>{Ce("allowIf",e,t,a,s)},e.applyViewDecorator=oe,e.auth=r=>{const a=e.PersistenceKeys.AUTH;return t.Decoration.for(a).define({decorator:e=>t.metadata(a,e),args:[r]}).apply()},e.blockIf=(e,...t)=>(r,a,s)=>{Ce("blockIf",e,t,a,s)},e.cacheModelForPopulate=at,e.cascadeDelete=it,e.column=pt,e.computeBackoffMs=nr,e.create=Lt,e.createOrUpdate=Ue,e.createdAt=mt,e.createdBy=ft,e.createdByOnCreateUpdate=gt,e.defaultQueryAttr=()=>(r,a)=>{const s=t.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let i=t.Metadata.get(r.constructor,s)||[];return i=[...new Set([...i,a])],t.apply(t.propMetadata(s,i))(r,a)},e.del=jt,e.generateInjectableNameForRepository=Te,e.getAndConstructJunctionTable=tt,e.getFilters=ye,e.getLogPipe=ir,e.getPkTypes=bt,e.getPopulateKey=rt,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ne,e.injectableServiceKey=C,e.isOperationBlocked=P,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.list([e,...d]),a.onCreate(Ze,c),a.onUpdate(He,c),a.afterAny(st,c)];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.manyToManyOnCreate=Ze,e.manyToManyOnDelete=async function(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n||!n.length)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ke.forModel(c,this.adapter.alias):ot(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await at(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Ze.call(this,t,r,a,s)},e.manyToOne=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.type([e,...d]),a.onCreate(Qe,c),a.onUpdate(Je,c),a.onDelete(Xe,c),a.afterAny(st,c)];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.manyToOneOnCreate=Qe,e.manyToOneOnDelete=Xe,e.manyToOneOnUpdate=Je,e.migration=(r,a,s,i)=>t.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(a,s,i)=>n=>{const o=a&&"object"==typeof a&&!("name"in a)?a:void 0,c=o?.precedence,l=o?.flavour,d=o?.rules,u=o?c:a,p=o?l:s,h=o?d:i,g=o?void 0!==c:void 0!==u&&("string"!=typeof u||"string"==typeof u&&"string"==typeof p);let f,y,m=u;"string"==typeof u?"string"==typeof p?(m=u,f=p,y=h):Array.isArray(p)?(m=void 0,f=u,y=p):(m=void 0,f=u,y=h):Array.isArray(p)?y=p:(f=p,y=h),void 0===m&&null!==m&&(m=Cr);const _=t.Metadata.flavourOf(n)||t.DefaultFlavour,w=(g&&m===Cr&&r&&r!==f?r:f)||_,v=t.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")),w||t.DefaultFlavour)||[];return t.Metadata.set([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-"),w||t.DefaultFlavour,[...v,{class:n}]),t.Metadata.set(e.PersistenceKeys.MIGRATION,r,n),t.metadata(e.PersistenceKeys.MIGRATION,{reference:r||n.name,precedence:m,flavour:w||t.DefaultFlavour,rules:y})(n)},args:[a,s,i]}).apply(),e.noValidateOn=Et,e.noValidateOnCreate=()=>Et(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>Et(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>Et(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.list([e,...d]),a.onCreate(Ye,c,{priority:70}),a.onUpdate(He,c,{priority:70}),a.onDelete(Ve,c,{priority:70}),a.onUpdate(it,c,{priority:80}),a.afterAny(st,c,{priority:70})];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.oneToManyOnCreateUpdate=Ye,e.oneToManyOnDelete=Ve,e.oneToManyOnUpdate=He,e.oneToOne=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.type([e,...d]),a.onCreate(qe,c,{priority:70}),a.onUpdate(Ge,c,{priority:70}),a.onDelete(ze,c,{priority:70}),a.onUpdate(it,c,{priority:80}),a.afterAny(st,c,{priority:70})];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.oneToOneOnCreate=qe,e.oneToOneOnDelete=ze,e.oneToOneOnUpdate=Ge,e.onlyOnBulk=he,e.onlyOnCreate=ce,e.onlyOnDelete=de,e.onlyOnFilter=ge,e.onlyOnSingle=pe,e.onlyOnTransactional=ue,e.onlyOnUpdate=le,e.persistentVersion=St,e.pk=je,e.pkDec=Fe,e.pkOnCreate=$e,e.populate=st,e.prefixMethod=N,e.prepared=ne,e.promiseSequence=M,e.query=(r={})=>t.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:r=>function s(i,n,o){const c=ie.getFieldsFromMethodName(n);return t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.QUERY,n),{...r,fields:c}),ne(),(e=>(t,r,i)=>{i.value=new Proxy(i.value,{async apply(t,r,i){const{action:n,select:o,selector:c,where:l,groupBy:d,orderBy:u,limit:p,offset:h}=ie.build(t.name,...i);if(!(r instanceof a.Repository))throw Error("thisArg must be an instance of Repository");const g=r,{ctx:f}=(await g.logCtx(i,s.name,!0)).for(s);let y;switch(n){case"find":case"page":y=g.select(o);break;case"count":y=g.count(c);break;case"sum":y=g.sum(c);break;case"avg":y=g.avg(c);break;case"min":y=g.min(c);break;case"max":y=g.max(c);break;case"distinct":y=g.distinct(c);break;case"group":y=g.select(),c&&(y=y.groupBy(c));break;default:throw new J("Unsupported action: "+n)}if(l&&(y=y.where(l)),d&&d.length>0&&"group"!==n){y=y.groupBy(d[0]);for(let e=1;e<d.length;e++)y=y.thenBy(d[e])}else if(d&&d.length>0&&"group"===n)for(const e of d)y=y.thenBy(e);const{allowLimit:m,allowOffset:_,allowOrderBy:w,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},S=[{key:"orderBy",value:(u||[])[0],allowed:w},{key:"limit",value:p,allowed:m},{key:"offset",value:h,allowed:_}];for(const e of S)if(void 0!==e.value){if(!e.allowed&&v)throw new J(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(y=y[e.key](e.value))}if("page"===n){const e=i[i.length-1],t="number"==typeof e?e:e?.limit??10;return y.paginate(t,f)}return y.execute(f)}})})(r))(i,n,o)},args:[r]}).apply(),e.read=Ft,e.relation=kt,e.repository=Ae,e.repositoryFromTypeMetadata=ot,e.resolveBulkSequenceResult=U,e.resolveTransactionLock=Qt,e.roles=r=>t.metadata(e.PersistenceKeys.AUTH_ROLE,r),e.route=(r,a)=>{const s=e.PersistenceKeys.DECAF_ROUTE;return t.Decoration.for(s).define({decorator:()=>(e,i,n)=>{const o={path:a,httpMethod:r,handler:n};return t.apply(t.methodMetadata(t.Metadata.key(s,i),o))(e,i,n)},args:[]}).apply()},e.sequence=(r,a)=>{const s=Object.assign({},De);delete s.generated,r=Object.assign({},s,r);const i="boolean"==typeof a?{update:a}:a||{};return t.Decoration.for(e.PersistenceKeys.SEQUENCE).define({decorator:Ke,args:[r,i,{priority:70}]}).apply()},e.sequenceDec=Ke,e.sequenceOnCreateUpdate=Le,e.serializeError=or,e.service=Ut,e.sleep=cr,e.splitByCount=br,e.splitBySize=Er,e.table=ut,e.task=ar,e.throttle=function r(s,i,n){let o,c;if("function"==typeof s)o=s,c=i??{};else{const t="string"==typeof i?i:e.ThrottleMode.BY_COUNT;c=("object"!=typeof i||Array.isArray(i)?n:i)??{},o=t===e.ThrottleMode.BY_SIZE?Er(s):br(s)}const{delayMs:l,argIndex:d=0}=c;return(s,i,n)=>t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.THROTTLE,i),c),(e,t,s)=>{s.value=new Proxy(s.value,{async apply(e,s,i){const n=i,{log:u,ctx:p}=(await s.logCtx(i,e.name,!0)).for(r),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttle() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(d);if(!h.length)throw new a.InternalError("@throttle() expects at least one argument index to throttle");h.forEach(e=>{if(e>=n.length)throw new a.InternalError(`@throttle() requires argument index ${e} but only ${n.length} provided`);if(!Array.isArray(n[e]))throw new a.InternalError(`@throttle() expects argument at index ${e} to be an array`)});const g=h.map(e=>n[e]),f=g[0].length;if(!g.every(e=>e.length===f))throw new a.InternalError("@throttle() requires all targeted arguments to have the same length");if(0===f)return e.apply(s,n);const y=((e,t,r,a)=>{let s=0;return e.map(e=>{const i=e.length,n=a.map((a,n)=>{const o=r.indexOf(n);return-1===o?a:0===o?e:t[o].slice(s,s+i)});return s+=i,n})})(o(g[0]),g,h,n),m=c.breakOnSingleFailure??(()=>{try{return p.get("breakOnSingleFailureInBulk")}catch{return}})()??!0,_=[],w=[];for(const t of y){try{Tr(await e.apply(s,t),_)}catch(e){if(m)throw e;w.push(e)}l&&await new Promise(e=>setTimeout(e,l))}if(w.length){u.warn(`${t+""} throttled execution continued with ${w.length} failure(s)`);const e=new AggregateError(w,`Throttled ${t+""} failed for ${w.length} chunk(s)`);throw e.results=_,e}return _}})})(s,i,n)},e.transactional=(...e)=>t.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:Wt,args:e}).apply(),e.unique=()=>{const s=e.PersistenceKeys.UNIQUE;return t.Decoration.for(s).define(r.async(),a.onCreateUpdate(ht),t.propMetadata(s,{})).apply()},e.uniqueOnCreateUpdate=ht,e.update=Kt,e.updatedAt=_t,e.updatedBy=yt,e.uuid=Ht,e.uuidCreateUpdateHandler=Yt,e.validBidirectionalRelation=We,e.version=(e=!1)=>e?St():a.version(),e.view=r=>t.Decoration.for(e.Operator.VIEW).define({decorator:t=>oe(e.Operator.VIEW,"view",t),args:[r]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/logging"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/injectable-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/logging","@decaf-ts/transactional-decorators","@decaf-ts/injectable-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsLogging,e.decafTsTransactionalDecorators,e.decafTsInjectableDecorators);
1
+ var e,t;e=this,t=function(e,t,r,a,s,i,n,o){"use strict";var c,l,d,u;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_BY_PAGINATE="findByPaginate",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.FIND="find",u.PAGE="page",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf";const p="__self__";var h;e.PersistenceKeys=void 0,(h=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",h.INDEX="index",h.SEQUENCE="sequence",h.UNIQUE="unique",h.ADAPTER="adapter",h.INJECTABLE="decaf_{0}_adapter_for_{1}",h.SERVICE="service",h.TABLE="table",h.COLUMN="column",h.METADATA="__metadata",h.OWNERSHIP="ownership",h.CREATED_BY="ownership.created-by",h.UPDATED_BY="ownership.updated-by",h.RELATIONS="__relations",h.RELATION="relation",h.ONE_TO_ONE="relation.one-to-one",h.ONE_TO_MANY="relation.one-to-many",h.MANY_TO_ONE="relation.many-to-one",h.MANY_TO_MANY="relation.many-to-many",h.POPULATE="populate",h.NO_VALIDATE="no-validate",h.MIGRATION="migration",h.STATEMENT="statement",h.QUERY="query",h.UUID="uuid",h.TAG_FOR_DELETION="tag_for_deletion",h.INITIALIZATION="initialization",h.SHUTDOWN="shutdown",h.BY_KEY="by-key",h.AUTH="auth",h.AUTH_ROLE="auth-role",h.DECAF_ROUTE="DecafRoute",h.THROTTLE="throttle",h.PERSISTENT_VERSION="persistent-version",h.DEFAULT_QUERY_ATTR="default-query-attr";const g=Object.assign({},{ignoreDevSafeGuards:!1}),f=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},preferFromCache:!1,noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,breakOnSingleFailureInBulk:!0,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1,afterQueryHandlers:!1,maxConcurrentTransactions:-1}),y=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],m=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],w=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],_=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],v=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.FIND_BY_PAGINATE,e.PreparedStatementKeys.PAGE];class b extends a.Context{constructor(e){super(e)}static{this.factory=e=>(new b).accumulate(Object.assign({},e,{timestamp:new Date,logger:e.logger||i.Logging.get()}))}static async from(e,t,r,...a){return this.factory(Object.assign({},t||{},{operation:e,model:r,affectedTables:r,args:a,logger:t?.logger||i.Logging.get()}))}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).reduce((e,t)=>(Array.isArray(t)?e.push(...t):null!=t&&e.push(t),e),[]).filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}pending(){return this.getFromChildren("pending")}getOrUndefined(e){try{return this.get(e)}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const n=i[0];if(!n)throw new a.InternalError("Invalid property access to overridden context: "+n);return n in e?e[n]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class E extends i.LoggedClass{logCtx(e,t,r=!1,a){return E.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...s){const n=(e,t,r)=>{const a=t.log||i.Logging.get();return t.log=e.context?a.clear().for(e):a.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let o=s.pop();const c=o instanceof b||(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"function"==typeof t.get&&"function"==typeof t.accumulate&&"function"==typeof t.override&&"function"==typeof t.toOverrides&&void 0!==t.cache})(o);if(o&&!c&&(s.push(o),o=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!o)throw new a.InternalError("Missing context. should be impossible");return n(this,{log:o.logger,ctx:o,ctxArgs:[...s,o]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,o].filter(Boolean)).then(t=>n(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class k extends E{constructor(){super(),this._Context=b}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let a=r.pop();return a instanceof b||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class T{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=E.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:n}=a;if(!n)return!0;try{return n(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>a.observer.refresh(e,t,r,...i)))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class O extends a.InternalError{constructor(e){super(e,O.name,500)}}class A extends a.InternalError{constructor(e,t=A.name){super(e,t,500)}}class x extends A{constructor(e){super(e,x.name)}}function C(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):t.Metadata.Symbol(t.Metadata.constr(e)).toString().replaceAll(".","-")}async function M(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}const D=[a.OperationKeys.CREATE,a.OperationKeys.READ,a.OperationKeys.UPDATE,a.OperationKeys.DELETE];function I(e){return D.includes(e)}function P(e,r,s){const i=t.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};if(!i?.handler)return!1;const n=void 0===s&&I(r)?"crud":r,o=void 0===s&&I(r)?r:s,c=i.args?.[0]||[];return i.handler(c,n,o)??!1}function N(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof x)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class B{generate(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})}static get instance(){return B._instance||(B._instance=new B),B._instance}}class R{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return R._instance||(R._instance=new R),R._instance}}class L extends n.Lock{static{this.registry=new WeakMap}static for(e,t){let r=L.registry.get(e);return r||(r=new L(t),L.registry.set(e,r)),r}constructor(e){super(),this.waiters=[],this.permits=e}async acquire(e){if(0>=this.permits)return new Promise(e=>this.waiters.push(e));this.permits--}release(e){const t=this.waiters.shift();t?t():this.permits++}}class ${constructor(e,...t){this.adapter=e,this.depth=0}async begin(e){const{log:t,ctx:r}=this.adapter.logCtx([e],this.begin),a=r.getOrUndefined("maxConcurrentTransactions"),s="number"==typeof a?a:f.maxConcurrentTransactions;if(0===s)throw t.debug(`Rejecting transaction on adapter "${this.adapter.alias}": transactions are disabled (maxConcurrentTransactions=0)`),new O(`Transactions are disabled for adapter "${this.adapter.alias}" (maxConcurrentTransactions=0)`);s>0&&(t.silly(`Gating transaction on adapter "${this.adapter.alias}" (maxConcurrentTransactions=${s})`),this.semaphore=L.for(this.adapter,s),await this.semaphore.acquire(r))}async commit(e){const{ctx:t}=this.adapter.logCtx([e],this.commit);this.semaphore?.release(t)}async rollback(e,t){const{ctx:r}=this.adapter.logCtx([t],this.rollback);this.semaphore?.release(r)}}const F=t.Decoration.flavourResolver.bind(t.Decoration);t.Decoration.flavourResolver=e=>{const r=e=>{if(!e)return;const t=q._cache?.[e];return t?.flavour||e};try{const a=F(e);if(a&&a!==t.DefaultFlavour)return r(a);const s="function"==typeof e?e:e?.constructor,i=s&&"function"==typeof t.Metadata.registeredFlavour?t.Metadata.registeredFlavour(s):void 0;if(i&&i!==t.DefaultFlavour)return r(i);const n=q._currentFlavour;if(n){const e=q._cache?.[n];return e?.flavour?e.flavour:r(n)}}catch(e){return t.DefaultFlavour}};const j=Symbol("AdapterProxyCleanup");function U(e,t,r,a){if(!t)return e;const s=e,i=[],n=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):n.push(e.reason);if(n.length){r.warn(`Bulk ${a} encountered ${n.length} failure(s) while continuing`);const e=new AggregateError(n,`Bulk ${a} failed for ${n.length} item(s)`);throw e.results=s,e}return i}class q extends k{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!q._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return q._baseRepository}transactionLock(...e){return new $(this,...e)}async shutdownProxies(e,...t){e&&"string"!=typeof e&&(t=[e,...t],e=void 0);const{log:r}=this.logCtx(t,this.shutdownProxies);if(!this.proxies)return;if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);const s=async e=>{if(!e)return;const t=e[j];"function"==typeof t&&await t()};if(e)try{await s(this.proxies[e]),delete this.proxies[e]}catch(t){r.error("Failed to cleanup proxied adapter "+e,t)}else for(const e in this.proxies){try{await s(this.proxies[e])}catch(t){r.error("Failed to cleanup proxied adapter "+e,t);continue}delete this.proxies[e]}}async shutdown(...t){const{log:r,ctxArgs:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.internalLock.acquire(e.PersistenceKeys.SHUTDOWN);try{if(this.shutdownPromise)return this.shutdownPromise;this.shutdownPromise=(async()=>{const{log:r}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await this.shutdownProxies(...s),this.dispatch&&await this.dispatch.close(...s)})()}catch(e){throw new a.InternalError("Failed to create shutdown wrapper: "+e)}finally{this.internalLock.release(e.PersistenceKeys.SHUTDOWN)}try{await this.shutdownPromise}catch(e){r.error("Error during proxy shutdown",e)}finally{this.shutdownPromise=void 0}}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.internalLock=new n.Lock,this.alias in q._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);q._cache[this.alias]=this,this.alias!==this.flavour&&(this.flavour in q._cache||(q._cache[this.flavour]=this)),this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),q._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),q._currentFlavour=this.alias)}Dispatch(){return new q._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new q._baseSequence(e,this,t)}async flags(e,s,n,...o){if("string"==typeof s)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(s)?s.length?s[0]:void 0:s,l=c?""+r.Model.tableName(c):"";n.correlationId=n.correlationId||`${l}|${e}|${B.instance.generate()}`;const d=n.logger||i.Logging.for(this),u=Object.assign({},f.cacheForPopulate,n.cacheForPopulate);return Object.assign({},f,n,{affectedTables:s?[...new Set([...(Array.isArray(s)?s:[s]).filter(Boolean),...n.affectedTables?Array.isArray(n.affectedTables)?n.affectedTables:[n.affectedTables]:[]])]:n.affectedTables,cacheForPopulate:u,args:o,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:s?t.Metadata.validationExceptions(Array.isArray(s)&&s[0]?s[0]:s,e):[],logger:d})}get Context(){return b}async context(e,t,a,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${a?Array.isArray(a)?a.map(e=>r.Model.tableName(e)):r.Model.tableName(a):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof b||(s.push(i),i=void 0);const n=(()=>{if(!i)return!1;try{return!!i.get("allowGenerationOverride")}catch{return!1}})();t=i?Object.assign({},i.toOverrides(),t):t,n&&(t.allowGenerationOverride=!0);const o=await this.flags("string"==typeof e?e:e.name,a,t,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const e=(new this.Context).accumulate({...i.cache,...o,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],e]}),e}const t=i.getOrUndefined("operation"),r=i.getOrUndefined("affectedTables");if(!t||t!==e||a&&a!==r){const e=(new this.Context).accumulate({...i.cache,...o,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],e]}),e}return i.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...s){const{log:i}=this.logCtx(s,this.prepare),n=t.segregate(),o=Object.entries(n.model).reduce((e,[s,i])=>{if(void 0===i)return e;const n=r.Model.columnName(t.constructor,s);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return e[n]=i,e},{});return t[e.PersistenceKeys.METADATA]&&(i.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(o,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:o,id:t[r.Model.pk(t.constructor)],transient:n.transient}}revert(t,s,i,n,...o){const{log:c,ctx:l}=this.logCtx(o,this.revert),d=r.Model.pk(s),u=new s;u[d]=i,c.silly(`Rebuilding model ${u.constructor.name} id ${i}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[r.Model.columnName(s,a)],e),u);return l.get("rebuildWithTransient")&&n&&(c.verbose("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${i}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.createAll);if(!t||!s)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==s.length)throw new a.ValidationError("Ids and models must have the same length");const c=r.Model.tableName(e);n.debug(`Creating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,r)=>()=>this.create(e,t,s[r],...i,o.override({noEmitSingle:!0})));return U(l?await M(d,!0):await M(d),l,n,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...s){const{log:i,ctx:n}=this.logCtx(s,this.readAll),o=r.Model.tableName(e);i.debug(`Reading ${t.length} entries ${o} table`);const c=!(n.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...s,n.override({noEmitSingle:!0})));return U(c?await M(l,!0):await M(l),c,i,a.BulkCrudOperationKeys.READ_ALL)}async updateAll(e,t,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.updateAll);if(t.length!==s.length)throw new a.InternalError("Ids and models must have the same length");const c=r.Model.tableName(e);n.debug(`Updating ${t.length} entries ${c} table`);const l=!(o.get("breakOnSingleFailureInBulk")??1),d=t.map((t,r)=>()=>this.update(e,t,s[r],...i,o.override({noEmitSingle:!0})));return U(l?await M(d,!0):await M(d),l,n,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const n=!(i.get("breakOnSingleFailureInBulk")??1),o=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return U(n?await M(o,!0):await M(o),n,s,a.BulkCrudOperationKeys.DELETE_ALL)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t);const r=this.log.for(this.observe);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch()),this.dispatch.observe(this),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.observerHandler.count()>0||(this.log.for(this.unObserve).debug("No active observers for adpter. Closing dispatcher and unobserving."),this.dispatch?.close([]),this.dispatch?.unObserve(this)),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(a&&o||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...n)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return t.Metadata.flavourOf(e)}static get currentFlavour(){if(!q._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return q._currentFlavour}static get current(){return q.get(this.currentFlavour)}static unregister(e){if(!e)return;const t=q._cache[e];t&&(delete q._cache[e],q._currentFlavour===e&&(q._currentFlavour=void 0),t.flavour&&q._cache[t.flavour]&&q._cache[t.flavour]===t&&delete q._cache[t.flavour])}static get(e){if(!e)return q.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return t.Metadata.flavouredAs(e).filter(r.Model.isModel)}catch(e){throw new a.InternalError(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const a=`${this.alias} - ${r.hashObj(e)}`;if(a in this.proxies)return this.proxies[a];let s;const i=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,a)},set:(e,t,r,a)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,a)});return Reflect.defineProperty(i,j,{value:async()=>{if(!s)return;const e=["cancel","close","destroy","disconnect"];for(const t of e){const e=s[t];if("function"==typeof e)try{const t=e.call(s);t instanceof Promise&&await t}catch{}}s=void 0},configurable:!0,enumerable:!1}),this.proxies[a]=i,i}migrations(){return t.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}var G,z,Y,H,V;s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,b]),s.__metadata("design:returntype",Promise)],q.prototype,"context",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],q.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],q.prototype,"unObserve",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],q.prototype,"client",null),e.TaskStatus=void 0,(G=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",G.SCHEDULED="scheduled",G.RUNNING="running",G.FAILED="failed",G.SUCCEEDED="succeeded",G.CANCELED="canceled",G.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(z=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",z.FIXED="fixed",e.JitterStrategy=void 0,(Y=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",Y.FULL="full",e.TaskEventType=void 0,(H=e.TaskEventType||(e.TaskEventType={})).STATUS="status",H.UPDATE="update",H.LOG="log",H.PROGRESS="progress",H.ALL="all",e.TaskType=void 0,(V=e.TaskType||(e.TaskType={})).ATOMIC="atomic",V.COMPOSITE="composite";const Q="tasks",W={workerId:"default-worker",concurrency:10,maxConcurrentCompositeSteps:-1,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4,autoShutdown:{enabled:!1,backoffStepMs:1e3,maxIdleDelayMs:6e4}};t.Metadata.tasks=(()=>t.Metadata.innerGet(Symbol.for(Q))).bind(t.Metadata),t.Metadata.taskFor=(e=>{const r=t.Metadata.tasks();return r?r[e]:void 0}).bind(t.Metadata),t.Metadata.validationExceptions=((s,i)=>{const n=t.Metadata.get(s,e.PersistenceKeys.NO_VALIDATE)||[],o=Object.entries(n).filter(([,e])=>e.includes(i)).map(([e])=>e);let c=[];return i!==a.OperationKeys.CREATE&&i!==a.OperationKeys.UPDATE||(c=r.Model.nestedRelations(s)),[...new Set([...o,...c])]}).bind(t.Metadata),t.Metadata.migrationsFor=(r=>{if(!(r=r??q.current))throw new a.InternalError("Could not get adapter for migrations");return t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),r.alias).map(e=>e.class)}).bind(t.Metadata),t.Metadata.migrations=(()=>{const r=t.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(r).flat().map(e=>[e.class.name,e.class])}).bind(t.Metadata),t.Metadata.relations=((r,s)=>{const i=t.Metadata.get(r,e.PersistenceKeys.RELATIONS);if(i){if(!s)return Object.keys(i);if(!i[s])throw new a.InternalError("No relations metadata found for property "+s);return i[s]}}).bind(t.Metadata),r.Model.relations=(e,a)=>t.Metadata.relations(e instanceof r.Model?e.constructor:e,a)||[],r.Model.nestedRelations=((a,s=[])=>{let i=[];const n=t.Metadata.get(a,e.PersistenceKeys.RELATIONS);if(!n||!Object.keys(n).length)return[...new Set([...s])];for(const e in n){const t=n[e];if(t?.class&&r.Model.relations(t.class)){const a=r.Model.relations(t.class).map(t=>`${e}.${t}`);s=[...s,...a],i=r.Model.nestedRelations(t.class,s)}}return[...new Set([...s,...i])]}).bind(r.Model),r.Model.generatedBySequence=((e,t)=>{const a="function"!=typeof e?e.constructor:e;return!!r.Model.sequenceFor(a).generated}).bind(r.Model),r.Model.fromTable=(s=>{const i=t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!i||!i[s]||!r.Model.get(i[s].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return r.Model.get(i[s].name)}).bind(r.Model),t.Metadata.createdBy=(r=>{const s=t.Metadata.get("function"!=typeof r?r.constructor:r,e.PersistenceKeys.CREATED_BY);if(!s)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return s}).bind(t.Metadata),t.Metadata.updatedBy=(r=>{const s=t.Metadata.get("function"!=typeof r?r.constructor:r,e.PersistenceKeys.UPDATED_BY);if(!s)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return s}).bind(t.Metadata),r.Model.tableName=s=>{if(!(s instanceof r.Model?r.Model.get(s.constructor.name):s))throw new a.InternalError("Unable to find model "+s);return t.Metadata.get(s instanceof r.Model?s.constructor:s,e.PersistenceKeys.TABLE)||(s instanceof r.Model?s.constructor.name:s.name)},r.Model.columnName=(a,s)=>t.Metadata.get(a instanceof r.Model?a.constructor:a,t.Metadata.key(e.PersistenceKeys.COLUMN,s))||s,r.Model.defaultQueryAttributes=(a,s=!1)=>{const i="function"==typeof a?a:a.constructor;return t.Metadata.get(i,t.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||(s?[r.Model.pk(a)]:[])},r.Model.sequenceName=(e,...t)=>[r.Model.tableName(e),...t].join("_"),r.Model.versionOf=(r=>{const s=t.Metadata.get(r.constructor),i=s?.[e.PersistenceKeys.PERSISTENT_VERSION],n=i&&"object"==typeof i?Object.keys(i)[0]:void 0,o=s?.[a.DBKeys.VERSION],c=o&&"object"==typeof o?Object.keys(o)[0]:void 0,l=n??c;if(!l)throw new a.InternalError("No version found for "+r.constructor.name);const d=r[l];if("number"!=typeof d||1>d)throw new a.InternalError("Invalid version number: "+d);return d}).bind(r.Model),r.Model.sequenceFor=(s,i)=>{const n="function"!=typeof s?s.constructor:s;let o=e.PersistenceKeys.SEQUENCE;const c=r.Model.pk(n);i&&i+""!=c+""||(i=c,o=a.DBKeys.ID),o=t.Metadata.key(o,i);const l=t.Metadata.get(n,o);if(!l)throw new a.InternalError(`No sequence options defined for property ${i+""}. did you use @sequence() or @pk()?`);return l},r.Model.indexes=a=>{const s=t.Metadata.get(a instanceof r.Model?a.constructor:a,e.PersistenceKeys.INDEX);return Object.keys(s||{}).reduce((t,r)=>{const a=s[r]||{};return t[r]=Object.keys(a).reduce((t,r)=>(t[r===p?e.PersistenceKeys.INDEX:`${e.PersistenceKeys.INDEX}_${r}`]=a[r],t),{}),t},{})},o.Injectables.services=()=>t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),o.Injectables.repositories=()=>t.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY)),r.Model.merge=((e,t,a)=>{const s=e=>Object.entries(e).reduce((e,[t,s])=>{let i=!1;try{"relation.one-to-one"===r.Model.relations(a,t).key&&(i=!0)}catch(e){i=!1}return(void 0!==s||i)&&(e[t]=s),e},{});return new(a=a||e.constructor)(Object.assign({},s(e),s(t)))}).bind(r.Model);class J extends a.InternalError{constructor(e){super(e,J.name,500)}}class X extends a.InternalError{constructor(e){super(e,X.name,500)}}class Z extends r.Model{constructor(e,t,a){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||a?(this.attr1=e,this.operator=t,this.comparison=a):r.Model.fromModel(this,e)}and(e){return Z.and(this,e)}or(e){return Z.or(this,e)}not(t){return new Z(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Z)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof Z){if(!(this.comparison instanceof Z)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return Z.group(t,e.GroupOperator.AND,r)}static or(t,r){return Z.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new Z(e,t,r)}static attribute(e){return(new Z.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Z(this.attr1,this.operator,this.comparison)}catch(e){throw new J(e)}}}}static builder(){return new Z.Builder}static from(e){return new Z(e)}}var ee,te;s.__decorate([r.required(),s.__metadata("design:type",Object)],Z.prototype,"attr1",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Z.prototype,"operator",void 0),s.__decorate([r.required(),s.__metadata("design:type",Object)],Z.prototype,"comparison",void 0),e.OrderDirection=void 0,(ee=e.OrderDirection||(e.OrderDirection={})).ASC="asc",ee.DSC="desc",e.Cascade=void 0,(te=e.Cascade||(e.Cascade={})).CASCADE="cascade",te.NONE="none";const re={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},ae={Equals:(e,t)=>Z.attribute(e).eq(t),Diff:(e,t)=>Z.attribute(e).dif(t),LessThan:(e,t)=>Z.attribute(e).lt(t),LessThanEqual:(e,t)=>Z.attribute(e).lte(t),GreaterThan:(e,t)=>Z.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Z.attribute(e).gte(t),In:(e,t)=>Z.attribute(e).in(t),Matches:(e,t)=>Z.attribute(e).regexp(t)},se=e=>e.charAt(0).toLowerCase()+e.slice(1);class ie extends i.LoggedClass{static get log(){return this._logger||(this._logger=i.Logging.for(ie.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const n=this.extractCore(e,s),o=this.extractSelect(e),c=this.extractGroupBy(e),l=this.buildWhere(n,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,n);return{action:a,select:o,selector:i,where:l,groupBy:c,orderBy:d,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?se(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(se).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(se).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),n=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&n.push(se(r))}return n.length>0?n:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let n;return s.forEach((t,a)=>{const{field:s,operator:o}=this.parseFieldAndOperator(t),c=o?ae[o]:ae.Equals;if(!c)throw Error("Unsupported operator "+o);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);n=0===a?d:i[a-1]===e.QueryClause.AND?n.and(d):n.or(d)}),n}static parseFieldAndOperator(e){for(const t of Object.keys(ae))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:se(r),operator:t}}return{field:se(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,r){const a=ie.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new J("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new J(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,n=t.slice(i)??[];let o,c,l;if(n.at(-1)instanceof a.Context&&n.pop(),n.length>=1){const t=n[0],r=this.extractOrderByField(e);o=this.getProperlyOrderByOrThrow(r,t)}return 2>n.length||"number"!=typeof n[1]||(c=n[1]),3>n.length||"number"!=typeof n[2]||(l=n[2]),{orderBy:o,limit:c,offset:l}}}function ne(){return t.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(r,a,s)=>t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.STATEMENT,a),!0))(r,a,s),args:[]}).apply()}function oe(e,r,a){return(s,i)=>{const n=a?.name||((e,r,a)=>{const s=(t.Metadata.get(e.constructor,r)||{})[a]||{};return Object.keys(s).length+1+""})(s,e,i),o=t.Metadata.key(e,i,n),c={...a||{},kind:r,attribute:i};return t.propMetadata(o,c)(s,i)}}function ce(e){return ge(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function le(e){return ge(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function de(e){return ge(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ue(e){return ge(e,y)}function pe(e){return ge(e,Object.values(a.OperationKeys))}function he(e){return ge(e,Object.values(a.BulkCrudOperationKeys))}function ge(e,s){return(i,n,o,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=E.prototype.logCtx(c,ge);return l.silly(`filtering ${n} event for${i?" "+(r.Model.tableName(i)||i):""} ${o}`),("string"==typeof i?i===r.Model.tableName(e)||i===e.constructor.name:t.Metadata.constr(e)===t.Metadata.constr(i))&&s.includes(n)}}const fe={onlyOnCreate:ce,onlyOnUpdate:le,onlyOnDelete:de,onlyOnTransactional:ue,onlyOnSingle:pe,onlyOnBulk:he};function ye(e){const t=Object.assign({},fe);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var me,we,_e,ve,Se,be,Ee;class ke extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=r.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ye(this)}constructor(e,r,s=!1,...i){super(r),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0,afterQueryHandlers:!1},e&&(this._adapter=e),r&&(ke.register(r,this,this.adapter.alias,s),e)&&t.Metadata.get(r,t.DecorationKeys.FLAVOUR)===t.DefaultFlavour&&t.uses(e.flavour)(r);const n=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(n,n[t+"Prefix"],e,n[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(n,n[this.updateAll.name+"Prefix"],this.updateAll,n[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new T}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,a);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,c,a)}async createAll(e,...t){if(!e.length)return e;const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,a)),o=n.map(e=>e.id);let c=n.map(e=>e.record);return c=await this.adapter.createAll(this.class,o,c,...i),c.map((e,t)=>this.adapter.revert(e,this.class,o[t],a.get("rebuildWithTransient")?n[t].transient:void 0,a))}async createAllPrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");if(n.silly(`handlerSetting: ${o}, validationSetting: ${c}`),!e.length)return[e,...i];const l=r.Model.sequenceFor(e[0]);let d=[];if(r.Model.generatedBySequence(this.class)?(l.name||(l.name=r.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...i)):r.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),o||await a.enforceDBDecorators(this,s,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=s.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const r=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(r);if(i)throw new a.ValidationError(i)}return[e,...i]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await a.enforceDBDecorators(this,r,o,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${r.Model.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,a)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${r.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}async update(e,...t){const{ctxArgs:a,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...a),this.adapter.revert(n,this.class,o,c,i)}async updatePrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");n.silly(`handlerSetting: ${o}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(s.get("applyUpdateValidation")&&(d=await this.read(l,s),s.get("mergeForUpdate")&&(e=r.Model.merge(d,e,this.class))),o||await a.enforceDBDecorators(this,s,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=s.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const r=await Promise.resolve(e.hasErrors(d,...t));if(r)throw new a.ValidationError(r.toString())}return[e,...i,d]}async updateAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,a));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,a.get("rebuildWithTransient")?n[t].transient:void 0,a))}async updateAllPrefix(e,...t){const{ctx:s,ctxArgs:i,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),o=s.get("ignoreHandlers"),c=s.get("ignoreValidation");n.silly(`handlerSetting: ${o}, ignoredValidation: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(s.get("applyUpdateValidation")&&(d=await this.readAll(l,s),s.get("mergeForUpdate")&&(e=e.map((e,t)=>r.Model.merge(d[t],e,this.class)))),o||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,s,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[t]:void 0))),!c){const t=s.get("ignoredValidationProperties")||[];let r;n.silly("ignored validation properties: "+t),r=s.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(r);if(i)throw new a.ValidationError(i)}return[e,...i,d]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${r.Model.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,a)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:a,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${r.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,r)=>this.adapter.revert(t,this.class,e[r],void 0,a))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(...o)}async listBy(t,a,...s){const{log:i,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return i.verbose(`listing ${r.Model.tableName(this.class)} by ${t} ${a}`),this.select().orderBy([t,a]).execute(...n)}async paginateBy(t,a,s={offset:1,limit:10},...i){s.offset=s.offset||1,s.limit=s.limit||10;const{offset:n,bookmark:o,limit:c}=s;if(!n&&!o)throw new J("PaginateBy needs a page or a bookmark");const{log:l,ctx:d,ctxArgs:u}=(await this.logCtx(i,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let p;if(l.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${c}`),o&&d.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>a===e.OrderDirection.ASC?this.attr(r.Model.pk(this.class)).gt(o):this.attr(r.Model.pk(this.class)).lt(o))()).orderBy([t,a]).paginate(c,...u);else{if(!n)throw new J("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,a]).paginate(c,...u)}const h=await p.page(n,o&&!d.get("paginateByBookmark")?o:void 0,...u);return p.serialize(h)}async find(t,a=e.OrderDirection.ASC,...s){if("string"!=typeof t)throw new J("Find value must be a string");const i=this.getDefaultQueryAttributes(),{log:n,ctxArgs:o}=(await this.logCtx(s,e.PreparedStatementKeys.FIND,!0)).for(this.find);n.verbose(`finding ${r.Model.tableName(this.class)} by default attributes ${i.join(", ")}`);const c=this.buildDefaultStartsWithCondition(t,i);return this.select().where(c).orderBy([i[0],a]).execute(...o)}async page(t,a=e.OrderDirection.ASC,s={offset:1,limit:10},...i){if("string"!=typeof t)throw new J("Page value must be a string");const n=s.offset||1,{offset:o,bookmark:c,limit:l}=s;if(!o&&!c)throw new J("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(i,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${r.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const f=l??10,y=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let w;if(c&&h.get("paginateByBookmark")){const t=r.Model.pk(this.class),s=a===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);w=await m.select().where(u.and(s)).orderBy([y,a]).paginate(f,...g)}else{if(!o)throw new J("PaginateBy needs a page or a bookmark");w=await m.select().where(u).orderBy([y,a]).paginate(f,...g)}const _=await w.page(n,c&&!h.get("paginateByBookmark")?c:void 0,...g);return w.serialize(_)}async findOneBy(t,s,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);n.verbose(`finding ${r.Model.tableName(this.class)} with ${t} ${s}`);const c=await this.select().where(this.attr(t).eq(s)).limit(1).execute(...o);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,a,...s){const{log:i,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return i.verbose(`finding ${r.Model.tableName(this.class)} with ${t} ${a}`),this.select().where(this.attr(t).eq(a)).execute(...n)}async findByPaginate(t,a,s={direction:e.OrderDirection.DSC,offset:1,limit:10},...i){s.direction=s.direction||e.OrderDirection.DSC,s.offset=s.offset||1,s.limit=s.limit||10;const{direction:n,offset:o,bookmark:c,limit:l}=s;if(!o&&!c)throw new J("FindByPaginate needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(i,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);d.verbose(`finding and paginating ${r.Model.tableName(this.class)} with ${t} ${a}`);const h=this.attr(t).eq(a);let g;if(c&&u.get("paginateByBookmark")){const a=r.Model.pk(this.class),s=n===e.OrderDirection.ASC?this.attr(a).gt(c):this.attr(a).lt(c);g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h.and(s)).orderBy([t,n]).paginate(l,...p)}else{if(!o)throw new J("FindByPaginate needs a page or a bookmark");g=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(h).orderBy([t,n]).paginate(l,...p)}const f=await g.page(o,c&&!u.get("paginateByBookmark")?c:void 0,...p);return g.serialize(f)}async countOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return s.verbose(`counting ${r.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...i)}async maxOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return s.verbose(`finding max of ${t} in ${r.Model.tableName(this.class)}`),this.max(t).execute(...i)}async minOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return s.verbose(`finding min of ${t} in ${r.Model.tableName(this.class)}`),this.min(t).execute(...i)}async avgOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return s.verbose(`calculating average of ${t} in ${r.Model.tableName(this.class)}`),this.avg(t).execute(...i)}async sumOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return s.verbose(`calculating sum of ${t} in ${r.Model.tableName(this.class)}`),this.sum(t).execute(...i)}async distinctOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return s.verbose(`finding distinct values of ${t} in ${r.Model.tableName(this.class)}`),this.distinct(t).execute(...i)}async groupOf(t,...a){const{log:s,ctxArgs:i}=(await this.logCtx(a,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return s.verbose(`grouping ${r.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...i)}async statement(t,...r){if(!ke.statements(this,t))throw new J("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}getDefaultQueryAttributes(){const e=r.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new J("No default query attributes defined for "+r.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new J("Default query value must be a string");let a;for(const r of t){const t=this.attr(r).startsWith(e);a=a?a.or(t):t}if(!a)throw new J("No default query attributes available for "+r.Model.tableName(this.class));return a}attr(e){return Z.attr(e)}observe(e,r){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const a=this.log.for(this.observe),s=this.class.name;return this.observerHandler?.count()||this.adapter.observe(this,(e,r,a,...i)=>"string"==typeof e?e===s:t.Metadata.constr(e)===t.Metadata.constr(this.class)),a.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,r),a.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,s,...i){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=this.logCtx(i,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(s)?s.map(e=>q._baseSequence.parseValue(r.Model.sequenceFor(this.class).type,e)):q._baseSequence.parseValue(r.Model.sequenceFor(this.class).type,s),...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(s,i,...n){let o;const c=t.Metadata.registeredFlavour(s),l=c&&c!==t.DefaultFlavour?c:void 0,d=i||l||t.Metadata.flavourOf(s)||q.currentFlavour;try{o=this.get(s,d)}catch(e){o=void 0}const u="function"==typeof o?o:void 0,p=i||l||t.Metadata.flavourOf(s)||u&&t.Metadata.get(u,e.PersistenceKeys.ADAPTER)||q.currentFlavour,h=p?q.get(p):void 0;if(!h)throw new a.InternalError("No registered persistence adapter found flavour "+p);if(o instanceof ke)return o;const g=[r.Model.tableName(s),h.alias].join(a.DefaultSeparator),f=u||h.repository();return delete this._cache[g],new f(h,s,...n)}static get(e,t){const s=r.Model.tableName(e);let i=s;if(t&&(i=[s,t].join(a.DefaultSeparator)),i in this._cache)return this._cache[i];if(s in this._cache)return this._cache[s];throw new a.InternalError("Could not find repository registered under "+s)}static register(e,t,s,i=!1){let n=r.Model.tableName(e);if(s&&(n=[n,s].join(a.DefaultSeparator)),n in this._cache&&this._cache[n]instanceof ke&&!i)throw new a.InternalError(n+" already has a registered instance");this._cache[n]=t}static statements(r,a){const s=r instanceof ke?r.constructor:r,i=t.Metadata.get(s,a?t.Metadata.key(e.PersistenceKeys.STATEMENT,a):e.PersistenceKeys.STATEMENT);return(a?i:Object.keys(i))||!1}static queries(r,a){const s=r instanceof ke?r.constructor:r;return t.Metadata.get(s,a?t.Metadata.key(e.PersistenceKeys.QUERY,a):e.PersistenceKeys.QUERY)}}function Te(s,i){if(!(i||(i=t.Decoration.flavourResolver(s instanceof r.Model?s.constructor:s))&&i!==t.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(s instanceof r.Model?s.constructor.name:s.name));return r.sf(e.PersistenceKeys.INJECTABLE,i,r.Model.tableName(s))}s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"listBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"paginateBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"find",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"page",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findOneBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findBy",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"findByPaginate",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"countOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(me="undefined"!=typeof K&&K)?me:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"maxOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(we="undefined"!=typeof K&&K)?we:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"minOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(_e="undefined"!=typeof K&&K)?_e:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"avgOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(ve="undefined"!=typeof K&&K)?ve:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"sumOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Se="undefined"!=typeof K&&K)?Se:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"distinctOf",null),s.__decorate([ne(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(be="undefined"!=typeof K&&K)?be:Object,void 0]),s.__metadata("design:returntype",Promise)],ke.prototype,"groupOf",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],ke.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],ke.prototype,"unObserve",null),q&&(q._baseRepository=ke);class Oe extends o.InjectableRegistryImp{get log(){return this.logger||(this.logger=i.Logging.for(this)),this.logger}constructor(){super()}get(a,s){const i=this.log.for(this.get);let n;try{n=super.get(a)}catch{}if(!n){let c;if("function"==typeof a?c=r.Model.get(a.name)||a:"symbol"!=typeof a&&"string"!=typeof a||(c=r.Model.get(a.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=s||t.Metadata.get(c,l)||t.Metadata.flavourOf(c);try{let e=d;try{d&&q.get(d)}catch{const t=q.current;t&&t.flavour===d&&(e=t.alias)}if(n=ke.forModel(c,e),n instanceof ke)return n;const r=d||t.Metadata.get(n.constructor,l)||t.Metadata.get(c,l);o.Injectables.register(n,Te(c,r))}catch(e){i.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ke.get(c,d);if("function"==typeof t){const e=d?q.get(d):q.current;if(!e)return;return new t(e,c)}}}return n}}function Ae(s,i){return(n,c)=>c?o.inject(t.Metadata.constr(s))(n,c):(t.Metadata.set(a.DBKeys.REPOSITORY,t.Metadata.key(i||q.currentFlavour,r.Model.tableName(s)),n),t.metadata(a.DBKeys.REPOSITORY,n.name)(s),i=i||t.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),ke.register(s,n),o.injectable(t.Metadata.constr(s),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:s}),e)})(n))}class xe extends a.InternalError{constructor(e){super(e,xe.name,500)}}function Ce(e,t,r,s,i){i.value=new Proxy(i.value,{async apply(i,n,o){((e,t,r)=>{if("function"!=typeof e?.logCtx)throw new O(`${t} on ${e?.constructor?.name??"UnknownClass"}.${r} requires a logCtx() method`)})(n,e,s+"");const{ctx:c,ctxArgs:l}=await n.logCtx(o,i.name,!0);let d;try{d=t(...o,...r,c)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(d)throw d;return i.call(n,...l)}})}e.AuthKeys=void 0,(Ee=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Ee.ROLES="roles",Ee.NAMESPACE="namespace";const Me={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},De=Me,Ie={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},Pe=Object.assign({},Ie,{type:"BigInt"});function Ne(r,a,s){return t.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(r,a,s)=>(i,n)=>{"string"==typeof r&&(s=r,r=void 0,a=void 0),"string"==typeof a&&(s=a,a=void 0),!a&&r&&r.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(a=r,r=void 0);const o=a&&a.length?a.join("_"):p;return t.propMetadata(t.Metadata.key(e.PersistenceKeys.INDEX,n,o),{directions:r,compositions:a,name:s})(i,n)},args:[r,a,s]}).apply()}function Be(e){return"function"==typeof e}function Re(e,r,a){if(!a.type){const s=t.Metadata.type(e.constructor,r);if(![Number.name,String.name,BigInt.name].includes(s?.name||s))throw Error("Incorrrect option type");a.type=s}switch(a.type){case String.name||String.name.toLowerCase():case String:a.generated=void 0!==a.generated&&a.generated,a.type=String;break;case Number.name||String.name.toLowerCase():case Number:a.generated=void 0===a.generated||a.generated,a.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:a.type=BigInt,a.generated=void 0===a.generated||a.generated;break;case"uuid":case"serial":a.generated=!0;break;default:throw Error("Unsupported type")}void 0===a.generated&&(a.generated=!0)}async function Le(e,t,s,i){if(!t.type||!t.generated||i[s])return;let n;t.name||(t.name=r.Model.sequenceName(i,"pk"));try{n=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var o,c,l;o=i,c=s,l=await n.next(e),Reflect.set(o,c,l)}async function $e(e,t,s,i,n){if(!t.type||!t.generated)return;if(!t.name){const e=r.Model.pk(i,!0);if(null==e)throw new a.InternalError("Cannot generate sequence without an id for "+i.constructor.name);t.name=r.Model.sequenceName(i,e+"",s+"")}let o;try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const c=null!=n,l=void 0!==i[s]&&null!==i[s],d=!!e.get("allowGenerationOverride")&&l;if(l&&await o.ensureAtLeast(i[s],e),c&&!t.update)return;if(d)return;const u=await o.next(e);Reflect.set(i,s,u)}function Fe(s,i){return(n,o)=>{var c,l;t.prop()(n,o),Re(n,o,s),s.name||(s.name=(c=n.constructor,l="pk",Be(r.Model.sequenceName)?r.Model.sequenceName(c,l):[Be(r.Model.tableName)?r.Model.tableName(c):c?.name??"",l].filter(Boolean).join("_")));const d=[t.propMetadata(t.Metadata.key(a.DBKeys.ID,o),s),t.propMetadata(t.Metadata.key(e.PersistenceKeys.SEQUENCE,o),s),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),r.required(),a.readonly(),a.onCreate(Le,s,i)];return s.generated&&d.push(a.generated()),t.apply(...d)(n,o)}}function Ke(s,i={},n){return(o,c)=>{t.prop()(o,c),Re(o,c,s);const l=[r.required(),t.propMetadata(t.Metadata.key(e.PersistenceKeys.SEQUENCE,c),s),a.onCreate($e,{...s,...i},n)];return i.update&&l.push(a.onUpdate($e,{...s,...i},n)),s.generated&&l.push(a.generated()),t.apply(...l)(o,c)}}function je(e){const r=Object.assign({},De);return delete r.generated,e=Object.assign({},r,e),t.Decoration.for(a.DBKeys.ID).define({decorator:Fe,args:[e,{priority:60}]}).apply()}async function Ue(e,t,s,i,n){const o=t.logger.for(Ue);if(!i){const t=r.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);i=ke.forModel(t,s),o.info("Retrieved "+i.toString())}let c;if(i=n?i.override(n):i,void 0===e[r.Model.pk(i.class)])o.info(`No pk found in ${r.Model.tableName(i.class)} - creating`),c=await i.create(e,t);else{o.info(`pk found in ${r.Model.tableName(i.class)} - attempting update`);try{c=await i.update(e,t),o.info("Updated "+r.Model.tableName(i.class))}catch(s){if(!(s instanceof a.NotFoundError))throw s;o.info("update Failed - creating new "+r.Model.tableName(i.class)),c=await i.create(e,t)}o.info("After create update: "+c)}return c}async function qe(e,t,s,i){const n=i[s];if(!n)return;if(We(i,t),"object"!=typeof n){const t=ot(i,s,this.adapter.alias),r=await t.override(this._overrides).read(n,e);return await at(e,i,s,n,r),void(i[s]=n)}const o="function"!=typeof t.class||t.class.name?t.class:t.class();if(!o)throw new a.InternalError("Could not find model "+t.class);const c=ke.forModel(o,this.adapter.alias),l=await c.override(this._overrides).create(n,e),d=r.Model.pk(l);await at(e,i,s,l[d],l),i[s]=l[d]}async function Ge(t,a,s,i){const n=i[s];if(!n)return;if(a.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof n){const e=ot(i,s,this.adapter.alias),r=await e.override(this._overrides).read(n,t);return await at(t,i,s,n,r),void(i[s]=n)}const o=await Ue(i[s],t,this.adapter.alias,void 0,this._overrides),c=r.Model.pk(o);await at(t,i,s,o[c],o),i[s]=o[c]}async function ze(t,a,s,i){const n=i[s];if(null==n)return;if(a.cascade.delete!==e.Cascade.CASCADE)return;const o=ot(i,s,this.adapter.alias);let c;c=n instanceof r.Model?await o.delete(i[s][o.pk],t):await o.delete(i[s],t),await at(t,i,s,c[o.pk],c)}async function Ye(e,t,a,s,i){const n=s[a];if(!n||!n.length)return;We(s,t);const o=e.logger.for(Ye),c=ot(s,a,this.adapter.alias),l=r.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of n){let r;"object"!=typeof t?(r=await c.override(this._overrides).read(t,e),o.debug("read: "+r[l])):(o.verbose("Creating or updating one-to-many model: "+t[l]),r=await Ue(t,e,this.adapter.alias,void 0,this._overrides)),o.debug(`caching for populate: ${JSON.stringify(r)} under ${r[l]}`),await at(e,s,a,r[l],r),d.add(r[l])}s[a]=[...d]}async function He(t,r,a,s,i){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return Ye.call(this,t,r,a,s,i)}async function Ve(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ke.forModel(c,this.adapter.alias):ot(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await at(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}async function Qe(e,t,s,i){const n=i[s];if(!n)return;We(i,t);const o=e.logger.for(Qe);if("object"!=typeof n){const t=ot(i,s,this.adapter.alias),r=await t.override(this._overrides).read(n,e);return await at(e,i,s,n,r),void(i[s]=n)}if(!(t.class instanceof r.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);o.info("Creating or updating many-to-one model: "+JSON.stringify(n));const c=await Ue(n,e,this.adapter.alias,void 0,this._overrides),l=r.Model.pk(c);o.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await at(e,i,s,c[l],c),i[s]=c[l]}function We(r,s){let i;const n="function"==typeof s.class&&s.class.name?s.class:s.class(),o=t.Metadata.get(n,e.PersistenceKeys.RELATIONS);if(o&&(i=Object.values(o)?.find(e=>{const t="function"==typeof e.class&&e.class.name?e.class:e.class();return r instanceof t})),!0===i?.populate&&!0===s?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Je(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Qe.call(this,t,r,a,s)}async function Xe(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const n="object"==typeof i,o=n?ke.forModel(i,this.adapter.alias):ot(s,a,this.adapter.alias),c=n?i[o.pk]:i,l=await o.override(this._overrides).delete(c);await at(t,s,a,c,l),s[a]=c}async function Ze(e,t,s,i){const n=i[s];if(!n||!n.length)return;We(i,t);const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c=e.logger.for(Ze),l=new Set([...n]);if("object"!==o){const r=ot(i,s,this.adapter.alias),a=await r.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<a.length;t++){const r=a[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(r)),await at(e,r,s,[...l.values()][t],a)}return await et.call(this,i,[...n],c,e,t),i[s]=[...l],void c.info("SET MANY TO MANY IDS: "+i[s])}const d=r.Model.pk(n[0].constructor),u=new Set;for(const t of n){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const r=await Ue(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(r)} under ${r[d]}`),await at(e,i,s,r[d],r),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=r.id,u.add(r[d])}const p=r.Model.pk(i.constructor);if(void 0===i[p]){const t=await(async(e,t,s)=>{const i=t[r.Model.pk(t.constructor)];if(void 0!==i)return i;const n=r.Model.sequenceFor(t.constructor);let o;n?.name||(n.name=r.Model.sequenceName(t,"pk"));try{return o=await e.adapter.Sequence(n,e._overrides),await o.next(s)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${n.name}: ${e}`)}})(this,i,e);i[p]=t}const h=await et.call(this,i,n,c,e,t);c.info("Junction model created: "+h.name),i[s]=[...u]}async function et(e,t,a,s,i){const{JunctionModel:n,fkA:o,fkB:c}=tt(e,t[0],i),l=[];for(const i of t){a.info("Creating or updating many-to-many junction model: "+JSON.stringify(i));const t={[o]:e instanceof r.Model?e[r.Model.pk(e.constructor)]:e,[c]:i instanceof r.Model?i[r.Model.pk(i.constructor)]:i},d=await Ue(new n(t),s,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=ke.forModel(n);await(e?.override(this._overrides).readAll(l))}return n}function tt(s,i,n){const o=r.Model.tableName(s);let c;if(i instanceof r.Model)c=r.Model.tableName(i);else if(r.Model.isModel(i)&&"function"==typeof i)c=i.name?i.name:i()?.name;else if(n?.class){const e="function"!=typeof n.class||n.class.name?n.class:n.class();c=r.Model.tableName(e)}if(!o||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=n?.joinTable?.name?n?.joinTable?.name:`${o}_${c}`,d=o?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends r.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),je({type:Number})(p.prototype,"id"),r.required()(p.prototype,d),r.required()(p.prototype,u);const h=r.model()(p);return t.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function rt(t,r,a){return r?[e.PersistenceKeys.POPULATE,t,r,a].join("."):[e.PersistenceKeys.POPULATE,t,a].join(".")}async function at(e,t,r,a,s){const i=rt(t.constructor.name,r,a),n=e.logger.for(at),o=e.get("cacheForPopulate")||{};let c=o[i],l=e.getOrUndefined("preferFromCache");if(!l)try{n.silly("retrieving from children"),l=e.getFromChildren("preferFromCache")||!1,l&&(c=(e.getFromChildren("cacheForPopulate")||{})[i])}catch(e){l=!1}return l&&n.debug("preferring previous cache: "+!!o[i]),o[i]=l&&c?c:s,e.accumulate({cacheForPopulate:o})}async function st(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=this,c=await(async(t,r,s,i)=>{let n,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){n=rt(r.constructor.name,s,t);try{if(c=u[n],!c)throw Error("Not found in cache")}catch(i){const n=ot(r,s,o.adapter.alias);if(!n)throw new a.InternalError("Could not find repo");c=await n.override(o._overrides).read(t,e)}l.push(c)}return l})(e,s,r,n?i:[i]);s[r]=n?c:c[0]}async function it(t,s,i,n,o){if(s.cascade.update!==e.Cascade.CASCADE)return;if(!o)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function c(e){return Array.isArray(e)?e.map(c):"object"!=typeof e?e:e[r.Model.pk(e)]}const l=c(n[i]),d=c(o[i]);if(void 0===d||r.isEqual(l,d))return;if(Array.isArray(l)!==Array.isArray(d))throw new a.InternalError("Cannot cascade update for different array types");const u=(Array.isArray(l)?l:[l]).filter(Boolean),p=(Array.isArray(d)?d:[d]).filter(Boolean).filter(e=>!u.includes(e)),h=ot(n,i,this.adapter.alias);if(!h)throw new a.InternalError("Could not find repo");try{const e=await h.override(this._overrides).deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${r.Model.tableName(h.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}const nt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function ot(e,s,i){if(!e)throw Error("No model was provided to get repository");let n,o=e instanceof r.Model?e.constructor:e;if(Array.isArray(e[s])||e[s]instanceof Set){const e=t.Metadata.get(o,t.Metadata.key(r.ValidationKeys.REFLECT,s,r.ValidationKeys.LIST))?.clazz;if(!e)throw new a.InternalError("Failed to find types decorators for property "+s);n=(Array.isArray(e)?[...e]:[e]).map(e=>"function"!=typeof e||e.name?e:e())}else n=r.Model.relations(o).includes(s)?t.Metadata.allowedTypes(o,s):t.Metadata.getPropDesignTypes(e instanceof r.Model?e.constructor:e,s)?.designTypes;o=n?.find(e=>!nt.includes((""+e.name).toLowerCase()));const c=ke.forModel(o,i);if(o!==c.class)throw new a.InternalError("Invalid repository class for "+s);return c}class ct extends a.BadRequestError{constructor(e,t=ct.name,r=401){super(e,t,r)}}class lt extends ct{constructor(e,t=lt.name){super(e,t,403)}}class dt extends a.InternalError{constructor(e){super(e,dt.name,503)}}function ut(r){return t.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:r=>a=>(t.Metadata.set(e.PersistenceKeys.TABLE,r||a.name.toLowerCase(),a),t.metadata(e.PersistenceKeys.TABLE,r||a.name.toLowerCase())(a)),args:[r]}).apply()}function pt(r){return t.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:r=>(a,s)=>t.propMetadata(t.Metadata.key(e.PersistenceKeys.COLUMN,s),r||s)(a,s),args:[r]}).apply()}async function ht(e,t,s,i){if(!i[s])return;const n=await this.select().where(Z.attribute(s).eq(i[s])).execute(),o=r.Model.pk(i),c=i[o];if(n.filter(e=>e[o]!==c).length)throw new a.ConflictError(`model already exists with property ${s} equal to ${JSON.stringify(i[s],void 0,2)}`)}async function gt(e,t,r,a){throw new ct("This adapter does not support user identification")}function ft(){return t.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(r,s)=>t.apply(a.onCreate(gt),t.propMetadata(e.PersistenceKeys.CREATED_BY,s),a.generated(e.PersistenceKeys.CREATED_BY))(r,s),args:[]}).apply()}function yt(){return t.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(r,s)=>t.apply(a.onUpdate(gt),t.propMetadata(e.PersistenceKeys.UPDATED_BY,s),a.generated(e.PersistenceKeys.UPDATED_BY))(r,s),args:[]}).apply()}function mt(){return a.timestamp([a.OperationKeys.CREATE])}function wt(){return a.timestamp()}async function _t(e,t,s,i){if("??sequence"===r.Model.tableName(i))return;const n=r.Model.pk(i,!0);if(null==n)throw new a.InternalError("Cannot generate persistent version without an id for "+i.constructor.name);const o={name:r.Model.sequenceName(i,n+"",s+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},c=await this.adapter.Sequence(o,this._overrides),l=void 0!==i[s]&&null!==i[s],d=!!e.get("allowGenerationOverride")&&l;if(l&&(await c.ensureAtLeast(i[s],e),d))return;const u=await c.next(e);i[s]=u}async function vt(e,t,s,i,n){if("??sequence"===r.Model.tableName(i))return;if(e.get("applyUpdateValidation")&&n&&i[s]!==n[s])throw new a.ValidationError(`Version mismatch: ${i[s]} !== ${n[s]}`);const o=r.Model.pk(i,!0);if(null==o)throw new a.InternalError("Cannot generate persistent version without an id for "+i.constructor.name);const c={name:r.Model.sequenceName(i,o+"",s+""),type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},l=await this.adapter.Sequence(c,this._overrides),d=void 0!==i[s]&&null!==i[s],u=!!e.get("allowGenerationOverride")&&d;if(d&&(await l.ensureAtLeast(i[s],e),u))return;const p=await l.next(e);i[s]=p}function St(){const s=e.PersistenceKeys.PERSISTENT_VERSION;return(e,i)=>t.Decoration.for(s).define(t.prop(),t.propMetadata(t.Metadata.key(s,i),!0),a.generated(s),r.type(Number),a.onCreate(_t,{},{priority:70}),a.onUpdate(vt,{},{priority:70})).apply()(e,i)}function bt(e){return[()=>{const a="function"==typeof e&&e.name?e:e(),s=r.Model.pk(a);return(t.Metadata.allowedTypes(a,s)||[])[0]}]}function Et(...r){return(a,s)=>{const i=t.Metadata.get(a,t.Metadata.key(e.PersistenceKeys.NO_VALIDATE,s))||[],n=[...new Set([...i,...r])];return t.apply(t.metadata(t.Metadata.key(e.PersistenceKeys.NO_VALIDATE,s),n))(a,s)}}function kt(r,a){return t.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(r,a)=>(s,i)=>(t.propMetadata(r,a)(s,i),t.propMetadata(t.Metadata.key(e.PersistenceKeys.RELATIONS,i),Object.assign({},a,{key:r}))(s,i)),args:[r,a]}).apply()}class Tt extends r.Model{constructor(e){super(e)}}s.__decorate([mt(),s.__metadata("design:type",Date)],Tt.prototype,"createdAt",void 0),s.__decorate([wt(),s.__metadata("design:type",Date)],Tt.prototype,"updatedAt",void 0),e.SequenceModel=class extends Tt{constructor(e){super(e)}},s.__decorate([je({type:String,generated:!1}),s.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),s.__decorate([r.required(),Ne(),s.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=s.__decorate([ut("??sequence"),r.model(),s.__metadata("design:paramtypes",[Object])],e.SequenceModel);class Ot extends i.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,N(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.FIND_BY_PAGINATE}|${e.PreparedStatementKeys.LIST_BY}|${e.PreparedStatementKeys.PAGE_BY}|${e.PreparedStatementKeys.FIND}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof b?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof b||(this._bookmark=r);const n=ke.forModel(this.clazz,this.adapter.alias),o=this.query,{method:c,args:l,params:d}=o;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await n.statement(...r,...i);return this.apply(s)}let u;if(c===e.PreparedStatementKeys.FIND_BY?u=e.PreparedStatementKeys.FIND_BY_PAGINATE:c.startsWith(e.PreparedStatementKeys.FIND_BY)?u=c.replace(e.PreparedStatementKeys.FIND_BY,e.PreparedStatementKeys.PAGE_BY):c===e.PreparedStatementKeys.LIST_BY?u=e.PreparedStatementKeys.PAGE_BY:c!==e.PreparedStatementKeys.PAGE_BY&&c!==e.PreparedStatementKeys.FIND_BY_PAGINATE||(u=c),!u)throw new O(`Method ${c} is not supported for pagination`);const p=[u,...l];let h={limit:this.size,offset:t,bookmark:this._bookmark};u!==e.PreparedStatementKeys.PAGE_BY||p.length>2?h={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:p.push(d.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new X("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new X(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new O("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new a.SerializationError(e)}}apply(e){const t="string"==typeof e?Ot.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var At,xt,Ct,Mt,Dt,It,Pt;class Nt extends E{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=a.get("forcePrepareSimpleQueries"),o=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${n}, forceComplex: ${o}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(n&&(this.isSimpleQuery()||c)||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Nt)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new J("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?r.Model.get(e):e,!this.fromSelector)throw new J("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new J("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new J("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new J("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new J(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new J("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const i=await this.raw(s,...a);if(this.hasAggregation())return i;if(!this.selectSelector){const e=e=>this.processRecord(e,r);if(this.groupBySelectors?.length){const t=this.revertGroupedResults(i,e);return await this.applyAfterHandlersToResult(t,r)}if(Array.isArray(i)){const t=i.map(e);return await this.applyAfterHandlersToResult(t,r)}const t=e(i);return await this.applyAfterHandlersToResult(t,r)}return i}catch(e){throw new J(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ke.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new O("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const i=e=>this.processRecord(e,r);if(Array.isArray(s)){const e=s.map(i);return await this.applyAfterHandlersToResult(e,r)}const n=i(s);return await this.applyAfterHandlersToResult(n,r)}processRecord(e,t){const a=e[r.Model.pk(this.fromSelector)];return this.adapter.revert(e,this.fromSelector,a,void 0,t)}async applyAfterHandlersToResult(e,t){return t.getOrUndefined("afterQueryHandlers")?e instanceof r.Model?(await a.enforceDBDecorators(this.getRepository(),t,e,a.OperationKeys.READ,a.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterHandlersToResult(e,t))),e):e&&"object"==typeof e?(await Promise.all(Object.entries(e).map(([r,a])=>this.applyAfterHandlersToResult(a,t).then(t=>{e[r]=t}))),e):e:e}getRepository(){return ke.forModel(this.fromSelector,this.adapter.alias)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const n={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,n.args=[...n.args||[],...t.args||[]]}if(i instanceof Z){const e=this.prepareCondition(i,r);t=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:n.method=a,n.args=[...n.args||[],i];break;case e.Operator.DIFFERENT:n.method=a+" diff",n.args=[...n.args||[],i];break;case e.Operator.REGEXP:n.method=a+" matches",n.args=[...n.args||[],i];break;case e.Operator.BIGGER:n.method=a+" bigger",n.args=[...n.args||[],i];break;case e.Operator.BIGGER_EQ:n.method=a+" bigger than equal";break;case e.Operator.SMALLER:n.method=a+" less",n.args=[...n.args||[],i];break;case e.Operator.SMALLER_EQ:n.method=a+" less than equal",n.args=[...n.args||[],i];break;case e.Operator.IN:n.method=a+" in",n.args=[...n.args||[],i];break;default:throw new J("Unsupported operator "+s)}return n}squash(t){const a=this.matchDefaultQueryCondition();if(a){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[a.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof Z)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let s;this.whereCondition&&(s=this.whereCondition.attr1);const i=this.orderBySelectors?.[0]?this.orderBySelectors[0]:s?[s,e.OrderDirection.DSC]:[r.Model.pk(this.fromSelector),e.OrderDirection.DSC],[n,o]=i,c={direction:o};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[n],params:c};return s&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[s,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=r.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const a=Array.from(new Set(t.map(String))),s=Array.from(new Set(e.attributes.map(String)));return a.length===s.length&&a.every(e=>s.includes(e))?{value:e.value,attributes:a}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof Z?this.collectStartsWithAttributes(r):void 0,t=s instanceof Z?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof Z?this.collectStartsWithAttributes(r):void 0)||(s instanceof Z?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},s={class:this.fromSelector,args:r,params:a};let n,o=e.QueryClause.FIND_BY;void 0!==this.countSelector?(o=e.QueryClause.COUNT_BY,n=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(o=e.QueryClause.SUM_BY,n=this.sumSelector):this.avgSelector?(o=e.QueryClause.AVG_BY,n=this.avgSelector):this.minSelector?(o=e.QueryClause.MIN_BY,n=this.minSelector):this.maxSelector?(o=e.QueryClause.MAX_BY,n=this.maxSelector):this.distinctSelector?(o=e.QueryClause.DISTINCT_BY,n=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(o=e.QueryClause.GROUP_BY_PREFIX,n=this.groupBySelectors[0]);const c=[o];if(n&&c.push(n),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&o!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&o===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),s.method=i.toCamelCase(c.join(" ")),s.params=a,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(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new J(e)}}toString(){return this.adapter.flavour+" statement"}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array]),s.__metadata("design:returntype",Object)],Nt.prototype,"select",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(At="undefined"!=typeof S&&S)?At:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"distinct",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(xt="undefined"!=typeof S&&S)?xt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"max",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Ct="undefined"!=typeof S&&S)?Ct:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"min",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Mt="undefined"!=typeof S&&S)?Mt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"sum",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Dt="undefined"!=typeof S&&S)?Dt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"avg",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(It="undefined"!=typeof S&&S)?It:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"count",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"from",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Z]),s.__metadata("design:returntype",Object)],Nt.prototype,"where",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String]),s.__metadata("design:returntype",Object)],Nt.prototype,"orderBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,String]),s.__metadata("design:returntype",Object)],Nt.prototype,"thenBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",["function"==typeof(Pt="undefined"!=typeof Key&&Key)?Pt:Object]),s.__metadata("design:returntype",Object)],Nt.prototype,"groupBy",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Number]),s.__metadata("design:returntype",Object)],Nt.prototype,"limit",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Number]),s.__metadata("design:returntype",Object)],Nt.prototype,"offset",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[void 0]),s.__metadata("design:returntype",Promise)],Nt.prototype,"execute",null);class Bt extends E{constructor(){super(),this.observers=[],this.Context=b}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Bt?i.for(e,...t):i instanceof ke?i.override(e):i}})}override(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof Bt?i.override(e,...t):i instanceof ke?i.override(e):i}})}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new T,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${B.instance.generate()}`;const a=t.logger||i.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},g,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof b||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return E.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const t=C(e),r=o.Injectables.get(t);if(r)return r;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof b||(t.push(r),r=void 0);const s=await Bt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...t);r=r?new b(r).accumulate({...s,parentContext:r}):(new b).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Bt.prototype.logCtx(t,this.boot),c=o.Injectables.services();if(!c||!Object.keys(c).length)throw new a.InternalError("No services registered for shutdown");for(const[e,t]of Object.entries(c))try{i.verbose(`Booting ${t.name} service...`);const r=o.Injectables.get(t);if(!r)throw new a.InternalError("Failed to resolve injectable for "+e);r instanceof Rt&&(i.verbose(`Initializing ${t.name} service...`),await r.boot(...n))}catch(e){throw new a.InternalError(`Failed to boot ${t.name} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof b||(t.push(r),r=void 0);const s=await Bt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...t);r=r?new b(r).accumulate({...s,parentContext:r}):(new b).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Bt.prototype.logCtx(t,this.shutdown),c=o.Injectables.services();if(!c||!Object.keys(c).length)throw new a.InternalError("No services registered for shutdown");for(const[e,t]of Object.entries(c).reverse())try{i.verbose(`Shutting down ${t.name} service...`);const r=o.Injectables.get(t);if(!r)throw new a.InternalError("Failed to resolve injectable for "+e);if(r instanceof Rt){i.verbose(`Gracefully shutting down ${t.name} service...`);try{await r.shutdown(...n)}catch(e){i.error(`Failed to gracefully shutdown ${t.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Function]),s.__metadata("design:returntype",Function)],Bt.prototype,"observe",null),s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",void 0)],Bt.prototype,"unObserve",null);class Rt extends Bt{constructor(){super()}async boot(...t){const{config:r,client:a}=await this.initialize(...t);this._config=r,this._client=a;const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);s.verbose(this.toString()+" initialized...")}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info("Shutting down...")}}function Lt(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&P(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}s.__decorate([i.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object]),s.__metadata("design:returntype",Promise)],Rt.prototype,"boot",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],Rt.prototype,"config",null),s.__decorate([i.final(),s.__metadata("design:type",Object),s.__metadata("design:paramtypes",[])],Rt.prototype,"client",null);const $t=()=>Lt(a.OperationKeys.CREATE),Ft=()=>Lt(a.OperationKeys.READ),Kt=()=>Lt(a.OperationKeys.UPDATE),jt=()=>Lt(a.OperationKeys.DELETE);function Ut(r){return(a,s,i)=>{i||s?(t.prop()(a,s),r=r||t.Metadata.type(a.constructor,s)):r=r||a,r=C(r);const n=[];if(i&&"number"==typeof i.value)n.push(o.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(o.inject(r))}else t.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(o.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return t.apply(...n)(a,s,i)}}const qt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Gt extends Bt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ke.forModel(this.clazz)),this._repository}constructor(e){super(),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=qt(e);try{const e=Bt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}select(e){return this.repo.select(e)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.repo.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let r;t=qt(t||e);try{r=Gt.get(t)}catch(e){r=void 0}if(r instanceof Gt)return r;const a=this;let i=class extends a{constructor(){super(e)}};return i=s.__decorate([Ut(t),s.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo._adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}s.__decorate([$t(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"create",null),s.__decorate([$t(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"createAll",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"delete",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"deleteAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"read",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"readAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,Object]),s.__metadata("design:returntype",Promise)],Gt.prototype,"query",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],Gt.prototype,"update",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,Object]),s.__metadata("design:returntype",Promise)],Gt.prototype,"updateAll",null);class zt extends E{isSameObservedAdapter(e){if(!this.adapter)return!1;if(this.adapter===e)return!0;const t=this.adapter,r=e;return r instanceof q&&t.alias===r.alias&&t.flavour===r.flavour}constructor(){super(),this.initialized=!1}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");if(this.initialized)return void this.log.for(this.initialize).debug("Dispatcher already initialized; skipping initialization to prevent duplicate setup");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`),this.initialized=!0;const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:n,ctx:o}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,l,d]=a,u=await t.call(r,c,l,d,...n),p=[c,i(e),l];return o.get("observeFullResult")&&p.push(Array.isArray(u)?u.map(e=>c(e)):c(u)),this.updateObservers(...p,...n).catch(t=>s.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(...e){}observe(e){if(!(e instanceof q))throw new O("Only Adapters can be observed by dispatch");if(this.adapter){if(this.isSameObservedAdapter(e))return()=>this.unObserve(e);throw new O("Dispatch is already observing another adapter")}return this.adapter=e,this.models=q.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(!this.isSameObservedAdapter(e))throw new O("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,s,...i){if(!e)throw new a.InternalError("Model must be provided for observer update");const n=e&&"string"==typeof e?e:r.Model.tableName(e);if(!this.adapter)return void this.log.for(this.updateObservers).debug(`No adapter observed for dispatch; skipping observer update for ${n}:${t}`);const{log:o,ctxArgs:c,ctx:l}=this.logCtx(i,this.updateObservers);try{o.debug(`dispatching observer refresh for ${t}:${n}: ${s}${l.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,s,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Yt(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await B.instance.generate(s)}function Ht(s=!1,i,...n){"function"==typeof s&&(i=s,s=!1);const o=e.PersistenceKeys.UUID;return t.Decoration.for(o).define({decorator:(s,i,...n)=>{const o={update:s,seed:i,args:n},c=[r.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Yt,o,{priority:54})];return s&&c.push(a.onUpdate(Yt,o,{priority:54})),s||c.push(a.readonly()),t.apply(...c)},args:[s,i,...n]}).apply()}q&&(q._baseDispatch=zt);class Vt extends E{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ke.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:n,incrementBy:o,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return Vt.lock.execute(async()=>{const r=t||o;if(r%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof n&&n?.name?n.name:n,d=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(B.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(R.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new O(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}async ensureAtLeast(t,...r){const{ctx:s}=(await this.logCtx(r,a.OperationKeys.UPDATE,!0)).for(this.ensureAtLeast),{name:i}=this.options;if(!i)throw new a.InternalError("Sequence name is required");const n=this.parse(t),o=(e,t)=>"bigint"==typeof e||"bigint"==typeof t?BigInt(e)>BigInt(t):"number"==typeof e||"number"==typeof t?Number(e)>Number(t):e+"">t+"";return Vt.lock.execute(async()=>{const t=async()=>{try{return await this.repo.read(i,s)}catch(e){if(e instanceof a.NotFoundError)return;throw e}};for(;;)try{const r=await t();if(!r)return await this.repo.create(new e.SequenceModel({id:i,current:n}),s),n;const a=this.parse(r.current);return o(n,a)?(await this.repo.update(new e.SequenceModel({id:i,current:n}),s),n):a}catch(e){if(e instanceof a.ConflictError)continue;throw e}},i)}parse(e){return Vt.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return r.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new O(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Qt(e,...t){let r;if(e instanceof Gt&&(r=e.repo.adapter),e instanceof ke&&(r=e.adapter),e instanceof q&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function Wt(...e){return(r,s,i)=>{if(!i)throw new a.InternalError("This decorator only applies to methods");return t.method()(r,s,i),t.Metadata.set(r.constructor,t.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,s),{data:e}),i.value=new Proxy(i.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),n=i.getOrUndefined("transactionLock"),o=n||Qt(t);let c;o.depth++,n||(await o.begin(i),i.cache.put("transactionLock",o));try{c=await e.call(t,...r,i)}catch(e){const t=0===o.depth;if(o.depth=0,!t)try{await o.rollback(e,i)}catch(e){s.error("Failed to rollback transaction",e)}throw e}if(o.depth--,0===o.depth)try{await o.commit(i)}catch(e){throw new a.InternalError("Failed to commit transaction: "+e)}return c}}),i}}q._baseSequence=Vt,e.TaskBackoffModel=class extends r.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},s.__decorate([r.required(),r.type(String),r.option(e.BackoffStrategy),t.description("the backoff strategy"),s.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),s.__decorate([r.required(),t.description("base interval between attempts"),s.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),s.__decorate([r.required(),t.description("max interval"),s.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),s.__decorate([r.type(String),r.option(e.JitterStrategy),t.description("optional jitter strategy"),s.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([r.required(),t.description("The error message"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),s.__decorate([t.prop(),t.description("The error stack"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),s.__decorate([t.prop(),t.description("The error code"),s.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),s.__decorate([t.prop(),t.description("The error details"),s.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends r.Model{constructor(e){if(super(e),this.ts=new Date,"string"==typeof this.payload)try{this.payload=JSON.parse(this.payload)}catch{}}},s.__decorate([je(),a.composed(["taskId","classification","uuid"],":"),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),s.__decorate([pt(),a.readonly(),r.required(),a.transient(),Ht(!1),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),s.__decorate([pt(),a.readonly(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),s.__decorate([r.date(),pt(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),s.__decorate([pt(),a.readonly(),r.required(),r.option(e.TaskEventType),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),s.__decorate([t.prop(),pt(),a.serialize(),a.readonly(),s.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=s.__decorate([ut("task_event"),r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Jt extends r.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof Z){const a=this.serializePlain(e,...t);return a[r.ModelKeys.ANCHOR]="??condition",a}return r.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const a=this.serializePlain(e,...t),s=this.getMetadata(e.constructor)??e.constructor?.name;return s&&(a[r.ModelKeys.ANCHOR]=s),a}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return t.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[r.ModelKeys.ANCHOR],a=this.rebuildObject(e);return t?"??condition"===t?Z.from(a):r.Model.build(a,t):a}rebuildObject(e){const t={};for(const[a,s]of Object.entries(e))a!==r.ModelKeys.ANCHOR&&(t[a]=this.rebuildValue(s));return t}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends r.Model{constructor(e){super(e),this.ts=new Date}},s.__decorate([r.date(),r.required(),s.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),s.__decorate([r.required(),r.option(i.LogLevel),s.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],e.TaskLogEntryModel.prototype,"step",void 0),s.__decorate([r.required(),t.prop(),s.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),s.__decorate([t.prop(),s.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends r.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},s.__decorate([je(),Ht(),t.description("the task id"),s.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),s.__decorate([pt(),r.required(),r.type(String),r.option(e.TaskType),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("defines a single or composite task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),s.__decorate([pt(),r.required(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds task classification - must match @task()"),s.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),s.__decorate([pt(),t.prop(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("optional task name for ambiguity"),s.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),s.__decorate([pt(),t.prop(),t.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),s.__metadata("design:type",String)],e.TaskModel.prototype,"lock",void 0),s.__decorate([pt(),r.required(),r.type(String),r.option(e.TaskStatus),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["nextRunAt"]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["leaseExpiry"]),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC],["scheduledTo"]),t.description("Holds the task current status"),s.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),s.__decorate([t.prop(),pt(),a.serialize(Jt),t.description("Holds task input"),s.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),s.__decorate([t.prop(),pt(),a.serialize(Jt),t.description("Holds the task output when successfully completed"),s.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the error for failed tasks"),s.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),s.__decorate([pt(),r.required(),r.min(0),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the current attempt"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),s.__decorate([pt(),r.min(1),r.required(),t.description("max attempts for the task"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),s.__decorate([pt(),r.required(),a.serialize(),t.description("backoff configuration"),s.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),s.__decorate([r.date(),pt(),t.description("Next execution timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),s.__decorate([r.date(),pt(),t.description("Task scheduled timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),s.__decorate([pt(),a.serialize(),t.description("Task dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"dependencies",void 0),s.__decorate([t.prop(),pt(),t.description("Task lease owner identifier"),s.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),s.__decorate([r.date(),pt(),t.description("Task lease expiration timestamp"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the various steps definition and inputs - only for type === 'composite'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),s.__decorate([t.prop(),pt(),r.min(0),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the current step - only for type === 'composite'"),s.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the step results - only for type === 'composite'"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),s.__decorate([t.prop(),pt(),a.serialize(),t.description("Holds the task log entries"),s.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),s.__decorate([pt(),mt(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("timestamp of creation"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),s.__decorate([pt(),wt(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("timestamp of last update"),s.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),s.__decorate([pt(),ft(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the creator of the task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),s.__decorate([pt(),yt(),Ne([e.OrderDirection.ASC,e.OrderDirection.DSC]),t.description("Holds the creator of the task"),s.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=s.__decorate([t.description("Holds the current step when applicable"),ut("tasks"),r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([r.required(),t.description("The status of a step"),s.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),s.__decorate([t.prop(),t.description("The result of a successful step"),s.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),s.__decorate([t.prop(),t.description("the error of a failed step"),s.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),s.__decorate([t.prop(),r.min(1),t.description("Number of attempts taken to complete or fail this step"),s.__metadata("design:type",Number)],e.TaskStepResultModel.prototype,"attempt",void 0),e.TaskStepResultModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends r.Model{constructor(e){super(e),this.allowConcurrent=!1,this.canFail=!1}},s.__decorate([r.required(),t.description("task handler type"),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),s.__decorate([r.minlength(1),t.description("optional task name for ambiguity"),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"name",void 0),s.__decorate([t.description("optional task step input"),t.prop(),s.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),s.__decorate([t.description("Optional lock key. Tasks/steps sharing the same key cannot run concurrently"),t.prop(),s.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"lock",void 0),s.__decorate([t.prop(),t.description("When true, compatible steps that share the same lock may run concurrently"),s.__metadata("design:type",Boolean)],e.TaskStepSpecModel.prototype,"allowConcurrent",void 0),s.__decorate([t.description("Task-step dependencies. Supports '<taskId>' or '<taskId>:<step index|step reference>'"),t.prop(),r.list(()=>String),s.__metadata("design:type",Array)],e.TaskStepSpecModel.prototype,"dependsOn",void 0),s.__decorate([t.prop(),t.description("Whether a failing step may be tolerated so the composite can continue"),s.__metadata("design:type",Boolean)],e.TaskStepSpecModel.prototype,"canFail",void 0),s.__decorate([t.prop(),r.min(1),t.description("Max attempts for this step. Defaults to 1 (no per-step retry)."),s.__metadata("design:type",Number)],e.TaskStepSpecModel.prototype,"maxAttempts",void 0),s.__decorate([t.prop(),a.serialize(),t.description("Step-level backoff config. Falls back to the parent task backoff when absent."),s.__metadata("design:type",e.TaskBackoffModel)],e.TaskStepSpecModel.prototype,"backoff",void 0),e.TaskStepSpecModel=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class Xt extends r.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,r.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}s.__decorate([r.required(),r.min(1e3),s.__metadata("design:type",Number)],Xt.prototype,"baseMs",void 0),s.__decorate([r.required(),r.option(e.JitterStrategy),s.__metadata("design:type",String)],Xt.prototype,"jitter",void 0),s.__decorate([r.gt("baseMs"),r.min(1e3),r.required(),s.__metadata("design:type",Number)],Xt.prototype,"maxMs",void 0),s.__decorate([r.required(),r.option(e.BackoffStrategy),s.__metadata("design:type",String)],Xt.prototype,"strategy",void 0);class Zt extends r.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Xt,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setLock(e){return this.lock=e,this}setDependencies(e){return this.dependencies=e,this}setDependsOn(e){return this.setDependencies(e)}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,r.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"classification",void 0),s.__decorate([t.prop(),s.__metadata("design:type",String)],Zt.prototype,"name",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"status",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],Zt.prototype,"atomicity",void 0),s.__decorate([r.required(),s.__metadata("design:type",e.TaskBackoffModel)],Zt.prototype,"backoff",void 0),s.__decorate([t.prop(),s.__metadata("design:type",Object)],Zt.prototype,"input",void 0),s.__decorate([t.prop(),s.__metadata("design:type",String)],Zt.prototype,"lock",void 0),s.__decorate([t.prop(),r.list(()=>String),s.__metadata("design:type",Array)],Zt.prototype,"dependencies",void 0),s.__decorate([r.min(1),r.required(),s.__metadata("design:type",Number)],Zt.prototype,"maxAttempts",void 0);class er{constructor(e,t){this.parent=e,this.step=t}setClassification(e){return this.step.classification=e,this}setName(e){return this.step.name=e,this}setInput(e){return this.step.input=e,this}setLock(e){return this.step.lock=e,this}setAllowConcurrent(e=!1){return this.step.allowConcurrent=e,this}setDependsOn(e){return this.step.dependsOn=e,this}setCanFail(e){return this.step.canFail=e,this}setMaxAttempts(e){return this.step.maxAttempts=e,this}setBackoff(e){return this.step.backoff=e,this}addStep(e,t,r,a){return 4>arguments.length?this.parent.addStep(e,t,r):this.parent.addStep(e,t,r,a)}setSteps(e){return this.parent.setSteps(e)}build(){return this.parent}}class tr extends Zt{constructor(t){super(t),this.stepResults=[],r.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),this}addStep(t,r,a){this.steps=this.steps||[];const s=new Date,i=1===arguments.length,n=arguments.length>=3,o=arguments.length>=4,c=n&&"string"==typeof r?r:void 0,l=o||n&&"string"==typeof r?a:i?void 0:r,d=o?!!arguments[3]:!(!n||"string"==typeof r||!a),u=new e.TaskStepSpecModel({classification:t,name:c,input:l,canFail:d,createdAt:s,updatedAt:s});return this.steps.push(u),i?new er(this,u):this}}s.__decorate([r.list(()=>e.TaskStepSpecModel),s.__metadata("design:type",Array)],tr.prototype,"steps",void 0);class rr extends k{get type(){if(!this._type){const e=t.Metadata.get(this.constructor,Q);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}async catch(e,t,r){}}function ar(e){return t.Decoration.for(Q).define({decorator:e=>r=>{const a={type:e};return t.Metadata.set(Q,e,r),t.metadata(Q,a)(r)},args:[e]}).apply()}e.CleanUpTask=class extends rr{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof Z)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=Z.attr("status").eq(e.TaskStatus.SUCCEEDED).and(Z.attr("updatedAt").lte(t.successfulExpiry)),i=Z.attr("status").eq(e.TaskStatus.FAILED).and(Z.attr("updatedAt").lte(t.failedExpiry)),n=Z.attr("status").eq(e.TaskStatus.CANCELED).and(Z.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(n)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${n.length} tasks`),a.debug("deleted tasks:",n),n}catch(e){throw a.error("Error during task cleanup",e),e}}},s.__decorate([Ae(e.TaskModel),s.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=s.__decorate([ar("cleanup-task"),s.__metadata("design:paramtypes",[])],e.CleanUpTask);class sr{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(i.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}fatal(e,t,r){this.logger.fatal(e,t,r)}critical(e,t,r){this.logger.critical(e,t,r)}for(e,...t){return new Proxy(this,{get(r,a){if("logger"===a){const s=Reflect.get(r,a);try{return s.for(e,...t)}catch(e){r.error("Failed to bind task logger. received: "+(s&&s.constructor?s.constructor.name:s.name?s.name:"unknown"),e);try{r.trace(JSON.stringify(s,void 0,2))}catch(e){r.trace("unserializable output: "+(s.name||"unknown"))}throw e}}return Reflect.get(r,a)}})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function ir(t,r={logProgress:!0,logStatus:!0,style:!0}){return async a=>{switch(t=t.for(a.taskId,{style:!1}),a.classification){case e.TaskEventType.LOG:{const e=a.payload.map(e=>Array.isArray(e)?e:[e.level,e.msg,e.meta]);for(let[a,s,n]of e){r.style||(s=i.style(s),s=s.clear().toString());const e=[s];a===i.LogLevel.verbose&&e.push(1),e.push(n);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=a.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=a.payload?.status??a.payload;let s=i.style(r);switch(r){case e.TaskStatus.SUCCEEDED:s=s.green.bold;break;case e.TaskStatus.RUNNING:s=s.blue.bold;break;case e.TaskStatus.PENDING:s=s.yellow;break;case e.TaskStatus.WAITING_RETRY:s=s.yellow.bold;break;case e.TaskStatus.FAILED:s=s.red.bold;break;case e.TaskStatus.CANCELED:s=s.magenta.bold;break;case e.TaskStatus.SCHEDULED:s=s.cyan;break;default:t.warn("Received unknown task status: "+a.payload)}t.info("### STATUS "+s)}break;case e.TaskEventType.UPDATE:if(r.logProgress){const{currentStep:e,totalSteps:r,output:s}=a.payload??{},i=s?.added,n=s?.insertionIndex,o=null!=i?` (+${i} at index ${n})`:"";t.info(`### UPDATE step ${e}/${r}${o}`)}break;default:t.warn("Unhandled task event classification: "+a.classification)}}}function nr(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function or(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function cr(e){return new Promise(t=>setTimeout(t,e))}class lr extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=lr.name,Object.setPrototypeOf(this,lr.prototype)}}class dr extends b{get taskId(){return this.get("taskId")}get logger(){return super.logger}get step(){return this.getOrUndefined("step")}setStep(e){this.cache.put("step",e)}get pipe(){return this.get("pipe").bind(this)}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}get stepWriteLock(){return this.get("stepWriteLock")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new lr({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?or(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}scheduleSteps(...t){const r=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t));return{afterCurrent:async e=>{const t=this.getOrUndefined("scheduleCompositeSteps");if(!t)throw new a.InternalError("scheduleSteps().afterCurrent() is only available while running a composite task step");await t(r,e)},atEnd:async e=>{const t=this.getOrUndefined("scheduleCompositeStepsAtEnd");if(!t)throw new a.InternalError("scheduleSteps().atEnd() is only available while running a composite task step");await t(r,e)}}}constructor(e){super(e)}}class ur{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=t.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class pr extends T{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:n}=q.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class hr extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class gr extends hr{constructor(e,t,r){super(gr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class fr extends hr{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(fr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class yr extends hr{constructor(e,t,r){super(yr.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class mr extends hr{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(mr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class wr{constructor(t,a){this.bus=t,this.task=a,this.resolved=!1,this.unregistration=t.observe(this,(t,a,s,...i)=>s.startsWith(this.task.id)&&(t===e.TaskEventModel||t===r.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(ir(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=(r.payload??[]).map(e=>Array.isArray(e)?e:[e.level,`${e.ts} - ${e.msg}`,e.meta]);await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}onUpdate(t){const r=async(r,a)=>{r.classification===e.TaskEventType.UPDATE&&await t(r,a)};return this.pipe(r,e.TaskEventType.UPDATE),()=>{this.pipes?.[e.TaskEventType.UPDATE]?.delete(r)}}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,n);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(t.classification!==e.TaskEventType.STATUS)return;if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new b),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new gr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new yr(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new fr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new mr(this.task.id,r,a);default:return new gr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class _r extends k{get Context(){return dr}get adapter(){return this._adapter||(this._adapter=this.config.adapter,this.config.overrides&&(this._adapter=this.adapter.for(this.config.overrides))),this._adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=new(this.adapter.repository())(this.adapter,e.TaskModel,!0).override({afterQueryHandlers:!0})),this._tasks}get events(){return this._events||(this._events=new(this.adapter.repository())(this.adapter,e.TaskEventModel,!0).override({afterQueryHandlers:!0})),this._events}static createTaskContext(e,t){const r=new dr(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1;const t=Object.assign({},W.autoShutdown,e.autoShutdown);this.config=Object.assign({},W,e,{autoShutdown:t,bus:e.bus||new pr,registry:e.registry||new ur}),this.idleDelayMs=this.config.pollMsIdle}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const n=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${n.id}`),t?{task:n,tracker:new wr(this.bus,n)}:n}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new wr(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await cr(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const n=await this.tasks.update(s,a);return await this.emitStatus(a,n,e.TaskStatus.CANCELED,i),n}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.idleDelayMs=this.config.pollMsIdle,this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(Z.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const n=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(n),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(n),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop),r=this.config.autoShutdown??{enabled:!1,backoffStepMs:0,maxIdleDelayMs:this.config.pollMsIdle},a=Math.max(r.maxIdleDelayMs??this.config.pollMsIdle,this.config.pollMsIdle),s=r.backoffStepMs??0;for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e)));const i=0===e.length;if(i)if(r.enabled){if(this.idleDelayMs=Math.min(this.idleDelayMs+s,a),this.idleDelayMs>=a)return t.logger.info(`auto-shutdown triggered after ${this.idleDelayMs}ms idle polling`),void await this.stop(t)}else this.idleDelayMs=this.config.pollMsIdle;else this.idleDelayMs=this.config.pollMsIdle;const n=i?this.idleDelayMs:this.config.pollMsBusy;await cr(Math.max(n,0))}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=Z.attribute("status").eq(e.TaskStatus.PENDING),i=Z.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(Z.attribute("nextRunAt").lte(a)),n=Z.attribute("status").eq(e.TaskStatus.RUNNING).and(Z.attribute("leaseExpiry").lte(a)),o=Z.attribute("status").eq(e.TaskStatus.SCHEDULED).and(Z.attribute("scheduledTo").lte(a)),c=s.or(i).or(n).or(o),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}if(!await this.isRunnable(i,r))return null;const n=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,r)}catch{return null}}isTaskFinished(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t)}parseTaskDependency(e){const t=e?.trim();if(!t)return;const r=t.lastIndexOf(":");if(0>=r||r>=t.length-1)return{taskId:t};const a=t.slice(0,r).trim(),s=t.slice(r+1).trim();return a&&s?{taskId:a,stepRef:s}:{taskId:t}}normalizeDependencies(e){if(!e)return[];let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{t=[t]}return t instanceof Set&&(t=Array.from(t)),Array.isArray(t)?t.filter(e=>"string"==typeof e).map(e=>this.parseTaskDependency(e)).filter(Boolean):[]}resolveDependencyStepIndex(e,t){const r=t.trim();if(!r)return;const a=Number(r);if(Number.isInteger(a)&&a>=0)return a;const s=this.normalizeSteps(e.steps).findIndex(e=>e.name===r||e.classification===r);return 0>s?void 0:s}async areDependenciesSatisfied(e,t){if(!e.length)return!0;const r=Array.from(new Set(e.map(e=>e.taskId))),a=new Map;try{const e=await this.tasks.readAll(r,t);for(const t of e)t?.id&&a.set(t.id,t)}catch{return!1}for(const t of e)try{const e=a.get(t.taskId);if(!e)return!1;if(!t.stepRef){if(!this.isTaskFinished(e.status))return!1;continue}const r=this.resolveDependencyStepIndex(e,t.stepRef);if(null==r)return!1;const s=this.normalizeStepResults(e.stepResults)[r];if(!s||!this.isTaskFinished(s.status))return!1}catch{return!1}return!0}getStepLock(t,r){if(t.atomicity!==e.TaskType.COMPOSITE)return;const a=this.normalizeSteps(t.steps);if(!a.length)return;const s=a[r??0];return s?.lock}async hasLockConflict(t,r,a){const s=[t.lock,this.getStepLock(t,r)].filter(e=>!!e&&"string"==typeof e);if(!s.length)return!1;const i=await this.tasks.select().where(Z.attribute("status").eq(e.TaskStatus.RUNNING)).execute(a);for(const e of i)if(e.id!==t.id&&[e.lock,this.getStepLock(e,e.currentStep)].filter(e=>!!e&&"string"==typeof e).some(e=>s.includes(e)))return!0;return!1}async isRunnable(t,r){const a=this.normalizeDependencies(t.dependencies);if(!await this.areDependenciesSatisfied(a,r))return!1;const s=t.atomicity===e.TaskType.COMPOSITE?t.currentStep??0:void 0;return!await this.hasLockConflict(t,s,r)}getCompositeStepConcurrencyLimit(){const e=this.config.maxConcurrentCompositeSteps??-1;return 0===e?1:0>e?1/0:Math.max(1,e)}isConcurrentCompositeStep(e){return!(!e.allowConcurrent||!e.lock)}createCompositeStepContext(e,t){return _r.createTaskContext(e,{step:t})}async withStepWriteLock(e,t){const r=e.stepWriteLock;await r.acquire();try{return await t()}finally{r.release()}}recalculateCompositeCurrentStep(t,r){let a=0;for(;a<t.length;){const s=r[a];if(!s)break;if(s.status===e.TaskStatus.FAILED&&!t[a]?.canFail)break;a+=1}return a}async executeClaimed(t){const{ctx:r,log:s}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),o=this;let c=Promise.resolve();const l=new dr(r).accumulate({taskId:t.id,stepWriteLock:new n.Lock,logger:new sr(s,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{"task.attempt":t.attempt},pipe:async function(...e){const r=o.normalizePipeArgs(e);r.length&&(c=c.then(async()=>{const[e,a]=await o.appendLog(this,t,r);Object.assign(t,e),await o.emitLog(this,t.id,a)}),await c)},flush:async()=>l.logger.flush(l.pipe),progress:async e=>{await this.emitProgress(l,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});let d,u;await this.emitStatus(l,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,l);try{const e=await this.tasks.read(t.id,l);Object.assign(t,e)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(d=e,u=t.input,s.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,l),await l.flush(),s.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0;const i=await this.tasks.update(t,l);Object.assign(t,i),l.logger.info(`task ${t.id} success state ${t.status}`),s.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(l,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{await l.flush()}catch{}try{const e=await this.tasks.read(t.id,l);Object.assign(t,e)}catch{}if(r instanceof lr)return void await this.handleTaskStateChange(r.request,t,l);try{await(d?.catch?.(u,r,l))}catch(e){s.error("task handler catch() hook failed",e)}if(s.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=or(r);if(a<t.maxAttempts){const o=nr(a,this.normalizeBackoff(t.backoff)),c=new Date(Date.now()+o);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=c,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const d=await this.tasks.update(t,l);Object.assign(t,d),s.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await l.pipe(i.LogLevel.warn,"Retry scheduled",{nextRunAt:c,delayMs:o,attempt:a}),await this.emitStatus(l,t,e.TaskStatus.WAITING_RETRY,n,r)}else{t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0;const o=await this.tasks.update(t,l);Object.assign(t,o),s.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await l.pipe(i.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(l,t,e.TaskStatus.FAILED,n,r)}}}async handleTaskStateChange(t,r,s){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.CANCELED,a),void await s.pipe(i.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,n=nr(a,this.normalizeBackoff(r.backoff)),o=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+n),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=o,r.scheduledTo=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.WAITING_RETRY,c),void await s.pipe(i.LogLevel.warn,"Retry requested",{nextRunAt:o,delayMs:n,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const n=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=n,r.nextRunAt=void 0,r=await this.tasks.update(r,s),await this.emitStatus(s,r,e.TaskStatus.SCHEDULED,n),void await s.pipe(i.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite);let s=this.normalizeSteps(t.steps),n=t.currentStep??0;const o=this.normalizeStepResults(t.stepResults),c=this.getCompositeStepConcurrencyLimit(),l=c>1,d=(e,t)=>{r.cacheResult(e,t),a instanceof dr&&a!==r&&a.cacheResult(e,t)},u=()=>{s=this.normalizeSteps(t.steps);for(let r=0;r<o.length;r+=1){const a=o[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=s[r];if(!e)continue;const i=`${t.id}:step:${r}`;d(e.classification,a.output),d(i,a.output)}}},p=(a,i)=>{i.cache.put("scheduleCompositeSteps",async(i,n)=>{const o=n.logger.for("scheduleSteps.afterCurrent"),c=this.normalizeSteps(i);if(!c.length)return;const l=this.normalizeSteps(t.steps),d=Math.min(a+1,l.length);l.splice(d,0,...c),t.steps=l;const p=await this.tasks.update(t,r);Object.assign(t,p),u(),o.verbose(`Inserted ${c.length} steps at index ${d}`);const h=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:a,totalSteps:s.length,output:{added:c.length,insertionIndex:d}});this.bus.emit(h,r)}),i.cache.put("scheduleCompositeStepsAtEnd",async(i,n)=>{const o=n.logger.for("scheduleSteps.atEnd"),c=this.normalizeSteps(i);if(!c.length)return;const l=this.normalizeSteps(t.steps),d=l.length;l.push(...c),t.steps=l;const p=await this.tasks.update(t,r);Object.assign(t,p),u(),o.verbose(`Appended ${c.length} steps at tail (index ${d})`);const h=await this.persistEvent(r,t.id,e.TaskEventType.UPDATE,{status:"update",currentStep:a,totalSteps:s.length,output:{added:c.length,insertionIndex:d}});this.bus.emit(h,r)})},h=async n=>{const c=s[n],l=this.registry.get(c.classification);if(!l)throw Error("No task handler registered for composite step: "+c.classification);const u=this.createCompositeStepContext(r,n);p(n,u);const h=this.normalizeDependencies(c.dependsOn);await this.areDependenciesSatisfied(h,u)||u.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting dependencies for step ${n} (${c.classification})`),await this.hasLockConflict(t,n,u)&&u.reschedule(new Date(Date.now()+this.config.pollMsIdle),`Waiting lock for step ${n} (${c.classification})`),await this.withStepWriteLock(u,async()=>{t.currentStep=n;const e=await this.tasks.update(t,r);Object.assign(t,e)}),await u.progress({currentStep:n,totalSteps:s.length}),await u.pipe([i.LogLevel.info,`Composite step ${n+1}/${s.length}: ${c.classification}`]);const g=c.maxAttempts??1;let f,y=0;for(;g>y;)try{const a=await l.run(c.input,u);await u.flush();const i=new Date;o[n]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:a,attempt:y+1,createdAt:i,updatedAt:i});const p=`${t.id}:step:${n}`;d(c.classification,a),d(p,a),await this.withStepWriteLock(u,async()=>{t.stepResults=o,t.currentStep=this.recalculateCompositeCurrentStep(s,o);const e=await this.tasks.update(t,r);Object.assign(t,e)}),await this.emitProgress(u,t.id,{currentStep:t.currentStep??n+1,totalSteps:s.length,output:a}),f=void 0;break}catch(e){if(y+=1,f=e,g>y){const e=nr(y,this.normalizeBackoff(c.backoff??t.backoff));await u.pipe(i.LogLevel.warn,`Composite step ${n} attempt ${y}/${g} failed, retrying in ${e}ms`,{classification:c.classification,attempt:y,delay:e}),await cr(e),await u.heartbeat()}}if(f){const i=new Date,d=!0===c.canFail,p=or(f);if(o[n]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:p,attempt:y,createdAt:i,updatedAt:i}),d)try{await(l.catch?.(c.input,f,u))}catch(e){a.logger.warn("composite step catch() hook failed",{error:e})}if(await this.withStepWriteLock(u,async()=>{t.stepResults=o,t.error=d?void 0:p,t.currentStep=this.recalculateCompositeCurrentStep(s,o);const e=await this.tasks.update(t,r);Object.assign(t,e)}),!d)throw f}},g=async e=>{const t=e.map(e=>h(e)),r=(await Promise.allSettled(t)).find(e=>"rejected"===e.status);if(r&&"rejected"===r.status)throw r.reason};for(u();n<s.length;){const e=s[n];if(this.isConcurrentCompositeStep(e)&&l){const r=e.lock,a=[n];for(let e=n+1;e<s.length&&a.length<c;e+=1){const t=s[e];if(!this.isConcurrentCompositeStep(t))break;if(t.lock!==r)break;if(t.dependsOn?.length)break;a.push(e)}if(a.length>1){await g(a),s=this.normalizeSteps(t.steps),n=this.recalculateCompositeCurrentStep(s,o);continue}}await h(n),s=this.normalizeSteps(t.steps),n=this.recalculateCompositeCurrentStep(s,o)}return{stepResults:o}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=Array.isArray(a)&&Array.isArray(a[0]),i=r.atomicity===e.TaskType.COMPOSITE?t instanceof dr?t.step??r.currentStep:r.currentStep:void 0,n=(s?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a,step:i}));try{return await this.withStepWriteLock(t,async()=>{const e=[...r.logTail??[],...n].slice(-this.config.logTailMax);return r.logTail=e,[await this.tasks.update(r,t),n]})}catch{return[r,[]]}}async emitStatus(t,r,a,s,i){t instanceof dr&&await t.flush();const n={status:a};s&&s instanceof e.TaskErrorModel?n.error=s:s&&(n.output=s),r.nextRunAt&&(n.nextRunAt=r.nextRunAt),r.scheduledTo&&(n.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,n),c=void 0!==i?Object.assign({},n,{originalError:i}):n,l=new e.TaskEventModel({...o,payload:c});this.bus.emit(l,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta,step:e.step})));this.bus.emit(s,t)}normalizePipeArgs(e){if(!e.length)return[];if(1===e.length){const t=e[0];return Array.isArray(t)?0===t.length?[]:Array.isArray(t[0])?t.filter(Array.isArray):[t]:[]}const[t,r,a]=e;return"string"!=typeof t||"string"!=typeof r?[]:[[t,r,a]]}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class vr extends Rt{get adapter(){return this.client.adapter}get tasks(){return this.client.tasks}get events(){return this.client.events}constructor(){super()}async initialize(...e){const t=e.shift();if(!t||t instanceof b)throw new a.InternalError("No/invalid config provided");if(!t.adapter)throw new a.InternalError("No adapter provided");return{client:new(t.engine||_r)(t),config:t}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}select(e){return this.tasks.select(e)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.tasks.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.tasks.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.tasks.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.tasks.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.tasks.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.tasks.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.tasks?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.tasks,s)}async update(e,...t){throw new O("Updates to tasks are not available")}async updateAll(e,...t){throw new O("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.tasks.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.tasks.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.tasks.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.tasks.findBy(t,r,...s)}async findByPaginate(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_BY_PAGINATE,!0)).for(this.findByPaginate);return this.tasks.findByPaginate(t,r,a,...i)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.tasks.statement(t,...a)}refresh(e,t,r,...a){return this.tasks.refresh(e,t,r,...a)}observe(e,t){return this.tasks.observe(e,t)}unObserve(e){return this.tasks.unObserve(e)}updateObservers(e,t,r,...a){return this.tasks.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.tasks._adapter.logCtx([this.tasks.class,...e],t,r,this.tasks._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}var Sr;function br(e){if(0>=e)throw new a.InternalError("splitByCount: count must be greater than zero");return t=>{const r=[];for(let a=0;a<t.length;a+=e)r.push(t.slice(a,a+e));return r}}function Er(e){if(0>=e)throw new a.InternalError("splitBySize: maxBytes must be greater than zero");return t=>{const r=[];let a=[],s=0;for(const i of t){const t=kr(i);a.length>0&&s+t>e?(r.push(a),a=[i],s=t):(a.push(i),s+=t)}return a.length>0&&r.push(a),r}}function kr(e){if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}}function Tr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}s.__decorate([$t(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[e.TaskModel,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"create",null),s.__decorate([$t(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"createAll",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"delete",null),s.__decorate([jt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"deleteAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"read",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"readAll",null),s.__decorate([Ft(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"query",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[e.TaskModel,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"update",null),s.__decorate([Kt(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Array,void 0]),s.__metadata("design:returntype",Promise)],vr.prototype,"updateAll",null),e.ThrottleMode=void 0,(Sr=e.ThrottleMode||(e.ThrottleMode={})).BY_COUNT="count",Sr.BY_SIZE="size";const Or=Object.assign({},f,{persistMigrationSteps:!0});class Ar{constructor(e="migration-task"){this.builder=(new tr).setClassification("migration-composite").setName(e).setMaxAttempts(1)}addMigrationStep(e){return this.builder.addStep("migration",e),this}addStep(e,t){return this.builder.addStep(e,t),this}build(){return this.builder.build()}}class xr{isVersionHint(e){return!!e}normalize(e,t){return t&&e&&(e.includes(t)||e===t)?t:e||t||"migration"}compare(e,t){return e.localeCompare(t)}gt(e,t){return this.compare(e,t)>0}lte(e,t){return 0>=this.compare(e,t)}}class Cr extends Rt{constructor(){super(),this.versioning=new xr,this.allowedReferences=void 0,this.queuedTaskChain=[],this.reference=Cr.name,this.precedence=null}static async migrateAdapters(e,t={},...r){return(Cr.defaultSingleton||=new Cr).migrateAdapters(e,t,...r)}async migrateAdapters(e,t={},...r){const s=t.flavours?.length?new Set(t.flavours):void 0,i=e.filter(e=>!s||s.has(e.alias)),n=new Set(e.map(e=>e.alias).filter(Boolean)),o=t.taskService?.client,c=o?.adapter?.alias||o?.adapter?.flavour;if(c&&n.has(c))throw new a.InternalError(`TaskEngine adapter alias "${c}" cannot participate in the migration targets`);const l=this;l.versioning=t.versioning||new xr,l.allowedReferences=t.references?.length?new Set(t.references):void 0,l.queuedTaskChain=[],l.orchestrationConfig={...Or,targetVersion:t.toVersion,taskMode:!!t.taskMode,taskService:t.taskService,versioning:t.versioning,references:t.references};for(const e of i){const a=e.alias,s=t.handlers?.[a]||t.handlers?.[e.flavour]||{},n={...Or,persistenceFlavour:a,targetVersion:t.toVersion,taskMode:!!t.taskMode,includeGenericInTaskMode:t.includeGenericInTaskMode??!(t.taskMode&&i.length>1),retrieveLastVersion:s.retrieveLastVersion,setCurrentVersion:s.setCurrentVersion,taskService:t.taskService,versioning:t.versioning,references:t.references};t.taskMode?await l.migrateViaTasksWithConfig(n,...r):await l.migrateNormallyWithConfig(n,...r)}return l}async initialize(...t){const{log:r,ctx:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);try{Bt.get(e.PersistenceKeys.PERSISTENCE)}catch(e){a.get("ignoreDevSafeGuards")||r.warn("Persistence service not available. this may indicate poor initialization of the persistence layer (or not)")}const s=Object.assign({},t.length?t[0]:Or,Or);return this.versioning=s.versioning||new xr,this.allowedReferences=s.references?.length?new Set(s.references):void 0,this.transaction=s.persistMigrationSteps,{config:s,client:s.persistenceFlavour?q.get(s.persistenceFlavour):void 0}}async down(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(i.style("Cleaning up after all migrations").green.bold)}normalizeVersion(e,t){return this.versioning.normalize(e,t)}extractPrecedenceTokens(e){const t=e.precedence;return t?(Array.isArray(t)?t:[t]).map(e=>{if(e&&"string"!=typeof e)return"function"==typeof e?e.name:"string"==typeof e.reference?e.reference:e.constructor?.name?e.constructor.name:void 0}).filter(e=>!!e):[]}referencesMigration(e,t){const r=this.extractPrecedenceTokens(e);return!!r.length&&(r.includes(t.reference)||r.includes(t.migration?.constructor?.name))}precedenceHint(e){return"string"==typeof e.precedence?e.precedence:void 0}compareByPrecedence(e,t){const r=e.migration,a=t.migration,s=this.referencesMigration(r,t),i=this.referencesMigration(a,e);if(s&&!i)return 1;if(i&&!s)return-1;const n=this.extractPrecedenceTokens(r),o=this.extractPrecedenceTokens(a);return n.length!==o.length?n.length-o.length:0}sort(e){const t=[...e].sort((e,t)=>{const r=this.versioning.compare(e.version,t.version);if(0!==r)return r;const a=this.compareByPrecedence(e,t);if(0!==a)return a;const s=e.flavour.localeCompare(t.flavour);return 0!==s?s:e.reference.localeCompare(t.reference)});for(let e=0;e<t.length;e++){const r=t[e],s=t[e+1];if(r&&s&&r.version===s.version&&r.flavour===s.flavour&&0===this.compareByPrecedence(r,s))throw new a.InternalError(`Unable to deterministically sort flavour migrations for version ${r.version} and flavour ${r.flavour}: ${r.reference} vs ${s.reference}`)}return t}resolveMigration(r){const a=t.Metadata.get(r.constructor,e.PersistenceKeys.MIGRATION),s=a?.flavour||r.flavour||t.DefaultFlavour,i=a?.reference||r.reference,n=this.precedenceHint(r);return{migration:r,flavour:s,reference:i,version:this.normalizeVersion(i,n)}}shouldIncludeMigration(e,r,a=!0){return!r||e.flavour===r||a&&e.flavour===t.DefaultFlavour}collectMigrations(e,r=!0){const s=t.Metadata.migrations(),i=[];for(const[t,n]of s){let s;try{s=new n}catch(e){throw new a.InternalError(`failed to create migration ${t}: ${e}`)}const o=this.resolveMigration(s);this.shouldIncludeMigration(o,e,r)&&i.push(o)}return i}buildExecutionPlan(e){const t=e?.fromVersion?this.normalizeVersion(e.fromVersion):void 0,r=e?.toVersion?this.normalizeVersion(e.toVersion):void 0;return this.sort(this.collectMigrations(e?.targetFlavour,e?.includeGeneric)).filter(e=>!(this.allowedReferences&&!this.allowedReferences.has(e.reference)||t&&!this.versioning.gt(e.version,t)||r&&!this.versioning.lte(e.version,r)))}async executeMigration(e,...t){const r=e.migration;let s,i;try{if(s=q.get(e.flavour),!s)throw new a.InternalError(`failed to create migration ${r.reference}. did you call Service.boot() or use the Persistence Service??`);i=s.client}catch(e){throw new a.InternalError(`Failed to load adapter to migrate ${r.reference}: ${e}`)}try{await r.up(i,s,...t)}catch(e){throw new A(`failed to initialize migration ${r.reference}: ${e}`)}try{await r.migrate(i,s,...t)}catch(e){throw new A(`failed to migrate ${r.reference}: ${e}`)}try{await r.down(i,s,...t)}catch(e){throw new A(`failed to conclude migration ${r.reference}: ${e}`)}}buildMigrationTaskForPlan(e,...t){const r=[...t],a=new Ar;return e.forEach(e=>{const t={reference:e.reference,args:r};a.addMigrationStep(t)}),a.build()}buildMigrationTasksForPlan(e,...t){const r=new Map;for(const t of e){const e=r.get(t.version)||[];e.push(t),r.set(t.version,e)}return[...r.entries()].map(([e,r])=>({version:e,task:this.buildMigrationTaskForPlan(r,...t)}))}createMigrationTask(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTaskForPlan(i,...r)}createMigrationTasks(e,t,...r){const a=this.config,s=!a.taskMode||(a.includeGenericInTaskMode??!0),i=this.buildExecutionPlan({toVersion:e||a.targetVersion,fromVersion:t,targetFlavour:a.persistenceFlavour,includeGeneric:s});return this.buildMigrationTasksForPlan(i,...r)}migrationTaskIdsFromContext(e,t){const r=t[t.length-1],a=r?.pending?.()||r?.pending||{},s=a?.[e];return Array.isArray(s)?s.filter(e=>"string"==typeof e):[]}async migrate(e,t,...r){this.config.taskMode?await this.migrateViaTasks(void 0,void 0,...r):await this.migrateNormally(void 0,void 0,...r)}async migrateNormally(e,t,...r){return this.migrateNormallyWithConfig(this.config,...r)}async migrateNormallyWithConfig(t,...r){const{ctxArgs:a,log:s}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateNormally),i=t.persistenceFlavour,n=!t.taskMode||(t.includeGenericInTaskMode??!0),o=i?q.get(i):void 0;let c;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(o,...a);e&&(c=this.normalizeVersion(e))}const l=this.buildExecutionPlan({fromVersion:c,toVersion:t.targetVersion,targetFlavour:i,includeGeneric:n});s.debug("sorted migration before execution: "+l.map(e=>`${e.reference}@${e.version}`));for(const e of l)await this.executeMigration(e,...a);if(t.setCurrentVersion){const e=t.targetVersion||l[l.length-1]?.version||c||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),o,...a)}}async migrateViaTasks(e,t,...r){return this.queuedTaskChain=[],this.migrateViaTasksWithConfig(this.config,...r)}async migrateViaTasksWithConfig(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.migrateViaTasks),n=t.persistenceFlavour,o=t.includeGenericInTaskMode??!0,c=n?q.get(n):void 0;let l;if(t.retrieveLastVersion){const e=await t.retrieveLastVersion(c,...s);e&&(l=this.normalizeVersion(e))}const d=this.buildExecutionPlan({fromVersion:l,toVersion:t.targetVersion,targetFlavour:n,includeGeneric:o});if(i.debug("sorted migration before execution: "+d.map(e=>`${e.reference}@${e.version}`)),d.length){const r=this.buildMigrationTasksForPlan(d,...s);if(t.taskService){let n;for(const o of r){n&&(o.task.dependencies=[...o.task.dependencies||[],n]);const r=await t.taskService.push(o.task,!1,...s);n=r.id,this.queuedTaskChain.push({id:r.id,version:o.version,adapter:c,setCurrentVersion:t.setCurrentVersion}),r?.id||i.warn("TaskService.push returned missing id for version "+o.version),a.pushPending(e.PersistenceKeys.MIGRATION,r.id)}}else{for(const e of d)await this.executeMigration(e,...s);if(t.setCurrentVersion){const e=t.targetVersion||d[d.length-1]?.version||l||void 0;e&&await t.setCurrentVersion(this.normalizeVersion(e),c,...s)}}}}async track(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.track),s=this.orchestrationConfig||this.config;if(!s.taskService||!s.taskMode)return;const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return;const l=new Map(this.queuedTaskChain.map(e=>[e.id,e])),d=s.persistenceFlavour?q.get(s.persistenceFlavour):void 0;for(const e of c){const{tracker:t}=await s.taskService.track(e,...a);await t.wait();const r=l.get(e),i=r?.setCurrentVersion||s.setCurrentVersion;i&&r?.version&&await i(this.normalizeVersion(r.version),r.adapter||d,...a)}}async retry(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.MIGRATION,!0)).for(this.retry),s=this.orchestrationConfig||this.config;if(!s.taskMode||!s.taskService)return void await this.migrateNormally(void 0,void 0,...a);const i="string"==typeof t?[t]:Array.isArray(t)?t:void 0,n=this.queuedTaskChain.map(e=>e.id),o=this.migrationTaskIdsFromContext(e.PersistenceKeys.MIGRATION,a),c=i?.length?i:n.length?n:o;if(!c.length)return void await this.migrateViaTasks(void 0,void 0,...a);const l=s.taskService.client.tasks,d="function"==typeof l?.override?l.override({ignoreHandlers:!0}):l;for(const t of c){const r=(await s.taskService.track(t,...a)).task;if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(r.status))continue;const i=new e.TaskModel({...r,status:e.TaskStatus.PENDING,error:void 0,nextRunAt:void 0,scheduledTo:void 0,leaseOwner:void 0,leaseExpiry:void 0});await d.update(i,...a)}}async up(e,t,...r){const{log:a}=this.logCtx(r,this.down);a.verbose(i.style("Setting up migration process").yellow.bold)}}const Mr=t.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.DefaultFlavour)||[];t.Metadata.set(e.PersistenceKeys.MIGRATION,t.DefaultFlavour,[...Mr,Cr]),e.MigrationTask=class extends rr{async run(r,s){s.logger.info("Executing migration "+r.reference);const i=t.Metadata.migrations().find(([,a])=>{const s=a?.name,i=t.Metadata.get(a,e.PersistenceKeys.MIGRATION)?.reference;return s===r.reference||i===r.reference});if(!i)throw new a.InternalError(`Migration ${r.reference} is not registered with the metadata layer`);const n=i[1];let o;try{o=new n}catch(e){throw new a.InternalError(`Failed to instantiate migration ${r.reference}: ${e}`)}const c=t.Metadata.get(o.constructor,e.PersistenceKeys.MIGRATION),l=c?.flavour||o.flavour,d=q.get(l);if(!d)throw new a.InternalError("Unable to resolve adapter for migration "+r.reference);const u=d.client,p=r.args??[];try{await o.up(u,d,...p,s)}catch(e){throw s.logger.error(`Up phase for ${r.reference} failed: ${e}`),new A(`Up phase for ${r.reference} failed: ${e}`)}try{await o.migrate(u,d,...p,s)}catch(e){throw s.logger.error(`migration phase for ${r.reference} failed: ${e}`),new A(`Migration phase for ${r.reference} failed: ${e}`)}try{await o.down(u,d,...p,s)}catch(e){throw s.logger.error(`down phase for ${r.reference} failed: ${e}`),new A(`Down phase for ${r.reference} failed: ${e}`)}s.logger.info(`migration ${r.reference} completed`)}},e.MigrationTask=s.__decorate([ar("migration")],e.MigrationTask),o.Injectables.setRegistry(new Oe);const Dr="##VERSION##",Ir="##PACKAGE##";t.Metadata.registerLibrary(Ir,Dr),e.AbsContextual=k,e.AbsMigration=class extends k{get reference(){if(!this._reference){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._reference=r.reference,!this._reference)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._reference}get precedence(){if(void 0===this._precedence){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(this._precedence=r.precedence,!this._precedence)throw new a.InternalError(`No precedence defined for ${this.constructor.name}. did you use @migration()?`)}return this._precedence}constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;N(this,e,this.prefix(t))})}get adapter(){const r=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!r)throw new a.InternalError("No migration metadata for "+this.constructor.name);const s=r.flavour;return q.get(s)}async enforceRules(r,a,s){const i=t.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!i||!i.length)return!0;for(const e of i)if(!await e(r,a,s))return!1;return!0}prefix(t){return async function(r,...a){let s;r instanceof q?s=this.getQueryRunner(r.client):(s=r,r=this.adapter);const{ctx:i,log:n}=await this.logCtx([t,...a],e.PersistenceKeys.MIGRATION,!0);if(!await this.enforceRules(s,r,i))throw n.verbose(`Skipping migration ${this.constructor.name} due to rules`),new x("Migration skipped for rule enforcement");return[s,r,i]}.bind(this)}logCtx(t,r,a=!1,s){let i;try{i=this.adapter}catch{i=void 0}return a&&i?i.context("string"==typeof r?r:r.name,s||{},void 0,...t).then(a=>super.logCtx(["string"==typeof r?r:r.name,...t.slice(0,-1),a],e.PersistenceKeys.MIGRATION,!1,s)):super.logCtx(t,r,a,s)}},e.Adapter=q,e.AuthorizationError=ct,e.BaseModel=Tt,e.BigIntSequence=Pe,e.COMMIT="49b1386",e.ClientBasedService=Rt,e.CompositeTaskBuilder=tr,e.Condition=Z,e.ConnectionError=dt,e.Context=b,e.ContextLock=$,e.ContextualLoggedClass=E,e.DefaultAdapterFlags=f,e.DefaultCascade=re,e.DefaultContextFlags=g,e.DefaultMigrationConfig=Or,e.DefaultRepositoryFilters=fe,e.DefaultSequenceOptions=De,e.DefaultTaskEngineConfig=W,e.Dispatch=zt,e.FULL_VERSION="0.28.1-49b1386",e.ForbiddenError=lt,e.INDEX_SELF=p,e.InjectablesRegistry=Oe,e.MethodQueryBuilder=ie,e.MigrationError=A,e.MigrationRuleError=x,e.MigrationService=Cr,e.MigrationTaskBuilder=Ar,e.ModelService=Gt,e.MultipleSelectOperationKeys=_,e.NonTransactionOperationKeys=m,e.NoneSequenceOptions=Me,e.NumericSequence=Ie,e.ObserverError=xe,e.ObserverHandler=T,e.OperatorsMap=ae,e.PACKAGE_NAME=Ir,e.PaginationOperationKeys=v,e.Paginator=Ot,e.PagingError=X,e.PersistenceService=class extends Rt{constructor(){super()}for(e,...t){throw new O("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof b||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),n=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of n)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:n,config:r}}},e.QueryError=J,e.Repository=ke,e.SelectOperationKeys=w,e.Sequence=Vt,e.Serial=R,e.Service=Bt,e.SimpleConcurrencyLock=L,e.StandardMigrationVersioning=xr,e.Statement=Nt,e.TaskBackoffBuilder=Xt,e.TaskBuilder=Zt,e.TaskCancelError=yr,e.TaskContext=dr,e.TaskControlError=hr,e.TaskEngine=_r,e.TaskEventBus=pr,e.TaskEventService=class extends Gt{constructor(){super(e.TaskEventModel)}get repo(){return this._repository||(this._repository=Bt.get(e.TaskModel).events),this._repository}},e.TaskFailError=gr,e.TaskHandler=rr,e.TaskHandlerRegistry=ur,e.TaskIOSerializer=Jt,e.TaskLogger=sr,e.TaskRescheduleError=mr,e.TaskRetryError=fr,e.TaskService=vr,e.TaskStepSpecBuilder=er,e.TaskTracker=wr,e.TasksKey=Q,e.TransactionOperationKeys=y,e.UUID=B,e.UnsupportedError=O,e.VERSION=Dr,e.allowIf=(e,...t)=>(r,a,s)=>{Ce("allowIf",e,t,a,s)},e.applyViewDecorator=oe,e.auth=r=>{const a=e.PersistenceKeys.AUTH;return t.Decoration.for(a).define({decorator:e=>t.metadata(a,e),args:[r]}).apply()},e.blockIf=(e,...t)=>(r,a,s)=>{Ce("blockIf",e,t,a,s)},e.cacheModelForPopulate=at,e.cascadeDelete=it,e.column=pt,e.computeBackoffMs=nr,e.create=$t,e.createOrUpdate=Ue,e.createdAt=mt,e.createdBy=ft,e.createdByOnCreateUpdate=gt,e.defaultQueryAttr=()=>(r,a)=>{const s=t.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let i=t.Metadata.get(r.constructor,s)||[];return i=[...new Set([...i,a])],t.apply(t.propMetadata(s,i))(r,a)},e.del=jt,e.generateInjectableNameForRepository=Te,e.getAndConstructJunctionTable=tt,e.getFilters=ye,e.getLogPipe=ir,e.getPkTypes=bt,e.getPopulateKey=rt,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ne,e.injectableServiceKey=C,e.isOperationBlocked=P,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.list([e,...d]),a.onCreate(Ze,c),a.onUpdate(He,c),a.afterAny(st,c)];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.manyToManyOnCreate=Ze,e.manyToManyOnDelete=async function(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const n=i[s];if(!n||!n.length)return;const o=typeof n[0];if(!n.every(e=>typeof e===o))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===o,d=l?ke.forModel(c,this.adapter.alias):ot(i,s,this.adapter.alias),u=[...new Set([...l?n.map(e=>e[d.pk]):n]).values()];let p,h;try{p=await d.override(this._overrides).deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await at(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Ze.call(this,t,r,a,s)},e.manyToOne=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.type([e,...d]),a.onCreate(Qe,c),a.onUpdate(Je,c),a.onDelete(Xe,c),a.afterAny(st,c)];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.manyToOneOnCreate=Qe,e.manyToOneOnDelete=Xe,e.manyToOneOnUpdate=Je,e.migration=(r,a,s,i)=>t.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(a,s,i)=>n=>{const o=a&&"object"==typeof a&&!("name"in a)?a:void 0,c=o?.precedence,l=o?.flavour,d=o?.rules,u=o?c:a,p=o?l:s,h=o?d:i,g=o?void 0!==c:void 0!==u&&("string"!=typeof u||"string"==typeof u&&"string"==typeof p);let f,y,m=u;"string"==typeof u?"string"==typeof p?(m=u,f=p,y=h):Array.isArray(p)?(m=void 0,f=u,y=p):(m=void 0,f=u,y=h):Array.isArray(p)?y=p:(f=p,y=h),void 0===m&&null!==m&&(m=Cr);const w=t.Metadata.flavourOf(n)||t.DefaultFlavour,_=(g&&m===Cr&&r&&r!==f?r:f)||w,v=t.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")),_||t.DefaultFlavour)||[];return t.Metadata.set([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-"),_||t.DefaultFlavour,[...v,{class:n}]),t.Metadata.set(e.PersistenceKeys.MIGRATION,r,n),t.metadata(e.PersistenceKeys.MIGRATION,{reference:r||n.name,precedence:m,flavour:_||t.DefaultFlavour,rules:y})(n)},args:[a,s,i]}).apply(),e.noValidateOn=Et,e.noValidateOnCreate=()=>Et(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>Et(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>Et(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.list([e,...d]),a.onCreate(Ye,c,{priority:70}),a.onUpdate(He,c,{priority:70}),a.onDelete(Ve,c,{priority:70}),a.onUpdate(it,c,{priority:80}),a.afterAny(st,c,{priority:70})];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.oneToManyOnCreateUpdate=Ye,e.oneToManyOnDelete=Ve,e.oneToManyOnUpdate=He,e.oneToOne=(s,i=re,n=!0,o,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return t.Decoration.for(l).define({decorator:(e,s,i,n,o)=>{const c={class:e,cascade:s,populate:i};n&&(c.joinTable=n),o&&(c.name=o);const d=bt(e),u=[t.prop(),kt(l,c),r.type([e,...d]),a.onCreate(qe,c,{priority:70}),a.onUpdate(Ge,c,{priority:70}),a.onDelete(ze,c,{priority:70}),a.onUpdate(it,c,{priority:80}),a.afterAny(st,c,{priority:70})];return t.apply(...u)},args:[s,i,n,o,c]}).apply()},e.oneToOneOnCreate=qe,e.oneToOneOnDelete=ze,e.oneToOneOnUpdate=Ge,e.onlyOnBulk=he,e.onlyOnCreate=ce,e.onlyOnDelete=de,e.onlyOnFilter=ge,e.onlyOnSingle=pe,e.onlyOnTransactional=ue,e.onlyOnUpdate=le,e.persistentVersion=St,e.pk=je,e.pkDec=Fe,e.pkOnCreate=Le,e.populate=st,e.prefixMethod=N,e.prepared=ne,e.promiseSequence=M,e.query=(r={})=>t.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:r=>function s(i,n,o){const c=ie.getFieldsFromMethodName(n);return t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.QUERY,n),{...r,fields:c}),ne(),(e=>(t,r,i)=>{i.value=new Proxy(i.value,{async apply(t,r,i){const{action:n,select:o,selector:c,where:l,groupBy:d,orderBy:u,limit:p,offset:h}=ie.build(t.name,...i);if(!(r instanceof a.Repository))throw Error("thisArg must be an instance of Repository");const g=r,{ctx:f}=(await g.logCtx(i,s.name,!0)).for(s);let y;switch(n){case"find":case"page":y=g.select(o);break;case"count":y=g.count(c);break;case"sum":y=g.sum(c);break;case"avg":y=g.avg(c);break;case"min":y=g.min(c);break;case"max":y=g.max(c);break;case"distinct":y=g.distinct(c);break;case"group":y=g.select(),c&&(y=y.groupBy(c));break;default:throw new J("Unsupported action: "+n)}if(l&&(y=y.where(l)),d&&d.length>0&&"group"!==n){y=y.groupBy(d[0]);for(let e=1;e<d.length;e++)y=y.thenBy(d[e])}else if(d&&d.length>0&&"group"===n)for(const e of d)y=y.thenBy(e);const{allowLimit:m,allowOffset:w,allowOrderBy:_,throws:v}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},S=[{key:"orderBy",value:(u||[])[0],allowed:_},{key:"limit",value:p,allowed:m},{key:"offset",value:h,allowed:w}];for(const e of S)if(void 0!==e.value){if(!e.allowed&&v)throw new J(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(y=y[e.key](e.value))}if("page"===n){const e=i[i.length-1],t="number"==typeof e?e:e?.limit??10;return y.paginate(t,f)}return y.execute(f)}})})(r))(i,n,o)},args:[r]}).apply(),e.read=Ft,e.relation=kt,e.repository=Ae,e.repositoryFromTypeMetadata=ot,e.resolveBulkSequenceResult=U,e.resolveTransactionLock=Qt,e.roles=r=>t.metadata(e.PersistenceKeys.AUTH_ROLE,r),e.route=(r,a)=>{const s=e.PersistenceKeys.DECAF_ROUTE;return t.Decoration.for(s).define({decorator:()=>(e,i,n)=>{const o={path:a,httpMethod:r,handler:n};return t.apply(t.methodMetadata(t.Metadata.key(s,i),o))(e,i,n)},args:[]}).apply()},e.sequence=(r,a)=>{const s=Object.assign({},De);delete s.generated,r=Object.assign({},s,r);const i="boolean"==typeof a?{update:a}:a||{};return t.Decoration.for(e.PersistenceKeys.SEQUENCE).define({decorator:Ke,args:[r,i,{priority:70}]}).apply()},e.sequenceDec=Ke,e.sequenceOnCreateUpdate=$e,e.serializeError=or,e.service=Ut,e.sleep=cr,e.splitByCount=br,e.splitBySize=Er,e.table=ut,e.task=ar,e.throttle=function r(s,i,n){let o,c;if("function"==typeof s)o=s,c=i??{};else{const t="string"==typeof i?i:e.ThrottleMode.BY_COUNT;c=("object"!=typeof i||Array.isArray(i)?n:i)??{},o=t===e.ThrottleMode.BY_SIZE?Er(s):br(s)}const{delayMs:l,argIndex:d=0}=c;return(s,i,n)=>t.apply(t.methodMetadata(t.Metadata.key(e.PersistenceKeys.THROTTLE,i),c),(e,t,s)=>{s.value=new Proxy(s.value,{async apply(e,s,i){const n=i,{log:u,ctx:p}=(await s.logCtx(i,e.name,!0)).for(r),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttle() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(d);if(!h.length)throw new a.InternalError("@throttle() expects at least one argument index to throttle");h.forEach(e=>{if(e>=n.length)throw new a.InternalError(`@throttle() requires argument index ${e} but only ${n.length} provided`);if(!Array.isArray(n[e]))throw new a.InternalError(`@throttle() expects argument at index ${e} to be an array`)});const g=h.map(e=>n[e]),f=g[0].length;if(!g.every(e=>e.length===f))throw new a.InternalError("@throttle() requires all targeted arguments to have the same length");if(0===f)return e.apply(s,n);const y=((e,t,r,a)=>{let s=0;return e.map(e=>{const i=e.length,n=a.map((a,n)=>{const o=r.indexOf(n);return-1===o?a:0===o?e:t[o].slice(s,s+i)});return s+=i,n})})(o(g[0]),g,h,n),m=c.breakOnSingleFailure??(()=>{try{return p.get("breakOnSingleFailureInBulk")}catch{return}})()??!0,w=[],_=[];for(const t of y){try{Tr(await e.apply(s,t),w)}catch(e){if(m)throw e;_.push(e)}l&&await new Promise(e=>setTimeout(e,l))}if(_.length){u.warn(`${t+""} throttled execution continued with ${_.length} failure(s)`);const e=new AggregateError(_,`Throttled ${t+""} failed for ${_.length} chunk(s)`);throw e.results=w,e}return w}})})(s,i,n)},e.transactional=(...e)=>t.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:Wt,args:e}).apply(),e.unique=()=>{const s=e.PersistenceKeys.UNIQUE;return t.Decoration.for(s).define(r.async(),a.onCreateUpdate(ht),t.propMetadata(s,{})).apply()},e.uniqueOnCreateUpdate=ht,e.update=Kt,e.updatedAt=wt,e.updatedBy=yt,e.uuid=Ht,e.uuidCreateUpdateHandler=Yt,e.validBidirectionalRelation=We,e.version=(e=!1)=>e?St():a.version(),e.view=r=>t.Decoration.for(e.Operator.VIEW).define({decorator:t=>oe(e.Operator.VIEW,"view",t),args:[r]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/logging"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/injectable-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/logging","@decaf-ts/transactional-decorators","@decaf-ts/injectable-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsLogging,e.decafTsTransactionalDecorators,e.decafTsInjectableDecorators);
2
2
  //# sourceMappingURL=core.cjs.map