@noego/testing 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,11 @@
1
+ import {
2
+ __require
3
+ } from "./chunk-DGUM43GV.js";
4
+
1
5
  // src/builder.ts
2
6
  import {
3
7
  createContainer,
8
+ ExecutionContext,
4
9
  flattenModule,
5
10
  LoadAs,
6
11
  SCOPED_CONTAINER
@@ -21,23 +26,23 @@ var MissingIocSeamError = class extends TestingError {
21
26
  }
22
27
  };
23
28
  var UnwatchedInspectionError = class extends TestingError {
24
- constructor(token, method) {
29
+ constructor(token2, method) {
25
30
  super(
26
- `Method "${method}" on ${token} is not watched in this environment. Only watched methods are inspectable \u2014 install test.watch() or any test.* behavior/expectation descriptor for it.`
31
+ `Method "${method}" on ${token2} is not watched in this environment. Only watched methods are inspectable \u2014 install test.watch() or any test.* behavior/expectation descriptor for it.`
27
32
  );
28
33
  }
29
34
  };
30
35
  var CallScriptExhaustedError = class extends TestingError {
31
- constructor(token, method, scriptLength, callIndex) {
36
+ constructor(token2, method, scriptLength, callIndex) {
32
37
  super(
33
- `Call #${callIndex} to ${token}.${method} exceeds its test.calls() script of ${scriptLength} ${scriptLength === 1 ? "entry" : "entries"}.`
38
+ `Call #${callIndex} to ${token2}.${method} exceeds its test.calls() script of ${scriptLength} ${scriptLength === 1 ? "entry" : "entries"}.`
34
39
  );
35
40
  }
36
41
  };
37
42
  var ExpectationOverflowError = class extends TestingError {
38
- constructor(token, method, expected, attempted) {
43
+ constructor(token2, method, expected, attempted) {
39
44
  super(
40
- expected === 0 ? `${token}.${method} was expected never to be called, but it was invoked.` : `${token}.${method} was expected exactly ${expected} ${expected === 1 ? "call" : "calls"}, but call #${attempted} arrived.`
45
+ expected === 0 ? `${token2}.${method} was expected never to be called, but it was invoked.` : `${token2}.${method} was expected exactly ${expected} ${expected === 1 ? "call" : "calls"}, but call #${attempted} arrived.`
41
46
  );
42
47
  }
43
48
  };
@@ -51,16 +56,16 @@ var VerificationError = class extends TestingError {
51
56
  }
52
57
  };
53
58
  var MethodNotCallableError = class extends TestingError {
54
- constructor(token, method) {
59
+ constructor(token2, method) {
55
60
  super(
56
- `Cannot install a test.* descriptor on ${token}.${method}: the resolved instance has no callable method with that name.`
61
+ `Cannot install a test.* descriptor on ${token2}.${method}: the resolved instance has no callable method with that name.`
57
62
  );
58
63
  }
59
64
  };
60
65
  var NonObjectMethodTargetError = class extends TestingError {
61
- constructor(token) {
66
+ constructor(token2) {
62
67
  super(
63
- `.methods() is configured for ${token}, but that token resolved to a non-object value. Method descriptors apply only to IoC-managed instances.`
68
+ `.methods() is configured for ${token2}, but that token resolved to a non-object value. Method descriptors apply only to IoC-managed instances.`
64
69
  );
65
70
  }
66
71
  };
@@ -159,14 +164,14 @@ var test = {
159
164
  return frozen({ [DESCRIPTOR]: true, kind: "expect", expected: 0 });
160
165
  },
161
166
  /** Read the recorded history for a watched method in one environment. */
162
- inspect(environment, token, method) {
167
+ inspect(environment, token2, method) {
163
168
  const registry = environment?.[ENV_REGISTRY];
164
169
  if (!registry) {
165
170
  throw new InvalidDescriptorError(
166
171
  "test.inspect() requires a built @noego/testing environment as its first argument."
167
172
  );
168
173
  }
169
- return registry.inspect(token, method);
174
+ return registry.inspect(token2, method);
170
175
  }
171
176
  };
172
177
  Object.freeze(test);
@@ -175,10 +180,10 @@ var ENV_REGISTRY = /* @__PURE__ */ Symbol.for("noego:testing:env-registry");
175
180
  // src/method_state.ts
176
181
  var CONTEXT_WRAPPED = /* @__PURE__ */ Symbol.for("ioc:context-wrapped");
177
182
  var CONTEXT_OWNER = /* @__PURE__ */ Symbol.for("ioc:context-owner");
178
- function tokenLabel(token) {
179
- if (typeof token === "function") return token.name || "[anonymous class]";
180
- if (typeof token === "symbol") return String(token);
181
- return String(token);
183
+ function tokenLabel(token2) {
184
+ if (typeof token2 === "function") return token2.name || "[anonymous class]";
185
+ if (typeof token2 === "symbol") return String(token2);
186
+ return String(token2);
182
187
  }
183
188
  var MethodState = class {
184
189
  constructor(tokenName, method, descriptor) {
@@ -230,31 +235,31 @@ var WatchRegistry = class {
230
235
  return entry.byName ? String(entry.key) : tokenLabel(entry.key);
231
236
  }
232
237
  /** Entries applying to a resolving token (exact identity or name match). */
233
- matchEntries(token) {
234
- const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
238
+ matchEntries(token2) {
239
+ const name = typeof token2 === "function" ? token2.name : typeof token2 === "string" ? token2 : void 0;
235
240
  const matched = this.entries.filter(
236
- (entry) => entry.key === token || entry.byName && name !== void 0 && entry.key === name
241
+ (entry) => entry.key === token2 || entry.byName && name !== void 0 && entry.key === name
237
242
  );
238
243
  if (matched.length) {
239
244
  for (const entry of matched) this.matchedEntryKeys.add(entry.key);
240
- } else if (typeof token === "function" && name) {
241
- this.unmatchedConstructedByName.set(name, token);
245
+ } else if (typeof token2 === "function" && name) {
246
+ this.unmatchedConstructedByName.set(name, token2);
242
247
  }
243
248
  return matched;
244
249
  }
245
250
  state(entryKey, method) {
246
251
  return this.states.get(entryKey)?.get(method);
247
252
  }
248
- inspect(token, method) {
249
- const label = tokenLabel(token);
250
- const keys = [token];
251
- const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
253
+ inspect(token2, method) {
254
+ const label3 = tokenLabel(token2);
255
+ const keys = [token2];
256
+ const name = typeof token2 === "function" ? token2.name : typeof token2 === "string" ? token2 : void 0;
252
257
  if (name !== void 0 && this.nameIndex.has(name)) keys.push(this.nameIndex.get(name));
253
258
  for (const key of keys) {
254
259
  const state = this.states.get(key)?.get(method);
255
260
  if (state) return state.inspection();
256
261
  }
257
- throw new UnwatchedInspectionError(label, method);
262
+ throw new UnwatchedInspectionError(label3, method);
258
263
  }
259
264
  /**
260
265
  * Class-token entries that never identity-matched a construction while a
@@ -327,11 +332,11 @@ function recordOutcome(call, outcome, threw) {
327
332
  }
328
333
  function createMethodDecorator(registry) {
329
334
  const wrappers = /* @__PURE__ */ new WeakMap();
330
- return function decorate(instance, token) {
331
- const entries = registry.matchEntries(token);
335
+ return function decorate(instance, token2) {
336
+ const entries = registry.matchEntries(token2);
332
337
  if (entries.length === 0) return instance;
333
338
  if (instance === null || typeof instance !== "object" && typeof instance !== "function") {
334
- throw new NonObjectMethodTargetError(tokenLabel(token));
339
+ throw new NonObjectMethodTargetError(tokenLabel(token2));
335
340
  }
336
341
  if (wrappers.has(instance)) return wrappers.get(instance);
337
342
  const effective = /* @__PURE__ */ new Map();
@@ -342,7 +347,7 @@ function createMethodDecorator(registry) {
342
347
  }
343
348
  for (const method of effective.keys()) {
344
349
  if (typeof instance[method] !== "function") {
345
- throw new MethodNotCallableError(tokenLabel(token), method);
350
+ throw new MethodNotCallableError(tokenLabel(token2), method);
346
351
  }
347
352
  }
348
353
  const methodCache = /* @__PURE__ */ new Map();
@@ -548,6 +553,18 @@ var TestIocBuilder = class _TestIocBuilder {
548
553
  */
549
554
  async build(options = {}) {
550
555
  const root = options.root ?? createContainer();
556
+ try {
557
+ return await this.buildOnRoot(root, options);
558
+ } catch (primary) {
559
+ try {
560
+ await root.dispose();
561
+ } catch (cleanup) {
562
+ throw new AggregateError([primary, cleanup], "Test IoC build failed and rollback failed", { cause: primary });
563
+ }
564
+ throw primary;
565
+ }
566
+ }
567
+ async buildOnRoot(root, options) {
551
568
  if (typeof root.setInstanceDecorator !== "function") {
552
569
  throw new MissingIocSeamError();
553
570
  }
@@ -555,14 +572,14 @@ var TestIocBuilder = class _TestIocBuilder {
555
572
  const knownByName = /* @__PURE__ */ new Map();
556
573
  const ambiguousNames = /* @__PURE__ */ new Set();
557
574
  const knownLifetimes = /* @__PURE__ */ new Map();
558
- const note = (token, loadAs) => {
559
- const name = typeof token === "function" && token.name ? token.name : typeof token === "string" ? token : null;
575
+ const note = (token2, loadAs) => {
576
+ const name = typeof token2 === "function" && token2.name ? token2.name : typeof token2 === "string" ? token2 : null;
560
577
  if (name !== null) {
561
578
  const existing = knownByName.get(name);
562
- if (existing !== void 0 && existing !== token) ambiguousNames.add(name);
563
- knownByName.set(name, token);
579
+ if (existing !== void 0 && existing !== token2) ambiguousNames.add(name);
580
+ knownByName.set(name, token2);
564
581
  }
565
- if (loadAs !== void 0) knownLifetimes.set(token, loadAs);
582
+ if (loadAs !== void 0) knownLifetimes.set(token2, loadAs);
566
583
  };
567
584
  const effective = /* @__PURE__ */ new Map();
568
585
  const methodWrites = [];
@@ -608,12 +625,12 @@ var TestIocBuilder = class _TestIocBuilder {
608
625
  break;
609
626
  }
610
627
  case "classes": {
611
- const token = resolveKey(write.key, write.byName, "classes");
628
+ const token2 = resolveKey(write.key, write.byName, "classes");
612
629
  note(write.implementation, void 0);
613
- if (!write.byName) note(token, void 0);
614
- effective.set(token, {
630
+ if (!write.byName) note(token2, void 0);
631
+ effective.set(token2, {
615
632
  space: "class",
616
- token,
633
+ token: token2,
617
634
  implementation: write.implementation,
618
635
  // Lifetime priority: the replacement's own @Component scope, then
619
636
  // the lifetime the composition already knows for the token, then
@@ -621,37 +638,37 @@ var TestIocBuilder = class _TestIocBuilder {
621
638
  // class replacing a Singleton-scoped production service must not
622
639
  // silently degrade to Transient (captive-lifetime validation
623
640
  // would reject the production dependents).
624
- loadAs: componentScope(write.implementation) ?? knownLifetimes.get(token) ?? componentScope(token)
641
+ loadAs: componentScope(write.implementation) ?? knownLifetimes.get(token2) ?? componentScope(token2)
625
642
  });
626
643
  break;
627
644
  }
628
645
  case "functions": {
629
- const token = resolveKey(write.key, write.byName, "functions");
630
- const prior = effective.get(token);
631
- effective.set(token, {
646
+ const token2 = resolveKey(write.key, write.byName, "functions");
647
+ const prior = effective.get(token2);
648
+ effective.set(token2, {
632
649
  space: "factory",
633
- token,
650
+ token: token2,
634
651
  factory: write.factory,
635
652
  // preserve configured lifetime unless the scenario overrides it
636
- loadAs: prior && prior.space === "factory" ? prior.loadAs : knownLifetimes.get(token),
653
+ loadAs: prior && prior.space === "factory" ? prior.loadAs : knownLifetimes.get(token2),
637
654
  deps: prior && prior.space === "factory" ? prior.deps : void 0
638
655
  });
639
- note(token, void 0);
656
+ note(token2, void 0);
640
657
  break;
641
658
  }
642
659
  case "values": {
643
- const token = resolveKey(write.key, write.byName, "values");
644
- effective.set(token, { space: "value", token, value: write.value });
645
- note(token, LoadAs.Singleton);
660
+ const token2 = resolveKey(write.key, write.byName, "values");
661
+ effective.set(token2, { space: "value", token: token2, value: write.value });
662
+ note(token2, LoadAs.Singleton);
646
663
  break;
647
664
  }
648
665
  case "methods": {
649
666
  if (write.byName && ambiguousNames.has(write.key)) {
650
667
  throw new AmbiguousNameKeyError(write.key, "methods");
651
668
  }
652
- const token = write.byName && knownByName.has(write.key) ? knownByName.get(write.key) : write.key;
669
+ const token2 = write.byName && knownByName.has(write.key) ? knownByName.get(write.key) : write.key;
653
670
  methodWrites.push({
654
- key: token,
671
+ key: token2,
655
672
  byName: write.byName && !knownByName.has(write.key),
656
673
  methods: new Map(write.methods)
657
674
  });
@@ -659,17 +676,22 @@ var TestIocBuilder = class _TestIocBuilder {
659
676
  }
660
677
  }
661
678
  }
679
+ const borrowed = new Set(options.borrowedTokens);
662
680
  for (const entry of effective.values()) {
663
681
  if (entry.space === "class") {
664
682
  this.registerClassBinding(root, entry.token, entry.implementation, entry.loadAs);
665
683
  } else if (entry.space === "factory") {
666
684
  root.registerFunction(entry.token, entry.factory, {
667
685
  loadAs: entry.loadAs,
668
- param: entry.deps
686
+ param: entry.deps,
687
+ ...borrowed.has(entry.token) ? { owned: false } : {}
669
688
  });
670
689
  } else {
671
690
  const value = entry.value;
672
- root.registerFunction(entry.token, () => value, { loadAs: LoadAs.Singleton });
691
+ root.registerFunction(entry.token, () => value, {
692
+ loadAs: LoadAs.Singleton,
693
+ ...borrowed.has(entry.token) ? { owned: false } : {}
694
+ });
673
695
  }
674
696
  }
675
697
  const registry = new WatchRegistry();
@@ -688,8 +710,8 @@ var TestIocBuilder = class _TestIocBuilder {
688
710
  root.setInstanceDecorator(createMethodDecorator(registry));
689
711
  const env = {
690
712
  root,
691
- get: (token, params) => root.get(token, params),
692
- instance: (cls, params) => root.instance(cls, params),
713
+ get: (token2, params) => ExecutionContext.run(root, () => root.get(token2, params)),
714
+ instance: (cls, params) => ExecutionContext.run(root, () => root.instance(cls, params)),
693
715
  extend: () => root.extend(),
694
716
  verify: async () => registry.verify(),
695
717
  dispose: () => root.dispose(),
@@ -703,17 +725,17 @@ var TestIocBuilder = class _TestIocBuilder {
703
725
  * through real IoC, mirroring the implementation's effective lifetime so
704
726
  * lifetime validation (captive-lifetime checks) stays honest.
705
727
  */
706
- registerClassBinding(root, token, implementation, configuredLoadAs) {
728
+ registerClassBinding(root, token2, implementation, configuredLoadAs) {
707
729
  const loadAs = configuredLoadAs ?? componentScope(implementation) ?? LoadAs.Transient;
708
730
  root.registerClass(implementation, configuredLoadAs !== void 0 ? { loadAs } : void 0);
709
- if (token === implementation) return;
731
+ if (token2 === implementation) return;
710
732
  if (loadAs === LoadAs.Singleton) {
711
- root.registerFunction(token, () => root.get(implementation), {
733
+ root.registerFunction(token2, () => root.get(implementation), {
712
734
  loadAs: LoadAs.Singleton,
713
735
  owned: false
714
736
  });
715
737
  } else {
716
- root.registerFunction(token, (scope) => scope.get(implementation), {
738
+ root.registerFunction(token2, (scope) => scope.get(implementation), {
717
739
  loadAs,
718
740
  param: [SCOPED_CONTAINER],
719
741
  owned: false
@@ -750,16 +772,16 @@ function* tupleEntries(config, space) {
750
772
  );
751
773
  }
752
774
  }
753
- function registerClassBinding(root, token, implementation) {
754
- const loadAs = componentScope2(implementation) ?? componentScope2(token) ?? LoadAs2.Singleton;
775
+ function registerClassBinding(root, token2, implementation) {
776
+ const loadAs = componentScope2(implementation) ?? componentScope2(token2) ?? LoadAs2.Singleton;
755
777
  root.registerClass(implementation, { loadAs });
756
- if (token === implementation) return;
778
+ if (token2 === implementation) return;
757
779
  if (loadAs === LoadAs2.Singleton) {
758
- root.registerFunction(token, () => root.get(implementation), {
780
+ root.registerFunction(token2, () => root.get(implementation), {
759
781
  loadAs: LoadAs2.Singleton
760
782
  });
761
783
  } else {
762
- root.registerFunction(token, (scope) => scope.get(implementation), {
784
+ root.registerFunction(token2, (scope) => scope.get(implementation), {
763
785
  loadAs,
764
786
  param: [SCOPED_CONTAINER2]
765
787
  });
@@ -769,25 +791,29 @@ function installSeams(root, config) {
769
791
  if (typeof root.setInstanceDecorator !== "function") {
770
792
  throw new MissingIocSeamError();
771
793
  }
772
- for (const [token, implementation] of tupleEntries(config.classes ?? [], "classes")) {
773
- registerClassBinding(root, token, implementation);
794
+ for (const [token2, implementation] of tupleEntries(config.classes ?? [], "classes")) {
795
+ registerClassBinding(root, token2, implementation);
774
796
  }
775
- for (const [token, value] of tupleEntries(config.values ?? [], "values")) {
776
- root.registerFunction(token, () => value, { loadAs: LoadAs2.Singleton });
797
+ for (const [token2, value] of tupleEntries(config.values ?? [], "values")) {
798
+ root.registerFunction(token2, () => value, { loadAs: LoadAs2.Singleton });
777
799
  }
778
800
  const registry = new WatchRegistry();
779
- for (const [token, methodsInput] of tupleEntries(config.methods ?? [], "methods")) {
780
- const methods = /* @__PURE__ */ new Map();
801
+ const mergedMethods = /* @__PURE__ */ new Map();
802
+ for (const [token2, methodsInput] of tupleEntries(config.methods ?? [], "methods")) {
803
+ const methods = mergedMethods.get(token2) ?? /* @__PURE__ */ new Map();
781
804
  const entries = methodsInput instanceof Map ? methodsInput.entries() : Object.entries(methodsInput);
782
805
  for (const [name, descriptor] of entries) {
783
806
  if (typeof descriptor !== "function" && !isDescriptor(descriptor)) {
784
807
  throw new InvalidDescriptorError(
785
- `.methods entry ${tokenLabel(token)}.${name} must be a test.* descriptor or a raw wrapper function.`
808
+ `.methods entry ${tokenLabel(token2)}.${name} must be a test.* descriptor or a raw wrapper function.`
786
809
  );
787
810
  }
788
811
  methods.set(name, descriptor);
789
812
  }
790
- registry.addEntry({ key: token, byName: false, methods });
813
+ mergedMethods.set(token2, methods);
814
+ }
815
+ for (const [key, methods] of mergedMethods) {
816
+ registry.addEntry({ key, byName: false, methods });
791
817
  }
792
818
  root.setInstanceDecorator(createMethodDecorator(registry));
793
819
  return {
@@ -795,8 +821,659 @@ function installSeams(root, config) {
795
821
  [ENV_REGISTRY]: registry
796
822
  };
797
823
  }
824
+
825
+ // src/stub.ts
826
+ var owners = ["server", "client", "main", "renderer"];
827
+ var logs = /* @__PURE__ */ new WeakMap();
828
+ function fail(message) {
829
+ throw new InvalidDescriptorError(message);
830
+ }
831
+ function label(value, name) {
832
+ if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
833
+ fail(name + " requires a nonempty identity");
834
+ }
835
+ }
836
+ function token(value) {
837
+ if (value === null || value === void 0 || typeof value === "string" && !value.trim()) {
838
+ fail("replacement requires an exact declared token");
839
+ }
840
+ }
841
+ function executable(value, behaviorOnly = false, active = /* @__PURE__ */ new Set()) {
842
+ if (!behaviorOnly && typeof value === "function") return;
843
+ if (!isDescriptor(value)) fail("replacement requires a function or test.* descriptor");
844
+ if (active.has(value)) fail("cyclic test.* descriptor");
845
+ active.add(value);
846
+ const d = value;
847
+ try {
848
+ if (d.kind === "returns" || d.kind === "throws" || d.kind === "original") return;
849
+ if (!behaviorOnly && d.kind === "watch" && (d.wrapper === void 0 || typeof d.wrapper === "function")) return;
850
+ if (!behaviorOnly && d.kind === "expect" && Number.isInteger(d.expected) && d.expected >= 0) {
851
+ if (d.behavior !== void 0) executable(d.behavior, true, active);
852
+ return;
853
+ }
854
+ if (d.kind === "calls" && Array.isArray(d.script)) {
855
+ for (const child of d.script) executable(child, true, active);
856
+ return;
857
+ }
858
+ fail("invalid test.* descriptor");
859
+ } finally {
860
+ active.delete(value);
861
+ }
862
+ }
863
+ function snapshotExecutable(value) {
864
+ executable(value);
865
+ if (typeof value === "function") return value;
866
+ if (value.kind === "calls") {
867
+ return Object.freeze({ ...value, script: Object.freeze(value.script.map((v) => snapshotExecutable(v))) });
868
+ }
869
+ if (value.kind === "expect" && value.behavior !== void 0) {
870
+ return Object.freeze({ ...value, behavior: snapshotExecutable(value.behavior) });
871
+ }
872
+ return Object.freeze({ ...value });
873
+ }
874
+ function normalizeLoader(identity2) {
875
+ const ref = typeof identity2 === "string" ? { path: identity2, export: "default" } : identity2;
876
+ if (!ref || typeof ref !== "object" || Reflect.ownKeys(ref).some((k) => k !== "path" && k !== "export")) {
877
+ fail(".load requires a project-relative path or { path, export }");
878
+ }
879
+ label(ref.path, ".load path");
880
+ label(ref.export, ".load export");
881
+ if (/^[\/\\]|[\\?#:]/.test(ref.path) || ref.path.split("/").some((s) => !s || s === "." || s === "..")) {
882
+ fail(".load requires a normalized project-relative source path");
883
+ }
884
+ return Object.freeze({ path: ref.path, export: ref.export });
885
+ }
886
+ function append(stub, input, options) {
887
+ if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options) || Reflect.ownKeys(options).some((k) => k !== "owner") || options.owner !== void 0 && !owners.includes(options.owner))) {
888
+ fail("replacement options accept only owner: server | client | main | renderer");
889
+ }
890
+ const log = logs.get(stub);
891
+ const entry = Object.freeze({ ...input, owner: options?.owner, provenance: Object.freeze([log.calls]) });
892
+ return make([...log.entries, entry], log.calls + 1);
893
+ }
894
+ var TestStub = class {
895
+ constructor() {
896
+ }
897
+ class(target, replacement, options) {
898
+ token(target);
899
+ if (typeof target !== "function" || typeof replacement !== "function" || !replacement.prototype) {
900
+ fail(".class requires class tokens and a replacement constructor");
901
+ }
902
+ return append(this, { kind: "class", target, replacement }, options);
903
+ }
904
+ function(target, replacement, options) {
905
+ token(target);
906
+ if (typeof replacement !== "function") fail(".function requires a callable/provider replacement");
907
+ return append(this, { kind: "function", target, replacement }, options);
908
+ }
909
+ method(target, method, replacement, options) {
910
+ token(target);
911
+ label(method, ".method");
912
+ return append(this, { kind: "method", target, method, replacement: snapshotExecutable(replacement) }, options);
913
+ }
914
+ value(target, replacement, options) {
915
+ token(target);
916
+ return append(this, { kind: "value", target, replacement }, options);
917
+ }
918
+ middleware(target, replacement, options) {
919
+ label(target, ".middleware");
920
+ return append(this, { kind: "middleware", target, replacement: snapshotExecutable(replacement) }, options);
921
+ }
922
+ load(target, replacement, options) {
923
+ return append(this, { kind: "load", target: normalizeLoader(target), replacement: snapshotExecutable(replacement) }, options);
924
+ }
925
+ use(other) {
926
+ const incoming = stubEntries(other);
927
+ const log = logs.get(this);
928
+ return make([...log.entries, ...incoming.map((entry) => Object.freeze({
929
+ ...entry,
930
+ provenance: Object.freeze([log.calls, ...entry.provenance])
931
+ }))], log.calls + 1);
932
+ }
933
+ };
934
+ function make(entries, calls) {
935
+ const stub = Object.create(TestStub.prototype);
936
+ logs.set(stub, { entries: Object.freeze([...entries]), calls });
937
+ return Object.freeze(stub);
938
+ }
939
+ function testStub() {
940
+ return make([], 0);
941
+ }
942
+ function stubEntries(stub) {
943
+ const log = logs.get(stub);
944
+ if (!log) fail(".use requires an immutable testStub description (cyclic/foreign objects are not supported)");
945
+ return log.entries;
946
+ }
947
+
948
+ // src/selection.ts
949
+ var SourceSelectionError = class extends Error {
950
+ constructor(message, owner, choices = []) {
951
+ super((owner ? owner + ": " : "") + message);
952
+ this.owner = owner;
953
+ this.choices = choices;
954
+ this.name = "SourceSelectionError";
955
+ }
956
+ owner;
957
+ choices;
958
+ code = "testing/selection";
959
+ };
960
+ function record(value) {
961
+ return !!value && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
962
+ }
963
+ function normalizeOwner(value, owner) {
964
+ const fail2 = (message) => {
965
+ throw new SourceSelectionError(message, owner);
966
+ };
967
+ if (!record(value)) return fail2("select an owner with module, path, or {}");
968
+ const keys = Reflect.ownKeys(value);
969
+ if (keys.some((k) => k !== "module" && k !== "path") || keys.length > 1) {
970
+ return fail2("select module OR path, or {}; no other selector keys are supported");
971
+ }
972
+ if (!keys.length) return Object.freeze({});
973
+ const key = keys[0];
974
+ const input = value[key];
975
+ const list = key === "module" && typeof input === "string" ? [input] : input;
976
+ if (!Array.isArray(list) || !list.length || list.some((x) => typeof x !== "string" || !x.trim() || /[\u0000-\u001f\u007f]/.test(x))) {
977
+ return fail2(key + " requires nonempty " + (key === "module" ? "name(s)" : "path array"));
978
+ }
979
+ const unique = Object.freeze([...new Set(list)]);
980
+ return key === "module" ? Object.freeze({ module: unique }) : Object.freeze({ path: unique });
981
+ }
982
+ function normalizeTestSelection(selection, declaredOwners) {
983
+ const declared = new Set(declaredOwners);
984
+ if (selection === void 0) {
985
+ return Object.freeze(Object.fromEntries([...declared].map((owner) => [owner, Object.freeze({})])));
986
+ }
987
+ if (!record(selection) || !Reflect.ownKeys(selection).length) {
988
+ throw new SourceSelectionError("select() requires at least one declared owner");
989
+ }
990
+ const result = {};
991
+ for (const owner of Reflect.ownKeys(selection)) {
992
+ if (typeof owner !== "string" || !declared.has(owner)) {
993
+ throw new SourceSelectionError("owner is absent or unknown; available: " + [...declared].join(", "), String(owner), [...declared]);
994
+ }
995
+ Object.defineProperty(result, owner, { value: normalizeOwner(selection[owner], owner), enumerable: true });
996
+ }
997
+ return Object.freeze(result);
998
+ }
999
+ function validatePath(path, options) {
1000
+ const invalid = /[?#*\[\]\\\u0000-\u001f\u007f]/.test(path) || path.includes("://") || path.includes("//") || path.split("/").some((segment) => segment === "." || segment === "..");
1001
+ const native = options.native && /^[A-Za-z0-9_$-]+(?:\.[A-Za-z0-9_$-]+)*$/.test(path);
1002
+ if (invalid || !path.startsWith("/") && !native) {
1003
+ throw new SourceSelectionError('invalid source path selector "' + path + '"', options.owner);
1004
+ }
1005
+ }
1006
+ function matches(path, selector) {
1007
+ if (selector === "/") return path.startsWith("/");
1008
+ if (selector.startsWith("/") && selector.endsWith("/")) {
1009
+ return path === selector.slice(0, -1) || path.startsWith(selector);
1010
+ }
1011
+ return path === selector;
1012
+ }
1013
+ function selectSourceEntries(source, input, options = {}) {
1014
+ const selection = normalizeOwner(input, options.owner);
1015
+ if (selection.module !== void 0) {
1016
+ const names = selection.module;
1017
+ const choices = [.../* @__PURE__ */ new Set([...source.flatMap((e) => e.module == null ? [] : [e.module]), ...options.modules ?? []])];
1018
+ for (const name of names) if (!choices.includes(name)) {
1019
+ throw new SourceSelectionError('unknown module "' + name + '"; available: ' + choices.join(", "), options.owner, choices);
1020
+ }
1021
+ return source.filter((e) => e.module != null && names.includes(e.module));
1022
+ }
1023
+ if (selection.path !== void 0) {
1024
+ const paths = selection.path;
1025
+ const choices = [...new Set(source.map((e) => e.path))];
1026
+ for (const path of paths) {
1027
+ validatePath(path, options);
1028
+ if (!source.some((e) => matches(e.path, path))) {
1029
+ throw new SourceSelectionError('unknown path "' + path + '"; available: ' + choices.join(", "), options.owner, choices);
1030
+ }
1031
+ }
1032
+ return source.filter((e) => paths.some((path) => matches(e.path, path)));
1033
+ }
1034
+ return [...source];
1035
+ }
1036
+
1037
+ // src/resource_context.ts
1038
+ var ANCHOR = /* @__PURE__ */ Symbol.for("@noego/testing.resource-scope.v1");
1039
+ function storage() {
1040
+ const global = globalThis;
1041
+ if (global[ANCHOR]) {
1042
+ const existing = global[ANCHOR];
1043
+ if (typeof existing.run !== "function" || typeof existing.getStore !== "function") {
1044
+ throw new Error("Incompatible NoEgo resource-scope v1 channel");
1045
+ }
1046
+ return existing;
1047
+ }
1048
+ let hooks;
1049
+ try {
1050
+ hooks = global.process?.getBuiltinModule?.("node:async_hooks") ?? __require("async_hooks");
1051
+ } catch {
1052
+ return void 0;
1053
+ }
1054
+ if (!hooks?.AsyncLocalStorage) return void 0;
1055
+ const created = new hooks.AsyncLocalStorage();
1056
+ Object.defineProperty(global, ANCHOR, { value: created, configurable: false, writable: false });
1057
+ return created;
1058
+ }
1059
+ function runInResourceScope(scope, body) {
1060
+ const channel = storage();
1061
+ return channel ? channel.run(scope, body) : body();
1062
+ }
1063
+ async function registerTestResource(resource, owner = "resource") {
1064
+ try {
1065
+ const scope = storage()?.getStore();
1066
+ if (!scope) return resource;
1067
+ if (typeof resource.verify === "function") {
1068
+ scope.environment(resource, owner);
1069
+ } else scope.own(resource, owner);
1070
+ return resource;
1071
+ } catch (primary) {
1072
+ try {
1073
+ await resource.dispose();
1074
+ } catch (cleanup) {
1075
+ throw new AggregateError([primary, cleanup], "Resource admission and cleanup failed", { cause: primary });
1076
+ }
1077
+ throw primary;
1078
+ }
1079
+ }
1080
+
1081
+ // src/lifecycle.ts
1082
+ var TestFinalizationError = class extends AggregateError {
1083
+ failures;
1084
+ constructor(failures) {
1085
+ super(
1086
+ failures.map((f) => f.error),
1087
+ "Test finalization failed: " + failures.map((f) => f.owner + "/" + f.phase).join(", "),
1088
+ { cause: failures[0]?.error }
1089
+ );
1090
+ this.name = "TestFinalizationError";
1091
+ this.failures = Object.freeze(failures.map((f) => Object.freeze({ ...f })));
1092
+ }
1093
+ };
1094
+ var TestResourceScope = class {
1095
+ resources = [];
1096
+ owned = /* @__PURE__ */ new Map();
1097
+ closing;
1098
+ complete = false;
1099
+ /** Runner finalizers can avoid reporting an already-finished failure twice. */
1100
+ get finalized() {
1101
+ return this.complete;
1102
+ }
1103
+ own(resource, owner = "resource") {
1104
+ if (this.closing) throw new Error("Test resource scope is closed");
1105
+ if (!resource || typeof resource.dispose !== "function") throw new TypeError("Test resource requires dispose()");
1106
+ if (!this.owned.has(resource)) {
1107
+ const entry = { resource, owner };
1108
+ this.owned.set(resource, entry);
1109
+ this.resources.push(entry);
1110
+ }
1111
+ return resource;
1112
+ }
1113
+ environment(resource, owner = "application") {
1114
+ if (!resource || typeof resource.verify !== "function") throw new TypeError("Test environment requires verify()");
1115
+ this.own(resource, owner);
1116
+ this.owned.get(resource).verify = () => resource.verify();
1117
+ if (resource.settle) this.owned.get(resource).settle = () => resource.settle();
1118
+ return resource;
1119
+ }
1120
+ dispose() {
1121
+ return this.closing ??= Promise.resolve().then(async () => {
1122
+ const failures = [];
1123
+ const reverse = [...this.resources].reverse();
1124
+ for (const entry of reverse) if (entry.settle) {
1125
+ try {
1126
+ await entry.settle();
1127
+ } catch (error) {
1128
+ failures.push({ owner: entry.owner, phase: "settle", error });
1129
+ }
1130
+ }
1131
+ for (const entry of reverse) if (entry.verify) {
1132
+ try {
1133
+ await entry.verify();
1134
+ } catch (error) {
1135
+ failures.push({ owner: entry.owner, phase: "verify", error });
1136
+ }
1137
+ }
1138
+ for (const entry of reverse) {
1139
+ try {
1140
+ await entry.resource.dispose();
1141
+ } catch (error) {
1142
+ failures.push({ owner: entry.owner, phase: "dispose", error });
1143
+ }
1144
+ }
1145
+ if (failures.length) throw new TestFinalizationError(failures);
1146
+ }).finally(() => {
1147
+ this.complete = true;
1148
+ });
1149
+ }
1150
+ };
1151
+ function createTestScope() {
1152
+ return new TestResourceScope();
1153
+ }
1154
+ async function withTestScope(body) {
1155
+ const scope = createTestScope();
1156
+ let failed = false;
1157
+ let primary;
1158
+ let result;
1159
+ try {
1160
+ result = await runInResourceScope(scope, () => body(scope));
1161
+ } catch (error) {
1162
+ failed = true;
1163
+ primary = error;
1164
+ }
1165
+ try {
1166
+ await scope.dispose();
1167
+ } catch (error) {
1168
+ if (!failed) throw error;
1169
+ const cleanup = error instanceof TestFinalizationError ? error.failures : [{ owner: "scope", phase: "dispose", error }];
1170
+ throw new TestFinalizationError([{ owner: "test", phase: "test", error: primary }, ...cleanup]);
1171
+ }
1172
+ if (failed) throw primary;
1173
+ return result;
1174
+ }
1175
+
1176
+ // src/resource_case.ts
1177
+ function resourceCase(body) {
1178
+ return (...args) => withTestScope((resources) => {
1179
+ const context = args.find((value) => value && (typeof value === "object" || typeof value === "function") && typeof value.onTestFinished === "function");
1180
+ context?.onTestFinished(async () => {
1181
+ if (!resources.finalized) await resources.dispose();
1182
+ });
1183
+ return body(resources, ...args);
1184
+ });
1185
+ }
1186
+
1187
+ // src/coverage.ts
1188
+ var COVERAGE_METRICS = Object.freeze(["lines", "statements", "functions", "branches"]);
1189
+ var TestCoverageConfigurationError = class extends Error {
1190
+ constructor(message) {
1191
+ super(message);
1192
+ this.name = "TestCoverageConfigurationError";
1193
+ }
1194
+ };
1195
+ var DEFAULT_EXCLUSIONS = [
1196
+ { pattern: "**/*.{test,spec}.{js,jsx,ts,tsx,mjs,cjs,mts,cts}", kind: "tests", reason: "Test implementations are not product source." },
1197
+ { pattern: "**/*.d.{ts,mts,cts}", kind: "types", reason: "Type declarations have no executable counters." }
1198
+ ];
1199
+ var EXCLUSION_KINDS = ["tests", "types", "generated", "nonexecutable", "separate-runtime"];
1200
+ function nonempty(value, label3) {
1201
+ if (typeof value !== "string" || !value.trim()) throw new TestCoverageConfigurationError(label3 + " must be a nonempty string");
1202
+ }
1203
+ function version(value) {
1204
+ if (typeof value !== "string" || !/^[234]\.\d+\.\d+$/.test(value)) {
1205
+ throw new TestCoverageConfigurationError("Declare a qualified stable Vitest/provider version in majors 2, 3, or 4");
1206
+ }
1207
+ return Number(value[0]);
1208
+ }
1209
+ function vitestCoverage(input) {
1210
+ const major = version(input.runnerVersion);
1211
+ version(input.providerVersion);
1212
+ if (input.runnerVersion !== input.providerVersion) throw new TestCoverageConfigurationError("Vitest and @vitest/coverage-v8 versions must match exactly");
1213
+ if (!Array.isArray(input.include) || !input.include.length) throw new TestCoverageConfigurationError("coverage.include must name the complete eligible source set");
1214
+ for (const pattern of input.include) {
1215
+ nonempty(pattern, "include pattern");
1216
+ if (pattern.startsWith("!")) throw new TestCoverageConfigurationError("Record exclusions separately with provenance, not as negative includes");
1217
+ }
1218
+ const include = [...new Set(input.include)];
1219
+ const thresholds = { lines: 99, statements: 99, functions: 99, branches: 99, ...input.thresholds };
1220
+ if (Object.keys(thresholds).some((key) => !COVERAGE_METRICS.includes(key))) throw new TestCoverageConfigurationError("Unknown coverage metric");
1221
+ for (const metric of COVERAGE_METRICS) {
1222
+ if (!Number.isFinite(thresholds[metric]) || thresholds[metric] < 0 || thresholds[metric] > 100) {
1223
+ throw new TestCoverageConfigurationError(metric + " threshold must be between 0 and 100");
1224
+ }
1225
+ }
1226
+ const exclusions = [...DEFAULT_EXCLUSIONS, ...input.exclusions ?? []].map((entry) => {
1227
+ nonempty(entry.pattern, "exclusion pattern");
1228
+ nonempty(entry.reason, "exclusion reason");
1229
+ if (!EXCLUSION_KINDS.includes(entry.kind)) throw new TestCoverageConfigurationError("Unknown exclusion kind");
1230
+ if (entry.kind === "generated" || entry.kind === "separate-runtime") nonempty(entry.evidence, "exclusion evidence");
1231
+ return { ...entry };
1232
+ });
1233
+ if (new Set(exclusions.map((entry) => entry.pattern)).size !== exclusions.length) throw new TestCoverageConfigurationError("Duplicate exclusion pattern");
1234
+ const options = {
1235
+ provider: "v8",
1236
+ include: [...include],
1237
+ exclude: exclusions.map((entry) => entry.pattern),
1238
+ // v4 removed all: explicit include now includes covered AND uncovered files.
1239
+ ...major < 4 ? { all: true } : {},
1240
+ reporter: ["text-summary", "json-summary", "json"],
1241
+ reportOnFailure: true,
1242
+ thresholds: { ...thresholds }
1243
+ };
1244
+ return {
1245
+ options,
1246
+ provenance: Object.freeze({
1247
+ runner: "vitest",
1248
+ runnerVersion: input.runnerVersion,
1249
+ provider: "@vitest/coverage-v8",
1250
+ providerVersion: input.providerVersion,
1251
+ includesUnimported: true,
1252
+ include: Object.freeze(include),
1253
+ exclusions: Object.freeze(exclusions.map((entry) => Object.freeze(entry))),
1254
+ thresholds: Object.freeze(thresholds),
1255
+ metrics: Object.freeze([...COVERAGE_METRICS])
1256
+ })
1257
+ };
1258
+ }
1259
+ var TestDiscoveryError = class extends Error {
1260
+ constructor(failures) {
1261
+ super(failures.join("; "));
1262
+ this.failures = failures;
1263
+ this.name = "TestDiscoveryError";
1264
+ }
1265
+ failures;
1266
+ };
1267
+ function assertTestLanes(required, reports) {
1268
+ if (!required.length) throw new TestDiscoveryError(["At least one required lane must be declared"]);
1269
+ const names = /* @__PURE__ */ new Set();
1270
+ const failures = [];
1271
+ for (const name of required) nonempty(name, "required lane name");
1272
+ if (new Set(required).size !== required.length) throw new TestDiscoveryError(["Duplicate required lane"]);
1273
+ for (const report of reports) {
1274
+ nonempty(report.name, "reported lane name");
1275
+ if (names.has(report.name)) throw new TestDiscoveryError(["Duplicate report for lane " + report.name]);
1276
+ names.add(report.name);
1277
+ for (const key of ["total", "passed", "failed", "skipped"]) {
1278
+ if (!Number.isSafeInteger(report[key]) || report[key] < 0) throw new TestDiscoveryError(["Invalid " + key + " count for " + report.name]);
1279
+ }
1280
+ if (report.total !== report.passed + report.failed + report.skipped) throw new TestDiscoveryError(["Inconsistent counts for " + report.name]);
1281
+ if (report.failed) failures.push(report.name + ": " + report.failed + " failed");
1282
+ if (required.includes(report.name)) {
1283
+ if (!report.total) failures.push(report.name + ": required lane is empty");
1284
+ if (report.skipped) failures.push(report.name + ": " + report.skipped + " skipped");
1285
+ }
1286
+ }
1287
+ for (const name of required) if (!names.has(name)) failures.push(name + ": required lane is missing");
1288
+ if (failures.length) throw new TestDiscoveryError(Object.freeze(failures));
1289
+ }
1290
+
1291
+ // src/overlays.ts
1292
+ var TestOverlayError = class extends Error {
1293
+ constructor(message, entry) {
1294
+ super("entry " + entry.provenance.join(".") + ": " + message);
1295
+ this.entry = entry;
1296
+ this.name = "TestOverlayError";
1297
+ }
1298
+ entry;
1299
+ code = "testing/overlay";
1300
+ };
1301
+ function label2(target) {
1302
+ return typeof target === "function" ? target.name : String(target);
1303
+ }
1304
+ function binding(catalog, token2) {
1305
+ return catalog.bindings.find((b) => b.token === token2);
1306
+ }
1307
+ function owns(catalog, entry) {
1308
+ if (entry.kind === "middleware") return catalog.middleware?.includes(entry.target) ?? false;
1309
+ if (entry.kind === "load") return catalog.loaders?.some((l) => l.path === entry.target.path && l.export === entry.target.export) ?? false;
1310
+ return binding(catalog, entry.target) !== void 0;
1311
+ }
1312
+ function sameSlot(a, b) {
1313
+ if (a.owner !== b.owner) return false;
1314
+ const x = a.entry, y = b.entry;
1315
+ if (x.kind === "load" && y.kind === "load") return x.target.path === y.target.path && x.target.export === y.target.export;
1316
+ if (x.kind === "middleware" || x.kind === "load" || y.kind === "middleware" || y.kind === "load") {
1317
+ return x.kind === y.kind && x.target === y.target;
1318
+ }
1319
+ if (x.kind === "method" || y.kind === "method") {
1320
+ return x.kind === "method" && y.kind === "method" && x.target === y.target && x.method === y.method;
1321
+ }
1322
+ return x.target === y.target;
1323
+ }
1324
+ function resolveTestOverlays(stub, catalogs) {
1325
+ const names = catalogs.map((c) => c.owner);
1326
+ if (new Set(names).size !== names.length) throw new TypeError("duplicate test owner catalog");
1327
+ const result = [];
1328
+ for (const entry of stubEntries(stub)) {
1329
+ let candidates = catalogs.filter((c) => owns(c, entry) && (entry.owner === void 0 || c.owner === entry.owner));
1330
+ if (candidates.length === 0 && entry.kind !== "middleware" && entry.kind !== "load" && typeof entry.target === "function") {
1331
+ const fallback = catalogs.filter((c) => entry.owner === void 0 || c.owner === entry.owner);
1332
+ if (fallback.length === 1) {
1333
+ const synthetic = { token: entry.target, kind: "class", lifetime: "singleton", implementation: entry.target, dependencies: [] };
1334
+ candidates = [{ ...fallback[0], bindings: [...fallback[0].bindings, synthetic] }];
1335
+ }
1336
+ }
1337
+ if (candidates.length !== 1) {
1338
+ const identity2 = entry.kind === "load" ? entry.target.path + "#" + entry.target.export : label2(entry.target);
1339
+ throw new TestOverlayError((candidates.length ? "Ambiguous" : "Unknown") + " " + entry.kind + ' "' + identity2 + '" in selected owners [' + names.join(", ") + "]" + (entry.owner ? "; requested owner " + entry.owner : "; specify { owner } when ambiguous"), entry);
1340
+ }
1341
+ const catalog = candidates[0];
1342
+ const declared = entry.kind === "middleware" || entry.kind === "load" ? void 0 : binding(catalog, entry.target);
1343
+ if (entry.kind === "function" && declared?.kind !== "factory" && declared?.kind !== "class" && !(declared?.kind === "value" && typeof declared.implementation === "function")) {
1344
+ throw new TestOverlayError(".function requires a declared factory/provider, class, or callable value binding", entry);
1345
+ }
1346
+ const resolved = Object.freeze({ owner: catalog.owner, entry, binding: declared });
1347
+ const prior = result.findIndex((e) => sameSlot(e, resolved));
1348
+ if (prior !== -1) result.splice(prior, 1);
1349
+ result.push(resolved);
1350
+ }
1351
+ return Object.freeze([...result.filter((e) => e.entry.kind !== "method"), ...result.filter((e) => e.entry.kind === "method")]);
1352
+ }
1353
+
1354
+ // src/binding_overlays.ts
1355
+ import { defineModule } from "@noego/ioc";
1356
+ function applyTestBindings(production, overlays, owner) {
1357
+ let builder = production;
1358
+ const entries = overlays.filter((e) => e.owner === owner);
1359
+ const borrowed = [];
1360
+ for (const overlay of entries) {
1361
+ const { entry, binding: binding2 } = overlay;
1362
+ if (entry.kind === "middleware" || entry.kind === "load" || entry.kind === "method") continue;
1363
+ if (!binding2) throw new TestOverlayError("missing production binding metadata", entry);
1364
+ builder = builder.use(defineModule("@noego/testing/" + owner + "/" + entry.provenance.join("."), (bind) => {
1365
+ if (entry.kind === "class") {
1366
+ bind(entry.target).to(entry.replacement)[binding2.lifetime]();
1367
+ } else if (entry.kind === "function" && binding2.kind === "factory") {
1368
+ bind(entry.target).toFactory(entry.replacement, [...binding2.dependencies])[binding2.lifetime]();
1369
+ } else if (entry.kind === "function" && binding2.kind === "class") {
1370
+ bind(entry.target).toFactory(() => entry.replacement())[binding2.lifetime]();
1371
+ borrowed.push(entry.target);
1372
+ } else {
1373
+ bind(entry.target).toFactory(() => entry.replacement)[binding2.lifetime]();
1374
+ borrowed.push(entry.target);
1375
+ }
1376
+ }));
1377
+ }
1378
+ for (const { entry } of entries) if (entry.kind === "method") {
1379
+ builder = builder.methods([[entry.target, { [entry.method]: entry.replacement }]]);
1380
+ }
1381
+ return Object.freeze({ builder, buildOptions: Object.freeze({ borrowedTokens: Object.freeze(borrowed) }) });
1382
+ }
1383
+
1384
+ // src/executable_overlays.ts
1385
+ function identity(kind, target) {
1386
+ if (kind === "middleware") {
1387
+ if (typeof target !== "string") throw new TypeError("middleware identity must be a string");
1388
+ return "middleware:" + target;
1389
+ }
1390
+ if (typeof target === "string") return "load:" + target + "#default";
1391
+ return "load:" + target.path + "#" + target.export;
1392
+ }
1393
+ function createTestExecutables(overlays, owner) {
1394
+ const registry = new WatchRegistry();
1395
+ const decorator = createMethodDecorator(registry);
1396
+ const selected = /* @__PURE__ */ new Set();
1397
+ const installed = /* @__PURE__ */ new Map();
1398
+ for (const { owner: selectedOwner, entry } of overlays) {
1399
+ if (selectedOwner !== owner || entry.kind !== "middleware" && entry.kind !== "load") continue;
1400
+ const key = identity(entry.kind, entry.target);
1401
+ selected.add(key);
1402
+ const behavior = typeof entry.replacement === "function" ? test.watch(() => entry.replacement) : entry.replacement;
1403
+ registry.addEntry({ key, byName: false, methods: /* @__PURE__ */ new Map([["invoke", behavior]]) });
1404
+ }
1405
+ return {
1406
+ replace(kind, target, original) {
1407
+ if (typeof original !== "function") throw new TypeError("source executable must be callable");
1408
+ const key = identity(kind, target);
1409
+ if (!selected.has(key)) return original;
1410
+ const cached = installed.get(key);
1411
+ if (cached) {
1412
+ if (cached.original !== original) throw new TypeError("ambiguous source executable: " + key);
1413
+ return cached.replacement;
1414
+ }
1415
+ const subject = decorator({ invoke: original }, key);
1416
+ const replacement = function(...args) {
1417
+ return subject.invoke.apply(this, args);
1418
+ };
1419
+ installed.set(key, { original, replacement });
1420
+ return replacement;
1421
+ },
1422
+ inspect: (kind, target) => registry.inspect(identity(kind, target), "invoke"),
1423
+ verify: async () => registry.verify(),
1424
+ [ENV_REGISTRY]: registry
1425
+ };
1426
+ }
1427
+
1428
+ // src/binding_catalog.ts
1429
+ import { defineModule as defineModule2, flattenModule as flattenModule2 } from "@noego/ioc";
1430
+ function describeTestBindings(builder, discovered = []) {
1431
+ const declarations = /* @__PURE__ */ new Map();
1432
+ const classBinding = (token2, implementation) => flattenModule2(defineModule2("@noego/testing/discovered", (bind) => {
1433
+ bind(token2).to(implementation);
1434
+ }))[0];
1435
+ for (const write of builder.writes) {
1436
+ if (write.op === "use") {
1437
+ for (const registration of flattenModule2(write.module)) declarations.set(registration.token, registration);
1438
+ } else if (write.op === "classes") {
1439
+ const registration = classBinding(write.key, write.implementation);
1440
+ declarations.set(write.key, { ...registration, lifetime: declarations.get(write.key)?.lifetime ?? registration.lifetime });
1441
+ } else if (write.op === "functions" || write.op === "values") {
1442
+ const prior = declarations.get(write.key);
1443
+ declarations.set(write.key, {
1444
+ token: write.key,
1445
+ kind: write.op === "functions" ? "factory" : "value",
1446
+ lifetime: write.op === "values" ? "singleton" : prior?.lifetime ?? "transient",
1447
+ dependencies: write.op === "functions" && prior?.kind === "factory" ? prior.dependencies : [],
1448
+ implementation: write.op === "functions" ? write.factory : write.value,
1449
+ source: "@noego/testing/declared",
1450
+ requiredCapabilities: []
1451
+ });
1452
+ }
1453
+ }
1454
+ const visited = /* @__PURE__ */ new Set();
1455
+ const visit = (token2) => {
1456
+ if (visited.has(token2)) return;
1457
+ visited.add(token2);
1458
+ let registration = declarations.get(token2);
1459
+ if (!registration && typeof token2 === "function" && token2.prototype) {
1460
+ registration = classBinding(token2, token2);
1461
+ declarations.set(token2, registration);
1462
+ }
1463
+ if (!registration) return;
1464
+ for (const dependency of registration.dependencies) visit(dependency);
1465
+ if (registration.kind === "class" && registration.implementation !== token2) visit(registration.implementation);
1466
+ };
1467
+ for (const token2 of [...declarations.keys(), ...discovered]) visit(token2);
1468
+ return Object.freeze([...declarations.values()].map((r) => Object.freeze({
1469
+ ...r,
1470
+ dependencies: Object.freeze([...r.dependencies]),
1471
+ requiredCapabilities: Object.freeze([...r.requiredCapabilities])
1472
+ })));
1473
+ }
798
1474
  export {
799
1475
  AmbiguousNameKeyError,
1476
+ COVERAGE_METRICS,
800
1477
  CallScriptExhaustedError,
801
1478
  ENV_REGISTRY,
802
1479
  ExpectationOverflowError,
@@ -804,14 +1481,36 @@ export {
804
1481
  MethodNotCallableError,
805
1482
  MissingIocSeamError,
806
1483
  NonObjectMethodTargetError,
1484
+ SourceSelectionError,
1485
+ TestCoverageConfigurationError,
1486
+ TestDiscoveryError,
1487
+ TestFinalizationError,
807
1488
  TestIocBuilder,
1489
+ TestOverlayError,
1490
+ TestResourceScope,
1491
+ TestStub,
808
1492
  TestingError,
809
1493
  TokenIdentitySplitError,
810
1494
  UnknownTokenKeyError,
811
1495
  UnwatchedInspectionError,
812
1496
  VerificationError,
1497
+ applyTestBindings,
1498
+ assertTestLanes,
1499
+ createTestExecutables,
1500
+ createTestScope,
1501
+ describeTestBindings,
813
1502
  installSeams,
1503
+ normalizeTestSelection,
1504
+ registerTestResource,
1505
+ resolveTestOverlays,
1506
+ resourceCase,
1507
+ runInResourceScope,
1508
+ selectSourceEntries,
1509
+ stubEntries,
814
1510
  test,
815
- testIoc
1511
+ testIoc,
1512
+ testStub,
1513
+ vitestCoverage,
1514
+ withTestScope
816
1515
  };
817
1516
  //# sourceMappingURL=index.js.map