@ultimat3/testing 30.9.0 → 31.0.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 (148) hide show
  1. package/CLAUDE.md +46 -55
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +20 -2
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-line.ts +98 -0
  55. package/src/exercise-report.ts +30 -51
  56. package/src/exercise.ts +12 -6
  57. package/src/factories.ts +192 -179
  58. package/src/factory-api.ts +131 -0
  59. package/src/factory-associations.ts +67 -0
  60. package/src/factory-errors.ts +38 -0
  61. package/src/factory-lint.ts +92 -0
  62. package/src/factory-persist.ts +74 -16
  63. package/src/factory-pipeline.ts +191 -0
  64. package/src/factory-registry.ts +2 -1
  65. package/src/factory-types.ts +131 -0
  66. package/src/failure-store-conformance.ts +137 -0
  67. package/src/fixture-jobs.ts +27 -11
  68. package/src/fixture-mail.ts +7 -7
  69. package/src/fixture-seed.ts +111 -0
  70. package/src/fixture-statements.ts +68 -52
  71. package/src/framework-fixtures.ts +1 -1
  72. package/src/idempotency-store-conformance.ts +186 -0
  73. package/src/idempotency-store-replay-conformance.ts +140 -0
  74. package/src/idempotency-store-tx-conformance.ts +132 -0
  75. package/src/idempotency-store-world-conformance.ts +82 -0
  76. package/src/identity-provider-conformance.ts +144 -0
  77. package/src/image-transform-conformance.ts +89 -0
  78. package/src/index.ts +68 -157
  79. package/src/isr-store-conformance.ts +113 -0
  80. package/src/job-sim-effects.ts +19 -31
  81. package/src/job-sim-world.ts +6 -15
  82. package/src/lease-store-conformance.ts +195 -0
  83. package/src/mail-driver-conformance.ts +108 -0
  84. package/src/matcher-doubles.ts +104 -0
  85. package/src/matcher-stub.ts +78 -0
  86. package/src/matcher-surface.ts +21 -0
  87. package/src/matchers.ts +19 -1
  88. package/src/mcp-confirmation-store-conformance.ts +262 -0
  89. package/src/meter-store-conformance.ts +135 -0
  90. package/src/notify-digest-conformance.ts +133 -0
  91. package/src/notify-inbox-conformance.ts +130 -0
  92. package/src/notify-ledger-conformance.ts +134 -0
  93. package/src/notify-preference-conformance.ts +49 -0
  94. package/src/notify-stores-conformance.ts +73 -0
  95. package/src/outbox-store-conformance-claims.ts +112 -0
  96. package/src/outbox-store-conformance-subject.ts +65 -0
  97. package/src/outbox-store-conformance.ts +71 -0
  98. package/src/per-test-reset.ts +55 -20
  99. package/src/preload.ts +4 -2
  100. package/src/purge-conformance.ts +79 -0
  101. package/src/push-device-conformance.ts +124 -0
  102. package/src/push-subscription-conformance.ts +123 -0
  103. package/src/quiet-logs.ts +4 -4
  104. package/src/rate-limit-store-conformance.ts +178 -0
  105. package/src/registry-leak-error.ts +8 -1
  106. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  107. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  108. package/src/scrape-driver-conformance-site.ts +84 -0
  109. package/src/scrape-driver-conformance.ts +34 -0
  110. package/src/search-index-conformance-list.ts +76 -0
  111. package/src/search-index-conformance-support.ts +69 -0
  112. package/src/search-index-conformance-versions.ts +66 -0
  113. package/src/search-index-conformance.ts +126 -0
  114. package/src/secret-source-conformance.ts +91 -0
  115. package/src/seed-factories.ts +57 -0
  116. package/src/seed-writer.ts +8 -19
  117. package/src/semantic-cache-factory-conformance.ts +86 -0
  118. package/src/sms-transport-conformance.ts +102 -0
  119. package/src/step-store-conformance.ts +171 -0
  120. package/src/storage-conformance-read-checks.ts +132 -0
  121. package/src/storage-conformance-shape.ts +121 -0
  122. package/src/storage-conformance-stream-checks.ts +226 -0
  123. package/src/storage-conformance.ts +34 -0
  124. package/src/stub-action.ts +24 -0
  125. package/src/stub-errors.ts +86 -0
  126. package/src/stub-job.ts +30 -0
  127. package/src/stub-query.ts +25 -0
  128. package/src/stub-script.ts +76 -0
  129. package/src/stub-stack.ts +29 -0
  130. package/src/stub.ts +73 -0
  131. package/src/swap-adapter.ts +135 -0
  132. package/src/test-scope.ts +96 -0
  133. package/src/test-types.ts +1 -1
  134. package/src/totp-replay-guard-conformance.ts +76 -0
  135. package/src/transport-conformance.ts +179 -0
  136. package/src/upload-scanner-conformance.ts +112 -0
  137. package/src/vector-store-conformance-checks.ts +174 -0
  138. package/src/vector-store-conformance.ts +21 -0
  139. package/src/cdp-connection.ts +0 -291
  140. package/src/cdp-errors.ts +0 -179
  141. package/src/cdp-launch-attempt.ts +0 -224
  142. package/src/cdp-launch-candidates.ts +0 -62
  143. package/src/cdp-launch-profile.ts +0 -106
  144. package/src/cdp-launch-reap.ts +0 -68
  145. package/src/cdp-launch-wire.ts +0 -171
  146. package/src/cdp-launch.ts +0 -175
  147. package/src/cdp-pipe.ts +0 -77
  148. package/src/cdp-wire-watch.ts +0 -113
package/src/cdp-errors.ts DELETED
@@ -1,179 +0,0 @@
1
- // One constructor per way the raw-CDP e2e browser refuses. Every cause quotes a value that came
2
- // out of a BROWSER or off a spawned process's stderr, so every one is rendered rather than
3
- // interpolated — the rule `e2e-errors.ts` already states.
4
-
5
- import { isFixShellSafe, renderCauseValue, UltimateError } from '@ultimat3/core';
6
- // Bare: the titles these constructors' codes render with are registered there.
7
- import './e2e-error-codes';
8
-
9
- /**
10
- * No browser to drive. This is the one an author meets first, so its fix names the two ways out:
11
- * point the driver at a binary, or accept that this machine cannot run the check.
12
- */
13
- export class CdpBrowserMissingError extends UltimateError {
14
- constructor(input: { readonly tried: readonly string[] }) {
15
- super({
16
- code: 'X_CDP_BROWSER_MISSING',
17
- cause: `no Chrome or Chromium executable was found — tried ${renderCauseValue(input.tried)}`,
18
- fix: 'set CHROME_PATH to a Chrome or Chromium binary (GitHub-hosted ubuntu runners ship one at /usr/bin/google-chrome), or skip the browser-backed e2e suite by leaving it unset',
19
- });
20
- }
21
- }
22
-
23
- /** One start of the browser that ended without an answer — what `cdp-launch-attempt.ts` reports. */
24
- export interface CdpLaunchAttempt {
25
- /**
26
- * `deadline`: alive and silent for `waitedMs`. `closed`: its wire ended, or its dial was
27
- * refused, before any answer. `spawn`: the binary could not be started at all — it never ran.
28
- */
29
- readonly why: 'deadline' | 'closed' | 'spawn';
30
- readonly waitedMs: number;
31
- /** The code it exited with on its own, or `null` when the launcher had to kill it. */
32
- readonly exitCode: number | null;
33
- /** The last lines it wrote to stderr; empty when it wrote none. */
34
- readonly stderr: string;
35
- /**
36
- * What the LAUNCHER saw end the attempt, rendered: the refused dial and its endpoint, the call
37
- * that timed out, the spawn's own error. Absent on a record that predates it.
38
- */
39
- readonly detail?: string | undefined;
40
- }
41
-
42
- const HAND_FLAGS =
43
- '--headless=new --no-sandbox --disable-dev-shm-usage --disable-gpu --remote-debugging-port=0 about:blank';
44
-
45
- const endedText = (attempt: CdpLaunchAttempt): string => {
46
- const after = `after ${String(attempt.waitedMs)}ms`;
47
- if (attempt.why === 'spawn') return 'could not be started';
48
- if (attempt.why === 'deadline')
49
- return `no answer inside ${String(attempt.waitedMs)}ms, so it was killed`;
50
- return attempt.exitCode === null
51
- ? `its DevTools connection ended ${after} without an answer, and it was killed`
52
- : `exited with code ${String(attempt.exitCode)} ${after} without answering`;
53
- };
54
-
55
- const attemptText = (attempt: CdpLaunchAttempt, index: number): string => {
56
- const saw =
57
- attempt.detail === undefined || attempt.detail === ''
58
- ? ''
59
- : `: ${renderCauseValue(attempt.detail)}`;
60
- const said = attempt.stderr === '' ? 'it printed nothing' : renderCauseValue(attempt.stderr);
61
- return `launch ${String(index + 1)}: ${endedText(attempt)}${saw}; stderr: ${said}`;
62
- };
63
-
64
- /**
65
- * The binary ran and never answered a DevTools call — a crash, a bad flag, a sandbox refusal, or a
66
- * machine too loaded to start it inside the launch deadline. Every attempt is in the cause with its
67
- * own stderr, because Chrome's start-up noise reads the same in a healthy browser and a dead one:
68
- * what tells them apart is whether it EXITED or was still starting when the deadline passed.
69
- */
70
- export class CdpLaunchFailedError extends UltimateError {
71
- constructor(input: {
72
- readonly executable: string;
73
- readonly attempts: readonly CdpLaunchAttempt[];
74
- }) {
75
- // Run by hand, a healthy Chrome prints `DevTools listening on ws://…` and a broken one prints
76
- // why. A path that is not shell-inert is the operator's own CHROME_PATH — every candidate is.
77
- const binary = isFixShellSafe(input.executable) ? input.executable : '"$CHROME_PATH"';
78
- super({
79
- code: 'X_CDP_LAUNCH_FAILED',
80
- cause: `${renderCauseValue(input.executable)} did not announce a DevTools endpoint: it answered no DevTools call in ${String(input.attempts.length)} ${input.attempts.length === 1 ? 'launch' : 'launches, each on its own fresh profile'} — ${input.attempts.map(attemptText).join(' · ')}`,
81
- fix: `${binary} ${HAND_FLAGS}`,
82
- meta: { executable: input.executable, attempts: input.attempts },
83
- });
84
- }
85
- }
86
-
87
- /** A CDP call answered with an error frame, or the connection died under it. */
88
- export class CdpCallFailedError extends UltimateError {
89
- constructor(input: { readonly method: string; readonly detail: string }) {
90
- super({
91
- code: 'X_CDP_CALL_FAILED',
92
- cause: `the browser refused ${renderCauseValue(input.method)}: ${renderCauseValue(input.detail)}`,
93
- fix: 'print what the page had: await page.evaluate(() => document.body.innerHTML) — a call that refuses the same way means the browser itself is gone, so read the launch above it',
94
- });
95
- }
96
- }
97
-
98
- /** How a call's target went away: its session detached, its target was destroyed, or it crashed. */
99
- export type CdpTargetGone = 'detached' | 'destroyed' | 'crashed';
100
-
101
- /** What the wire did between a call being sent and its deadline (`cdp-wire-watch.ts`). */
102
- export interface CdpTimeoutObservation {
103
- /** The session the call was sent on; `null` for a browser-level call. */
104
- readonly sessionId: string | null;
105
- /** Frames that arrived and parsed after the call was sent — replies to other calls, and events. */
106
- readonly framesArrived: number;
107
- /** The last of those, oldest first, bounded: `reply <id>`, or `<method> @<session>`. */
108
- readonly lastFrames: readonly string[];
109
- /** Frames that arrived after the call and could not be parsed. One of them may be its reply. */
110
- readonly framesDropped: number;
111
- readonly transportOpen: boolean;
112
- /** `detached`, `destroyed` or `crashed` when the call's target went away; `null` while it is there. */
113
- readonly targetGone: CdpTargetGone | null;
114
- /** Main-frame navigations on the call's session since it was sent. */
115
- readonly navigations: number;
116
- }
117
-
118
- /** The one-word verdict a reader — or a script over `--json` — branches on. */
119
- export type CdpTimeoutReading = 'target-gone' | 'lost-in-transport' | 'no-answer';
120
-
121
- export const readTimeout = (seen: CdpTimeoutObservation): CdpTimeoutReading =>
122
- seen.targetGone !== null
123
- ? 'target-gone'
124
- : seen.framesDropped > 0
125
- ? 'lost-in-transport'
126
- : 'no-answer';
127
-
128
- const READING: Record<CdpTimeoutReading, (seen: CdpTimeoutObservation) => string> = {
129
- 'target-gone': (seen) =>
130
- `its target is gone (${String(seen.targetGone)}), so nothing was left to answer`,
131
- 'lost-in-transport': (seen) =>
132
- `${String(seen.framesDropped)} frame(s) arrived unparseable after it was sent and were dropped, so its reply may have been lost in transport (${String(seen.framesArrived)} other frame(s) arrived intact)`,
133
- 'no-answer': (seen) => {
134
- if (seen.framesArrived === 0) {
135
- return `nothing at all arrived after the call was sent, on a transport that is ${seen.transportOpen ? 'still open' : 'closed'} — the whole browser went silent`;
136
- }
137
- const moved =
138
- seen.navigations === 0
139
- ? ''
140
- : `; the page navigated ${String(seen.navigations)} time(s) since the call`;
141
- return `the target did not answer: ${String(seen.framesArrived)} other frame(s) arrived intact after the call, the last ${renderCauseValue(seen.lastFrames)}${moved}`;
142
- },
143
- };
144
-
145
- /**
146
- * A call that never answered. Its own code rather than `X_TIMEOUT`, because the actionable half is
147
- * WHICH call: a hung `Page.navigate` is an app that never finishes responding, and a hung
148
- * `Runtime.evaluate` is an expression that never settles.
149
- *
150
- * `observed` is what the connection saw meanwhile, and it is what tells three failures apart that
151
- * all read "did not answer": the target went away, the reply was dropped on the wire, or the target
152
- * was there and silent. A deadline the connection did not keep (`waitFor`, the handshake) has none.
153
- */
154
- export class CdpTimeoutError extends UltimateError {
155
- constructor(input: {
156
- readonly method: string;
157
- readonly timeoutMs: number;
158
- readonly observed?: CdpTimeoutObservation | undefined;
159
- }) {
160
- const { observed } = input;
161
- const base = `${renderCauseValue(input.method)} did not answer inside ${String(input.timeoutMs)}ms`;
162
- const reading = observed === undefined ? undefined : readTimeout(observed);
163
- super({
164
- code: 'X_CDP_TIMEOUT',
165
- cause:
166
- observed === undefined || reading === undefined
167
- ? base
168
- : `${base} — ${READING[reading](observed)}`,
169
- fix:
170
- reading === undefined || reading === 'no-answer'
171
- ? 'raise timeoutMs on installE2eDriver({ timeoutMs }), or find the request the page is still waiting on — a navigation that never settles is an app that never finishes its response'
172
- : // `--json`: the rerun's `meta.reading` and `meta.framesDropped` are only printed there.
173
- 'x test e2e --json',
174
- ...(observed === undefined
175
- ? {}
176
- : { meta: { method: input.method, timeoutMs: input.timeoutMs, reading, ...observed } }),
177
- });
178
- }
179
- }
@@ -1,224 +0,0 @@
1
- // One responsibility: ONE start of a Chrome process — spawn it on a throwaway profile, wait for its
2
- // first DevTools answer, and on no answer reap it (killed, awaited, profile removed) and say why.
3
- // Which binary, which flags and how many starts is `cdp-launch.ts`.
4
-
5
- import { renderThrowable } from '@ultimat3/core';
6
- import type { CdpConnection } from './cdp-connection';
7
- import type { CdpLaunchAttempt } from './cdp-errors';
8
- import { CdpTimeoutError } from './cdp-errors';
9
- import { throwawayProfile } from './cdp-launch-profile';
10
- import { CLOSE_GRACE_MS, killTree } from './cdp-launch-reap';
11
- import type { CdpWire } from './cdp-launch-wire';
12
- import { pipeConnection, portConnection, wireStdio } from './cdp-launch-wire';
13
-
14
- export { CLOSE_GRACE_MS } from './cdp-launch-reap';
15
-
16
- /**
17
- * The longest `LaunchedBrowser.close()` is DESIGNED to take: SIGTERM's grace, SIGKILL's, the group
18
- * reap, then the profile's removal — four `CLOSE_GRACE_MS`, each step bounded by its own. A hook
19
- * that closes a browser and gives it less is killed by Bun mid-close, and when that hook is the
20
- * run's last the process exits with the profile half-removed: the `Default/Cache` tree the leaked
21
- * `x-e2e-chrome-*` directories held.
22
- */
23
- export const LAUNCHED_CLOSE_MS = 4 * CLOSE_GRACE_MS;
24
-
25
- export interface LaunchedBrowser {
26
- /** The browser's own CDP connection, over its debugging pipe or port. Already answering. */
27
- readonly connection: CdpConnection;
28
- /**
29
- * THE close, idempotent, and awaited by every caller: the connection closed, SIGTERM, SIGKILL
30
- * after `CLOSE_GRACE_MS`, then the browser's whole process group killed and, only then, the
31
- * profile removed — bounded at `LAUNCHED_CLOSE_MS`. On Windows, which has no SIGTERM to grant grace to, the process TREE
32
- * is killed outright (`killTree`) and awaited. A promise because a Chrome still shutting down competes with the next
33
- * launch on a 4-CPU runner, and its children re-create a profile removed before they are gone.
34
- */
35
- close(): Promise<void>;
36
- }
37
-
38
- export interface LaunchAttemptOptions {
39
- readonly executable: string;
40
- /** What the process is started with, given the profile directory this attempt made for it. */
41
- readonly flags: (profileDir: string) => readonly string[];
42
- /** Which wire the flags opened — `cdp-launch-wire.ts`. */
43
- readonly wire: CdpWire;
44
- /** Whose process rules the reap follows. Defaults to this process's platform. */
45
- readonly platform?: string | undefined;
46
- /** Every call's deadline AFTER the first. */
47
- readonly timeoutMs: number;
48
- /** The first call's deadline: how long a cold start may take. */
49
- readonly launchTimeoutMs: number;
50
- }
51
-
52
- export type LaunchAttemptResult =
53
- | { readonly ok: true; readonly browser: LaunchedBrowser }
54
- /** `reaped: false` is a process that outlived SIGKILL's grace — never start another beside it. */
55
- | { readonly ok: false; readonly failure: CdpLaunchAttempt; readonly reaped: boolean };
56
-
57
- const STDERR_TAIL_CHARS = 4_000;
58
- /** How much of the tail one attempt hands a cause: the last lines, each cut to a readable width. */
59
- const TAIL_LINES = 3;
60
- const TAIL_LINE_CHARS = 160;
61
-
62
- /**
63
- * Read stderr to its end for the life of the process, keeping only a bounded tail. A pipe nobody
64
- * reads fills, and Chrome's next stderr write then blocks the thread making it — a browser that
65
- * stops answering mid-run for a reason no log shows. The tail is the launch-failure diagnostics:
66
- * a missing library, a sandbox refusal and a bad flag are all named there and nowhere else.
67
- */
68
- function stderrTail(stream: ReadableStream<Uint8Array>): {
69
- readonly lastLines: () => string;
70
- /** Settles once the stream has ended — every byte the process wrote has been read. */
71
- readonly drained: Promise<void>;
72
- } {
73
- let text = '';
74
- const drained = (async () => {
75
- const decoder = new TextDecoder();
76
- for await (const chunk of stream) {
77
- text = (text + decoder.decode(chunk, { stream: true })).slice(-STDERR_TAIL_CHARS);
78
- }
79
- })().catch(() => undefined);
80
- const lastLines = (): string =>
81
- text
82
- .trim()
83
- .split('\n')
84
- .slice(-TAIL_LINES)
85
- .map((line) => line.slice(0, TAIL_LINE_CHARS))
86
- .join(' | ');
87
- return { lastLines, drained };
88
- }
89
-
90
- /**
91
- * How long a browser that CLOSED ITS PIPE gets to finish dying, and any browser's stderr to finish
92
- * draining, before the tail is read. The pipe ending and the stderr reader reaching the last line
93
- * are two unordered events; read at the first, the reason a browser died was reported as "printed
94
- * nothing". Bounded, because a WEDGED browser neither exits nor closes stderr.
95
- */
96
- const FAILURE_DRAIN_MS = 1_000;
97
-
98
- /**
99
- * The longest a FAILED attempt spends after its deadline before the next can start: the drain a
100
- * browser that hung up gets, the bounded close (`LAUNCHED_CLOSE_MS`), then the stderr drain. A
101
- * caller's hook deadline adds this per attempt.
102
- */
103
- export const LAUNCH_REAP_MS = FAILURE_DRAIN_MS + LAUNCHED_CLOSE_MS + FAILURE_DRAIN_MS;
104
-
105
- const within = (ms: number, work: Promise<unknown>): Promise<unknown> =>
106
- Promise.race([work, Bun.sleep(ms)]);
107
-
108
- /**
109
- * Start the browser once and answer when it has answered one CDP call. With a pipe there is no
110
- * "DevTools listening" line to wait for — the first reply IS the readiness signal.
111
- */
112
- export async function launchAttempt(options: LaunchAttemptOptions): Promise<LaunchAttemptResult> {
113
- const platform = options.platform ?? process.platform;
114
- const profile = throwawayProfile();
115
- const profileDir = profile.path;
116
- const began = performance.now();
117
- let child: ReturnType<typeof spawnBrowser>;
118
- try {
119
- child = spawnBrowser(options, profileDir, platform);
120
- } catch (error) {
121
- // A binary that cannot be started at all — not there, not executable, not an executable FORMAT
122
- // this OS runs (a `#!` script on Windows). Bun throws from `spawn`, synchronously, and that
123
- // throw escaped as a bare ENOENT where every other way a launch fails is X_CDP_LAUNCH_FAILED.
124
- await profile.remove(undefined, CLOSE_GRACE_MS);
125
- return {
126
- ok: false,
127
- failure: {
128
- why: 'spawn',
129
- waitedMs: 0,
130
- exitCode: null,
131
- stderr: '',
132
- detail: renderThrowable(error),
133
- },
134
- reaped: true,
135
- };
136
- }
137
- const tail = stderrTail(child.stderr as ReadableStream<Uint8Array>);
138
- let connection: CdpConnection | undefined =
139
- options.wire === 'pipe' ? pipeConnection(child.stdio, options.timeoutMs) : undefined;
140
- let exiting: Promise<void> | undefined;
141
- const close = (): Promise<void> => {
142
- exiting ??= (async () => {
143
- // Read while the browser still runs: a clean exit unlinks it, a killed one never does.
144
- const singleton = profile.singletonDir();
145
- connection?.close();
146
- if (platform === 'win32') {
147
- // No SIGTERM to grant grace to: a kill on Windows is TerminateProcess, and taking the
148
- // browser alone would orphan the children that hold the profile's files open.
149
- await killTree(child.pid, platform);
150
- await within(CLOSE_GRACE_MS, child.exited);
151
- } else {
152
- child.kill();
153
- const exited =
154
- (await within(
155
- CLOSE_GRACE_MS,
156
- child.exited.then(() => true),
157
- )) === true;
158
- if (!exited) {
159
- child.kill('SIGKILL');
160
- await within(CLOSE_GRACE_MS, child.exited);
161
- }
162
- await killTree(child.pid, platform);
163
- }
164
- // Only now, with the tree gone: removed under a live browser, the profile is re-created by
165
- // its shutdown — the network process flushes its cache, the browser writes its prefs — and
166
- // a close cut short there leaves exactly that tree. Measured on Chrome 150, 30 launches
167
- // each: left behind 6 and 12 times without the group reap, 0 with.
168
- await profile.remove(singleton, CLOSE_GRACE_MS);
169
- })();
170
- return exiting;
171
- };
172
- try {
173
- // The pipe needs no wait to exist; the port is not known until the browser writes it down, and
174
- // finding it spends the same launch deadline the first answer does.
175
- connection ??= await portConnection({
176
- profileDir,
177
- exited: () => child.exitCode !== null || child.signalCode !== null,
178
- deadlineMs: options.launchTimeoutMs,
179
- timeoutMs: options.timeoutMs,
180
- });
181
- const left = Math.max(1, options.launchTimeoutMs - (performance.now() - began));
182
- await connection.send('Browser.getVersion', {}, undefined, left);
183
- return { ok: true, browser: { connection, close } };
184
- } catch (error) {
185
- const why = error instanceof CdpTimeoutError ? 'deadline' : 'closed';
186
- // The deadline itself when that is what ended it: the number the reader can raise.
187
- const waitedMs =
188
- why === 'deadline' ? options.launchTimeoutMs : Math.round(performance.now() - began);
189
- // Only a browser that hung up may be on its way out with the reason still unwritten. One that
190
- // was silent for the whole deadline has had its time.
191
- if (why === 'closed') await within(FAILURE_DRAIN_MS, child.exited);
192
- // Read BEFORE the kill: after it, an exit code is ours and says nothing about the browser.
193
- const exitCode = child.exitCode;
194
- await close();
195
- await within(FAILURE_DRAIN_MS, tail.drained);
196
- return {
197
- ok: false,
198
- // `detail`: the error itself. Without it a refused dial after "DevTools listening" read as a
199
- // browser that hung up (seen on windows), and nothing said which step had failed.
200
- failure: {
201
- why,
202
- waitedMs,
203
- exitCode,
204
- stderr: tail.lastLines(),
205
- detail: renderThrowable(error),
206
- },
207
- reaped: child.exitCode !== null || child.signalCode !== null,
208
- };
209
- }
210
- }
211
-
212
- /**
213
- * The process, on its own process GROUP on POSIX so the zygote, GPU and network processes are
214
- * reaped with it (`killTree`). It still ends with this process on the pipe wire: Chrome exits when
215
- * its fd 3 closes. Windows has no group to make — `detached` there is a console flag — so not.
216
- */
217
- function spawnBrowser(options: LaunchAttemptOptions, profileDir: string, platform: string) {
218
- // Spread into a fresh tuple: Bun's `stdio` type takes a mutable tuple, never a readonly one.
219
- const [stdin, stdout, stderr, ...extra] = wireStdio(options.wire);
220
- return Bun.spawn([options.executable, ...options.flags(profileDir)], {
221
- stdio: [stdin, stdout, stderr, ...extra],
222
- detached: platform !== 'win32',
223
- });
224
- }
@@ -1,62 +0,0 @@
1
- // One responsibility: WHERE a Chrome is installed, per platform — the ordered list `findChrome`
2
- // probes when `CHROME_PATH` names none. Which binary wins and how it starts is `cdp-launch.ts`.
3
-
4
- // why: a Windows candidate is spelled with `\` whatever OS computes the list (a test, or the
5
- // Linux runner asserting it), and only node:path's win32 half joins that way. Bun has no path API.
6
- import { win32 } from 'node:path';
7
-
8
- type Env = Readonly<Record<string, string | undefined>>;
9
-
10
- /** What GitHub-hosted `ubuntu-latest` ships, which lets CI run the browser suite with no download. */
11
- const LINUX: readonly string[] = [
12
- '/usr/bin/google-chrome',
13
- '/usr/bin/google-chrome-stable',
14
- '/usr/bin/chromium',
15
- '/usr/bin/chromium-browser',
16
- ];
17
-
18
- const set = (value: string | undefined): string | undefined =>
19
- value === undefined || value === '' ? undefined : value;
20
-
21
- /**
22
- * Chrome under each root an installer uses — machine-wide 64- and 32-bit, then per-user — then
23
- * Edge, which is Chromium, speaks the same DevTools protocol and is on every Windows 10 and 11. A
24
- * root the environment does not name falls back to its fixed default; a per-user root has none, so
25
- * it is not guessed at.
26
- */
27
- const windows = (env: Env): readonly string[] => {
28
- const programFiles = set(env['ProgramFiles']) ?? 'C:\\Program Files';
29
- const programFilesX86 = set(env['ProgramFiles(x86)']) ?? 'C:\\Program Files (x86)';
30
- const localAppData = set(env['LOCALAPPDATA']);
31
- const chromeRoots = [programFiles, programFilesX86, ...(localAppData ? [localAppData] : [])];
32
- return [
33
- ...chromeRoots.map((root) => win32.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe')),
34
- // x86 first for Edge: it is where the Windows image installs it, 64-bit or not.
35
- ...[programFilesX86, programFiles].map((root) =>
36
- win32.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
37
- ),
38
- ];
39
- };
40
-
41
- const MAC_CHROME = 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
42
-
43
- /** The app bundles' executables: system-wide, then the per-user `~/Applications` an admin-less install uses. */
44
- const mac = (env: Env): readonly string[] => {
45
- const home = set(env['HOME']);
46
- return [
47
- `/${MAC_CHROME}`,
48
- ...(home ? [`${home}/${MAC_CHROME}`] : []),
49
- '/Applications/Chromium.app/Contents/MacOS/Chromium',
50
- '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
51
- ];
52
- };
53
-
54
- /**
55
- * Where a Chrome is on `platform`, in the order worth trying. Any platform that is neither Windows
56
- * nor macOS gets the Linux paths — the BSDs install to the same names when they install at all.
57
- */
58
- export function chromeCandidates(platform: string, env: Env): readonly string[] {
59
- if (platform === 'win32') return windows(env);
60
- if (platform === 'darwin') return mac(env);
61
- return LINUX;
62
- }
@@ -1,106 +0,0 @@
1
- // One responsibility: the throwaway profile a launch hands Chrome, and its removal — after every
2
- // process of the browser is gone, retried while something re-creates it, bounded — together with
3
- // the singleton-socket directory Chrome makes BESIDE it in the temp root.
4
-
5
- // why: Bun exposes no temp-root, recursive-remove or readlink primitive; the profile needs all three.
6
- import { existsSync, mkdtempSync, readdirSync, readlinkSync, rmdirSync, rmSync } from 'node:fs';
7
- // why: Bun exposes no tmpdir(), so only node:os answers the platform temp root.
8
- import { tmpdir } from 'node:os';
9
- // why: Bun exposes no path-join primitive.
10
- import { basename, dirname, join } from 'node:path';
11
-
12
- /**
13
- * How long a removed profile is watched for coming back before it counts as gone. Chrome's late
14
- * writers are the network service flushing its disk cache and the browser's atomic preference
15
- * write (`Default/.com.google.Chrome.XXXXXX`) — the exact tree the leaked profiles held. Removal
16
- * waits for the process tree first, so the look is for what the tree kill cannot see: a process
17
- * outside the group (Chrome's crashpad handler calls `setsid`), and on Windows a child `taskkill`
18
- * has not finished ending when it returns.
19
- */
20
- export const PROFILE_SETTLE_MS = 50;
21
-
22
- /**
23
- * What Chrome's ProcessSingleton puts in its socket directory, and nothing else. The directory is
24
- * `<temp>/com.google.Chrome.XXXXXX` (Chromium: `org.chromium.Chromium.…`), linked from the profile's
25
- * `SingletonSocket`, and a browser that does not shut down cleanly never removes it: measured, one
26
- * left in the temp root per launch — 444 of them beside 146 leaked profiles.
27
- */
28
- const SINGLETON_FILES: ReadonlySet<string> = new Set([
29
- 'SingletonSocket',
30
- 'SingletonCookie',
31
- 'SingletonLock',
32
- ]);
33
-
34
- export interface ThrowawayProfile {
35
- readonly path: string;
36
- /**
37
- * Where the browser's singleton socket lives, read off the profile's own link. Asked BEFORE the
38
- * browser is signalled: a browser that exits cleanly removes the link first, and one killed
39
- * leaves the directory with nothing in the profile pointing at it.
40
- */
41
- singletonDir(): string | undefined;
42
- /**
43
- * Remove the profile — and `singleton`, when it holds Chrome's singleton files and nothing else —
44
- * and answer once neither has come back for `settleMs` (`PROFILE_SETTLE_MS`), or at `deadlineMs`.
45
- * Never throws: a directory that will not go is litter, never the close's verdict.
46
- */
47
- remove(singleton: string | undefined, deadlineMs: number, settleMs?: number): Promise<void>;
48
- }
49
-
50
- const quietly = (work: () => void): void => {
51
- try {
52
- work();
53
- } catch {
54
- // Already gone, or held open past the deadline: the loop's next look decides which.
55
- }
56
- };
57
-
58
- /**
59
- * Only a directory whose every entry is a singleton file is Chrome's to have made: a link that
60
- * points anywhere else is somebody's directory, and is left alone.
61
- */
62
- function isSingletonDir(dir: string): boolean {
63
- try {
64
- return readdirSync(dir).every((entry) => SINGLETON_FILES.has(entry));
65
- } catch {
66
- return false;
67
- }
68
- }
69
-
70
- /** File by file, then a plain `rmdir` — never a recursive remove of a path read off a link. */
71
- function removeSingleton(dir: string): void {
72
- for (const entry of SINGLETON_FILES) quietly(() => rmSync(join(dir, entry), { force: true }));
73
- quietly(() => rmdirSync(dir));
74
- }
75
-
76
- /** A fresh profile directory under the temp root, named so a leak is recognisable as ours. */
77
- export function throwawayProfile(root: string = tmpdir()): ThrowawayProfile {
78
- const path = mkdtempSync(join(root, 'x-e2e-chrome-'));
79
- return {
80
- path,
81
- singletonDir() {
82
- try {
83
- const target = readlinkSync(join(path, 'SingletonSocket'));
84
- return basename(target) === 'SingletonSocket' ? dirname(target) : undefined;
85
- } catch {
86
- return undefined;
87
- }
88
- },
89
- async remove(singleton, deadlineMs, settleMs = PROFILE_SETTLE_MS) {
90
- const until = performance.now() + deadlineMs;
91
- const owned = singleton !== undefined && isSingletonDir(singleton) ? singleton : undefined;
92
- const present = (): boolean => existsSync(path) || (owned !== undefined && existsSync(owned));
93
- do {
94
- quietly(() => rmSync(path, { recursive: true, force: true }));
95
- if (owned !== undefined) removeSingleton(owned);
96
- if (present()) {
97
- await Bun.sleep(settleMs / 5);
98
- continue;
99
- }
100
- // Gone NOW is not gone: the look after the settle is what a late writer fails.
101
- await Bun.sleep(settleMs);
102
- if (!present()) return;
103
- } while (performance.now() < until);
104
- },
105
- };
106
- }
@@ -1,68 +0,0 @@
1
- // One responsibility: nothing of a launched browser outlives its close — on POSIX its process GROUP,
2
- // on Windows its process TREE — and the close waits until that is so, bounded.
3
-
4
- /** How long a closed Chrome gets to exit on SIGTERM before it is killed outright. */
5
- export const CLOSE_GRACE_MS = 5_000;
6
-
7
- const GROUP_POLL_MS = 10;
8
-
9
- /** Runs a command to its exit; the seam the Windows branch is asserted through on any runner. */
10
- export type RunCommand = (argv: readonly string[]) => Promise<number>;
11
-
12
- const runQuiet: RunCommand = (argv) =>
13
- // Bounded: taskkill ends a tree in well under a second; a stuck one must not stall `close()`.
14
- Bun.spawn([...argv], { stdio: ['ignore', 'ignore', 'ignore'], timeout: 10_000 }).exited;
15
-
16
- /**
17
- * `/T` takes every process the browser started — renderer, GPU, network, crashpad — and `/F` does
18
- * not ask: a tree kill is the last step of a close, after the graceful one had its chance.
19
- */
20
- export const taskkillArgv = (pid: number): readonly string[] => [
21
- 'taskkill',
22
- '/T',
23
- '/F',
24
- '/PID',
25
- String(pid),
26
- ];
27
-
28
- const within = (ms: number, work: Promise<unknown>): Promise<unknown> =>
29
- Promise.race([work, Bun.sleep(ms)]);
30
-
31
- /**
32
- * Kill whatever is left of the browser's process group and wait until the group is EMPTY — the
33
- * condition, asked of the kernel, not a pause: signal 0 to a group with no member throws. Bounded
34
- * by `CLOSE_GRACE_MS` for a container whose init never reaps a zombie — on the monotonic clock,
35
- * not a count of sleeps: a loaded runner oversleeps every 10 ms, and the close's designed bound
36
- * (`LAUNCHED_CLOSE_MS`) is what a hook deadline is derived from.
37
- */
38
- async function reapGroup(pgid: number): Promise<void> {
39
- const until = performance.now() + CLOSE_GRACE_MS;
40
- try {
41
- process.kill(-pgid, 'SIGKILL');
42
- while (performance.now() < until) {
43
- await Bun.sleep(GROUP_POLL_MS);
44
- process.kill(-pgid, 0);
45
- }
46
- } catch {
47
- // ESRCH: nothing is left in the group, which is the answer being waited for.
48
- }
49
- }
50
-
51
- /**
52
- * Everything the browser `pid` started, gone. On Windows `process.kill(-pgid)` is no call at all —
53
- * there is no process group, and the browser's children hold the profile's files open — so the
54
- * tree is walked by `taskkill`, which must run while the browser is still ALIVE: its children are
55
- * found by parent pid, and a dead parent's children are nobody's.
56
- */
57
- export async function killTree(
58
- pid: number,
59
- platform: string = process.platform,
60
- run: RunCommand = runQuiet,
61
- ): Promise<void> {
62
- if (platform !== 'win32') return reapGroup(pid);
63
- try {
64
- await within(CLOSE_GRACE_MS, run(taskkillArgv(pid)));
65
- } catch {
66
- // No taskkill, or a tree already gone (exit 128): litter at worst, never the close's verdict.
67
- }
68
- }