@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.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AmbiguousNameKeyError: () => AmbiguousNameKeyError,
24
+ COVERAGE_METRICS: () => COVERAGE_METRICS,
24
25
  CallScriptExhaustedError: () => CallScriptExhaustedError,
25
26
  ENV_REGISTRY: () => ENV_REGISTRY,
26
27
  ExpectationOverflowError: () => ExpectationOverflowError,
@@ -28,15 +29,37 @@ __export(index_exports, {
28
29
  MethodNotCallableError: () => MethodNotCallableError,
29
30
  MissingIocSeamError: () => MissingIocSeamError,
30
31
  NonObjectMethodTargetError: () => NonObjectMethodTargetError,
32
+ SourceSelectionError: () => SourceSelectionError,
33
+ TestCoverageConfigurationError: () => TestCoverageConfigurationError,
34
+ TestDiscoveryError: () => TestDiscoveryError,
35
+ TestFinalizationError: () => TestFinalizationError,
31
36
  TestIocBuilder: () => TestIocBuilder,
37
+ TestOverlayError: () => TestOverlayError,
38
+ TestResourceScope: () => TestResourceScope,
39
+ TestStub: () => TestStub,
32
40
  TestingError: () => TestingError,
33
41
  TokenIdentitySplitError: () => TokenIdentitySplitError,
34
42
  UnknownTokenKeyError: () => UnknownTokenKeyError,
35
43
  UnwatchedInspectionError: () => UnwatchedInspectionError,
36
44
  VerificationError: () => VerificationError,
45
+ applyTestBindings: () => applyTestBindings,
46
+ assertTestLanes: () => assertTestLanes,
47
+ createTestExecutables: () => createTestExecutables,
48
+ createTestScope: () => createTestScope,
49
+ describeTestBindings: () => describeTestBindings,
37
50
  installSeams: () => installSeams,
51
+ normalizeTestSelection: () => normalizeTestSelection,
52
+ registerTestResource: () => registerTestResource,
53
+ resolveTestOverlays: () => resolveTestOverlays,
54
+ resourceCase: () => resourceCase,
55
+ runInResourceScope: () => runInResourceScope,
56
+ selectSourceEntries: () => selectSourceEntries,
57
+ stubEntries: () => stubEntries,
38
58
  test: () => test,
39
- testIoc: () => testIoc
59
+ testIoc: () => testIoc,
60
+ testStub: () => testStub,
61
+ vitestCoverage: () => vitestCoverage,
62
+ withTestScope: () => withTestScope
40
63
  });
41
64
  module.exports = __toCommonJS(index_exports);
42
65
 
@@ -58,23 +81,23 @@ var MissingIocSeamError = class extends TestingError {
58
81
  }
59
82
  };
60
83
  var UnwatchedInspectionError = class extends TestingError {
61
- constructor(token, method) {
84
+ constructor(token2, method) {
62
85
  super(
63
- `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.`
86
+ `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.`
64
87
  );
65
88
  }
66
89
  };
67
90
  var CallScriptExhaustedError = class extends TestingError {
68
- constructor(token, method, scriptLength, callIndex) {
91
+ constructor(token2, method, scriptLength, callIndex) {
69
92
  super(
70
- `Call #${callIndex} to ${token}.${method} exceeds its test.calls() script of ${scriptLength} ${scriptLength === 1 ? "entry" : "entries"}.`
93
+ `Call #${callIndex} to ${token2}.${method} exceeds its test.calls() script of ${scriptLength} ${scriptLength === 1 ? "entry" : "entries"}.`
71
94
  );
72
95
  }
73
96
  };
74
97
  var ExpectationOverflowError = class extends TestingError {
75
- constructor(token, method, expected, attempted) {
98
+ constructor(token2, method, expected, attempted) {
76
99
  super(
77
- 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.`
100
+ 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.`
78
101
  );
79
102
  }
80
103
  };
@@ -88,16 +111,16 @@ var VerificationError = class extends TestingError {
88
111
  }
89
112
  };
90
113
  var MethodNotCallableError = class extends TestingError {
91
- constructor(token, method) {
114
+ constructor(token2, method) {
92
115
  super(
93
- `Cannot install a test.* descriptor on ${token}.${method}: the resolved instance has no callable method with that name.`
116
+ `Cannot install a test.* descriptor on ${token2}.${method}: the resolved instance has no callable method with that name.`
94
117
  );
95
118
  }
96
119
  };
97
120
  var NonObjectMethodTargetError = class extends TestingError {
98
- constructor(token) {
121
+ constructor(token2) {
99
122
  super(
100
- `.methods() is configured for ${token}, but that token resolved to a non-object value. Method descriptors apply only to IoC-managed instances.`
123
+ `.methods() is configured for ${token2}, but that token resolved to a non-object value. Method descriptors apply only to IoC-managed instances.`
101
124
  );
102
125
  }
103
126
  };
@@ -196,14 +219,14 @@ var test = {
196
219
  return frozen({ [DESCRIPTOR]: true, kind: "expect", expected: 0 });
197
220
  },
198
221
  /** Read the recorded history for a watched method in one environment. */
199
- inspect(environment, token, method) {
222
+ inspect(environment, token2, method) {
200
223
  const registry = environment?.[ENV_REGISTRY];
201
224
  if (!registry) {
202
225
  throw new InvalidDescriptorError(
203
226
  "test.inspect() requires a built @noego/testing environment as its first argument."
204
227
  );
205
228
  }
206
- return registry.inspect(token, method);
229
+ return registry.inspect(token2, method);
207
230
  }
208
231
  };
209
232
  Object.freeze(test);
@@ -212,10 +235,10 @@ var ENV_REGISTRY = /* @__PURE__ */ Symbol.for("noego:testing:env-registry");
212
235
  // src/method_state.ts
213
236
  var CONTEXT_WRAPPED = /* @__PURE__ */ Symbol.for("ioc:context-wrapped");
214
237
  var CONTEXT_OWNER = /* @__PURE__ */ Symbol.for("ioc:context-owner");
215
- function tokenLabel(token) {
216
- if (typeof token === "function") return token.name || "[anonymous class]";
217
- if (typeof token === "symbol") return String(token);
218
- return String(token);
238
+ function tokenLabel(token2) {
239
+ if (typeof token2 === "function") return token2.name || "[anonymous class]";
240
+ if (typeof token2 === "symbol") return String(token2);
241
+ return String(token2);
219
242
  }
220
243
  var MethodState = class {
221
244
  constructor(tokenName, method, descriptor) {
@@ -267,31 +290,31 @@ var WatchRegistry = class {
267
290
  return entry.byName ? String(entry.key) : tokenLabel(entry.key);
268
291
  }
269
292
  /** Entries applying to a resolving token (exact identity or name match). */
270
- matchEntries(token) {
271
- const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
293
+ matchEntries(token2) {
294
+ const name = typeof token2 === "function" ? token2.name : typeof token2 === "string" ? token2 : void 0;
272
295
  const matched = this.entries.filter(
273
- (entry) => entry.key === token || entry.byName && name !== void 0 && entry.key === name
296
+ (entry) => entry.key === token2 || entry.byName && name !== void 0 && entry.key === name
274
297
  );
275
298
  if (matched.length) {
276
299
  for (const entry of matched) this.matchedEntryKeys.add(entry.key);
277
- } else if (typeof token === "function" && name) {
278
- this.unmatchedConstructedByName.set(name, token);
300
+ } else if (typeof token2 === "function" && name) {
301
+ this.unmatchedConstructedByName.set(name, token2);
279
302
  }
280
303
  return matched;
281
304
  }
282
305
  state(entryKey, method) {
283
306
  return this.states.get(entryKey)?.get(method);
284
307
  }
285
- inspect(token, method) {
286
- const label = tokenLabel(token);
287
- const keys = [token];
288
- const name = typeof token === "function" ? token.name : typeof token === "string" ? token : void 0;
308
+ inspect(token2, method) {
309
+ const label3 = tokenLabel(token2);
310
+ const keys = [token2];
311
+ const name = typeof token2 === "function" ? token2.name : typeof token2 === "string" ? token2 : void 0;
289
312
  if (name !== void 0 && this.nameIndex.has(name)) keys.push(this.nameIndex.get(name));
290
313
  for (const key of keys) {
291
314
  const state = this.states.get(key)?.get(method);
292
315
  if (state) return state.inspection();
293
316
  }
294
- throw new UnwatchedInspectionError(label, method);
317
+ throw new UnwatchedInspectionError(label3, method);
295
318
  }
296
319
  /**
297
320
  * Class-token entries that never identity-matched a construction while a
@@ -364,11 +387,11 @@ function recordOutcome(call, outcome, threw) {
364
387
  }
365
388
  function createMethodDecorator(registry) {
366
389
  const wrappers = /* @__PURE__ */ new WeakMap();
367
- return function decorate(instance, token) {
368
- const entries = registry.matchEntries(token);
390
+ return function decorate(instance, token2) {
391
+ const entries = registry.matchEntries(token2);
369
392
  if (entries.length === 0) return instance;
370
393
  if (instance === null || typeof instance !== "object" && typeof instance !== "function") {
371
- throw new NonObjectMethodTargetError(tokenLabel(token));
394
+ throw new NonObjectMethodTargetError(tokenLabel(token2));
372
395
  }
373
396
  if (wrappers.has(instance)) return wrappers.get(instance);
374
397
  const effective = /* @__PURE__ */ new Map();
@@ -379,7 +402,7 @@ function createMethodDecorator(registry) {
379
402
  }
380
403
  for (const method of effective.keys()) {
381
404
  if (typeof instance[method] !== "function") {
382
- throw new MethodNotCallableError(tokenLabel(token), method);
405
+ throw new MethodNotCallableError(tokenLabel(token2), method);
383
406
  }
384
407
  }
385
408
  const methodCache = /* @__PURE__ */ new Map();
@@ -585,6 +608,18 @@ var TestIocBuilder = class _TestIocBuilder {
585
608
  */
586
609
  async build(options = {}) {
587
610
  const root = options.root ?? (0, import_ioc.createContainer)();
611
+ try {
612
+ return await this.buildOnRoot(root, options);
613
+ } catch (primary) {
614
+ try {
615
+ await root.dispose();
616
+ } catch (cleanup) {
617
+ throw new AggregateError([primary, cleanup], "Test IoC build failed and rollback failed", { cause: primary });
618
+ }
619
+ throw primary;
620
+ }
621
+ }
622
+ async buildOnRoot(root, options) {
588
623
  if (typeof root.setInstanceDecorator !== "function") {
589
624
  throw new MissingIocSeamError();
590
625
  }
@@ -592,14 +627,14 @@ var TestIocBuilder = class _TestIocBuilder {
592
627
  const knownByName = /* @__PURE__ */ new Map();
593
628
  const ambiguousNames = /* @__PURE__ */ new Set();
594
629
  const knownLifetimes = /* @__PURE__ */ new Map();
595
- const note = (token, loadAs) => {
596
- const name = typeof token === "function" && token.name ? token.name : typeof token === "string" ? token : null;
630
+ const note = (token2, loadAs) => {
631
+ const name = typeof token2 === "function" && token2.name ? token2.name : typeof token2 === "string" ? token2 : null;
597
632
  if (name !== null) {
598
633
  const existing = knownByName.get(name);
599
- if (existing !== void 0 && existing !== token) ambiguousNames.add(name);
600
- knownByName.set(name, token);
634
+ if (existing !== void 0 && existing !== token2) ambiguousNames.add(name);
635
+ knownByName.set(name, token2);
601
636
  }
602
- if (loadAs !== void 0) knownLifetimes.set(token, loadAs);
637
+ if (loadAs !== void 0) knownLifetimes.set(token2, loadAs);
603
638
  };
604
639
  const effective = /* @__PURE__ */ new Map();
605
640
  const methodWrites = [];
@@ -645,12 +680,12 @@ var TestIocBuilder = class _TestIocBuilder {
645
680
  break;
646
681
  }
647
682
  case "classes": {
648
- const token = resolveKey(write.key, write.byName, "classes");
683
+ const token2 = resolveKey(write.key, write.byName, "classes");
649
684
  note(write.implementation, void 0);
650
- if (!write.byName) note(token, void 0);
651
- effective.set(token, {
685
+ if (!write.byName) note(token2, void 0);
686
+ effective.set(token2, {
652
687
  space: "class",
653
- token,
688
+ token: token2,
654
689
  implementation: write.implementation,
655
690
  // Lifetime priority: the replacement's own @Component scope, then
656
691
  // the lifetime the composition already knows for the token, then
@@ -658,37 +693,37 @@ var TestIocBuilder = class _TestIocBuilder {
658
693
  // class replacing a Singleton-scoped production service must not
659
694
  // silently degrade to Transient (captive-lifetime validation
660
695
  // would reject the production dependents).
661
- loadAs: componentScope(write.implementation) ?? knownLifetimes.get(token) ?? componentScope(token)
696
+ loadAs: componentScope(write.implementation) ?? knownLifetimes.get(token2) ?? componentScope(token2)
662
697
  });
663
698
  break;
664
699
  }
665
700
  case "functions": {
666
- const token = resolveKey(write.key, write.byName, "functions");
667
- const prior = effective.get(token);
668
- effective.set(token, {
701
+ const token2 = resolveKey(write.key, write.byName, "functions");
702
+ const prior = effective.get(token2);
703
+ effective.set(token2, {
669
704
  space: "factory",
670
- token,
705
+ token: token2,
671
706
  factory: write.factory,
672
707
  // preserve configured lifetime unless the scenario overrides it
673
- loadAs: prior && prior.space === "factory" ? prior.loadAs : knownLifetimes.get(token),
708
+ loadAs: prior && prior.space === "factory" ? prior.loadAs : knownLifetimes.get(token2),
674
709
  deps: prior && prior.space === "factory" ? prior.deps : void 0
675
710
  });
676
- note(token, void 0);
711
+ note(token2, void 0);
677
712
  break;
678
713
  }
679
714
  case "values": {
680
- const token = resolveKey(write.key, write.byName, "values");
681
- effective.set(token, { space: "value", token, value: write.value });
682
- note(token, import_ioc.LoadAs.Singleton);
715
+ const token2 = resolveKey(write.key, write.byName, "values");
716
+ effective.set(token2, { space: "value", token: token2, value: write.value });
717
+ note(token2, import_ioc.LoadAs.Singleton);
683
718
  break;
684
719
  }
685
720
  case "methods": {
686
721
  if (write.byName && ambiguousNames.has(write.key)) {
687
722
  throw new AmbiguousNameKeyError(write.key, "methods");
688
723
  }
689
- const token = write.byName && knownByName.has(write.key) ? knownByName.get(write.key) : write.key;
724
+ const token2 = write.byName && knownByName.has(write.key) ? knownByName.get(write.key) : write.key;
690
725
  methodWrites.push({
691
- key: token,
726
+ key: token2,
692
727
  byName: write.byName && !knownByName.has(write.key),
693
728
  methods: new Map(write.methods)
694
729
  });
@@ -696,17 +731,22 @@ var TestIocBuilder = class _TestIocBuilder {
696
731
  }
697
732
  }
698
733
  }
734
+ const borrowed = new Set(options.borrowedTokens);
699
735
  for (const entry of effective.values()) {
700
736
  if (entry.space === "class") {
701
737
  this.registerClassBinding(root, entry.token, entry.implementation, entry.loadAs);
702
738
  } else if (entry.space === "factory") {
703
739
  root.registerFunction(entry.token, entry.factory, {
704
740
  loadAs: entry.loadAs,
705
- param: entry.deps
741
+ param: entry.deps,
742
+ ...borrowed.has(entry.token) ? { owned: false } : {}
706
743
  });
707
744
  } else {
708
745
  const value = entry.value;
709
- root.registerFunction(entry.token, () => value, { loadAs: import_ioc.LoadAs.Singleton });
746
+ root.registerFunction(entry.token, () => value, {
747
+ loadAs: import_ioc.LoadAs.Singleton,
748
+ ...borrowed.has(entry.token) ? { owned: false } : {}
749
+ });
710
750
  }
711
751
  }
712
752
  const registry = new WatchRegistry();
@@ -725,8 +765,8 @@ var TestIocBuilder = class _TestIocBuilder {
725
765
  root.setInstanceDecorator(createMethodDecorator(registry));
726
766
  const env = {
727
767
  root,
728
- get: (token, params) => root.get(token, params),
729
- instance: (cls, params) => root.instance(cls, params),
768
+ get: (token2, params) => import_ioc.ExecutionContext.run(root, () => root.get(token2, params)),
769
+ instance: (cls, params) => import_ioc.ExecutionContext.run(root, () => root.instance(cls, params)),
730
770
  extend: () => root.extend(),
731
771
  verify: async () => registry.verify(),
732
772
  dispose: () => root.dispose(),
@@ -740,17 +780,17 @@ var TestIocBuilder = class _TestIocBuilder {
740
780
  * through real IoC, mirroring the implementation's effective lifetime so
741
781
  * lifetime validation (captive-lifetime checks) stays honest.
742
782
  */
743
- registerClassBinding(root, token, implementation, configuredLoadAs) {
783
+ registerClassBinding(root, token2, implementation, configuredLoadAs) {
744
784
  const loadAs = configuredLoadAs ?? componentScope(implementation) ?? import_ioc.LoadAs.Transient;
745
785
  root.registerClass(implementation, configuredLoadAs !== void 0 ? { loadAs } : void 0);
746
- if (token === implementation) return;
786
+ if (token2 === implementation) return;
747
787
  if (loadAs === import_ioc.LoadAs.Singleton) {
748
- root.registerFunction(token, () => root.get(implementation), {
788
+ root.registerFunction(token2, () => root.get(implementation), {
749
789
  loadAs: import_ioc.LoadAs.Singleton,
750
790
  owned: false
751
791
  });
752
792
  } else {
753
- root.registerFunction(token, (scope) => scope.get(implementation), {
793
+ root.registerFunction(token2, (scope) => scope.get(implementation), {
754
794
  loadAs,
755
795
  param: [import_ioc.SCOPED_CONTAINER],
756
796
  owned: false
@@ -787,16 +827,16 @@ function* tupleEntries(config, space) {
787
827
  );
788
828
  }
789
829
  }
790
- function registerClassBinding(root, token, implementation) {
791
- const loadAs = componentScope2(implementation) ?? componentScope2(token) ?? import_ioc2.LoadAs.Singleton;
830
+ function registerClassBinding(root, token2, implementation) {
831
+ const loadAs = componentScope2(implementation) ?? componentScope2(token2) ?? import_ioc2.LoadAs.Singleton;
792
832
  root.registerClass(implementation, { loadAs });
793
- if (token === implementation) return;
833
+ if (token2 === implementation) return;
794
834
  if (loadAs === import_ioc2.LoadAs.Singleton) {
795
- root.registerFunction(token, () => root.get(implementation), {
835
+ root.registerFunction(token2, () => root.get(implementation), {
796
836
  loadAs: import_ioc2.LoadAs.Singleton
797
837
  });
798
838
  } else {
799
- root.registerFunction(token, (scope) => scope.get(implementation), {
839
+ root.registerFunction(token2, (scope) => scope.get(implementation), {
800
840
  loadAs,
801
841
  param: [import_ioc2.SCOPED_CONTAINER]
802
842
  });
@@ -806,25 +846,29 @@ function installSeams(root, config) {
806
846
  if (typeof root.setInstanceDecorator !== "function") {
807
847
  throw new MissingIocSeamError();
808
848
  }
809
- for (const [token, implementation] of tupleEntries(config.classes ?? [], "classes")) {
810
- registerClassBinding(root, token, implementation);
849
+ for (const [token2, implementation] of tupleEntries(config.classes ?? [], "classes")) {
850
+ registerClassBinding(root, token2, implementation);
811
851
  }
812
- for (const [token, value] of tupleEntries(config.values ?? [], "values")) {
813
- root.registerFunction(token, () => value, { loadAs: import_ioc2.LoadAs.Singleton });
852
+ for (const [token2, value] of tupleEntries(config.values ?? [], "values")) {
853
+ root.registerFunction(token2, () => value, { loadAs: import_ioc2.LoadAs.Singleton });
814
854
  }
815
855
  const registry = new WatchRegistry();
816
- for (const [token, methodsInput] of tupleEntries(config.methods ?? [], "methods")) {
817
- const methods = /* @__PURE__ */ new Map();
856
+ const mergedMethods = /* @__PURE__ */ new Map();
857
+ for (const [token2, methodsInput] of tupleEntries(config.methods ?? [], "methods")) {
858
+ const methods = mergedMethods.get(token2) ?? /* @__PURE__ */ new Map();
818
859
  const entries = methodsInput instanceof Map ? methodsInput.entries() : Object.entries(methodsInput);
819
860
  for (const [name, descriptor] of entries) {
820
861
  if (typeof descriptor !== "function" && !isDescriptor(descriptor)) {
821
862
  throw new InvalidDescriptorError(
822
- `.methods entry ${tokenLabel(token)}.${name} must be a test.* descriptor or a raw wrapper function.`
863
+ `.methods entry ${tokenLabel(token2)}.${name} must be a test.* descriptor or a raw wrapper function.`
823
864
  );
824
865
  }
825
866
  methods.set(name, descriptor);
826
867
  }
827
- registry.addEntry({ key: token, byName: false, methods });
868
+ mergedMethods.set(token2, methods);
869
+ }
870
+ for (const [key, methods] of mergedMethods) {
871
+ registry.addEntry({ key, byName: false, methods });
828
872
  }
829
873
  root.setInstanceDecorator(createMethodDecorator(registry));
830
874
  return {
@@ -832,9 +876,660 @@ function installSeams(root, config) {
832
876
  [ENV_REGISTRY]: registry
833
877
  };
834
878
  }
879
+
880
+ // src/stub.ts
881
+ var owners = ["server", "client", "main", "renderer"];
882
+ var logs = /* @__PURE__ */ new WeakMap();
883
+ function fail(message) {
884
+ throw new InvalidDescriptorError(message);
885
+ }
886
+ function label(value, name) {
887
+ if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
888
+ fail(name + " requires a nonempty identity");
889
+ }
890
+ }
891
+ function token(value) {
892
+ if (value === null || value === void 0 || typeof value === "string" && !value.trim()) {
893
+ fail("replacement requires an exact declared token");
894
+ }
895
+ }
896
+ function executable(value, behaviorOnly = false, active = /* @__PURE__ */ new Set()) {
897
+ if (!behaviorOnly && typeof value === "function") return;
898
+ if (!isDescriptor(value)) fail("replacement requires a function or test.* descriptor");
899
+ if (active.has(value)) fail("cyclic test.* descriptor");
900
+ active.add(value);
901
+ const d = value;
902
+ try {
903
+ if (d.kind === "returns" || d.kind === "throws" || d.kind === "original") return;
904
+ if (!behaviorOnly && d.kind === "watch" && (d.wrapper === void 0 || typeof d.wrapper === "function")) return;
905
+ if (!behaviorOnly && d.kind === "expect" && Number.isInteger(d.expected) && d.expected >= 0) {
906
+ if (d.behavior !== void 0) executable(d.behavior, true, active);
907
+ return;
908
+ }
909
+ if (d.kind === "calls" && Array.isArray(d.script)) {
910
+ for (const child of d.script) executable(child, true, active);
911
+ return;
912
+ }
913
+ fail("invalid test.* descriptor");
914
+ } finally {
915
+ active.delete(value);
916
+ }
917
+ }
918
+ function snapshotExecutable(value) {
919
+ executable(value);
920
+ if (typeof value === "function") return value;
921
+ if (value.kind === "calls") {
922
+ return Object.freeze({ ...value, script: Object.freeze(value.script.map((v) => snapshotExecutable(v))) });
923
+ }
924
+ if (value.kind === "expect" && value.behavior !== void 0) {
925
+ return Object.freeze({ ...value, behavior: snapshotExecutable(value.behavior) });
926
+ }
927
+ return Object.freeze({ ...value });
928
+ }
929
+ function normalizeLoader(identity2) {
930
+ const ref = typeof identity2 === "string" ? { path: identity2, export: "default" } : identity2;
931
+ if (!ref || typeof ref !== "object" || Reflect.ownKeys(ref).some((k) => k !== "path" && k !== "export")) {
932
+ fail(".load requires a project-relative path or { path, export }");
933
+ }
934
+ label(ref.path, ".load path");
935
+ label(ref.export, ".load export");
936
+ if (/^[\/\\]|[\\?#:]/.test(ref.path) || ref.path.split("/").some((s) => !s || s === "." || s === "..")) {
937
+ fail(".load requires a normalized project-relative source path");
938
+ }
939
+ return Object.freeze({ path: ref.path, export: ref.export });
940
+ }
941
+ function append(stub, input, options) {
942
+ 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))) {
943
+ fail("replacement options accept only owner: server | client | main | renderer");
944
+ }
945
+ const log = logs.get(stub);
946
+ const entry = Object.freeze({ ...input, owner: options?.owner, provenance: Object.freeze([log.calls]) });
947
+ return make([...log.entries, entry], log.calls + 1);
948
+ }
949
+ var TestStub = class {
950
+ constructor() {
951
+ }
952
+ class(target, replacement, options) {
953
+ token(target);
954
+ if (typeof target !== "function" || typeof replacement !== "function" || !replacement.prototype) {
955
+ fail(".class requires class tokens and a replacement constructor");
956
+ }
957
+ return append(this, { kind: "class", target, replacement }, options);
958
+ }
959
+ function(target, replacement, options) {
960
+ token(target);
961
+ if (typeof replacement !== "function") fail(".function requires a callable/provider replacement");
962
+ return append(this, { kind: "function", target, replacement }, options);
963
+ }
964
+ method(target, method, replacement, options) {
965
+ token(target);
966
+ label(method, ".method");
967
+ return append(this, { kind: "method", target, method, replacement: snapshotExecutable(replacement) }, options);
968
+ }
969
+ value(target, replacement, options) {
970
+ token(target);
971
+ return append(this, { kind: "value", target, replacement }, options);
972
+ }
973
+ middleware(target, replacement, options) {
974
+ label(target, ".middleware");
975
+ return append(this, { kind: "middleware", target, replacement: snapshotExecutable(replacement) }, options);
976
+ }
977
+ load(target, replacement, options) {
978
+ return append(this, { kind: "load", target: normalizeLoader(target), replacement: snapshotExecutable(replacement) }, options);
979
+ }
980
+ use(other) {
981
+ const incoming = stubEntries(other);
982
+ const log = logs.get(this);
983
+ return make([...log.entries, ...incoming.map((entry) => Object.freeze({
984
+ ...entry,
985
+ provenance: Object.freeze([log.calls, ...entry.provenance])
986
+ }))], log.calls + 1);
987
+ }
988
+ };
989
+ function make(entries, calls) {
990
+ const stub = Object.create(TestStub.prototype);
991
+ logs.set(stub, { entries: Object.freeze([...entries]), calls });
992
+ return Object.freeze(stub);
993
+ }
994
+ function testStub() {
995
+ return make([], 0);
996
+ }
997
+ function stubEntries(stub) {
998
+ const log = logs.get(stub);
999
+ if (!log) fail(".use requires an immutable testStub description (cyclic/foreign objects are not supported)");
1000
+ return log.entries;
1001
+ }
1002
+
1003
+ // src/selection.ts
1004
+ var SourceSelectionError = class extends Error {
1005
+ constructor(message, owner, choices = []) {
1006
+ super((owner ? owner + ": " : "") + message);
1007
+ this.owner = owner;
1008
+ this.choices = choices;
1009
+ this.name = "SourceSelectionError";
1010
+ }
1011
+ owner;
1012
+ choices;
1013
+ code = "testing/selection";
1014
+ };
1015
+ function record(value) {
1016
+ return !!value && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1017
+ }
1018
+ function normalizeOwner(value, owner) {
1019
+ const fail2 = (message) => {
1020
+ throw new SourceSelectionError(message, owner);
1021
+ };
1022
+ if (!record(value)) return fail2("select an owner with module, path, or {}");
1023
+ const keys = Reflect.ownKeys(value);
1024
+ if (keys.some((k) => k !== "module" && k !== "path") || keys.length > 1) {
1025
+ return fail2("select module OR path, or {}; no other selector keys are supported");
1026
+ }
1027
+ if (!keys.length) return Object.freeze({});
1028
+ const key = keys[0];
1029
+ const input = value[key];
1030
+ const list = key === "module" && typeof input === "string" ? [input] : input;
1031
+ if (!Array.isArray(list) || !list.length || list.some((x) => typeof x !== "string" || !x.trim() || /[\u0000-\u001f\u007f]/.test(x))) {
1032
+ return fail2(key + " requires nonempty " + (key === "module" ? "name(s)" : "path array"));
1033
+ }
1034
+ const unique = Object.freeze([...new Set(list)]);
1035
+ return key === "module" ? Object.freeze({ module: unique }) : Object.freeze({ path: unique });
1036
+ }
1037
+ function normalizeTestSelection(selection, declaredOwners) {
1038
+ const declared = new Set(declaredOwners);
1039
+ if (selection === void 0) {
1040
+ return Object.freeze(Object.fromEntries([...declared].map((owner) => [owner, Object.freeze({})])));
1041
+ }
1042
+ if (!record(selection) || !Reflect.ownKeys(selection).length) {
1043
+ throw new SourceSelectionError("select() requires at least one declared owner");
1044
+ }
1045
+ const result = {};
1046
+ for (const owner of Reflect.ownKeys(selection)) {
1047
+ if (typeof owner !== "string" || !declared.has(owner)) {
1048
+ throw new SourceSelectionError("owner is absent or unknown; available: " + [...declared].join(", "), String(owner), [...declared]);
1049
+ }
1050
+ Object.defineProperty(result, owner, { value: normalizeOwner(selection[owner], owner), enumerable: true });
1051
+ }
1052
+ return Object.freeze(result);
1053
+ }
1054
+ function validatePath(path, options) {
1055
+ const invalid = /[?#*\[\]\\\u0000-\u001f\u007f]/.test(path) || path.includes("://") || path.includes("//") || path.split("/").some((segment) => segment === "." || segment === "..");
1056
+ const native = options.native && /^[A-Za-z0-9_$-]+(?:\.[A-Za-z0-9_$-]+)*$/.test(path);
1057
+ if (invalid || !path.startsWith("/") && !native) {
1058
+ throw new SourceSelectionError('invalid source path selector "' + path + '"', options.owner);
1059
+ }
1060
+ }
1061
+ function matches(path, selector) {
1062
+ if (selector === "/") return path.startsWith("/");
1063
+ if (selector.startsWith("/") && selector.endsWith("/")) {
1064
+ return path === selector.slice(0, -1) || path.startsWith(selector);
1065
+ }
1066
+ return path === selector;
1067
+ }
1068
+ function selectSourceEntries(source, input, options = {}) {
1069
+ const selection = normalizeOwner(input, options.owner);
1070
+ if (selection.module !== void 0) {
1071
+ const names = selection.module;
1072
+ const choices = [.../* @__PURE__ */ new Set([...source.flatMap((e) => e.module == null ? [] : [e.module]), ...options.modules ?? []])];
1073
+ for (const name of names) if (!choices.includes(name)) {
1074
+ throw new SourceSelectionError('unknown module "' + name + '"; available: ' + choices.join(", "), options.owner, choices);
1075
+ }
1076
+ return source.filter((e) => e.module != null && names.includes(e.module));
1077
+ }
1078
+ if (selection.path !== void 0) {
1079
+ const paths = selection.path;
1080
+ const choices = [...new Set(source.map((e) => e.path))];
1081
+ for (const path of paths) {
1082
+ validatePath(path, options);
1083
+ if (!source.some((e) => matches(e.path, path))) {
1084
+ throw new SourceSelectionError('unknown path "' + path + '"; available: ' + choices.join(", "), options.owner, choices);
1085
+ }
1086
+ }
1087
+ return source.filter((e) => paths.some((path) => matches(e.path, path)));
1088
+ }
1089
+ return [...source];
1090
+ }
1091
+
1092
+ // src/resource_context.ts
1093
+ var ANCHOR = /* @__PURE__ */ Symbol.for("@noego/testing.resource-scope.v1");
1094
+ function storage() {
1095
+ const global = globalThis;
1096
+ if (global[ANCHOR]) {
1097
+ const existing = global[ANCHOR];
1098
+ if (typeof existing.run !== "function" || typeof existing.getStore !== "function") {
1099
+ throw new Error("Incompatible NoEgo resource-scope v1 channel");
1100
+ }
1101
+ return existing;
1102
+ }
1103
+ let hooks;
1104
+ try {
1105
+ hooks = global.process?.getBuiltinModule?.("node:async_hooks") ?? require("async_hooks");
1106
+ } catch {
1107
+ return void 0;
1108
+ }
1109
+ if (!hooks?.AsyncLocalStorage) return void 0;
1110
+ const created = new hooks.AsyncLocalStorage();
1111
+ Object.defineProperty(global, ANCHOR, { value: created, configurable: false, writable: false });
1112
+ return created;
1113
+ }
1114
+ function runInResourceScope(scope, body) {
1115
+ const channel = storage();
1116
+ return channel ? channel.run(scope, body) : body();
1117
+ }
1118
+ async function registerTestResource(resource, owner = "resource") {
1119
+ try {
1120
+ const scope = storage()?.getStore();
1121
+ if (!scope) return resource;
1122
+ if (typeof resource.verify === "function") {
1123
+ scope.environment(resource, owner);
1124
+ } else scope.own(resource, owner);
1125
+ return resource;
1126
+ } catch (primary) {
1127
+ try {
1128
+ await resource.dispose();
1129
+ } catch (cleanup) {
1130
+ throw new AggregateError([primary, cleanup], "Resource admission and cleanup failed", { cause: primary });
1131
+ }
1132
+ throw primary;
1133
+ }
1134
+ }
1135
+
1136
+ // src/lifecycle.ts
1137
+ var TestFinalizationError = class extends AggregateError {
1138
+ failures;
1139
+ constructor(failures) {
1140
+ super(
1141
+ failures.map((f) => f.error),
1142
+ "Test finalization failed: " + failures.map((f) => f.owner + "/" + f.phase).join(", "),
1143
+ { cause: failures[0]?.error }
1144
+ );
1145
+ this.name = "TestFinalizationError";
1146
+ this.failures = Object.freeze(failures.map((f) => Object.freeze({ ...f })));
1147
+ }
1148
+ };
1149
+ var TestResourceScope = class {
1150
+ resources = [];
1151
+ owned = /* @__PURE__ */ new Map();
1152
+ closing;
1153
+ complete = false;
1154
+ /** Runner finalizers can avoid reporting an already-finished failure twice. */
1155
+ get finalized() {
1156
+ return this.complete;
1157
+ }
1158
+ own(resource, owner = "resource") {
1159
+ if (this.closing) throw new Error("Test resource scope is closed");
1160
+ if (!resource || typeof resource.dispose !== "function") throw new TypeError("Test resource requires dispose()");
1161
+ if (!this.owned.has(resource)) {
1162
+ const entry = { resource, owner };
1163
+ this.owned.set(resource, entry);
1164
+ this.resources.push(entry);
1165
+ }
1166
+ return resource;
1167
+ }
1168
+ environment(resource, owner = "application") {
1169
+ if (!resource || typeof resource.verify !== "function") throw new TypeError("Test environment requires verify()");
1170
+ this.own(resource, owner);
1171
+ this.owned.get(resource).verify = () => resource.verify();
1172
+ if (resource.settle) this.owned.get(resource).settle = () => resource.settle();
1173
+ return resource;
1174
+ }
1175
+ dispose() {
1176
+ return this.closing ??= Promise.resolve().then(async () => {
1177
+ const failures = [];
1178
+ const reverse = [...this.resources].reverse();
1179
+ for (const entry of reverse) if (entry.settle) {
1180
+ try {
1181
+ await entry.settle();
1182
+ } catch (error) {
1183
+ failures.push({ owner: entry.owner, phase: "settle", error });
1184
+ }
1185
+ }
1186
+ for (const entry of reverse) if (entry.verify) {
1187
+ try {
1188
+ await entry.verify();
1189
+ } catch (error) {
1190
+ failures.push({ owner: entry.owner, phase: "verify", error });
1191
+ }
1192
+ }
1193
+ for (const entry of reverse) {
1194
+ try {
1195
+ await entry.resource.dispose();
1196
+ } catch (error) {
1197
+ failures.push({ owner: entry.owner, phase: "dispose", error });
1198
+ }
1199
+ }
1200
+ if (failures.length) throw new TestFinalizationError(failures);
1201
+ }).finally(() => {
1202
+ this.complete = true;
1203
+ });
1204
+ }
1205
+ };
1206
+ function createTestScope() {
1207
+ return new TestResourceScope();
1208
+ }
1209
+ async function withTestScope(body) {
1210
+ const scope = createTestScope();
1211
+ let failed = false;
1212
+ let primary;
1213
+ let result;
1214
+ try {
1215
+ result = await runInResourceScope(scope, () => body(scope));
1216
+ } catch (error) {
1217
+ failed = true;
1218
+ primary = error;
1219
+ }
1220
+ try {
1221
+ await scope.dispose();
1222
+ } catch (error) {
1223
+ if (!failed) throw error;
1224
+ const cleanup = error instanceof TestFinalizationError ? error.failures : [{ owner: "scope", phase: "dispose", error }];
1225
+ throw new TestFinalizationError([{ owner: "test", phase: "test", error: primary }, ...cleanup]);
1226
+ }
1227
+ if (failed) throw primary;
1228
+ return result;
1229
+ }
1230
+
1231
+ // src/resource_case.ts
1232
+ function resourceCase(body) {
1233
+ return (...args) => withTestScope((resources) => {
1234
+ const context = args.find((value) => value && (typeof value === "object" || typeof value === "function") && typeof value.onTestFinished === "function");
1235
+ context?.onTestFinished(async () => {
1236
+ if (!resources.finalized) await resources.dispose();
1237
+ });
1238
+ return body(resources, ...args);
1239
+ });
1240
+ }
1241
+
1242
+ // src/coverage.ts
1243
+ var COVERAGE_METRICS = Object.freeze(["lines", "statements", "functions", "branches"]);
1244
+ var TestCoverageConfigurationError = class extends Error {
1245
+ constructor(message) {
1246
+ super(message);
1247
+ this.name = "TestCoverageConfigurationError";
1248
+ }
1249
+ };
1250
+ var DEFAULT_EXCLUSIONS = [
1251
+ { pattern: "**/*.{test,spec}.{js,jsx,ts,tsx,mjs,cjs,mts,cts}", kind: "tests", reason: "Test implementations are not product source." },
1252
+ { pattern: "**/*.d.{ts,mts,cts}", kind: "types", reason: "Type declarations have no executable counters." }
1253
+ ];
1254
+ var EXCLUSION_KINDS = ["tests", "types", "generated", "nonexecutable", "separate-runtime"];
1255
+ function nonempty(value, label3) {
1256
+ if (typeof value !== "string" || !value.trim()) throw new TestCoverageConfigurationError(label3 + " must be a nonempty string");
1257
+ }
1258
+ function version(value) {
1259
+ if (typeof value !== "string" || !/^[234]\.\d+\.\d+$/.test(value)) {
1260
+ throw new TestCoverageConfigurationError("Declare a qualified stable Vitest/provider version in majors 2, 3, or 4");
1261
+ }
1262
+ return Number(value[0]);
1263
+ }
1264
+ function vitestCoverage(input) {
1265
+ const major = version(input.runnerVersion);
1266
+ version(input.providerVersion);
1267
+ if (input.runnerVersion !== input.providerVersion) throw new TestCoverageConfigurationError("Vitest and @vitest/coverage-v8 versions must match exactly");
1268
+ if (!Array.isArray(input.include) || !input.include.length) throw new TestCoverageConfigurationError("coverage.include must name the complete eligible source set");
1269
+ for (const pattern of input.include) {
1270
+ nonempty(pattern, "include pattern");
1271
+ if (pattern.startsWith("!")) throw new TestCoverageConfigurationError("Record exclusions separately with provenance, not as negative includes");
1272
+ }
1273
+ const include = [...new Set(input.include)];
1274
+ const thresholds = { lines: 99, statements: 99, functions: 99, branches: 99, ...input.thresholds };
1275
+ if (Object.keys(thresholds).some((key) => !COVERAGE_METRICS.includes(key))) throw new TestCoverageConfigurationError("Unknown coverage metric");
1276
+ for (const metric of COVERAGE_METRICS) {
1277
+ if (!Number.isFinite(thresholds[metric]) || thresholds[metric] < 0 || thresholds[metric] > 100) {
1278
+ throw new TestCoverageConfigurationError(metric + " threshold must be between 0 and 100");
1279
+ }
1280
+ }
1281
+ const exclusions = [...DEFAULT_EXCLUSIONS, ...input.exclusions ?? []].map((entry) => {
1282
+ nonempty(entry.pattern, "exclusion pattern");
1283
+ nonempty(entry.reason, "exclusion reason");
1284
+ if (!EXCLUSION_KINDS.includes(entry.kind)) throw new TestCoverageConfigurationError("Unknown exclusion kind");
1285
+ if (entry.kind === "generated" || entry.kind === "separate-runtime") nonempty(entry.evidence, "exclusion evidence");
1286
+ return { ...entry };
1287
+ });
1288
+ if (new Set(exclusions.map((entry) => entry.pattern)).size !== exclusions.length) throw new TestCoverageConfigurationError("Duplicate exclusion pattern");
1289
+ const options = {
1290
+ provider: "v8",
1291
+ include: [...include],
1292
+ exclude: exclusions.map((entry) => entry.pattern),
1293
+ // v4 removed all: explicit include now includes covered AND uncovered files.
1294
+ ...major < 4 ? { all: true } : {},
1295
+ reporter: ["text-summary", "json-summary", "json"],
1296
+ reportOnFailure: true,
1297
+ thresholds: { ...thresholds }
1298
+ };
1299
+ return {
1300
+ options,
1301
+ provenance: Object.freeze({
1302
+ runner: "vitest",
1303
+ runnerVersion: input.runnerVersion,
1304
+ provider: "@vitest/coverage-v8",
1305
+ providerVersion: input.providerVersion,
1306
+ includesUnimported: true,
1307
+ include: Object.freeze(include),
1308
+ exclusions: Object.freeze(exclusions.map((entry) => Object.freeze(entry))),
1309
+ thresholds: Object.freeze(thresholds),
1310
+ metrics: Object.freeze([...COVERAGE_METRICS])
1311
+ })
1312
+ };
1313
+ }
1314
+ var TestDiscoveryError = class extends Error {
1315
+ constructor(failures) {
1316
+ super(failures.join("; "));
1317
+ this.failures = failures;
1318
+ this.name = "TestDiscoveryError";
1319
+ }
1320
+ failures;
1321
+ };
1322
+ function assertTestLanes(required, reports) {
1323
+ if (!required.length) throw new TestDiscoveryError(["At least one required lane must be declared"]);
1324
+ const names = /* @__PURE__ */ new Set();
1325
+ const failures = [];
1326
+ for (const name of required) nonempty(name, "required lane name");
1327
+ if (new Set(required).size !== required.length) throw new TestDiscoveryError(["Duplicate required lane"]);
1328
+ for (const report of reports) {
1329
+ nonempty(report.name, "reported lane name");
1330
+ if (names.has(report.name)) throw new TestDiscoveryError(["Duplicate report for lane " + report.name]);
1331
+ names.add(report.name);
1332
+ for (const key of ["total", "passed", "failed", "skipped"]) {
1333
+ if (!Number.isSafeInteger(report[key]) || report[key] < 0) throw new TestDiscoveryError(["Invalid " + key + " count for " + report.name]);
1334
+ }
1335
+ if (report.total !== report.passed + report.failed + report.skipped) throw new TestDiscoveryError(["Inconsistent counts for " + report.name]);
1336
+ if (report.failed) failures.push(report.name + ": " + report.failed + " failed");
1337
+ if (required.includes(report.name)) {
1338
+ if (!report.total) failures.push(report.name + ": required lane is empty");
1339
+ if (report.skipped) failures.push(report.name + ": " + report.skipped + " skipped");
1340
+ }
1341
+ }
1342
+ for (const name of required) if (!names.has(name)) failures.push(name + ": required lane is missing");
1343
+ if (failures.length) throw new TestDiscoveryError(Object.freeze(failures));
1344
+ }
1345
+
1346
+ // src/overlays.ts
1347
+ var TestOverlayError = class extends Error {
1348
+ constructor(message, entry) {
1349
+ super("entry " + entry.provenance.join(".") + ": " + message);
1350
+ this.entry = entry;
1351
+ this.name = "TestOverlayError";
1352
+ }
1353
+ entry;
1354
+ code = "testing/overlay";
1355
+ };
1356
+ function label2(target) {
1357
+ return typeof target === "function" ? target.name : String(target);
1358
+ }
1359
+ function binding(catalog, token2) {
1360
+ return catalog.bindings.find((b) => b.token === token2);
1361
+ }
1362
+ function owns(catalog, entry) {
1363
+ if (entry.kind === "middleware") return catalog.middleware?.includes(entry.target) ?? false;
1364
+ if (entry.kind === "load") return catalog.loaders?.some((l) => l.path === entry.target.path && l.export === entry.target.export) ?? false;
1365
+ return binding(catalog, entry.target) !== void 0;
1366
+ }
1367
+ function sameSlot(a, b) {
1368
+ if (a.owner !== b.owner) return false;
1369
+ const x = a.entry, y = b.entry;
1370
+ if (x.kind === "load" && y.kind === "load") return x.target.path === y.target.path && x.target.export === y.target.export;
1371
+ if (x.kind === "middleware" || x.kind === "load" || y.kind === "middleware" || y.kind === "load") {
1372
+ return x.kind === y.kind && x.target === y.target;
1373
+ }
1374
+ if (x.kind === "method" || y.kind === "method") {
1375
+ return x.kind === "method" && y.kind === "method" && x.target === y.target && x.method === y.method;
1376
+ }
1377
+ return x.target === y.target;
1378
+ }
1379
+ function resolveTestOverlays(stub, catalogs) {
1380
+ const names = catalogs.map((c) => c.owner);
1381
+ if (new Set(names).size !== names.length) throw new TypeError("duplicate test owner catalog");
1382
+ const result = [];
1383
+ for (const entry of stubEntries(stub)) {
1384
+ let candidates = catalogs.filter((c) => owns(c, entry) && (entry.owner === void 0 || c.owner === entry.owner));
1385
+ if (candidates.length === 0 && entry.kind !== "middleware" && entry.kind !== "load" && typeof entry.target === "function") {
1386
+ const fallback = catalogs.filter((c) => entry.owner === void 0 || c.owner === entry.owner);
1387
+ if (fallback.length === 1) {
1388
+ const synthetic = { token: entry.target, kind: "class", lifetime: "singleton", implementation: entry.target, dependencies: [] };
1389
+ candidates = [{ ...fallback[0], bindings: [...fallback[0].bindings, synthetic] }];
1390
+ }
1391
+ }
1392
+ if (candidates.length !== 1) {
1393
+ const identity2 = entry.kind === "load" ? entry.target.path + "#" + entry.target.export : label2(entry.target);
1394
+ 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);
1395
+ }
1396
+ const catalog = candidates[0];
1397
+ const declared = entry.kind === "middleware" || entry.kind === "load" ? void 0 : binding(catalog, entry.target);
1398
+ if (entry.kind === "function" && declared?.kind !== "factory" && declared?.kind !== "class" && !(declared?.kind === "value" && typeof declared.implementation === "function")) {
1399
+ throw new TestOverlayError(".function requires a declared factory/provider, class, or callable value binding", entry);
1400
+ }
1401
+ const resolved = Object.freeze({ owner: catalog.owner, entry, binding: declared });
1402
+ const prior = result.findIndex((e) => sameSlot(e, resolved));
1403
+ if (prior !== -1) result.splice(prior, 1);
1404
+ result.push(resolved);
1405
+ }
1406
+ return Object.freeze([...result.filter((e) => e.entry.kind !== "method"), ...result.filter((e) => e.entry.kind === "method")]);
1407
+ }
1408
+
1409
+ // src/binding_overlays.ts
1410
+ var import_ioc3 = require("@noego/ioc");
1411
+ function applyTestBindings(production, overlays, owner) {
1412
+ let builder = production;
1413
+ const entries = overlays.filter((e) => e.owner === owner);
1414
+ const borrowed = [];
1415
+ for (const overlay of entries) {
1416
+ const { entry, binding: binding2 } = overlay;
1417
+ if (entry.kind === "middleware" || entry.kind === "load" || entry.kind === "method") continue;
1418
+ if (!binding2) throw new TestOverlayError("missing production binding metadata", entry);
1419
+ builder = builder.use((0, import_ioc3.defineModule)("@noego/testing/" + owner + "/" + entry.provenance.join("."), (bind) => {
1420
+ if (entry.kind === "class") {
1421
+ bind(entry.target).to(entry.replacement)[binding2.lifetime]();
1422
+ } else if (entry.kind === "function" && binding2.kind === "factory") {
1423
+ bind(entry.target).toFactory(entry.replacement, [...binding2.dependencies])[binding2.lifetime]();
1424
+ } else if (entry.kind === "function" && binding2.kind === "class") {
1425
+ bind(entry.target).toFactory(() => entry.replacement())[binding2.lifetime]();
1426
+ borrowed.push(entry.target);
1427
+ } else {
1428
+ bind(entry.target).toFactory(() => entry.replacement)[binding2.lifetime]();
1429
+ borrowed.push(entry.target);
1430
+ }
1431
+ }));
1432
+ }
1433
+ for (const { entry } of entries) if (entry.kind === "method") {
1434
+ builder = builder.methods([[entry.target, { [entry.method]: entry.replacement }]]);
1435
+ }
1436
+ return Object.freeze({ builder, buildOptions: Object.freeze({ borrowedTokens: Object.freeze(borrowed) }) });
1437
+ }
1438
+
1439
+ // src/executable_overlays.ts
1440
+ function identity(kind, target) {
1441
+ if (kind === "middleware") {
1442
+ if (typeof target !== "string") throw new TypeError("middleware identity must be a string");
1443
+ return "middleware:" + target;
1444
+ }
1445
+ if (typeof target === "string") return "load:" + target + "#default";
1446
+ return "load:" + target.path + "#" + target.export;
1447
+ }
1448
+ function createTestExecutables(overlays, owner) {
1449
+ const registry = new WatchRegistry();
1450
+ const decorator = createMethodDecorator(registry);
1451
+ const selected = /* @__PURE__ */ new Set();
1452
+ const installed = /* @__PURE__ */ new Map();
1453
+ for (const { owner: selectedOwner, entry } of overlays) {
1454
+ if (selectedOwner !== owner || entry.kind !== "middleware" && entry.kind !== "load") continue;
1455
+ const key = identity(entry.kind, entry.target);
1456
+ selected.add(key);
1457
+ const behavior = typeof entry.replacement === "function" ? test.watch(() => entry.replacement) : entry.replacement;
1458
+ registry.addEntry({ key, byName: false, methods: /* @__PURE__ */ new Map([["invoke", behavior]]) });
1459
+ }
1460
+ return {
1461
+ replace(kind, target, original) {
1462
+ if (typeof original !== "function") throw new TypeError("source executable must be callable");
1463
+ const key = identity(kind, target);
1464
+ if (!selected.has(key)) return original;
1465
+ const cached = installed.get(key);
1466
+ if (cached) {
1467
+ if (cached.original !== original) throw new TypeError("ambiguous source executable: " + key);
1468
+ return cached.replacement;
1469
+ }
1470
+ const subject = decorator({ invoke: original }, key);
1471
+ const replacement = function(...args) {
1472
+ return subject.invoke.apply(this, args);
1473
+ };
1474
+ installed.set(key, { original, replacement });
1475
+ return replacement;
1476
+ },
1477
+ inspect: (kind, target) => registry.inspect(identity(kind, target), "invoke"),
1478
+ verify: async () => registry.verify(),
1479
+ [ENV_REGISTRY]: registry
1480
+ };
1481
+ }
1482
+
1483
+ // src/binding_catalog.ts
1484
+ var import_ioc4 = require("@noego/ioc");
1485
+ function describeTestBindings(builder, discovered = []) {
1486
+ const declarations = /* @__PURE__ */ new Map();
1487
+ const classBinding = (token2, implementation) => (0, import_ioc4.flattenModule)((0, import_ioc4.defineModule)("@noego/testing/discovered", (bind) => {
1488
+ bind(token2).to(implementation);
1489
+ }))[0];
1490
+ for (const write of builder.writes) {
1491
+ if (write.op === "use") {
1492
+ for (const registration of (0, import_ioc4.flattenModule)(write.module)) declarations.set(registration.token, registration);
1493
+ } else if (write.op === "classes") {
1494
+ const registration = classBinding(write.key, write.implementation);
1495
+ declarations.set(write.key, { ...registration, lifetime: declarations.get(write.key)?.lifetime ?? registration.lifetime });
1496
+ } else if (write.op === "functions" || write.op === "values") {
1497
+ const prior = declarations.get(write.key);
1498
+ declarations.set(write.key, {
1499
+ token: write.key,
1500
+ kind: write.op === "functions" ? "factory" : "value",
1501
+ lifetime: write.op === "values" ? "singleton" : prior?.lifetime ?? "transient",
1502
+ dependencies: write.op === "functions" && prior?.kind === "factory" ? prior.dependencies : [],
1503
+ implementation: write.op === "functions" ? write.factory : write.value,
1504
+ source: "@noego/testing/declared",
1505
+ requiredCapabilities: []
1506
+ });
1507
+ }
1508
+ }
1509
+ const visited = /* @__PURE__ */ new Set();
1510
+ const visit = (token2) => {
1511
+ if (visited.has(token2)) return;
1512
+ visited.add(token2);
1513
+ let registration = declarations.get(token2);
1514
+ if (!registration && typeof token2 === "function" && token2.prototype) {
1515
+ registration = classBinding(token2, token2);
1516
+ declarations.set(token2, registration);
1517
+ }
1518
+ if (!registration) return;
1519
+ for (const dependency of registration.dependencies) visit(dependency);
1520
+ if (registration.kind === "class" && registration.implementation !== token2) visit(registration.implementation);
1521
+ };
1522
+ for (const token2 of [...declarations.keys(), ...discovered]) visit(token2);
1523
+ return Object.freeze([...declarations.values()].map((r) => Object.freeze({
1524
+ ...r,
1525
+ dependencies: Object.freeze([...r.dependencies]),
1526
+ requiredCapabilities: Object.freeze([...r.requiredCapabilities])
1527
+ })));
1528
+ }
835
1529
  // Annotate the CommonJS export names for ESM import in node:
836
1530
  0 && (module.exports = {
837
1531
  AmbiguousNameKeyError,
1532
+ COVERAGE_METRICS,
838
1533
  CallScriptExhaustedError,
839
1534
  ENV_REGISTRY,
840
1535
  ExpectationOverflowError,
@@ -842,14 +1537,36 @@ function installSeams(root, config) {
842
1537
  MethodNotCallableError,
843
1538
  MissingIocSeamError,
844
1539
  NonObjectMethodTargetError,
1540
+ SourceSelectionError,
1541
+ TestCoverageConfigurationError,
1542
+ TestDiscoveryError,
1543
+ TestFinalizationError,
845
1544
  TestIocBuilder,
1545
+ TestOverlayError,
1546
+ TestResourceScope,
1547
+ TestStub,
846
1548
  TestingError,
847
1549
  TokenIdentitySplitError,
848
1550
  UnknownTokenKeyError,
849
1551
  UnwatchedInspectionError,
850
1552
  VerificationError,
1553
+ applyTestBindings,
1554
+ assertTestLanes,
1555
+ createTestExecutables,
1556
+ createTestScope,
1557
+ describeTestBindings,
851
1558
  installSeams,
1559
+ normalizeTestSelection,
1560
+ registerTestResource,
1561
+ resolveTestOverlays,
1562
+ resourceCase,
1563
+ runInResourceScope,
1564
+ selectSourceEntries,
1565
+ stubEntries,
852
1566
  test,
853
- testIoc
1567
+ testIoc,
1568
+ testStub,
1569
+ vitestCoverage,
1570
+ withTestScope
854
1571
  });
855
1572
  //# sourceMappingURL=index.cjs.map