Skip to content

@trialkit/replay

Record real HTTP replies once, then replay them without network calls or model fees. Pass the returned fetch to your SDK; its request builder and parser still run.

Terminal window
npm install --save-dev @trialkit/replay @trialkit/core

Peer: @trialkit/core; no other dependencies. Node.js 22.23.4+; ESM and CommonJS. The root uses web APIs; @trialkit/replay/node provides file access. The package never patches globals or reads the environment.

import { type Cassette, recordingFetch, replayFetch } from '@trialkit/replay';
import { loadCassette, saveCassette } from '@trialkit/replay/node';
const path = 'cassettes/model.json';
export function recorder(): typeof fetch {
const cassette: Cassette = [];
return recordingFetch(globalThis.fetch, cassette, {
save: () => saveCassette(path, cassette),
});
}
export function replayer(): typeof fetch {
return replayFetch(loadCassette(path), { hint: 'Record the cassette again.' });
}
  • Record and replay with the same base URL. Label replayed runs separately from real runs.
  • Review cassette diffs for secrets before committing; request and response bodies are stored.
  • See the recording guide.
Export Contract
recordingFetch(fetch, cassette, options?) Returns a fetch wrapper; supply the real fetch and a Cassette, or [] for a new recording. Use one wrapper for all clients sharing a cassette and do not mutate it while in use.
replayFetch(cassette, options?) Returns a network-free fetch; reads the cassette at creation, so later changes are not reflected.
Cassette / CassetteEntry JSON array of unique requests, each with at least one recorded response.
CassetteRequest method, absolute url, optional matched headers, and either JSON body, text text, or neither.
CassetteResponse status 200–299 except 204/205, with JSON body or stream headers and chunks.
RecordingOptions / ReplayOptions Options below.
loadCassette(path) From @trialkit/replay/node; synchronously reads and validates JSON, allowing a BOM. Missing or invalid files throw.
saveCassette(path, cassette) From @trialkit/replay/node; validates, makes parent directories, and atomically replaces the file with two-space JSON and a final newline. A failed write leaves the old cassette intact.
Option Default Meaning
matchHeaders [] Both wrappers: case-insensitive request header names to match and store; authorization, proxy-authorization, x-api-key, api-key, and cookie are refused.
redactQuery [] Both wrappers: replace named query values with REDACTED in the cassette; use the same names for record and replay.
mode 'record' Recording only: 'record' always calls the supplied fetch; 'auto' replays hits and records network misses.
save None Recording only: callback with the changed cassette; JSON waits before fetch resolves, streams wait at their final read.
hint None Replay only: non-empty text appended to a miss message.
Part Rule
Method Uppercase comparison.
URL Absolute; host is lowercase, default port, fragment and credentials are removed, query sorted by name with repeated values in order. Scheme, host, port, path and non-redacted query values count.
Body JSON uses canonical JSON; non-JSON text matches exactly; no body matches only no body. JSON with lone surrogates or nesting over 500 levels is treated as text.
Headers Ignored unless named in matchHeaders.

Requests accept a string, URL, or Request plus fetch init; bodies can be strings, URLSearchParams, or UTF-8 bytes. Multipart, FormData, Blob, streams, iterables, and non-UTF-8 bytes are refused before network access. A query parameter named key, api_key, token, access_token, or sig is refused unless named in redactQuery (case, _, and - do not count). Send credentials in headers, not bodies; do not record token-fetch responses.

The recorder keeps only 2xx valid JSON without a non-null error member, or SSE, NDJSON, and JSON-sequence streams. It returns JSON unchanged; for streams it reads a clone and retains status, only content-type, and text chunks. Other responses are not recorded. Concurrent save calls can overlap; a save error rejects the JSON fetch or the final stream read.

Replay cycles through each request’s recorded responses in order, with independent counters per wrapper. JSON replies use the recorded status and body with content-type: application/json; streams retain status, headers and chunks without timing delays. A pre-aborted signal rejects. A miss returns 404 JSON { "error": { "message": "..." } } with request details, recording advice and optional hint. SDKs that throw on 404 produce an infrastructure error; plain fetch callers must check response.ok and throw infrastructureError themselves.

JSON is parsed as JavaScript numbers and serialized again: whitespace and numeric spelling can change, large integers lose precision, -0 becomes 0, and overflow such as 1e400 serializes as null. The same parsing affects request matching and saved cassettes.

Invalid arguments, options, cassette fields, or duplicate equivalent requests throw a TypeError naming the problem. Request-read errors reject before a real call; file operations also propagate filesystem errors. Use a stable placeholder base URL and forward to the real host in the supplied fetch if a host differs between machines.

In auto mode, concurrent identical misses each call the network; their responses are appended in arrival order. Replays have no original response URL or redirect history, and JSON replays omit provider headers such as request ids. Stream error events are recorded as stream content, so review them before saving a cassette for CI. A consumed Request rejects before network access with the runtime’s request-read error.