@codefast/di 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +161 -0
  2. package/README.md +48 -32
  3. package/dist/ambient-container.d.ts +46 -0
  4. package/dist/ambient-container.js +72 -1
  5. package/dist/container/binding-chain.js +3 -3
  6. package/dist/container/container.d.ts +41 -29
  7. package/dist/container/container.js +49 -264
  8. package/dist/container/introspect.d.ts +47 -0
  9. package/dist/container/introspect.js +53 -0
  10. package/dist/core/binding-builders.d.ts +22 -1
  11. package/dist/core/binding-declaration.js +2 -2
  12. package/dist/core/module.d.ts +4 -25
  13. package/dist/core/module.js +3 -27
  14. package/dist/core/state-epoch.d.ts +1 -1
  15. package/dist/core/state-epoch.js +1 -1
  16. package/dist/core/types.d.ts +16 -7
  17. package/dist/decorators/inject.js +27 -22
  18. package/dist/decorators/injectable.d.ts +14 -18
  19. package/dist/decorators/injectable.js +23 -2
  20. package/dist/errors.d.ts +11 -2
  21. package/dist/errors.js +6 -3
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +3 -2
  24. package/dist/injection/dependency-slot.d.ts +17 -0
  25. package/dist/injection/dependency-slot.js +46 -0
  26. package/dist/injection/descriptor.d.ts +9 -3
  27. package/dist/injection/descriptor.js +10 -1
  28. package/dist/introspection/validation.d.ts +28 -0
  29. package/dist/introspection/validation.js +244 -0
  30. package/dist/lifecycle/hooks.d.ts +11 -2
  31. package/dist/lifecycle/hooks.js +30 -18
  32. package/dist/resolution/cache/class-introspector.d.ts +7 -8
  33. package/dist/resolution/cache/class-introspector.js +40 -3
  34. package/dist/resolution/cache/lookup.d.ts +10 -0
  35. package/dist/resolution/cache/lookup.js +27 -0
  36. package/dist/resolution/context.d.ts +12 -12
  37. package/dist/resolution/plan/codegen.d.ts +2 -1
  38. package/dist/resolution/plan/codegen.js +1 -1
  39. package/dist/resolution/plan/compiler.d.ts +6 -6
  40. package/dist/resolution/plan/compiler.js +152 -22
  41. package/dist/resolution/resolver.d.ts +2 -8
  42. package/dist/resolution/resolver.js +17 -93
  43. package/package.json +10 -2
@@ -2,7 +2,7 @@ import { DEFAULT_BINDING_SLOT, withSlotCriterion } from "#core/binding";
2
2
  import { slotName } from "#core/tag";
3
3
  import { tokenName } from "#core/token";
4
4
  import { InvalidBindingDeclarationError, ManyBindingSlotError, SelfBindingRequiresClassError } from "#errors";
5
- import { normalizeToDescriptor } from "#injection/descriptor";
5
+ import { settledDescriptorsOf } from "#injection/descriptor";
6
6
  // Only this module can mint the symbol, so an entry carrying it was made by `binding()`.
7
7
  const declarationBrand = Symbol("di:binding-declaration");
8
8
  /** Whether an entry carries the brand `binding()` alone sets, and so every field a declaration holds. */
@@ -132,7 +132,7 @@ export function binding(key, definition) {
132
132
  }
133
133
  kind = strategy === "toResolved" ? "resolved" : "resolved-async";
134
134
  factory = strategy === "toResolved" ? definition.toResolved : definition.toResolvedAsync;
135
- deps = declaredDeps.map((dependency) => normalizeToDescriptor(dependency));
135
+ deps = settledDescriptorsOf(declaredDeps);
136
136
  break;
137
137
  }
138
138
  case "toAlias":
@@ -1,7 +1,5 @@
1
- import type { BindToBuilder } from "#core/binding-builders";
1
+ import type { Binder } from "#core/binding-builders";
2
2
  import type { BindingDeclaration, DeclaredBinding } from "#core/binding-declaration";
3
- import type { Token } from "#core/token";
4
- import type { Constructor } from "#core/types";
5
3
  declare const SYNC_MODULE_BRAND: unique symbol;
6
4
  declare const ASYNC_MODULE_BRAND: unique symbol;
7
5
  /**
@@ -36,8 +34,7 @@ export interface AsyncModule {
36
34
  *
37
35
  * @since 0.3.16-canary.0
38
36
  */
39
- export interface ModuleBuilder {
40
- bind<Value>(token: Token<Value> | Constructor<Value>): BindToBuilder<Value>;
37
+ export interface ModuleBuilder extends Binder {
41
38
  import(...modules: Array<SyncModule>): void;
42
39
  }
43
40
  /**
@@ -45,29 +42,11 @@ export interface ModuleBuilder {
45
42
  *
46
43
  * @since 0.3.16-canary.0
47
44
  */
48
- export interface AsyncModuleBuilder {
49
- bind<Value>(token: Token<Value> | Constructor<Value>): BindToBuilder<Value>;
45
+ export interface AsyncModuleBuilder extends Binder {
50
46
  import(...modules: Array<SyncModule | AsyncModule>): void;
51
47
  }
52
48
  /**
53
- * The companion factory that creates `SyncModule` values.
54
- *
55
- * @since 0.3.16-canary.0
56
- */
57
- export declare const SyncModule: {
58
- create(name: string, setup: (builder: ModuleBuilder) => void): SyncModule;
59
- fromBindings(name: string, declarations: ReadonlyArray<BindingDeclaration>): SyncModule;
60
- };
61
- /**
62
- * The companion factory that creates `AsyncModule` values.
63
- *
64
- * @since 0.3.16-canary.0
65
- */
66
- export declare const AsyncModule: {
67
- create(name: string, setup: (builder: AsyncModuleBuilder) => Promise<void>): AsyncModule;
68
- };
69
- /**
70
- * The unified module factory — `create` and `fromBindings` for sync modules, `createAsync` for async ones.
49
+ * The module factory: `create` and `fromBindings` for a sync module, `createAsync` for an async one.
71
50
  *
72
51
  * @since 0.3.16-canary.0
73
52
  */
@@ -11,11 +11,11 @@ const ASYNC_MODULE_BRAND = Symbol("di:async-module");
11
11
  export const MODULE_SETUP = Symbol("di:module-setup");
12
12
  // ── Static factories ─────────────────────────────────────────────────────────────────────────────────────────────────
13
13
  /**
14
- * The companion factory that creates `SyncModule` values.
14
+ * The module factory: `create` and `fromBindings` for a sync module, `createAsync` for an async one.
15
15
  *
16
16
  * @since 0.3.16-canary.0
17
17
  */
18
- export const SyncModule = {
18
+ export const Module = {
19
19
  create(name, setup) {
20
20
  return {
21
21
  name,
@@ -33,14 +33,7 @@ export const SyncModule = {
33
33
  [MODULE_SETUP]: declared,
34
34
  };
35
35
  },
36
- };
37
- /**
38
- * The companion factory that creates `AsyncModule` values.
39
- *
40
- * @since 0.3.16-canary.0
41
- */
42
- export const AsyncModule = {
43
- create(name, setup) {
36
+ createAsync(name, setup) {
44
37
  return {
45
38
  name,
46
39
  [ASYNC_MODULE_BRAND]: true,
@@ -48,23 +41,6 @@ export const AsyncModule = {
48
41
  };
49
42
  },
50
43
  };
51
- // ── Module — unified API ─────────────────────────────────────────────────────────────────────────────────────────────
52
- /**
53
- * The unified module factory — `create` and `fromBindings` for sync modules, `createAsync` for async ones.
54
- *
55
- * @since 0.3.16-canary.0
56
- */
57
- export const Module = {
58
- create(name, setup) {
59
- return SyncModule.create(name, setup);
60
- },
61
- fromBindings(name, declarations) {
62
- return SyncModule.fromBindings(name, declarations);
63
- },
64
- createAsync(name, setup) {
65
- return AsyncModule.create(name, setup);
66
- },
67
- };
68
44
  /**
69
45
  * Narrows a module union to `SyncModule` by checking its brand.
70
46
  *
@@ -16,7 +16,7 @@ export declare function stateEpoch(): number;
16
16
  export declare function advanceStateEpoch(): void;
17
17
  /**
18
18
  * The container-disposal counter, held in a cell so a hot reader dereferences a field rather than
19
- * paying a cross-module call — apart from {@link stateEpoch} so a per-request child's `dispose()`
19
+ * paying a cross-module call — apart from {@link stateEpoch} so a per-request child's `disposeAsync()`
20
20
  * does not invalidate the chain-version memo that keeps deep resolves cheap. A child compares it to
21
21
  * learn whether an ancestor was disposed, re-walking the chain only after a disposal somewhere.
22
22
  *
@@ -21,7 +21,7 @@ export function advanceStateEpoch() {
21
21
  }
22
22
  /**
23
23
  * The container-disposal counter, held in a cell so a hot reader dereferences a field rather than
24
- * paying a cross-module call — apart from {@link stateEpoch} so a per-request child's `dispose()`
24
+ * paying a cross-module call — apart from {@link stateEpoch} so a per-request child's `disposeAsync()`
25
25
  * does not invalidate the chain-version memo that keeps deep resolves cheap. A child compares it to
26
26
  * learn whether an ancestor was disposed, re-walking the chain only after a disposal somewhere.
27
27
  *
@@ -102,18 +102,27 @@ export interface ConstraintContext {
102
102
  * @since 0.6.0
103
103
  */
104
104
  export type BindingConstraint = (ctx: ConstraintContext) => boolean;
105
+ /**
106
+ * The resolve methods a container and a factory's resolution context share.
107
+ *
108
+ * @remarks One declaration for both, so a slot name narrows the same way wherever a token is resolved.
109
+ *
110
+ * @since 0.14.0
111
+ */
112
+ export interface Resolver {
113
+ resolve<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value;
114
+ resolveAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value>;
115
+ resolveOptional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value | undefined;
116
+ resolveOptionalAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value | undefined>;
117
+ resolveAll<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): ReadonlyArray<Value>;
118
+ resolveAllAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<ReadonlyArray<Value>>;
119
+ }
105
120
  /**
106
121
  * The container view a dynamic factory or activation handler resolves further dependencies through.
107
122
  *
108
123
  * @since 0.3.16-canary.0
109
124
  */
110
- export interface ResolutionContext {
111
- resolve<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value;
112
- resolveAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value>;
113
- resolveOptional<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value | undefined;
114
- resolveOptionalAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value | undefined>;
115
- resolveAll<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): ReadonlyArray<Value>;
116
- resolveAllAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<ReadonlyArray<Value>>;
125
+ export interface ResolutionContext extends Resolver {
117
126
  readonly graph: ConstraintContext;
118
127
  }
119
128
  /**
@@ -1,4 +1,4 @@
1
- import { getActiveContainer, getAmbientResolution } from "#ambient-container";
1
+ import { getActiveContainer, getAmbientResolution, markPreparableSlot, NOT_PREPARED } from "#ambient-container";
2
2
  import { decoratorMetadataOf } from "#decorators/metadata-record";
3
3
  import { MissingContainerContextError, StaticMemberDecoratorError } from "#errors";
4
4
  import { injectionSlotToResolveOptions } from "#injection/dependency-slot";
@@ -47,27 +47,32 @@ export function inject(token, options) {
47
47
  key: context.name,
48
48
  descriptor,
49
49
  });
50
- context.addInitializer(function () {
51
- // Prefer the engine's path-continuing resolver: it keeps this accessor's dependencies on the
52
- // live resolution path, so a cycle through an accessor is detected instead of recursing.
53
- const ambient = getAmbientResolution();
54
- if (ambient !== undefined) {
55
- const value = descriptor.optional
56
- ? ambient.resolveOptional(resolveKey, resolveOptions)
57
- : ambient.resolve(resolveKey, resolveOptions);
58
- context.access.set(this, value);
59
- return;
60
- }
61
- const container = getActiveContainer();
62
- if (container === undefined) {
63
- throw new MissingContainerContextError(classNameOf(this), context.name);
64
- }
65
- const value = descriptor.optional
66
- ? container.resolveOptional(resolveKey, resolveOptions)
67
- : container.resolve(resolveKey, resolveOptions);
68
- context.access.set(this, value);
69
- });
70
- return {};
50
+ markPreparableSlot(descriptor);
51
+ // The value is the accessor's initial value, so its storage is written once as the field initializes.
52
+ return {
53
+ init() {
54
+ // Prefer the engine's path-continuing resolver: it keeps this accessor's dependencies on the
55
+ // live resolution path, so a cycle through an accessor is detected instead of recursing.
56
+ const ambient = getAmbientResolution();
57
+ if (ambient !== undefined) {
58
+ // A compiled plan resolved this accessor before construction; take its value when it holds one.
59
+ const prepared = ambient.takePrepared === undefined ? NOT_PREPARED : ambient.takePrepared(this, descriptor);
60
+ if (prepared !== NOT_PREPARED) {
61
+ return prepared;
62
+ }
63
+ return (descriptor.optional
64
+ ? ambient.resolveOptional(resolveKey, resolveOptions)
65
+ : ambient.resolve(resolveKey, resolveOptions));
66
+ }
67
+ const container = getActiveContainer();
68
+ if (container === undefined) {
69
+ throw new MissingContainerContextError(classNameOf(this), context.name);
70
+ }
71
+ return (descriptor.optional
72
+ ? container.resolveOptional(resolveKey, resolveOptions)
73
+ : container.resolve(resolveKey, resolveOptions));
74
+ },
75
+ };
71
76
  };
72
77
  // Use defineProperties to handle read-only `name` property of functions
73
78
  const props = {};
@@ -1,11 +1,15 @@
1
+ import type { SyncModule } from "#core/module";
1
2
  import type { BindingScope, Constructor } from "#core/types";
2
3
  import type { InjectableDependency, ResolvedDependencyValue } from "#injection/descriptor";
3
4
  /**
4
- * The collector `@injectable` registers a class into, for a container to bind later.
5
+ * The collector `@injectable` registers a class into: a module that binds every registered class to itself.
6
+ *
7
+ * @remarks It loads like any `SyncModule` — deduplicated and ref-counted, and torn down by `unload()`.
8
+ * A load binds the entries registered by then; the set one load bound is the set its unload removes.
5
9
  *
6
10
  * @since 0.3.16-canary.0
7
11
  */
8
- export interface AutoRegisterRegistry {
12
+ export interface AutoRegisterRegistry extends SyncModule {
9
13
  register(target: Constructor, scope: BindingScope): void;
10
14
  entries(): ReadonlyArray<{
11
15
  target: Constructor;
@@ -13,11 +17,11 @@ export interface AutoRegisterRegistry {
13
17
  }>;
14
18
  }
15
19
  /**
16
- * Creates an empty auto-register registry.
20
+ * Creates an empty auto-register registry, loaded under `name`.
17
21
  *
18
22
  * @since 0.3.16-canary.0
19
23
  */
20
- export declare function createAutoRegisterRegistry(): AutoRegisterRegistry;
24
+ export declare function createAutoRegisterRegistry(name: string): AutoRegisterRegistry;
21
25
  /**
22
26
  * Auto-registration options `@injectable` accepts alongside its deps list.
23
27
  *
@@ -31,27 +35,19 @@ export interface InjectableOptions {
31
35
  * The parameters a constructor is handed, given what its `deps` declare.
32
36
  *
33
37
  * @remarks Reuses the same reading a `toResolved` factory gets, so `injectAll` arrives as an array
34
- * and `optional` as possibly undefined in both places.
38
+ * and `injectOptional` as possibly undefined in both places.
35
39
  */
36
40
  type InjectedParameters<Deps extends ReadonlyArray<InjectableDependency>> = {
37
41
  -readonly [Index in keyof Deps]: ResolvedDependencyValue<Deps[Index]>;
38
42
  };
39
43
  /**
40
- * Declare a class injectable, and what its constructor is to be handed.
44
+ * Declares a class injectable, and what its constructor is to be handed.
41
45
  *
42
- * @since 0.3.16-canary.0
43
- */
44
- export declare function injectable(): (target: unknown, context: ClassDecoratorContext) => void;
45
- /**
46
- * @remarks Declaring dependencies constrains the class: the decorator only accepts one whose
47
- * constructor takes exactly what `deps` resolve to, in that order — including arity, so a literal
48
- * deps list longer than the constructor is a compile error rather than a resolved-and-discarded
49
- * value. Optional trailing parameters admit every arity they declare, and a rest parameter admits
50
- * any list. A deps *array* — one whose length the compiler cannot know — skips the arity check,
51
- * which is also the deliberate spelling for declaring more dependencies than the constructor
52
- * takes, e.g. for the dependency graph's edges.
46
+ * @remarks The decorator only accepts a class whose constructor takes exactly what `deps` resolve to, in that order —
47
+ * no deps means no required parameter, so a class (or a subclass inheriting its base's constructor) cannot be built
48
+ * with an argument left `undefined`. A deps *array* whose length the compiler cannot know skips the arity check.
53
49
  *
54
50
  * @since 0.3.16-canary.0
55
51
  */
56
- export declare function injectable<const Deps extends ReadonlyArray<InjectableDependency>>(deps: Deps, options?: InjectableOptions): <Target extends abstract new (...args: InjectedParameters<Deps>) => unknown>(target: Target & (number extends Deps["length"] ? unknown : Deps["length"] extends ConstructorParameters<Target>["length"] ? unknown : never), context: ClassDecoratorContext) => void;
52
+ export declare function injectable<const Deps extends ReadonlyArray<InjectableDependency> = []>(deps?: Deps, options?: InjectableOptions): <Target extends abstract new (...args: InjectedParameters<Deps>) => unknown>(target: Target & (number extends Deps["length"] ? unknown : Deps["length"] extends ConstructorParameters<Target>["length"] ? unknown : never), context: ClassDecoratorContext) => void;
57
53
  export type { InjectableDependency };
@@ -1,14 +1,22 @@
1
+ import { Module } from "#core/module";
1
2
  import { decoratorMetadataOf } from "#decorators/metadata-record";
2
3
  import { normalizeToDescriptor } from "#injection/descriptor";
3
4
  import { INJECTABLE_KEY } from "#metadata/keys";
4
5
  /**
5
- * Creates an empty auto-register registry.
6
+ * Creates an empty auto-register registry, loaded under `name`.
6
7
  *
7
8
  * @since 0.3.16-canary.0
8
9
  */
9
- export function createAutoRegisterRegistry() {
10
+ export function createAutoRegisterRegistry(name) {
10
11
  const registeredEntries = [];
12
+ // A setup callback rather than declarations, so a class decorated after the registry exists still loads.
13
+ const module = Module.create(name, (builder) => {
14
+ for (const { target, scope } of registeredEntries) {
15
+ APPLY_BINDING_SCOPE[scope](builder.bind(target).toSelf());
16
+ }
17
+ });
11
18
  return {
19
+ ...module,
12
20
  register(target, scope) {
13
21
  registeredEntries.push({ target, scope });
14
22
  },
@@ -17,6 +25,19 @@ export function createAutoRegisterRegistry() {
17
25
  },
18
26
  };
19
27
  }
28
+ // A Record rather than an if-chain, so a new `BindingScope` is a compile error here instead of
29
+ // silently landing in whichever branch happened to be last.
30
+ const APPLY_BINDING_SCOPE = {
31
+ singleton: (builder) => {
32
+ builder.singleton();
33
+ },
34
+ scoped: (builder) => {
35
+ builder.scoped();
36
+ },
37
+ transient: (builder) => {
38
+ builder.transient();
39
+ },
40
+ };
20
41
  /**
21
42
  * Writes the declared dependencies into the class's metadata and optionally auto-registers it.
22
43
  *
package/dist/errors.d.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  import type { ConstraintRequirement } from "#core/constraint-requirement";
2
2
  import type { BindingIdentifier, BindingScope, ResolveOptions } from "#core/types";
3
+ /**
4
+ * The machine-readable code of every error the library throws.
5
+ *
6
+ * @since 0.14.0
7
+ */
8
+ export type DiErrorCode = "AMBIGUOUS_BINDING" | "ASYNC_ACTIVATION" | "ASYNC_DEACTIVATION" | "ASYNC_MODULE_LOAD" | "ASYNC_RESOLUTION" | "CHAIN_ALREADY_REGISTERED" | "CHAIN_NOT_REGISTERED" | "CIRCULAR_DEPENDENCY" | "DISPOSED_CONTAINER" | "EMPTY_TAG_CRITERIA" | "INTERNAL_ERROR" | "INVALID_BINDING_DECLARATION" | "INVALID_METADATA" | "MANY_BINDING_SLOT" | "MISSING_CONTAINER_CONTEXT" | "MISSING_DECORATOR_METADATA" | "MISSING_METADATA" | "MISSING_SCOPE_CONTEXT" | "NO_MATCHING_BINDING" | "PRIVATE_LIFECYCLE_METHOD" | "REBIND_UNBOUND_TOKEN" | "SCOPE_VIOLATION" | "SELF_BINDING_REQUIRES_CLASS" | "STATIC_MEMBER_DECORATOR" | "SYMBOL_KEYED_LIFECYCLE" | "TOKEN_NOT_BOUND" | "UNREACHABLE_CONSTRAINT" | "UNREACHABLE_LIFECYCLE_HOOK";
3
9
  /**
4
10
  * Base class for every error the library throws, each carrying a machine-readable `code`.
5
11
  *
6
12
  * @since 0.3.16-canary.0
7
13
  */
8
14
  export declare abstract class DiError extends Error {
9
- abstract readonly code: string;
15
+ abstract readonly code: DiErrorCode;
10
16
  abstract readonly name: string;
11
17
  }
12
18
  /**
@@ -85,7 +91,10 @@ export declare class AsyncResolutionError extends DiError {
85
91
  constructor(tokenName: string, asyncSourceToken?: string);
86
92
  }
87
93
  /**
88
- * A sync `unbind()` of a binding whose `onDeactivation` handler is async.
94
+ * A sync teardown — `unbind()`, `unbindAll()`, `rebind()` or `unload()` — that reached an async deactivation hook.
95
+ *
96
+ * @remarks By the time it is thrown every deactivation stage of the instance has run and the binding
97
+ * is gone; only the promises the async hooks returned were left unawaited.
89
98
  *
90
99
  * @since 0.3.16-canary.0
91
100
  */
package/dist/errors.js CHANGED
@@ -148,7 +148,10 @@ export class AsyncResolutionError extends DiError {
148
148
  }
149
149
  }
150
150
  /**
151
- * A sync `unbind()` of a binding whose `onDeactivation` handler is async.
151
+ * A sync teardown — `unbind()`, `unbindAll()`, `rebind()` or `unload()` — that reached an async deactivation hook.
152
+ *
153
+ * @remarks By the time it is thrown every deactivation stage of the instance has run and the binding
154
+ * is gone; only the promises the async hooks returned were left unawaited.
152
155
  *
153
156
  * @since 0.3.16-canary.0
154
157
  */
@@ -157,7 +160,7 @@ export class AsyncDeactivationError extends DiError {
157
160
  code = "ASYNC_DEACTIVATION";
158
161
  tokenName;
159
162
  constructor(tokenName) {
160
- super(`Token '${tokenName}' has an async onDeactivation handler. Use unbindAsync() instead.`);
163
+ super(`Token '${tokenName}' has an async deactivation hook: every hook ran, but its promise was not awaited. Use unbindAsync() or unloadAsync() instead.`);
161
164
  this.tokenName = tokenName;
162
165
  }
163
166
  }
@@ -534,7 +537,7 @@ export class AsyncActivationError extends DiError {
534
537
  methodName;
535
538
  constructor(tokenName, hookKind, methodName) {
536
539
  const detail = hookKind === "postConstruct"
537
- ? `@postConstruct method '${methodName ?? ""}' returned a Promise`
540
+ ? `@postConstruct method '${methodName ?? ""}' of '${tokenName}' returned a Promise`
538
541
  : `onActivation for '${tokenName}' returned a Promise`;
539
542
  super(`${detail}. Use resolveAsync() instead.`);
540
543
  this.tokenName = tokenName;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- export type { ActivationHandler, BindingConstraint, BindingIdentifier, BindingKind, BindingScope, BindingTag, ConstraintContext, Constructor, DependencyKey, DeactivationHandler, ResolutionFrame, ResolveOptions, ResolutionContext, TokenValue, } from "#core/types";
1
+ export type { ActivationHandler, BindingConstraint, BindingIdentifier, BindingKind, BindingScope, BindingTag, ConstraintContext, Constructor, DependencyKey, DeactivationHandler, ResolutionFrame, ResolveOptions, ResolutionContext, Resolver, TokenValue, } from "#core/types";
2
2
  export { token, tokenName } from "#core/token";
3
3
  export type { SlotNamesOf, Token } from "#core/token";
4
4
  export { coversTagKeys, NO_TAG_KEYS, slotName, tag, tagKeyMaskOf } from "#core/tag";
5
5
  export type { TagKey, TagKeyMask } from "#core/tag";
6
- export type { AliasBindingBuilder, BindToBuilder, BindingBuilder, ConstantBindingBuilder, ScopedBindingBuilder, SingletonBindingBuilder, SingletonLifecycleBuilder, SlotConstrainedBuilder, TransientBindingBuilder, } from "#core/binding-builders";
6
+ export type { AliasBindingBuilder, Binder, BindToBuilder, BindingBuilder, ClassBindToBuilder, ConstantBindingBuilder, ScopedBindingBuilder, SingletonBindingBuilder, SingletonLifecycleBuilder, SlotConstrainedBuilder, TransientBindingBuilder, } from "#core/binding-builders";
7
7
  export { Container } from "#container/container";
8
- export type { Container as ContainerInterface, ContainerOptions, ContainerStatic } from "#container/container";
8
+ export type { ContainerOptions, ContainerStatic } from "#container/container";
9
+ export { explain, generateDependencyGraph, inspect, lookupBindings, validate } from "#container/introspect";
9
10
  export { getActiveContainer, runWithContainer } from "#ambient-container";
10
11
  export { bindingSlotToResolveOptions, injectionSlotToResolveOptions, resolveOptionsForSlot, } from "#injection/dependency-slot";
11
12
  export type { DependencySlot } from "#injection/dependency-slot";
@@ -13,12 +14,12 @@ export type { BindingSnapshot, ContainerSnapshot } from "#introspection/inspecto
13
14
  export type { CandidateExplanation, CandidateVerdict, ExplainOptions, ExplanationOutcome, ExplanationStep, ResolutionExplanation, SelectionRule, } from "#introspection/explanation";
14
15
  export type { CandidateRule } from "#resolution/select/candidates";
15
16
  export type { ContainerGraphJson, GraphEdge, GraphNode, GraphOptions } from "#introspection/dependency-graph";
16
- export { AsyncModule, isSyncModule, Module, SyncModule } from "#core/module";
17
- export type { AsyncModuleBuilder, ModuleBuilder } from "#core/module";
17
+ export { isSyncModule, Module } from "#core/module";
18
+ export type { AsyncModule, AsyncModuleBuilder, ModuleBuilder, SyncModule } from "#core/module";
18
19
  export { binding } from "#core/binding-declaration";
19
20
  export type { BindingDeclaration, BindingDefinition } from "#core/binding-declaration";
20
21
  export { inject } from "#decorators/inject";
21
- export { injectAll, isInjectionDescriptor, optional } from "#injection/descriptor";
22
+ export { injectAll, injectOptional, isInjectionDescriptor } from "#injection/descriptor";
22
23
  export type { InjectionDescriptor, InjectOptions } from "#injection/descriptor";
23
24
  export { injectable } from "#decorators/injectable";
24
25
  export type { InjectableDependency, InjectableOptions } from "#decorators/injectable";
@@ -30,7 +31,7 @@ export type { ConstructorMetadata, LifecycleMetadata, MetadataReader, MutableLif
30
31
  export { defaultMetadataReader, SymbolMetadataReader } from "#metadata/symbol-reader";
31
32
  export { whenAnyAncestorIs, whenAnyAncestorNamed, whenAnyAncestorTagged, whenAnyAncestorTaggedAll, whenNoAncestorIs, whenNoParentIs, whenParentIs, whenParentNamed, whenParentTagged, whenParentTaggedAll, } from "#resolution/select/constraints";
32
33
  export { AmbiguousBindingError, AsyncActivationError, AsyncDeactivationError, AsyncModuleLoadError, AsyncResolutionError, ChainAlreadyRegisteredError, ChainNotRegisteredError, ManyBindingSlotError, CircularDependencyError, DiError, DisposedContainerError, InternalError, InvalidBindingDeclarationError, InvalidMetadataError, MissingContainerContextError, MissingDecoratorMetadataError, MissingMetadataError, MissingScopeContextError, NoMatchingBindingError, RebindUnboundTokenError, ScopeViolationError, SelfBindingRequiresClassError, PrivateLifecycleMethodError, StaticMemberDecoratorError, SymbolKeyedLifecycleError, EmptyTagCriteriaError, TokenNotBoundError, UnreachableConstraintError, UnreachableLifecycleHookError, } from "#errors";
33
- export type { ScopeViolationDetails } from "#errors";
34
+ export type { DiErrorCode, ScopeViolationDetails } from "#errors";
34
35
  export { toDotGraph } from "#introspection/graph-adapters/dot";
35
36
  export { toCytoscapeGraph } from "#introspection/graph-adapters/cytoscape";
36
37
  export type { CytoscapeEdge, CytoscapeElements, CytoscapeNode } from "#introspection/graph-adapters/cytoscape";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ export { token, tokenName } from "#core/token";
4
4
  export { coversTagKeys, NO_TAG_KEYS, slotName, tag, tagKeyMaskOf } from "#core/tag";
5
5
  // Container
6
6
  export { Container } from "#container/container";
7
+ export { explain, generateDependencyGraph, inspect, lookupBindings, validate } from "#container/introspect";
7
8
  // Ambient container — the context an `@inject` accessor initializer resolves from. `resolution/context`
8
9
  // stays internal: it hands out resolver callbacks, not public values.
9
10
  export { getActiveContainer, runWithContainer } from "#ambient-container";
@@ -11,11 +12,11 @@ export { getActiveContainer, runWithContainer } from "#ambient-container";
11
12
  // public API hands one out. `BindingSnapshot.scope` and `GraphNode.scope` are the public answers.
12
13
  export { bindingSlotToResolveOptions, injectionSlotToResolveOptions, resolveOptionsForSlot, } from "#injection/dependency-slot";
13
14
  // Module
14
- export { AsyncModule, isSyncModule, Module, SyncModule } from "#core/module";
15
+ export { isSyncModule, Module } from "#core/module";
15
16
  export { binding } from "#core/binding-declaration";
16
17
  // Decorators
17
18
  export { inject } from "#decorators/inject";
18
- export { injectAll, isInjectionDescriptor, optional } from "#injection/descriptor";
19
+ export { injectAll, injectOptional, isInjectionDescriptor } from "#injection/descriptor";
19
20
  export { injectable } from "#decorators/injectable";
20
21
  export { postConstruct, preDestroy } from "#decorators/lifecycle";
21
22
  // Auto-register
@@ -1,6 +1,7 @@
1
1
  import type { BindingTag } from "#core/tag";
2
2
  import type { Token } from "#core/token";
3
3
  import type { Constructor, ResolveOptions } from "#core/types";
4
+ import type { ParamMetadata } from "#metadata/types";
4
5
  /**
5
6
  * What one resolvable dependency declares.
6
7
  *
@@ -61,6 +62,22 @@ export declare function resolveOptionsForSlot(injectionSlot: DependencySlot): Re
61
62
  * @since 0.8.0
62
63
  */
63
64
  export declare function singleCriterionForSlot(injectionSlot: DependencySlot): BindingTag | null;
65
+ /**
66
+ * A copy of a slot in the one shape the engine resolves, its options and lone criterion settled up front.
67
+ *
68
+ * @remarks The engine passes every slot it resolves through here once — a factory's dependencies when it is bound, a
69
+ * class's parameters when they are settled — so a dependency read meets one hidden class and never adds a memo. A lone
70
+ * name whose criterion is still unknown is left unsettled, since a later bind can fold it.
71
+ *
72
+ * @since 0.14.0
73
+ */
74
+ export declare function settledSlot(slot: DependencySlot): DependencySlot;
75
+ /**
76
+ * A copy of a constructor parameter in the one shape the engine resolves, as `settledSlot` makes one.
77
+ *
78
+ * @since 0.14.0
79
+ */
80
+ export declare function settledParam(param: ParamMetadata): ParamMetadata;
64
81
  /**
65
82
  * Resolve options derived from a binding slot (tags may be empty; omits when nothing to match).
66
83
  *
@@ -140,6 +140,52 @@ export function singleCriterionForSlot(injectionSlot) {
140
140
  }
141
141
  return folded;
142
142
  }
143
+ /**
144
+ * A copy of a slot in the one shape the engine resolves, its options and lone criterion settled up front.
145
+ *
146
+ * @remarks The engine passes every slot it resolves through here once — a factory's dependencies when it is bound, a
147
+ * class's parameters when they are settled — so a dependency read meets one hidden class and never adds a memo. A lone
148
+ * name whose criterion is still unknown is left unsettled, since a later bind can fold it.
149
+ *
150
+ * @since 0.14.0
151
+ */
152
+ export function settledSlot(slot) {
153
+ const options = resolveOptionsForSlot(slot);
154
+ const settled = {
155
+ token: slot.token,
156
+ optional: slot.optional,
157
+ multi: slot.multi,
158
+ name: slot.name,
159
+ tags: slot.tags,
160
+ [MEMOIZED_RESOLVE_OPTIONS]: options,
161
+ [MEMOIZED_SINGLE_CRITERION]: settledCriterionOf(options),
162
+ };
163
+ return settled;
164
+ }
165
+ /**
166
+ * A copy of a constructor parameter in the one shape the engine resolves, as `settledSlot` makes one.
167
+ *
168
+ * @since 0.14.0
169
+ */
170
+ export function settledParam(param) {
171
+ const options = resolveOptionsForSlot(param);
172
+ const settled = {
173
+ index: param.index,
174
+ token: param.token,
175
+ optional: param.optional,
176
+ multi: param.multi,
177
+ name: param.name,
178
+ tags: param.tags,
179
+ [MEMOIZED_RESOLVE_OPTIONS]: options,
180
+ [MEMOIZED_SINGLE_CRITERION]: settledCriterionOf(options),
181
+ };
182
+ return settled;
183
+ }
184
+ /** The lone criterion `singleCriterionForSlot` would memoize for these options, or `undefined` where it would not. */
185
+ function settledCriterionOf(options) {
186
+ const criterion = singleCriterionOnlyOf(options);
187
+ return criterion !== undefined || !isLoneNameOptions(options) ? (criterion ?? null) : undefined;
188
+ }
143
189
  /** A slot request whose only criterion is a name — the one shape whose fold can change after a bind. */
144
190
  function isLoneNameOptions(options) {
145
191
  // Slot-derived options never carry the `tag` shorthand — `buildOptions` folds it into `tags`.
@@ -44,7 +44,7 @@ export type InjectableDependency<Value = unknown> = Token<Value> | Constructor<V
44
44
  /**
45
45
  * The value a factory receives for one declared dependency.
46
46
  *
47
- * @remarks `optional()` and `injectAll()` fold their effect into the descriptor's own type
47
+ * @remarks `injectOptional()` and `injectAll()` fold their effect into the descriptor's own type
48
48
  * parameter, so reading it back is enough; bare tokens fall through to {@link TokenValue}.
49
49
  *
50
50
  * @since 0.5.0-canary.7
@@ -59,7 +59,7 @@ export type ResolvedDependencyValue<Dependency> = Dependency extends {
59
59
  *
60
60
  * @remarks Split out because a hand-written descriptor states its flags and its value type
61
61
  * separately, and only the flags are load-bearing: `{ token: Plugin, multi: true }` says `Plugin`
62
- * and delivers `ReadonlyArray<Plugin>`. `injectAll()` and `optional()` already fold their effect in, so the
62
+ * and delivers `ReadonlyArray<Plugin>`. `injectAll()` and `injectOptional()` already fold their effect in, so the
63
63
  * flags find an array or an optional there and leave it alone.
64
64
  */
65
65
  type DescribedValue<Dependency> = Dependency extends InjectionDescriptor<infer Value> ? Value : TokenValue<Dependency>;
@@ -75,6 +75,12 @@ export declare function isInjectionDescriptor(value: unknown): value is Injectio
75
75
  * @since 0.3.16-canary.0
76
76
  */
77
77
  export declare function normalizeToDescriptor(dependency: InjectableDependency): InjectionDescriptor;
78
+ /**
79
+ * Normalises a factory's declared dependencies to settled descriptors, the one shape the engine resolves.
80
+ *
81
+ * @since 0.14.0
82
+ */
83
+ export declare function settledDescriptorsOf(dependencies: ReadonlyArray<InjectableDependency>): Array<InjectionDescriptor>;
78
84
  /**
79
85
  * The descriptor half of `inject()`, shared with the accessor decorator that wraps it.
80
86
  *
@@ -86,7 +92,7 @@ export declare function buildInjectionDescriptor<Value, Names extends string = s
86
92
  *
87
93
  * @since 0.3.16-canary.0
88
94
  */
89
- export declare function optional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<InjectOptions<Names>>): InjectionDescriptor<Value | undefined>;
95
+ export declare function injectOptional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<InjectOptions<Names>>): InjectionDescriptor<Value | undefined>;
90
96
  /**
91
97
  * Creates a descriptor that resolves every matching binding for the token into a read-only array.
92
98
  *
@@ -1,3 +1,4 @@
1
+ import { settledSlot } from "#injection/dependency-slot";
1
2
  /**
2
3
  * Returns whether the value is an `InjectionDescriptor`, dual-role `inject()` functions included.
3
4
  *
@@ -25,6 +26,14 @@ export function normalizeToDescriptor(dependency) {
25
26
  }
26
27
  return { token: dependency, optional: false, multi: false };
27
28
  }
29
+ /**
30
+ * Normalises a factory's declared dependencies to settled descriptors, the one shape the engine resolves.
31
+ *
32
+ * @since 0.14.0
33
+ */
34
+ export function settledDescriptorsOf(dependencies) {
35
+ return dependencies.map((dependency) => settledSlot(normalizeToDescriptor(dependency)));
36
+ }
28
37
  /**
29
38
  * Dual-role `inject()` values are functions: [[Function]].name must not be treated as a DI slot name.
30
39
  * Only enumerable own `name` / `tags` from `Object.defineProperties` are real injection options.
@@ -100,7 +109,7 @@ export function buildInjectionDescriptor(token, options) {
100
109
  *
101
110
  * @since 0.3.16-canary.0
102
111
  */
103
- export function optional(token, options) {
112
+ export function injectOptional(token, options) {
104
113
  return withOptions({
105
114
  token,
106
115
  optional: true,