@kaokei/di 5.0.7 → 5.0.9

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,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,7 +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
+ readonly DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject).";
33
33
  };
34
34
  export declare const UNINITIALIZED: unique symbol;
35
35
  export type BindingType = (typeof BINDING)[keyof typeof BINDING];
@@ -29,7 +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
+ readonly DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject).";
33
33
  };
34
34
  export declare const UNINITIALIZED: unique symbol;
35
35
  export type BindingType = (typeof BINDING)[keyof typeof BINDING];
@@ -1,10 +1,20 @@
1
1
  import { Binding } from './binding';
2
2
  import { GetOptions, Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
3
+ /**
4
+ * 依赖注入容器。
5
+ *
6
+ * @example 基本用法
7
+ * ```typescript
8
+ * const container = new Container();
9
+ * container.bind(MyService).toSelf();
10
+ * const myService = container.get(MyService);
11
+ * ```
12
+ */
3
13
  export declare class Container {
4
14
  static _instanceContainerMap: WeakMap<object, Container>;
5
15
  static getContainerOf(instance: object): Container | undefined;
6
16
  parent?: Container;
7
- children?: Set<Container>;
17
+ _children?: Set<Container>;
8
18
  _bindings: Map<CommonToken, Binding>;
9
19
  _destroyed: boolean;
10
20
  _onActivationHandler?: ActivationHandler;
@@ -17,6 +27,7 @@ export declare class Container {
17
27
  isCurrentBound<T>(token: CommonToken<T>): boolean;
18
28
  isBound<T>(token: CommonToken<T>): boolean;
19
29
  createChild(): Container;
30
+ getChildren(): Set<Container> | undefined;
20
31
  destroy(): void;
21
32
  get<T>(token: CommonToken<T>, options: GetOptions & {
22
33
  optional: true;
@@ -1,10 +1,20 @@
1
1
  import { Binding } from './binding';
2
2
  import { GetOptions, Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
3
+ /**
4
+ * 依赖注入容器。
5
+ *
6
+ * @example 基本用法
7
+ * ```typescript
8
+ * const container = new Container();
9
+ * container.bind(MyService).toSelf();
10
+ * const myService = container.get(MyService);
11
+ * ```
12
+ */
3
13
  export declare class Container {
4
14
  static _instanceContainerMap: WeakMap<object, Container>;
5
15
  static getContainerOf(instance: object): Container | undefined;
6
16
  parent?: Container;
7
- children?: Set<Container>;
17
+ _children?: Set<Container>;
8
18
  _bindings: Map<CommonToken, Binding>;
9
19
  _destroyed: boolean;
10
20
  _onActivationHandler?: ActivationHandler;
@@ -17,6 +27,7 @@ export declare class Container {
17
27
  isCurrentBound<T>(token: CommonToken<T>): boolean;
18
28
  isBound<T>(token: CommonToken<T>): boolean;
19
29
  createChild(): Container;
30
+ getChildren(): Set<Container> | undefined;
20
31
  destroy(): void;
21
32
  get<T>(token: CommonToken<T>, options: GetOptions & {
22
33
  optional: true;
@@ -41,18 +41,5 @@ export declare function LazyInject<T>(token: GenericToken<T>, container?: Contai
41
41
  * 创建绑定到指定容器的延迟注入装饰器工厂。
42
42
  */
43
43
  export declare function createLazyInject(container: Container): <T>(token: GenericToken<T>) => (_value: undefined, context: ClassFieldDecoratorContext) => void;
44
- /**
45
- * 方法装饰器:自动绑定方法的 this 到实例(Stage 3 Method Decorator)
46
- *
47
- * 解决方法作为回调传递时丢失 this 的问题,例如:
48
- * - Vue 模板中 `@click="service.method"` 丢失 this
49
- * - `promise.then(service.method)` 丢失 this
50
- *
51
- * 通过 context.addInitializer 在实例创建时执行 bind,
52
- * 每个实例都会拥有自己的绑定版本,互不影响。
53
- *
54
- * 使用方式:@autobind(无参数,直接作为装饰器使用)
55
- */
56
- export declare function autobind<T extends (...args: any[]) => any>(value: T, context: ClassMethodDecoratorContext): void;
57
44
  export declare function decorate(decorator: any, target: any, key: string): void;
58
45
  export {};
@@ -41,18 +41,5 @@ export declare function LazyInject<T>(token: GenericToken<T>, container?: Contai
41
41
  * 创建绑定到指定容器的延迟注入装饰器工厂。
42
42
  */
43
43
  export declare function createLazyInject(container: Container): <T>(token: GenericToken<T>) => (_value: undefined, context: ClassFieldDecoratorContext) => void;
44
- /**
45
- * 方法装饰器:自动绑定方法的 this 到实例(Stage 3 Method Decorator)
46
- *
47
- * 解决方法作为回调传递时丢失 this 的问题,例如:
48
- * - Vue 模板中 `@click="service.method"` 丢失 this
49
- * - `promise.then(service.method)` 丢失 this
50
- *
51
- * 通过 context.addInitializer 在实例创建时执行 bind,
52
- * 每个实例都会拥有自己的绑定版本,互不影响。
53
- *
54
- * 使用方式:@autobind(无参数,直接作为装饰器使用)
55
- */
56
- export declare function autobind<T extends (...args: any[]) => any>(value: T, context: ClassMethodDecoratorContext): void;
57
44
  export declare function decorate(decorator: any, target: any, key: string): void;
58
45
  export {};
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var W=Object.defineProperty;var Y=(n,t,e)=>t in n?W(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var r=(n,t,e)=>Y(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 g(n,t){return Object.prototype.hasOwnProperty.call(n,t)}function J(n){return n!==null&&typeof n=="object"}const y=new WeakMap,T=new WeakMap;function A(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function P(n,t){y.set(n,t),T.delete(n)}function j(n){const t=y.get(n);if(t)return t[l.POST_CONSTRUCT];if(A(n))return j(Object.getPrototypeOf(n))}function w(n){const t=y.get(n);if(t)return t[l.PRE_DESTROY];if(A(n))return w(Object.getPrototypeOf(n))}function V(n){if(T.has(n)){const e=T.get(n);return e&&Object.assign({},e)}const t=G(n);return T.set(n,t),t&&Object.assign({},t)}function G(n){const t=y.get(n),e=t&&g(t,l.INJECTED_PROPS)?t[l.INJECTED_PROPS]:void 0;if(!A(n))return e;const i=V(Object.getPrototypeOf(n));if(i||e)return Object.assign({},i,e)}class K{constructor(t){r(this,"name");this.name=t}}class R{constructor(t){r(this,"_callback");this._callback=t}resolve(){return this._callback()}}function S(n){if(!n)throw new Error(I.INVALID_TOKEN);return n instanceof R?n.resolve():n}class p 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 L(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: "+L(t).join(" --> ")}}class B 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 M extends m{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const N=class N{constructor(t,e){r(this,"container");r(this,"context");r(this,"token");r(this,"type",f.INVALID);r(this,"status",d.DEFAULT);r(this,"classValue");r(this,"constantValue");r(this,"dynamicValue");r(this,"cache");r(this,"postConstructResult",b);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=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 B(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:s}=j(this.classValue)||{};if(i)if(s){const o=e.filter(c=>f.INSTANCE===(c==null?void 0:c.type)),a=this._getAwaitBindings(o,s);for(const c of a)if(c&&c.postConstructResult===b)throw new M({token:c.token,parent:t});const u=a.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}=w(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:s}=this._getInjectProperties(t);return this._injectProperties(i),this._postConstruct(t,s),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=V(this.classValue)||{},i=Object.keys(e),s=Object.create(null),o=[];for(let a=0;a<i.length;a++){const u=i[a],c=e[u],h=Object.assign({},c);h.parent=t;const v=this.container._resolveWithInternalOpts(S(h.inject),h);v===void 0&&h.optional||(s[u]=v),o.push(h.binding)}return{properties:s,bindings:o}}};r(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 H extends p{constructor(t,e){if(super("No matching binding found for token: ",t),e!=null&&e.parent){const i=L(e.parent);i.length>0&&(this.message+=`
2
- `+i.map(s=>" required by: "+s).join(`
3
- `))}}}class k 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 C=class C{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 C._instanceContainerMap.get(t)}bind(t){if(this._bindings.has(t))throw new k(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 C;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 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 H(t,e)}};r(C,"_instanceContainerMap",new WeakMap);let _=C;class x 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,s){const o=s.name,a=s.metadata;g(a,l.INJECTED_PROPS)||(a[l.INJECTED_PROPS]={});const u=a[l.INJECTED_PROPS];u[o]||(u[o]={}),u[o][n]=e===void 0?t:e}}}function z(n,t){return e=>(i,s)=>{const o=s.name,a=s.metadata;if(g(a,n))throw new Error(t);a[n]={key:o,value:e}}}const Z=O(l.INJECT),$=O(l.SELF,!0),q=O(l.SKIP_SELF,!0),Q=O(l.OPTIONAL,!0),X=z(l.POST_CONSTRUCT,I.POST_CONSTRUCT),tt=z(l.PRE_DESTROY,I.PRE_DESTROY);function et(){return function(n,t){const e=t.metadata;P(n,e)}}function nt(n,t,e,i){if(e==null)throw new Error(I.LAZY_INJECT_INVALID_TOKEN);let s,o=!1;Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!o){const a=i||_.getContainerOf(n),u=n.constructor;if(!a)throw new x(S(e),u);s=a._resolveWithInternalOpts(S(e),{parent:{token:u}}),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(){nt(this,s,n,t)})}}function it(n){return function(t){return U(t,n)}}function st(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],s=t.prototype,o=typeof s[e]=="function";D.has(t)||D.set(t,{});const a=D.get(t),u={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(h){throw new Error(I.DECORATE_NOT_SUPPORT_INITIALIZER)},metadata:a};let c=o?s[e]:void 0;for(let h=i.length-1;h>=0;h--){const v=i[h](c,u);o&&typeof v=="function"&&(c=v)}o&&c!==s[e]&&(s[e]=c),P(t,a)}exports.BaseError=p;exports.Binding=E;exports.BindingNotFoundError=H;exports.BindingNotValidError=B;exports.CircularDependencyError=m;exports.Container=_;exports.ContainerDestroyedError=F;exports.ContainerNotFoundError=x;exports.DuplicateBindingError=k;exports.ERRORS=I;exports.Inject=Z;exports.Injectable=et;exports.LazyInject=U;exports.LazyToken=R;exports.Optional=Q;exports.PostConstruct=X;exports.PostConstructError=M;exports.PreDestroy=tt;exports.Self=$;exports.SkipSelf=q;exports.Token=K;exports.autobind=st;exports.createLazyInject=it;exports.decorate=rt;exports.hasOwn=g;exports.isObject=J;
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)."},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 o=e.filter(c=>f.INSTANCE===(c==null?void 0:c.type)),a=this._getAwaitBindings(o,r);for(const c of a)if(c&&c.postConstructResult===b)throw new B({token:c.token,parent:t});const u=a.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),o=[];for(let a=0;a<i.length;a++){const u=i[a],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),o.push(h.binding)}return{properties:r,bindings:o}}};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 x 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(a){return Promise.reject(a)}const o=i.binding;return(o==null?void 0:o.postConstructResult)instanceof Promise?o.postConstructResult.then(()=>r):Promise.resolve(r)}_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 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 F 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 o=r.name,a=r.metadata;C(a,l.INJECTED_PROPS)||(a[l.INJECTED_PROPS]={});const u=a[l.INJECTED_PROPS];u[o]||(u[o]={}),u[o][n]=e===void 0?t:e}}}function k(n,t){return e=>(i,r)=>{const o=r.name,a=r.metadata;if(C(a,n))throw new Error(t);a[n]={key:o,value:e}}}const K=O(l.INJECT),Z=O(l.SELF,!0),$=O(l.SKIP_SELF,!0),q=O(l.OPTIONAL,!0),Q=k(l.POST_CONSTRUCT,I.POST_CONSTRUCT),X=k(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,o=!1;Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!o){const a=i||_.getContainerOf(n),u=n.constructor;if(!a)throw new F(S(e),u);r=a._resolveWithInternalOpts(S(e),{parent:{token:u}}),o=!0}return r},set(a){r=a,o=!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)}}const D=new WeakMap;function it(n,t,e){const i=Array.isArray(n)?n:[n],r=t.prototype,o=typeof r[e]=="function";D.has(t)||D.set(t,{});const a=D.get(t),u={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(h){throw new Error(I.DECORATE_NOT_SUPPORT_INITIALIZER)},metadata:a};let c=o?r[e]:void 0;for(let h=i.length-1;h>=0;h--){const v=i[h](c,u);o&&typeof v=="function"&&(c=v)}o&&c!==r[e]&&(r[e]=c),A(t,a)}exports.BaseError=p;exports.Binding=E;exports.BindingNotFoundError=M;exports.BindingNotValidError=L;exports.CircularDependencyError=m;exports.Container=_;exports.ContainerDestroyedError=x;exports.ContainerNotFoundError=F;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.createLazyInject=nt;exports.decorate=it;exports.defineMetadata=A;exports.getMetadata=T;exports.getOwnMetadata=j;exports.hasOwn=C;exports.isObject=Y;
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, Laz
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
5
- export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, autobind, } from './decorator';
5
+ export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, } from './decorator';
6
6
  export { BaseError } from './errors/BaseError';
7
7
  export { BindingNotFoundError } from './errors/BindingNotFoundError';
8
8
  export { BindingNotValidError } from './errors/BindingNotValidError';
@@ -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
@@ -2,7 +2,7 @@ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, Laz
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
5
- export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, autobind, } from './decorator';
5
+ export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, } from './decorator';
6
6
  export { BaseError } from './errors/BaseError';
7
7
  export { BindingNotFoundError } from './errors/BindingNotFoundError';
8
8
  export { BindingNotValidError } from './errors/BindingNotValidError';
@@ -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 B = Object.defineProperty;
2
- var M = (n, t, e) => t in n ? B(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var r = (n, t, e) => M(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",
@@ -34,59 +34,58 @@ const l = {
34
34
  // 用于 decorator.ts 的 defineLazyProperty —— 无效 token
35
35
  LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined.",
36
36
  // 用于 decorator.ts 的 decorate —— 不支持 addInitializer 的装饰器
37
- DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject, @autobind)."
37
+ DECORATE_NOT_SUPPORT_INITIALIZER: "decorate does not support decorators that rely on context.addInitializer (e.g. @LazyInject)."
38
38
  }, O = Symbol("UNINITIALIZED");
39
- function D(n, t) {
39
+ function g(n, t) {
40
40
  return Object.prototype.hasOwnProperty.call(n, t);
41
41
  }
42
- function Z(n) {
42
+ function K(n) {
43
43
  return n !== null && typeof n == "object";
44
44
  }
45
- const g = /* @__PURE__ */ new WeakMap(), C = /* @__PURE__ */ new WeakMap();
46
- function m(n) {
45
+ const N = /* @__PURE__ */ new WeakMap();
46
+ function S(n) {
47
47
  return typeof n == "function" && Object.getPrototypeOf(n) !== Function.prototype;
48
48
  }
49
- function S(n, t) {
50
- g.set(n, t), C.delete(n);
49
+ function m(n, t) {
50
+ N.set(n, { metadata: t });
51
51
  }
52
- function P(n) {
53
- const t = g.get(n);
54
- if (t)
55
- return t[l.POST_CONSTRUCT];
56
- if (m(n))
57
- return P(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;
58
56
  }
59
- function w(n) {
60
- const t = g.get(n);
61
- if (t)
62
- return t[l.PRE_DESTROY];
63
- if (m(n))
64
- return w(Object.getPrototypeOf(n));
57
+ function A(n, t) {
58
+ const e = N.get(t);
59
+ if (e && g(e.metadata, n))
60
+ return e.metadata[n];
61
+ if (S(t))
62
+ return A(n, Object.getPrototypeOf(t));
65
63
  }
66
- function V(n) {
67
- if (C.has(n)) {
68
- const e = C.get(n);
69
- return e && Object.assign({}, e);
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;
70
69
  }
71
- const t = H(n);
72
- return C.set(n, t), t && Object.assign({}, t);
70
+ const e = B(n);
71
+ return t && (t.injectedPropsCache = e ?? null), e && Object.assign({}, e);
73
72
  }
74
- function H(n) {
75
- const t = g.get(n), e = t && D(t, l.INJECTED_PROPS) ? t[l.INJECTED_PROPS] : void 0;
76
- if (!m(n))
77
- return e;
78
- const i = V(Object.getPrototypeOf(n));
79
- if (i || e)
80
- return Object.assign({}, i, e);
73
+ function B(n) {
74
+ const t = M(l.INJECTED_PROPS, n);
75
+ if (!S(n))
76
+ return t;
77
+ const e = P(Object.getPrototypeOf(n));
78
+ if (e || t)
79
+ return Object.assign({}, e, t);
81
80
  }
82
- class $ {
81
+ class Z {
83
82
  constructor(t) {
84
83
  // 仅类型层面存在,无运行时开销
85
84
  r(this, "name");
86
85
  this.name = t;
87
86
  }
88
87
  }
89
- class k {
88
+ class H {
90
89
  constructor(t) {
91
90
  r(this, "_callback");
92
91
  this._callback = t;
@@ -98,7 +97,7 @@ class k {
98
97
  function b(n) {
99
98
  if (!n)
100
99
  throw new Error(T.INVALID_TOKEN);
101
- return n instanceof k ? n.resolve() : n;
100
+ return n instanceof H ? n.resolve() : n;
102
101
  }
103
102
  class p extends Error {
104
103
  constructor(e, i) {
@@ -108,16 +107,16 @@ class p extends Error {
108
107
  this.name = this.constructor.name, this.token = i;
109
108
  }
110
109
  }
111
- function j(n) {
110
+ function w(n) {
112
111
  const t = [];
113
112
  let e = n;
114
113
  for (; e && e.token; )
115
114
  t.push(e.token.name || "<anonymous>"), e = e.parent;
116
115
  return t.reverse();
117
116
  }
118
- class R extends p {
117
+ class V extends p {
119
118
  constructor(t) {
120
- super(""), this.message = "Circular dependency found: " + j(t).join(" --> ");
119
+ super(""), this.message = "Circular dependency found: " + w(t).join(" --> ");
121
120
  }
122
121
  }
123
122
  class x extends p {
@@ -128,12 +127,12 @@ class x extends p {
128
127
  );
129
128
  }
130
129
  }
131
- class F extends R {
130
+ class F extends V {
132
131
  constructor(t) {
133
132
  super(t), this.name = "CircularDependencyError inside @PostConstruct";
134
133
  }
135
134
  }
136
- const N = class N {
135
+ const C = class C {
137
136
  constructor(t, e) {
138
137
  r(this, "container");
139
138
  r(this, "context");
@@ -186,13 +185,13 @@ const N = class N {
186
185
  }
187
186
  get(t) {
188
187
  if (d.INITING === this.status)
189
- throw new R(t);
188
+ throw new V(t);
190
189
  if (d.ACTIVATED === this.status)
191
190
  if (this.transient)
192
191
  this.status = d.DEFAULT;
193
192
  else
194
193
  return this.cache;
195
- const e = N._resolvers.get(this.type);
194
+ const e = C._resolvers.get(this.type);
196
195
  if (e)
197
196
  return e.call(this, t);
198
197
  throw new x(this.token);
@@ -215,19 +214,19 @@ const N = class N {
215
214
  */
216
215
  _postConstruct(t, e) {
217
216
  if (f.INSTANCE === this.type) {
218
- const { key: i, value: s } = P(this.classValue) || {};
217
+ const { key: i, value: s } = A(l.POST_CONSTRUCT, this.classValue) || {};
219
218
  if (i)
220
219
  if (s) {
221
- const o = e.filter(
220
+ const a = e.filter(
222
221
  (c) => f.INSTANCE === (c == null ? void 0 : c.type)
223
- ), a = this._getAwaitBindings(o, s);
224
- for (const c of a)
222
+ ), o = this._getAwaitBindings(a, s);
223
+ for (const c of o)
225
224
  if (c && c.postConstructResult === O)
226
225
  throw new F({
227
226
  token: c.token,
228
227
  parent: t
229
228
  });
230
- const u = a.map((c) => c.postConstructResult);
229
+ const u = o.map((c) => c.postConstructResult);
231
230
  this.postConstructResult = Promise.all(u).then(
232
231
  () => this._execute(i)
233
232
  );
@@ -239,7 +238,7 @@ const N = class N {
239
238
  }
240
239
  preDestroy() {
241
240
  if (f.INSTANCE === this.type && this.cache !== void 0) {
242
- const { key: t } = w(this.classValue) || {};
241
+ const { key: t } = A(l.PRE_DESTROY, this.classValue) || {};
243
242
  t && this._execute(t);
244
243
  }
245
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;
@@ -277,21 +276,21 @@ const N = class N {
277
276
  return this.cache = this.activate(t), this.status = d.ACTIVATED, this.cache;
278
277
  }
279
278
  _getInjectProperties(t) {
280
- const e = V(this.classValue) || {}, i = Object.keys(e), s = /* @__PURE__ */ Object.create(null), o = [];
281
- for (let a = 0; a < i.length; a++) {
282
- const u = i[a], c = e[u], h = Object.assign({}, c);
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);
283
282
  h.parent = t;
284
283
  const _ = this.container._resolveWithInternalOpts(
285
284
  b(h.inject),
286
285
  h
287
286
  );
288
- _ === void 0 && h.optional || (s[u] = _), o.push(h.binding);
287
+ _ === void 0 && h.optional || (s[u] = _), a.push(h.binding);
289
288
  }
290
- return { properties: s, bindings: o };
289
+ return { properties: s, bindings: a };
291
290
  }
292
291
  };
293
292
  // 类型到解析函数的静态映射表,直接存储函数引用,消除字符串查表和 as any 间接调用
294
- r(N, "_resolvers", /* @__PURE__ */ new Map([
293
+ r(C, "_resolvers", /* @__PURE__ */ new Map([
295
294
  [f.INSTANCE, function(t) {
296
295
  return this._resolveInstanceValue(t);
297
296
  }],
@@ -302,23 +301,23 @@ r(N, "_resolvers", /* @__PURE__ */ new Map([
302
301
  return this._resolveDynamicValue();
303
302
  }]
304
303
  ]));
305
- let A = N;
304
+ let D = C;
306
305
  class U extends p {
307
306
  constructor(t, e) {
308
307
  if (super("No matching binding found for token: ", t), e != null && e.parent) {
309
- const i = j(e.parent);
308
+ const i = w(e.parent);
310
309
  i.length > 0 && (this.message += `
311
310
  ` + i.map((s) => " required by: " + s).join(`
312
311
  `));
313
312
  }
314
313
  }
315
314
  }
316
- class W extends p {
315
+ class k extends p {
317
316
  constructor(t) {
318
317
  super("Cannot bind token multiple times: ", t);
319
318
  }
320
319
  }
321
- class z extends p {
320
+ class W extends p {
322
321
  constructor(t) {
323
322
  super("Container has been destroyed. Cannot call get() for token: ", t);
324
323
  }
@@ -326,7 +325,7 @@ class z extends p {
326
325
  const I = class I {
327
326
  constructor() {
328
327
  r(this, "parent");
329
- r(this, "children");
328
+ r(this, "_children");
330
329
  r(this, "_bindings", /* @__PURE__ */ new Map());
331
330
  r(this, "_destroyed", !1);
332
331
  r(this, "_onActivationHandler");
@@ -338,7 +337,7 @@ const I = class I {
338
337
  }
339
338
  bind(t) {
340
339
  if (this._bindings.has(t))
341
- throw new W(t);
340
+ throw new k(t);
342
341
  const e = this._buildBinding(t);
343
342
  return this._bindings.set(t, e), e;
344
343
  }
@@ -367,16 +366,19 @@ const I = class I {
367
366
  }
368
367
  createChild() {
369
368
  const t = new I();
370
- 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;
371
373
  }
372
374
  destroy() {
373
375
  var t, e;
374
- if (this._destroyed = !0, this.children) {
375
- const i = Array.from(this.children);
376
+ if (this._destroyed = !0, this._children) {
377
+ const i = Array.from(this._children);
376
378
  for (const s of i)
377
379
  s.destroy();
378
380
  }
379
- 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;
380
382
  }
381
383
  get(t, e = {}) {
382
384
  const i = Object.assign({}, e);
@@ -387,16 +389,16 @@ const I = class I {
387
389
  let s;
388
390
  try {
389
391
  s = this._resolveWithInternalOpts(t, i);
390
- } catch (a) {
391
- return Promise.reject(a);
392
+ } catch (o) {
393
+ return Promise.reject(o);
392
394
  }
393
- const o = i.binding;
394
- 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);
395
397
  }
396
398
  // 内部解析入口,接受完整 Options;被 getAsync、toService、_getInjectProperties 等内部路径调用
397
399
  _resolveWithInternalOpts(t, e) {
398
400
  if (this._destroyed)
399
- throw new z(t);
401
+ throw new W(t);
400
402
  return e.skipSelf ? this._resolveSkipSelf(t, e) : e.self ? this._resolveSelf(t, e) : this._resolveDefault(t, e);
401
403
  }
402
404
  // 处理 skipSelf 选项:跳过当前容器,委托父容器解析
@@ -430,7 +432,7 @@ const I = class I {
430
432
  this._onDeactivationHandler && this._onDeactivationHandler(t.cache, t.token);
431
433
  }
432
434
  _buildBinding(t) {
433
- return new A(t, this);
435
+ return new D(t, this);
434
436
  }
435
437
  _getBinding(t) {
436
438
  return this._bindings.get(t);
@@ -459,122 +461,118 @@ class Y extends p {
459
461
  function E(n, t) {
460
462
  return function(e) {
461
463
  return function(i, s) {
462
- const o = s.name, a = s.metadata;
463
- D(a, l.INJECTED_PROPS) || (a[l.INJECTED_PROPS] = {});
464
- const u = a[l.INJECTED_PROPS];
465
- u[o] || (u[o] = {}), u[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;
466
468
  };
467
469
  };
468
470
  }
469
- function L(n, t) {
471
+ function j(n, t) {
470
472
  return (e) => (i, s) => {
471
- const o = s.name, a = s.metadata;
472
- if (D(a, n))
473
+ const a = s.name, o = s.metadata;
474
+ if (g(o, n))
473
475
  throw new Error(t);
474
- a[n] = { key: o, value: e };
476
+ o[n] = { key: a, value: e };
475
477
  };
476
478
  }
477
- const q = E(l.INJECT), Q = E(l.SELF, !0), X = E(l.SKIP_SELF, !0), tt = E(l.OPTIONAL, !0), et = L(
479
+ const $ = E(l.INJECT), q = E(l.SELF, !0), Q = E(l.SKIP_SELF, !0), X = E(l.OPTIONAL, !0), tt = j(
478
480
  l.POST_CONSTRUCT,
479
481
  T.POST_CONSTRUCT
480
- ), nt = L(
482
+ ), et = j(
481
483
  l.PRE_DESTROY,
482
484
  T.PRE_DESTROY
483
485
  );
484
- function it() {
486
+ function nt() {
485
487
  return function(n, t) {
486
488
  const e = t.metadata;
487
- S(n, e);
489
+ m(n, e);
488
490
  };
489
491
  }
490
- function J(n, t, e, i) {
492
+ function z(n, t, e, i) {
491
493
  if (e == null)
492
494
  throw new Error(T.LAZY_INJECT_INVALID_TOKEN);
493
- let s, o = !1;
495
+ let s, a = !1;
494
496
  Object.defineProperty(n, t, {
495
497
  configurable: !0,
496
498
  enumerable: !0,
497
499
  get() {
498
- if (!o) {
499
- const a = i || v.getContainerOf(n), u = n.constructor;
500
- if (!a)
500
+ if (!a) {
501
+ const o = i || v.getContainerOf(n), u = n.constructor;
502
+ if (!o)
501
503
  throw new Y(b(e), u);
502
- s = a._resolveWithInternalOpts(b(e), {
504
+ s = o._resolveWithInternalOpts(b(e), {
503
505
  parent: { token: u }
504
- }), o = !0;
506
+ }), a = !0;
505
507
  }
506
508
  return s;
507
509
  },
508
- set(a) {
509
- s = a, o = !0;
510
+ set(o) {
511
+ s = o, a = !0;
510
512
  }
511
513
  });
512
514
  }
513
- function G(n, t) {
515
+ function J(n, t) {
514
516
  return function(e, i) {
515
517
  const s = i.name;
516
518
  i.addInitializer(function() {
517
- J(this, s, n, t);
519
+ z(this, s, n, t);
518
520
  });
519
521
  };
520
522
  }
521
- function st(n) {
523
+ function it(n) {
522
524
  return function(t) {
523
- return G(t, n);
525
+ return J(t, n);
524
526
  };
525
527
  }
526
- function rt(n, t) {
527
- const e = t.name;
528
- t.addInitializer(function() {
529
- this[e] = n.bind(this);
530
- });
531
- }
532
528
  const y = /* @__PURE__ */ new WeakMap();
533
- function ot(n, t, e) {
534
- const i = Array.isArray(n) ? n : [n], s = t.prototype, o = typeof s[e] == "function";
529
+ function st(n, t, e) {
530
+ const i = Array.isArray(n) ? n : [n], s = t.prototype, a = typeof s[e] == "function";
535
531
  y.has(t) || y.set(t, {});
536
- const a = y.get(t), u = {
537
- kind: o ? "method" : "field",
532
+ const o = y.get(t), u = {
533
+ kind: a ? "method" : "field",
538
534
  name: e,
539
535
  static: !1,
540
536
  private: !1,
541
537
  addInitializer(h) {
542
538
  throw new Error(T.DECORATE_NOT_SUPPORT_INITIALIZER);
543
539
  },
544
- metadata: a
540
+ metadata: o
545
541
  };
546
- let c = o ? s[e] : void 0;
542
+ let c = a ? s[e] : void 0;
547
543
  for (let h = i.length - 1; h >= 0; h--) {
548
544
  const _ = i[h](c, u);
549
- o && typeof _ == "function" && (c = _);
545
+ a && typeof _ == "function" && (c = _);
550
546
  }
551
- o && c !== s[e] && (s[e] = c), S(t, a);
547
+ a && c !== s[e] && (s[e] = c), m(t, o);
552
548
  }
553
549
  export {
554
550
  p as BaseError,
555
- A as Binding,
551
+ D as Binding,
556
552
  U as BindingNotFoundError,
557
553
  x as BindingNotValidError,
558
- R as CircularDependencyError,
554
+ V as CircularDependencyError,
559
555
  v as Container,
560
- z as ContainerDestroyedError,
556
+ W as ContainerDestroyedError,
561
557
  Y as ContainerNotFoundError,
562
- W as DuplicateBindingError,
558
+ k as DuplicateBindingError,
563
559
  T as ERRORS,
564
- q as Inject,
565
- it as Injectable,
566
- G as LazyInject,
567
- k as LazyToken,
568
- tt as Optional,
569
- et as PostConstruct,
560
+ $ as Inject,
561
+ nt as Injectable,
562
+ J as LazyInject,
563
+ H as LazyToken,
564
+ X as Optional,
565
+ tt as PostConstruct,
570
566
  F as PostConstructError,
571
- nt as PreDestroy,
572
- Q as Self,
573
- X as SkipSelf,
574
- $ as Token,
575
- rt as autobind,
576
- st as createLazyInject,
577
- ot as decorate,
578
- D as hasOwn,
579
- Z as isObject
567
+ et as PreDestroy,
568
+ q as Self,
569
+ Q as SkipSelf,
570
+ Z as Token,
571
+ it as createLazyInject,
572
+ st as decorate,
573
+ m as defineMetadata,
574
+ A as getMetadata,
575
+ M as getOwnMetadata,
576
+ g as hasOwn,
577
+ K as isObject
580
578
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaokei/di",
3
- "version": "5.0.7",
3
+ "version": "5.0.9",
4
4
  "type": "module",
5
5
  "description": "Tiny di library depends on typescript decorator.",
6
6
  "main": "./dist/index.cjs",
@@ -20,7 +20,7 @@
20
20
  "./package.json": "./package.json"
21
21
  },
22
22
  "sideEffects": false,
23
- "homepage": "https://github.com/kaokei/di",
23
+ "homepage": "https://di.kaokei.com/",
24
24
  "author": "kaokei",
25
25
  "license": "MIT",
26
26
  "bugs": {