@chromahq/core 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,1670 +1,12 @@
1
- function e(e){return ("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function t$2(e){switch(typeof e){case "string":case "symbol":return e.toString();case "function":return e.name;default:throw new Error(`Unexpected ${typeof e} service id type`)}}const n$1=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");class r{[n$1];#e;constructor(e){this.#e=e,this[n$1]=true;}static is(e){return "object"==typeof e&&null!==e&&true===e[n$1]}unwrap(){return this.#e()}}
1
+ import { inject, injectable } from '@inversifyjs/core';
2
+ import { T as TOKENS } from './IJob-aWBqI3FC.js';
3
+ export { J as JobState } from './IJob-aWBqI3FC.js';
2
4
 
3
- function t$1(t,e){return Reflect.getOwnMetadata(e,t)}function n(t,e,n){Reflect.defineMetadata(e,n,t);}function a(e,n,a,f){const c=f(t$1(e,n)??a());Reflect.defineMetadata(n,c,e);}
4
-
5
- const s="@inversifyjs/container/bindingId";function c(){const i=t$1(Object,s)??0;return i===Number.MAX_SAFE_INTEGER?n(Object,s,Number.MIN_SAFE_INTEGER):a(Object,s,(()=>i),(e=>e+1)),i}const u={Request:"Request",Singleton:"Singleton",Transient:"Transient"},d={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};function*l(...e){for(const t of e)yield*t;}class p{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(const t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e;}add(e,t){this.#i(e).push(t);for(const n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e);}clone(){const e=this.#r(),t=this.#a(),n=Reflect.ownKeys(this.#n),i=this._buildNewInstance(this.#n);this.#s(this.#e,i.#e,e,t);for(const t of n)this.#c(this.#t[t],i.#t[t],e);return i}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){const n=this.get(e,t);if(void 0===n)return;const i=new Set(n);for(const n of i){const i=this.#e.get(n);if(void 0===i)throw new Error("Expecting model relation, none found");for(const o of i)o[e]===t&&this.#u(n,o);this.#e.delete(n);}}_buildNewInstance(e){return new p(e)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){const e=new Map;for(const t of this.#e.keys()){const n=this._cloneModel(t);e.set(t,n);}return e}#a(){const e=new Map;for(const t of this.#e.values())for(const n of t){const t=this._cloneRelation(n);e.set(n,t);}return e}#i(e){let t=this.#e.get(e);return void 0===t&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return void 0===n&&(n=[],this.#t[e].set(t,n)),n}#d(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting model to be cloned, none found");return n}#l(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting relation to be cloned, none found");return n}#c(e,t,n){for(const[i,o]of e){const e=new Array;for(const t of o)e.push(this.#d(t,n));t.set(i,e);}}#s(e,t,n,i){for(const[o,r]of e){const e=new Array;for(const t of r)e.push(this.#l(t,i));t.set(this.#d(o,n),e);}}#u(e,t){for(const n of Reflect.ownKeys(t))this.#p(e,n,t[n]);}#p(e,t,n){const i=this.#t[t].get(n);if(void 0!==i){const o=i.indexOf(e);-1!==o&&i.splice(o,1),0===i.length&&this.#t[t].delete(n);}}}var f,g,h;!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(f||(f={}));let m$1 = class m{#f;#g;constructor(e,t){this.#f=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new m(e)}add(e,t){this.#f.add(e,t);}clone(){return new m(this.#g,this.#f.clone())}get(e){const t=[],n=this.#f.get(f.serviceId,e);void 0!==n&&t.push(n);const i=this.#g?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l(...t)}removeAllByModuleId(e){this.#f.removeByRelation(f.moduleId,e);}removeAllByServiceId(e){this.#f.removeByRelation(f.serviceId,e);}};function v(e){return e.isRight?{isRight:true,value:e.value}:e}function y(e){switch(e.type){case d.ConstantValue:case d.DynamicValue:return function(e){return {cache:v(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type,value:e.value}}(e);case d.Factory:return function(e){return {cache:v(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.Instance:return function(e){return {cache:v(e.cache),id:e.id,implementationType:e.implementationType,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.Provider:return function(e){return {cache:v(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,provider:e.provider,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.ResolvedValue:return function(e){return {cache:v(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,metadata:e.metadata,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.ServiceRedirection:return function(e){return {id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,serviceIdentifier:e.serviceIdentifier,targetServiceIdentifier:e.targetServiceIdentifier,type:e.type}}(e)}}!function(e){e.id="id",e.moduleId="moduleId",e.serviceId="serviceId";}(g||(g={}));class M extends p{_buildNewInstance(e){return new M(e)}_cloneModel(e){return y(e)}}let I$1 = class I{#h;#g;constructor(e,t){this.#h=t??new M({id:{isOptional:false},moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new I(e)}clone(){return new I(this.#g,this.#h.clone())}get(e){return this.getNonParentBindings(e)??this.#g?.get(e)}getBoundServices(){const e=new Set(this.#h.getAllKeys(g.serviceId));if(void 0!==this.#g)for(const t of this.#g.getBoundServices())e.add(t);return e}getById(e){return this.#h.get(g.id,e)??this.#g?.getById(e)}getByModuleId(e){return this.#h.get(g.moduleId,e)??this.#g?.getByModuleId(e)}getNonParentBindings(e){return this.#h.get(g.serviceId,e)}getNonParentBoundServices(){return this.#h.getAllKeys(g.serviceId)}removeById(e){this.#h.removeByRelation(g.id,e);}removeAllByModuleId(e){this.#h.removeByRelation(g.moduleId,e);}removeAllByServiceId(e){this.#h.removeByRelation(g.serviceId,e);}set(e){const t={[g.id]:e.id,[g.serviceId]:e.serviceIdentifier};void 0!==e.moduleId&&(t[g.moduleId]=e.moduleId),this.#h.add(e,t);}};!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(h||(h={}));class w{#m;#g;constructor(e,t){this.#m=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new w(e)}add(e,t){this.#m.add(e,t);}clone(){return new w(this.#g,this.#m.clone())}get(e){const t=[],n=this.#m.get(h.serviceId,e);void 0!==n&&t.push(n);const i=this.#g?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l(...t)}removeAllByModuleId(e){this.#m.removeByRelation(h.moduleId,e);}removeAllByServiceId(e){this.#m.removeByRelation(h.serviceId,e);}}function b(e,t,n){const i=Array.isArray(e)?e:[e];if(void 0!==n)if("number"!=typeof n)Reflect.decorate(i,t.prototype,n);else for(const e of i)e(t,void 0,n);else Reflect.decorate(i,t);}const S="@inversifyjs/core/classMetadataReflectKey";function j$1(){return {constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}const R="@inversifyjs/core/pendingClassMetadataCountReflectKey";const T$1=Symbol.for("@inversifyjs/core/InversifyCoreError");let A$1 = class A extends Error{[T$1];kind;constructor(e,t,n){super(t,n),this[T$1]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[T$1]}static isErrorOfKind(e,t){return A.is(e)&&e.kind===t}};var C$1,B$1,$$1;function x$1(t){const n=t$1(t,S)??j$1();if(!function(t){const n=t$1(t,R);return void 0!==n&&0!==n}(t))return function(e,t){const n=[];if(t.length<e.length)throw new A$1(C$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e) void 0===t[e]&&n.push(e);if(n.length>0)throw new A$1(C$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join('", "')}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(t,n.constructorArguments),n;!function(e,t){const n=[];for(let i=0;i<t.constructorArguments.length;++i){const o=t.constructorArguments[i];void 0!==o&&o.kind!==B$1.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${i.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`);}for(const[i,o]of t.properties)o.kind===B$1.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${i.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);if(0===n.length)throw new A$1(C$1.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new A$1(C$1.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join("\n\n")}`)}(t,n);}function D$1(){return 0}function k$1(e){return t=>{ void 0!==t&&t.kind===B$1.unknown&&a(e,R,D$1,(e=>e-1));}}function P$1(e,t){return (...n)=>i=>{if(void 0===i)return e(...n);if(i.kind===$$1.unmanaged)throw new A$1(C$1.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return t(i,...n)}}function O$1(e){if(e.kind!==B$1.unknown&&true!==e.isFromTypescriptParamType)throw new A$1(C$1.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}!function(e){e[e.injectionDecoratorConflict=0]="injectionDecoratorConflict",e[e.missingInjectionDecorator=1]="missingInjectionDecorator",e[e.planning=2]="planning",e[e.resolution=3]="resolution",e[e.unknown=4]="unknown";}(C$1||(C$1={})),function(e){e[e.unknown=32]="unknown";}(B$1||(B$1={})),function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection",e[e.unmanaged=2]="unmanaged";}($$1||($$1={}));const V$1=P$1((function(e,t){return {kind:e,name:void 0,optional:false,tags:new Map,value:t}}),(function(e,t,n){return O$1(e),{...e,kind:t,value:n}}));function F$1(e,t){return n=>{const i=n.properties.get(t);return n.properties.set(t,e(i)),n}}var E$1;function N$1(e,t,n,i){if(A$1.isErrorOfKind(i,C$1.injectionDecoratorConflict)){const o=function(e,t,n){if(void 0===n){if(void 0===t)throw new A$1(C$1.unknown,"Unexpected undefined property and index values");return {kind:E$1.property,property:t,targetClass:e.constructor}}return "number"==typeof n?{index:n,kind:E$1.parameter,targetClass:e}:{kind:E$1.method,method:t,targetClass:e}}(e,t,n);throw new A$1(C$1.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${i.message}\n\nDetails\n\n${function(e){switch(e.kind){case E$1.method:return `[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case E$1.parameter:return `[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case E$1.property:return `[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(o)}`,{cause:i})}throw i}function U$1(e,t){return (i,o,r)=>{try{void 0===r?function(e,t){const i=K$1(e,t);return (e,t)=>{a(e.constructor,S,j$1,F$1(i(e),t));}}(e,t)(i,o):"number"==typeof r?function(e,t){const i=K$1(e,t);return (e,t,o)=>{if(!function(e,t){return "function"==typeof e&&void 0===t}(e,t))throw new A$1(C$1.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??""}" at class "${e.constructor.name}"`);a(e,S,j$1,function(e,t){return n=>{const i=n.constructorArguments[t];return n.constructorArguments[t]=e(i),n}}(i(e),o));}}(e,t)(i,o,r):function(e,t){const i=K$1(e,t);return (e,t,o)=>{if(!function(e){return void 0!==e.set}(o))throw new A$1(C$1.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);a(e.constructor,S,j$1,F$1(i(e),t));}}(e,t)(i,o,r);}catch(e){N$1(i,o,r,e);}}}function K$1(e,t){return n=>{const i=t(n);return t=>(i(t),e(t))}}function _$1(e){return U$1(V$1($$1.singleInjection,e),k$1)}!function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property";}(E$1||(E$1={}));const q$1="@inversifyjs/core/classIsInjectableFlagReflectKey";const z$1=[Array,BigInt,Boolean,Function,Number,Object,String];function G$1(t){const i=t$1(t,"design:paramtypes");void 0!==i&&a(t,S,j$1,function(e){return t=>(e.forEach(((e,n)=>{var i;void 0!==t.constructorArguments[n]||(i=e,z$1.includes(i))||(t.constructorArguments[n]=function(e){return {isFromTypescriptParamType:true,kind:$$1.singleInjection,name:void 0,optional:false,tags:new Map,value:e}}(e));})),t)}(i));}function L$1(i){return o=>{!function(n$1){if(void 0!==t$1(n$1,q$1))throw new A$1(C$1.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${n$1.name}"`);n(n$1,q$1,true);}(o),G$1(o);}}var ue;!function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection";}(ue||(ue={}));class de{#v;constructor(e){this.#v=e;}get name(){return this.#v.elem.name}get serviceIdentifier(){return this.#v.elem.serviceIdentifier}get tags(){return this.#v.elem.tags}getAncestor(){if(void 0!==this.#v.previous)return new de(this.#v.previous)}}class le{last;constructor(e){this.last=e;}concat(e){return new le({elem:e,previous:this.last})}[Symbol.iterator](){let e=this.last;return {next:()=>{if(void 0===e)return {done:true,value:void 0};const t=e.elem;return e=e.previous,{done:false,value:t}}}}}function pe(e,t,n){const i=n?.customServiceIdentifier??t.serviceIdentifier,o=[...e.getBindings(i)??[]].filter((e=>e.isSatisfiedBy(t)));if(0===o.length&&void 0!==e.autobindOptions&&"function"==typeof i){const t=function(e,t){const n=x$1(t),i=n.scope??e.scope;return {cache:{isRight:false,value:void 0},id:c(),implementationType:t,isSatisfiedBy:()=>true,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:i,serviceIdentifier:t,type:d.Instance}}(e.autobindOptions,i);e.setBinding(t),o.push(t);}return o}function fe(e){return void 0!==e.redirections}function ge(e,t,n,i){let r,a;fe(n)?(r=n.binding.targetServiceIdentifier,a=n.binding.serviceIdentifier):(r=n.serviceIdentifier,a=n.parent?.binding.serviceIdentifier),Array.isArray(e)?function(e,t,n,i,r){if(0!==e.length){const t=`Ambiguous bindings found for service: "${t$2(n)}".\n\nRegistered bindings:\n\n${e.map((e=>function(e){switch(e.type){case d.Instance:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case d.ServiceRedirection:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", redirection: "${t$2(e.targetServiceIdentifier)}" ]`;default:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding))).join("\n")}\n\nTrying to resolve bindings for "${me(n,i)}".\n\n${ve(r)}`;throw new A$1(C$1.planning,t)}t||he(n,i,r);}(e,t,r,a,i):function(e,t,n,i,o){if(void 0!==e||t)return;he(n,i,o);}(e,t,r,a,i);}function he(e,t,n){const i=`No bindings found for service: "${t$2(e)}".\n\nTrying to resolve bindings for "${me(e,t)}".\n\n${ve(n)}`;throw new A$1(C$1.planning,i)}function me(e,t){return void 0===t?`${t$2(e)} (Root service)`:t$2(t)}function ve(e){const t=0===e.tags.size?"":`\n- tags:\n - ${[...e.tags.keys()].map((e=>e.toString())).join("\n - ")}`;return `Binding constraints:\n- service identifier: ${t$2(e.serviceIdentifier)}\n- name: ${e.name?.toString()??"-"}${t}`}function ye(e,t,n){if(1!==e.redirections.length)ge(e.redirections,t,e,n);else {const[i]=e.redirections;fe(i)&&ye(i,t,n);}}function Me(e,t,n){if(Array.isArray(e.bindings)&&1===e.bindings.length){const[i]=e.bindings;fe(i)&&ye(i,t,n);}else ge(e.bindings,t,e,n);}function Ie(e,t){if(function(e){return e instanceof Error&&(e instanceof RangeError&&/stack space|call stack|too much recursion/i.test(e.message)||"InternalError"===e.name&&/too much recursion/.test(e.message))}(t)){const n=function(e){const t=[...e];if(0===t.length)return "(No dependency trace)";return t.map(t$2).join(" -> ")}(function(e){const t=new Set;for(const n of e.servicesBranch){if(t.has(n))return [...t,n];t.add(n);}return [...t]}(e));throw new A$1(C$1.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}function we(e){try{const t=new Map;void 0!==e.rootConstraints.tag&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value);const n=new le({elem:{name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0}),i=new de(n.last),o=pe(e,i),r=[],a={bindings:r,parent:void 0,serviceIdentifier:e.rootConstraints.serviceIdentifier};if(r.push(...Te(e,n,o,a)),!e.rootConstraints.isMultiple){Me(a,e.rootConstraints.isOptional??!1,i);const[t]=r;a.bindings=t;}return {tree:{root:a}}}catch(t){Ie(e,t);}}function be(e,t,n,i){const o={binding:t,classMetadata:e.getClassMetadata(t.implementationType),constructorParams:[],parent:i,propertyParams:new Map};return Ce({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:o,servicesBranch:e.servicesBranch,setBinding:e.setBinding},n)}function Se(e,t,n){if(n.kind===$$1.unmanaged)return;const i=r.is(n.value)?n.value.unwrap():n.value,o=t.concat({name:n.name,serviceIdentifier:i,tags:n.tags}),a=new de(o.last),s=pe(e,a),c=[],u={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...Te(e,o,s,u)),n.kind===$$1.singleInjection){Me(u,n.optional,a);const[e]=c;u.bindings=e;}return u}function je(e,t,n){const i=r.is(n.value)?n.value.unwrap():n.value,o=t.concat({name:n.name,serviceIdentifier:i,tags:n.tags}),a=new de(o.last),s=pe(e,a),c=[],u={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...Te(e,o,s,u)),n.kind===ue.singleInjection){Me(u,n.optional,a);const[e]=c;u.bindings=e;}return u}function Re(e,t,n,i){const o={binding:t,params:[],parent:i};return Ce({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:o,servicesBranch:e.servicesBranch,setBinding:e.setBinding},n)}function Te(e,t,n,i){const o=fe(i)?i.binding.targetServiceIdentifier:i.serviceIdentifier;e.servicesBranch.push(o);const r=[];for(const o of n)switch(o.type){case d.Instance:r.push(be(e,o,t,i));break;case d.ResolvedValue:r.push(Re(e,o,t,i));break;case d.ServiceRedirection:{const n=Ae(e,t,o,i);r.push(n);break}default:r.push({binding:o,parent:i});}return e.servicesBranch.pop(),r}function Ae(e,t,n,i){const o={binding:n,parent:i,redirections:[]},r=pe(e,new de(t.last),{customServiceIdentifier:n.targetServiceIdentifier});return o.redirections.push(...Te(e,t,r,o)),o}function Ce(e,t){return e.node.binding.type===d.Instance?function(e,t,n){const i=t.classMetadata;for(const[o,r]of i.constructorArguments.entries())t.constructorParams[o]=Se(e,n,r);for(const[o,r]of i.properties){const i=Se(e,n,r);void 0!==i&&t.propertyParams.set(o,i);}return e.node}(e,e.node,t):function(e,t,n){const i=t.binding.metadata;for(const[o,r]of i.arguments.entries())t.params[o]=je(e,n,r);return e.node}(e,e.node,t)}class Be{#y;#M;#I;constructor(){this.#y=[],this.#M=8,this.#I=1024;}*[Symbol.iterator](){let e=0;for(const t of this.#y){const n=t.deref();void 0===n?++e:yield n;}this.#y.length>=this.#M&&this.#w(e)&&this.#b(e);}push(e){const t=new WeakRef(e);if(this.#y.push(t),this.#y.length>=this.#M&&this.#y.length%this.#I===0){let e=0;for(const t of this.#y) void 0===t.deref()&&++e;this.#w(e)&&this.#b(e);}}#b(e){const t=new Array(this.#y.length-e);let n=0;for(const e of this.#y)e.deref()&&(t[n++]=e);this.#y=t;}#w(e){return e>=.5*this.#y.length}}var $e;!function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length";}($e||($e={}));class xe{#S;#j;#R;#T;#A;constructor(){this.#S=this.#C(),this.#j=this.#C(),this.#R=this.#C(),this.#T=this.#C(),this.#A=new Be;}clearCache(){for(const e of this.#B())e.clear();for(const e of this.#A)e.clearCache();}get(e){return void 0===e.name?void 0===e.tag?this.#$(this.#S,e).get(e.serviceIdentifier):this.#$(this.#T,e).get(e.serviceIdentifier)?.get(e.tag.key)?.get(e.tag.value):void 0===e.tag?this.#$(this.#j,e).get(e.serviceIdentifier)?.get(e.name):this.#$(this.#R,e).get(e.serviceIdentifier)?.get(e.name)?.get(e.tag.key)?.get(e.tag.value)}set(e,t){ void 0===e.name?void 0===e.tag?this.#$(this.#S,e).set(e.serviceIdentifier,t):this.#x(this.#x(this.#$(this.#T,e),e.serviceIdentifier),e.tag.key).set(e.tag.value,t):void 0===e.tag?this.#x(this.#$(this.#j,e),e.serviceIdentifier).set(e.name,t):this.#x(this.#x(this.#x(this.#$(this.#R,e),e.serviceIdentifier),e.name),e.tag.key).set(e.tag.value,t);}subscribe(e){this.#A.push(e);}#C(){const e=new Array($e.length);for(let t=0;t<e.length;++t)e[t]=new Map;return e}#x(e,t){let n=e.get(t);return void 0===n&&(n=new Map,e.set(t,n)),n}#$(e,t){return e[this.#D(t)]}#B(){return [...this.#S,...this.#j,...this.#R,...this.#T]}#D(e){return e.isMultiple?true===e.optional?$e.multipleOptional:$e.multipleMandatory:true===e.optional?$e.singleOptional:$e.singleMandatory}}function De(e$1,t){return e(t)?(e$1.cache={isRight:true,value:t},t.then((t=>ke(e$1,t)))):ke(e$1,t)}function ke(e,t){return e.cache={isRight:true,value:t},t}function Pe(e$1,t,n){const i=e$1.getActivations(t);return void 0===i?n:e(n)?Oe(e$1,n,i[Symbol.iterator]()):function(e$1,t,n){let i=t,o=n.next();for(;true!==o.done;){const t=o.value(e$1.context,i);if(e(t))return Oe(e$1,t,n);i=t,o=n.next();}return i}(e$1,n,i[Symbol.iterator]())}async function Oe(e,t,n){let i=await t,o=n.next();for(;true!==o.done;)i=await o.value(e.context,i),o=n.next();return i}function Ve(e$1,t,n){let i=n;if(void 0!==t.onActivation){const n=t.onActivation;i=e(i)?i.then((t=>n(e$1.context,t))):n(e$1.context,i);}return Pe(e$1,t.serviceIdentifier,i)}function Fe(e){return (t,n)=>{if(n.cache.isRight)return n.cache.value;return De(n,Ve(t,n,e(t,n)))}}const Ee=Fe((function(e,t){return t.value}));function Ne(e){return e}function Ue(e,t){return (n,i)=>{const o=e(i);switch(o.scope){case u.Singleton:if(o.cache.isRight)return o.cache.value;return De(o,Ve(n,o,t(n,i)));case u.Request:{if(n.requestScopeCache.has(o.id))return n.requestScopeCache.get(o.id);const e=Ve(n,o,t(n,i));return n.requestScopeCache.set(o.id,e),e}case u.Transient:return Ve(n,o,t(n,i))}}}const Ke=(e=>Ue(Ne,e))((function(e,t){return t.value(e.context)}));const _e=Fe((function(e,t){return t.factory(e.context)}));function qe(e$1,t,n){const i=function(e$1,t,n){if(void 0===n)return;if(!(n in e$1))throw new A$1(C$1.resolution,`Expecting a "${n.toString()}" property when resolving "${t.implementationType.name}" class @postConstruct decorated method, none found.`);if("function"!=typeof e$1[n])throw new A$1(C$1.resolution,`Expecting a "${n.toString()}" method when resolving "${t.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let i;try{i=e$1[n]();}catch(e){throw new A$1(C$1.resolution,`Unexpected error found when calling "${n.toString()}" @postConstruct decorated method on class "${t.implementationType.name}"`,{cause:e})}if(e(i))return async function(e,t,n){try{await n;}catch(n){throw new A$1(C$1.resolution,`Unexpected error found when calling "${t.toString()}" @postConstruct decorated method on class "${e.implementationType.name}"`,{cause:n})}}(t,n,i)}}(e$1,t,n);return e(i)?i.then((()=>e$1)):e$1}function ze(e$1){return (t,n,i)=>{const o=new i.binding.implementationType(...t),r=e$1(n,o,i);return e(r)?r.then((()=>qe(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName))):qe(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName)}}const Ge=Fe((function(e,t){return t.provider(e.context)}));function Le(e){return e.binding}function We(e){return e.binding}const Xe=function(e$1){return (t,n,i)=>{const o=[];for(const[r,s]of i.propertyParams){const c=i.classMetadata.properties.get(r);if(void 0===c)throw new A$1(C$1.resolution,`Expecting metadata at property "${r.toString()}", none found`);c.kind!==$$1.unmanaged&&void 0!==s.bindings&&(n[r]=e$1(t,s),e(n[r])&&o.push((async()=>{n[r]=await n[r];})()));}if(o.length>0)return Promise.all(o).then((()=>{}))}}(nt),He=function(e){return function t(n,i){const o=[];for(const r of i.redirections)fe(r)?o.push(...t(n,r)):o.push(e(n,r));return o}}(tt),Je=function(e$1,t,n){return (i,o)=>{const r=e$1(i,o);return e(r)?t(r,i,o):n(r,i,o)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.constructorParams) void 0===o?i.push(void 0):i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(nt),function(e){return async(t,n,i)=>{const o=await t;return e(o,n,i)}}(ze(Xe)),ze(Xe)),Qe=function(e$1){return (t,n)=>{const i=e$1(t,n);return e(i)?i.then((e=>n.binding.factory(...e))):n.binding.factory(...i)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.params)i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(nt)),Ye=(e=>Ue(Le,e))(Je),Ze=(e=>Ue(We,e))(Qe);function et(e){return nt(e,e.planResult.tree.root)}function tt(e,t){switch(t.binding.type){case d.ConstantValue:return Ee(e,t.binding);case d.DynamicValue:return Ke(e,t.binding);case d.Factory:return _e(e,t.binding);case d.Instance:return Ye(e,t);case d.Provider:return Ge(e,t.binding);case d.ResolvedValue:return Ze(e,t)}}function nt(e$1,t){if(void 0!==t.bindings)return Array.isArray(t.bindings)?function(e$1,t){const n=[];for(const i of t)fe(i)?n.push(...He(e$1,i)):n.push(tt(e$1,i));if(n.some(e))return Promise.all(n);return n}(e$1,t.bindings):function(e,t){if(fe(t)){const n=He(e,t);if(1===n.length)return n[0];throw new A$1(C$1.resolution,"Unexpected multiple resolved values on single injection")}return tt(e,t)}(e$1,t.bindings)}function it(e){return void 0!==e.scope}function ot(e,t){if(void 0!==e.lifecycle.preDestroyMethodName&&"function"==typeof t[e.lifecycle.preDestroyMethodName])return t[e.lifecycle.preDestroyMethodName]()}function rt(e$1,t,n){const i=e$1.getDeactivations(t);if(void 0!==i)return e(n)?at(n,i[Symbol.iterator]()):function(e$1,t){let n=t.next();for(;true!==n.done;){const i=n.value(e$1);if(e(i))return at(e$1,t);n=t.next();}}(n,i[Symbol.iterator]())}async function at(e,t){const n=await e;let i=t.next();for(;true!==i.done;)await i.value(n),i=t.next();}function st(e$1,t){const n=function(e$1,t){if(t.type===d.Instance){const n=e$1.getClassMetadata(t.implementationType),i=t.cache.value;return e(i)?i.then((e=>ot(n,e))):ot(n,i)}}(e$1,t);return void 0===n?ct(e$1,t):n.then((()=>ct(e$1,t)))}function ct(e$1,t){const n=t.cache;return e(n.value)?n.value.then((n=>ut(e$1,t,n))):ut(e$1,t,n.value)}function ut(e,t,n){let i;if(void 0!==t.onDeactivation){i=(0, t.onDeactivation)(n);}return void 0===i?rt(e,t.serviceIdentifier,n):i.then((()=>rt(e,t.serviceIdentifier,n)))}function dt(e,t){if(void 0===t)return;const n=function(e){const t=[];for(const n of e)it(n)&&n.scope===u.Singleton&&n.cache.isRight&&t.push(n);return t}(t),i=[];for(const t of n){const n=st(e,t);void 0!==n&&i.push(n);}return i.length>0?Promise.all(i).then((()=>{})):void 0}function lt(e,t){const n=e.getBindingsFromModule(t);return dt(e,n)}function pt(e,t){const n=e.getBindings(t);return dt(e,n)}
6
-
7
- const t=Symbol.for("@inversifyjs/plugin/isPlugin");
8
-
9
- const m=Symbol.for("@inversifyjs/container/bindingIdentifier");function I(e){return "object"==typeof e&&null!==e&&true===e[m]}class A{static always=e=>true}function P(e){return {[m]:true,id:e.id}}function C(e){return n=>{for(let i=n.getAncestor();void 0!==i;i=i.getAncestor())if(e(i))return true;return false}}function B(e){return n=>n.name===e}function x(e){return n=>n.serviceIdentifier===e}function O(e,n){return i=>i.tags.has(e)&&i.tags.get(e)===n}function N(e){return void 0===e.name&&0===e.tags.size}function U(e){const n=C(e);return e=>!n(e)}function F(e){return n=>{const i=n.getAncestor();return void 0===i||!e(i)}}function k(e){return n=>{const i=n.getAncestor();return void 0!==i&&e(i)}}class j{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}inRequestScope(){return this.#i.scope=u.Request,new E(this.#i)}inSingletonScope(){return this.#i.scope=u.Singleton,new E(this.#i)}inTransientScope(){return this.#i.scope=u.Transient,new E(this.#i)}}class D{#t;#r;#a;#s;constructor(e,n,i,t){this.#t=e,this.#r=n,this.#a=i,this.#s=t;}to(e){const n=x$1(e),i={cache:{isRight:false,value:void 0},id:c(),implementationType:e,isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:n.scope??this.#a,serviceIdentifier:this.#s,type:d.Instance};return this.#t(i),new L(i)}toSelf(){if("function"!=typeof this.#s)throw new Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#s)}toConstantValue(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:u.Singleton,serviceIdentifier:this.#s,type:d.ConstantValue,value:e};return this.#t(n),new E(n)}toDynamicValue(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:d.DynamicValue,value:e};return this.#t(n),new L(n)}toResolvedValue(e,n){const i={cache:{isRight:false,value:void 0},factory:e,id:c(),isSatisfiedBy:A.always,metadata:this.#o(n),moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:d.ResolvedValue};return this.#t(i),new L(i)}toFactory(e){const n={cache:{isRight:false,value:void 0},factory:e,id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:u.Singleton,serviceIdentifier:this.#s,type:d.Factory};return this.#t(n),new E(n)}toProvider(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,provider:e,scope:u.Singleton,serviceIdentifier:this.#s,type:d.Provider};return this.#t(n),new E(n)}toService(e){const n={id:c(),isSatisfiedBy:A.always,moduleId:this.#r,serviceIdentifier:this.#s,targetServiceIdentifier:e,type:d.ServiceRedirection};this.#t(n);}#o(e){return {arguments:(e??[]).map((e=>function(e){return "object"==typeof e&&!r.is(e)}(e)?{kind:true===e.isMultiple?ue.multipleInjection:ue.singleInjection,name:e.name,optional:e.optional??false,tags:new Map((e.tags??[]).map((e=>[e.key,e.value]))),value:e.serviceIdentifier}:{kind:ue.singleInjection,name:void 0,optional:false,tags:new Map,value:e}))}}}class T{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}onActivation(e){return this.#i.onActivation=e,new V(this.#i)}onDeactivation(e){return this.#i.onDeactivation=e,new V(this.#i)}}class V{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}when(e){return this.#i.isSatisfiedBy=e,new T(this.#i)}whenAnyAncestor(e){return this.when(C(e))}whenAnyAncestorIs(e){return this.when(C(x(e)))}whenAnyAncestorNamed(e){return this.when(function(e){return C(B(e))}(e))}whenAnyAncestorTagged(e,n){return this.when(function(e,n){return C(O(e,n))}(e,n))}whenDefault(){return this.when(N)}whenNamed(e){return this.when(B(e))}whenNoParent(e){return this.when(F(e))}whenNoParentIs(e){return this.when(F(x(e)))}whenNoParentNamed(e){return this.when(function(e){return F(B(e))}(e))}whenNoParentTagged(e,n){return this.when(function(e,n){return F(O(e,n))}(e,n))}whenParent(e){return this.when(k(e))}whenParentIs(e){return this.when(k(x(e)))}whenParentNamed(e){return this.when(function(e){return k(B(e))}(e))}whenParentTagged(e,n){return this.when(function(e,n){return k(O(e,n))}(e,n))}whenTagged(e,n){return this.when(O(e,n))}whenNoAncestor(e){return this.when(U(e))}whenNoAncestorIs(e){return this.when(U(x(e)))}whenNoAncestorNamed(e){return this.when(function(e){return U(B(e))}(e))}whenNoAncestorTagged(e,n){return this.when(function(e,n){return U(O(e,n))}(e,n))}}class E extends V{#c;constructor(e){super(e),this.#c=new T(e);}onActivation(e){return this.#c.onActivation(e)}onDeactivation(e){return this.#c.onDeactivation(e)}}class L extends E{#d;constructor(e){super(e),this.#d=new j(e);}inRequestScope(){return this.#d.inRequestScope()}inSingletonScope(){return this.#d.inSingletonScope()}inTransientScope(){return this.#d.inTransientScope()}}const q=Symbol.for("@inversifyjs/container/InversifyContainerError");class $ extends Error{[q];kind;constructor(e,n,i){super(n,i),this[q]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[q]}static isErrorOfKind(e,n){return $.is(e)&&e.kind===n}}var G;!function(e){e[e.invalidOperation=0]="invalidOperation";}(G||(G={}));class H{#l;#a;#u;constructor(e,n,i){this.#l=e,this.#a=n,this.#u=i;}bind(e){return new D((e=>{this.#h(e);}),void 0,this.#a,e)}isBound(e,n){const i=this.#u.bindingService.get(e);return this.#v(e,i,n)}isCurrentBound(e,n){const i=this.#u.bindingService.getNonParentBindings(e);return this.#v(e,i,n)}async rebind(e){return await this.unbind(e),this.bind(e)}rebindSync(e){return this.unbindSync(e),this.bind(e)}async unbind(e){await this.#g(e);}async unbindAll(){const e=[...this.#u.bindingService.getNonParentBoundServices()];await Promise.all(e.map((async e=>pt(this.#l,e))));for(const n of e)this.#u.activationService.removeAllByServiceId(n),this.#u.bindingService.removeAllByServiceId(n),this.#u.deactivationService.removeAllByServiceId(n);this.#u.planResultCacheService.clearCache();}unbindSync(e){ void 0!==this.#g(e)&&this.#f(e);}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}#f(e){let n;if(I(e)){const t=this.#u.bindingService.getById(e.id),r=(i=t,function(e){if(void 0===e)return;const n=e.next();return true!==n.done?n.value:void 0}(i?.[Symbol.iterator]()))?.serviceIdentifier;n=void 0===r?"Unexpected asynchronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asynchronous deactivation when unbinding "${t$2(r)}" binding. Consider using Container.unbind() instead.`;}else n=`Unexpected asynchronous deactivation when unbinding "${t$2(e)}" service. Consider using Container.unbind() instead.`;var i;throw new $(G.invalidOperation,n)}#g(e){return I(e)?this.#b(e):this.#p(e)}#b(e){const n=this.#u.bindingService.getById(e.id),i=dt(this.#l,n);if(void 0!==i)return i.then((()=>{this.#S(e);}));this.#S(e);}#S(e){this.#u.bindingService.removeById(e.id),this.#u.planResultCacheService.clearCache();}#p(e){const n=pt(this.#l,e);if(void 0!==n)return n.then((()=>{this.#M(e);}));this.#M(e);}#M(e){this.#u.activationService.removeAllByServiceId(e),this.#u.bindingService.removeAllByServiceId(e),this.#u.deactivationService.removeAllByServiceId(e),this.#u.planResultCacheService.clearCache();}#v(e,n,i){if(void 0===n)return false;const t={getAncestor:()=>{},name:i?.name,serviceIdentifier:e,tags:new Map};void 0!==i?.tag&&t.tags.set(i.tag.key,i.tag.value);for(const e of n)if(e.isSatisfiedBy(t))return true;return false}}class _{#y;#l;#a;#u;constructor(e,n,i,t){this.#y=e,this.#l=n,this.#a=i,this.#u=t;}async load(...e){await Promise.all(this.#n(...e));}loadSync(...e){const n=this.#n(...e);for(const e of n)if(void 0!==e)throw new $(G.invalidOperation,"Unexpected asynchronous module load. Consider using Container.load() instead.")}async unload(...e){await Promise.all(this.#R(...e)),this.#w(e);}unloadSync(...e){const n=this.#R(...e);for(const e of n)if(void 0!==e)throw new $(G.invalidOperation,"Unexpected asynchronous module unload. Consider using Container.unload() instead.");this.#w(e);}#m(e){return {bind:n=>new D((e=>{this.#h(e);}),e,this.#a,n),isBound:this.#y.isBound.bind(this.#y),onActivation:(n,i)=>{this.#u.activationService.add(i,{moduleId:e,serviceId:n});},onDeactivation:(n,i)=>{this.#u.deactivationService.add(i,{moduleId:e,serviceId:n});},rebind:this.#y.rebind.bind(this.#y),rebindSync:this.#y.rebindSync.bind(this.#y),unbind:this.#y.unbind.bind(this.#y),unbindSync:this.#y.unbindSync.bind(this.#y)}}#w(e){for(const n of e)this.#u.activationService.removeAllByModuleId(n.id),this.#u.bindingService.removeAllByModuleId(n.id),this.#u.deactivationService.removeAllByModuleId(n.id);this.#u.planResultCacheService.clearCache();}#n(...e){return e.map((e=>e.load(this.#m(e.id))))}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}#R(...e){return e.map((e=>lt(this.#l,e.id)))}}class z{#I;#A;#P;#u;constructor(e,n,i){this.#u=n,this.#P=i,this.#I=this.#C(e),this.#A=this.#B();}register(e,n){const i=new n(e,this.#A);if(true!==i[t])throw new $(G.invalidOperation,"Invalid plugin. The plugin must extend the Plugin class");i.load(this.#I);}#C(e){return {define:(n,i)=>{if(Object.prototype.hasOwnProperty.call(e,n))throw new $(G.invalidOperation,`Container already has a method named "${String(n)}"`);e[n]=i;},onPlan:this.#P.onPlan.bind(this.#P)}}#B(){const e=this.#u;return {get activationService(){return e.activationService},get bindingService(){return e.bindingService},get deactivationService(){return e.deactivationService},get planResultCacheService(){return e.planResultCacheService}}}}class K{activationService;bindingService;deactivationService;planResultCacheService;#x;constructor(e,n,i,t){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService=t,this.#x=[];}reset(e,n,i){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService.clearCache();for(const e of this.#x)e();}onReset(e){this.#x.push(e);}}class X{#O;#a;#N;#U;#F;#k;#u;#j;constructor(e,n,i){this.#u=e,this.#F=this.#D(),this.#O=n,this.#a=i,this.#N=e=>this.#u.activationService.get(e),this.#U=this.#u.bindingService.get.bind(this.#u.bindingService),this.#k=[],this.#j=this.#h.bind(this),this.#u.onReset((()=>{this.#T();}));}get(e$1,n){const i=this.#V(false,e$1,n),t=this.#E(i);if(e(t))throw new $(G.invalidOperation,`Unexpected asynchronous service when resolving service "${t$2(e$1)}"`);return t}getAll(e$1,n){const i=this.#V(true,e$1,n),t=this.#E(i);if(e(t))throw new $(G.invalidOperation,`Unexpected asynchronous service when resolving service "${t$2(e$1)}"`);return t}async getAllAsync(e,n){const i=this.#V(true,e,n);return this.#E(i)}async getAsync(e,n){const i=this.#V(false,e,n);return this.#E(i)}onPlan(e){this.#k.push(e);}#T(){this.#U=this.#u.bindingService.get.bind(this.#u.bindingService),this.#j=this.#h.bind(this),this.#F=this.#D();}#L(e,n,i){return {isMultiple:e,name:i?.name,optional:i?.optional,serviceIdentifier:n,tag:i?.tag}}#q(e,n,i){const r={autobindOptions:i?.autobind??this.#O?{scope:this.#a}:void 0,getBindings:this.#U,getClassMetadata:x$1,rootConstraints:{isMultiple:n,serviceIdentifier:e},servicesBranch:[],setBinding:this.#j};return this.#$(r,i),r}#V(e,n,i){const t=this.#L(e,n,i),r=this.#u.planResultCacheService.get(t);if(void 0!==r)return r;const a=we(this.#q(n,e,i));this.#u.planResultCacheService.set(t,a);for(const e of this.#k)e(t,a);return a}#D(){return {get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#E(e){return et({context:this.#F,getActivations:this.#N,planResult:e,requestScopeCache:new Map})}#$(e,n){ void 0!==n&&(void 0!==n.name&&(e.rootConstraints.name=n.name),true===n.optional&&(e.rootConstraints.isOptional=true),void 0!==n.tag&&(e.rootConstraints.tag={key:n.tag.key,value:n.tag.value}));}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}}class J{#u;#G;constructor(e){this.#u=e,this.#G=[];}restore(){const e=this.#G.pop();if(void 0===e)throw new $(G.invalidOperation,"No snapshot available to restore");this.#u.reset(e.activationService,e.bindingService,e.deactivationService);}snapshot(){this.#G.push({activationService:this.#u.activationService.clone(),bindingService:this.#u.bindingService.clone(),deactivationService:this.#u.deactivationService.clone()});}}const Q=u.Transient;class W{#y;#H;#_;#u;#P;#z;constructor(e){this.#u=this.#K(e);const n=e?.autobind??false,i=e?.defaultScope??Q,r={getBindings:(a=this.#u).bindingService.get.bind(a.bindingService),getBindingsFromModule:a.bindingService.getByModuleId.bind(a.bindingService),getClassMetadata:x$1,getDeactivations:a.deactivationService.get.bind(a.deactivationService)};var a;this.#y=new H(r,i,this.#u),this.#H=new _(this.#y,r,i,this.#u),this.#P=new X(this.#u,n,i),this.#_=new z(this,this.#u,this.#P),this.#z=new J(this.#u);}bind(e){return this.#y.bind(e)}get(e,n){return this.#P.get(e,n)}getAll(e,n){return this.#P.getAll(e,n)}async getAllAsync(e,n){return this.#P.getAllAsync(e,n)}async getAsync(e,n){return this.#P.getAsync(e,n)}isBound(e,n){return this.#y.isBound(e,n)}isCurrentBound(e,n){return this.#y.isCurrentBound(e,n)}async load(...e){return this.#H.load(...e)}loadSync(...e){this.#H.loadSync(...e);}onActivation(e,n){this.#u.activationService.add(n,{serviceId:e});}onDeactivation(e,n){this.#u.deactivationService.add(n,{serviceId:e});}register(e){this.#_.register(this,e);}restore(){this.#z.restore();}async rebind(e){return this.#y.rebind(e)}rebindSync(e){return this.#y.rebindSync(e)}snapshot(){this.#z.snapshot();}async unbind(e){await this.#y.unbind(e);}async unbindAll(){return this.#y.unbindAll()}unbindSync(e){this.#y.unbindSync(e);}async unload(...e){return this.#H.unload(...e)}unloadSync(...e){this.#H.unloadSync(...e);}#K(e){if(void 0===e?.parent)return new K(m$1.build(void 0),I$1.build(void 0),w.build(void 0),new xe);const n=new xe;return e.parent.#u.planResultCacheService.subscribe(n),new K(m$1.build(e.parent.#u.activationService),I$1.build(e.parent.#u.bindingService),w.build(e.parent.#u.deactivationService),n)}}
10
-
11
- const METADATA_KEY = {
12
- PARAM_TYPES: "design:paramtypes",
13
- TYPE: "design:type",
14
- RETURN_TYPE: "design:returntype"
15
- };
16
- const container = new W({
17
- defaultScope: "Singleton"
18
- });
19
- const bind = (id, cls) => container.bind(id).to(cls).inSingletonScope();
20
- const resolve = (id) => container.get(id);
21
- function isInjectable(target) {
22
- return !!Reflect.getMetadata(METADATA_KEY.PARAM_TYPES, target);
23
- }
24
-
25
- class MiddlewareRegistryClass {
26
- constructor() {
27
- this.global = [];
28
- this.perHandler = /* @__PURE__ */ new Map();
29
- }
30
- registerGlobal(fn) {
31
- this.global.push(fn);
32
- }
33
- registerForKey(key, fn) {
34
- const arr = this.perHandler.get(key) ?? [];
35
- arr.push(fn);
36
- this.perHandler.set(key, arr);
37
- }
38
- pipeline(key) {
39
- return [...this.global, ...this.perHandler.get(key) ?? []];
40
- }
41
- }
42
- const MiddlewareRegistry = new MiddlewareRegistryClass();
43
-
44
- const DEFAULT_PORT_NAME = "chroma-bridge";
45
-
46
- class DefaultErrorHandler {
47
- handle(error, context) {
48
- console.error("Error in bridge handler:", error);
49
- return {
50
- id: context.request.id,
51
- error: error?.message ?? "UNKNOWN_ERROR",
52
- timestamp: Date.now()
53
- };
54
- }
55
- }
56
- const _BridgeRuntimeManager = class _BridgeRuntimeManager {
57
- constructor(options) {
58
- this.keepAliveTimer = null;
59
- this.isInitialized = false;
60
- this.container = options.container;
61
- this.portName = options.portName ?? DEFAULT_PORT_NAME;
62
- this.enableLogging = options.enableLogging ?? true;
63
- this.errorHandler = options.errorHandler ?? new DefaultErrorHandler();
64
- this.logger = new BridgeLogger(this.enableLogging);
65
- this.keepAlive = options.keepAlive ?? false;
66
- }
67
- /**
68
- * Initialize the bridge runtime and start listening for connections
69
- */
70
- initialize() {
71
- if (this.isInitialized) {
72
- this.logger.warn("Bridge runtime already initialized");
73
- return;
74
- }
75
- this.setupPortListener();
76
- if (this.keepAlive) {
77
- this.startKeepAlive();
78
- }
79
- this.isInitialized = true;
80
- this.logger.success(`\u{1F309} Bridge runtime initialized on port: ${this.portName}`);
81
- }
82
- /**
83
- * Setup Chrome runtime port listener
84
- */
85
- setupPortListener() {
86
- chrome.runtime.onConnect.addListener((port) => {
87
- try {
88
- if (!this.isValidPort(port)) {
89
- return;
90
- }
91
- this.logger.info(`\u{1F4E1} Port connected: ${port.name}`);
92
- this.setupMessageHandler(port);
93
- if (chrome.runtime.lastError) {
94
- this.logger.warn(`Runtime error during port setup: ${chrome.runtime.lastError.message}`);
95
- chrome.runtime.lastError;
96
- }
97
- } catch (error) {
98
- this.logger.error("Error setting up port listener:", error);
99
- if (chrome.runtime.lastError) {
100
- this.logger.warn(`Additional runtime error: ${chrome.runtime.lastError.message}`);
101
- chrome.runtime.lastError;
102
- }
103
- }
104
- });
105
- }
106
- /**
107
- * Validate incoming port connection
108
- */
109
- isValidPort(port) {
110
- if (port.name !== this.portName) {
111
- this.logger.warn(`Ignoring port "${port.name}", expected "${this.portName}"`);
112
- return false;
113
- }
114
- const senderId = port.sender?.id;
115
- if (senderId !== chrome.runtime.id) {
116
- this.logger.warn(
117
- `Ignoring port from different extension (senderId: ${senderId}, expected: ${chrome.runtime.id})`
118
- );
119
- return false;
120
- }
121
- return true;
122
- }
123
- /**
124
- * Setup message handler for connected port
125
- */
126
- setupMessageHandler(port) {
127
- port.onMessage.addListener(async (request) => {
128
- const context = this.createPipelineContext(request);
129
- try {
130
- this.logger.debug("\u{1F4E8} Received message:", {
131
- key: request.key,
132
- id: request.id,
133
- hasPayload: !!request.payload
134
- });
135
- const response = await this.processMessage(context);
136
- this.sendResponse(port, response);
137
- } catch (error) {
138
- const errorResponse = await this.handleError(error, context);
139
- this.sendResponse(port, errorResponse);
140
- }
141
- });
142
- port.onDisconnect.addListener(() => {
143
- if (chrome.runtime.lastError) {
144
- this.logger.warn(`\u{1F4F4} Port disconnected with error: ${chrome.runtime.lastError.message}`);
145
- chrome.runtime.lastError;
146
- } else {
147
- this.logger.info(`\u{1F4F4} Port disconnected: ${port.name}`);
148
- }
149
- });
150
- }
151
- /**
152
- * Create pipeline context for request processing
153
- */
154
- createPipelineContext(request) {
155
- return {
156
- request,
157
- startTime: Date.now(),
158
- metadata: { ...request.metadata }
159
- };
160
- }
161
- /**
162
- * Process message through middleware pipeline and handler
163
- */
164
- async processMessage(context) {
165
- const { request } = context;
166
- const handler = this.resolveHandler(request.key);
167
- const middlewares = MiddlewareRegistry.pipeline(request.key);
168
- const data = await this.runPipeline(
169
- middlewares,
170
- context,
171
- () => handler.handle(request.payload)
172
- );
173
- return {
174
- id: request.id,
175
- data,
176
- timestamp: Date.now()
177
- };
178
- }
179
- /**
180
- * Resolve message handler from dependency injection container
181
- */
182
- resolveHandler(key) {
183
- try {
184
- const handler = this.container.get(key);
185
- if (!handler || typeof handler.handle !== "function") {
186
- throw new Error(`Handler "${key}" does not implement MessageHandler interface`);
187
- }
188
- return handler;
189
- } catch (error) {
190
- throw new Error(`Failed to resolve handler "${key}": ${error.message}`);
191
- }
192
- }
193
- /**
194
- * Execute middleware pipeline with proper error handling
195
- */
196
- async runPipeline(middlewares, context, finalHandler) {
197
- let currentIndex = -1;
198
- const executeNext = async () => {
199
- currentIndex++;
200
- if (currentIndex === middlewares.length) {
201
- return finalHandler();
202
- }
203
- if (currentIndex > middlewares.length) {
204
- throw new Error("next() called multiple times");
205
- }
206
- const middleware = middlewares[currentIndex];
207
- return middleware(context, executeNext);
208
- };
209
- return executeNext();
210
- }
211
- /**
212
- * Handle errors during message processing
213
- */
214
- async handleError(error, context) {
215
- const duration = Date.now() - context.startTime;
216
- this.logger.error(`\u{1F4A5} Message processing failed after ${duration}ms:`, {
217
- key: context.request.key,
218
- id: context.request.id,
219
- error: error.message
220
- });
221
- return this.errorHandler.handle(error, context);
222
- }
223
- /**
224
- * Send response back through the port
225
- */
226
- sendResponse(port, response) {
227
- try {
228
- if (!port) {
229
- this.logger.warn(`Cannot send response: port is null (ID: ${response.id})`);
230
- return;
231
- }
232
- port.postMessage(response);
233
- if (chrome.runtime.lastError) {
234
- this.logger.warn(
235
- `Chrome runtime error during postMessage: ${chrome.runtime.lastError.message} (ID: ${response.id})`
236
- );
237
- chrome.runtime.lastError;
238
- return;
239
- }
240
- this.logger.debug("\u{1F4E4} Response sent:", {
241
- id: response.id,
242
- hasData: !!response.data,
243
- hasError: !!response.error,
244
- data: response.data
245
- });
246
- } catch (error) {
247
- this.logger.error("Failed to send response:", error);
248
- if (chrome.runtime.lastError) {
249
- this.logger.warn(`Additional Chrome runtime error: ${chrome.runtime.lastError.message}`);
250
- chrome.runtime.lastError;
251
- }
252
- }
253
- }
254
- /**
255
- * Get runtime statistics
256
- */
257
- getStats() {
258
- return {
259
- portName: this.portName,
260
- initialized: this.isInitialized
261
- };
262
- }
263
- /**
264
- * Start keep-alive timer to keep service worker alive
265
- */
266
- startKeepAlive() {
267
- if (this.keepAliveTimer) return;
268
- this.logger.info("Starting keep-alive timer to keep service worker alive");
269
- this.keepAliveTimer = setInterval(() => {
270
- chrome.runtime.getPlatformInfo(() => {
271
- });
272
- }, _BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS);
273
- }
274
- /**
275
- * Stop keep-alive timer
276
- */
277
- stopKeepAlive() {
278
- if (this.keepAliveTimer) {
279
- clearInterval(this.keepAliveTimer);
280
- this.keepAliveTimer = null;
281
- this.logger.info("Stopped keep-alive timer");
282
- }
283
- }
284
- };
285
- _BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS = 25e3;
286
- let BridgeRuntimeManager = _BridgeRuntimeManager;
287
- class BridgeLogger {
288
- constructor(enabled = true) {
289
- this.enabled = enabled;
290
- }
291
- info(message, context) {
292
- if (!this.enabled) return;
293
- console.log(`[Bridge] ${message}`);
294
- if (context) console.log(" Context:", context);
295
- }
296
- success(message) {
297
- if (!this.enabled) return;
298
- console.log(`[Bridge] ${message}`);
299
- }
300
- warn(message) {
301
- if (!this.enabled) return;
302
- console.warn(`[Bridge] ${message}`);
303
- }
304
- error(message, error) {
305
- if (!this.enabled) return;
306
- console.error(`[Bridge] ${message}`);
307
- if (error) console.error(" Error:", error);
308
- }
309
- debug(message, context) {
310
- if (!this.enabled) return;
311
- console.debug(`[Bridge] ${message}`);
312
- if (context) console.debug(" Context:", context);
313
- }
314
- }
315
- function bootstrap$1(options) {
316
- const runtime = new BridgeRuntimeManager(options);
317
- console.debug("\u{1F309} Initializing Bridge Runtime with options:", options);
318
- runtime.initialize();
319
- }
320
-
321
- class AlarmAdapter {
322
- constructor() {
323
- this.callbacks = /* @__PURE__ */ new Map();
324
- }
325
- onTrigger(callback) {
326
- this.triggerCallback = callback;
327
- }
328
- schedule(id, when) {
329
- const delay = Math.max(0, when - Date.now());
330
- const timeoutId = setTimeout(() => {
331
- this.callbacks.delete(id);
332
- this.triggerCallback?.(id);
333
- }, delay);
334
- this.callbacks.set(id, () => clearTimeout(timeoutId));
335
- return timeoutId;
336
- }
337
- cancel(id) {
338
- const callback = this.callbacks.get(id);
339
- if (callback) {
340
- callback();
341
- this.callbacks.delete(id);
342
- }
343
- }
344
- }
345
-
346
- class TimeoutAdapter {
347
- constructor() {
348
- this.callbacks = /* @__PURE__ */ new Map();
349
- }
350
- onTrigger(callback) {
351
- this.triggerCallback = callback;
352
- }
353
- schedule(id, when) {
354
- const delay = Math.max(0, when - Date.now());
355
- const timeoutId = setTimeout(() => {
356
- this.callbacks.delete(id);
357
- this.triggerCallback?.(id);
358
- }, delay);
359
- this.callbacks.set(id, () => clearTimeout(timeoutId));
360
- return timeoutId;
361
- }
362
- cancel(id) {
363
- const callback = this.callbacks.get(id);
364
- if (callback) {
365
- callback();
366
- this.callbacks.delete(id);
367
- }
368
- }
369
- }
370
-
371
- var JobState = /* @__PURE__ */ ((JobState2) => {
372
- JobState2["SCHEDULED"] = "scheduled";
373
- JobState2["RUNNING"] = "running";
374
- JobState2["PAUSED"] = "paused";
375
- JobState2["STOPPED"] = "stopped";
376
- JobState2["COMPLETED"] = "completed";
377
- JobState2["FAILED"] = "failed";
378
- return JobState2;
379
- })(JobState || {});
380
-
381
- const _JobRegistry = class _JobRegistry {
382
- constructor() {
383
- this.jobs = /* @__PURE__ */ new Map();
384
- }
385
- register(id, job, options) {
386
- const context = this.createJobContext(id, options);
387
- this.jobs.set(id, {
388
- job,
389
- context,
390
- options
391
- });
392
- }
393
- resolve(id) {
394
- const entry = this.jobs.get(id);
395
- return entry?.job;
396
- }
397
- meta(id) {
398
- const entry = this.jobs.get(id);
399
- return entry?.options;
400
- }
401
- getContext(id) {
402
- const entry = this.jobs.get(id);
403
- return entry?.context;
404
- }
405
- updateState(id, state) {
406
- const entry = this.jobs.get(id);
407
- if (entry) {
408
- entry.context.state = state;
409
- entry.context.updatedAt = /* @__PURE__ */ new Date();
410
- switch (state) {
411
- case JobState.RUNNING:
412
- entry.context.startedAt = /* @__PURE__ */ new Date();
413
- break;
414
- case JobState.PAUSED:
415
- entry.context.pausedAt = /* @__PURE__ */ new Date();
416
- break;
417
- case JobState.STOPPED:
418
- entry.context.stoppedAt = /* @__PURE__ */ new Date();
419
- break;
420
- case JobState.COMPLETED:
421
- entry.context.completedAt = /* @__PURE__ */ new Date();
422
- break;
423
- }
424
- }
425
- }
426
- setTimeoutId(id, timeoutId) {
427
- const entry = this.jobs.get(id);
428
- if (entry) {
429
- entry.timeoutId = timeoutId;
430
- }
431
- }
432
- setIntervalId(id, intervalId) {
433
- const entry = this.jobs.get(id);
434
- if (entry) {
435
- entry.intervalId = intervalId;
436
- }
437
- }
438
- clearTimers(id) {
439
- const entry = this.jobs.get(id);
440
- if (entry) {
441
- if (entry.timeoutId) {
442
- clearTimeout(entry.timeoutId);
443
- entry.timeoutId = void 0;
444
- }
445
- if (entry.intervalId) {
446
- clearInterval(entry.intervalId);
447
- entry.intervalId = void 0;
448
- }
449
- }
450
- }
451
- pause(id) {
452
- const entry = this.jobs.get(id);
453
- console.log(`Pausing job ${id}`);
454
- if (entry && entry.context.state === JobState.RUNNING) {
455
- console.log(`paused job ${id}`);
456
- this.updateState(id, JobState.PAUSED);
457
- this.clearTimers(id);
458
- entry.job.pause?.();
459
- }
460
- }
461
- resume(id) {
462
- const entry = this.jobs.get(id);
463
- console.log(`Resuming job ${id}`);
464
- if (entry && entry.context.state === JobState.PAUSED) {
465
- console.log(`Resuming job ${id}`);
466
- this.updateState(id, JobState.SCHEDULED);
467
- entry.job.resume?.();
468
- }
469
- }
470
- stop(id) {
471
- const entry = this.jobs.get(id);
472
- if (entry && entry.context.state !== JobState.STOPPED) {
473
- console.log(`Stopping job ${id}`);
474
- this.updateState(id, JobState.STOPPED);
475
- this.clearTimers(id);
476
- entry.job.stop?.();
477
- }
478
- }
479
- createJobContext(id, options) {
480
- const now = /* @__PURE__ */ new Date();
481
- return {
482
- id,
483
- options,
484
- state: JobState.SCHEDULED,
485
- createdAt: now,
486
- updatedAt: now,
487
- retryCount: 0,
488
- pause: () => this.pause(id),
489
- resume: () => this.resume(id),
490
- stop: () => this.stop(id),
491
- complete: () => this.updateState(id, JobState.COMPLETED),
492
- fail: (error) => {
493
- this.updateState(id, JobState.FAILED);
494
- const entry = this.jobs.get(id);
495
- if (entry) entry.context.error = error;
496
- },
497
- retry: () => {
498
- const entry = this.jobs.get(id);
499
- if (entry) {
500
- entry.context.retryCount = (entry.context.retryCount || 0) + 1;
501
- this.updateState(id, JobState.SCHEDULED);
502
- }
503
- },
504
- isRunning: () => this.getContext(id)?.state === JobState.RUNNING,
505
- isPaused: () => this.getContext(id)?.state === JobState.PAUSED,
506
- isStopped: () => this.getContext(id)?.state === JobState.STOPPED,
507
- isCompleted: () => this.getContext(id)?.state === JobState.COMPLETED,
508
- isFailed: () => this.getContext(id)?.state === JobState.FAILED,
509
- isRetrying: () => (this.getContext(id)?.retryCount || 0) > 0,
510
- isScheduled: () => this.getContext(id)?.state === JobState.SCHEDULED,
511
- isDelayed: () => !!options.delay,
512
- isRecurring: () => !!options.cron,
513
- isCron: () => !!options.cron,
514
- isTimeout: () => !!options.delay && !options.cron,
515
- isAlarm: () => !!options.cron || !!options.delay && options.delay > 6e4
516
- };
517
- }
518
- };
519
- _JobRegistry.instance = new _JobRegistry();
520
- let JobRegistry = _JobRegistry;
521
-
522
- /* Extracts second, minute, hour, date, month and the weekday from a date. */
523
- function extractDateElements(date) {
524
- return {
525
- second: date.getSeconds(),
526
- minute: date.getMinutes(),
527
- hour: date.getHours(),
528
- day: date.getDate(),
529
- month: date.getMonth(),
530
- weekday: date.getDay(),
531
- year: date.getFullYear(),
532
- };
533
- }
534
- /* Gets the amount of days in the given month (indexed by 0) of the given year. */
535
- function getDaysInMonth(year, month) {
536
- return new Date(year, month + 1, 0).getDate();
537
- }
538
- /* Gets the amount of days from weekday1 to weekday2. */
539
- function getDaysBetweenWeekdays(weekday1, weekday2) {
540
- if (weekday1 <= weekday2) {
541
- return weekday2 - weekday1;
542
- }
543
- return 6 - weekday1 + weekday2 + 1;
544
- }
545
-
546
- class Cron {
547
- constructor({ seconds, minutes, hours, days, months, weekdays, }) {
548
- // Validate that there are values provided.
549
- if (!seconds || seconds.size === 0)
550
- throw new Error('There must be at least one allowed second.');
551
- if (!minutes || minutes.size === 0)
552
- throw new Error('There must be at least one allowed minute.');
553
- if (!hours || hours.size === 0)
554
- throw new Error('There must be at least one allowed hour.');
555
- if (!months || months.size === 0)
556
- throw new Error('There must be at least one allowed month.');
557
- if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))
558
- throw new Error('There must be at least one allowed day or weekday.');
559
- // Convert set to array and sort in ascending order.
560
- this.seconds = Array.from(seconds).sort((a, b) => a - b);
561
- this.minutes = Array.from(minutes).sort((a, b) => a - b);
562
- this.hours = Array.from(hours).sort((a, b) => a - b);
563
- this.days = Array.from(days).sort((a, b) => a - b);
564
- this.months = Array.from(months).sort((a, b) => a - b);
565
- this.weekdays = Array.from(weekdays).sort((a, b) => a - b);
566
- // Validate that all values are integers within the constraint.
567
- const validateData = (name, data, constraint) => {
568
- if (data.some((x) => typeof x !== 'number' ||
569
- x % 1 !== 0 ||
570
- x < constraint.min ||
571
- x > constraint.max)) {
572
- throw new Error(`${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`);
573
- }
574
- };
575
- validateData('seconds', this.seconds, { min: 0, max: 59 });
576
- validateData('minutes', this.minutes, { min: 0, max: 59 });
577
- validateData('hours', this.hours, { min: 0, max: 23 });
578
- validateData('days', this.days, { min: 1, max: 31 });
579
- validateData('months', this.months, { min: 0, max: 11 });
580
- validateData('weekdays', this.weekdays, { min: 0, max: 6 });
581
- // For each element, store a reversed copy in the reversed attribute for finding prev dates.
582
- this.reversed = {
583
- seconds: this.seconds.map((x) => x).reverse(),
584
- minutes: this.minutes.map((x) => x).reverse(),
585
- hours: this.hours.map((x) => x).reverse(),
586
- days: this.days.map((x) => x).reverse(),
587
- months: this.months.map((x) => x).reverse(),
588
- weekdays: this.weekdays.map((x) => x).reverse(),
589
- };
590
- }
591
- /**
592
- * Find the next or previous hour, starting from the given start hour that matches the hour constraint.
593
- * startHour itself might also be allowed.
594
- */
595
- findAllowedHour(dir, startHour) {
596
- return dir === 'next'
597
- ? this.hours.find((x) => x >= startHour)
598
- : this.reversed.hours.find((x) => x <= startHour);
599
- }
600
- /**
601
- * Find the next or previous minute, starting from the given start minute that matches the minute constraint.
602
- * startMinute itself might also be allowed.
603
- */
604
- findAllowedMinute(dir, startMinute) {
605
- return dir === 'next'
606
- ? this.minutes.find((x) => x >= startMinute)
607
- : this.reversed.minutes.find((x) => x <= startMinute);
608
- }
609
- /**
610
- * Find the next or previous second, starting from the given start second that matches the second constraint.
611
- * startSecond itself IS NOT allowed.
612
- */
613
- findAllowedSecond(dir, startSecond) {
614
- return dir === 'next'
615
- ? this.seconds.find((x) => x > startSecond)
616
- : this.reversed.seconds.find((x) => x < startSecond);
617
- }
618
- /**
619
- * Find the next or previous time, starting from the given start time that matches the hour, minute
620
- * and second constraints. startTime itself might also be allowed.
621
- */
622
- findAllowedTime(dir, startTime) {
623
- // Try to find an allowed hour.
624
- let hour = this.findAllowedHour(dir, startTime.hour);
625
- if (hour !== undefined) {
626
- if (hour === startTime.hour) {
627
- // We found an hour that is the start hour. Try to find an allowed minute.
628
- let minute = this.findAllowedMinute(dir, startTime.minute);
629
- if (minute !== undefined) {
630
- if (minute === startTime.minute) {
631
- // We found a minute that is the start minute. Try to find an allowed second.
632
- const second = this.findAllowedSecond(dir, startTime.second);
633
- if (second !== undefined) {
634
- // We found a second within the start hour and minute.
635
- return { hour, minute, second };
636
- }
637
- // We did not find a valid second within the start minute. Try to find another minute.
638
- minute = this.findAllowedMinute(dir, dir === 'next' ? startTime.minute + 1 : startTime.minute - 1);
639
- if (minute !== undefined) {
640
- // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
641
- return {
642
- hour,
643
- minute,
644
- second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
645
- };
646
- }
647
- }
648
- else {
649
- // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
650
- return {
651
- hour,
652
- minute,
653
- second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
654
- };
655
- }
656
- }
657
- // We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.
658
- hour = this.findAllowedHour(dir, dir === 'next' ? startTime.hour + 1 : startTime.hour - 1);
659
- if (hour !== undefined) {
660
- // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
661
- return {
662
- hour,
663
- minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
664
- second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
665
- };
666
- }
667
- }
668
- else {
669
- // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
670
- return {
671
- hour,
672
- minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
673
- second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
674
- };
675
- }
676
- }
677
- // No allowed time found.
678
- return undefined;
679
- }
680
- /**
681
- * Find the next or previous day in the given month, starting from the given startDay
682
- * that matches either the day or the weekday constraint. startDay itself might also be allowed.
683
- */
684
- findAllowedDayInMonth(dir, year, month, startDay) {
685
- var _a, _b;
686
- if (startDay < 1)
687
- throw new Error('startDay must not be smaller than 1.');
688
- // If only days are restricted: allow day based on day constraint only.
689
- // If only weekdays are restricted: allow day based on weekday constraint only.
690
- // If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.
691
- // If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).
692
- const daysInMonth = getDaysInMonth(year, month);
693
- const daysRestricted = this.days.length !== 31;
694
- const weekdaysRestricted = this.weekdays.length !== 7;
695
- if (!daysRestricted && !weekdaysRestricted) {
696
- if (startDay > daysInMonth) {
697
- return dir === 'next' ? undefined : daysInMonth;
698
- }
699
- return startDay;
700
- }
701
- // Try to find a day based on the days constraint.
702
- let allowedDayByDays;
703
- if (daysRestricted) {
704
- allowedDayByDays =
705
- dir === 'next'
706
- ? this.days.find((x) => x >= startDay)
707
- : this.reversed.days.find((x) => x <= startDay);
708
- // Make sure the day does not exceed the amount of days in month.
709
- if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {
710
- allowedDayByDays = undefined;
711
- }
712
- }
713
- // Try to find a day based on the weekday constraint.
714
- let allowedDayByWeekdays;
715
- if (weekdaysRestricted) {
716
- const startWeekday = new Date(year, month, startDay).getDay();
717
- const nearestAllowedWeekday = dir === 'next'
718
- ? (_a = this.weekdays.find((x) => x >= startWeekday)) !== null && _a !== void 0 ? _a : this.weekdays[0]
719
- : (_b = this.reversed.weekdays.find((x) => x <= startWeekday)) !== null && _b !== void 0 ? _b : this.reversed.weekdays[0];
720
- if (nearestAllowedWeekday !== undefined) {
721
- const daysBetweenWeekdays = dir === 'next'
722
- ? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)
723
- : getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday);
724
- allowedDayByWeekdays =
725
- dir === 'next'
726
- ? startDay + daysBetweenWeekdays
727
- : startDay - daysBetweenWeekdays;
728
- // Make sure the day does not exceed the month boundaries.
729
- if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {
730
- allowedDayByWeekdays = undefined;
731
- }
732
- }
733
- }
734
- if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {
735
- // If a day is found both via the days and the weekdays constraint, pick the day
736
- // that is closer to start date.
737
- return dir === 'next'
738
- ? Math.min(allowedDayByDays, allowedDayByWeekdays)
739
- : Math.max(allowedDayByDays, allowedDayByWeekdays);
740
- }
741
- if (allowedDayByDays !== undefined) {
742
- return allowedDayByDays;
743
- }
744
- if (allowedDayByWeekdays !== undefined) {
745
- return allowedDayByWeekdays;
746
- }
747
- return undefined;
748
- }
749
- /** Gets the next date starting from the given start date or now. */
750
- getNextDate(startDate = new Date()) {
751
- const startDateElements = extractDateElements(startDate);
752
- let minYear = startDateElements.year;
753
- let startIndexMonth = this.months.findIndex((x) => x >= startDateElements.month);
754
- if (startIndexMonth === -1) {
755
- startIndexMonth = 0;
756
- minYear++;
757
- }
758
- // We try every month within the next 5 years to make sure that we tried to
759
- // find a matching date insidde a whole leap year.
760
- const maxIterations = this.months.length * 5;
761
- for (let i = 0; i < maxIterations; i++) {
762
- // Get the next year and month.
763
- const year = minYear + Math.floor((startIndexMonth + i) / this.months.length);
764
- const month = this.months[(startIndexMonth + i) % this.months.length];
765
- const isStartMonth = year === startDateElements.year && month === startDateElements.month;
766
- // Find the next day.
767
- let day = this.findAllowedDayInMonth('next', year, month, isStartMonth ? startDateElements.day : 1);
768
- let isStartDay = isStartMonth && day === startDateElements.day;
769
- // If we found a day and it is the start day, try to find a valid time beginning from the start date time.
770
- if (day !== undefined && isStartDay) {
771
- const nextTime = this.findAllowedTime('next', startDateElements);
772
- if (nextTime !== undefined) {
773
- return new Date(year, month, day, nextTime.hour, nextTime.minute, nextTime.second);
774
- }
775
- // If no valid time has been found for the start date, try the next day.
776
- day = this.findAllowedDayInMonth('next', year, month, day + 1);
777
- isStartDay = false;
778
- }
779
- // If we found a next day and it is not the start day, just use the next day with the first allowed values
780
- // for hours, minutes and seconds.
781
- if (day !== undefined && !isStartDay) {
782
- return new Date(year, month, day, this.hours[0], this.minutes[0], this.seconds[0]);
783
- }
784
- // No allowed day has been found for this month. Continue to search in next month.
785
- }
786
- throw new Error('No valid next date was found.');
787
- }
788
- /** Gets the specified amount of future dates starting from the given start date or now. */
789
- getNextDates(amount, startDate) {
790
- const dates = [];
791
- let nextDate;
792
- for (let i = 0; i < amount; i++) {
793
- nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
794
- dates.push(nextDate);
795
- }
796
- return dates;
797
- }
798
- /**
799
- * Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
800
- * The iterator runs until the optional endDate is reached or forever.
801
- */
802
- *getNextDatesIterator(startDate, endDate) {
803
- let nextDate;
804
- while (true) {
805
- nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
806
- if (endDate && endDate.getTime() < nextDate.getTime()) {
807
- return;
808
- }
809
- yield nextDate;
810
- }
811
- }
812
- /** Gets the previous date starting from the given start date or now. */
813
- getPrevDate(startDate = new Date()) {
814
- const startDateElements = extractDateElements(startDate);
815
- let maxYear = startDateElements.year;
816
- let startIndexMonth = this.reversed.months.findIndex((x) => x <= startDateElements.month);
817
- if (startIndexMonth === -1) {
818
- startIndexMonth = 0;
819
- maxYear--;
820
- }
821
- // We try every month within the past 5 years to make sure that we tried to
822
- // find a matching date inside a whole leap year.
823
- const maxIterations = this.reversed.months.length * 5;
824
- for (let i = 0; i < maxIterations; i++) {
825
- // Get the next year and month.
826
- const year = maxYear -
827
- Math.floor((startIndexMonth + i) / this.reversed.months.length);
828
- const month = this.reversed.months[(startIndexMonth + i) % this.reversed.months.length];
829
- const isStartMonth = year === startDateElements.year && month === startDateElements.month;
830
- // Find the previous day.
831
- let day = this.findAllowedDayInMonth('prev', year, month, isStartMonth
832
- ? startDateElements.day
833
- : // Start searching from the last day of the month.
834
- getDaysInMonth(year, month));
835
- let isStartDay = isStartMonth && day === startDateElements.day;
836
- // If we found a day and it is the start day, try to find a valid time beginning from the start date time.
837
- if (day !== undefined && isStartDay) {
838
- const prevTime = this.findAllowedTime('prev', startDateElements);
839
- if (prevTime !== undefined) {
840
- return new Date(year, month, day, prevTime.hour, prevTime.minute, prevTime.second);
841
- }
842
- // If no valid time has been found for the start date, try the previous day.
843
- if (day > 1) {
844
- day = this.findAllowedDayInMonth('prev', year, month, day - 1);
845
- isStartDay = false;
846
- }
847
- }
848
- // If we found a previous day and it is not the start day, just use the previous day with the first allowed values
849
- // for hours, minutes and seconds (which will be the latest time due to using the reversed array).
850
- if (day !== undefined && !isStartDay) {
851
- return new Date(year, month, day, this.reversed.hours[0], this.reversed.minutes[0], this.reversed.seconds[0]);
852
- }
853
- // No allowed day has been found for this month. Continue to search in previous month.
854
- }
855
- throw new Error('No valid previous date was found.');
856
- }
857
- /** Gets the specified amount of previous dates starting from the given start date or now. */
858
- getPrevDates(amount, startDate) {
859
- const dates = [];
860
- let prevDate;
861
- for (let i = 0; i < amount; i++) {
862
- prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
863
- dates.push(prevDate);
864
- }
865
- return dates;
866
- }
867
- /**
868
- * Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
869
- * The iterator runs until the optional endDate is reached or forever.
870
- */
871
- *getPrevDatesIterator(startDate, endDate) {
872
- let prevDate;
873
- while (true) {
874
- prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
875
- if (endDate && endDate.getTime() > prevDate.getTime()) {
876
- return;
877
- }
878
- yield prevDate;
879
- }
880
- }
881
- /** Returns true when there is a cron date at the given date. */
882
- matchDate(date) {
883
- const { second, minute, hour, day, month, weekday } = extractDateElements(date);
884
- if (this.seconds.indexOf(second) === -1 ||
885
- this.minutes.indexOf(minute) === -1 ||
886
- this.hours.indexOf(hour) === -1 ||
887
- this.months.indexOf(month) === -1) {
888
- return false;
889
- }
890
- if (this.days.length !== 31 && this.weekdays.length !== 7) {
891
- return (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1);
892
- }
893
- return (this.days.indexOf(day) !== -1 && this.weekdays.indexOf(weekday) !== -1);
894
- }
895
- }
896
-
897
- const secondConstraint = {
898
- min: 0,
899
- max: 59,
900
- };
901
- const minuteConstraint = {
902
- min: 0,
903
- max: 59,
904
- };
905
- const hourConstraint = {
906
- min: 0,
907
- max: 23,
908
- };
909
- const dayConstraint = {
910
- min: 1,
911
- max: 31,
912
- };
913
- const monthConstraint = {
914
- min: 1,
915
- max: 12,
916
- aliases: {
917
- jan: '1',
918
- feb: '2',
919
- mar: '3',
920
- apr: '4',
921
- may: '5',
922
- jun: '6',
923
- jul: '7',
924
- aug: '8',
925
- sep: '9',
926
- oct: '10',
927
- nov: '11',
928
- dec: '12',
929
- },
930
- };
931
- const weekdayConstraint = {
932
- min: 0,
933
- max: 7,
934
- aliases: {
935
- mon: '1',
936
- tue: '2',
937
- wed: '3',
938
- thu: '4',
939
- fri: '5',
940
- sat: '6',
941
- sun: '7',
942
- },
943
- };
944
- const timeNicknames = {
945
- '@yearly': '0 0 1 1 *',
946
- '@annually': '0 0 1 1 *',
947
- '@monthly': '0 0 1 * *',
948
- '@weekly': '0 0 * * 0',
949
- '@daily': '0 0 * * *',
950
- '@hourly': '0 * * * *',
951
- '@minutely': '* * * * *',
952
- };
953
- function parseElement(element, constraint) {
954
- const result = new Set();
955
- // If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint
956
- if (element === '*') {
957
- for (let i = constraint.min; i <= constraint.max; i = i + 1) {
958
- result.add(i);
959
- }
960
- return result;
961
- }
962
- // If the element is a list, parse each element in the list.
963
- const listElements = element.split(',');
964
- if (listElements.length > 1) {
965
- for (const listElement of listElements) {
966
- const parsedListElement = parseElement(listElement, constraint);
967
- for (const x of parsedListElement) {
968
- result.add(x);
969
- }
970
- }
971
- return result;
972
- }
973
- // Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.
974
- const parseSingleElement = (singleElement) => {
975
- var _a, _b;
976
- // biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
977
- singleElement =
978
- (_b = (_a = constraint.aliases) === null || _a === void 0 ? void 0 : _a[singleElement.toLowerCase()]) !== null && _b !== void 0 ? _b : singleElement;
979
- const parsedElement = Number.parseInt(singleElement, 10);
980
- if (Number.isNaN(parsedElement)) {
981
- throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`);
982
- }
983
- if (parsedElement < constraint.min || parsedElement > constraint.max) {
984
- throw new Error(`Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`);
985
- }
986
- return parsedElement;
987
- };
988
- // Detect if the element is a range.
989
- // Possible range formats: 'start-end', 'start-end/step', '*', '*/step'.
990
- // Where start and end can be numbers or aliases.
991
- // Capture groups: 1: start-end, 2: start, 3: end, 4: /step, 5: step.
992
- const rangeSegments = /^(([0-9a-zA-Z]+)-([0-9a-zA-Z]+)|\*)(\/([0-9]+))?$/.exec(element);
993
- // If not, it must be a single element.
994
- if (rangeSegments === null) {
995
- result.add(parseSingleElement(element));
996
- return result;
997
- }
998
- // If it is a range, get start and end of the range.
999
- let parsedStart = rangeSegments[1] === '*'
1000
- ? constraint.min
1001
- : parseSingleElement(rangeSegments[2]);
1002
- const parsedEnd = rangeSegments[1] === '*'
1003
- ? constraint.max
1004
- : parseSingleElement(rangeSegments[3]);
1005
- // need to catch Sunday, which gets parsed here as 7, but is also legitimate at the start of a range as 0, to avoid the out of order error
1006
- if (constraint === weekdayConstraint &&
1007
- parsedStart === 7 &&
1008
- // this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]
1009
- parsedEnd !== 7) {
1010
- parsedStart = 0;
1011
- }
1012
- if (parsedStart > parsedEnd) {
1013
- throw new Error(`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`);
1014
- }
1015
- // Check whether there is a custom step defined for the range, defaulting to 1.
1016
- const step = rangeSegments[5];
1017
- let parsedStep = 1;
1018
- if (step !== undefined) {
1019
- parsedStep = Number.parseInt(step, 10);
1020
- if (Number.isNaN(parsedStep)) {
1021
- throw new Error(`Failed to parse step: ${step} is NaN.`);
1022
- }
1023
- if (parsedStep < 1) {
1024
- throw new Error(`Failed to parse step: Expected ${step} to be greater than 0.`);
1025
- }
1026
- }
1027
- // Go from start to end of the range by the given steps.
1028
- for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {
1029
- result.add(i);
1030
- }
1031
- return result;
1032
- }
1033
- /** Parses a cron expression into a Cron instance. */
1034
- function parseCronExpression(cronExpression) {
1035
- var _a;
1036
- if (typeof cronExpression !== 'string') {
1037
- throw new TypeError('Invalid cron expression: must be of type string.');
1038
- }
1039
- // Convert time nicknames.
1040
- // biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
1041
- cronExpression = (_a = timeNicknames[cronExpression.toLowerCase()]) !== null && _a !== void 0 ? _a : cronExpression;
1042
- // Split the cron expression into its elements, removing empty elements (extra whitespaces).
1043
- const elements = cronExpression.split(' ').filter((elem) => elem.length > 0);
1044
- if (elements.length < 5 || elements.length > 6) {
1045
- throw new Error('Invalid cron expression: expected 5 or 6 elements.');
1046
- }
1047
- const rawSeconds = elements.length === 6 ? elements[0] : '0';
1048
- const rawMinutes = elements.length === 6 ? elements[1] : elements[0];
1049
- const rawHours = elements.length === 6 ? elements[2] : elements[1];
1050
- const rawDays = elements.length === 6 ? elements[3] : elements[2];
1051
- const rawMonths = elements.length === 6 ? elements[4] : elements[3];
1052
- const rawWeekdays = elements.length === 6 ? elements[5] : elements[4];
1053
- return new Cron({
1054
- seconds: parseElement(rawSeconds, secondConstraint),
1055
- minutes: parseElement(rawMinutes, minuteConstraint),
1056
- hours: parseElement(rawHours, hourConstraint),
1057
- days: parseElement(rawDays, dayConstraint),
1058
- // months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.
1059
- months: new Set(Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)),
1060
- weekdays: new Set(Array.from(parseElement(rawWeekdays, weekdayConstraint)).map((x) => x % 7)),
1061
- });
1062
- }
1063
-
1064
- function getNextCronDate(expr) {
1065
- try {
1066
- const interval = parseCronExpression(expr);
1067
- return interval.getNextDate();
1068
- } catch (error) {
1069
- console.error("Invalid cron expression:", expr, error);
1070
- throw new Error("Invalid cron expression");
1071
- }
1072
- }
1073
-
1074
- function Injectable() {
1075
- return function(constructor) {
1076
- L$1()(constructor);
1077
- };
1078
- }
1079
-
1080
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1081
- var __decorateClass = (decorators, target, key, kind) => {
1082
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
1083
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
1084
- if (decorator = decorators[i])
1085
- result = (decorator(result)) || result;
1086
- return result;
1087
- };
1088
- let Scheduler = class {
1089
- constructor() {
1090
- this.registry = JobRegistry.instance;
1091
- this.alarm = new AlarmAdapter();
1092
- this.timeout = new TimeoutAdapter();
1093
- console.log("Scheduler initialized");
1094
- this.alarm.onTrigger(this.execute.bind(this));
1095
- this.timeout.onTrigger(this.execute.bind(this));
1096
- }
1097
- schedule(id, options) {
1098
- const context = this.registry.getContext(id);
1099
- if (!context || context.isStopped()) {
1100
- console.log(`Job ${id} is stopped, skipping schedule`);
1101
- return;
1102
- }
1103
- console.log(`Scheduling job ${id} with options:`, options);
1104
- const when = this.getScheduleTime(options);
1105
- const adapter = when - Date.now() < 6e4 ? this.timeout : this.alarm;
1106
- const timerId = adapter.schedule(id, when);
1107
- if (adapter === this.timeout) {
1108
- this.registry.setTimeoutId(id, timerId);
1109
- }
1110
- }
1111
- pause(id) {
1112
- console.log(`Pausing job ${id}`);
1113
- this.registry.pause(id);
1114
- }
1115
- resume(id) {
1116
- console.log(`Resuming job ${id}`);
1117
- this.registry.resume(id);
1118
- const options = this.registry.meta(id);
1119
- if (options) {
1120
- this.schedule(id, options);
1121
- }
1122
- }
1123
- stop(id) {
1124
- console.log(`Stopping job ${id}`);
1125
- this.registry.stop(id);
1126
- }
1127
- async execute(id) {
1128
- const job = this.registry.resolve(id);
1129
- const context = this.registry.getContext(id);
1130
- if (!job || !context) {
1131
- console.log(`Job ${id} not found or no context`);
1132
- return;
1133
- }
1134
- if (context.isPaused() || context.isStopped()) {
1135
- console.log(`Job ${id} is paused or stopped, skipping execution`);
1136
- return;
1137
- }
1138
- try {
1139
- this.registry.updateState(id, JobState.RUNNING);
1140
- console.log(`Executing job ${id}`);
1141
- const jobInstance = container.get(id);
1142
- console.log(jobInstance);
1143
- await jobInstance.handle.bind(jobInstance).call(jobInstance, context);
1144
- if (!context.isStopped() && !context.isPaused()) {
1145
- this.registry.updateState(id, JobState.COMPLETED);
1146
- const options = this.registry.meta(id);
1147
- if (options?.cron) {
1148
- this.registry.updateState(id, JobState.SCHEDULED);
1149
- this.schedule(id, options);
1150
- }
1151
- }
1152
- } catch (error) {
1153
- console.error(`Job ${id} execution failed:`, error);
1154
- context.fail(error);
1155
- }
1156
- }
1157
- getScheduleTime(options) {
1158
- if (options.delay) return Date.now() + options.delay;
1159
- if (options.cron) {
1160
- const date = getNextCronDate(options.cron);
1161
- if (!date) {
1162
- throw new Error("Invalid cron expression");
1163
- }
1164
- return date.getTime();
1165
- }
1166
- return Date.now();
1167
- }
1168
- // Public API for job control
1169
- getJobState(id) {
1170
- return this.registry.getContext(id)?.state;
1171
- }
1172
- listJobs() {
1173
- const jobs = [];
1174
- return jobs;
1175
- }
1176
- };
1177
- Scheduler = __decorateClass([
1178
- Injectable()
1179
- ], Scheduler);
1180
-
1181
- class ApplicationBootstrap {
1182
- constructor() {
1183
- this.serviceDependencies = /* @__PURE__ */ new Map();
1184
- this.serviceRegistry = /* @__PURE__ */ new Map();
1185
- this.logger = new BootstrapLogger();
1186
- this.storeDefinitions = [];
1187
- }
1188
- /**
1189
- * Add a store definition to be initialized
1190
- */
1191
- withStore(storeDefinition) {
1192
- if (storeDefinition && storeDefinition.name) {
1193
- this.storeDefinitions.push(storeDefinition);
1194
- this.logger.debug(`\u{1F4E6} Added store definition: ${storeDefinition.name}`);
1195
- }
1196
- return this;
1197
- }
1198
- /**
1199
- * Add multiple store definitions to be initialized
1200
- */
1201
- withStores(storeDefinitions) {
1202
- for (const store of storeDefinitions) {
1203
- this.withStore(store);
1204
- }
1205
- return this;
1206
- }
1207
- /**
1208
- * Create and initialize a new Chroma application instance
1209
- */
1210
- async create({
1211
- keepPortAlive = false,
1212
- portName
1213
- }) {
1214
- try {
1215
- this.logger.info("\u{1F680} Starting Chroma application bootstrap...");
1216
- await this.discoverAndInitializeStores();
1217
- await this.discoverServices();
1218
- await this.validateDependencies();
1219
- await this.registerServices();
1220
- await this.registerMessages();
1221
- await this.registerJobs();
1222
- await this.bootMessages();
1223
- await this.bootServices();
1224
- this.logger.success("\u{1F389} Chroma application initialization complete!");
1225
- bootstrap$1({ container, keepAlive: keepPortAlive, portName });
1226
- } catch (error) {
1227
- this.logger.error("\u{1F4A5} Application bootstrap failed:", error);
1228
- throw error;
1229
- }
1230
- }
1231
- /**
1232
- * Boot all registered services by calling their onBoot method if present
1233
- */
1234
- async bootServices() {
1235
- this.logger.info("\u{1F680} Booting services...");
1236
- console.log("services", this.serviceRegistry.entries());
1237
- for (const [serviceName, ServiceClass] of this.serviceRegistry.entries()) {
1238
- try {
1239
- const instance = container.get(ServiceClass);
1240
- if (typeof instance.onBoot === "function") {
1241
- await instance.onBoot();
1242
- this.logger.success(`Booted service: ${serviceName}`);
1243
- }
1244
- } catch (error) {
1245
- this.logger.error(`Failed to boot service ${serviceName}:`, error);
1246
- }
1247
- }
1248
- }
1249
- /**
1250
- * Discover all services in the application directory
1251
- */
1252
- async discoverServices() {
1253
- this.logger.info("\u{1F50D} Discovering services...");
1254
- const serviceModules = import.meta.glob(
1255
- "/src/app/services/**/*.service.{ts,js}",
1256
- { eager: true }
1257
- );
1258
- for (const module of Object.values(serviceModules)) {
1259
- const ServiceClass = module?.default;
1260
- if (!ServiceClass) continue;
1261
- this.serviceRegistry.set(ServiceClass.name, ServiceClass);
1262
- }
1263
- for (const module of Object.values(serviceModules)) {
1264
- const ServiceClass = module?.default;
1265
- if (!ServiceClass) continue;
1266
- const dependencies = this.resolveDependencies(ServiceClass);
1267
- this.serviceDependencies.set(ServiceClass.name, {
1268
- service: ServiceClass,
1269
- dependencies,
1270
- registered: false
1271
- });
1272
- this.logger.debug(`\u{1F4E6} Discovered ${ServiceClass.name}`, {
1273
- dependencies: dependencies.map((dep) => dep.name)
1274
- });
1275
- }
1276
- this.logger.success(`\u2705 Discovered ${this.serviceDependencies.size} services`);
1277
- }
1278
- /**
1279
- * Initialize stores from provided definitions
1280
- */
1281
- async discoverAndInitializeStores() {
1282
- try {
1283
- if (this.storeDefinitions.length === 0) {
1284
- this.logger.debug("\u{1F4ED} No store definitions provided");
1285
- return;
1286
- }
1287
- this.logger.info(`Initializing ${this.storeDefinitions.length} store(s)...`);
1288
- const chromaGlobal = globalThis.__CHROMA__;
1289
- if (chromaGlobal?.initStores && typeof chromaGlobal.initStores === "function") {
1290
- let isFirstStore = true;
1291
- for (const store of this.storeDefinitions) {
1292
- const { classes, store: storeInstance } = await chromaGlobal.initStores(store);
1293
- const diKey = `CentralStore:${store.name}`;
1294
- container.bind(diKey).toConstantValue(storeInstance);
1295
- if (isFirstStore) {
1296
- container.bind("appStore").toConstantValue(storeInstance);
1297
- isFirstStore = false;
1298
- }
1299
- this.registerMessageClass(classes.GetStoreStateMessage, `store:${store.name}:getState`);
1300
- this.registerMessageClass(classes.SetStoreStateMessage, `store:${store.name}:setState`);
1301
- this.registerMessageClass(
1302
- classes.SubscribeToStoreMessage,
1303
- `store:${store.name}:subscribe`
1304
- );
1305
- this.logger.debug(`\u2705 Initialized store: ${store.name}`);
1306
- }
1307
- }
1308
- this.logger.success(`\u2705 Initialized ${this.storeDefinitions.length} store(s)`);
1309
- } catch (error) {
1310
- this.logger.error("\u274C Failed to initialize stores:", error);
1311
- }
1312
- }
1313
- /**
1314
- * Resolve service dependencies using reflection and fallback parsing
1315
- */
1316
- resolveDependencies(ServiceClass) {
1317
- const paramTypes = Reflect.getMetadata("design:paramtypes", ServiceClass) || [];
1318
- if (paramTypes.length > 0) {
1319
- return paramTypes.filter((type) => type && type !== Object);
1320
- }
1321
- if (ServiceClass.length > 0) {
1322
- return this.parseConstructorDependencies(ServiceClass);
1323
- }
1324
- return [];
1325
- }
1326
- /**
1327
- * Parse constructor dependencies from class string representation
1328
- */
1329
- parseConstructorDependencies(ServiceClass) {
1330
- const constructorString = ServiceClass.toString();
1331
- const constructorMatch = constructorString.match(/constructor\s*\(([^)]*)\)/);
1332
- if (!constructorMatch) return [];
1333
- const parameters = constructorMatch[1].split(",").map((param) => param.trim()).filter((param) => param.length > 0);
1334
- const dependencies = [];
1335
- for (const param of parameters) {
1336
- const paramName = param.toLowerCase();
1337
- if (paramName === "appstore") {
1338
- let storeInstance;
1339
- storeInstance = container.get("appStore");
1340
- if (!storeInstance) {
1341
- throw new Error(`No store found for parameter "${param}" in ${ServiceClass.name}`);
1342
- }
1343
- dependencies.push("appStore");
1344
- continue;
1345
- }
1346
- const matchingService = Array.from(this.serviceRegistry.entries()).find(
1347
- ([name]) => name.toLowerCase() === paramName
1348
- );
1349
- if (matchingService) {
1350
- dependencies.push(matchingService[1]);
1351
- } else {
1352
- this.logger.warn(`\u26A0\uFE0F No service found for parameter "${param}" in ${ServiceClass.name}`);
1353
- dependencies.push(void 0);
1354
- }
1355
- }
1356
- return dependencies;
1357
- }
1358
- /**
1359
- * Validate service dependencies and detect circular references
1360
- */
1361
- async validateDependencies() {
1362
- this.logger.info("\u{1F50D} Validating dependencies...");
1363
- const circularDependencies = this.detectCircularDependencies();
1364
- if (circularDependencies.length > 0) {
1365
- this.handleCircularDependencies(circularDependencies);
1366
- } else {
1367
- this.logger.success("\u2705 No circular dependencies detected");
1368
- }
1369
- }
1370
- /**
1371
- * Detect circular dependencies using depth-first search
1372
- */
1373
- detectCircularDependencies() {
1374
- const visited = /* @__PURE__ */ new Set();
1375
- const recursionStack = /* @__PURE__ */ new Set();
1376
- const circularDeps = [];
1377
- const dfs = (serviceName, path) => {
1378
- if (recursionStack.has(serviceName)) {
1379
- const cycleStart = path.indexOf(serviceName);
1380
- const cycle = path.slice(cycleStart).concat([serviceName]);
1381
- circularDeps.push({
1382
- cycle: Object.freeze(cycle),
1383
- services: Object.freeze(Array.from(new Set(cycle)))
1384
- });
1385
- return;
1386
- }
1387
- if (visited.has(serviceName)) return;
1388
- visited.add(serviceName);
1389
- recursionStack.add(serviceName);
1390
- const serviceMetadata = this.serviceDependencies.get(serviceName);
1391
- if (serviceMetadata) {
1392
- for (const dependency of serviceMetadata.dependencies) {
1393
- if (this.serviceDependencies.has(dependency.name)) {
1394
- dfs(dependency.name, [...path, serviceName]);
1395
- }
1396
- }
1397
- }
1398
- recursionStack.delete(serviceName);
1399
- };
1400
- for (const serviceName of this.serviceDependencies.keys()) {
1401
- if (!visited.has(serviceName)) {
1402
- dfs(serviceName, []);
1403
- }
1404
- }
1405
- return circularDeps;
1406
- }
1407
- /**
1408
- * Handle circular dependencies with detailed reporting
1409
- */
1410
- handleCircularDependencies(circularDeps) {
1411
- this.logger.error("\u{1F534} CIRCULAR DEPENDENCIES DETECTED");
1412
- this.logger.divider();
1413
- circularDeps.forEach((circular, index) => {
1414
- this.logger.error(`\u{1F4CD} Circular Dependency #${index + 1}:`);
1415
- this.logger.error(` Cycle: ${circular.cycle.join(" \u2192 ")}`);
1416
- this.logger.error(` Affected Services: ${circular.services.join(", ")}`);
1417
- this.logger.info(" \u{1F4A1} Resolution Suggestions:");
1418
- this.logger.info(" \u2022 Extract shared functionality into a separate service");
1419
- this.logger.info(" \u2022 Use interfaces or abstractions to break the cycle");
1420
- this.logger.info(" \u2022 Consider Factory or Provider patterns");
1421
- this.logger.info(" \u2022 Move shared logic to utility classes");
1422
- });
1423
- this.logger.divider();
1424
- this.logger.warn("\u26A0\uFE0F Application will continue but some services may fail to resolve");
1425
- this.logger.warn(" Please address these circular dependencies for optimal functionality");
1426
- }
1427
- /**
1428
- * Register all services with the dependency injection container
1429
- */
1430
- async registerServices() {
1431
- this.logger.info("\u{1F527} Registering services...");
1432
- for (const serviceName of this.serviceDependencies.keys()) {
1433
- await this.registerService(serviceName);
1434
- }
1435
- const results = this.getRegistrationResults();
1436
- this.reportRegistrationResults(results);
1437
- }
1438
- /**
1439
- * Register a single service with dependency resolution
1440
- */
1441
- async registerService(serviceName, visitedServices = /* @__PURE__ */ new Set(), registrationPath = []) {
1442
- const serviceMetadata = this.serviceDependencies.get(serviceName);
1443
- if (!serviceMetadata) {
1444
- return { success: false, message: `Service ${serviceName} not found` };
1445
- }
1446
- if (serviceMetadata.registered) {
1447
- return { success: true, message: `Service ${serviceName} already registered` };
1448
- }
1449
- if (visitedServices.has(serviceName)) {
1450
- const cycle = [...registrationPath, serviceName];
1451
- this.logger.warn(`\u{1F504} Circular dependency in registration: ${cycle.join(" \u2192 ")}`);
1452
- return { success: false, message: "Circular dependency detected" };
1453
- }
1454
- const newVisited = new Set(visitedServices).add(serviceName);
1455
- const newPath = [...registrationPath, serviceName];
1456
- for (const dependency of serviceMetadata.dependencies) {
1457
- if (this.serviceDependencies.has(dependency.name)) {
1458
- await this.registerService(dependency.name, newVisited, newPath);
1459
- }
1460
- }
1461
- try {
1462
- const ServiceClass = serviceMetadata.service;
1463
- b(L$1(), ServiceClass);
1464
- serviceMetadata.dependencies.forEach((dependency, index) => {
1465
- b(_$1(dependency), ServiceClass, index);
1466
- });
1467
- container.bind(ServiceClass).toSelf().inSingletonScope();
1468
- serviceMetadata.registered = true;
1469
- this.logger.success(`\u2705 Registered service: ${ServiceClass.name}`);
1470
- return { success: true, message: `Successfully registered ${ServiceClass.name}` };
1471
- } catch (error) {
1472
- const errorMessage = `Failed to register ${serviceName}`;
1473
- this.logger.error(`\u274C ${errorMessage}:`, error);
1474
- return { success: false, message: errorMessage, error };
1475
- }
1476
- }
1477
- /**
1478
- * Get registration results summary
1479
- */
1480
- getRegistrationResults() {
1481
- const successful = [];
1482
- const failed = [];
1483
- for (const [name, metadata] of this.serviceDependencies.entries()) {
1484
- if (metadata.registered) {
1485
- successful.push(name);
1486
- } else {
1487
- failed.push(name);
1488
- }
1489
- }
1490
- return { successful, failed };
1491
- }
1492
- /**
1493
- * Report service registration results
1494
- */
1495
- reportRegistrationResults({
1496
- successful,
1497
- failed
1498
- }) {
1499
- if (failed.length > 0) {
1500
- this.logger.error("\u26A0\uFE0F Some services could not be registered:");
1501
- failed.forEach((serviceName) => {
1502
- const metadata = this.serviceDependencies.get(serviceName);
1503
- const deps = metadata?.dependencies.map((d) => d.name).join(", ") || "none";
1504
- this.logger.error(` \u2022 ${serviceName} (dependencies: ${deps})`);
1505
- });
1506
- } else {
1507
- this.logger.success(`\u2705 All ${successful.length} services registered successfully`);
1508
- }
1509
- }
1510
- /**
1511
- * Register message handlers
1512
- */
1513
- async registerMessages() {
1514
- this.logger.info("\u{1F4E8} Registering messages...");
1515
- const messageModules = import.meta.glob(
1516
- "/src/app/messages/**/*.message.{ts,js}",
1517
- { eager: true }
1518
- );
1519
- for (const module of Object.values(messageModules)) {
1520
- const MessageClass = module?.default;
1521
- if (!MessageClass) continue;
1522
- try {
1523
- const dependencies = this.resolveDependencies(MessageClass);
1524
- b(L$1(), MessageClass);
1525
- dependencies.forEach((dependency, index) => {
1526
- b(_$1(dependency), MessageClass, index);
1527
- });
1528
- const messageMetadata = Reflect.getMetadata("name", MessageClass);
1529
- const messageName = messageMetadata || MessageClass.name;
1530
- container.bind(messageName).to(MessageClass).inSingletonScope();
1531
- this.logger.success(`\u2705 Registered message: ${messageName}`);
1532
- } catch (error) {
1533
- this.logger.error(`\u274C Failed to register message ${MessageClass.name}:`, error);
1534
- }
1535
- }
1536
- }
1537
- async registerMessageClass(MessageClass, name) {
1538
- const dependencies = this.resolveDependencies(MessageClass);
1539
- b(L$1(), MessageClass);
1540
- dependencies.forEach((dependency, index) => {
1541
- b(_$1(dependency), MessageClass, index);
1542
- });
1543
- container.bind(name).to(MessageClass).inSingletonScope();
1544
- this.logger.success(`\u2705 Registered message: ${name}`);
1545
- }
1546
- /**
1547
- * Boot all registered messages
1548
- */
1549
- async bootMessages() {
1550
- this.logger.info("\u{1F680} Booting messages...");
1551
- const messageModules = import.meta.glob(
1552
- "/src/app/messages/**/*.message.{ts,js}",
1553
- { eager: true }
1554
- );
1555
- for (const module of Object.values(messageModules)) {
1556
- const MessageClass = module?.default;
1557
- if (!MessageClass || typeof MessageClass.prototype.boot !== "function") continue;
1558
- try {
1559
- const messageMetadata = Reflect.getMetadata("name", MessageClass);
1560
- const messageName = messageMetadata || MessageClass.name;
1561
- const messageInstance = container.get(messageName);
1562
- await messageInstance.boot();
1563
- this.logger.success(`\u2705 Booted message: ${messageName}`);
1564
- } catch (error) {
1565
- this.logger.error(`\u274C Failed to boot message ${MessageClass.name}:`, error);
1566
- }
1567
- }
1568
- }
1569
- /**
1570
- * Register jobs for scheduled execution
1571
- */
1572
- async registerJobs() {
1573
- this.logger.info("\u{1F552} Registering jobs...");
1574
- const jobModules = import.meta.glob(
1575
- "/src/app/jobs/**/*.job.{ts,js}",
1576
- { eager: true }
1577
- );
1578
- this.scheduler = new Scheduler();
1579
- for (const module of Object.values(jobModules)) {
1580
- const JobClass = module?.default;
1581
- if (!JobClass) continue;
1582
- try {
1583
- const dependencies = this.resolveDependencies(JobClass);
1584
- b(L$1(), JobClass);
1585
- dependencies.forEach((dependency, index) => {
1586
- b(_$1(dependency), JobClass, index);
1587
- });
1588
- const jobMetadata = Reflect.getMetadata("name", JobClass);
1589
- const jobName = jobMetadata || JobClass.name;
1590
- container.bind(JobClass).toSelf().inSingletonScope();
1591
- const id = `${jobName.toLowerCase()}:${JobClass.name.toLowerCase()} ${Math.random().toString(36).substring(2, 15)}`;
1592
- container.bind(id).to(JobClass).inSingletonScope();
1593
- const options = Reflect.getMetadata("job:options", JobClass) || {};
1594
- const instance = container.get(JobClass);
1595
- JobRegistry.instance.register(id, instance, options);
1596
- this.scheduler.schedule(id, options);
1597
- this.logger.success(`\u2705 Registered job: ${jobName}`);
1598
- } catch (error) {
1599
- this.logger.error(`\u274C Failed to register job ${JobClass.name}:`, error);
1600
- }
1601
- }
1602
- }
1603
- }
1604
- class BootstrapLogger {
1605
- info(message, context) {
1606
- console.log(message);
1607
- if (context) console.log(" ", context);
1608
- }
1609
- success(message) {
1610
- console.log(message);
1611
- }
1612
- warn(message) {
1613
- console.warn(message);
1614
- }
1615
- error(message, error) {
1616
- console.error(message);
1617
- if (error) console.error(" ", error);
1618
- }
1619
- debug(message, context) {
1620
- console.debug(message);
1621
- if (context) console.debug(" ", context);
1622
- }
1623
- divider() {
1624
- console.log("=".repeat(50));
1625
- }
1626
- }
1627
- async function create({
1628
- keepPortAlive = false,
1629
- portName
1630
- } = {}) {
1631
- const bootstrap2 = new ApplicationBootstrap();
1632
- await bootstrap2.create({
1633
- keepPortAlive,
1634
- portName
1635
- });
1636
- }
1637
- function bootstrap() {
1638
- return new BootstrapBuilder();
1639
- }
1640
- class BootstrapBuilder {
1641
- constructor() {
1642
- this.app = new ApplicationBootstrap();
1643
- }
1644
- /**
1645
- * Add a store definition to be initialized
1646
- */
1647
- withStore(storeDefinition) {
1648
- this.app.withStore(storeDefinition);
1649
- return this;
1650
- }
1651
- /**
1652
- * Add multiple store definitions to be initialized
1653
- */
1654
- withStores(storeDefinitions) {
1655
- this.app.withStores(storeDefinitions);
1656
- return this;
1657
- }
1658
- /**
1659
- * Create and start the application
1660
- */
1661
- async create({
1662
- keepPortAlive = false,
1663
- portName
1664
- } = {}) {
1665
- await this.app.create({ keepPortAlive, portName });
1666
- }
5
+ function Service() {
6
+ return injectable();
1667
7
  }
8
+ const Use = (id) => inject(id);
9
+ const Store = () => Use(TOKENS.Store);
1668
10
 
1669
11
  class IMessage {
1670
12
  handle(...args) {
@@ -1673,26 +15,12 @@ class IMessage {
1673
15
  }
1674
16
  function Message(name) {
1675
17
  return function(constructor) {
18
+ injectable()(constructor);
1676
19
  Reflect.defineMetadata("name", name, constructor);
1677
20
  return constructor;
1678
21
  };
1679
22
  }
1680
23
 
1681
- class Booteable {
1682
- /**
1683
- * Optional destroy method to be called when the service is being destroyed.
1684
- * This can be used to clean up resources or perform any necessary teardown logic.
1685
- */
1686
- destroy() {
1687
- }
1688
- }
1689
- function isBooteable(obj) {
1690
- return typeof obj.boot === "function";
1691
- }
1692
- function isDestroyable(obj) {
1693
- return typeof obj.destroy === "function";
1694
- }
1695
-
1696
24
  class Job {
1697
25
  constructor(data) {
1698
26
  this.data = data;
@@ -1710,6 +38,7 @@ class Job {
1710
38
 
1711
39
  function JobConfig(options = {}) {
1712
40
  return function(constructor) {
41
+ injectable()(constructor);
1713
42
  Reflect.defineMetadata("job:options", { options }, constructor);
1714
43
  return constructor;
1715
44
  };
@@ -1719,9 +48,26 @@ const Delay = (ms) => JobConfig({ delay: ms });
1719
48
 
1720
49
  function Every(cron) {
1721
50
  return function(constructor) {
51
+ injectable()(constructor);
1722
52
  Reflect.defineMetadata("job:options", { cron }, constructor);
1723
53
  return constructor;
1724
54
  };
1725
55
  }
1726
56
 
1727
- export { Booteable, Delay, Every, IMessage, _$1 as Inject, Injectable, Job, JobState, METADATA_KEY, Message, bind, bootstrap, container, create, isBooteable, isDestroyable, isInjectable, resolve };
57
+ class Booteable {
58
+ /**
59
+ * Optional destroy method to be called when the service is being destroyed.
60
+ * This can be used to clean up resources or perform any necessary teardown logic.
61
+ */
62
+ destroy() {
63
+ }
64
+ }
65
+ function isBooteable(obj) {
66
+ return typeof obj.boot === "function";
67
+ }
68
+ function isDestroyable(obj) {
69
+ return typeof obj.destroy === "function";
70
+ }
71
+
72
+ export { Booteable, Delay, Every, IMessage, Job, Message, Service, Store, Use, isBooteable, isDestroyable };
73
+ //# sourceMappingURL=index.es.js.map