vouchington-tooling 0.53.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +76 -12
  2. package/dist/agent-blackboard/index.d.mts +0 -1
  3. package/dist/agent-blackboard/index.mjs +0 -23
  4. package/dist/cli/commands/agent-blackboard-flags.d.mts +0 -1
  5. package/dist/cli/commands/agent-blackboard-flags.mjs +0 -9
  6. package/dist/cli/commands/agent-blackboard.d.mts +0 -2
  7. package/dist/cli/commands/agent-blackboard.mjs +7 -121
  8. package/dist/cli/commands/story-coverage.d.mts +2 -0
  9. package/dist/cli/commands/story-coverage.mjs +56 -0
  10. package/dist/cli/index.mjs +6 -0
  11. package/dist/cli/parse-forwarded-commands.d.mts +3 -0
  12. package/dist/cli/parse-forwarded-commands.mjs +2 -0
  13. package/dist/cli/parse-story-coverage-fields.d.mts +19 -0
  14. package/dist/cli/parse-story-coverage-fields.mjs +69 -0
  15. package/dist/cli/parse-story-coverage.d.mts +8 -0
  16. package/dist/cli/parse-story-coverage.mjs +34 -0
  17. package/dist/cli/parse.d.mts +5 -1
  18. package/dist/cli/parse.mjs +3 -0
  19. package/dist/cli/usage.d.mts +1 -1
  20. package/dist/cli/usage.mjs +8 -7
  21. package/dist/host-storage/check.d.mts +38 -0
  22. package/dist/host-storage/check.mjs +109 -0
  23. package/dist/host-storage/cli.d.mts +7 -0
  24. package/dist/host-storage/cli.mjs +102 -0
  25. package/dist/host-storage/host-storage.test-helpers.d.mts +26 -0
  26. package/dist/host-storage/host-storage.test-helpers.mjs +58 -0
  27. package/dist/host-storage/index.d.mts +3 -0
  28. package/dist/host-storage/index.mjs +3 -0
  29. package/dist/host-storage/preflight.d.mts +22 -0
  30. package/dist/host-storage/preflight.mjs +105 -0
  31. package/dist/index.d.mts +2 -0
  32. package/dist/index.mjs +1 -0
  33. package/dist/playwright/assertions.d.mts +1 -0
  34. package/dist/playwright/assertions.mjs +5 -0
  35. package/dist/playwright/blocked-external-network.d.mts +15 -0
  36. package/dist/playwright/blocked-external-network.mjs +73 -0
  37. package/dist/playwright/browser-dialog-issues.d.mts +12 -0
  38. package/dist/playwright/browser-dialog-issues.mjs +29 -0
  39. package/dist/playwright/browser-errors.d.mts +22 -0
  40. package/dist/playwright/browser-errors.mjs +130 -0
  41. package/dist/playwright/browser-issue-monitor.test-helpers.d.mts +31 -0
  42. package/dist/playwright/browser-issue-monitor.test-helpers.mjs +51 -0
  43. package/dist/playwright/browser-issue-records.d.mts +42 -0
  44. package/dist/playwright/browser-issue-records.mjs +148 -0
  45. package/dist/playwright/browser-test.d.mts +21 -0
  46. package/dist/playwright/browser-test.mjs +68 -0
  47. package/dist/playwright/expect-no-broken-images.d.mts +17 -0
  48. package/dist/playwright/expect-no-broken-images.mjs +39 -0
  49. package/dist/playwright/index.d.mts +30 -0
  50. package/dist/playwright/index.mjs +22 -0
  51. package/dist/playwright/mobile-assertions.d.mts +14 -0
  52. package/dist/playwright/mobile-assertions.mjs +43 -0
  53. package/dist/playwright/navigate-to.d.mts +27 -0
  54. package/dist/playwright/navigate-to.mjs +39 -0
  55. package/dist/playwright/radix-select.d.mts +18 -0
  56. package/dist/playwright/radix-select.mjs +19 -0
  57. package/dist/playwright/random-id.d.mts +34 -0
  58. package/dist/playwright/random-id.mjs +37 -0
  59. package/dist/playwright/retry-on-connection-lost.d.mts +7 -0
  60. package/dist/playwright/retry-on-connection-lost.mjs +107 -0
  61. package/dist/playwright/scroll-to-load-more.d.mts +37 -0
  62. package/dist/playwright/scroll-to-load-more.mjs +158 -0
  63. package/dist/playwright/storybook.d.mts +2 -0
  64. package/dist/playwright/storybook.mjs +13 -0
  65. package/dist/playwright/test-fixtures.d.mts +1 -0
  66. package/dist/playwright/test-fixtures.mjs +2 -0
  67. package/dist/playwright/test-lifecycle-reporter.d.mts +11 -0
  68. package/dist/playwright/test-lifecycle-reporter.mjs +35 -0
  69. package/dist/playwright/totp.d.mts +6 -0
  70. package/dist/playwright/totp.mjs +37 -0
  71. package/dist/playwright/turnstile-stub.d.mts +8 -0
  72. package/dist/playwright/turnstile-stub.mjs +61 -0
  73. package/dist/playwright/viewport-constants.d.mts +30 -0
  74. package/dist/playwright/viewport-constants.mjs +9 -0
  75. package/dist/playwright/virtual-authenticator.d.mts +5 -0
  76. package/dist/playwright/virtual-authenticator.mjs +15 -0
  77. package/dist/playwright/wait-for-hydration.d.mts +29 -0
  78. package/dist/playwright/wait-for-hydration.mjs +81 -0
  79. package/dist/shell-parse/ansi-c-string.d.mts +12 -0
  80. package/dist/shell-parse/ansi-c-string.mjs +80 -0
  81. package/dist/shell-parse/index.d.mts +20 -0
  82. package/dist/shell-parse/index.mjs +15 -0
  83. package/dist/shell-parse/shell-command-substitution-reads.d.mts +8 -0
  84. package/dist/shell-parse/shell-command-substitution-reads.mjs +53 -0
  85. package/dist/shell-parse/shell-command-substitutions.d.mts +8 -0
  86. package/dist/shell-parse/shell-command-substitutions.mjs +52 -0
  87. package/dist/shell-parse/shell-command-wrappers.d.mts +26 -0
  88. package/dist/shell-parse/shell-command-wrappers.mjs +143 -0
  89. package/dist/shell-parse/shell-commands.d.mts +24 -0
  90. package/dist/shell-parse/shell-commands.mjs +155 -0
  91. package/dist/shell-parse/shell-heredoc-delimiter.d.mts +5 -0
  92. package/dist/shell-parse/shell-heredoc-delimiter.mjs +52 -0
  93. package/dist/shell-parse/shell-heredoc-parser.d.mts +7 -0
  94. package/dist/shell-parse/shell-heredoc-parser.mjs +49 -0
  95. package/dist/shell-parse/shell-heredoc-quote-state.d.mts +19 -0
  96. package/dist/shell-parse/shell-heredoc-quote-state.mjs +40 -0
  97. package/dist/shell-parse/shell-heredoc.d.mts +10 -0
  98. package/dist/shell-parse/shell-heredoc.mjs +90 -0
  99. package/dist/shell-parse/shell-redirections.d.mts +5 -0
  100. package/dist/shell-parse/shell-redirections.mjs +34 -0
  101. package/dist/shell-parse/shell-script-operand.d.mts +13 -0
  102. package/dist/shell-parse/shell-script-operand.mjs +103 -0
  103. package/dist/shell-parse/shell-stdin-script.d.mts +6 -0
  104. package/dist/shell-parse/shell-stdin-script.mjs +61 -0
  105. package/dist/shell-parse/shell-token-utils.d.mts +9 -0
  106. package/dist/shell-parse/shell-token-utils.mjs +33 -0
  107. package/dist/shell-parse/shell-tokenizer-comments.d.mts +1 -0
  108. package/dist/shell-parse/shell-tokenizer-comments.mjs +57 -0
  109. package/dist/shell-parse/shell-tokenizer-operators.d.mts +14 -0
  110. package/dist/shell-parse/shell-tokenizer-operators.mjs +47 -0
  111. package/dist/shell-parse/shell-tokenizer.d.mts +12 -0
  112. package/dist/shell-parse/shell-tokenizer.mjs +104 -0
  113. package/dist/story-coverage/analyze.d.mts +8 -0
  114. package/dist/story-coverage/analyze.mjs +24 -0
  115. package/dist/story-coverage/check.d.mts +11 -0
  116. package/dist/story-coverage/check.mjs +42 -0
  117. package/dist/story-coverage/components.d.mts +10 -0
  118. package/dist/story-coverage/components.mjs +40 -0
  119. package/dist/story-coverage/coverage.d.mts +10 -0
  120. package/dist/story-coverage/coverage.mjs +43 -0
  121. package/dist/story-coverage/index.d.mts +13 -0
  122. package/dist/story-coverage/index.mjs +7 -0
  123. package/dist/story-coverage/messages.d.mts +10 -0
  124. package/dist/story-coverage/messages.mjs +42 -0
  125. package/dist/story-coverage/options.d.mts +27 -0
  126. package/dist/story-coverage/options.mjs +51 -0
  127. package/dist/story-coverage/workspace.d.mts +2 -0
  128. package/dist/story-coverage/workspace.mjs +27 -0
  129. package/dist/test-helpers/cancel-runs.test-helpers.d.mts +39 -0
  130. package/dist/test-helpers/cancel-runs.test-helpers.mjs +124 -0
  131. package/dist/test-helpers/run-bounded-exit-observer.test-helpers.d.mts +12 -0
  132. package/dist/test-helpers/run-bounded-exit-observer.test-helpers.mjs +68 -0
  133. package/dist/test-helpers/run-bounded-output-fixture.test-helpers.d.mts +18 -0
  134. package/dist/test-helpers/run-bounded-output-fixture.test-helpers.mjs +162 -0
  135. package/dist/vitest-diagnostics/index.d.mts +9 -1
  136. package/dist/vitest-diagnostics/index.mjs +5 -1
  137. package/dist/vitest-diagnostics/vitest-fake-timer-guard.d.mts +6 -0
  138. package/dist/vitest-diagnostics/vitest-fake-timer-guard.mjs +34 -0
  139. package/dist/vitest-diagnostics/vitest-fork-leak-detection.d.mts +1 -0
  140. package/dist/vitest-diagnostics/vitest-fork-leak-detection.mjs +8 -0
  141. package/dist/vitest-diagnostics/vitest-fork-leak-diagnostics.d.mts +10 -1
  142. package/dist/vitest-diagnostics/vitest-fork-leak-diagnostics.mjs +43 -2
  143. package/dist/vitest-diagnostics/vitest-fork-leak-handshake-samples.d.mts +50 -0
  144. package/dist/vitest-diagnostics/vitest-fork-leak-handshake-samples.mjs +69 -0
  145. package/dist/vitest-diagnostics/vitest-fork-leak-handshake.d.mts +19 -0
  146. package/dist/vitest-diagnostics/vitest-fork-leak-handshake.mjs +136 -0
  147. package/dist/vitest-diagnostics/vitest-network-allowlist-dns.d.mts +7 -0
  148. package/dist/vitest-diagnostics/vitest-network-allowlist-dns.mjs +54 -0
  149. package/dist/vitest-diagnostics/vitest-network-allowlist-host.d.mts +8 -0
  150. package/dist/vitest-diagnostics/vitest-network-allowlist-host.mjs +48 -0
  151. package/dist/vitest-diagnostics/vitest-network-allowlist-socket.d.mts +14 -0
  152. package/dist/vitest-diagnostics/vitest-network-allowlist-socket.mjs +39 -0
  153. package/dist/vitest-diagnostics/vitest-network-allowlist.d.mts +7 -0
  154. package/dist/vitest-diagnostics/vitest-network-allowlist.mjs +72 -0
  155. package/dist/vitest-diagnostics/vitest-process-resources.d.mts +6 -0
  156. package/dist/vitest-diagnostics/vitest-process-resources.mjs +51 -0
  157. package/dist/vitest-effective-timeout/cap.d.mts +9 -0
  158. package/dist/vitest-effective-timeout/cap.mjs +28 -0
  159. package/dist/vitest-effective-timeout/check-profiles.d.mts +15 -0
  160. package/dist/vitest-effective-timeout/check-profiles.mjs +52 -0
  161. package/dist/vitest-effective-timeout/config-file.d.mts +6 -0
  162. package/dist/vitest-effective-timeout/config-file.mjs +23 -0
  163. package/dist/vitest-effective-timeout/fixtures.d.mts +2 -0
  164. package/dist/vitest-effective-timeout/fixtures.mjs +18 -0
  165. package/dist/vitest-effective-timeout/index.d.mts +7 -0
  166. package/dist/vitest-effective-timeout/index.mjs +4 -0
  167. package/dist/vitest-effective-timeout/profiles.d.mts +10 -0
  168. package/dist/vitest-effective-timeout/profiles.mjs +33 -0
  169. package/dist/vitest-effective-timeout/run-profile.d.mts +31 -0
  170. package/dist/vitest-effective-timeout/run-profile.mjs +95 -0
  171. package/docs/mcp-server.md +2 -13
  172. package/package.json +32 -2
  173. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  174. package/scripts/chromium-launch-probe.d.mts +7 -0
  175. package/scripts/chromium-launch-probe.mjs +101 -0
  176. package/scripts/run-bounded-fixtures/run-bounded-backpressure.py +186 -0
  177. package/scripts/run-bounded-fixtures/run-bounded-merged-output.py +75 -0
  178. package/scripts/run-bounded-fixtures/run-bounded-reset-socket.py +25 -0
  179. package/scripts/run-bounded.py +199 -0
  180. package/scripts/run_bounded_process.py +129 -0
  181. package/scripts/worktree/git-index-lock.sh +16 -0
  182. package/scripts/worktree/git-worktrees.sh +23 -20
  183. package/scripts/worktree/reset-worktree-run.sh +199 -0
  184. package/scripts/worktree/reset-worktree.sh +122 -0
  185. package/skills/blackboard/SKILL.md +4 -64
  186. package/skills/stacked-prs/SKILL.md +1 -1
  187. package/skills/stacked-prs/references/drain.md +2 -2
@@ -0,0 +1,34 @@
1
+ // Fake-timer-leak guard: a test that leaves vi.useFakeTimers() installed corrupts every later
2
+ // test sharing the same fork (isolate: false) or file (isolate: true). This asserts the
3
+ // invariant after every test — a source-level lint rule can't help because a correct
4
+ // beforeEach/afterEach pair looks identical to a stray call at the AST level.
5
+ //
6
+ // Kept dependency-free (no import from 'vitest' at module scope) so the check function is
7
+ // unit-testable with a fake vi-shaped object, mirroring vitest-fork-leak-detection.mts.
8
+ //
9
+ // `.ts`, not `.mts`: the root-level setupFiles chain imports this inside the
10
+ // browser project whose transform hardcodes TypeScript detection to
11
+ // `.ts`/`.tsx` and silently misparses `.mts` as plain JS.
12
+ export function formatFakeTimerLeakDiagnostics(testName) {
13
+ return [
14
+ '[vitest-fake-timer-leak]',
15
+ `test: ${testName}`,
16
+ 'vi.useFakeTimers() was still installed when this test finished.',
17
+ "Fake timers are process-global state: under pool: 'forks', isolate: false they leak into",
18
+ 'every later test file sharing this fork (not just later tests in this file); under',
19
+ 'isolate: true they still leak into later tests in this same file. Either way, real',
20
+ 'timer-driven code in a later test can hang or silently behave differently.',
21
+ 'Fix: call vi.useRealTimers() in an afterEach for this file (or wrap the test body in',
22
+ 'try/finally) so real timers are restored even when the test throws or returns early.',
23
+ ].join('\n');
24
+ }
25
+ // Restores real timers defensively before returning, so a single offending test cannot corrupt
26
+ // every test that runs after it even when this guard's own failure aborts the current file.
27
+ // Returns a diagnostic string when the invariant was violated, or null when the test left
28
+ // real timers in place (the expected, clean state).
29
+ export function checkAndRestoreFakeTimers(controller, testName) {
30
+ if (!controller.isFakeTimers())
31
+ return null;
32
+ controller.useRealTimers();
33
+ return formatFakeTimerLeakDiagnostics(testName);
34
+ }
@@ -22,5 +22,6 @@ export type ForkLeakDetectorOptions = {
22
22
  export type ForkLeakDetector = {
23
23
  record(counts: ReadonlyMap<string, number>, testFile?: string | null): ForkLeakVerdict[];
24
24
  };
25
+ export declare function getForkLeakDetector(options?: ForkLeakDetectorOptions): ForkLeakDetector;
25
26
  export declare function waitForResourceCloseCallbacks(): Promise<void>;
26
27
  export declare function createForkLeakDetector(options?: ForkLeakDetectorOptions): ForkLeakDetector;
@@ -18,6 +18,14 @@ const PERSISTENT_HANDLE_TYPES = new Set([
18
18
  export const WARMUP_CHECKPOINTS = 5;
19
19
  export const LEAK_THRESHOLD = 4;
20
20
  export const SUSTAINED_CHECKPOINTS = 5;
21
+ const FORK_LEAK_DETECTOR_KEY = Symbol.for('vitest-fork-leak-detector');
22
+ // Vitest re-evaluates a fork's setup files on every file while reusing the process.
23
+ // A module-scope detector would reset every file and never leave the warmup window.
24
+ // Only the first call's options apply; later calls return the existing detector unchanged.
25
+ export function getForkLeakDetector(options = {}) {
26
+ return (globalThis[FORK_LEAK_DETECTOR_KEY] ??=
27
+ createForkLeakDetector(options));
28
+ }
21
29
  export function waitForResourceCloseCallbacks() {
22
30
  return new Promise((resolve) => realSetTimeout(resolve, 0));
23
31
  }
@@ -1,3 +1,12 @@
1
1
  import type { ForkLeakVerdict } from './vitest-fork-leak-detection.mts';
2
- /** Formats a bounded, single-line verdict for a test failure or diagnostic log. */
2
+ import type { PoolMetrics } from './vitest-fork-leak-handshake-samples.mts';
3
+ type PoolSocketHandles = {
4
+ active: ReadonlySet<object>;
5
+ owned: ReadonlySet<object>;
6
+ };
7
+ export declare function getRegisteredPoolMetrics(): PoolMetrics | null;
8
+ export declare function getRegisteredPoolSocketHandles(): PoolSocketHandles | null;
9
+ /** One-line summary, or a multi-line report when resource counts are supplied. */
3
10
  export declare function formatForkLeakDiagnostics(verdict: ForkLeakVerdict): string;
11
+ export declare function formatForkLeakDiagnostics(verdict: ForkLeakVerdict, counts: ReadonlyMap<string, number>, poolMetrics?: PoolMetrics | null): string;
12
+ export {};
@@ -1,5 +1,32 @@
1
- /** Formats a bounded, single-line verdict for a test failure or diagnostic log. */
2
- export function formatForkLeakDiagnostics(verdict) {
1
+ import { formatResourceCounts } from "./vitest-process-resources.mjs";
2
+ const POOL_METRICS_KEY = Symbol.for('vitest-fork-leak-pool-metrics');
3
+ const POOL_SOCKETS_KEY = Symbol.for('vitest-fork-leak-pool-socket-handles');
4
+ export function getRegisteredPoolMetrics() {
5
+ const provider = globalThis[POOL_METRICS_KEY];
6
+ return provider?.() ?? null;
7
+ }
8
+ export function getRegisteredPoolSocketHandles() {
9
+ const provider = globalThis[POOL_SOCKETS_KEY];
10
+ return provider?.() ?? null;
11
+ }
12
+ export function formatForkLeakDiagnostics(verdict, counts, poolMetrics) {
13
+ if (counts === undefined)
14
+ return formatForkLeakSummary(verdict);
15
+ return [
16
+ '[vitest-fork-leak]',
17
+ `type: ${verdict.type}`,
18
+ `baseline: ${verdict.baseline}`,
19
+ `current: ${verdict.current} (+${verdict.current - verdict.baseline})`,
20
+ `candidate evidence span: ${verdict.streak}`,
21
+ `candidate growth evidence: ${verdict.growthCheckpoints} (required: ${verdict.requiredGrowthCheckpoints})`,
22
+ `confirmed by continuation in file: ${verdict.detectedInFile ?? 'unknown'}`,
23
+ `suspected growth file: ${verdict.suspectedGrowth?.testFile ?? 'unknown'}`,
24
+ `largest growth step: ${formatGrowthStep(verdict.suspectedGrowth)}`,
25
+ `tracked resource counts: ${formatResourceCounts(counts)}`,
26
+ `pool metrics: ${formatPoolMetrics(poolMetrics ?? null)}`,
27
+ ].join('\n');
28
+ }
29
+ function formatForkLeakSummary(verdict) {
3
30
  const growth = verdict.suspectedGrowth;
4
31
  const file = growth?.testFile ?? verdict.detectedInFile ?? 'unknown';
5
32
  return [
@@ -12,3 +39,17 @@ export function formatForkLeakDiagnostics(verdict) {
12
39
  `delta=${growth?.delta ?? 0}`,
13
40
  ].join(' ');
14
41
  }
42
+ function formatPoolMetrics(metrics) {
43
+ if (!metrics)
44
+ return 'unavailable (pools not initialized)';
45
+ return Object.entries(metrics)
46
+ .toSorted(([left], [right]) => left.localeCompare(right))
47
+ .map(([label, pool]) => formatPool(label, pool))
48
+ .join(' ');
49
+ }
50
+ function formatPool(label, pool) {
51
+ return `${label}(total=${pool.total},idle=${pool.idle},non-idle-or-connecting=${pool.nonIdleOrConnecting},waiting=${pool.waiting})`;
52
+ }
53
+ function formatGrowthStep(step) {
54
+ return step ? `${step.previous} -> ${step.current} (+${step.delta})` : 'unknown';
55
+ }
@@ -0,0 +1,50 @@
1
+ export type PoolConnectionMetrics = {
2
+ total: number;
3
+ idle: number;
4
+ nonIdleOrConnecting: number;
5
+ waiting: number;
6
+ };
7
+ export type PoolMetrics = Readonly<Record<string, PoolConnectionMetrics>>;
8
+ export type PoolSocketHandles = {
9
+ active: ReadonlySet<object>;
10
+ owned: ReadonlySet<object>;
11
+ };
12
+ export declare function pendingPoolSocketEpisode(options: {
13
+ initial: ForkLeakHandshakeSnapshot;
14
+ probe: ForkLeakHandshakeSnapshot;
15
+ current: ForkLeakHandshakeSnapshot;
16
+ initialPool: PoolConnectionCounts;
17
+ currentPool: PoolConnectionCounts;
18
+ ownedHandlesObserved: ReadonlySet<object>;
19
+ previousHandle: object | null;
20
+ }): {
21
+ handle: object | null;
22
+ inFlight: boolean;
23
+ };
24
+ export type ForkLeakHandshakeSnapshot = {
25
+ connectWraps: number;
26
+ tcpSockets: number;
27
+ resources: readonly string[];
28
+ tcpSocketHandles: ReadonlySet<object>;
29
+ poolMetrics: PoolMetrics | null;
30
+ };
31
+ export declare function recordForkLeakCheckpoint<T>(record: (counts: ReadonlyMap<string, number>, testFile: string) => T[], settlement: {
32
+ snapshot: ForkLeakHandshakeSnapshot;
33
+ detectorSnapshot: ForkLeakHandshakeSnapshot;
34
+ coalesced: boolean;
35
+ }, testFile: string): T[];
36
+ export type PoolConnectionCounts = {
37
+ total: number;
38
+ idle: number;
39
+ nonIdleOrConnecting: number;
40
+ waiting: number;
41
+ };
42
+ export declare function handshakeSnapshot(resources: readonly string[], tcpSocketHandles: ReadonlySet<object>, poolMetrics: PoolMetrics | null): ForkLeakHandshakeSnapshot;
43
+ export declare function poolConnectionCounts(metrics: PoolMetrics): PoolConnectionCounts;
44
+ export declare function samePoolCounts(previous: PoolConnectionCounts, current: PoolConnectionCounts): boolean;
45
+ export declare function handshakeSettled(previous: ForkLeakHandshakeSnapshot, current: ForkLeakHandshakeSnapshot): boolean;
46
+ export declare function rawDetectorCheckpoint(options: {
47
+ current: ForkLeakHandshakeSnapshot;
48
+ ownedHandlesObserved: ReadonlySet<object>;
49
+ unownedGrowthSnapshots: ReadonlyMap<object, ForkLeakHandshakeSnapshot>;
50
+ }): ForkLeakHandshakeSnapshot;
@@ -0,0 +1,69 @@
1
+ import { countResourcesByType } from "./vitest-process-resources.mjs";
2
+ const pendingEpisodeKey = Symbol.for('vitest-fork-leak-pending-pool-socket-episodes');
3
+ function pendingPoolSocketEpisodes() {
4
+ return (globalThis[pendingEpisodeKey] ??= new WeakSet());
5
+ }
6
+ function startPendingPoolSocketEpisode(growthHandles, ownedHandles) {
7
+ const candidate = growthHandles.find((handle) => !ownedHandles.has(handle) && !pendingPoolSocketEpisodes().has(handle));
8
+ if (candidate)
9
+ pendingPoolSocketEpisodes().add(candidate);
10
+ return candidate ?? null;
11
+ }
12
+ export function pendingPoolSocketEpisode(options) {
13
+ const growthHandles = [...options.current.tcpSocketHandles].filter((handle) => !options.initial.tcpSocketHandles.has(handle));
14
+ const capacity = Math.max(0, options.currentPool.total - options.initialPool.total);
15
+ const newlyOwned = growthHandles.filter((handle) => options.ownedHandlesObserved.has(handle)).length;
16
+ const initialUnowned = [...options.initial.tcpSocketHandles].filter((handle) => !options.ownedHandlesObserved.has(handle));
17
+ const initialPending = options.currentPool.nonIdleOrConnecting > 0 && initialUnowned.length > 0;
18
+ const newPending = options.currentPool.nonIdleOrConnecting > 0 && newlyOwned < capacity;
19
+ const candidates = newPending
20
+ ? growthHandles
21
+ : initialPending
22
+ ? [...options.current.tcpSocketHandles].filter((handle) => options.initial.tcpSocketHandles.has(handle))
23
+ : [];
24
+ const handle = startPendingPoolSocketEpisode(candidates, options.ownedHandlesObserved) ??
25
+ options.previousHandle;
26
+ return {
27
+ handle,
28
+ inFlight: handle !== null &&
29
+ options.current.tcpSocketHandles.has(handle) &&
30
+ !options.ownedHandlesObserved.has(handle),
31
+ };
32
+ }
33
+ export function recordForkLeakCheckpoint(record, settlement, testFile) {
34
+ const checkpoint = settlement.coalesced ? settlement.snapshot : settlement.detectorSnapshot;
35
+ return record(countResourcesByType(checkpoint.resources), testFile);
36
+ }
37
+ export function handshakeSnapshot(resources, tcpSocketHandles, poolMetrics) {
38
+ const counts = countResourcesByType(resources);
39
+ return {
40
+ connectWraps: counts.get('ConnectWrap') ?? 0,
41
+ tcpSockets: counts.get('TCPSocketWrap') ?? 0,
42
+ resources,
43
+ tcpSocketHandles,
44
+ poolMetrics,
45
+ };
46
+ }
47
+ export function poolConnectionCounts(metrics) {
48
+ const counts = { total: 0, idle: 0, nonIdleOrConnecting: 0, waiting: 0 };
49
+ for (const pool of Object.values(metrics)) {
50
+ counts.total += pool.total;
51
+ counts.idle += pool.idle;
52
+ counts.nonIdleOrConnecting += pool.nonIdleOrConnecting;
53
+ counts.waiting += pool.waiting;
54
+ }
55
+ return counts;
56
+ }
57
+ export function samePoolCounts(previous, current) {
58
+ return (previous.total === current.total &&
59
+ previous.idle === current.idle &&
60
+ previous.nonIdleOrConnecting === current.nonIdleOrConnecting &&
61
+ previous.waiting === current.waiting);
62
+ }
63
+ export function handshakeSettled(previous, current) {
64
+ return (previous.connectWraps === current.connectWraps && previous.tcpSockets === current.tcpSockets);
65
+ }
66
+ export function rawDetectorCheckpoint(options) {
67
+ const firstUnresolvedSample = [...options.unownedGrowthSnapshots].find(([handle]) => !options.ownedHandlesObserved.has(handle))?.[1];
68
+ return firstUnresolvedSample ?? options.current;
69
+ }
@@ -0,0 +1,19 @@
1
+ export { formatActiveResources, formatProcessResources, formatResourceCounts, } from './vitest-process-resources.mts';
2
+ import { type ForkLeakHandshakeSnapshot, type PoolMetrics, type PoolSocketHandles } from './vitest-fork-leak-handshake-samples.mts';
3
+ export { recordForkLeakCheckpoint, type ForkLeakHandshakeSnapshot, } from './vitest-fork-leak-handshake-samples.mts';
4
+ export declare const FORK_LEAK_HANDSHAKE_STABLE_OBSERVATIONS = 2;
5
+ export declare const FORK_LEAK_HANDSHAKE_MAX_TURNS = 100;
6
+ export type ForkLeakHandshakeSettlement = {
7
+ snapshot: ForkLeakHandshakeSnapshot;
8
+ detectorSnapshot: ForkLeakHandshakeSnapshot;
9
+ observations: readonly ForkLeakHandshakeSnapshot[];
10
+ coalesced: boolean;
11
+ };
12
+ export declare function waitForForkLeakHandshakeSettle(options: {
13
+ readResources: () => readonly string[];
14
+ readPoolMetrics: () => PoolMetrics | null;
15
+ readPoolSocketHandles: () => PoolSocketHandles | null;
16
+ waitForTurn: () => Promise<void>;
17
+ stableObservations?: number;
18
+ maxTurns?: number;
19
+ }): Promise<ForkLeakHandshakeSettlement>;
@@ -0,0 +1,136 @@
1
+ export { formatActiveResources, formatProcessResources, formatResourceCounts, } from "./vitest-process-resources.mjs";
2
+ import { handshakeSettled, handshakeSnapshot, pendingPoolSocketEpisode, poolConnectionCounts, rawDetectorCheckpoint, samePoolCounts, } from "./vitest-fork-leak-handshake-samples.mjs";
3
+ export { recordForkLeakCheckpoint, } from "./vitest-fork-leak-handshake-samples.mjs";
4
+ // Two quiet event-loop turns settle a completed pool transition. The hard cap
5
+ // bounds slow handshakes; unresolved sockets retain their sampled history.
6
+ export const FORK_LEAK_HANDSHAKE_STABLE_OBSERVATIONS = 2;
7
+ export const FORK_LEAK_HANDSHAKE_MAX_TURNS = 100;
8
+ // A finite pool ramp is coalesced only when the async resource
9
+ // identities show that every new TCP socket belongs to a registered pool.
10
+ // Unowned or unresolved growth keeps its complete sample history for error
11
+ // diagnostics, while the detector receives only one real snapshot per test.
12
+ export async function waitForForkLeakHandshakeSettle(options) {
13
+ const waitForTurn = options.waitForTurn;
14
+ const stableObservations = options.stableObservations ?? FORK_LEAK_HANDSHAKE_STABLE_OBSERVATIONS;
15
+ const maxTurns = options.maxTurns ?? FORK_LEAK_HANDSHAKE_MAX_TURNS;
16
+ const initial = handshakeSnapshot(options.readResources(), options.readPoolSocketHandles()?.active ?? new Set(), options.readPoolMetrics());
17
+ if (initial.poolMetrics === null) {
18
+ return {
19
+ snapshot: initial,
20
+ detectorSnapshot: initial,
21
+ observations: [initial],
22
+ coalesced: false,
23
+ };
24
+ }
25
+ const initialPool = poolConnectionCounts(initial.poolMetrics);
26
+ const initialHandles = options.readPoolSocketHandles();
27
+ const probeMetrics = options.readPoolMetrics();
28
+ const probeHandles = options.readPoolSocketHandles();
29
+ const probe = handshakeSnapshot(options.readResources(), probeHandles?.active ?? new Set(), probeMetrics);
30
+ if (probeMetrics === null || probeHandles === null || initialHandles === null) {
31
+ return {
32
+ snapshot: probe,
33
+ detectorSnapshot: probe,
34
+ observations: [initial, probe],
35
+ coalesced: false,
36
+ };
37
+ }
38
+ const probePool = poolConnectionCounts(probeMetrics);
39
+ const poolTransitionPending = initialPool.nonIdleOrConnecting > 0 || probePool.total > initialPool.total;
40
+ if (!poolTransitionPending) {
41
+ return { snapshot: probe, detectorSnapshot: probe, observations: [probe], coalesced: false };
42
+ }
43
+ let previous = probe;
44
+ let previousPool = probePool;
45
+ let stable = 0;
46
+ const observations = [initial, probe];
47
+ const ownedHandlesObserved = new Set(probeHandles.owned);
48
+ const unownedGrowthSnapshots = new Map();
49
+ for (const handle of probe.tcpSocketHandles) {
50
+ if (!initial.tcpSocketHandles.has(handle) && !probeHandles.owned.has(handle)) {
51
+ unownedGrowthSnapshots.set(handle, probe);
52
+ }
53
+ }
54
+ let pendingEpisodeHandle = null;
55
+ for (let turn = 0; turn < maxTurns && stable < stableObservations; turn += 1) {
56
+ await waitForTurn();
57
+ const currentHandles = options.readPoolSocketHandles();
58
+ const currentMetrics = options.readPoolMetrics();
59
+ const current = handshakeSnapshot(options.readResources(), currentHandles?.active ?? new Set(), currentMetrics);
60
+ observations.push(current);
61
+ if (currentMetrics === null || currentHandles === null) {
62
+ return {
63
+ snapshot: current,
64
+ detectorSnapshot: rawDetectorCheckpoint({
65
+ current,
66
+ ownedHandlesObserved,
67
+ unownedGrowthSnapshots,
68
+ }),
69
+ observations,
70
+ coalesced: false,
71
+ };
72
+ }
73
+ for (const handle of currentHandles.owned)
74
+ ownedHandlesObserved.add(handle);
75
+ for (const handle of current.tcpSocketHandles) {
76
+ if (!initial.tcpSocketHandles.has(handle) &&
77
+ !currentHandles.owned.has(handle) &&
78
+ !unownedGrowthSnapshots.has(handle)) {
79
+ unownedGrowthSnapshots.set(handle, current);
80
+ }
81
+ }
82
+ const currentPool = poolConnectionCounts(currentMetrics);
83
+ stable =
84
+ handshakeSettled(previous, current) && samePoolCounts(previousPool, currentPool)
85
+ ? stable + 1
86
+ : 0;
87
+ const pendingEpisode = pendingPoolSocketEpisode({
88
+ initial,
89
+ probe,
90
+ current,
91
+ initialPool,
92
+ currentPool,
93
+ ownedHandlesObserved,
94
+ previousHandle: pendingEpisodeHandle,
95
+ });
96
+ pendingEpisodeHandle = pendingEpisode.handle;
97
+ const pendingEpisodeInFlight = pendingEpisode.inFlight;
98
+ if (stable >= stableObservations && pendingEpisodeInFlight)
99
+ stable = 0;
100
+ previous = current;
101
+ previousPool = currentPool;
102
+ if (stable >= stableObservations) {
103
+ const initialTcpHandles = initial.tcpSocketHandles;
104
+ const observedGrowthHandles = new Set([...current.tcpSocketHandles].filter((handle) => !initialTcpHandles.has(handle)));
105
+ const tcpCountGrowth = current.tcpSockets - initial.tcpSockets;
106
+ const identitiesAccountForAllGrowth = observedGrowthHandles.size === tcpCountGrowth;
107
+ const unresolvedGrowthWasObserved = [...unownedGrowthSnapshots.keys()].some((handle) => !ownedHandlesObserved.has(handle));
108
+ const allGrowthIsPoolOwned = identitiesAccountForAllGrowth &&
109
+ !unresolvedGrowthWasObserved &&
110
+ [...observedGrowthHandles].every((handle) => currentHandles.owned.has(handle) || ownedHandlesObserved.has(handle));
111
+ const detectorSnapshot = rawDetectorCheckpoint({
112
+ current,
113
+ ownedHandlesObserved,
114
+ unownedGrowthSnapshots,
115
+ });
116
+ // A stable nonzero ConnectWrap may be a slow pool handshake under runner
117
+ // contention. Preserve it as raw evidence instead of treating it as done.
118
+ return {
119
+ snapshot: current,
120
+ detectorSnapshot,
121
+ observations,
122
+ coalesced: allGrowthIsPoolOwned && current.connectWraps === 0,
123
+ };
124
+ }
125
+ }
126
+ return {
127
+ snapshot: previous,
128
+ detectorSnapshot: rawDetectorCheckpoint({
129
+ current: previous,
130
+ ownedHandlesObserved,
131
+ unownedGrowthSnapshots,
132
+ }),
133
+ observations,
134
+ coalesced: false,
135
+ };
136
+ }
@@ -0,0 +1,7 @@
1
+ export type DnsFn = (this: unknown, ...args: unknown[]) => unknown;
2
+ export type DnsAllowlistHooks = {
3
+ isAllowedHost: (host: string) => boolean;
4
+ blockDns: (host: string) => Error;
5
+ rememberAddresses: (value: unknown) => void;
6
+ };
7
+ export declare function patchDnsSurface(target: object | undefined, promises: boolean, hooks: DnsAllowlistHooks): void;
@@ -0,0 +1,54 @@
1
+ function isDnsQuery(name) {
2
+ return /^(lookup|lookupService|reverse|resolve)/.test(name);
3
+ }
4
+ function call(fn, ...args) {
5
+ ;
6
+ fn(...args);
7
+ }
8
+ function wrapDns(original, promises, hooks) {
9
+ return function wrapped(...args) {
10
+ const host = typeof args[0] === 'string' ? args[0] : null;
11
+ const callback = args.at(-1);
12
+ if (host !== null && !hooks.isAllowedHost(host)) {
13
+ const error = hooks.blockDns(host);
14
+ if (!promises && typeof callback === 'function') {
15
+ queueMicrotask(() => call(callback, error));
16
+ return undefined;
17
+ }
18
+ if (promises)
19
+ return Promise.reject(error);
20
+ throw error;
21
+ }
22
+ if (!promises && typeof callback === 'function') {
23
+ const next = args.slice();
24
+ next[next.length - 1] = (err, value, ...rest) => {
25
+ if (!err)
26
+ hooks.rememberAddresses(value);
27
+ call(callback, err, value, ...rest);
28
+ };
29
+ return Reflect.apply(original, this, next);
30
+ }
31
+ const result = Reflect.apply(original, this, args);
32
+ if (!promises || result === null || typeof result !== 'object' || !('then' in result))
33
+ return result;
34
+ return result.then((value) => {
35
+ hooks.rememberAddresses(value);
36
+ return value;
37
+ });
38
+ };
39
+ }
40
+ export function patchDnsSurface(target, promises, hooks) {
41
+ if (!target)
42
+ return;
43
+ for (const key of Object.getOwnPropertyNames(target)) {
44
+ if (!isDnsQuery(key))
45
+ continue;
46
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
47
+ if (!descriptor || typeof descriptor.value !== 'function')
48
+ continue;
49
+ Object.defineProperty(target, key, {
50
+ ...descriptor,
51
+ value: wrapDns(descriptor.value, promises, hooks),
52
+ });
53
+ }
54
+ }
@@ -0,0 +1,8 @@
1
+ export declare function normalizeHost(host: string): string;
2
+ export type HostAllowlist = {
3
+ isExempt: () => boolean;
4
+ allowedHosts: ReadonlySet<string>;
5
+ allowedIps: ReadonlySet<string>;
6
+ };
7
+ export declare function isAllowedHost(host: string, current: HostAllowlist): boolean;
8
+ export declare function rememberAddresses(value: unknown, ips: Set<string>): void;
@@ -0,0 +1,48 @@
1
+ import { isIP } from 'node:net';
2
+ export function normalizeHost(host) {
3
+ let value = host.trim().toLowerCase();
4
+ if (value.startsWith('[') && value.endsWith(']'))
5
+ value = value.slice(1, -1);
6
+ if (value.endsWith('.'))
7
+ value = value.slice(0, -1);
8
+ return value;
9
+ }
10
+ function isLoopbackHost(host) {
11
+ if (host === 'localhost' || host.endsWith('.localhost'))
12
+ return true;
13
+ if (host === '::' || host === '::1' || host === '0:0:0:0:0:0:0:1' || host === '0.0.0.0')
14
+ return true;
15
+ if (host.startsWith('::ffff:'))
16
+ return isLoopbackHost(host.slice('::ffff:'.length));
17
+ const parts = host.split('.');
18
+ if (parts.length !== 4 || parts.some((part) => !/^\d{1,3}$/.test(part)))
19
+ return false;
20
+ const octets = parts.map(Number);
21
+ return octets[0] === 127 && octets.every((part) => part <= 255);
22
+ }
23
+ export function isAllowedHost(host, current) {
24
+ if (current.isExempt())
25
+ return true;
26
+ const normalized = normalizeHost(host);
27
+ return (current.allowedHosts.has(normalized) ||
28
+ isLoopbackHost(normalized) ||
29
+ current.allowedIps.has(normalized));
30
+ }
31
+ export function rememberAddresses(value, ips) {
32
+ const visit = (item) => {
33
+ if (typeof item === 'string') {
34
+ if (isIP(item) !== 0)
35
+ ips.add(normalizeHost(item));
36
+ return;
37
+ }
38
+ if (Array.isArray(item)) {
39
+ for (const entry of item)
40
+ visit(entry);
41
+ return;
42
+ }
43
+ if (typeof item === 'object' && item !== null && 'address' in item) {
44
+ visit(item.address);
45
+ }
46
+ };
47
+ visit(value);
48
+ }
@@ -0,0 +1,14 @@
1
+ import type { DnsFn } from './vitest-network-allowlist-dns.mts';
2
+ export type NetModule = {
3
+ isIP: (host: string) => number;
4
+ Socket: {
5
+ prototype: {
6
+ connect: DnsFn;
7
+ };
8
+ };
9
+ };
10
+ export type SocketAllowlistHooks = {
11
+ isAllowedHost: (host: string) => boolean;
12
+ blockConnection: (host: string) => Error;
13
+ };
14
+ export declare function patchSocketConnect(net: NetModule, hooks: SocketAllowlistHooks): void;
@@ -0,0 +1,39 @@
1
+ import { normalizeHost } from "./vitest-network-allowlist-host.mjs";
2
+ function isRecord(value) {
3
+ return typeof value === 'object' && value !== null;
4
+ }
5
+ function connectHost(args) {
6
+ const list = Array.isArray(args[0]) ? args[0] : args;
7
+ const first = list[0];
8
+ if (typeof first === 'number') {
9
+ return { host: typeof list[1] === 'string' ? list[1] : 'localhost', options: null };
10
+ }
11
+ if (!isRecord(first))
12
+ return { host: null, options: null };
13
+ const rawHost = first.host ?? first.hostname;
14
+ if (typeof rawHost === 'string' && rawHost.length > 0)
15
+ return { host: rawHost, options: first };
16
+ if (typeof first.path === 'string')
17
+ return { host: null, options: null };
18
+ if (first.port != null)
19
+ return { host: 'localhost', options: first };
20
+ return { host: null, options: null };
21
+ }
22
+ export function patchSocketConnect(net, hooks) {
23
+ const original = net.Socket.prototype.connect;
24
+ net.Socket.prototype.connect = function connect(...args) {
25
+ const target = connectHost(args);
26
+ if (target.host === null || hooks.isAllowedHost(target.host))
27
+ return Reflect.apply(original, this, args);
28
+ const error = hooks.blockConnection(target.host);
29
+ // IP literals skip lookup, so reject them here. Hostnames still call connect so TLS can start.
30
+ if (!target.options || net.isIP(normalizeHost(target.host)) !== 0)
31
+ throw error;
32
+ target.options.lookup = (_hostname, second, third) => {
33
+ const callback = typeof third === 'function' ? third : second;
34
+ if (typeof callback === 'function')
35
+ callback(error);
36
+ };
37
+ return Reflect.apply(original, this, args);
38
+ };
39
+ }
@@ -0,0 +1,7 @@
1
+ export type TestNetworkAllowlistOptions = {
2
+ allowedHosts?: readonly string[];
3
+ isExempt?: () => boolean;
4
+ stateKey?: string;
5
+ };
6
+ export declare function installTestNetworkAllowlist(options?: TestNetworkAllowlistOptions): void;
7
+ export declare function consumeTestNetworkAllowlistViolation(stateKey?: string): string | null;
@@ -0,0 +1,72 @@
1
+ import { patchDnsSurface } from "./vitest-network-allowlist-dns.mjs";
2
+ import { isAllowedHost, normalizeHost, rememberAddresses, } from "./vitest-network-allowlist-host.mjs";
3
+ import { patchSocketConnect } from "./vitest-network-allowlist-socket.mjs";
4
+ const DEFAULT_HOSTS = ['example.com', 'example.net', 'example.org'];
5
+ const DEFAULT_STATE_KEY = 'test.networkAllowlist';
6
+ function defaultExempt() {
7
+ return false;
8
+ }
9
+ function state(key = DEFAULT_STATE_KEY) {
10
+ return (globalThis[Symbol.for(key)] ??=
11
+ {
12
+ installed: false,
13
+ violations: [],
14
+ allowedIps: new Set(),
15
+ allowedHosts: new Set(DEFAULT_HOSTS),
16
+ isExempt: defaultExempt,
17
+ });
18
+ }
19
+ class TestNetworkAllowlistError extends Error {
20
+ code;
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = 'TestNetworkAllowlistError';
24
+ this.code = 'TEST_NETWORK_ALLOWLIST';
25
+ }
26
+ }
27
+ function block(key, kind, host) {
28
+ const action = kind === 'dns' ? 'a DNS lookup for' : 'a connection to';
29
+ const current = state(key);
30
+ const allowed = [...current.allowedHosts].toSorted().join(', ');
31
+ const message = `Test network allowlist blocked ${action} "${normalizeHost(host)}". Tests may only reach ${allowed}, and loopback.`;
32
+ current.violations.push(message);
33
+ return new TestNetworkAllowlistError(message);
34
+ }
35
+ export function installTestNetworkAllowlist(options = {}) {
36
+ const key = options.stateKey ?? DEFAULT_STATE_KEY;
37
+ const current = state(key);
38
+ if (current.installed)
39
+ return;
40
+ current.installed = true;
41
+ current.allowedHosts = new Set(options.allowedHosts ?? DEFAULT_HOSTS);
42
+ current.isExempt = options.isExempt ?? defaultExempt;
43
+ if (typeof process.getBuiltinModule !== 'function')
44
+ return;
45
+ const dns = process.getBuiltinModule('node:dns');
46
+ const net = process.getBuiltinModule('node:net');
47
+ if (typeof net.Socket !== 'function')
48
+ return;
49
+ const hooks = {
50
+ isAllowedHost: (host) => isAllowedHost(host, state(key)),
51
+ blockDns: (host) => block(key, 'dns', host),
52
+ rememberAddresses: (value) => rememberAddresses(value, state(key).allowedIps),
53
+ };
54
+ patchDnsSurface(dns, false, hooks);
55
+ patchDnsSurface(dns.promises, true, hooks);
56
+ patchDnsSurface(dns.Resolver?.prototype, false, hooks);
57
+ patchDnsSurface(dns.promises?.Resolver?.prototype, true, hooks);
58
+ patchSocketConnect(net, {
59
+ isAllowedHost: hooks.isAllowedHost,
60
+ blockConnection: (host) => block(key, 'connection', host),
61
+ });
62
+ const nodeModule = process.getBuiltinModule('node:module');
63
+ nodeModule.syncBuiltinESMExports?.();
64
+ }
65
+ export function consumeTestNetworkAllowlistViolation(stateKey = DEFAULT_STATE_KEY) {
66
+ const violations = state(stateKey).violations;
67
+ if (violations.length === 0)
68
+ return null;
69
+ const message = violations.join('\n');
70
+ violations.length = 0;
71
+ return message;
72
+ }