@specific.dev/spectest 0.26.0 → 0.27.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 (74) hide show
  1. package/dist/aws-sigv4.d.ts +42 -0
  2. package/dist/aws-sigv4.js +166 -0
  3. package/dist/browser.d.ts +314 -0
  4. package/dist/browser.js +1320 -0
  5. package/dist/components/email.d.ts +135 -0
  6. package/dist/components/email.js +271 -0
  7. package/dist/components/expo.d.ts +69 -0
  8. package/dist/components/expo.js +125 -0
  9. package/dist/components/index.d.ts +8 -0
  10. package/dist/components/index.js +18 -0
  11. package/dist/components/k3s.d.ts +143 -0
  12. package/dist/components/k3s.js +1067 -0
  13. package/dist/components/postgres.d.ts +93 -0
  14. package/dist/components/postgres.js +58 -0
  15. package/dist/components/replayFake.d.ts +169 -0
  16. package/dist/components/replayFake.js +738 -0
  17. package/dist/components/s3.d.ts +99 -0
  18. package/dist/components/s3.js +81 -0
  19. package/dist/components/supabase.d.ts +197 -0
  20. package/dist/components/supabase.js +1003 -0
  21. package/dist/daemon.d.ts +1 -0
  22. package/dist/daemon.js +4223 -0
  23. package/dist/ids.d.ts +2 -0
  24. package/{src/ids.ts → dist/ids.js} +46 -50
  25. package/dist/index.d.ts +1183 -0
  26. package/dist/index.js +769 -0
  27. package/dist/ingress.d.ts +114 -0
  28. package/dist/ingress.js +210 -0
  29. package/dist/inspect.d.ts +228 -0
  30. package/dist/inspect.js +429 -0
  31. package/dist/locator.d.ts +260 -0
  32. package/dist/locator.js +293 -0
  33. package/dist/mobile.d.ts +71 -0
  34. package/dist/mobile.js +65 -0
  35. package/dist/record-secrets.d.ts +9 -0
  36. package/{src/record-secrets.ts → dist/record-secrets.js} +13 -15
  37. package/dist/recorder.d.ts +516 -0
  38. package/dist/recorder.js +219 -0
  39. package/dist/redis.d.ts +54 -0
  40. package/dist/redis.js +126 -0
  41. package/dist/replay-bundle.d.ts +38 -0
  42. package/{src/replay-bundle.ts → dist/replay-bundle.js} +29 -47
  43. package/dist/resolver.d.ts +1 -0
  44. package/dist/resolver.js +309 -0
  45. package/dist/s3.d.ts +89 -0
  46. package/dist/s3.js +198 -0
  47. package/dist/sql.d.ts +74 -0
  48. package/dist/sql.js +151 -0
  49. package/dist/terminal.d.ts +161 -0
  50. package/dist/terminal.js +538 -0
  51. package/package.json +24 -9
  52. package/src/browser.ts +0 -1819
  53. package/src/components/email.ts +0 -398
  54. package/src/components/expo.ts +0 -167
  55. package/src/components/index.ts +0 -63
  56. package/src/components/k3s.ts +0 -1312
  57. package/src/components/postgres.ts +0 -105
  58. package/src/components/replayFake.ts +0 -848
  59. package/src/components/s3.ts +0 -132
  60. package/src/components/supabase.ts +0 -1299
  61. package/src/daemon.ts +0 -4969
  62. package/src/index.ts +0 -2350
  63. package/src/ingress.ts +0 -288
  64. package/src/inspect.ts +0 -673
  65. package/src/locator.ts +0 -594
  66. package/src/mobile.ts +0 -133
  67. package/src/recorder.ts +0 -817
  68. package/src/redis.ts +0 -202
  69. package/src/resolver.ts +0 -351
  70. package/src/s3.ts +0 -333
  71. package/src/sql.ts +0 -243
  72. package/src/terminal.ts +0 -740
  73. package/src/vendor/rrweb-plugin-console-record.umd.js +0 -521
  74. package/src/vendor/rrweb-record.min.js +0 -5061
package/src/recorder.ts DELETED
@@ -1,817 +0,0 @@
1
- // Per-test event recorder. The daemon installs a fresh recorder before
2
- // running a test case and drains it afterwards. While a recorder is
3
- // active, instrumented sites (the SDK's `expect`, the daemon's wrapped
4
- // `ctx.exec`, and the test-scoped `fetch` wrapper) push structured
5
- // events into it.
6
- //
7
- // When no test is running (production code paths, eval, etc.) the
8
- // current recorder is `null` and the `record*` helpers are no-ops, so
9
- // callers can invoke them unconditionally.
10
-
11
- import { clearPendingNullish } from "./inspect.js";
12
-
13
- const OUTPUT_SNIPPET_BYTES = 256 * 1024;
14
-
15
- export type TestEvent =
16
- | ExecEvent
17
- | AssertionEvent
18
- | HttpEvent
19
- | KubeEvent
20
- | BrowserEvent
21
- | DbEvent
22
- | RedisEvent
23
- | S3Event
24
- | TerminalEvent
25
- | TerminalStepEvent
26
- | WaitEvent
27
- | FakeEvent
28
- | EnvEvent
29
- | EmailEvent;
30
-
31
- interface BaseEvent {
32
- /** Order of *start* within the test. Reserved when an op begins (see
33
- * `reserveEvent`), so an op whose nested children finish — and record —
34
- * before it does still sorts ahead of them. Ops that don't reserve get
35
- * their seq at record (= finish) time. */
36
- seq: number;
37
- /** Milliseconds since the recorder started, captured when the op began
38
- * (reserved) or, absent a reservation, when it was recorded. */
39
- tOffsetMs: number;
40
- /**
41
- * Optional grouping pointer. When set, this event was emitted inside
42
- * a larger logical step (e.g. an HTTP call that fed the predicate of
43
- * a `ctx.poll(...)`) and should render nested under the parent in
44
- * timelines. The parent event is identified by its `seq`.
45
- */
46
- parentSeq?: number;
47
- }
48
-
49
- export interface ExecEvent extends BaseEvent {
50
- kind: "exec";
51
- service: string;
52
- command: string;
53
- /**
54
- * Working directory the command ran from (`ctx.exec(svc, cmd, { cwd })`),
55
- * if any. Kept off `command` so the sidebar shows just the command; the
56
- * detail view surfaces it. Absent when the call used no `cwd`.
57
- */
58
- cwd?: string;
59
- exitCode: number;
60
- /** stdout truncated to OUTPUT_SNIPPET_BYTES. */
61
- stdout: string;
62
- stdoutTruncated: boolean;
63
- stderr: string;
64
- stderrTruncated: boolean;
65
- durationMs: number;
66
- /**
67
- * Links this exec to the asciicast `TerminalSessionRecord` of its run
68
- * (mirroring `TerminalEvent.sessionId`): one exec step covers one full
69
- * CLI run, so the whole recording belongs to this event. Absent on
70
- * events recorded before exec runs were captured.
71
- */
72
- sessionId?: string;
73
- }
74
-
75
- export interface AssertionEvent extends BaseEvent {
76
- kind: "assertion";
77
- /** Matcher name, e.g. "toBe", "toEqual". */
78
- matcher: string;
79
- /** Whether this was `expect(x).not.toBe(...)`. */
80
- negated: boolean;
81
- passed: boolean;
82
- /** Best-effort JSON-safe serialization. */
83
- actual: unknown;
84
- expected?: unknown;
85
- /** Failure message produced by the matcher (only when `passed` is false). */
86
- error?: string;
87
- /**
88
- * Author-supplied label for the assertion. **Required** for a raw assertion
89
- * (`expectRaw(value, message)`), where it renders as the summary
90
- * ("ASSERT <message>") and serves as the diff-alignment key since a raw
91
- * assertion has no provenance `path`. **Optional** for a provenance-linked
92
- * `expect(value, message)`, where it leads the summary as a clarifying note
93
- * alongside the rendered matcher/target. Absent when `expect(...)` was called
94
- * without a message.
95
- */
96
- message?: string;
97
- /**
98
- * `seq` of the op (http / db / browser) whose return value this
99
- * assertion drilled into. Set when `expect()` received a value wrapped
100
- * by `inspect.wrap()`. The UI nests assertions with `sourceSeq` under
101
- * the matching op; assertions without it render at top level.
102
- */
103
- sourceSeq?: number;
104
- /** JSON-path of property accesses from the op return value down to
105
- * the asserted value (e.g. `["body", "user", "name"]`). Empty for
106
- * direct asserts on the op return itself. */
107
- path?: string[];
108
- }
109
-
110
- export interface DbEvent extends BaseEvent {
111
- kind: "db";
112
- /** Service the query ran against (the key in `environment.services`). */
113
- service: string;
114
- /** SQL text. For tagged-template calls, values appear as `$1`, `$2`, … */
115
- query: string;
116
- /** Parameter values. Best-effort JSON-safe; large/binary values stringified. */
117
- params?: unknown[];
118
- /** Rows returned — or rows AFFECTED when `rowsAffected` is set. */
119
- rowCount?: number;
120
- /** Set when `rowCount` counts affected rows (a non-RETURNING
121
- * INSERT/UPDATE/DELETE) rather than a result set — rendered as
122
- * "N affected" so an `UPDATE → 0 rows` can't read as "nothing updated". */
123
- rowsAffected?: boolean;
124
- /** Captured rows for table rendering in the web UI. Capped at
125
- * MAX_DB_ROWS; `rowsTruncated` is set when there were more. */
126
- rows?: unknown[];
127
- rowsTruncated?: boolean;
128
- /** Column names in the order Bun.SQL returned them. Derived from the
129
- * first captured row, so omitted when no rows. */
130
- columns?: string[];
131
- durationMs: number;
132
- /** Set if the driver threw. */
133
- error?: string;
134
- }
135
-
136
- /**
137
- * One Redis/Valkey command issued through the instrumented {@link
138
- * "../redis".RedisClient} (a drop-in for `Bun.RedisClient` / `Bun.redis`).
139
- *
140
- * The return value is `wrap()`ped against this event's seq, so a later
141
- * `expect(...)` that drills into it nests under this step in the timeline
142
- * (same mechanism as http/db).
143
- */
144
- export interface RedisEvent extends BaseEvent {
145
- kind: "redis";
146
- /** Label for the connection — the URL host (often the service name). */
147
- service: string;
148
- /** Command name, upper-cased (`GET`, `SET`, `HGETALL`, `PUBLISH`, …). */
149
- command: string;
150
- /** First argument — almost always the key the command targets. Surfaced
151
- * separately so the UI can read `GET session:42` at a glance. */
152
- key?: string;
153
- /** Remaining arguments (best-effort JSON-safe; large/binary stringified).
154
- * Omitted when there are none. */
155
- args?: unknown[];
156
- /** Reply, best-effort JSON-safe and capped. Omitted when the command threw
157
- * or returned `null`/`undefined`. */
158
- result?: unknown;
159
- resultTruncated?: boolean;
160
- durationMs: number;
161
- /** Set if the command threw. */
162
- error?: string;
163
- }
164
-
165
- /**
166
- * One object-storage operation through the instrumented {@link
167
- * "../s3".S3Client} (a drop-in for `Bun.S3Client` / `Bun.s3`), covering both
168
- * client-level calls (`write`/`delete`/`exists`/`list`/`presign`/`stat`) and
169
- * the `S3File` handle `.file(path)` returns (`text`/`json`/`write`/…).
170
- *
171
- * The return value is `wrap()`ped against this event's seq, so `expect(...)`
172
- * drilling into it nests under this step (same mechanism as http/db).
173
- */
174
- export interface S3Event extends BaseEvent {
175
- kind: "s3";
176
- /** Operation: `write` | `read` | `delete` | `exists` | `list` |
177
- * `presign` | `stat`. */
178
- op: string;
179
- /** Bucket, when the client/handle knows it. */
180
- bucket?: string;
181
- /** Object key (path) the op targeted. Omitted for bucket-wide `list`. */
182
- key?: string;
183
- /** Bytes written or read, when known. */
184
- size?: number;
185
- /** Content type, when known (read/write/stat). */
186
- contentType?: string;
187
- /** Small text preview of the body (read/write of text), capped. */
188
- preview?: string;
189
- previewTruncated?: boolean;
190
- /** For `list`: number of keys returned. */
191
- count?: number;
192
- durationMs: number;
193
- /** Set if the op threw. */
194
- error?: string;
195
- }
196
-
197
- export interface HttpEvent extends BaseEvent {
198
- kind: "http";
199
- method: string;
200
- url: string;
201
- /** Truncated to OUTPUT_SNIPPET_BYTES. Only set for non-binary text bodies. */
202
- requestBody?: string;
203
- requestBodyTruncated?: boolean;
204
- status?: number;
205
- responseBody?: string;
206
- responseBodyTruncated?: boolean;
207
- durationMs: number;
208
- /** Set if the request threw (network error, abort, etc.). */
209
- error?: string;
210
- }
211
-
212
- /**
213
- * A Kubernetes API call (from `ctx.svc.<k3s>.client.*` / `apply(...)`).
214
- *
215
- * The k3s component routes the kube client through `globalThis.fetch`, so
216
- * the daemon's fetch wrapper first records it as a plain `http` event;
217
- * the component then parses the request path and *reclassifies* that event
218
- * into this richer shape via `recorderAnnotate`, so the UI can show
219
- * `verb resource/name` (e.g. `list pods · default`) instead of an opaque
220
- * `GET https://k8s.internal:6443/api/v1/...`. The underlying HTTP fields
221
- * are retained so the request/response bodies (the actual K8s objects)
222
- * still render in the detail view, and `expect(...)` on the returned
223
- * object nests under this event exactly as it does for `http`.
224
- */
225
- export interface KubeEvent extends BaseEvent {
226
- kind: "kube";
227
- /** API verb derived from the HTTP method + path shape: `get` | `list` |
228
- * `watch` | `create` | `update` | `patch` | `delete` |
229
- * `deletecollection`. */
230
- verb: string;
231
- /** API group — `""` for the core group (`/api/v1`), else e.g. `"apps"`,
232
- * `"networking.k8s.io"`. */
233
- group?: string;
234
- /** API version, e.g. `"v1"`. */
235
- apiVersion?: string;
236
- /** Resource plural, e.g. `"pods"`, `"deployments"`, `"ingresses"`. */
237
- resource?: string;
238
- /** Subresource, when addressed, e.g. `"status"`, `"scale"`, `"log"`. */
239
- subresource?: string;
240
- /** Object name, when the request targets a single object. */
241
- name?: string;
242
- /** Namespace, when namespaced. Absent for cluster-scoped requests. */
243
- namespace?: string;
244
- // Underlying HTTP fields, retained for drill-down (mirror HttpEvent).
245
- method: string;
246
- url: string;
247
- requestBody?: string;
248
- requestBodyTruncated?: boolean;
249
- status?: number;
250
- responseBody?: string;
251
- responseBodyTruncated?: boolean;
252
- durationMs: number;
253
- error?: string;
254
- }
255
-
256
- /**
257
- * One call to a fake's helper function (`ctx.fakes.<name>.<fn>(...)`).
258
- * Helpers are user-authored functions that read or mutate the fake's
259
- * private state, so this is the only window into what a test asked the
260
- * fake — distinct from the `http` events the *app under test* generates
261
- * when it actually calls the fake's endpoints.
262
- *
263
- * The return value is `wrap()`ped against this event's seq, so a later
264
- * `expect(...)` that drills into it nests under this step in the
265
- * timeline (same mechanism as http/db/exec).
266
- */
267
- export interface FakeEvent extends BaseEvent {
268
- kind: "fake";
269
- /** Fake name — the key in `ctx.fakes`. */
270
- fake: string;
271
- /** Helper function called, e.g. `"lastCharge"`. */
272
- member: string;
273
- /** Call arguments (best-effort JSON-safe). */
274
- args?: unknown[];
275
- /** Return value (best-effort JSON-safe). Omitted when the helper threw
276
- * or returned `undefined`. */
277
- result?: unknown;
278
- durationMs: number;
279
- /** Set if the helper threw. */
280
- error?: string;
281
- }
282
-
283
- /**
284
- * One captured email, as embedded on an {@link EmailEvent}. The HTML and
285
- * text bodies ride along (truncated to the output cap) so the dashboard
286
- * can render the actual email a test asserted against.
287
- */
288
- export interface EmailEventMessage {
289
- /** Sender address. */
290
- from?: string;
291
- /** Recipient addresses. */
292
- to?: string[];
293
- cc?: string[];
294
- bcc?: string[];
295
- subject?: string;
296
- /** RFC date of the message, ISO-formatted. */
297
- date?: string;
298
- /** HTML body (truncated to the output cap). */
299
- html?: string;
300
- htmlTruncated?: boolean;
301
- /** Plain-text body (truncated to the output cap). */
302
- text?: string;
303
- textTruncated?: boolean;
304
- attachments?: { filename: string; contentType: string; size: number }[];
305
- }
306
-
307
- /** One row of a mailbox listing embedded on an {@link EmailEvent}. */
308
- export interface EmailEventSummary {
309
- from?: string;
310
- to?: string[];
311
- subject?: string;
312
- /** Plain-text preview of the body. */
313
- snippet?: string;
314
- date?: string;
315
- }
316
-
317
- /**
318
- * One call to an email service's helpers (`ctx.svc.<name>.lastEmail(...)`
319
- * etc.). Single-message ops embed the full captured message — including its
320
- * HTML body — so timelines can render the email itself; listing ops embed
321
- * compact summaries. The return value is `wrap()`ped against this event's
322
- * seq, so `expect(...)` on it nests under this step (same mechanism as
323
- * http/db/fake). Inside a `ctx.poll` predicate the event ride-alongs with
324
- * the poll's iteration events: failed iterations get truncated, the winning
325
- * one survives as a child of the `wait` event.
326
- */
327
- export interface EmailEvent extends BaseEvent {
328
- kind: "email";
329
- /** Service key of the mail server (`ctx.svc.<service>`). */
330
- service: string;
331
- /** Helper called, e.g. `"lastEmail"`. */
332
- op: string;
333
- /** Human-readable match criteria, e.g. `to alice@example.com`. */
334
- query?: string;
335
- /** Number of matching messages (listing ops / mailbox size on error). */
336
- count?: number;
337
- /** The captured message (single-message ops). */
338
- message?: EmailEventMessage;
339
- /** Message summaries (listing ops). */
340
- messages?: EmailEventSummary[];
341
- durationMs: number;
342
- /** Set if the op threw (e.g. the mail server's query API failed). */
343
- error?: string;
344
- }
345
-
346
- /**
347
- * A runtime mutation of the environment — `ctx.startService` /
348
- * `ctx.stopService` / `ctx.dnsName`, whether called from a test or from a
349
- * fake handler reacting to the app under test. Distinct from the `http`
350
- * event the app generates when it calls the fake: this is the
351
- * infrastructure the fake (or test) created in response. No-op outside a
352
- * running test (bootstrap / project-setup / eval), same as every record*.
353
- */
354
- export interface EnvEvent extends BaseEvent {
355
- kind: "env";
356
- /** Which environment primitive ran. */
357
- op: "startService" | "stopService" | "dnsName";
358
- /** Service name (startService / stopService). */
359
- service?: string;
360
- /** Image reference started (startService). */
361
- image?: string;
362
- /** Resolved IP — the new container's (startService) or the target's (dnsName). */
363
- ip?: string;
364
- /** Hostname registered (dnsName). */
365
- hostname?: string;
366
- durationMs: number;
367
- /** Set if the op threw. */
368
- error?: string;
369
- }
370
-
371
- // A browser step's action label. Since the Playwright-native surface exposes
372
- // the full locator method vocabulary (click/fill/press/getAttribute/…) plus
373
- // the session verbs (goto/goBack/evaluate/waitForFunction/screenshot/…), this
374
- // is an open string rather than a closed union — the value is the Playwright
375
- // method name verbatim. Both renderers (control-plane web + CLI) treat it as
376
- // an opaque string with a generic `{action} <target>` fallback, so new method
377
- // names need no Rust change. Representative values: "goto", "goBack",
378
- // "goForward", "reload", "evaluate", "waitForFunction",
379
- // "click", "dblclick", "tap", "fill", "clear", "press", "type", "scroll",
380
- // "check", "hover", "textContent", "inputValue", "count", "screenshot".
381
- export type BrowserAction = string;
382
-
383
- export interface BrowserEvent extends BaseEvent {
384
- kind: "browser";
385
- action: BrowserAction;
386
- /** Target URL (navigate). */
387
- url?: string;
388
- /** CSS selector (click, scrollTo). */
389
- selector?: string;
390
- /** Human-readable label for `evaluate` ops. */
391
- description?: string;
392
- /** Evaluated script, truncated. */
393
- script?: string;
394
- scriptTruncated?: boolean;
395
- /** Typed text, truncated. */
396
- text?: string;
397
- textTruncated?: boolean;
398
- /** Key name (press). */
399
- key?: string;
400
- /** Scroll/click coordinates. */
401
- dx?: number;
402
- dy?: number;
403
- x?: number;
404
- y?: number;
405
- /** Screenshot image format. */
406
- format?: string;
407
- /** For `waitFor`: how many times the predicate was polled. */
408
- attempts?: number;
409
- durationMs: number;
410
- error?: string;
411
- /**
412
- * Session this op belonged to. Set whenever the Browser was opened
413
- * with a `BrowserSessionRecorder` attached (the daemon always does).
414
- */
415
- sessionId?: string;
416
- /**
417
- * Wall-clock `Date.now()` captured at the moment this op *finished*.
418
- * Lives in the same time base as rrweb's `event.timestamp` fields,
419
- * so the dashboard can seek the player by computing
420
- * `event.timestamp - events[0].timestamp`. Using the post-op time
421
- * (rather than op start) means clicking a "type 'foo'" step lands
422
- * on the frame where the field already shows the text.
423
- */
424
- sessionTimestamp?: number;
425
- }
426
-
427
- /**
428
- * Inline event for a single `ctx.terminal(...)` call. The heavy
429
- * asciicast frames live separately on a `TerminalSessionRecord`
430
- * (mirroring how `BrowserEvent` points at a `BrowserSessionRecord`).
431
- * The UI shows this row in the step list and seeks the player to
432
- * the session's start when clicked.
433
- */
434
- export interface TerminalEvent extends BaseEvent {
435
- kind: "terminal";
436
- service: string;
437
- command: string;
438
- exitCode: number;
439
- durationMs: number;
440
- /** Links this event to its TerminalSessionRecord. */
441
- sessionId: string;
442
- /** PTY size used for the run. */
443
- cols: number;
444
- rows: number;
445
- /** First N bytes of decoded output, for tooltip/inline preview. */
446
- outputPreview: string;
447
- outputTruncated: boolean;
448
- /** Set if spawning the PTY itself failed. */
449
- error?: string;
450
- }
451
-
452
- /** Action taken on an open interactive terminal session. */
453
- export type TerminalStepAction =
454
- | "send"
455
- | "sendLine"
456
- | "press"
457
- | "waitFor"
458
- | "exit"
459
- | "close";
460
-
461
- /**
462
- * One operation on an open interactive terminal — analogous to
463
- * `BrowserEvent`. The session's heavy asciicast frames live on the
464
- * `TerminalSessionRecord`; this event just carries metadata so the
465
- * step shows up in the timeline and the UI can seek the player.
466
- */
467
- export interface TerminalStepEvent extends BaseEvent {
468
- kind: "terminal-step";
469
- /** Links this event back to its TerminalSessionRecord. */
470
- sessionId: string;
471
- /** Service the terminal is attached to (mirrors TerminalEvent.service). */
472
- service: string;
473
- /** Which Terminal method produced this event. */
474
- action: TerminalStepAction;
475
- /** Bytes sent (send/sendLine), truncated. */
476
- text?: string;
477
- textTruncated?: boolean;
478
- /** Key name passed to `press`. */
479
- key?: string;
480
- /** Human label passed to `waitFor`. */
481
- description?: string;
482
- /** How many polls `waitFor` made. */
483
- attempts?: number;
484
- /** Whether `waitFor` matched (false means it timed out). */
485
- matched?: boolean;
486
- /** Exit code observed on `close`. */
487
- exitCode?: number;
488
- /** Rendered screen at the moment of the op (post-action), truncated. */
489
- screenPreview: string;
490
- screenTruncated: boolean;
491
- /**
492
- * Player-relative offset, in seconds, captured against the *same*
493
- * clock the asciicast frames use (the terminal factory's spawn
494
- * time). The UI seeks the asciinema-player to this value when the
495
- * step is clicked. Persisting it directly avoids ever subtracting
496
- * `step.tOffsetMs - session.openedAtMs` on the front-end, which is
497
- * fragile because the two timestamps live in slightly different
498
- * Date.now() frames (recorder vs. spawn).
499
- */
500
- castTimeSec: number;
501
- durationMs: number;
502
- error?: string;
503
- }
504
-
505
- /** An ordering slot claimed at op *start* and handed back to the matching
506
- * `record*` call at op finish. Lets a triggering op (an `exec`/`fetch` that
507
- * reaches the app, which calls a fake, which calls `ctx.startService`) keep a
508
- * lower seq than the nested events it sets off — even though those nested
509
- * events finish, and record, first. */
510
- export interface EventReservation {
511
- seq: number;
512
- tOffsetMs: number;
513
- }
514
-
515
- class Recorder {
516
- private events: TestEvent[] = [];
517
- private seq = 0;
518
- private readonly start = Date.now();
519
-
520
- /** Claim a seq + start offset now; pass the result to `push` at finish. */
521
- reserve(): EventReservation {
522
- return { seq: this.seq++, tOffsetMs: Date.now() - this.start };
523
- }
524
-
525
- push(
526
- ev: Omit<TestEvent, "seq" | "tOffsetMs">,
527
- reservation?: EventReservation,
528
- ): number {
529
- // A new op invalidates any pending nullish-leaf note: a note must not
530
- // survive past the op it belongs to and get adopted by a later, unrelated
531
- // `expect`. The assertion event itself is exempt — its `expect()` already
532
- // adopted (and consumed) the note before recording.
533
- if (ev.kind !== "assertion") clearPendingNullish();
534
- const seq = reservation?.seq ?? this.seq++;
535
- this.events.push({
536
- ...ev,
537
- seq,
538
- tOffsetMs: reservation?.tOffsetMs ?? Date.now() - this.start,
539
- } as TestEvent);
540
- return seq;
541
- }
542
-
543
- drain(): TestEvent[] {
544
- return this.events;
545
- }
546
-
547
- /** Index of the next event that would be pushed. Use with `truncate`
548
- * to drop everything pushed since this index. The seq counter does
549
- * not roll back — discarded seqs leave gaps. */
550
- eventCount(): number {
551
- return this.events.length;
552
- }
553
-
554
- /** Drop events with index >= `toLen`. The seq counter is unaffected
555
- * (so seqs already handed out remain unique even though the events
556
- * they named are gone). */
557
- truncate(toLen: number): void {
558
- if (toLen < this.events.length) {
559
- this.events.length = toLen;
560
- }
561
- }
562
-
563
- /** Stamp `parentSeq` onto every event at index >= `startIdx`. Used
564
- * by `ctx.poll` to group the kept iteration's events under the
565
- * resulting wait event. */
566
- markChildren(startIdx: number, parentSeq: number): void {
567
- for (let i = startIdx; i < this.events.length; i++) {
568
- const ev = this.events[i]!;
569
- if (ev.seq === parentSeq) continue;
570
- ev.parentSeq = parentSeq;
571
- }
572
- }
573
-
574
- /** Shallow-merge `patch` into the already-recorded event with this
575
- * `seq`. Lets an instrumentation site enrich or reclassify an event
576
- * after the fact — e.g. the k3s component upgrades the generic `http`
577
- * event its API call produced into a Kubernetes-specific `kube` event
578
- * once it has parsed the request. Searches from the end since the
579
- * target is almost always the most recent event. No-op when no event
580
- * carries that seq. */
581
- annotate(seq: number, patch: Record<string, unknown>): void {
582
- for (let i = this.events.length - 1; i >= 0; i--) {
583
- const ev = this.events[i]!;
584
- if (ev.seq === seq) {
585
- Object.assign(ev, patch);
586
- return;
587
- }
588
- }
589
- }
590
-
591
- /** Drop the single event carrying this `seq`. Used to retract an event
592
- * that an instrumentation site recorded but then decided is noise — e.g.
593
- * the dynamic kube client's internal discovery GET. Caller must ensure
594
- * nothing references the seq (no child events/assertions hang off it).
595
- * The seq counter does not roll back, so the seq stays retired. Searches
596
- * from the end since the target is almost always the most recent event. */
597
- remove(seq: number): void {
598
- for (let i = this.events.length - 1; i >= 0; i--) {
599
- if (this.events[i]!.seq === seq) {
600
- this.events.splice(i, 1);
601
- return;
602
- }
603
- }
604
- }
605
- }
606
-
607
- let current: Recorder | null = null;
608
-
609
- // Counter-based pause: `pauseRecording`/`resumeRecording` nest safely
610
- // (a nested `ctx.poll` inside another `ctx.poll`'s predicate stays
611
- // suppressed until its own resume balances out). Active record* sites
612
- // no-op while `paused > 0`, so http/exec/db/etc. inside a paused
613
- // region produce no events and the returned seq is `undefined` —
614
- // which means the daemon's fetch wrapper also skips installing the
615
- // inspector proxy on the Response.
616
- let paused = 0;
617
-
618
- export function pauseRecording(): void {
619
- paused += 1;
620
- }
621
-
622
- export function resumeRecording(): void {
623
- paused = Math.max(0, paused - 1);
624
- }
625
-
626
- function active(): boolean {
627
- return current !== null && paused === 0;
628
- }
629
-
630
- export function startRecording(): void {
631
- current = new Recorder();
632
- paused = 0;
633
- }
634
-
635
- export function stopRecording(): TestEvent[] {
636
- if (!current) return [];
637
- const evs = current.drain();
638
- current = null;
639
- paused = 0;
640
- return evs;
641
- }
642
-
643
- export function isRecording(): boolean {
644
- return current !== null;
645
- }
646
-
647
- /** Reserve an ordering slot at the start of an op so nested events it triggers
648
- * (which finish — and record — first) still sort after it. Hand the returned
649
- * reservation to the matching `record*` call at op finish. Returns `undefined`
650
- * when nothing is recording, in which case `record*` falls back to allocating
651
- * the seq at record time. */
652
- export function reserveEvent(): EventReservation | undefined {
653
- return active() ? current!.reserve() : undefined;
654
- }
655
-
656
- export function recordExec(
657
- ev: Omit<ExecEvent, "seq" | "tOffsetMs" | "kind">,
658
- reservation?: EventReservation,
659
- ): number | undefined {
660
- return active() ? current!.push({ kind: "exec", ...ev }, reservation) : undefined;
661
- }
662
-
663
- export function recordAssertion(
664
- ev: Omit<AssertionEvent, "seq" | "tOffsetMs" | "kind">,
665
- ): number | undefined {
666
- return active() ? current!.push({ kind: "assertion", ...ev }) : undefined;
667
- }
668
-
669
- export function recordHttp(
670
- ev: Omit<HttpEvent, "seq" | "tOffsetMs" | "kind">,
671
- reservation?: EventReservation,
672
- ): number | undefined {
673
- return active() ? current!.push({ kind: "http", ...ev }, reservation) : undefined;
674
- }
675
-
676
- export function recordBrowser(
677
- ev: Omit<BrowserEvent, "seq" | "tOffsetMs" | "kind">,
678
- reservation?: EventReservation,
679
- ): number | undefined {
680
- return active() ? current!.push({ kind: "browser", ...ev }, reservation) : undefined;
681
- }
682
-
683
- export function recordDb(
684
- ev: Omit<DbEvent, "seq" | "tOffsetMs" | "kind">,
685
- reservation?: EventReservation,
686
- ): number | undefined {
687
- return active() ? current!.push({ kind: "db", ...ev }, reservation) : undefined;
688
- }
689
-
690
- export function recordRedis(
691
- ev: Omit<RedisEvent, "seq" | "tOffsetMs" | "kind">,
692
- reservation?: EventReservation,
693
- ): number | undefined {
694
- return active() ? current!.push({ kind: "redis", ...ev }, reservation) : undefined;
695
- }
696
-
697
- export function recordS3(
698
- ev: Omit<S3Event, "seq" | "tOffsetMs" | "kind">,
699
- reservation?: EventReservation,
700
- ): number | undefined {
701
- return active() ? current!.push({ kind: "s3", ...ev }, reservation) : undefined;
702
- }
703
-
704
- export function recordTerminal(
705
- ev: Omit<TerminalEvent, "seq" | "tOffsetMs" | "kind">,
706
- reservation?: EventReservation,
707
- ): number | undefined {
708
- return active() ? current!.push({ kind: "terminal", ...ev }, reservation) : undefined;
709
- }
710
-
711
- export function recordTerminalStep(
712
- ev: Omit<TerminalStepEvent, "seq" | "tOffsetMs" | "kind">,
713
- reservation?: EventReservation,
714
- ): number | undefined {
715
- return active() ? current!.push({ kind: "terminal-step", ...ev }, reservation) : undefined;
716
- }
717
-
718
- export function recordFake(
719
- ev: Omit<FakeEvent, "seq" | "tOffsetMs" | "kind">,
720
- reservation?: EventReservation,
721
- ): number | undefined {
722
- return active() ? current!.push({ kind: "fake", ...ev }, reservation) : undefined;
723
- }
724
-
725
- export function recordEnv(
726
- ev: Omit<EnvEvent, "seq" | "tOffsetMs" | "kind">,
727
- reservation?: EventReservation,
728
- ): number | undefined {
729
- return active() ? current!.push({ kind: "env", ...ev }, reservation) : undefined;
730
- }
731
-
732
- export function recordEmail(
733
- ev: Omit<EmailEvent, "seq" | "tOffsetMs" | "kind">,
734
- reservation?: EventReservation,
735
- ): number | undefined {
736
- return active() ? current!.push({ kind: "email", ...ev }, reservation) : undefined;
737
- }
738
-
739
- /**
740
- * Recorded once per `ctx.poll(...)` call. Stands in for the suppressed
741
- * intermediate iterations and gives downstream tagged values
742
- * (`wrap(polledValue, waitSeq)`) a single, stable event to point at —
743
- * assertions on those values then link to the wait, not to one of N
744
- * dropped polls.
745
- */
746
- export interface WaitEvent extends BaseEvent {
747
- kind: "wait";
748
- description: string;
749
- attempts: number;
750
- durationMs: number;
751
- passed: boolean;
752
- /** Set when the predicate threw or the wait timed out. */
753
- error?: string;
754
- }
755
-
756
- export function recordWait(
757
- ev: Omit<WaitEvent, "seq" | "tOffsetMs" | "kind">,
758
- reservation?: EventReservation,
759
- ): number | undefined {
760
- // Use `current` directly (not `active()`) so a `recordWait` at the
761
- // end of a `ctx.poll` block lands even though the surrounding code
762
- // just resumed from `paused`. Pushing this event is the whole point
763
- // of the poll primitive.
764
- return current?.push({ kind: "wait", ...ev }, reservation);
765
- }
766
-
767
- /** Number of events the active recorder has accumulated. Returns 0
768
- * when no recorder is active. */
769
- export function recorderEventCount(): number {
770
- return current?.eventCount() ?? 0;
771
- }
772
-
773
- /** Drop events with index >= `toLen` from the active recorder. */
774
- export function recorderTruncate(toLen: number): void {
775
- current?.truncate(toLen);
776
- }
777
-
778
- /** Stamp `parentSeq` onto every event from `startIdx` onward, so the
779
- * UI groups them under the parent in the timeline. */
780
- export function recorderMarkChildren(
781
- startIdx: number,
782
- parentSeq: number,
783
- ): void {
784
- current?.markChildren(startIdx, parentSeq);
785
- }
786
-
787
- /** Shallow-merge `patch` into the active recorder's event with this
788
- * `seq` (enrich/reclassify after the fact). No-op when nothing is
789
- * recording or no event carries that seq. */
790
- export function recorderAnnotate(
791
- seq: number,
792
- patch: Record<string, unknown>,
793
- ): void {
794
- current?.annotate(seq, patch);
795
- }
796
-
797
- /** Retract the active recorder's event with this `seq` (an instrumentation
798
- * site recorded it, then decided it's noise). No-op when nothing is
799
- * recording or no event carries that seq. */
800
- export function recorderRemove(seq: number): void {
801
- current?.remove(seq);
802
- }
803
-
804
- /** Best-effort JSON-safe deep clone; falls back to `String(v)`. */
805
- export function safeSerialize(v: unknown): unknown {
806
- if (v === undefined) return undefined;
807
- try {
808
- return JSON.parse(JSON.stringify(v));
809
- } catch {
810
- return String(v);
811
- }
812
- }
813
-
814
- export function truncateUtf8(s: string): { value: string; truncated: boolean } {
815
- if (s.length <= OUTPUT_SNIPPET_BYTES) return { value: s, truncated: false };
816
- return { value: s.slice(0, OUTPUT_SNIPPET_BYTES), truncated: true };
817
- }