@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
@@ -1,19 +1,18 @@
1
1
  import { bindingSlotToString, NO_INSTANCE } from "#core/binding";
2
2
  import { slotNameCriterionOf } from "#core/tag";
3
3
  import { tokenName } from "#core/token";
4
- import { AsyncActivationError, AsyncResolutionError, CircularDependencyError, DisposedContainerError, InternalError, MissingMetadataError, MissingScopeContextError, NoMatchingBindingError, TokenNotBoundError, } from "#errors";
4
+ import { AsyncActivationError, AsyncResolutionError, CircularDependencyError, DisposedContainerError, InternalError, MissingScopeContextError, NoMatchingBindingError, TokenNotBoundError, } from "#errors";
5
5
  import { loneTagBesideNameOf, resolveOptionsForSlot, singleCriterionForSlot, singleCriterionOnlyOf, } from "#injection/dependency-slot";
6
6
  import { SCOPED_MISS } from "#lifecycle/scopes";
7
7
  import { settleInOrder } from "#resolution/async-fan-out";
8
8
  import { ActivationNeedCache } from "#resolution/cache/activation-need";
9
9
  import { ClassIntrospector } from "#resolution/cache/class-introspector";
10
- import { BindingLookupCache } from "#resolution/cache/lookup";
10
+ import { BindingLookupCache, stableCollectionValuesOf } from "#resolution/cache/lookup";
11
11
  import { AsyncLevelContext, DefaultConstraintContext, DefaultResolutionContext } from "#resolution/context";
12
- import { branchDepthOf, buildResolutionFrame, cycleNamesOf, enterSyncPath, extendResolutionBranch, leaveSyncPath, ROOT_BRANCH, UNOWNED_BRANCH, } from "#resolution/path";
12
+ import { branchDepthOf, buildResolutionFrame, cycleNamesOf, enterSyncPath, extendResolutionBranch, leaveSyncPath, missPathOf, ROOT_BRANCH, UNOWNED_BRANCH, } from "#resolution/path";
13
13
  import { InstantiationPlanCompiler, PLAN_RETRY } from "#resolution/plan/compiler";
14
14
  import { matchesSlot, selectAllBindings, selectBinding } from "#resolution/select/candidates";
15
15
  const EMPTY_FRAME_LIST = [];
16
- const EMPTY_PARAM_LIST = [];
17
16
  // A class with no params is constructed with no arguments, so no dependency array is built for it.
18
17
  const NO_ARGUMENTS = [];
19
18
  /** Plans compiled so far, with the `null` unplannable marks left out. */
@@ -252,10 +251,11 @@ export class DependencyResolver {
252
251
  // dominated by that capture. Bindings under the token anywhere in the chain mean the request
253
252
  // matched none of them, so a child reports the same miss its parent would.
254
253
  const bound = this.#allBindingsFromChain(currentToken);
254
+ const path = missPathOf(resolutionStack, token, visitedAliasTokens);
255
255
  if (bound.length > 0) {
256
- throw new NoMatchingBindingError(tokenName(currentToken), options ?? {}, bound.map((binding) => bindingSlotToString(binding.slot)));
256
+ throw new NoMatchingBindingError(tokenName(currentToken), options ?? {}, bound.map((binding) => bindingSlotToString(binding.slot)), path);
257
257
  }
258
- throw new TokenNotBoundError(tokenName(currentToken));
258
+ throw new TokenNotBoundError(tokenName(currentToken), path);
259
259
  }
260
260
  return found;
261
261
  }
@@ -295,6 +295,22 @@ export class DependencyResolver {
295
295
  peekCandidateBindingsForValidate(token, options) {
296
296
  return this.#candidateBindings(token, options, []);
297
297
  }
298
+ /** Every binding the chain holds under a token, nearest container first — for `Container.validate`. */
299
+ bindingsForValidate(token) {
300
+ return this.#allBindingsFromChain(token);
301
+ }
302
+ /** The resolver whose chain a binding this one can see resolves its dependencies from, as a singleton does. */
303
+ ownerForValidate(binding) {
304
+ return this.#ownerOf(binding);
305
+ }
306
+ /** Deactivates a scoped instance of a binding this resolver owns, with its hooks and reader, when it owes a teardown. */
307
+ deactivateScoped(binding, instance) {
308
+ const lifecycle = this.#lifecycle;
309
+ const reader = this.#metadataReader;
310
+ return lifecycle.owesDeactivation(binding, reader)
311
+ ? lifecycle.runDeactivation(binding, instance, reader)
312
+ : undefined;
313
+ }
298
314
  // ── Sync resolve ───────────────────────────────────────────────────────────────────────────────────────────────────
299
315
  resolveFromContext(token, resolutionStack) {
300
316
  // Hot lane: own-registry fast default. Fall back to the chain-versioned memo
@@ -457,19 +473,8 @@ export class DependencyResolver {
457
473
  return {
458
474
  hasActivationHandlers: (binding) => this.#ownerOf(binding).#lifecycle.hasActivationHandlers(binding.token),
459
475
  knownPostConstruct: (target) => classes.knownPostConstruct(target),
460
- needsActiveContainer: (target) => classes.needsActiveContainer(target),
461
- // A plan runs at the top level, so the lent root stack is free when it is; a plan reached
462
- // with the root stack held mints its own path, exactly as the interpreted lane would.
463
- constructWithAccessors: (binding, target, deps) => {
464
- const stack = this.rootStack.length === 0 ? this.rootStack : [];
465
- enterSyncPath(stack, binding, this.#getResolutionFrame(binding));
466
- try {
467
- return classes.instantiate(target, deps, this.#ambientResolutionFor(stack));
468
- }
469
- finally {
470
- leaveSyncPath(stack, binding);
471
- }
472
- },
476
+ accessorSlots: (target) => classes.accessorSlots(target),
477
+ constructWithAccessors: (target, deps, resolution) => classes.construct(target, deps, true, resolution),
473
478
  getConstructorMetadata: (target) => classes.constructorMetadata(target),
474
479
  lookupDependencyEntry: (token) => {
475
480
  const entry = this.#lookup.defaultEntry(token);
@@ -647,7 +652,7 @@ export class DependencyResolver {
647
652
  this.#scope.setSingleton(binding, activated);
648
653
  }
649
654
  else if (scope === "scoped") {
650
- this.#scope.setScoped(binding, activated);
655
+ this.#scope.setScoped(binding, activated, owner);
651
656
  }
652
657
  return activated;
653
658
  }
@@ -715,34 +720,10 @@ export class DependencyResolver {
715
720
  throw new InternalError("alias should have been followed before instantiation");
716
721
  }
717
722
  }
718
- /**
719
- * The parameters a class binding injects.
720
- *
721
- * @remarks A class the metadata reader knows nothing about is constructible only if it declares
722
- * no parameters; anything else is a missing `@injectable()`.
723
- */
723
+ /** The parameters a class binding injects. */
724
724
  #constructorParams(target, facts) {
725
725
  // Metadata is fixed once a class is defined, so the answer is too; only a throw is left unsettled.
726
- return (facts.params ??= this.#settleConstructorParams(target, facts));
727
- }
728
- #settleConstructorParams(target, facts) {
729
- const meta = this.#introspector().constructorMetadataOf(target, facts);
730
- if (meta !== undefined) {
731
- return meta.params;
732
- }
733
- if (target.length === 0) {
734
- // A subclass with an implicit constructor and no own metadata inherits its base's declared
735
- // deps but would be built with zero arguments, injecting `undefined` silently — reject it.
736
- const inherited = this.#introspector().inheritedConstructorMetadata(target);
737
- if (inherited !== undefined && inherited.metadata.params.length > 0) {
738
- throw new MissingMetadataError(target.name, {
739
- baseName: inherited.base.name,
740
- dependencyCount: inherited.metadata.params.length,
741
- });
742
- }
743
- return EMPTY_PARAM_LIST;
744
- }
745
- throw new MissingMetadataError(target.name);
726
+ return (facts.params ??= this.#introspector().settleParams(target, facts));
746
727
  }
747
728
  // One dispatch table for both dependency sources — constructor params and `toResolved`
748
729
  // descriptors declare the same four things.
@@ -823,10 +804,8 @@ export class DependencyResolver {
823
804
  const resolutionStack = this.rootStack;
824
805
  const memo = this.#rootCollection(token, resolutionStack);
825
806
  if (memo.values !== undefined && memo.activationVersion === this.#chainActivationVersion()) {
826
- // A copy, never the memo itself: a caller that writes into its result must not rewrite the
827
- // next caller's. Reading a frozen array is several times slower than reading a plain one, so
828
- // the copy is the cheaper guard by far, and it costs one allocation the read already paid before the memo.
829
- return memo.values.slice();
807
+ // The memo itself: the result is typed read-only, so every caller may share one list.
808
+ return memo.values;
830
809
  }
831
810
  const { candidates } = memo;
832
811
  const resolved = new Array(candidates.length);
@@ -844,7 +823,7 @@ export class DependencyResolver {
844
823
  // Selection runs `when()` predicates and follows aliases, either of which may throw.
845
824
  const memo = this.#rootCollection(token, resolutionStack);
846
825
  if (memo.values !== undefined && memo.activationVersion === this.#chainActivationVersion()) {
847
- return Promise.resolve(memo.values.slice());
826
+ return Promise.resolve(memo.values);
848
827
  }
849
828
  return asPromise(this.#settleCandidates(memo.candidates, undefined, resolutionStack, UNOWNED_BRANCH, (values) => {
850
829
  this.#settleOnRepeat(memo);
@@ -883,24 +862,16 @@ export class DependencyResolver {
883
862
  entry.readBefore = true;
884
863
  }
885
864
  }
886
- /**
887
- * Fills a collection memo's value list once every member is stable: a hook-free constant, or a
888
- * hook-free singleton whose instance is cached — anything that changes either bumps a registry
889
- * version the memo is keyed on. A member still to be materialised leaves the list unfilled.
890
- */
865
+ /** Fills a collection memo's value list once its members are stable and no activation hook exists in the chain. */
891
866
  #settleCollectionValues(entry) {
892
867
  if (entry.values !== undefined || this.#chainActivationVersion() !== 0) {
893
868
  return;
894
869
  }
895
- const { candidates } = entry;
896
- for (let index = 0; index < candidates.length; index += 1) {
897
- if (!isStableCollectionMember(candidates[index])) {
898
- return;
899
- }
870
+ const values = stableCollectionValuesOf(entry.candidates);
871
+ if (values !== undefined) {
872
+ entry.values = values;
873
+ entry.activationVersion = 0;
900
874
  }
901
- // Kept unfrozen: a frozen array reads through a slow elements kind, and every read copies it anyway.
902
- entry.values = candidates.map(stableMemberValue);
903
- entry.activationVersion = 0;
904
875
  }
905
876
  /** Every binding in the chain a `resolveAll` request matches, in chain order. */
906
877
  #candidateBindings(token, options, resolutionStack) {
@@ -1117,13 +1088,13 @@ export class DependencyResolver {
1117
1088
  return activated;
1118
1089
  }
1119
1090
  if (isPending(activated)) {
1120
- return this.#publishInFlight(binding, activated, scope);
1091
+ return this.#publishInFlight(binding, activated, scope, owner);
1121
1092
  }
1122
1093
  if (scope === "singleton") {
1123
1094
  this.#scope.setSingleton(binding, activated);
1124
1095
  }
1125
1096
  else {
1126
- this.#scope.setScoped(binding, activated);
1097
+ this.#scope.setScoped(binding, activated, owner);
1127
1098
  }
1128
1099
  return activated;
1129
1100
  }
@@ -1131,13 +1102,13 @@ export class DependencyResolver {
1131
1102
  * Publishes a pending singleton or scoped materialisation so concurrent callers dedup onto it,
1132
1103
  * and caches what it settles to; the creator, like every joiner, is handed a promise of its own.
1133
1104
  */
1134
- #publishInFlight(binding, pending, scope) {
1105
+ #publishInFlight(binding, pending, scope, owner) {
1135
1106
  const published = pending.then((activated) => {
1136
1107
  if (scope === "singleton") {
1137
1108
  this.#scope.setSingleton(binding, activated);
1138
1109
  }
1139
1110
  else {
1140
- this.#scope.setScoped(binding, activated);
1111
+ this.#scope.setScoped(binding, activated, owner);
1141
1112
  }
1142
1113
  this.#scope.clearInflight(binding.identifier);
1143
1114
  return activated;
@@ -1645,22 +1616,6 @@ export class DependencyResolver {
1645
1616
  return new DefaultResolutionContext(this, resolutionStack, options);
1646
1617
  }
1647
1618
  }
1648
- /**
1649
- * Whether a binding answers a collection read with a fixed value: a hook-free constant, or a
1650
- * singleton whose instance is already cached.
1651
- *
1652
- * @remarks A cached singleton reads like a constant until a registry change evicts it, which also
1653
- * drops the memo.
1654
- */
1655
- function isStableCollectionMember(binding) {
1656
- if (binding.kind === "alias" || binding.activationHook !== undefined) {
1657
- return false;
1658
- }
1659
- return binding.kind === "constant" || (binding.scope === "singleton" && binding.instance !== NO_INSTANCE);
1660
- }
1661
- function stableMemberValue(binding) {
1662
- return binding.kind === "constant" ? binding.value : binding.instance;
1663
- }
1664
1619
  function anyPredicate(bindings) {
1665
1620
  for (let index = 0; index < bindings.length; index += 1) {
1666
1621
  if (bindings[index].predicate !== undefined) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codefast/di",
3
- "version": "0.12.0",
4
- "description": "Lightweight dependency injection primitives for Codefast",
3
+ "version": "0.14.0",
4
+ "description": "Type-safe, zero-dependency dependency injection for TypeScript, on standard decorators",
5
5
  "keywords": [
6
6
  "codefast",
7
7
  "dependency-injection",
@@ -54,6 +54,10 @@
54
54
  "types": "./dist/container/container.d.ts",
55
55
  "import": "./dist/container/container.js"
56
56
  },
57
+ "./container/introspect": {
58
+ "types": "./dist/container/introspect.d.ts",
59
+ "import": "./dist/container/introspect.js"
60
+ },
57
61
  "./core/binding": {
58
62
  "types": "./dist/core/binding.d.ts",
59
63
  "import": "./dist/core/binding.js"
@@ -162,6 +166,10 @@
162
166
  "types": "./dist/introspection/inspector.d.ts",
163
167
  "import": "./dist/introspection/inspector.js"
164
168
  },
169
+ "./introspection/validation": {
170
+ "types": "./dist/introspection/validation.d.ts",
171
+ "import": "./dist/introspection/validation.js"
172
+ },
165
173
  "./lifecycle/hooks": {
166
174
  "types": "./dist/lifecycle/hooks.d.ts",
167
175
  "import": "./dist/lifecycle/hooks.js"
@@ -244,6 +252,6 @@
244
252
  "access": "public"
245
253
  },
246
254
  "engines": {
247
- "node": ">=24.0.0"
255
+ "node": ">=22.18.0"
248
256
  }
249
257
  }