@codefast/di 0.12.0 → 0.14.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 (54) hide show
  1. package/CHANGELOG.md +192 -0
  2. package/README.md +142 -43
  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 -30
  7. package/dist/container/container.js +59 -243
  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 +27 -3
  11. package/dist/core/binding-declaration.d.ts +2 -2
  12. package/dist/core/binding-declaration.js +4 -4
  13. package/dist/core/module.d.ts +4 -25
  14. package/dist/core/module.js +3 -27
  15. package/dist/core/state-epoch.d.ts +1 -1
  16. package/dist/core/state-epoch.js +1 -1
  17. package/dist/core/types.d.ts +16 -7
  18. package/dist/decorators/inject.d.ts +3 -1
  19. package/dist/decorators/inject.js +27 -22
  20. package/dist/decorators/injectable.d.ts +14 -18
  21. package/dist/decorators/injectable.js +23 -2
  22. package/dist/decorators/lifecycle.d.ts +9 -3
  23. package/dist/decorators/lifecycle.js +5 -1
  24. package/dist/errors.d.ts +33 -15
  25. package/dist/errors.js +41 -21
  26. package/dist/index.d.ts +9 -8
  27. package/dist/index.js +4 -3
  28. package/dist/injection/dependency-slot.d.ts +17 -0
  29. package/dist/injection/dependency-slot.js +46 -0
  30. package/dist/injection/descriptor.d.ts +9 -3
  31. package/dist/injection/descriptor.js +10 -1
  32. package/dist/introspection/explanation.js +26 -8
  33. package/dist/introspection/validation.d.ts +28 -0
  34. package/dist/introspection/validation.js +244 -0
  35. package/dist/lifecycle/hooks.d.ts +13 -2
  36. package/dist/lifecycle/hooks.js +36 -18
  37. package/dist/lifecycle/scopes.d.ts +21 -2
  38. package/dist/lifecycle/scopes.js +86 -2
  39. package/dist/metadata/keys.d.ts +1 -1
  40. package/dist/metadata/keys.js +1 -1
  41. package/dist/resolution/cache/class-introspector.d.ts +7 -8
  42. package/dist/resolution/cache/class-introspector.js +40 -3
  43. package/dist/resolution/cache/lookup.d.ts +10 -0
  44. package/dist/resolution/cache/lookup.js +27 -0
  45. package/dist/resolution/context.d.ts +12 -12
  46. package/dist/resolution/path.d.ts +12 -2
  47. package/dist/resolution/path.js +22 -2
  48. package/dist/resolution/plan/codegen.d.ts +2 -1
  49. package/dist/resolution/plan/codegen.js +1 -1
  50. package/dist/resolution/plan/compiler.d.ts +6 -6
  51. package/dist/resolution/plan/compiler.js +152 -22
  52. package/dist/resolution/resolver.d.ts +6 -0
  53. package/dist/resolution/resolver.js +39 -84
  54. package/package.json +11 -3
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
  /**
@@ -28,7 +34,9 @@ export declare class TokenNotBoundError extends DiError {
28
34
  readonly name = "TokenNotBoundError";
29
35
  readonly code = "TOKEN_NOT_BOUND";
30
36
  readonly tokenName: string;
31
- constructor(tokenName: string);
37
+ /** The token names from the outermost request down to the unbound one, which is last. */
38
+ readonly path: ReadonlyArray<string>;
39
+ constructor(tokenName: string, path?: ReadonlyArray<string>);
32
40
  }
33
41
  /**
34
42
  * A token that has bindings, none of whose slots match the given `ResolveOptions`.
@@ -41,7 +49,9 @@ export declare class NoMatchingBindingError extends DiError {
41
49
  readonly tokenName: string;
42
50
  readonly options: ResolveOptions;
43
51
  readonly availableSlots: Array<string>;
44
- constructor(tokenName: string, options: ResolveOptions, availableSlots: Array<string>);
52
+ /** The token names from the outermost request down to the unmatched one, which is last. */
53
+ readonly path: ReadonlyArray<string>;
54
+ constructor(tokenName: string, options: ResolveOptions, availableSlots: Array<string>, path?: ReadonlyArray<string>);
45
55
  }
46
56
  /**
47
57
  * Two or more candidate bindings that matched without the more-specific rule deciding a winner.
@@ -81,7 +91,10 @@ export declare class AsyncResolutionError extends DiError {
81
91
  constructor(tokenName: string, asyncSourceToken?: string);
82
92
  }
83
93
  /**
84
- * 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.
85
98
  *
86
99
  * @since 0.3.16-canary.0
87
100
  */
@@ -162,7 +175,7 @@ export declare class UnreachableLifecycleHookError extends DiError {
162
175
  readonly code = "UNREACHABLE_LIFECYCLE_HOOK";
163
176
  readonly tokenName: string;
164
177
  readonly phase: "onActivation" | "onDeactivation";
165
- /** Nothing binds the token, or — for a deactivation hook — every binding it has is transient or scoped. */
178
+ /** Nothing binds the token, or — for a deactivation hook — every binding it has is transient. */
166
179
  readonly reason: "unbound" | "no-deactivatable-binding";
167
180
  constructor(tokenName: string, phase: "onActivation" | "onDeactivation", reason?: "unbound" | "no-deactivatable-binding");
168
181
  }
@@ -207,16 +220,6 @@ export declare class AsyncModuleLoadError extends DiError {
207
220
  readonly moduleName: string;
208
221
  constructor(moduleName: string);
209
222
  }
210
- /**
211
- * A synchronous disposal attempt on a container whose `onDeactivation` handlers may be async.
212
- *
213
- * @since 0.3.16-canary.0
214
- */
215
- export declare class SyncDisposalNotSupportedError extends DiError {
216
- readonly name = "SyncDisposalNotSupportedError";
217
- readonly code = "SYNC_DISPOSAL_NOT_SUPPORTED";
218
- constructor();
219
- }
220
223
  /**
221
224
  * A `scoped` binding resolved from a container with no child scope context.
222
225
  *
@@ -342,6 +345,21 @@ export declare class SymbolKeyedLifecycleError extends DiError {
342
345
  readonly memberName: string;
343
346
  constructor(decoratorName: string, memberName: string);
344
347
  }
348
+ /**
349
+ * A `@postConstruct` or `@preDestroy` on a private method, which the lifecycle reader cannot call by name.
350
+ *
351
+ * @remarks Reported at decoration rather than at resolve, so the error points at the declaration
352
+ * instead of a `MetadataReader` the caller never configured.
353
+ *
354
+ * @since 0.13.0
355
+ */
356
+ export declare class PrivateLifecycleMethodError extends DiError {
357
+ readonly name = "PrivateLifecycleMethodError";
358
+ readonly code = "PRIVATE_LIFECYCLE_METHOD";
359
+ readonly decoratorName: string;
360
+ readonly memberName: string;
361
+ constructor(decoratorName: string, memberName: string);
362
+ }
345
363
  /**
346
364
  * A decorator handed no metadata object, because the runtime has no `Symbol.metadata` to key one by.
347
365
  *
package/dist/errors.js CHANGED
@@ -18,6 +18,10 @@ export class InternalError extends DiError {
18
18
  super(message);
19
19
  }
20
20
  }
21
+ // A path of one token only repeats the name the message already opens with.
22
+ function pathSuffix(path) {
23
+ return path.length > 1 ? ` Path: ${path.join(" → ")}` : "";
24
+ }
21
25
  /**
22
26
  * A token with no binding at all, even after walking the parent container chain.
23
27
  *
@@ -27,9 +31,12 @@ export class TokenNotBoundError extends DiError {
27
31
  name = "TokenNotBoundError";
28
32
  code = "TOKEN_NOT_BOUND";
29
33
  tokenName;
30
- constructor(tokenName) {
31
- super(`No binding found for token '${tokenName}'. Did you forget container.bind(${tokenName})?`);
34
+ /** The token names from the outermost request down to the unbound one, which is last. */
35
+ path;
36
+ constructor(tokenName, path = [tokenName]) {
37
+ super(`No binding found for token '${tokenName}'. Did you forget container.bind(${tokenName})?${pathSuffix(path)}`);
32
38
  this.tokenName = tokenName;
39
+ this.path = path;
33
40
  }
34
41
  }
35
42
  // Options carry caller values a tag may hold — a bigint or a circular object must not make the
@@ -78,13 +85,16 @@ export class NoMatchingBindingError extends DiError {
78
85
  tokenName;
79
86
  options;
80
87
  availableSlots;
81
- constructor(tokenName, options, availableSlots) {
88
+ /** The token names from the outermost request down to the unmatched one, which is last. */
89
+ path;
90
+ constructor(tokenName, options, availableSlots, path = [tokenName]) {
82
91
  const optionsString = describeResolveOptions(options);
83
92
  const slotsStr = availableSlots.join(", ");
84
- super(`No binding for '${tokenName}' matching ${optionsString}. Available slots: [${slotsStr}].`);
93
+ super(`No binding for '${tokenName}' matching ${optionsString}. Available slots: [${slotsStr}].${pathSuffix(path)}`);
85
94
  this.tokenName = tokenName;
86
95
  this.options = options;
87
96
  this.availableSlots = availableSlots;
97
+ this.path = path;
88
98
  }
89
99
  }
90
100
  /**
@@ -138,7 +148,10 @@ export class AsyncResolutionError extends DiError {
138
148
  }
139
149
  }
140
150
  /**
141
- * 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.
142
155
  *
143
156
  * @since 0.3.16-canary.0
144
157
  */
@@ -147,7 +160,7 @@ export class AsyncDeactivationError extends DiError {
147
160
  code = "ASYNC_DEACTIVATION";
148
161
  tokenName;
149
162
  constructor(tokenName) {
150
- 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.`);
151
164
  this.tokenName = tokenName;
152
165
  }
153
166
  }
@@ -225,12 +238,12 @@ export class UnreachableLifecycleHookError extends DiError {
225
238
  code = "UNREACHABLE_LIFECYCLE_HOOK";
226
239
  tokenName;
227
240
  phase;
228
- /** Nothing binds the token, or — for a deactivation hook — every binding it has is transient or scoped. */
241
+ /** Nothing binds the token, or — for a deactivation hook — every binding it has is transient. */
229
242
  reason;
230
243
  constructor(tokenName, phase, reason = "unbound") {
231
244
  super(reason === "unbound"
232
245
  ? `${phase}() is registered for '${tokenName}', which nothing is bound to in this container or its ancestors, so the hook can never run. Bind the token, or — if '${tokenName}' is a class you bound as an implementation via .to(${tokenName}) — register the hook against the token you bound instead.`
233
- : `${phase}() is registered for '${tokenName}', whose every binding in this container and its ancestors is transient or scoped, so the hook can never run: only a singleton or a constant is deactivated. Make one of its bindings a singleton, or drop the hook.`);
246
+ : `${phase}() is registered for '${tokenName}', whose every binding in this container and its ancestors is transient, so the hook can never run: a transient instance is never deactivated. Make one of its bindings a singleton or scoped, or drop the hook.`);
234
247
  this.tokenName = tokenName;
235
248
  this.phase = phase;
236
249
  this.reason = reason;
@@ -286,18 +299,6 @@ export class AsyncModuleLoadError extends DiError {
286
299
  this.moduleName = moduleName;
287
300
  }
288
301
  }
289
- /**
290
- * A synchronous disposal attempt on a container whose `onDeactivation` handlers may be async.
291
- *
292
- * @since 0.3.16-canary.0
293
- */
294
- export class SyncDisposalNotSupportedError extends DiError {
295
- name = "SyncDisposalNotSupportedError";
296
- code = "SYNC_DISPOSAL_NOT_SUPPORTED";
297
- constructor() {
298
- super("Container cannot be disposed synchronously because onDeactivation handlers may be async. Use `await using` or call container.dispose() explicitly.");
299
- }
300
- }
301
302
  /**
302
303
  * A `scoped` binding resolved from a container with no child scope context.
303
304
  *
@@ -456,6 +457,25 @@ export class SymbolKeyedLifecycleError extends DiError {
456
457
  this.memberName = memberName;
457
458
  }
458
459
  }
460
+ /**
461
+ * A `@postConstruct` or `@preDestroy` on a private method, which the lifecycle reader cannot call by name.
462
+ *
463
+ * @remarks Reported at decoration rather than at resolve, so the error points at the declaration
464
+ * instead of a `MetadataReader` the caller never configured.
465
+ *
466
+ * @since 0.13.0
467
+ */
468
+ export class PrivateLifecycleMethodError extends DiError {
469
+ name = "PrivateLifecycleMethodError";
470
+ code = "PRIVATE_LIFECYCLE_METHOD";
471
+ decoratorName;
472
+ memberName;
473
+ constructor(decoratorName, memberName) {
474
+ super(`@${decoratorName}() does not support a private method ('${memberName}'). Make the lifecycle method public, and call the private code from it.`);
475
+ this.decoratorName = decoratorName;
476
+ this.memberName = memberName;
477
+ }
478
+ }
459
479
  /**
460
480
  * A decorator handed no metadata object, because the runtime has no `Symbol.metadata` to key one by.
461
481
  *
@@ -517,7 +537,7 @@ export class AsyncActivationError extends DiError {
517
537
  methodName;
518
538
  constructor(tokenName, hookKind, methodName) {
519
539
  const detail = hookKind === "postConstruct"
520
- ? `@postConstruct method '${methodName ?? ""}' returned a Promise`
540
+ ? `@postConstruct method '${methodName ?? ""}' of '${tokenName}' returned a Promise`
521
541
  : `onActivation for '${tokenName}' returned a Promise`;
522
542
  super(`${detail}. Use resolveAsync() instead.`);
523
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";
@@ -29,8 +30,8 @@ export { MetadataReaderToken } from "#metadata/reader-token";
29
30
  export type { ConstructorMetadata, LifecycleMetadata, MetadataReader, MutableLifecycleMetadata, ParamMetadata, } from "#metadata/types";
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
- export { AmbiguousBindingError, AsyncActivationError, AsyncDeactivationError, AsyncModuleLoadError, AsyncResolutionError, ChainAlreadyRegisteredError, ChainNotRegisteredError, ManyBindingSlotError, CircularDependencyError, DiError, DisposedContainerError, InternalError, InvalidBindingDeclarationError, InvalidMetadataError, MissingContainerContextError, MissingDecoratorMetadataError, MissingMetadataError, MissingScopeContextError, NoMatchingBindingError, RebindUnboundTokenError, ScopeViolationError, SelfBindingRequiresClassError, StaticMemberDecoratorError, SymbolKeyedLifecycleError, SyncDisposalNotSupportedError, EmptyTagCriteriaError, TokenNotBoundError, UnreachableConstraintError, UnreachableLifecycleHookError, } from "#errors";
33
- export type { ScopeViolationDetails } from "#errors";
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";
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
@@ -26,7 +27,7 @@ export { defaultMetadataReader, SymbolMetadataReader } from "#metadata/symbol-re
26
27
  // Constraints — contextual injection predicates for .when()
27
28
  export { whenAnyAncestorIs, whenAnyAncestorNamed, whenAnyAncestorTagged, whenAnyAncestorTaggedAll, whenNoAncestorIs, whenNoParentIs, whenParentIs, whenParentNamed, whenParentTagged, whenParentTaggedAll, } from "#resolution/select/constraints";
28
29
  // Errors
29
- export { AmbiguousBindingError, AsyncActivationError, AsyncDeactivationError, AsyncModuleLoadError, AsyncResolutionError, ChainAlreadyRegisteredError, ChainNotRegisteredError, ManyBindingSlotError, CircularDependencyError, DiError, DisposedContainerError, InternalError, InvalidBindingDeclarationError, InvalidMetadataError, MissingContainerContextError, MissingDecoratorMetadataError, MissingMetadataError, MissingScopeContextError, NoMatchingBindingError, RebindUnboundTokenError, ScopeViolationError, SelfBindingRequiresClassError, StaticMemberDecoratorError, SymbolKeyedLifecycleError, SyncDisposalNotSupportedError, EmptyTagCriteriaError, TokenNotBoundError, UnreachableConstraintError, UnreachableLifecycleHookError, } from "#errors";
30
+ 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";
30
31
  // Graph adapters — render `generateDependencyGraph()` output for common viewers
31
32
  export { toDotGraph } from "#introspection/graph-adapters/dot";
32
33
  export { toCytoscapeGraph } from "#introspection/graph-adapters/cytoscape";
@@ -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,
@@ -3,7 +3,7 @@ import { tokenName } from "#core/token";
3
3
  import { AmbiguousBindingError, CircularDependencyError, InternalError, NoMatchingBindingError, TokenNotBoundError, } from "#errors";
4
4
  import { snapshotOf } from "#introspection/inspector";
5
5
  import { DefaultConstraintContext } from "#resolution/context";
6
- import { buildResolutionFrame } from "#resolution/path";
6
+ import { buildResolutionFrame, missPathOf } from "#resolution/path";
7
7
  import { candidateRuleOf, chooseCandidate, matchesSlot } from "#resolution/select/candidates";
8
8
  // ── Explanation ──────────────────────────────────────────────────────────────────────────────────────────────────────
9
9
  /**
@@ -21,7 +21,7 @@ export function explainRequest(registries, token, options) {
21
21
  for (const ancestor of options?.ancestors ?? []) {
22
22
  const walk = walkLookup(registries, ancestor, undefined, stack);
23
23
  if (walk.binding === undefined) {
24
- throw lookupError(registries, walk);
24
+ throw lookupError(registries, ancestor, walk, stack);
25
25
  }
26
26
  stack.push(buildResolutionFrame(walk.binding, tokenName(walk.binding.token)));
27
27
  }
@@ -57,15 +57,32 @@ function walkLookup(registries, token, request, stack) {
57
57
  lastToken: current,
58
58
  ambiguity: found.eligible,
59
59
  cycle: undefined,
60
+ aliasHops: visited,
60
61
  };
61
62
  }
62
63
  if (found.kind === "none") {
63
64
  const outcome = registries.some((registry) => registry.getAll(current).length > 0) ? "unmatched" : "unbound";
64
- return { steps, binding: undefined, outcome, lastToken: current, ambiguity: undefined, cycle: undefined };
65
+ return {
66
+ steps,
67
+ binding: undefined,
68
+ outcome,
69
+ lastToken: current,
70
+ ambiguity: undefined,
71
+ cycle: undefined,
72
+ aliasHops: visited,
73
+ };
65
74
  }
66
75
  const binding = found.binding;
67
76
  if (binding.kind !== "alias") {
68
- return { steps, binding, outcome: "selected", lastToken: current, ambiguity: undefined, cycle: undefined };
77
+ return {
78
+ steps,
79
+ binding,
80
+ outcome: "selected",
81
+ lastToken: current,
82
+ ambiguity: undefined,
83
+ cycle: undefined,
84
+ aliasHops: visited,
85
+ };
69
86
  }
70
87
  // An alias hop restarts at the container asked, as `resolve` does, and a revisited token is a cycle.
71
88
  const target = binding.target;
@@ -78,6 +95,7 @@ function walkLookup(registries, token, request, stack) {
78
95
  lastToken: current,
79
96
  ambiguity: undefined,
80
97
  cycle: [...visited, target],
98
+ aliasHops: visited,
81
99
  };
82
100
  }
83
101
  visited.add(target);
@@ -133,8 +151,8 @@ function verdictOf(binding, request, ctx) {
133
151
  const predicate = binding.predicate;
134
152
  return predicate === undefined || predicate(ctx) ? "eligible" : "predicate-refused";
135
153
  }
136
- /** The error `resolve` throws for a lookup that ended without a binding. */
137
- function lookupError(registries, walk) {
154
+ /** The error `resolve` throws for a lookup that ended without a binding, named along the path it was made from. */
155
+ function lookupError(registries, requested, walk, stack) {
138
156
  const name = tokenName(walk.lastToken);
139
157
  switch (walk.outcome) {
140
158
  case "ambiguous":
@@ -142,9 +160,9 @@ function lookupError(registries, walk) {
142
160
  case "alias-cycle":
143
161
  return new CircularDependencyError((walk.cycle ?? []).map((entry) => tokenName(entry)));
144
162
  case "unmatched":
145
- return new NoMatchingBindingError(name, {}, registries.flatMap((registry) => registry.getAll(walk.lastToken).map((binding) => bindingSlotToString(binding.slot))));
163
+ return new NoMatchingBindingError(name, {}, registries.flatMap((registry) => registry.getAll(walk.lastToken).map((binding) => bindingSlotToString(binding.slot))), missPathOf(stack, requested, walk.aliasHops));
146
164
  case "unbound":
147
- return new TokenNotBoundError(name);
165
+ return new TokenNotBoundError(name, missPathOf(stack, requested, walk.aliasHops));
148
166
  case "selected":
149
167
  return new InternalError("a lookup that selected a binding has no error");
150
168
  }
@@ -0,0 +1,28 @@
1
+ import type { BindingRegistry } from "#core/registry";
2
+ import type { LifecycleManager } from "#lifecycle/hooks";
3
+ import type { MetadataReader } from "#metadata/types";
4
+ import type { DependencyResolver } from "#resolution/resolver";
5
+ /**
6
+ * What `validate` reads off a container.
7
+ *
8
+ * @remarks `registries` lists the container's own registry first, then each ancestor's, nearest first — the order
9
+ * every chain walk reads them in.
10
+ *
11
+ * @since 0.14.0
12
+ */
13
+ export interface ValidationTarget {
14
+ readonly registries: readonly [BindingRegistry, ...ReadonlyArray<BindingRegistry>];
15
+ readonly resolver: DependencyResolver;
16
+ readonly metadataReader: MetadataReader;
17
+ readonly lifecycle: Pick<LifecycleManager, "hookedTokens">;
18
+ }
19
+ /**
20
+ * Runs every static check over a container's chain, throwing the first error a resolve would meet.
21
+ *
22
+ * @throws `CircularDependencyError`, `ScopeViolationError`, `TokenNotBoundError` or `NoMatchingBindingError` for a
23
+ * singleton graph that cannot resolve, `UnreachableLifecycleHookError` or `UnreachableConstraintError` for a hook or
24
+ * constraint that can never fire.
25
+ *
26
+ * @since 0.14.0
27
+ */
28
+ export declare function validateChain(target: ValidationTarget): void;