@kaokei/di 5.0.6 → 5.0.8

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.
@@ -1,6 +1,6 @@
1
1
  import { BindingType, StatusType } from './constants';
2
2
  import { Container } from './container';
3
- import { Newable, Context, Options, CommonToken, RecordObject, DynamicValue, PostConstructParam, ActivationHandler, DeactivationHandler } from './interfaces';
3
+ import { Newable, Context, Options, CommonToken, RecordObject, DynamicValue, PostConstructParam, BindingActivationHandler, BindingDeactivationHandler } from './interfaces';
4
4
  export interface InjectPropertiesResult {
5
5
  properties: RecordObject;
6
6
  bindings: Binding[];
@@ -18,11 +18,11 @@ export declare class Binding<T = unknown> {
18
18
  cache?: T;
19
19
  postConstructResult: Promise<void> | symbol | undefined;
20
20
  transient: boolean;
21
- onActivationHandler?: ActivationHandler<T>;
22
- onDeactivationHandler?: DeactivationHandler<T>;
21
+ onActivationHandler?: BindingActivationHandler<T>;
22
+ onDeactivationHandler?: BindingDeactivationHandler<T>;
23
23
  constructor(token: CommonToken<T>, container: Container);
24
- onActivation(handler: ActivationHandler<T>): void;
25
- onDeactivation(handler: DeactivationHandler<T>): void;
24
+ onActivation(handler: BindingActivationHandler<T>): void;
25
+ onDeactivation(handler: BindingDeactivationHandler<T>): void;
26
26
  activate(input: T): T;
27
27
  deactivate(): void;
28
28
  to(constructor: Newable<T>): this;
package/dist/binding.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BindingType, StatusType } from './constants';
2
2
  import { Container } from './container';
3
- import { Newable, Context, Options, CommonToken, RecordObject, DynamicValue, PostConstructParam, ActivationHandler, DeactivationHandler } from './interfaces';
3
+ import { Newable, Context, Options, CommonToken, RecordObject, DynamicValue, PostConstructParam, BindingActivationHandler, BindingDeactivationHandler } from './interfaces';
4
4
  export interface InjectPropertiesResult {
5
5
  properties: RecordObject;
6
6
  bindings: Binding[];
@@ -18,11 +18,11 @@ export declare class Binding<T = unknown> {
18
18
  cache?: T;
19
19
  postConstructResult: Promise<void> | symbol | undefined;
20
20
  transient: boolean;
21
- onActivationHandler?: ActivationHandler<T>;
22
- onDeactivationHandler?: DeactivationHandler<T>;
21
+ onActivationHandler?: BindingActivationHandler<T>;
22
+ onDeactivationHandler?: BindingDeactivationHandler<T>;
23
23
  constructor(token: CommonToken<T>, container: Container);
24
- onActivation(handler: ActivationHandler<T>): void;
25
- onDeactivation(handler: DeactivationHandler<T>): void;
24
+ onActivation(handler: BindingActivationHandler<T>): void;
25
+ onDeactivation(handler: BindingDeactivationHandler<T>): void;
26
26
  activate(input: T): T;
27
27
  deactivate(): void;
28
28
  to(constructor: Newable<T>): this;
@@ -1,40 +1,22 @@
1
- import { CommonToken, PostConstructParam } from './interfaces';
1
+ import { CommonToken } from './interfaces';
2
2
  /**
3
- * 关联 target 和 metadata 对象
4
- * @Injectable 类装饰器调用,直接存储 context.metadata
3
+ * 关联 target 和 metadata 对象(由 @Injectable / decorate() 调用)
4
+ * 存储 context.metadata 引用,后续读取均通过此映射完成。
5
5
  */
6
6
  export declare function defineMetadata(target: CommonToken, metadata: Record<string, unknown>): void;
7
7
  /**
8
- * 获取 PostConstruct 元数据
9
- *
10
- * 如果 target 在 map 中注册了(使用了 @Injectable),
11
- * 直接读取 metadata[key],原型链自动处理继承。
12
- * 如果 target 未注册但有父类,递归向上查找。
8
+ * 获取 target 自身的元数据值(不沿继承链查找)
9
+ * 对应 Reflect.getOwnMetadata(key, target)
13
10
  */
14
- export declare function getPostConstruct(target: CommonToken): {
15
- key: string;
16
- value?: PostConstructParam;
17
- } | undefined;
11
+ export declare function getOwnMetadata(key: string, target: CommonToken): unknown;
18
12
  /**
19
- * 获取 PreDestroy 元数据
20
- *
21
- * 与 getPostConstruct 同理。
13
+ * 获取元数据值,沿继承链向上查找直到找到为止
14
+ * 对应 Reflect.getMetadata(key, target)
22
15
  */
23
- export declare function getPreDestroy(target: CommonToken): {
24
- key: string;
25
- } | undefined;
16
+ export declare function getMetadata(key: string, target: CommonToken): unknown;
26
17
  /**
27
- * 获取属性注入元数据(需要手动处理继承链中嵌套对象的合并)
28
- *
29
- * context.metadata 的原型链继承只对第一层属性有效。
30
- * INJECTED_PROPS 对应的值是一个嵌套对象 { propName: { inject, self, ... } },
31
- * 原型链无法自动合并嵌套属性。
32
- *
33
- * 例如:父类有 { a: {...}, b: {...} },子类有 { a: {...} }
34
- * 通过原型链读取子类的 INJECTED_PROPS 只能拿到子类自己的 { a: {...} },
35
- * 无法自动合并父类的 b 属性。
18
+ * 获取属性注入元数据,手动合并继承链(原型链无法自动合并嵌套对象)
36
19
  *
37
- * 所以需要手动递归处理:合并当前类和父类的 INJECTED_PROPS,
38
- * 子类同名属性覆盖父类。
20
+ * 父类 { a, b } + 子类 { a } → 合并结果 { a(子类覆盖), b(继承) }
39
21
  */
40
22
  export declare function getInjectedProps(target: CommonToken): Record<string, Record<string, unknown>> | undefined;
@@ -1,40 +1,22 @@
1
- import { CommonToken, PostConstructParam } from './interfaces';
1
+ import { CommonToken } from './interfaces';
2
2
  /**
3
- * 关联 target 和 metadata 对象
4
- * @Injectable 类装饰器调用,直接存储 context.metadata
3
+ * 关联 target 和 metadata 对象(由 @Injectable / decorate() 调用)
4
+ * 存储 context.metadata 引用,后续读取均通过此映射完成。
5
5
  */
6
6
  export declare function defineMetadata(target: CommonToken, metadata: Record<string, unknown>): void;
7
7
  /**
8
- * 获取 PostConstruct 元数据
9
- *
10
- * 如果 target 在 map 中注册了(使用了 @Injectable),
11
- * 直接读取 metadata[key],原型链自动处理继承。
12
- * 如果 target 未注册但有父类,递归向上查找。
8
+ * 获取 target 自身的元数据值(不沿继承链查找)
9
+ * 对应 Reflect.getOwnMetadata(key, target)
13
10
  */
14
- export declare function getPostConstruct(target: CommonToken): {
15
- key: string;
16
- value?: PostConstructParam;
17
- } | undefined;
11
+ export declare function getOwnMetadata(key: string, target: CommonToken): unknown;
18
12
  /**
19
- * 获取 PreDestroy 元数据
20
- *
21
- * 与 getPostConstruct 同理。
13
+ * 获取元数据值,沿继承链向上查找直到找到为止
14
+ * 对应 Reflect.getMetadata(key, target)
22
15
  */
23
- export declare function getPreDestroy(target: CommonToken): {
24
- key: string;
25
- } | undefined;
16
+ export declare function getMetadata(key: string, target: CommonToken): unknown;
26
17
  /**
27
- * 获取属性注入元数据(需要手动处理继承链中嵌套对象的合并)
28
- *
29
- * context.metadata 的原型链继承只对第一层属性有效。
30
- * INJECTED_PROPS 对应的值是一个嵌套对象 { propName: { inject, self, ... } },
31
- * 原型链无法自动合并嵌套属性。
32
- *
33
- * 例如:父类有 { a: {...}, b: {...} },子类有 { a: {...} }
34
- * 通过原型链读取子类的 INJECTED_PROPS 只能拿到子类自己的 { a: {...} },
35
- * 无法自动合并父类的 b 属性。
18
+ * 获取属性注入元数据,手动合并继承链(原型链无法自动合并嵌套对象)
36
19
  *
37
- * 所以需要手动递归处理:合并当前类和父类的 INJECTED_PROPS,
38
- * 子类同名属性覆盖父类。
20
+ * 父类 { a, b } + 子类 { a } → 合并结果 { a(子类覆盖), b(继承) }
39
21
  */
40
22
  export declare function getInjectedProps(target: CommonToken): Record<string, Record<string, unknown>> | undefined;
@@ -29,6 +29,7 @@ export declare const ERRORS: {
29
29
  readonly PRE_DESTROY: "Multiple @PreDestroy decorators are not allowed in a single class.";
30
30
  readonly INVALID_TOKEN: "@Inject requires a valid token, but received null or undefined.";
31
31
  readonly LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined.";
32
+ readonly DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject, @autobind).";
32
33
  };
33
34
  export declare const UNINITIALIZED: unique symbol;
34
35
  export type BindingType = (typeof BINDING)[keyof typeof BINDING];
@@ -29,6 +29,7 @@ export declare const ERRORS: {
29
29
  readonly PRE_DESTROY: "Multiple @PreDestroy decorators are not allowed in a single class.";
30
30
  readonly INVALID_TOKEN: "@Inject requires a valid token, but received null or undefined.";
31
31
  readonly LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined.";
32
+ readonly DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject, @autobind).";
32
33
  };
33
34
  export declare const UNINITIALIZED: unique symbol;
34
35
  export type BindingType = (typeof BINDING)[keyof typeof BINDING];
@@ -4,7 +4,7 @@ export declare class Container {
4
4
  static _instanceContainerMap: WeakMap<object, Container>;
5
5
  static getContainerOf(instance: object): Container | undefined;
6
6
  parent?: Container;
7
- children?: Set<Container>;
7
+ _children?: Set<Container>;
8
8
  _bindings: Map<CommonToken, Binding>;
9
9
  _destroyed: boolean;
10
10
  _onActivationHandler?: ActivationHandler;
@@ -17,6 +17,7 @@ export declare class Container {
17
17
  isCurrentBound<T>(token: CommonToken<T>): boolean;
18
18
  isBound<T>(token: CommonToken<T>): boolean;
19
19
  createChild(): Container;
20
+ getChildren(): Set<Container> | undefined;
20
21
  destroy(): void;
21
22
  get<T>(token: CommonToken<T>, options: GetOptions & {
22
23
  optional: true;
@@ -4,7 +4,7 @@ export declare class Container {
4
4
  static _instanceContainerMap: WeakMap<object, Container>;
5
5
  static getContainerOf(instance: object): Container | undefined;
6
6
  parent?: Container;
7
- children?: Set<Container>;
7
+ _children?: Set<Container>;
8
8
  _bindings: Map<CommonToken, Binding>;
9
9
  _destroyed: boolean;
10
10
  _onActivationHandler?: ActivationHandler;
@@ -17,6 +17,7 @@ export declare class Container {
17
17
  isCurrentBound<T>(token: CommonToken<T>): boolean;
18
18
  isBound<T>(token: CommonToken<T>): boolean;
19
19
  createChild(): Container;
20
+ getChildren(): Set<Container> | undefined;
20
21
  destroy(): void;
21
22
  get<T>(token: CommonToken<T>, options: GetOptions & {
22
23
  optional: true;
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var Y=Object.defineProperty;var J=(n,t,e)=>t in n?Y(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var r=(n,t,e)=>J(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l={INJECTED_PROPS:"injected:props",INJECT:"inject",SELF:"self",SKIP_SELF:"skipSelf",OPTIONAL:"optional",POST_CONSTRUCT:"postConstruct",PRE_DESTROY:"preDestroy"},f={DEFAULT:"default",INITING:"initing",ACTIVATED:"activated"},p={INVALID:"Invalid",INSTANCE:"Instance",CONSTANT:"ConstantValue",DYNAMIC:"DynamicValue"},C={POST_CONSTRUCT:"Multiple @PostConstruct decorators are not allowed in a single class.",PRE_DESTROY:"Multiple @PreDestroy decorators are not allowed in a single class.",INVALID_TOKEN:"@Inject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined."},D=Symbol("UNINITIALIZED");function E(n,t){return Object.prototype.hasOwnProperty.call(n,t)}function G(n){return n!==null&&typeof n=="object"}const O=new WeakMap,y=new WeakMap;function A(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function j(n,t){O.set(n,t),y.delete(n)}function w(n){const t=O.get(n);if(t)return t[l.POST_CONSTRUCT];if(A(n))return w(Object.getPrototypeOf(n))}function V(n){const t=O.get(n);if(t)return t[l.PRE_DESTROY];if(A(n))return V(Object.getPrototypeOf(n))}function R(n){if(y.has(n)){const e=y.get(n);return e&&Object.assign({},e)}const t=K(n);return y.set(n,t),t&&Object.assign({},t)}function K(n){const t=O.get(n),e=t&&E(t,l.INJECTED_PROPS)?t[l.INJECTED_PROPS]:void 0;if(!A(n))return e;const i=R(Object.getPrototypeOf(n));if(i||e)return Object.assign({},i,e)}class ${constructor(t){r(this,"name");this.name=t}}class L{constructor(t){r(this,"_callback");this._callback=t}resolve(){return this._callback()}}function m(n){if(!n)throw new Error(C.INVALID_TOKEN);return n instanceof L?n.resolve():n}class _ extends Error{constructor(e,i){const s=(i==null?void 0:i.name)||"<unknown token>";super(`${e}${s}`);r(this,"token");this.name=this.constructor.name,this.token=i}}function B(n){const t=[];let e=n;for(;e&&e.token;)t.push(e.token.name||"<anonymous>"),e=e.parent;return t.reverse()}class P extends _{constructor(t){super(""),this.message="Circular dependency found: "+B(t).join(" --> ")}}class M extends _{constructor(t){super(`Binding is incomplete: container.bind(${t==null?void 0:t.name}) was called but missing to/toSelf/toConstantValue/toDynamicValue method. `,t)}}class k extends P{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const T=class T{constructor(t,e){r(this,"container");r(this,"context");r(this,"token");r(this,"type",p.INVALID);r(this,"status",f.DEFAULT);r(this,"classValue");r(this,"constantValue");r(this,"dynamicValue");r(this,"cache");r(this,"postConstructResult",D);r(this,"transient",!1);r(this,"onActivationHandler");r(this,"onDeactivationHandler");this.container=e,this.context={container:this.container},this.token=t}onActivation(t){this.onActivationHandler=t}onDeactivation(t){this.onDeactivationHandler=t}activate(t){const e=this.onActivationHandler?this.onActivationHandler(this.context,t):t;return this.container.activate(e,this.token)}deactivate(){this.onDeactivationHandler&&this.onDeactivationHandler(this.cache)}to(t){return this.type=p.INSTANCE,this.classValue=t,this}toSelf(){return this.to(this.token)}toConstantValue(t){return this.type=p.CONSTANT,this.constantValue=t,this}toDynamicValue(t){return this.type=p.DYNAMIC,this.dynamicValue=t,this}inTransientScope(){return this.transient=!0,this}toService(t){return this.toDynamicValue(e=>e.container._resolveWithInternalOpts(t,{parent:{token:this.token}}))}get(t){if(f.INITING===this.status)throw new P(t);if(f.ACTIVATED===this.status)if(this.transient)this.status=f.DEFAULT;else return this.cache;const e=T._resolvers.get(this.type);if(e)return e.call(this,t);throw new M(this.token)}_getAwaitBindings(t,e){return e===!0?t:Array.isArray(e)?t.filter(i=>e.includes(i.token)):typeof e=="function"?t.filter(e):[]}_postConstruct(t,e){if(p.INSTANCE===this.type){const{key:i,value:s}=w(this.classValue)||{};if(i)if(s){const o=e.filter(u=>p.INSTANCE===(u==null?void 0:u.type)),a=this._getAwaitBindings(o,s);for(const u of a)if(u&&u.postConstructResult===D)throw new k({token:u.token,parent:t});const c=a.map(u=>u.postConstructResult);this.postConstructResult=Promise.all(c).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(p.INSTANCE===this.type&&this.cache!==void 0){const{key:t}=V(this.classValue)||{};t&&this._execute(t)}this.container&&!this.container._destroyed&&I._instanceContainerMap.delete(this.cache),this.container=void 0,this.context=void 0,this.classValue=void 0,this.constantValue=void 0,this.dynamicValue=void 0,this.cache=void 0,this.postConstructResult=D,this.onActivationHandler=void 0,this.onDeactivationHandler=void 0}_execute(t){const e=this.cache[t];return e==null?void 0:e.call(this.cache)}_resolveInstanceValue(t){this.status=f.INITING;const e=this._createInstance();this.cache=this.activate(e),this.status=f.ACTIVATED,this._registerInstance();const{properties:i,bindings:s}=this._getInjectProperties(t);return this._injectProperties(i),this._postConstruct(t,s),this.cache}_createInstance(){const t=this.classValue;return new t}_registerInstance(){I._instanceContainerMap.set(this.cache,this.container)}_injectProperties(t){Object.assign(this.cache,t)}_resolveConstantValue(){return this.status=f.INITING,this.cache=this.activate(this.constantValue),this.status=f.ACTIVATED,this.cache}_resolveDynamicValue(){this.status=f.INITING;const t=this.dynamicValue(this.context);return this.cache=this.activate(t),this.status=f.ACTIVATED,this.cache}_getInjectProperties(t){const e=R(this.classValue)||{},i=Object.keys(e),s=Object.create(null),o=[];for(let a=0;a<i.length;a++){const c=i[a],u=e[c],h=Object.assign({},u);h.parent=t;const d=this.container._resolveWithInternalOpts(m(h.inject),h);d===void 0&&h.optional||(s[c]=d),o.push(h.binding)}return{properties:s,bindings:o}}};r(T,"_resolvers",new Map([[p.INSTANCE,function(t){return this._resolveInstanceValue(t)}],[p.CONSTANT,function(t){return this._resolveConstantValue()}],[p.DYNAMIC,function(t){return this._resolveDynamicValue()}]]));let N=T;class H extends _{constructor(t,e){if(super("No matching binding found for token: ",t),e!=null&&e.parent){const i=B(e.parent);i.length>0&&(this.message+=`
2
- `+i.map(s=>" required by: "+s).join(`
3
- `))}}}class F extends _{constructor(t){super("Cannot bind token multiple times: ",t)}}class x extends _{constructor(t){super("Container has been destroyed. Cannot call get() for token: ",t)}}const v=class v{constructor(){r(this,"parent");r(this,"children");r(this,"_bindings",new Map);r(this,"_destroyed",!1);r(this,"_onActivationHandler");r(this,"_onDeactivationHandler")}static getContainerOf(t){return v._instanceContainerMap.get(t)}bind(t){if(this._bindings.has(t))throw new F(t);const e=this._buildBinding(t);return this._bindings.set(t,e),e}unbind(t){if(this._bindings.has(t)){const e=this._getBinding(t);this.deactivate(e),e.deactivate(),e.preDestroy(),this._bindings.delete(t)}}tryGet(t){return this.get(t,{optional:!0})}rebind(t){return this._bindings.has(t)&&this.unbind(t),this.bind(t)}unbindAll(){const t=Array.from(this._bindings.keys());for(const e of t)this.unbind(e)}isCurrentBound(t){return this._bindings.has(t)}isBound(t){return this.isCurrentBound(t)||!!this.parent&&this.parent.isBound(t)}createChild(){const t=new v;return t.parent=this,this.children||(this.children=new Set),this.children.add(t),t}destroy(){var t,e;if(this._destroyed=!0,this.children){const i=Array.from(this.children);for(const s of i)s.destroy()}this.unbindAll(),this._bindings.clear(),(e=(t=this.parent)==null?void 0:t.children)==null||e.delete(this),this.parent=void 0,this.children=void 0,this._onActivationHandler=void 0,this._onDeactivationHandler=void 0}get(t,e={}){const i=Object.assign({},e);return this._resolveWithInternalOpts(t,i)}getAsync(t,e={}){const i=Object.assign({},e);let s;try{s=this._resolveWithInternalOpts(t,i)}catch(a){return Promise.reject(a)}const o=i.binding;return(o==null?void 0:o.postConstructResult)instanceof Promise?o.postConstructResult.then(()=>s):Promise.resolve(s)}_resolveWithInternalOpts(t,e){if(this._destroyed)throw new x(t);return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}_resolveSkipSelf(t,e){if(this.parent){const i=Object.assign({},e,{skipSelf:!1});return this.parent._resolveWithInternalOpts(t,i)}return this._checkBindingNotFoundError(t,e)}_resolveSelf(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this._checkBindingNotFoundError(t,e)}_resolveDefault(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this.parent?this.parent._resolveWithInternalOpts(t,e):this._checkBindingNotFoundError(t,e)}onActivation(t){this._onActivationHandler=t}onDeactivation(t){this._onDeactivationHandler=t}activate(t,e){return this._onActivationHandler?this._onActivationHandler({container:this},t,e):t}deactivate(t){this._onDeactivationHandler&&this._onDeactivationHandler(t.cache,t.token)}_buildBinding(t){return new N(t,this)}_getBinding(t){return this._bindings.get(t)}_checkBindingNotFoundError(t,e){if(!e.optional)throw new H(t,e)}};r(v,"_instanceContainerMap",new WeakMap);let I=v;class z extends _{constructor(t,e){super(`@LazyInject(${t==null?void 0:t.name}) in class ${e.name} requires a registered container but none was found. Token: `,t)}}function b(n,t){return function(e){return function(i,s){const o=s.name,a=s.metadata;E(a,l.INJECTED_PROPS)||(a[l.INJECTED_PROPS]={});const c=a[l.INJECTED_PROPS];c[o]||(c[o]={}),c[o][n]=e===void 0?t:e}}}function W(n,t){return e=>(i,s)=>{const o=s.name,a=s.metadata;if(E(a,n))throw new Error(t);a[n]={key:o,value:e}}}const q=b(l.INJECT),Z=b(l.SELF,!0),Q=b(l.SKIP_SELF,!0),X=b(l.OPTIONAL,!0),tt=W(l.POST_CONSTRUCT,C.POST_CONSTRUCT),et=W(l.PRE_DESTROY,C.PRE_DESTROY);function nt(){return function(n,t){const e=t.metadata;j(n,e)}}function it(n,t,e,i){if(e==null)throw new Error(C.LAZY_INJECT_INVALID_TOKEN);let s,o=!1;Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!o){const a=i||I.getContainerOf(n),c=n.constructor;if(!a)throw new z(m(e),c);s=a._resolveWithInternalOpts(m(e),{parent:{token:c}}),o=!0}return s},set(a){s=a,o=!0}})}function U(n,t){return function(e,i){const s=i.name;i.addInitializer(function(){it(this,s,n,t)})}}function st(n){return function(t){return U(t,n)}}function rt(n,t){const e=t.name;t.addInitializer(function(){this[e]=n.bind(this)})}const S=new WeakMap;function ot(n,t,e){const i=Array.isArray(n)?n:[n],s=t.prototype,o=typeof s[e]=="function",a=[];S.has(t)||S.set(t,{});const c=S.get(t),u={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(d){a.push(d)},metadata:c};let h=o?s[e]:void 0;for(let d=i.length-1;d>=0;d--){const g=i[d](h,u);o&&typeof g=="function"&&(h=g)}if(o&&h!==s[e]&&(s[e]=h),j(t,c),a.length>0){const d=Object.create(s);for(const g of a)g.call(d)}}exports.BaseError=_;exports.Binding=N;exports.BindingNotFoundError=H;exports.BindingNotValidError=M;exports.CircularDependencyError=P;exports.Container=I;exports.ContainerDestroyedError=x;exports.ContainerNotFoundError=z;exports.DuplicateBindingError=F;exports.ERRORS=C;exports.Inject=q;exports.Injectable=nt;exports.LazyInject=U;exports.LazyToken=L;exports.Optional=X;exports.PostConstruct=tt;exports.PostConstructError=k;exports.PreDestroy=et;exports.Self=Z;exports.SkipSelf=Q;exports.Token=$;exports.autobind=rt;exports.createLazyInject=st;exports.decorate=ot;exports.hasOwn=E;exports.isObject=G;
1
+ "use strict";var U=Object.defineProperty;var W=(n,t,e)=>t in n?U(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var s=(n,t,e)=>W(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l={INJECTED_PROPS:"injected:props",INJECT:"inject",SELF:"self",SKIP_SELF:"skipSelf",OPTIONAL:"optional",POST_CONSTRUCT:"postConstruct",PRE_DESTROY:"preDestroy"},d={DEFAULT:"default",INITING:"initing",ACTIVATED:"activated"},f={INVALID:"Invalid",INSTANCE:"Instance",CONSTANT:"ConstantValue",DYNAMIC:"DynamicValue"},I={POST_CONSTRUCT:"Multiple @PostConstruct decorators are not allowed in a single class.",PRE_DESTROY:"Multiple @PreDestroy decorators are not allowed in a single class.",INVALID_TOKEN:"@Inject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined.",DECORATE_NOT_SUPPORT_INITIALIZER:"decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject, @autobind)."},b=Symbol("UNINITIALIZED");function C(n,t){return Object.prototype.hasOwnProperty.call(n,t)}function Y(n){return n!==null&&typeof n=="object"}const y=new WeakMap;function P(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function A(n,t){y.set(n,{metadata:t})}function j(n,t){const e=y.get(t);if(e)return C(e.metadata,n)?e.metadata[n]:void 0}function T(n,t){const e=y.get(t);if(e&&C(e.metadata,n))return e.metadata[n];if(P(t))return T(n,Object.getPrototypeOf(t))}function w(n){const t=y.get(n);if(t&&t.injectedPropsCache!==void 0){const i=t.injectedPropsCache;return i?Object.assign({},i):void 0}const e=J(n);return t&&(t.injectedPropsCache=e??null),e&&Object.assign({},e)}function J(n){const t=j(l.INJECTED_PROPS,n);if(!P(n))return t;const e=w(Object.getPrototypeOf(n));if(e||t)return Object.assign({},e,t)}class G{constructor(t){s(this,"name");this.name=t}}class V{constructor(t){s(this,"_callback");this._callback=t}resolve(){return this._callback()}}function S(n){if(!n)throw new Error(I.INVALID_TOKEN);return n instanceof V?n.resolve():n}class p extends Error{constructor(e,i){const r=(i==null?void 0:i.name)||"<unknown token>";super(`${e}${r}`);s(this,"token");this.name=this.constructor.name,this.token=i}}function R(n){const t=[];let e=n;for(;e&&e.token;)t.push(e.token.name||"<anonymous>"),e=e.parent;return t.reverse()}class m extends p{constructor(t){super(""),this.message="Circular dependency found: "+R(t).join(" --> ")}}class L extends p{constructor(t){super(`Binding is incomplete: container.bind(${t==null?void 0:t.name}) was called but missing to/toSelf/toConstantValue/toDynamicValue method. `,t)}}class B extends m{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const N=class N{constructor(t,e){s(this,"container");s(this,"context");s(this,"token");s(this,"type",f.INVALID);s(this,"status",d.DEFAULT);s(this,"classValue");s(this,"constantValue");s(this,"dynamicValue");s(this,"cache");s(this,"postConstructResult",b);s(this,"transient",!1);s(this,"onActivationHandler");s(this,"onDeactivationHandler");this.container=e,this.context={container:this.container},this.token=t}onActivation(t){this.onActivationHandler=t}onDeactivation(t){this.onDeactivationHandler=t}activate(t){const e=this.onActivationHandler?this.onActivationHandler(this.context,t):t;return this.container.activate(e,this.token)}deactivate(){this.onDeactivationHandler&&this.onDeactivationHandler(this.cache)}to(t){return this.type=f.INSTANCE,this.classValue=t,this}toSelf(){return this.to(this.token)}toConstantValue(t){return this.type=f.CONSTANT,this.constantValue=t,this}toDynamicValue(t){return this.type=f.DYNAMIC,this.dynamicValue=t,this}inTransientScope(){return this.transient=!0,this}toService(t){return this.toDynamicValue(e=>e.container._resolveWithInternalOpts(t,{parent:{token:this.token}}))}get(t){if(d.INITING===this.status)throw new m(t);if(d.ACTIVATED===this.status)if(this.transient)this.status=d.DEFAULT;else return this.cache;const e=N._resolvers.get(this.type);if(e)return e.call(this,t);throw new L(this.token)}_getAwaitBindings(t,e){return e===!0?t:Array.isArray(e)?t.filter(i=>e.includes(i.token)):typeof e=="function"?t.filter(e):[]}_postConstruct(t,e){if(f.INSTANCE===this.type){const{key:i,value:r}=T(l.POST_CONSTRUCT,this.classValue)||{};if(i)if(r){const a=e.filter(c=>f.INSTANCE===(c==null?void 0:c.type)),o=this._getAwaitBindings(a,r);for(const c of o)if(c&&c.postConstructResult===b)throw new B({token:c.token,parent:t});const u=o.map(c=>c.postConstructResult);this.postConstructResult=Promise.all(u).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(f.INSTANCE===this.type&&this.cache!==void 0){const{key:t}=T(l.PRE_DESTROY,this.classValue)||{};t&&this._execute(t)}this.container&&!this.container._destroyed&&_._instanceContainerMap.delete(this.cache),this.container=void 0,this.context=void 0,this.classValue=void 0,this.constantValue=void 0,this.dynamicValue=void 0,this.cache=void 0,this.postConstructResult=b,this.onActivationHandler=void 0,this.onDeactivationHandler=void 0}_execute(t){const e=this.cache[t];return e==null?void 0:e.call(this.cache)}_resolveInstanceValue(t){this.status=d.INITING;const e=this._createInstance();this.cache=this.activate(e),this.status=d.ACTIVATED,this._registerInstance();const{properties:i,bindings:r}=this._getInjectProperties(t);return this._injectProperties(i),this._postConstruct(t,r),this.cache}_createInstance(){const t=this.classValue;return new t}_registerInstance(){_._instanceContainerMap.set(this.cache,this.container)}_injectProperties(t){Object.assign(this.cache,t)}_resolveConstantValue(){return this.status=d.INITING,this.cache=this.activate(this.constantValue),this.status=d.ACTIVATED,this.cache}_resolveDynamicValue(){this.status=d.INITING;const t=this.dynamicValue(this.context);return this.cache=this.activate(t),this.status=d.ACTIVATED,this.cache}_getInjectProperties(t){const e=w(this.classValue)||{},i=Object.keys(e),r=Object.create(null),a=[];for(let o=0;o<i.length;o++){const u=i[o],c=e[u],h=Object.assign({},c);h.parent=t;const v=this.container._resolveWithInternalOpts(S(h.inject),h);v===void 0&&h.optional||(r[u]=v),a.push(h.binding)}return{properties:r,bindings:a}}};s(N,"_resolvers",new Map([[f.INSTANCE,function(t){return this._resolveInstanceValue(t)}],[f.CONSTANT,function(t){return this._resolveConstantValue()}],[f.DYNAMIC,function(t){return this._resolveDynamicValue()}]]));let E=N;class M extends p{constructor(t,e){if(super("No matching binding found for token: ",t),e!=null&&e.parent){const i=R(e.parent);i.length>0&&(this.message+=`
2
+ `+i.map(r=>" required by: "+r).join(`
3
+ `))}}}class H extends p{constructor(t){super("Cannot bind token multiple times: ",t)}}class F extends p{constructor(t){super("Container has been destroyed. Cannot call get() for token: ",t)}}const g=class g{constructor(){s(this,"parent");s(this,"_children");s(this,"_bindings",new Map);s(this,"_destroyed",!1);s(this,"_onActivationHandler");s(this,"_onDeactivationHandler")}static getContainerOf(t){return g._instanceContainerMap.get(t)}bind(t){if(this._bindings.has(t))throw new H(t);const e=this._buildBinding(t);return this._bindings.set(t,e),e}unbind(t){if(this._bindings.has(t)){const e=this._getBinding(t);this.deactivate(e),e.deactivate(),e.preDestroy(),this._bindings.delete(t)}}tryGet(t){return this.get(t,{optional:!0})}rebind(t){return this._bindings.has(t)&&this.unbind(t),this.bind(t)}unbindAll(){const t=Array.from(this._bindings.keys());for(const e of t)this.unbind(e)}isCurrentBound(t){return this._bindings.has(t)}isBound(t){return this.isCurrentBound(t)||!!this.parent&&this.parent.isBound(t)}createChild(){const t=new g;return t.parent=this,this._children||(this._children=new Set),this._children.add(t),t}getChildren(){return this._children}destroy(){var t,e;if(this._destroyed=!0,this._children){const i=Array.from(this._children);for(const r of i)r.destroy()}this.unbindAll(),this._bindings.clear(),(e=(t=this.parent)==null?void 0:t._children)==null||e.delete(this),this.parent=void 0,this._children=void 0,this._onActivationHandler=void 0,this._onDeactivationHandler=void 0}get(t,e={}){const i=Object.assign({},e);return this._resolveWithInternalOpts(t,i)}getAsync(t,e={}){const i=Object.assign({},e);let r;try{r=this._resolveWithInternalOpts(t,i)}catch(o){return Promise.reject(o)}const a=i.binding;return(a==null?void 0:a.postConstructResult)instanceof Promise?a.postConstructResult.then(()=>r):Promise.resolve(r)}_resolveWithInternalOpts(t,e){if(this._destroyed)throw new F(t);return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}_resolveSkipSelf(t,e){if(this.parent){const i=Object.assign({},e,{skipSelf:!1});return this.parent._resolveWithInternalOpts(t,i)}return this._checkBindingNotFoundError(t,e)}_resolveSelf(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this._checkBindingNotFoundError(t,e)}_resolveDefault(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this.parent?this.parent._resolveWithInternalOpts(t,e):this._checkBindingNotFoundError(t,e)}onActivation(t){this._onActivationHandler=t}onDeactivation(t){this._onDeactivationHandler=t}activate(t,e){return this._onActivationHandler?this._onActivationHandler({container:this},t,e):t}deactivate(t){this._onDeactivationHandler&&this._onDeactivationHandler(t.cache,t.token)}_buildBinding(t){return new E(t,this)}_getBinding(t){return this._bindings.get(t)}_checkBindingNotFoundError(t,e){if(!e.optional)throw new M(t,e)}};s(g,"_instanceContainerMap",new WeakMap);let _=g;class k extends p{constructor(t,e){super(`@LazyInject(${t==null?void 0:t.name}) in class ${e.name} requires a registered container but none was found. Token: `,t)}}function O(n,t){return function(e){return function(i,r){const a=r.name,o=r.metadata;C(o,l.INJECTED_PROPS)||(o[l.INJECTED_PROPS]={});const u=o[l.INJECTED_PROPS];u[a]||(u[a]={}),u[a][n]=e===void 0?t:e}}}function x(n,t){return e=>(i,r)=>{const a=r.name,o=r.metadata;if(C(o,n))throw new Error(t);o[n]={key:a,value:e}}}const K=O(l.INJECT),Z=O(l.SELF,!0),$=O(l.SKIP_SELF,!0),q=O(l.OPTIONAL,!0),Q=x(l.POST_CONSTRUCT,I.POST_CONSTRUCT),X=x(l.PRE_DESTROY,I.PRE_DESTROY);function tt(){return function(n,t){const e=t.metadata;A(n,e)}}function et(n,t,e,i){if(e==null)throw new Error(I.LAZY_INJECT_INVALID_TOKEN);let r,a=!1;Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!a){const o=i||_.getContainerOf(n),u=n.constructor;if(!o)throw new k(S(e),u);r=o._resolveWithInternalOpts(S(e),{parent:{token:u}}),a=!0}return r},set(o){r=o,a=!0}})}function z(n,t){return function(e,i){const r=i.name;i.addInitializer(function(){et(this,r,n,t)})}}function nt(n){return function(t){return z(t,n)}}function it(n,t){const e=t.name;t.addInitializer(function(){this[e]=n.bind(this)})}const D=new WeakMap;function rt(n,t,e){const i=Array.isArray(n)?n:[n],r=t.prototype,a=typeof r[e]=="function";D.has(t)||D.set(t,{});const o=D.get(t),u={kind:a?"method":"field",name:e,static:!1,private:!1,addInitializer(h){throw new Error(I.DECORATE_NOT_SUPPORT_INITIALIZER)},metadata:o};let c=a?r[e]:void 0;for(let h=i.length-1;h>=0;h--){const v=i[h](c,u);a&&typeof v=="function"&&(c=v)}a&&c!==r[e]&&(r[e]=c),A(t,o)}exports.BaseError=p;exports.Binding=E;exports.BindingNotFoundError=M;exports.BindingNotValidError=L;exports.CircularDependencyError=m;exports.Container=_;exports.ContainerDestroyedError=F;exports.ContainerNotFoundError=k;exports.DuplicateBindingError=H;exports.ERRORS=I;exports.Inject=K;exports.Injectable=tt;exports.LazyInject=z;exports.LazyToken=V;exports.Optional=q;exports.PostConstruct=Q;exports.PostConstructError=B;exports.PreDestroy=X;exports.Self=Z;exports.SkipSelf=$;exports.Token=G;exports.autobind=it;exports.createLazyInject=nt;exports.decorate=rt;exports.defineMetadata=A;exports.getMetadata=T;exports.getOwnMetadata=j;exports.hasOwn=C;exports.isObject=Y;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
1
+ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, BindingActivationHandler, DeactivationHandler, BindingDeactivationHandler, PostConstructParam, } from './interfaces';
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
@@ -12,3 +12,4 @@ export { PostConstructError } from './errors/PostConstructError';
12
12
  export { ContainerNotFoundError } from './errors/ContainerNotFoundError';
13
13
  export { ContainerDestroyedError } from './errors/ContainerDestroyedError';
14
14
  export { hasOwn, isObject, ERRORS } from './constants';
15
+ export { defineMetadata, getOwnMetadata, getMetadata } from './cachemap';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
1
+ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, BindingActivationHandler, DeactivationHandler, BindingDeactivationHandler, PostConstructParam, } from './interfaces';
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
@@ -12,3 +12,4 @@ export { PostConstructError } from './errors/PostConstructError';
12
12
  export { ContainerNotFoundError } from './errors/ContainerNotFoundError';
13
13
  export { ContainerDestroyedError } from './errors/ContainerDestroyedError';
14
14
  export { hasOwn, isObject, ERRORS } from './constants';
15
+ export { defineMetadata, getOwnMetadata, getMetadata } from './cachemap';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- var M = Object.defineProperty;
2
- var H = (n, t, e) => t in n ? M(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var r = (n, t, e) => H(n, typeof t != "symbol" ? t + "" : t, e);
1
+ var R = Object.defineProperty;
2
+ var L = (n, t, e) => t in n ? R(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var r = (n, t, e) => L(n, typeof t != "symbol" ? t + "" : t, e);
4
4
  const l = {
5
5
  // 记录实例属性装饰器对应的数据的键
6
6
  INJECTED_PROPS: "injected:props",
@@ -16,11 +16,11 @@ const l = {
16
16
  POST_CONSTRUCT: "postConstruct",
17
17
  // PreDestroy 装饰器的键
18
18
  PRE_DESTROY: "preDestroy"
19
- }, f = {
19
+ }, d = {
20
20
  DEFAULT: "default",
21
21
  INITING: "initing",
22
22
  ACTIVATED: "activated"
23
- }, p = {
23
+ }, f = {
24
24
  INVALID: "Invalid",
25
25
  INSTANCE: "Instance",
26
26
  CONSTANT: "ConstantValue",
@@ -32,50 +32,51 @@ const l = {
32
32
  // 用于 token.ts 的 resolveToken —— 无效 token
33
33
  INVALID_TOKEN: "@Inject requires a valid token, but received null or undefined.",
34
34
  // 用于 decorator.ts 的 defineLazyProperty —— 无效 token
35
- LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined."
36
- }, E = Symbol("UNINITIALIZED");
37
- function A(n, t) {
35
+ LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined.",
36
+ // 用于 decorator.ts 的 decorate —— 不支持 addInitializer 的装饰器
37
+ DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject, @autobind)."
38
+ }, O = Symbol("UNINITIALIZED");
39
+ function g(n, t) {
38
40
  return Object.prototype.hasOwnProperty.call(n, t);
39
41
  }
40
- function q(n) {
42
+ function K(n) {
41
43
  return n !== null && typeof n == "object";
42
44
  }
43
- const y = /* @__PURE__ */ new WeakMap(), g = /* @__PURE__ */ new WeakMap();
44
- function S(n) {
45
+ const N = /* @__PURE__ */ new WeakMap();
46
+ function D(n) {
45
47
  return typeof n == "function" && Object.getPrototypeOf(n) !== Function.prototype;
46
48
  }
47
- function P(n, t) {
48
- y.set(n, t), g.delete(n);
49
+ function S(n, t) {
50
+ N.set(n, { metadata: t });
49
51
  }
50
- function w(n) {
51
- const t = y.get(n);
52
- if (t)
53
- return t[l.POST_CONSTRUCT];
54
- if (S(n))
55
- return w(Object.getPrototypeOf(n));
52
+ function M(n, t) {
53
+ const e = N.get(t);
54
+ if (e)
55
+ return g(e.metadata, n) ? e.metadata[n] : void 0;
56
56
  }
57
- function V(n) {
58
- const t = y.get(n);
59
- if (t)
60
- return t[l.PRE_DESTROY];
61
- if (S(n))
62
- return V(Object.getPrototypeOf(n));
57
+ function b(n, t) {
58
+ const e = N.get(t);
59
+ if (e && g(e.metadata, n))
60
+ return e.metadata[n];
61
+ if (D(t))
62
+ return b(n, Object.getPrototypeOf(t));
63
63
  }
64
- function j(n) {
65
- if (g.has(n)) {
66
- const e = g.get(n);
67
- return e && Object.assign({}, e);
68
- }
69
- const t = k(n);
70
- return g.set(n, t), t && Object.assign({}, t);
64
+ function P(n) {
65
+ const t = N.get(n);
66
+ if (t && t.injectedPropsCache !== void 0) {
67
+ const i = t.injectedPropsCache;
68
+ return i ? Object.assign({}, i) : void 0;
69
+ }
70
+ const e = B(n);
71
+ return t && (t.injectedPropsCache = e ?? null), e && Object.assign({}, e);
71
72
  }
72
- function k(n) {
73
- const t = y.get(n), e = t && A(t, l.INJECTED_PROPS) ? t[l.INJECTED_PROPS] : void 0;
74
- if (!S(n))
75
- return e;
76
- const i = j(Object.getPrototypeOf(n));
77
- if (i || e)
78
- return Object.assign({}, i, e);
73
+ function B(n) {
74
+ const t = M(l.INJECTED_PROPS, n);
75
+ if (!D(n))
76
+ return t;
77
+ const e = P(Object.getPrototypeOf(n));
78
+ if (e || t)
79
+ return Object.assign({}, e, t);
79
80
  }
80
81
  class Z {
81
82
  constructor(t) {
@@ -84,7 +85,7 @@ class Z {
84
85
  this.name = t;
85
86
  }
86
87
  }
87
- class x {
88
+ class H {
88
89
  constructor(t) {
89
90
  r(this, "_callback");
90
91
  this._callback = t;
@@ -93,12 +94,12 @@ class x {
93
94
  return this._callback();
94
95
  }
95
96
  }
96
- function D(n) {
97
+ function A(n) {
97
98
  if (!n)
98
99
  throw new Error(T.INVALID_TOKEN);
99
- return n instanceof x ? n.resolve() : n;
100
+ return n instanceof H ? n.resolve() : n;
100
101
  }
101
- class _ extends Error {
102
+ class p extends Error {
102
103
  constructor(e, i) {
103
104
  const s = (i == null ? void 0 : i.name) || "<unknown token>";
104
105
  super(`${e}${s}`);
@@ -106,19 +107,19 @@ class _ extends Error {
106
107
  this.name = this.constructor.name, this.token = i;
107
108
  }
108
109
  }
109
- function R(n) {
110
+ function w(n) {
110
111
  const t = [];
111
112
  let e = n;
112
113
  for (; e && e.token; )
113
114
  t.push(e.token.name || "<anonymous>"), e = e.parent;
114
115
  return t.reverse();
115
116
  }
116
- class L extends _ {
117
+ class V extends p {
117
118
  constructor(t) {
118
- super(""), this.message = "Circular dependency found: " + R(t).join(" --> ");
119
+ super(""), this.message = "Circular dependency found: " + w(t).join(" --> ");
119
120
  }
120
121
  }
121
- class F extends _ {
122
+ class x extends p {
122
123
  constructor(t) {
123
124
  super(
124
125
  `Binding is incomplete: container.bind(${t == null ? void 0 : t.name}) was called but missing to/toSelf/toConstantValue/toDynamicValue method. `,
@@ -126,23 +127,23 @@ class F extends _ {
126
127
  );
127
128
  }
128
129
  }
129
- class W extends L {
130
+ class F extends V {
130
131
  constructor(t) {
131
132
  super(t), this.name = "CircularDependencyError inside @PostConstruct";
132
133
  }
133
134
  }
134
- const N = class N {
135
+ const C = class C {
135
136
  constructor(t, e) {
136
137
  r(this, "container");
137
138
  r(this, "context");
138
139
  r(this, "token");
139
- r(this, "type", p.INVALID);
140
- r(this, "status", f.DEFAULT);
140
+ r(this, "type", f.INVALID);
141
+ r(this, "status", d.DEFAULT);
141
142
  r(this, "classValue");
142
143
  r(this, "constantValue");
143
144
  r(this, "dynamicValue");
144
145
  r(this, "cache");
145
- r(this, "postConstructResult", E);
146
+ r(this, "postConstructResult", O);
146
147
  // 是否为瞬态作用域,默认 false(单例)
147
148
  r(this, "transient", !1);
148
149
  r(this, "onActivationHandler");
@@ -163,16 +164,16 @@ const N = class N {
163
164
  this.onDeactivationHandler && this.onDeactivationHandler(this.cache);
164
165
  }
165
166
  to(t) {
166
- return this.type = p.INSTANCE, this.classValue = t, this;
167
+ return this.type = f.INSTANCE, this.classValue = t, this;
167
168
  }
168
169
  toSelf() {
169
170
  return this.to(this.token);
170
171
  }
171
172
  toConstantValue(t) {
172
- return this.type = p.CONSTANT, this.constantValue = t, this;
173
+ return this.type = f.CONSTANT, this.constantValue = t, this;
173
174
  }
174
175
  toDynamicValue(t) {
175
- return this.type = p.DYNAMIC, this.dynamicValue = t, this;
176
+ return this.type = f.DYNAMIC, this.dynamicValue = t, this;
176
177
  }
177
178
  inTransientScope() {
178
179
  return this.transient = !0, this;
@@ -183,17 +184,17 @@ const N = class N {
183
184
  );
184
185
  }
185
186
  get(t) {
186
- if (f.INITING === this.status)
187
- throw new L(t);
188
- if (f.ACTIVATED === this.status)
187
+ if (d.INITING === this.status)
188
+ throw new V(t);
189
+ if (d.ACTIVATED === this.status)
189
190
  if (this.transient)
190
- this.status = f.DEFAULT;
191
+ this.status = d.DEFAULT;
191
192
  else
192
193
  return this.cache;
193
- const e = N._resolvers.get(this.type);
194
+ const e = C._resolvers.get(this.type);
194
195
  if (e)
195
196
  return e.call(this, t);
196
- throw new F(this.token);
197
+ throw new x(this.token);
197
198
  }
198
199
  _getAwaitBindings(t, e) {
199
200
  return e === !0 ? t : Array.isArray(e) ? t.filter((i) => e.includes(i.token)) : typeof e == "function" ? t.filter(e) : [];
@@ -212,21 +213,21 @@ const N = class N {
212
213
  * - 如果前置服务初始化失败,rejected promise 自然传播,当前服务的 PostConstruct 不执行
213
214
  */
214
215
  _postConstruct(t, e) {
215
- if (p.INSTANCE === this.type) {
216
- const { key: i, value: s } = w(this.classValue) || {};
216
+ if (f.INSTANCE === this.type) {
217
+ const { key: i, value: s } = b(l.POST_CONSTRUCT, this.classValue) || {};
217
218
  if (i)
218
219
  if (s) {
219
- const o = e.filter(
220
- (u) => p.INSTANCE === (u == null ? void 0 : u.type)
221
- ), a = this._getAwaitBindings(o, s);
222
- for (const u of a)
223
- if (u && u.postConstructResult === E)
224
- throw new W({
225
- token: u.token,
220
+ const a = e.filter(
221
+ (c) => f.INSTANCE === (c == null ? void 0 : c.type)
222
+ ), o = this._getAwaitBindings(a, s);
223
+ for (const c of o)
224
+ if (c && c.postConstructResult === O)
225
+ throw new F({
226
+ token: c.token,
226
227
  parent: t
227
228
  });
228
- const c = a.map((u) => u.postConstructResult);
229
- this.postConstructResult = Promise.all(c).then(
229
+ const u = o.map((c) => c.postConstructResult);
230
+ this.postConstructResult = Promise.all(u).then(
230
231
  () => this._execute(i)
231
232
  );
232
233
  } else
@@ -236,20 +237,20 @@ const N = class N {
236
237
  }
237
238
  }
238
239
  preDestroy() {
239
- if (p.INSTANCE === this.type && this.cache !== void 0) {
240
- const { key: t } = V(this.classValue) || {};
240
+ if (f.INSTANCE === this.type && this.cache !== void 0) {
241
+ const { key: t } = b(l.PRE_DESTROY, this.classValue) || {};
241
242
  t && this._execute(t);
242
243
  }
243
- this.container && !this.container._destroyed && v._instanceContainerMap.delete(this.cache), this.container = void 0, this.context = void 0, this.classValue = void 0, this.constantValue = void 0, this.dynamicValue = void 0, this.cache = void 0, this.postConstructResult = E, this.onActivationHandler = void 0, this.onDeactivationHandler = void 0;
244
+ this.container && !this.container._destroyed && v._instanceContainerMap.delete(this.cache), this.container = void 0, this.context = void 0, this.classValue = void 0, this.constantValue = void 0, this.dynamicValue = void 0, this.cache = void 0, this.postConstructResult = O, this.onActivationHandler = void 0, this.onDeactivationHandler = void 0;
244
245
  }
245
246
  _execute(t) {
246
247
  const e = this.cache[t];
247
248
  return e == null ? void 0 : e.call(this.cache);
248
249
  }
249
250
  _resolveInstanceValue(t) {
250
- this.status = f.INITING;
251
+ this.status = d.INITING;
251
252
  const e = this._createInstance();
252
- this.cache = this.activate(e), this.status = f.ACTIVATED, this._registerInstance();
253
+ this.cache = this.activate(e), this.status = d.ACTIVATED, this._registerInstance();
253
254
  const { properties: i, bindings: s } = this._getInjectProperties(t);
254
255
  return this._injectProperties(i), this._postConstruct(t, s), this.cache;
255
256
  }
@@ -267,56 +268,56 @@ const N = class N {
267
268
  Object.assign(this.cache, t);
268
269
  }
269
270
  _resolveConstantValue() {
270
- return this.status = f.INITING, this.cache = this.activate(this.constantValue), this.status = f.ACTIVATED, this.cache;
271
+ return this.status = d.INITING, this.cache = this.activate(this.constantValue), this.status = d.ACTIVATED, this.cache;
271
272
  }
272
273
  _resolveDynamicValue() {
273
- this.status = f.INITING;
274
+ this.status = d.INITING;
274
275
  const t = this.dynamicValue(this.context);
275
- return this.cache = this.activate(t), this.status = f.ACTIVATED, this.cache;
276
+ return this.cache = this.activate(t), this.status = d.ACTIVATED, this.cache;
276
277
  }
277
278
  _getInjectProperties(t) {
278
- const e = j(this.classValue) || {}, i = Object.keys(e), s = /* @__PURE__ */ Object.create(null), o = [];
279
- for (let a = 0; a < i.length; a++) {
280
- const c = i[a], u = e[c], h = Object.assign({}, u);
279
+ const e = P(this.classValue) || {}, i = Object.keys(e), s = /* @__PURE__ */ Object.create(null), a = [];
280
+ for (let o = 0; o < i.length; o++) {
281
+ const u = i[o], c = e[u], h = Object.assign({}, c);
281
282
  h.parent = t;
282
- const d = this.container._resolveWithInternalOpts(
283
- D(h.inject),
283
+ const _ = this.container._resolveWithInternalOpts(
284
+ A(h.inject),
284
285
  h
285
286
  );
286
- d === void 0 && h.optional || (s[c] = d), o.push(h.binding);
287
+ _ === void 0 && h.optional || (s[u] = _), a.push(h.binding);
287
288
  }
288
- return { properties: s, bindings: o };
289
+ return { properties: s, bindings: a };
289
290
  }
290
291
  };
291
292
  // 类型到解析函数的静态映射表,直接存储函数引用,消除字符串查表和 as any 间接调用
292
- r(N, "_resolvers", /* @__PURE__ */ new Map([
293
- [p.INSTANCE, function(t) {
293
+ r(C, "_resolvers", /* @__PURE__ */ new Map([
294
+ [f.INSTANCE, function(t) {
294
295
  return this._resolveInstanceValue(t);
295
296
  }],
296
- [p.CONSTANT, function(t) {
297
+ [f.CONSTANT, function(t) {
297
298
  return this._resolveConstantValue();
298
299
  }],
299
- [p.DYNAMIC, function(t) {
300
+ [f.DYNAMIC, function(t) {
300
301
  return this._resolveDynamicValue();
301
302
  }]
302
303
  ]));
303
- let m = N;
304
- class U extends _ {
304
+ let m = C;
305
+ class U extends p {
305
306
  constructor(t, e) {
306
307
  if (super("No matching binding found for token: ", t), e != null && e.parent) {
307
- const i = R(e.parent);
308
+ const i = w(e.parent);
308
309
  i.length > 0 && (this.message += `
309
310
  ` + i.map((s) => " required by: " + s).join(`
310
311
  `));
311
312
  }
312
313
  }
313
314
  }
314
- class Y extends _ {
315
+ class k extends p {
315
316
  constructor(t) {
316
317
  super("Cannot bind token multiple times: ", t);
317
318
  }
318
319
  }
319
- class z extends _ {
320
+ class z extends p {
320
321
  constructor(t) {
321
322
  super("Container has been destroyed. Cannot call get() for token: ", t);
322
323
  }
@@ -324,7 +325,7 @@ class z extends _ {
324
325
  const I = class I {
325
326
  constructor() {
326
327
  r(this, "parent");
327
- r(this, "children");
328
+ r(this, "_children");
328
329
  r(this, "_bindings", /* @__PURE__ */ new Map());
329
330
  r(this, "_destroyed", !1);
330
331
  r(this, "_onActivationHandler");
@@ -336,7 +337,7 @@ const I = class I {
336
337
  }
337
338
  bind(t) {
338
339
  if (this._bindings.has(t))
339
- throw new Y(t);
340
+ throw new k(t);
340
341
  const e = this._buildBinding(t);
341
342
  return this._bindings.set(t, e), e;
342
343
  }
@@ -365,16 +366,19 @@ const I = class I {
365
366
  }
366
367
  createChild() {
367
368
  const t = new I();
368
- return t.parent = this, this.children || (this.children = /* @__PURE__ */ new Set()), this.children.add(t), t;
369
+ return t.parent = this, this._children || (this._children = /* @__PURE__ */ new Set()), this._children.add(t), t;
370
+ }
371
+ getChildren() {
372
+ return this._children;
369
373
  }
370
374
  destroy() {
371
375
  var t, e;
372
- if (this._destroyed = !0, this.children) {
373
- const i = Array.from(this.children);
376
+ if (this._destroyed = !0, this._children) {
377
+ const i = Array.from(this._children);
374
378
  for (const s of i)
375
379
  s.destroy();
376
380
  }
377
- this.unbindAll(), this._bindings.clear(), (e = (t = this.parent) == null ? void 0 : t.children) == null || e.delete(this), this.parent = void 0, this.children = void 0, this._onActivationHandler = void 0, this._onDeactivationHandler = void 0;
381
+ this.unbindAll(), this._bindings.clear(), (e = (t = this.parent) == null ? void 0 : t._children) == null || e.delete(this), this.parent = void 0, this._children = void 0, this._onActivationHandler = void 0, this._onDeactivationHandler = void 0;
378
382
  }
379
383
  get(t, e = {}) {
380
384
  const i = Object.assign({}, e);
@@ -385,11 +389,11 @@ const I = class I {
385
389
  let s;
386
390
  try {
387
391
  s = this._resolveWithInternalOpts(t, i);
388
- } catch (a) {
389
- return Promise.reject(a);
392
+ } catch (o) {
393
+ return Promise.reject(o);
390
394
  }
391
- const o = i.binding;
392
- return (o == null ? void 0 : o.postConstructResult) instanceof Promise ? o.postConstructResult.then(() => s) : Promise.resolve(s);
395
+ const a = i.binding;
396
+ return (a == null ? void 0 : a.postConstructResult) instanceof Promise ? a.postConstructResult.then(() => s) : Promise.resolve(s);
393
397
  }
394
398
  // 内部解析入口,接受完整 Options;被 getAsync、toService、_getInjectProperties 等内部路径调用
395
399
  _resolveWithInternalOpts(t, e) {
@@ -446,7 +450,7 @@ const I = class I {
446
450
  // 由于 Instance 类型每次都通过 new ClassName() 创建新实例,不存在同一实例被多个容器注册的覆盖风险
447
451
  r(I, "_instanceContainerMap", /* @__PURE__ */ new WeakMap());
448
452
  let v = I;
449
- class J extends _ {
453
+ class W extends p {
450
454
  constructor(t, e) {
451
455
  super(
452
456
  `@LazyInject(${t == null ? void 0 : t.name}) in class ${e.name} requires a registered container but none was found. Token: `,
@@ -454,129 +458,128 @@ class J extends _ {
454
458
  );
455
459
  }
456
460
  }
457
- function O(n, t) {
461
+ function E(n, t) {
458
462
  return function(e) {
459
463
  return function(i, s) {
460
- const o = s.name, a = s.metadata;
461
- A(a, l.INJECTED_PROPS) || (a[l.INJECTED_PROPS] = {});
462
- const c = a[l.INJECTED_PROPS];
463
- c[o] || (c[o] = {}), c[o][n] = e === void 0 ? t : e;
464
+ const a = s.name, o = s.metadata;
465
+ g(o, l.INJECTED_PROPS) || (o[l.INJECTED_PROPS] = {});
466
+ const u = o[l.INJECTED_PROPS];
467
+ u[a] || (u[a] = {}), u[a][n] = e === void 0 ? t : e;
464
468
  };
465
469
  };
466
470
  }
467
- function B(n, t) {
471
+ function j(n, t) {
468
472
  return (e) => (i, s) => {
469
- const o = s.name, a = s.metadata;
470
- if (A(a, n))
473
+ const a = s.name, o = s.metadata;
474
+ if (g(o, n))
471
475
  throw new Error(t);
472
- a[n] = { key: o, value: e };
476
+ o[n] = { key: a, value: e };
473
477
  };
474
478
  }
475
- const Q = O(l.INJECT), X = O(l.SELF, !0), tt = O(l.SKIP_SELF, !0), et = O(l.OPTIONAL, !0), nt = B(
479
+ const $ = E(l.INJECT), q = E(l.SELF, !0), Q = E(l.SKIP_SELF, !0), X = E(l.OPTIONAL, !0), tt = j(
476
480
  l.POST_CONSTRUCT,
477
481
  T.POST_CONSTRUCT
478
- ), it = B(
482
+ ), et = j(
479
483
  l.PRE_DESTROY,
480
484
  T.PRE_DESTROY
481
485
  );
482
- function st() {
486
+ function nt() {
483
487
  return function(n, t) {
484
488
  const e = t.metadata;
485
- P(n, e);
489
+ S(n, e);
486
490
  };
487
491
  }
488
- function G(n, t, e, i) {
492
+ function Y(n, t, e, i) {
489
493
  if (e == null)
490
494
  throw new Error(T.LAZY_INJECT_INVALID_TOKEN);
491
- let s, o = !1;
495
+ let s, a = !1;
492
496
  Object.defineProperty(n, t, {
493
497
  configurable: !0,
494
498
  enumerable: !0,
495
499
  get() {
496
- if (!o) {
497
- const a = i || v.getContainerOf(n), c = n.constructor;
498
- if (!a)
499
- throw new J(D(e), c);
500
- s = a._resolveWithInternalOpts(D(e), {
501
- parent: { token: c }
502
- }), o = !0;
500
+ if (!a) {
501
+ const o = i || v.getContainerOf(n), u = n.constructor;
502
+ if (!o)
503
+ throw new W(A(e), u);
504
+ s = o._resolveWithInternalOpts(A(e), {
505
+ parent: { token: u }
506
+ }), a = !0;
503
507
  }
504
508
  return s;
505
509
  },
506
- set(a) {
507
- s = a, o = !0;
510
+ set(o) {
511
+ s = o, a = !0;
508
512
  }
509
513
  });
510
514
  }
511
- function K(n, t) {
515
+ function J(n, t) {
512
516
  return function(e, i) {
513
517
  const s = i.name;
514
518
  i.addInitializer(function() {
515
- G(this, s, n, t);
519
+ Y(this, s, n, t);
516
520
  });
517
521
  };
518
522
  }
519
- function rt(n) {
523
+ function it(n) {
520
524
  return function(t) {
521
- return K(t, n);
525
+ return J(t, n);
522
526
  };
523
527
  }
524
- function ot(n, t) {
528
+ function st(n, t) {
525
529
  const e = t.name;
526
530
  t.addInitializer(function() {
527
531
  this[e] = n.bind(this);
528
532
  });
529
533
  }
530
- const b = /* @__PURE__ */ new WeakMap();
531
- function at(n, t, e) {
532
- const i = Array.isArray(n) ? n : [n], s = t.prototype, o = typeof s[e] == "function", a = [];
533
- b.has(t) || b.set(t, {});
534
- const c = b.get(t), u = {
535
- kind: o ? "method" : "field",
534
+ const y = /* @__PURE__ */ new WeakMap();
535
+ function rt(n, t, e) {
536
+ const i = Array.isArray(n) ? n : [n], s = t.prototype, a = typeof s[e] == "function";
537
+ y.has(t) || y.set(t, {});
538
+ const o = y.get(t), u = {
539
+ kind: a ? "method" : "field",
536
540
  name: e,
537
541
  static: !1,
538
542
  private: !1,
539
- addInitializer(d) {
540
- a.push(d);
543
+ addInitializer(h) {
544
+ throw new Error(T.DECORATE_NOT_SUPPORT_INITIALIZER);
541
545
  },
542
- metadata: c
546
+ metadata: o
543
547
  };
544
- let h = o ? s[e] : void 0;
545
- for (let d = i.length - 1; d >= 0; d--) {
546
- const C = i[d](h, u);
547
- o && typeof C == "function" && (h = C);
548
- }
549
- if (o && h !== s[e] && (s[e] = h), P(t, c), a.length > 0) {
550
- const d = Object.create(s);
551
- for (const C of a)
552
- C.call(d);
548
+ let c = a ? s[e] : void 0;
549
+ for (let h = i.length - 1; h >= 0; h--) {
550
+ const _ = i[h](c, u);
551
+ a && typeof _ == "function" && (c = _);
553
552
  }
553
+ a && c !== s[e] && (s[e] = c), S(t, o);
554
554
  }
555
555
  export {
556
- _ as BaseError,
556
+ p as BaseError,
557
557
  m as Binding,
558
558
  U as BindingNotFoundError,
559
- F as BindingNotValidError,
560
- L as CircularDependencyError,
559
+ x as BindingNotValidError,
560
+ V as CircularDependencyError,
561
561
  v as Container,
562
562
  z as ContainerDestroyedError,
563
- J as ContainerNotFoundError,
564
- Y as DuplicateBindingError,
563
+ W as ContainerNotFoundError,
564
+ k as DuplicateBindingError,
565
565
  T as ERRORS,
566
- Q as Inject,
567
- st as Injectable,
568
- K as LazyInject,
569
- x as LazyToken,
570
- et as Optional,
571
- nt as PostConstruct,
572
- W as PostConstructError,
573
- it as PreDestroy,
574
- X as Self,
575
- tt as SkipSelf,
566
+ $ as Inject,
567
+ nt as Injectable,
568
+ J as LazyInject,
569
+ H as LazyToken,
570
+ X as Optional,
571
+ tt as PostConstruct,
572
+ F as PostConstructError,
573
+ et as PreDestroy,
574
+ q as Self,
575
+ Q as SkipSelf,
576
576
  Z as Token,
577
- ot as autobind,
578
- rt as createLazyInject,
579
- at as decorate,
580
- A as hasOwn,
581
- q as isObject
577
+ st as autobind,
578
+ it as createLazyInject,
579
+ rt as decorate,
580
+ S as defineMetadata,
581
+ b as getMetadata,
582
+ M as getOwnMetadata,
583
+ g as hasOwn,
584
+ K as isObject
582
585
  };
@@ -23,6 +23,8 @@ export interface Options<T = unknown> extends GetOptions {
23
23
  binding?: Binding<T>;
24
24
  parent?: Options<any>;
25
25
  }
26
- export type ActivationHandler<T = unknown> = (ctx: Context, input: T, token?: CommonToken<T>) => T;
27
- export type DeactivationHandler<T = unknown> = (input: T, token?: CommonToken<T>) => void;
26
+ export type ActivationHandler<T = unknown> = (ctx: Context, input: T, token: CommonToken<T>) => T;
27
+ export type BindingActivationHandler<T = unknown> = (ctx: Context, input: T) => T;
28
+ export type DeactivationHandler<T = unknown> = (input: T, token: CommonToken<T>) => void;
29
+ export type BindingDeactivationHandler<T = unknown> = (input: T) => void;
28
30
  export type PostConstructParam = void | true | CommonToken[] | ((item: Binding, index: number, arr: Binding[]) => boolean);
@@ -23,6 +23,8 @@ export interface Options<T = unknown> extends GetOptions {
23
23
  binding?: Binding<T>;
24
24
  parent?: Options<any>;
25
25
  }
26
- export type ActivationHandler<T = unknown> = (ctx: Context, input: T, token?: CommonToken<T>) => T;
27
- export type DeactivationHandler<T = unknown> = (input: T, token?: CommonToken<T>) => void;
26
+ export type ActivationHandler<T = unknown> = (ctx: Context, input: T, token: CommonToken<T>) => T;
27
+ export type BindingActivationHandler<T = unknown> = (ctx: Context, input: T) => T;
28
+ export type DeactivationHandler<T = unknown> = (input: T, token: CommonToken<T>) => void;
29
+ export type BindingDeactivationHandler<T = unknown> = (input: T) => void;
28
30
  export type PostConstructParam = void | true | CommonToken[] | ((item: Binding, index: number, arr: Binding[]) => boolean);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaokei/di",
3
- "version": "5.0.6",
3
+ "version": "5.0.8",
4
4
  "type": "module",
5
5
  "description": "Tiny di library depends on typescript decorator.",
6
6
  "main": "./dist/index.cjs",