@kaokei/di 5.0.1 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,27 +18,3 @@
18
18
  - [API 文档](./docs/api/index.md)
19
19
  - [博客文章](./docs/note/01.什么是Token.md)
20
20
  - [CodeSandbox 在线示例](./docs/guide/EXAMPLES.md)
21
-
22
- ## Todo
23
-
24
- - 完善docs中todo项目
25
- - 最低需要typescript@5.0.0版本,esbuild@0.24.0版本,vite@6.0.0版本,
26
- 这里主要是vite依赖了esbuild,但是低版本esbuild在stage3装饰器的翻译上存在bug,所以esbuild最低版本需要0.24.0,而对应的vite最低版本则是6.0.0
27
- 当然如果明确使用 useDefineForClassFields: true,低版本esbuild也是可以正常工作的。
28
- https://chatgpt.com/share/69ca7982-2fd0-8321-8e6b-31867f5839e5
29
- - 需要重构当前的实现方案,应该通过context.metadata来收集依赖注入信息,然后通过类装饰器建立类和context.metadata的关联关系。
30
- addInitializer → this.constructor → class
31
- metadata → class decorator → WeakMap
32
-
33
- - stage3 装饰器执行顺序
34
- enter method decorator -->
35
- enter field decorator -->
36
- enter class decorator -->
37
- class decorator addInitializer callback -->
38
- method decorator addInitializer callback -->
39
- field decorator addInitializer callback -->
40
- class constructor
41
-
42
- - 5.0.4,5.1.6并不支持context.metadata
43
- - 5.2.2 开始支持context.metadata
44
-
@@ -24,9 +24,9 @@ export declare const PreDestroy: (metaValue?: any) => (_value: Function, context
24
24
  * @Injectable 读取 context.metadata 并通过 defineMetadata 写入 CacheMap,
25
25
  * 建立 target → metadata 的映射关系。
26
26
  *
27
- * 使用方式:@Injectable(无参数,直接作为装饰器使用)
27
+ * 使用方式:@Injectable()(需要调用,与其他装饰器保持一致)
28
28
  */
29
- export declare function Injectable(Ctor: Function, context: ClassDecoratorContext): void;
29
+ export declare function Injectable(): (Ctor: Function, context: ClassDecoratorContext) => void;
30
30
  /**
31
31
  * 延迟注入装饰器,Stage 3 Field Decorator 签名。
32
32
  * 通过 context.addInitializer 在实例上定义 getter/setter,
@@ -41,5 +41,18 @@ 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;
44
57
  export declare function decorate(decorator: any, target: any, key: string): void;
45
58
  export {};
@@ -24,9 +24,9 @@ export declare const PreDestroy: (metaValue?: any) => (_value: Function, context
24
24
  * @Injectable 读取 context.metadata 并通过 defineMetadata 写入 CacheMap,
25
25
  * 建立 target → metadata 的映射关系。
26
26
  *
27
- * 使用方式:@Injectable(无参数,直接作为装饰器使用)
27
+ * 使用方式:@Injectable()(需要调用,与其他装饰器保持一致)
28
28
  */
29
- export declare function Injectable(Ctor: Function, context: ClassDecoratorContext): void;
29
+ export declare function Injectable(): (Ctor: Function, context: ClassDecoratorContext) => void;
30
30
  /**
31
31
  * 延迟注入装饰器,Stage 3 Field Decorator 签名。
32
32
  * 通过 context.addInitializer 在实例上定义 getter/setter,
@@ -41,5 +41,18 @@ 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;
44
57
  export declare function decorate(decorator: any, target: any, key: string): void;
45
58
  export {};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var z=Object.defineProperty;var U=(n,t,e)=>t in n?z(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var r=(n,t,e)=>U(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u={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"},g={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 or @LazyInject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined."};function C(n,t){return Object.prototype.hasOwnProperty.call(n,t)}const D=Symbol("UNINITIALIZED"),y=new WeakMap;function P(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function m(n,t){y.set(n,t)}function V(n){const t=y.get(n);if(t)return t[u.POST_CONSTRUCT];if(P(n))return V(Object.getPrototypeOf(n))}function w(n){const t=y.get(n);if(t)return t[u.PRE_DESTROY];if(P(n))return w(Object.getPrototypeOf(n))}function R(n){const t=y.get(n),e=t&&C(t,u.INJECTED_PROPS)?t[u.INJECTED_PROPS]:void 0;if(!P(n))return e;const i=R(Object.getPrototypeOf(n));if(i||e)return{...i||{},...e||{}}}class Y{constructor(t){r(this,"name");this.name=t}}class j{constructor(t){r(this,"_callback");this._callback=t}resolve(){return this._callback()}}function O(n){if(!n)throw new Error(g.INVALID_TOKEN);return n instanceof j?n.resolve():n}class v 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}}class b extends v{constructor(t){super("");const e=[];let i=t;for(;i&&i.token;)e.push(i.token),i=i.parent;const s=e.reverse().map(o=>o.name||"<anonymous>").join(" --> ");this.message=`Circular dependency found: ${s}`}}class L extends v{constructor(t){super("Invalid binding: ",t)}}class k extends b{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const E=class E{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",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=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.get(t,{parent:{token:this.token}}))}get(t){if(d.INITING===this.status)throw new b(t);if(d.ACTIVATED===this.status)if(this.transient)this.status=d.DEFAULT;else return this.cache;const e=E._resolvers[this.type];if(e)return this[e](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:s}=V(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===D)throw new k({token:c.token,parent:t});const l=a.map(c=>c.postConstructResult);this.postConstructResult=Promise.all(l).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(f.INSTANCE===this.type){const{key:t}=w(this.classValue)||{};t&&this._execute(t)}_._instanceContainerMap.delete(this.cache),this.container=null,this.context=null,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=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=R(this.classValue)||{},i=Object.keys(e),s=Object.create(null),o=[];for(let a=0;a<i.length;a++){const l=i[a],c=e[l],{inject:I,...h}=c;h.parent=t;const p=this.container.get(O(I),h);p===void 0&&c.optional||(s[l]=p),o.push(h.binding)}return{properties:s,bindings:o}}};r(E,"_resolvers",{[f.INSTANCE]:"_resolveInstanceValue",[f.CONSTANT]:"_resolveConstantValue",[f.DYNAMIC]:"_resolveDynamicValue"});let N=E;class B extends v{constructor(t){super("No matching binding found for token: ",t)}}class H extends v{constructor(t){super("Cannot bind token multiple times: ",t)}}const T=class T{constructor(){r(this,"parent");r(this,"children");r(this,"_bindings",new Map);r(this,"_onActivationHandler");r(this,"_onDeactivationHandler")}static getContainerOf(t){return T._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)}}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 T;return t.parent=this,this.children||(this.children=new Set),this.children.add(t),t}destroy(){var t,e;if(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={}){return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}async getAsync(t,e={}){const i=this.get(t,e),s=e.binding;return(s==null?void 0:s.postConstructResult)instanceof Promise&&await s.postConstructResult,i}_resolveSkipSelf(t,e){return this.parent?(e.skipSelf=!1,this.parent.get(t,e)):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.get(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 B(t)}};r(T,"_instanceContainerMap",new WeakMap);let _=T;class M extends v{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 A(n,t){return function(e){return function(i,s){const o=s.name,a=s.metadata;C(a,u.INJECTED_PROPS)||(a[u.INJECTED_PROPS]={});const l=a[u.INJECTED_PROPS];l[o]||(l[o]={}),l[o][n]=e===void 0?t:e}}}function F(n,t){return e=>(i,s)=>{const o=s.name,a=s.metadata;if(C(a,n))throw new Error(t);a[n]={key:o,value:e}}}const J=A(u.INJECT),K=A(u.SELF,!0),G=A(u.SKIP_SELF,!0),$=A(u.OPTIONAL,!0),Z=F(u.POST_CONSTRUCT,g.POST_CONSTRUCT),q=F(u.PRE_DESTROY,g.PRE_DESTROY);function W(n,t){const e=t.metadata;m(n,e)}function Q(n,t,e,i){if(e==null)throw new Error(g.LAZY_INJECT_INVALID_TOKEN);const s=Symbol.for(t);Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!C(n,s)){const o=i||_.getContainerOf(n),a=n.constructor;if(!o)throw new M(O(e),a);n[s]=o.get(O(e),{parent:{token:a}})}return n[s]},set(o){n[s]=o}})}function x(n,t){return function(e,i){const s=i.name;i.addInitializer(function(){Q(this,s,n,t)})}}function X(n){return function(t){return x(t,n)}}const S=Symbol("decorate.metadata");function tt(n,t,e){const i=Array.isArray(n)?n:[n],s=t.prototype,o=typeof s[e]=="function",a=[];C(t,S)||(t[S]={});const l=t[S],c={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(h){a.push(h)},metadata:l};let I=o?s[e]:void 0;for(let h=i.length-1;h>=0;h--){const p=i[h](I,c);o&&typeof p=="function"&&(I=p)}if(o&&I!==s[e]&&(s[e]=I),m(t,l),a.length>0){const h=Object.create(s);for(const p of a)p.call(h)}}exports.BaseError=v;exports.Binding=N;exports.BindingNotFoundError=B;exports.BindingNotValidError=L;exports.CircularDependencyError=b;exports.Container=_;exports.ContainerNotFoundError=M;exports.DuplicateBindingError=H;exports.Inject=J;exports.Injectable=W;exports.LazyInject=x;exports.LazyToken=j;exports.Optional=$;exports.PostConstruct=Z;exports.PostConstructError=k;exports.PreDestroy=q;exports.Self=K;exports.SkipSelf=G;exports.Token=Y;exports.createLazyInject=X;exports.decorate=tt;
1
+ "use strict";var z=Object.defineProperty;var U=(n,t,e)=>t in n?z(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var r=(n,t,e)=>U(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u={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"},g={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 or @LazyInject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined."};function N(n,t){return Object.prototype.hasOwnProperty.call(n,t)}const D=Symbol("UNINITIALIZED"),y=new WeakMap;function m(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function P(n,t){y.set(n,t)}function V(n){const t=y.get(n);if(t)return t[u.POST_CONSTRUCT];if(m(n))return V(Object.getPrototypeOf(n))}function w(n){const t=y.get(n);if(t)return t[u.PRE_DESTROY];if(m(n))return w(Object.getPrototypeOf(n))}function R(n){const t=y.get(n),e=t&&N(t,u.INJECTED_PROPS)?t[u.INJECTED_PROPS]:void 0;if(!m(n))return e;const i=R(Object.getPrototypeOf(n));if(i||e)return{...i||{},...e||{}}}class Y{constructor(t){r(this,"name");this.name=t}}class j{constructor(t){r(this,"_callback");this._callback=t}resolve(){return this._callback()}}function b(n){if(!n)throw new Error(g.INVALID_TOKEN);return n instanceof j?n.resolve():n}class v 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}}class O extends v{constructor(t){super("");const e=[];let i=t;for(;i&&i.token;)e.push(i.token),i=i.parent;const s=e.reverse().map(o=>o.name||"<anonymous>").join(" --> ");this.message=`Circular dependency found: ${s}`}}class L extends v{constructor(t){super("Invalid binding: ",t)}}class k extends O{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const E=class E{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",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=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.get(t,{parent:{token:this.token}}))}get(t){if(d.INITING===this.status)throw new O(t);if(d.ACTIVATED===this.status)if(this.transient)this.status=d.DEFAULT;else return this.cache;const e=E._resolvers[this.type];if(e)return this[e](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:s}=V(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===D)throw new k({token:c.token,parent:t});const l=a.map(c=>c.postConstructResult);this.postConstructResult=Promise.all(l).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(f.INSTANCE===this.type){const{key:t}=w(this.classValue)||{};t&&this._execute(t)}_._instanceContainerMap.delete(this.cache),this.container=null,this.context=null,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=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=R(this.classValue)||{},i=Object.keys(e),s=Object.create(null),o=[];for(let a=0;a<i.length;a++){const l=i[a],c=e[l],{inject:I,...h}=c;h.parent=t;const p=this.container.get(b(I),h);p===void 0&&c.optional||(s[l]=p),o.push(h.binding)}return{properties:s,bindings:o}}};r(E,"_resolvers",{[f.INSTANCE]:"_resolveInstanceValue",[f.CONSTANT]:"_resolveConstantValue",[f.DYNAMIC]:"_resolveDynamicValue"});let C=E;class B extends v{constructor(t){super("No matching binding found for token: ",t)}}class H extends v{constructor(t){super("Cannot bind token multiple times: ",t)}}const T=class T{constructor(){r(this,"parent");r(this,"children");r(this,"_bindings",new Map);r(this,"_onActivationHandler");r(this,"_onDeactivationHandler")}static getContainerOf(t){return T._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)}}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 T;return t.parent=this,this.children||(this.children=new Set),this.children.add(t),t}destroy(){var t,e;if(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={}){return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}async getAsync(t,e={}){const i=this.get(t,e),s=e.binding;return(s==null?void 0:s.postConstructResult)instanceof Promise&&await s.postConstructResult,i}_resolveSkipSelf(t,e){return this.parent?(e.skipSelf=!1,this.parent.get(t,e)):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.get(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 C(t,this)}_getBinding(t){return this._bindings.get(t)}_checkBindingNotFoundError(t,e){if(!e.optional)throw new B(t)}};r(T,"_instanceContainerMap",new WeakMap);let _=T;class M extends v{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 A(n,t){return function(e){return function(i,s){const o=s.name,a=s.metadata;N(a,u.INJECTED_PROPS)||(a[u.INJECTED_PROPS]={});const l=a[u.INJECTED_PROPS];l[o]||(l[o]={}),l[o][n]=e===void 0?t:e}}}function F(n,t){return e=>(i,s)=>{const o=s.name,a=s.metadata;if(N(a,n))throw new Error(t);a[n]={key:o,value:e}}}const J=A(u.INJECT),K=A(u.SELF,!0),G=A(u.SKIP_SELF,!0),$=A(u.OPTIONAL,!0),Z=F(u.POST_CONSTRUCT,g.POST_CONSTRUCT),q=F(u.PRE_DESTROY,g.PRE_DESTROY);function W(){return function(n,t){const e=t.metadata;P(n,e)}}function Q(n,t,e,i){if(e==null)throw new Error(g.LAZY_INJECT_INVALID_TOKEN);const s=Symbol.for(t);Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!N(n,s)){const o=i||_.getContainerOf(n),a=n.constructor;if(!o)throw new M(b(e),a);n[s]=o.get(b(e),{parent:{token:a}})}return n[s]},set(o){n[s]=o}})}function x(n,t){return function(e,i){const s=i.name;i.addInitializer(function(){Q(this,s,n,t)})}}function X(n){return function(t){return x(t,n)}}function tt(n,t){const e=t.name;t.addInitializer(function(){this[e]=n.bind(this)})}const S=Symbol("decorate.metadata");function et(n,t,e){const i=Array.isArray(n)?n:[n],s=t.prototype,o=typeof s[e]=="function",a=[];N(t,S)||(t[S]={});const l=t[S],c={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(h){a.push(h)},metadata:l};let I=o?s[e]:void 0;for(let h=i.length-1;h>=0;h--){const p=i[h](I,c);o&&typeof p=="function"&&(I=p)}if(o&&I!==s[e]&&(s[e]=I),P(t,l),a.length>0){const h=Object.create(s);for(const p of a)p.call(h)}}exports.BaseError=v;exports.Binding=C;exports.BindingNotFoundError=B;exports.BindingNotValidError=L;exports.CircularDependencyError=O;exports.Container=_;exports.ContainerNotFoundError=M;exports.DuplicateBindingError=H;exports.Inject=J;exports.Injectable=W;exports.LazyInject=x;exports.LazyToken=j;exports.Optional=$;exports.PostConstruct=Z;exports.PostConstructError=k;exports.PreDestroy=q;exports.Self=K;exports.SkipSelf=G;exports.Token=Y;exports.autobind=tt;exports.createLazyInject=X;exports.decorate=et;
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, } from './decorator';
5
+ export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, autobind, } from './decorator';
6
6
  export { BaseError } from './errors/BaseError';
7
7
  export { BindingNotFoundError } from './errors/BindingNotFoundError';
8
8
  export { BindingNotValidError } from './errors/BindingNotValidError';
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, } from './decorator';
5
+ export { Inject, Self, SkipSelf, Optional, PostConstruct, PreDestroy, Injectable, decorate, LazyInject, createLazyInject, autobind, } from './decorator';
6
6
  export { BaseError } from './errors/BaseError';
7
7
  export { BindingNotFoundError } from './errors/BindingNotFoundError';
8
8
  export { BindingNotValidError } from './errors/BindingNotValidError';
package/dist/index.js CHANGED
@@ -38,29 +38,29 @@ function T(n, t) {
38
38
  return Object.prototype.hasOwnProperty.call(n, t);
39
39
  }
40
40
  const y = Symbol("UNINITIALIZED"), E = /* @__PURE__ */ new WeakMap();
41
- function m(n) {
41
+ function O(n) {
42
42
  return typeof n == "function" && Object.getPrototypeOf(n) !== Function.prototype;
43
43
  }
44
- function P(n, t) {
44
+ function b(n, t) {
45
45
  E.set(n, t);
46
46
  }
47
- function b(n) {
47
+ function P(n) {
48
48
  const t = E.get(n);
49
49
  if (t)
50
50
  return t[u.POST_CONSTRUCT];
51
- if (m(n))
52
- return b(Object.getPrototypeOf(n));
51
+ if (O(n))
52
+ return P(Object.getPrototypeOf(n));
53
53
  }
54
54
  function V(n) {
55
55
  const t = E.get(n);
56
56
  if (t)
57
57
  return t[u.PRE_DESTROY];
58
- if (m(n))
58
+ if (O(n))
59
59
  return V(Object.getPrototypeOf(n));
60
60
  }
61
61
  function w(n) {
62
62
  const t = E.get(n), e = t && T(t, u.INJECTED_PROPS) ? t[u.INJECTED_PROPS] : void 0;
63
- if (!m(n))
63
+ if (!O(n))
64
64
  return e;
65
65
  const i = w(Object.getPrototypeOf(n));
66
66
  if (i || e)
@@ -201,7 +201,7 @@ const C = class C {
201
201
  */
202
202
  _postConstruct(t, e) {
203
203
  if (f.INSTANCE === this.type) {
204
- const { key: i, value: s } = b(this.classValue) || {};
204
+ const { key: i, value: s } = P(this.classValue) || {};
205
205
  if (i)
206
206
  if (s) {
207
207
  const o = e.filter(
@@ -282,7 +282,7 @@ r(C, "_resolvers", {
282
282
  [f.CONSTANT]: "_resolveConstantValue",
283
283
  [f.DYNAMIC]: "_resolveDynamicValue"
284
284
  });
285
- let O = C;
285
+ let m = C;
286
286
  class x extends N {
287
287
  constructor(t) {
288
288
  super("No matching binding found for token: ", t);
@@ -375,7 +375,7 @@ const I = class I {
375
375
  this._onDeactivationHandler && this._onDeactivationHandler(t.cache, t.token);
376
376
  }
377
377
  _buildBinding(t) {
378
- return new O(t, this);
378
+ return new m(t, this);
379
379
  }
380
380
  _getBinding(t) {
381
381
  return this._bindings.get(t);
@@ -393,7 +393,7 @@ const I = class I {
393
393
  // 由于 Instance 类型每次都通过 new ClassName() 创建新实例,不存在同一实例被多个容器注册的覆盖风险
394
394
  r(I, "_instanceContainerMap", /* @__PURE__ */ new WeakMap());
395
395
  let v = I;
396
- class U extends N {
396
+ class z extends N {
397
397
  constructor(t, e) {
398
398
  super(
399
399
  `@LazyInject(${t == null ? void 0 : t.name}) in class ${e.name} requires a registered container but none was found. Token: `,
@@ -426,11 +426,13 @@ const G = A(u.INJECT), $ = A(u.SELF, !0), Z = A(u.SKIP_SELF, !0), q = A(u.OPTION
426
426
  u.PRE_DESTROY,
427
427
  g.PRE_DESTROY
428
428
  );
429
- function X(n, t) {
430
- const e = t.metadata;
431
- P(n, e);
429
+ function X() {
430
+ return function(n, t) {
431
+ const e = t.metadata;
432
+ b(n, e);
433
+ };
432
434
  }
433
- function Y(n, t, e, i) {
435
+ function U(n, t, e, i) {
434
436
  if (e == null)
435
437
  throw new Error(g.LAZY_INJECT_INVALID_TOKEN);
436
438
  const s = Symbol.for(t);
@@ -441,7 +443,7 @@ function Y(n, t, e, i) {
441
443
  if (!T(n, s)) {
442
444
  const o = i || v.getContainerOf(n), a = n.constructor;
443
445
  if (!o)
444
- throw new U(S(e), a);
446
+ throw new z(S(e), a);
445
447
  n[s] = o.get(S(e), {
446
448
  parent: { token: a }
447
449
  });
@@ -453,21 +455,27 @@ function Y(n, t, e, i) {
453
455
  }
454
456
  });
455
457
  }
456
- function z(n, t) {
458
+ function Y(n, t) {
457
459
  return function(e, i) {
458
460
  const s = i.name;
459
461
  i.addInitializer(function() {
460
- Y(this, s, n, t);
462
+ U(this, s, n, t);
461
463
  });
462
464
  };
463
465
  }
464
466
  function tt(n) {
465
467
  return function(t) {
466
- return z(t, n);
468
+ return Y(t, n);
467
469
  };
468
470
  }
471
+ function et(n, t) {
472
+ const e = t.name;
473
+ t.addInitializer(function() {
474
+ this[e] = n.bind(this);
475
+ });
476
+ }
469
477
  const D = Symbol("decorate.metadata");
470
- function et(n, t, e) {
478
+ function nt(n, t, e) {
471
479
  const i = Array.isArray(n) ? n : [n], s = t.prototype, o = typeof s[e] == "function", a = [];
472
480
  T(t, D) || (t[D] = {});
473
481
  const l = t[D], c = {
@@ -485,7 +493,7 @@ function et(n, t, e) {
485
493
  const p = i[h](_, c);
486
494
  o && typeof p == "function" && (_ = p);
487
495
  }
488
- if (o && _ !== s[e] && (s[e] = _), P(t, l), a.length > 0) {
496
+ if (o && _ !== s[e] && (s[e] = _), b(t, l), a.length > 0) {
489
497
  const h = Object.create(s);
490
498
  for (const p of a)
491
499
  p.call(h);
@@ -493,16 +501,16 @@ function et(n, t, e) {
493
501
  }
494
502
  export {
495
503
  N as BaseError,
496
- O as Binding,
504
+ m as Binding,
497
505
  x as BindingNotFoundError,
498
506
  H as BindingNotValidError,
499
507
  R as CircularDependencyError,
500
508
  v as Container,
501
- U as ContainerNotFoundError,
509
+ z as ContainerNotFoundError,
502
510
  F as DuplicateBindingError,
503
511
  G as Inject,
504
512
  X as Injectable,
505
- z as LazyInject,
513
+ Y as LazyInject,
506
514
  B as LazyToken,
507
515
  q as Optional,
508
516
  W as PostConstruct,
@@ -511,6 +519,7 @@ export {
511
519
  $ as Self,
512
520
  Z as SkipSelf,
513
521
  K as Token,
522
+ et as autobind,
514
523
  tt as createLazyInject,
515
- et as decorate
524
+ nt as decorate
516
525
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaokei/di",
3
- "version": "5.0.1",
3
+ "version": "5.0.2",
4
4
  "type": "module",
5
5
  "description": "Tiny di library depends on typescript decorator.",
6
6
  "main": "./dist/index.cjs",