@crvouga/mockingbird-service-redis 2.6.0 → 2.8.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.
package/dist/index.d.ts CHANGED
@@ -86,6 +86,7 @@ interface Session {
86
86
  multi: Array<{
87
87
  name: string;
88
88
  args: Uint8Array[];
89
+ raw?: string;
89
90
  }> | null;
90
91
  multiFailed: boolean;
91
92
  watching: Array<{
@@ -98,6 +99,12 @@ interface Session {
98
99
  dead: boolean;
99
100
  quit: boolean;
100
101
  inExec: boolean;
102
+ /** Port of the RESP listener this session arrived on, for INFO and CLIENT INFO. */
103
+ localPort?: number | undefined;
104
+ /** `host:port` of the client socket, shown on the MONITOR stream. */
105
+ remoteAddr?: string | undefined;
106
+ /** True after MONITOR: the connection receives every command other clients run. */
107
+ monitor?: boolean;
101
108
  onPush: (reply: Reply) => void;
102
109
  }
103
110
  declare class Redis {
@@ -121,6 +128,9 @@ declare class Redis {
121
128
  private invoked;
122
129
  private scriptDepth;
123
130
  private commandCount;
131
+ private readonly commandStats;
132
+ private peakMemory;
133
+ private startedAt;
124
134
  private closed;
125
135
  private controlPaused;
126
136
  private pendingCommands;
@@ -164,7 +174,20 @@ declare class Redis {
164
174
  private random;
165
175
  private memory;
166
176
  private dispatch;
177
+ /** What a MONITOR connection may not run: Redis treats it like a replica link. */
178
+ private touchesKeyspace;
179
+ /**
180
+ * Runs one command and shows it to MONITOR connections. `raw` is the name as the client typed
181
+ * it, which is what Redis prints. EVAL is shown before the script's own calls (origin `lua`);
182
+ * everything else after it ran, so SELECT shows the new database. Commands Redis refuses
183
+ * before running them (unknown, wrong arity, NOAUTH, queued in MULTI) are not shown.
184
+ */
167
185
  private execCmd;
186
+ private monitoring;
187
+ private feedMonitors;
188
+ private execCommand;
189
+ private readonly extraHost;
190
+ private aclUsers;
168
191
  private guardWrite;
169
192
  private cmdPing;
170
193
  private cmdAuth;
@@ -173,6 +196,10 @@ declare class Redis {
173
196
  private cmdReset;
174
197
  private cmdClient;
175
198
  private clientInfo;
199
+ /**
200
+ * INFO. Sections and field names follow Redis 7.2; values the emulator has no process behind
201
+ * (CPU time, RSS, system memory) are fixed nominal numbers so parsers get well-formed fields.
202
+ */
176
203
  private info;
177
204
  private keyspaceLines;
178
205
  private cmdTime;
@@ -189,7 +216,13 @@ declare class Redis {
189
216
  private cmdPersist;
190
217
  private stringAt;
191
218
  private cmdGet;
219
+ /**
220
+ * SET and its aliases. `command` names the caller in the expire-time error, as Redis does.
221
+ * Options are parsed first and the expiry is validated after, like Redis, so a bad
222
+ * expiry is rejected before NX/XX are considered and leaves any existing value alone.
223
+ */
192
224
  private cmdSet;
225
+ private cmdSetnx;
193
226
  private cmdMget;
194
227
  private cmdMset;
195
228
  private cmdAppend;
@@ -239,6 +272,7 @@ declare class Redis {
239
272
  private cmdEval;
240
273
  private cmdScript;
241
274
  private runScript;
275
+ /** `redis.call` (`raise`) and `redis.pcall`: run one command for the script and convert its reply. */
242
276
  private luaDispatch;
243
277
  private block;
244
278
  private wake;
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  encodeReply,
10
10
  manualClock,
11
11
  wallClock
12
- } from "./chunk-Z3XQGVTX.js";
12
+ } from "./chunk-TVELGGZ4.js";
13
13
  export {
14
14
  Redis,
15
15
  RedisClient,
package/dist/server.d.ts CHANGED
@@ -56,6 +56,15 @@ type FaultRule = {
56
56
  requestHeaders?: Record<string, string>;
57
57
  /** Fault only requests carrying these query parameters. `"*"` matches any value. */
58
58
  query?: Record<string, string>;
59
+ /**
60
+ * Fault only requests whose JSON body carries these fields. Each key is a dotted path into
61
+ * the parsed body (`"patient_details.email"`; a number steps into an array, `"items.0.sku"`)
62
+ * and each value is what the field must equal: a string, number, boolean or `null`, compared
63
+ * strictly (`3` is not `"3"`). `"*"` matches any value that is present. A request whose body
64
+ * is missing, is not JSON, or is not a JSON object never matches. Not `body`, which is the
65
+ * response a rule injects.
66
+ */
67
+ requestBody?: Record<string, RequestBodyValue>;
59
68
  /**
60
69
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
61
70
  * an in-process caller usually wants, and what a parallel worker usually does not:
@@ -122,6 +131,8 @@ type FaultRule = {
122
131
  /** The preset this rule was expanded from, if any. */
123
132
  fromPreset?: string;
124
133
  };
134
+ /** What a field of the request body must equal in {@link FaultRule.requestBody}. */
135
+ type RequestBodyValue = string | number | boolean | null;
125
136
 
126
137
  /**
127
138
  * The admin controls every mock shares, as one document.
@@ -309,6 +320,13 @@ type ConfigService = {
309
320
  adminPrefix?: string;
310
321
  adminKey?: string;
311
322
  seed?: string;
323
+ /**
324
+ * Where this service's generated ids start: a non-negative integer or `"boot"` (derived from
325
+ * the clock). Replaces the fleet-wide `idBase`. Default: the same ids on every boot.
326
+ */
327
+ idBase?: number | string;
328
+ /** Boot settings, checked by the service's settings schema; every namespace starts from them. */
329
+ settings?: Record<string, unknown>;
312
330
  /** Admin controls this service boots with. A key given here replaces the fleet-wide one. */
313
331
  adminControls?: MockControls;
314
332
  fixtures?: Record<string, unknown>;
@@ -400,6 +418,7 @@ interface Session {
400
418
  multi: Array<{
401
419
  name: string;
402
420
  args: Uint8Array[];
421
+ raw?: string;
403
422
  }> | null;
404
423
  multiFailed: boolean;
405
424
  watching: Array<{
@@ -412,6 +431,12 @@ interface Session {
412
431
  dead: boolean;
413
432
  quit: boolean;
414
433
  inExec: boolean;
434
+ /** Port of the RESP listener this session arrived on, for INFO and CLIENT INFO. */
435
+ localPort?: number | undefined;
436
+ /** `host:port` of the client socket, shown on the MONITOR stream. */
437
+ remoteAddr?: string | undefined;
438
+ /** True after MONITOR: the connection receives every command other clients run. */
439
+ monitor?: boolean;
415
440
  onPush: (reply: Reply) => void;
416
441
  }
417
442
  declare class Redis {
@@ -435,6 +460,9 @@ declare class Redis {
435
460
  private invoked;
436
461
  private scriptDepth;
437
462
  private commandCount;
463
+ private readonly commandStats;
464
+ private peakMemory;
465
+ private startedAt;
438
466
  private closed;
439
467
  private controlPaused;
440
468
  private pendingCommands;
@@ -478,7 +506,20 @@ declare class Redis {
478
506
  private random;
479
507
  private memory;
480
508
  private dispatch;
509
+ /** What a MONITOR connection may not run: Redis treats it like a replica link. */
510
+ private touchesKeyspace;
511
+ /**
512
+ * Runs one command and shows it to MONITOR connections. `raw` is the name as the client typed
513
+ * it, which is what Redis prints. EVAL is shown before the script's own calls (origin `lua`);
514
+ * everything else after it ran, so SELECT shows the new database. Commands Redis refuses
515
+ * before running them (unknown, wrong arity, NOAUTH, queued in MULTI) are not shown.
516
+ */
481
517
  private execCmd;
518
+ private monitoring;
519
+ private feedMonitors;
520
+ private execCommand;
521
+ private readonly extraHost;
522
+ private aclUsers;
482
523
  private guardWrite;
483
524
  private cmdPing;
484
525
  private cmdAuth;
@@ -487,6 +528,10 @@ declare class Redis {
487
528
  private cmdReset;
488
529
  private cmdClient;
489
530
  private clientInfo;
531
+ /**
532
+ * INFO. Sections and field names follow Redis 7.2; values the emulator has no process behind
533
+ * (CPU time, RSS, system memory) are fixed nominal numbers so parsers get well-formed fields.
534
+ */
490
535
  private info;
491
536
  private keyspaceLines;
492
537
  private cmdTime;
@@ -503,7 +548,13 @@ declare class Redis {
503
548
  private cmdPersist;
504
549
  private stringAt;
505
550
  private cmdGet;
551
+ /**
552
+ * SET and its aliases. `command` names the caller in the expire-time error, as Redis does.
553
+ * Options are parsed first and the expiry is validated after, like Redis, so a bad
554
+ * expiry is rejected before NX/XX are considered and leaves any existing value alone.
555
+ */
506
556
  private cmdSet;
557
+ private cmdSetnx;
507
558
  private cmdMget;
508
559
  private cmdMset;
509
560
  private cmdAppend;
@@ -553,6 +604,7 @@ declare class Redis {
553
604
  private cmdEval;
554
605
  private cmdScript;
555
606
  private runScript;
607
+ /** `redis.call` (`raise`) and `redis.pcall`: run one command for the script and convert its reply. */
556
608
  private luaDispatch;
557
609
  private block;
558
610
  private wake;
package/dist/server.js CHANGED
@@ -2,8 +2,8 @@ import {
2
2
  DEFAULT_PORT,
3
3
  serve,
4
4
  serveTarget
5
- } from "./chunk-LHUY4G3I.js";
6
- import "./chunk-Z3XQGVTX.js";
5
+ } from "./chunk-55PZE5Z4.js";
6
+ import "./chunk-TVELGGZ4.js";
7
7
  export {
8
8
  DEFAULT_PORT,
9
9
  serve,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/mockingbird-service-redis",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "In-process Redis RESP server for tests: strings, hashes, lists, sets, sorted sets, streams, transactions, pub/sub, and a Lua subset, with an injected clock. Not an HTTP emulator.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -94,8 +94,5 @@
94
94
  "bullmq": "5.67.1",
95
95
  "ioredis": "5.11.1",
96
96
  "ioredis-5-9": "npm:ioredis@5.9.2"
97
- },
98
- "dependencies": {
99
- "@msgpack/msgpack": "3.1.2"
100
97
  }
101
98
  }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/server.ts", "../../core/src/clock.ts", "../../core/src/controls.ts", "../../core/src/control.ts", "../../core/src/outbound.ts"],
4
- "sourcesContent": ["import { createConnection, createServer, type Server, type Socket } from \"node:net\"\nimport type { ConfigService, FleetChild } from \"@crvouga/mockingbird-adapter-node\"\nimport {\n matchNamespacePath,\n normalizeBootControls,\n resolveAdminPrefix,\n} from \"@crvouga/mockingbird-service\"\nimport { createRedis, type Redis, RedisConnectionError } from \"./engine.ts\"\nimport { asCommand, encodeReply, type Reply, RespParser } from \"./protocol.ts\"\n\n/** HTTP port for `serve --config`. The RESP socket binds an ephemeral port. */\nexport const DEFAULT_PORT = 8827\n\nexport interface ServeOptions {\n port?: number\n host?: string\n admit?: () => boolean\n closeEngine?: boolean\n controlPrivileged?: boolean\n}\n\nexport interface RedisListening {\n readonly listening: boolean\n host: string\n port: number\n close(): Promise<void>\n}\n\nexport function serve(redis: Redis, options: ServeOptions = {}): Promise<RedisListening> {\n const host = options.host ?? \"127.0.0.1\"\n const port = options.port ?? 6379\n const sockets = new Set<Socket>()\n const server = createServer({ keepAlive: true }, (socket) => {\n if (options.admit && !options.admit()) {\n socket.destroy()\n return\n }\n sockets.add(socket)\n attach(redis, socket, () => sockets.delete(socket), options.controlPrivileged ?? false)\n })\n return new Promise((resolve, reject) => {\n const fail = (error: Error) => reject(error)\n server.once(\"error\", fail)\n server.listen(port, host, () => {\n server.off(\"error\", fail)\n const address = server.address()\n const actual = address && typeof address === \"object\" ? address.port : port\n resolve({\n get listening() {\n return server.listening\n },\n host,\n port: actual,\n close: () => shutdown(server, sockets, redis, options.closeEngine !== false),\n })\n })\n })\n}\n\nfunction attach(redis: Redis, socket: Socket, onGone: () => void, controlPrivileged = false): void {\n const session = redis.createSession()\n session.controlPrivileged = controlPrivileged\n const parser = new RespParser()\n const pending: Array<{ name: string; args: Uint8Array[] }> = []\n let pumping = false\n const write = (reply: Reply) => {\n if (!socket.destroyed) socket.write(encodeReply(reply, session.protocol))\n }\n session.onPush = write\n const stop = redis.onDisconnect((dropped) => {\n if (dropped === session) socket.destroy()\n })\n const finish = () => {\n redis.disconnect(session)\n stop()\n onGone()\n }\n socket.on(\"data\", (chunk: Uint8Array) => {\n for (const reply of parser.push(chunk)) {\n const command = asCommand(reply)\n if (\"t\" in command) {\n write(command)\n continue\n }\n pending.push(command)\n }\n void pump()\n })\n const pump = async () => {\n if (pumping) return\n pumping = true\n try {\n while (pending.length > 0) {\n const command = pending.shift()\n if (!command) break\n try {\n const reply = await redis.perform(session, command.name, command.args)\n write(reply)\n if (session.quit) {\n socket.end()\n break\n }\n } catch (error) {\n if (error instanceof RedisConnectionError) {\n socket.destroy()\n break\n }\n socket.destroy()\n break\n }\n }\n } finally {\n pumping = false\n if (pending.length > 0 && !socket.destroyed) void pump()\n }\n }\n socket.on(\"close\", finish)\n socket.on(\"error\", finish)\n}\n\nfunction shutdown(\n server: Server,\n sockets: Set<Socket>,\n redis: Redis,\n closeEngine = true,\n): Promise<void> {\n if (closeEngine) redis.close()\n for (const socket of sockets) socket.destroy()\n return new Promise((resolve) => {\n server.close(() => resolve())\n })\n}\n\ntype FleetRuntime = {\n fetch(request: Request): Promise<Response>\n respPort: number\n close(): Promise<void>\n}\n\nconst isHealth = (pathname: string, adminPrefix: string): boolean => {\n const path = pathname.replace(/\\/+$/, \"\") || \"/\"\n return (\n path === `${adminPrefix}/health` ||\n matchNamespacePath(path, adminPrefix)?.[2] === `${adminPrefix}/health`\n )\n}\n\n/**\n * Fleet entry for `serve --config`. HTTP `GET /__admin/health` reports `service: redis`.\n * RESP listens on an ephemeral port named in the startup banner.\n */\nexport const serveTarget = {\n name: \"redis\",\n protocol: \"redis\" as const,\n defaultPort: 6379,\n start: startProtocol,\n async create(\n _values: unknown = {},\n common: { adminPrefix?: string } = {},\n ): Promise<FleetRuntime> {\n const redis = createRedis()\n const tcp = await serve(redis, { host: \"127.0.0.1\", port: 0 })\n const runtime: FleetRuntime = {\n respPort: tcp.port,\n close: () => tcp.close(),\n fetch: async (request: Request) => {\n if (\n request.method === \"GET\" &&\n isHealth(new URL(request.url).pathname, resolveAdminPrefix(common.adminPrefix))\n ) {\n return Response.json({ status: \"ok\", service: \"redis\" })\n }\n return new Response(\"not found\", { status: 404 })\n },\n }\n return runtime\n },\n banner(runtime: FleetRuntime) {\n return [`resp: redis://127.0.0.1:${runtime.respPort}`]\n },\n}\n\n/** Each fleet namespace owns a listener and an engine; Redis SELECT retains vendor semantics. */\nasync function startProtocol(entry: ConfigService): Promise<FleetChild> {\n const namespaces = new Map<string, { redis: Redis; listener: RedisListening; database: number }>()\n const selectors = { default: 0, ...entry.namespaces }\n if (\n entry.seed !== undefined &&\n (!String(entry.seed).trim() || !Number.isFinite(Number(entry.seed)))\n )\n throw new Error(\"Redis seed must be a finite number\")\n let admission: ((namespace: string) => boolean) | undefined\n const boot = normalizeBootControls(entry.adminControls)\n const create = async (name: string, database: number, port = 0) => {\n if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name)) throw new Error(\"invalid Redis namespace\")\n if (!Number.isInteger(database) || database < 0 || database > 15)\n throw new Error(\"invalid Redis database index\")\n const redis = createRedis({\n ...(entry.password !== undefined ? { password: entry.password } : {}),\n ...(entry.seed !== undefined ? { seed: Number(entry.seed) } : {}),\n })\n const control = { ...boot.shared.clock, ...boot.namespaces[name]?.clock }\n if (control.frozen) redis.clock.freeze()\n if (control.now !== undefined) redis.clock.set(control.now)\n const listener = await serve(redis, {\n host: entry.host ?? \"127.0.0.1\",\n port,\n admit: () => admission?.(name) !== false,\n })\n namespaces.set(name, { redis, listener, database })\n }\n try {\n for (const [name, database] of Object.entries(selectors))\n await create(name, database as number, name === \"default\" ? (entry.port ?? 6379) : 0)\n } catch (error) {\n await Promise.allSettled([...namespaces.values()].map(({ listener }) => listener.close()))\n throw error\n }\n const get = (name: string) => {\n const found = namespaces.get(name)\n if (!found) throw new Error(`Redis namespace ${name} is not configured`)\n return found\n }\n const url = (name: string, privateUrl = false) => {\n const { listener, database } = get(name)\n const host = listener.host.includes(\":\") ? `[${listener.host}]` : listener.host\n const auth =\n privateUrl && entry.password !== undefined ? `:${encodeURIComponent(entry.password)}@` : \"\"\n return `redis://${auth}${host}:${listener.port}/${database}`\n }\n return {\n protocol: \"redis\",\n url: url(\"default\"),\n connection: url(\"default\", true),\n get connections() {\n return Object.fromEntries([...namespaces.keys()].map((name) => [name, url(name, true)]))\n },\n get namespaces() {\n return {\n mechanism: \"endpoint\",\n endpoints: Object.fromEntries([...namespaces.keys()].map((name) => [name, url(name)])),\n }\n },\n async createNamespace(name) {\n if (namespaces.has(name)) throw new Error(\"namespace already exists\")\n await create(name, 0)\n },\n async deleteNamespace(name) {\n const { redis, listener } = get(name)\n if (\n redis.activeCommands() ||\n redis.waiterCount() ||\n redis.activeJobs() ||\n redis.connections()\n )\n throw new Error(\"Redis namespace has active clients or work\")\n await listener.close()\n namespaces.delete(name)\n },\n async exportCheckpoint(name, point) {\n return get(name).redis.exportSnapshot(point)\n },\n async importCheckpoint(name, document) {\n return (namespaces.get(name) ?? get(\"default\")).redis.importSnapshot(document)\n },\n async inspect(name, { offset, limit, collection }) {\n const { redis, database } = get(name)\n const keys = redis.inspect(database)\n return {\n total: keys.length,\n keys: keys\n .filter((key) => collection === undefined || key.key === collection)\n .slice(offset, offset + limit),\n pendingJobs: redis.pendingJobs(),\n activeJobs: redis.activeJobs(),\n }\n },\n async initializationAccess() {\n const listeners: RedisListening[] = []\n const connections: Record<string, string> = {}\n try {\n for (const [name, { redis, database }] of namespaces) {\n const seed = await serve(redis, {\n port: 0,\n host: \"127.0.0.1\",\n closeEngine: false,\n controlPrivileged: true,\n })\n listeners.push(seed)\n connections[name] =\n `redis://${entry.password ? `:${encodeURIComponent(entry.password)}@` : \"\"}127.0.0.1:${seed.port}/${database}`\n }\n } catch (error) {\n await Promise.allSettled(listeners.map((l) => l.close()))\n throw error\n }\n return {\n connections,\n close: async () => {\n await Promise.all(listeners.map((l) => l.close()))\n },\n }\n },\n setAdmission(allow) {\n admission = allow\n },\n async ready() {\n if (admission) return [...namespaces.values()].every(({ listener }) => listener.listening)\n const ready = (\n await Promise.all(\n [...namespaces.values()].map(({ listener, database }) =>\n probe(listener, database, entry.password),\n ),\n )\n ).every(Boolean)\n const deadline = Date.now() + 2000\n while (\n [...namespaces.values()].some(({ redis }) => redis.connections() > 0) &&\n Date.now() < deadline\n )\n await new Promise((resolve) => setTimeout(resolve, 1))\n return ready\n },\n async close() {\n await Promise.all([...namespaces.values()].map(({ listener }) => listener.close()))\n },\n lock: (name) => get(name).redis.fence(),\n diagnostics(name) {\n const { redis } = get(name)\n return {\n activeRequests: redis.activeCommands(),\n activeConnections: redis.connections(),\n blockedCommands: redis.waiterCount(),\n pendingJobs: redis.pendingJobs(),\n activeJobs: redis.activeJobs(),\n pendingWebhooks: 0,\n unmatchedRequests: 0,\n }\n },\n async checkpoint(name) {\n return get(name).redis.snapshot()\n },\n async restore(name, point) {\n get(name).redis.restore(point)\n },\n async reset(name) {\n const { redis } = get(name)\n redis.reset()\n const control = { ...boot.shared.clock, ...boot.namespaces[name]?.clock }\n if (control.frozen) redis.clock.freeze()\n if (control.now !== undefined) redis.clock.set(control.now)\n },\n nextEvent: (name) => get(name).redis.nextEvent(),\n async settle(name) {\n get(name).redis.settleTimers()\n },\n clock: (name) => get(name).redis.clock,\n }\n}\n\n/** Readiness checks the actual RESP listener, including configured authentication and SELECT. */\nfunction probe(\n listener: RedisListening,\n database: number,\n password: string | undefined,\n): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ host: listener.host, port: listener.port })\n const parser = new RespParser()\n const commands = [\n ...(password !== undefined ? [[\"AUTH\", password]] : []),\n [\"SELECT\", String(database)],\n [\"PING\"],\n ]\n const expected = commands.map((command) => (command[0] === \"PING\" ? \"PONG\" : \"OK\"))\n let result = false\n const finish = (ok: boolean) => {\n result = ok\n socket.destroy()\n }\n const timeout = setTimeout(() => finish(false), 2000)\n socket.once(\"close\", () => {\n clearTimeout(timeout)\n resolve(result)\n })\n socket.on(\"error\", () => finish(false))\n socket.once(\"connect\", () => {\n for (const command of commands)\n socket.write(\n `*${command.length}\\r\\n${command.map((arg) => `$${Buffer.byteLength(arg)}\\r\\n${arg}\\r\\n`).join(\"\")}`,\n )\n })\n socket.on(\"data\", (data) => {\n try {\n for (const reply of parser.push(data)) {\n if (reply.t !== \"simple\" || reply.v !== expected.shift()) {\n finish(false)\n return\n }\n if (expected.length === 0) {\n finish(true)\n return\n }\n }\n } catch {\n finish(false)\n }\n })\n })\n}\n", "/**\n * The single source of time for a service.\n *\n * Every timestamp a mock writes reads from here, so a suite moves time instead of\n * sleeping: appointment windows, result delays and expiries become reachable in\n * milliseconds. A frozen clock also makes timestamps reproducible from a seed.\n */\nexport type ClockState = {\n /** Current epoch milliseconds. */\n now: number\n /** True while time does not advance on its own. */\n frozen: boolean\n /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */\n offsetMs: number\n}\n\nexport type Clock = {\n now(): number\n /** Pin the clock to an exact instant, keeping it frozen if it already was. */\n set(epochMs: number): void\n /** Move the clock forward, or back with a negative delta. */\n advance(deltaMs: number): void\n /** Stop time at the current instant. */\n freeze(): void\n /** Resume from the current instant. */\n unfreeze(): void\n /** Drop back to the underlying source, live. */\n reset(): void\n state(): ClockState\n}\n\n/** A {@link Clock} over `source` (default `Date.now`), live and unfrozen. */\nexport const createClock = (source: () => number = Date.now): Clock => {\n let offsetMs = 0\n let frozenAt: number | undefined\n const now = () => frozenAt ?? source() + offsetMs\n return {\n now,\n set: (epochMs) => {\n if (frozenAt !== undefined) frozenAt = epochMs\n else offsetMs = epochMs - source()\n },\n advance: (deltaMs) => {\n if (frozenAt !== undefined) frozenAt += deltaMs\n else offsetMs += deltaMs\n },\n freeze: () => {\n frozenAt = now()\n },\n unfreeze: () => {\n if (frozenAt === undefined) return\n offsetMs = frozenAt - source()\n frozenAt = undefined\n },\n reset: () => {\n offsetMs = 0\n frozenAt = undefined\n },\n // A frozen clock does not follow its source, so it has no offset to report.\n state: () => ({\n now: now(),\n frozen: frozenAt !== undefined,\n offsetMs: frozenAt !== undefined ? 0 : offsetMs,\n }),\n }\n}\n\n/** A clock over a base clock, which can tell its own freeze from the base's. */\nexport type DerivedClock = Clock & {\n /** True while this clock itself is frozen, and so no longer follows the base. */\n pinned(): boolean\n /** Put the clock at an instant: pinned there, or following the base from there. */\n place(state: { now: number; pinned: boolean }): void\n}\n\n/**\n * A clock that follows `base` \u2014 its time, its freezes, its jumps \u2014 plus an offset and a\n * freeze of its own. Moving it never moves `base`, so a namespace can travel in time alone.\n * It reports `frozen` while either clock is, and no offset while it stands still. `moved` is\n * called after anything moves it, for whatever keeps a schedule by this clock.\n */\nexport const deriveClock = (base: Clock, moved: () => void = () => {}): DerivedClock => {\n const own = createClock(() => base.now())\n /** Tell whoever is driven by this clock that its time is no longer what it was. */\n const moving =\n <A extends unknown[]>(change: (...args: A) => void) =>\n (...args: A): void => {\n change(...args)\n moved()\n }\n return {\n ...own,\n set: moving(own.set),\n advance: moving(own.advance),\n reset: moving(own.reset),\n state: () => {\n const state = own.state()\n const frozen = state.frozen || base.state().frozen\n return { now: state.now, frozen, offsetMs: frozen ? 0 : state.offsetMs }\n },\n pinned: () => own.state().frozen,\n place: moving(({ now, pinned }) => {\n own.reset()\n // Frozen first, so the instant is set exactly instead of read back from the base.\n if (pinned) own.freeze()\n own.set(now)\n }),\n }\n}\n\n/**\n * Put a clock at an instant, frozen or running. Frozen first, so the instant is set exactly:\n * setting a live clock and freezing it afterwards reads the source again and can land a tick late.\n */\nexport const restoreClock = (clock: Clock, state: { now: number; frozen: boolean }): void => {\n clock.freeze()\n clock.set(state.now)\n if (!state.frozen) clock.unfreeze()\n}\n", "import type { FaultRule } from \"./faults.js\"\n\n/**\n * The admin controls every mock shares, as one document.\n *\n * The same shape is accepted in three places, and means the same thing in each:\n *\n * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,\n * `MOCKINGBIRD_ADMIN_CONTROLS`\n * - over HTTP: `PUT /__admin/controls`\n * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}\n *\n * Every control is deterministic: given the same seed, clock and requests, a mock answers\n * the same bytes. Nothing here reads the wall clock or `Math.random`.\n */\n\n/** Milliseconds, or a string like `\"250ms\"`, `\"2s\"`, `\"15m\"`, `\"1h\"`, `\"3d\"`. */\nexport type Duration = number | string\n/** Epoch milliseconds, or an ISO-8601 string. */\nexport type Instant = number | string\n\n/** A control that cannot be applied: a bad value, an unknown key, a missing snapshot. */\nexport class ControlError extends RangeError {\n constructor(message: string) {\n super(message)\n this.name = \"ControlError\"\n }\n}\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n}\n\n/** Milliseconds from a number, a numeric string, or a duration like `\"90s\"`, `\"15m\"`, `\"2h\"`. */\nexport const parseDuration = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined\n if (typeof value !== \"string\") return undefined\n const match = /^(-?\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)?$/.exec(value.trim())\n if (!match) return undefined\n return Number(match[1]) * (UNITS[match[2] ?? \"ms\"] as number)\n}\n\n/** Epoch milliseconds from a number, a string of digits, or an ISO-8601 string. */\nexport const parseInstant = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined\n if (typeof value !== \"string\") return undefined\n const text = value.trim()\n if (/^-?\\d+$/.test(text)) return Number(text)\n const parsed = Date.parse(text)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\n/** {@link parseDuration}, or a {@link ControlError} naming `label`. Negative only when allowed. */\nexport const durationMs = (value: unknown, label: string, negative = false): number => {\n const parsed = parseDuration(value)\n if (parsed === undefined)\n throw new ControlError(`${label}: expected milliseconds or a duration like \"250ms\" or \"15m\"`)\n if (!negative && parsed < 0) throw new ControlError(`${label}: must not be negative`)\n return parsed\n}\n\n/** {@link parseInstant}, or a {@link ControlError} naming `label`. */\nexport const instantMs = (value: unknown, label: string): number => {\n const parsed = parseInstant(value)\n if (parsed === undefined) throw new ControlError(`${label}: expected epoch ms or ISO-8601`)\n return parsed\n}\n\n/** A string of digits is that number, so `--seed 7`, `{\"seed\": 7}` and a header agree. */\nexport const normalizeSeed = (seed: unknown, label = \"seed\"): number | string => {\n if (typeof seed === \"number\" && Number.isFinite(seed)) return seed\n if (typeof seed === \"string\" && seed !== \"\") return /^\\d+$/.test(seed) ? Number(seed) : seed\n throw new ControlError(`${label}: expected a number or a non-empty string`)\n}\n\nexport type ClockControls = {\n /** Move the clock to this instant. */\n now?: Instant\n /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */\n frozen?: boolean\n /**\n * Step the clock forward by this much before every vendor request. With a frozen clock\n * each request still gets its own, reproducible timestamp.\n */\n autoAdvance?: Duration\n}\n\n/** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */\nexport type LatencyRuleInput = { delay?: Duration; jitter?: Duration }\n\nexport type LatencyControls = LatencyRuleInput & {\n /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */\n operations?: Record<string, Duration | LatencyRuleInput>\n}\n\n/** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */\nexport type FaultInput =\n | (Omit<FaultRule, \"id\"> & { id?: string })\n | ({ preset: string } & Partial<FaultRule>)\n\n/** Identifies a {@link SnapshotDocument}. */\nexport const SNAPSHOT_FORMAT = \"mockingbird.snapshot/v1\"\n\n/**\n * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what\n * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and\n * `records` are required, so a hand-written seed file is a valid snapshot.\n */\nexport type SnapshotDocument = {\n format: typeof SNAPSHOT_FORMAT\n /** The service that wrote it. A snapshot is rejected by any other service. */\n service?: string\n /**\n * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is\n * the stored text of a row that is not a plain record, and replaces `value` when present.\n */\n records: { collection: string; id: string; seq?: number; value?: unknown; raw?: string }[]\n /** Id counters, so the next generated id continues where the snapshot left off. */\n sequences?: { name: string; kind: string; value: number }[]\n clock?: { now: number; frozen: boolean; autoAdvanceMs?: number }\n seed?: number | string\n /** Positions of the seeded random streams. */\n rng?: { state: number; faults?: number; latency?: number }\n faults?: unknown\n latency?: unknown\n virtualTime?: boolean\n /** Quiescent webhook endpoints, delivery history and fault state. Contains private configuration. */\n webhooks?: unknown\n}\n\n/** Controls for one namespace. */\nexport type NamespaceControls = {\n /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */\n seed?: number | string\n clock?: ClockControls\n /**\n * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the\n * wall clock: the request returns at once, the clock has moved, and the journal records\n * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.\n */\n virtualTime?: boolean\n /** Baseline response time for every vendor request. A bare duration is its `delay`. */\n latency?: Duration | LatencyControls\n faults?: readonly FaultInput[]\n /** Start from this state instead of the service's own seed data. */\n snapshot?: SnapshotDocument\n}\n\n/** {@link NamespaceControls} for every namespace, with per-namespace overrides. */\nexport type MockControls = NamespaceControls & {\n /** Vendor credential \u2192 namespace, for SDKs that cannot send a namespace header. */\n credentials?: Record<string, string>\n /** Overrides for named namespaces. A key given here replaces the shared value. */\n namespaces?: Record<string, NamespaceControls>\n}\n\nconst NAMESPACE_KEYS = new Set([\"seed\", \"clock\", \"virtualTime\", \"latency\", \"faults\", \"snapshot\"])\nconst MOCK_KEYS = new Set([...NAMESPACE_KEYS, \"credentials\", \"namespaces\"])\n/**\n * What `GET /__admin/controls` reports beside the controls themselves. Accepted and ignored,\n * so what was read from one namespace can be applied to another as it is.\n */\nconst REPORTED_KEYS = new Set([\"namespace\", \"snapshots\"])\nconst REPORTED_CLOCK_KEYS = new Set([\"iso\", \"offsetMs\"])\n\n/** What a namespace, a branch, a snapshot and a fault's namespace may be called. */\nexport const KEY_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst unknownKeys = (\n value: Record<string, unknown>,\n known: Set<string>,\n label: string,\n reported?: Set<string>,\n): void => {\n for (const key of Object.keys(value)) {\n if (!known.has(key) && !reported?.has(key))\n throw new ControlError(\n `${label}: unknown control ${JSON.stringify(key)}; expected ${[...known].join(\", \")}`,\n )\n }\n}\n\n/** A latency rule in milliseconds. */\nexport type LatencyRule = { delayMs: number; jitterMs: number }\n/** Baseline latency for a namespace, normalized. */\nexport type LatencyState = LatencyRule & { operations: Record<string, LatencyRule> }\n\nconst latencyRule = (value: unknown, label: string): LatencyRule => {\n if (!isRecord(value)) return { delayMs: durationMs(value, label), jitterMs: 0 }\n unknownKeys(value, new Set([\"delay\", \"jitter\", \"delayMs\", \"jitterMs\", \"operations\"]), label)\n return {\n delayMs: durationMs(value.delay ?? value.delayMs ?? 0, `${label}.delay`),\n jitterMs: durationMs(value.jitter ?? value.jitterMs ?? 0, `${label}.jitter`),\n }\n}\n\n/** Validate and normalize a `latency` control. */\nexport const normalizeLatency = (value: unknown, label = \"latency\"): LatencyState => {\n const base = latencyRule(value, label)\n const operations: Record<string, LatencyRule> = {}\n if (isRecord(value) && value.operations !== undefined) {\n if (!isRecord(value.operations))\n throw new ControlError(`${label}.operations: expected an object keyed by operationId`)\n for (const [operationId, rule] of Object.entries(value.operations)) {\n if (isRecord(rule) && rule.operations !== undefined)\n throw new ControlError(`${label}.operations.${operationId}: cannot nest operations`)\n operations[operationId] = latencyRule(rule, `${label}.operations.${operationId}`)\n }\n }\n return { ...base, operations }\n}\n\n/** A clock control, normalized. Absent keys leave that part of the clock alone. */\nexport type ClockPlan = { now?: number; frozen?: boolean; autoAdvanceMs?: number }\n\n/** Validate and normalize a `clock` control. Accepts the `POST /clock` spellings too. */\nexport const normalizeClock = (value: unknown, label = \"clock\"): ClockPlan => {\n if (!isRecord(value)) throw new ControlError(`${label}: expected an object`)\n unknownKeys(\n value,\n new Set([\"now\", \"set\", \"frozen\", \"freeze\", \"autoAdvance\", \"autoAdvanceMs\"]),\n label,\n REPORTED_CLOCK_KEYS,\n )\n const plan: ClockPlan = {}\n const now = value.now ?? value.set\n if (now !== undefined) plan.now = instantMs(now, `${label}.now`)\n const frozen = value.frozen ?? value.freeze\n if (frozen !== undefined) {\n if (typeof frozen !== \"boolean\") throw new ControlError(`${label}.frozen: expected a boolean`)\n plan.frozen = frozen\n }\n const auto = value.autoAdvance ?? value.autoAdvanceMs\n if (auto !== undefined) plan.autoAdvanceMs = durationMs(auto, `${label}.autoAdvance`)\n return plan\n}\n\n/** {@link NamespaceControls} with every value checked and every duration in milliseconds. */\nexport type ControlPlan = {\n seed?: number | string\n clock?: ClockPlan\n virtualTime?: boolean\n latency?: LatencyState\n faults?: readonly FaultInput[]\n snapshot?: SnapshotDocument\n}\n\n/** Check a snapshot document's shape. The runtime checks `service` when it restores one. */\nexport const assertSnapshotDocument = (value: unknown, label = \"snapshot\"): SnapshotDocument => {\n if (!isRecord(value)) throw new ControlError(`${label}: expected a snapshot document`)\n if (value.format !== SNAPSHOT_FORMAT)\n throw new ControlError(`${label}.format: expected ${JSON.stringify(SNAPSHOT_FORMAT)}`)\n if (!Array.isArray(value.records)) throw new ControlError(`${label}.records: expected a list`)\n value.records.forEach((row: unknown, index: number) => {\n if (\n !isRecord(row) ||\n typeof row.collection !== \"string\" ||\n typeof row.id !== \"string\" ||\n (row.value === undefined && typeof row.raw !== \"string\") ||\n (row.seq !== undefined && !Number.isSafeInteger(row.seq))\n )\n throw new ControlError(`${label}.records[${index}]: expected {collection, id, value, seq?}`)\n })\n if (value.sequences !== undefined) {\n if (!Array.isArray(value.sequences))\n throw new ControlError(`${label}.sequences: expected a list`)\n value.sequences.forEach((row: unknown, index: number) => {\n if (\n !isRecord(row) ||\n typeof row.name !== \"string\" ||\n typeof row.kind !== \"string\" ||\n !Number.isSafeInteger(row.value)\n )\n throw new ControlError(`${label}.sequences[${index}]: expected {name, kind, value}`)\n })\n }\n if (value.clock !== undefined) {\n if (\n !isRecord(value.clock) ||\n typeof value.clock.now !== \"number\" ||\n !Number.isFinite(value.clock.now) ||\n typeof value.clock.frozen !== \"boolean\"\n )\n throw new ControlError(`${label}.clock: expected {now, frozen}`)\n }\n return value as SnapshotDocument\n}\n\n/** Validate one namespace's controls. Fault rules are checked when they are added. */\nexport const normalizeControls = (value: unknown, label = \"controls\"): ControlPlan => {\n if (!isRecord(value)) throw new ControlError(`${label}: expected an object`)\n unknownKeys(value, NAMESPACE_KEYS, label, REPORTED_KEYS)\n const plan: ControlPlan = {}\n if (value.seed !== undefined) plan.seed = normalizeSeed(value.seed, `${label}.seed`)\n if (value.clock !== undefined) plan.clock = normalizeClock(value.clock, `${label}.clock`)\n if (value.virtualTime !== undefined) {\n if (typeof value.virtualTime !== \"boolean\")\n throw new ControlError(`${label}.virtualTime: expected a boolean`)\n plan.virtualTime = value.virtualTime\n }\n if (value.latency !== undefined)\n plan.latency = normalizeLatency(value.latency, `${label}.latency`)\n if (value.faults !== undefined) {\n if (!Array.isArray(value.faults) || !value.faults.every(isRecord))\n throw new ControlError(`${label}.faults: expected a list of fault rules`)\n plan.faults = value.faults as FaultInput[]\n }\n if (value.snapshot !== undefined)\n plan.snapshot = assertSnapshotDocument(value.snapshot, `${label}.snapshot`)\n return plan\n}\n\n/** Boot controls, checked once when the runtime is created. */\nexport type BootPlan = {\n shared: ControlPlan\n namespaces: Record<string, ControlPlan>\n credentials: Record<string, string>\n}\n\n/** Validate a boot {@link MockControls} document. */\nexport const normalizeBootControls = (value: unknown, label = \"controls\"): BootPlan => {\n if (value === undefined) return { shared: {}, namespaces: {}, credentials: {} }\n if (!isRecord(value)) throw new ControlError(`${label}: expected an object`)\n unknownKeys(value, MOCK_KEYS, label)\n const { credentials, namespaces, ...shared } = value\n const plan: BootPlan = {\n shared: normalizeControls(shared, label),\n namespaces: {},\n credentials: {},\n }\n if (namespaces !== undefined) {\n if (!isRecord(namespaces)) throw new ControlError(`${label}.namespaces: expected an object`)\n for (const [name, each] of Object.entries(namespaces)) {\n if (!KEY_PATTERN.test(name))\n throw new ControlError(`${label}.namespaces: bad namespace ${JSON.stringify(name)}`)\n plan.namespaces[name] = normalizeControls(each, `${label}.namespaces.${name}`)\n }\n }\n if (credentials !== undefined) {\n if (!isRecord(credentials)) throw new ControlError(`${label}.credentials: expected an object`)\n for (const [credential, namespace] of Object.entries(credentials)) {\n if (typeof namespace !== \"string\" || !KEY_PATTERN.test(namespace))\n throw new ControlError(`${label}.credentials: bad namespace for a credential`)\n plan.credentials[credential] = namespace\n }\n }\n return plan\n}\n\n// \u2500\u2500 request headers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Every header a request can carry a control in. Selection headers pick what a request\n * reads; the rest act exactly like the matching admin call made just before the request.\n */\nexport const CONTROL_HEADERS = {\n namespace: \"x-mockingbird-namespace\",\n adminKey: \"x-mockingbird-admin-key\",\n branch: \"x-mockingbird-branch\",\n at: \"x-mockingbird-at\",\n reset: \"x-mockingbird-reset\",\n restore: \"x-mockingbird-restore\",\n seed: \"x-mockingbird-seed\",\n time: \"x-mockingbird-time\",\n advance: \"x-mockingbird-advance\",\n virtualTime: \"x-mockingbird-virtual-time\",\n fault: \"x-mockingbird-fault\",\n delay: \"x-mockingbird-delay\",\n timeout: \"x-mockingbird-timeout\",\n snapshot: \"x-mockingbird-snapshot\",\n} as const\n\nexport type ControlHeaderName = keyof typeof CONTROL_HEADERS\n\n/**\n * What each control header does, in the order the runtime applies them. This list is the\n * source for `GET /__admin` and is checked against the guide in `docs/ADMIN_CONTROLS.md`.\n */\nexport const CONTROL_HEADER_REFERENCE: readonly {\n header: string\n value: string\n /** `select` picks what is read; `namespace` changes it and persists; `request` is one request. */\n scope: \"select\" | \"namespace\" | \"request\"\n /** Needs `x-mockingbird-admin-key` when the mock has an admin key. */\n guarded: boolean\n summary: string\n}[] = [\n {\n header: CONTROL_HEADERS.namespace,\n value: \"<key>\",\n scope: \"select\",\n guarded: false,\n summary:\n \"Isolation key. Each key has its own records, clock, random streams, faults, latency, journal and snapshots.\",\n },\n {\n header: CONTROL_HEADERS.branch,\n value: \"<name>\",\n scope: \"select\",\n guarded: false,\n summary: \"Read and write a named copy-on-write branch of the namespace's history.\",\n },\n {\n header: CONTROL_HEADERS.at,\n value: \"<checkpoint>\",\n scope: \"select\",\n guarded: false,\n summary: \"Read the namespace as it was at a checkpoint. With a branch, start the branch there.\",\n },\n {\n header: CONTROL_HEADERS.reset,\n value: \"true\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Reset the namespace to its boot state before the request is handled.\",\n },\n {\n header: CONTROL_HEADERS.restore,\n value: \"<snapshot>\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Restore a snapshot before the request is handled.\",\n },\n {\n header: CONTROL_HEADERS.seed,\n value: \"<seed>\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Restart the namespace's random streams from this seed.\",\n },\n {\n header: CONTROL_HEADERS.time,\n value: \"<epoch ms | ISO-8601>\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Freeze the namespace clock at this instant.\",\n },\n {\n header: CONTROL_HEADERS.advance,\n value: \"<duration>\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Move the namespace clock by this much, forward or (negative) back.\",\n },\n {\n header: CONTROL_HEADERS.virtualTime,\n value: \"true | false\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Spend injected waits on the mock clock (true) or the wall clock (false).\",\n },\n {\n header: CONTROL_HEADERS.delay,\n value: \"<duration>\",\n scope: \"request\",\n guarded: true,\n summary: \"Hold this response back this long, on top of the namespace's latency.\",\n },\n {\n header: CONTROL_HEADERS.timeout,\n value: \"<duration>\",\n scope: \"request\",\n guarded: true,\n summary: \"Never answer this request: hold it this long, then drop the connection.\",\n },\n {\n header: CONTROL_HEADERS.fault,\n value: '<status> | drop | <preset> | key=value; \u2026 | {\"status\": 503, \u2026}',\n scope: \"request\",\n guarded: true,\n summary: \"Fault this request only. Stored fault rules are not consulted when it answers.\",\n },\n {\n header: CONTROL_HEADERS.snapshot,\n value: \"<name>\",\n scope: \"namespace\",\n guarded: true,\n summary: \"Snapshot the namespace after the request is handled. Echoed on the response.\",\n },\n]\n\n/** The controls one request carries in its headers, parsed and checked. */\nexport type RequestControls = {\n reset?: true\n restore?: string\n seed?: number | string\n time?: number\n advance?: number\n virtualTime?: boolean\n delay?: number\n timeout?: number\n fault?: Record<string, unknown>\n snapshot?: string\n}\n\nconst flag = (value: string, header: string): boolean => {\n const text = value.trim().toLowerCase()\n if (text === \"true\" || text === \"1\") return true\n if (text === \"false\" || text === \"0\") return false\n throw new ControlError(`${header}: expected true or false`)\n}\n\nconst name = (value: string, header: string): string => {\n const text = value.trim()\n if (!KEY_PATTERN.test(text)) throw new ControlError(`${header}: must match ${KEY_PATTERN}`)\n return text\n}\n\nconst FAULT_PAIRS = new Set([\n \"status\",\n \"delay\",\n \"jitter\",\n \"timeout\",\n \"drop\",\n \"truncate\",\n \"effect\",\n \"preset\",\n \"body\",\n])\n\n/**\n * Parse an `x-mockingbird-fault` value into a fault rule (or preset reference):\n *\n * - `503` \u2014 answer with that status\n * - `drop` \u2014 drop the connection\n * - `rate_limited` \u2014 a preset, by name\n * - `status=503; delay=2s; header.retry-after=5` \u2014 `key=value` pairs\n * - `{\"status\": 503, \"body\": {\u2026}}` \u2014 a rule as JSON\n */\nexport const parseFaultHeader = (\n value: string,\n header: string = CONTROL_HEADERS.fault,\n): Record<string, unknown> => {\n const text = value.trim()\n if (text === \"\") throw new ControlError(`${header}: expected a fault`)\n if (text.startsWith(\"{\")) {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new ControlError(`${header}: not valid JSON`)\n }\n if (!isRecord(parsed)) throw new ControlError(`${header}: expected a JSON object`)\n return parsed\n }\n const rule: Record<string, unknown> = {}\n const headers: Record<string, string> = {}\n for (const [index, raw] of text.split(\";\").entries()) {\n const part = raw.trim()\n if (part === \"\") continue\n const equals = part.indexOf(\"=\")\n if (equals < 0) {\n if (index > 0 && part !== \"drop\")\n throw new ControlError(`${header}: expected key=value, got ${JSON.stringify(part)}`)\n if (/^\\d{3}$/.test(part)) rule.status = Number(part)\n else if (part === \"drop\") rule.drop = true\n else rule.preset = name(part, header)\n continue\n }\n const key = part.slice(0, equals).trim().toLowerCase()\n const item = part.slice(equals + 1).trim()\n if (key.startsWith(\"header.\")) headers[key.slice(\"header.\".length)] = item\n else if (!FAULT_PAIRS.has(key))\n throw new ControlError(\n `${header}: unknown key ${JSON.stringify(key)}; expected ${[...FAULT_PAIRS].join(\", \")} or header.<name>`,\n )\n else if (key === \"status\" || key === \"truncate\") {\n if (!/^\\d+$/.test(item)) throw new ControlError(`${header}: ${key} must be a number`)\n rule[key] = Number(item)\n } else if (key === \"drop\") rule.drop = flag(item, `${header} drop`)\n else rule[key] = item\n }\n if (Object.keys(headers).length > 0) rule.headers = headers\n if (Object.keys(rule).length === 0) throw new ControlError(`${header}: expected a fault`)\n return rule\n}\n\nconst GUARDED = CONTROL_HEADER_REFERENCE.filter((each) => each.guarded).map((each) => each.header)\n\n/** Whether a request carries a control that changes the mock or injects a failure. */\nexport const hasGuardedControlHeader = (headers: Headers): boolean =>\n GUARDED.some((header) => headers.has(header))\n\n/** Read a request's control headers. `undefined` when it carries none. Throws {@link ControlError}. */\nexport const parseControlHeaders = (headers: Headers): RequestControls | undefined => {\n if (!hasGuardedControlHeader(headers)) return undefined\n const controls: RequestControls = {}\n const read = (key: ControlHeaderName) => headers.get(CONTROL_HEADERS[key])\n const reset = read(\"reset\")\n if (reset !== null && flag(reset, CONTROL_HEADERS.reset)) controls.reset = true\n const restore = read(\"restore\")\n if (restore !== null) controls.restore = name(restore, CONTROL_HEADERS.restore)\n const seed = read(\"seed\")\n if (seed !== null) controls.seed = normalizeSeed(seed.trim(), CONTROL_HEADERS.seed)\n const time = read(\"time\")\n if (time !== null) controls.time = instantMs(time, CONTROL_HEADERS.time)\n const advance = read(\"advance\")\n if (advance !== null) controls.advance = durationMs(advance, CONTROL_HEADERS.advance, true)\n const virtualTime = read(\"virtualTime\")\n if (virtualTime !== null) controls.virtualTime = flag(virtualTime, CONTROL_HEADERS.virtualTime)\n const delay = read(\"delay\")\n if (delay !== null) controls.delay = durationMs(delay, CONTROL_HEADERS.delay)\n const timeout = read(\"timeout\")\n if (timeout !== null) controls.timeout = durationMs(timeout, CONTROL_HEADERS.timeout)\n const fault = read(\"fault\")\n if (fault !== null) controls.fault = parseFaultHeader(fault)\n const snapshot = read(\"snapshot\")\n if (snapshot !== null) controls.snapshot = name(snapshot, CONTROL_HEADERS.snapshot)\n return controls\n}\n\n/** What {@link controlHeaders} turns into request headers. */\nexport type ControlHeaderInput = {\n namespace?: string\n adminKey?: string\n branch?: string\n at?: string\n reset?: boolean\n restore?: string\n seed?: number | string\n time?: Instant | Date\n advance?: Duration\n virtualTime?: boolean\n delay?: Duration\n timeout?: Duration\n /** A status, `\"drop\"`, a preset name, or a fault rule. */\n fault?: number | string | Record<string, unknown>\n snapshot?: string\n}\n\n/**\n * Build the request headers for a set of controls, to spread into a `fetch` or hand to an\n * SDK's default headers. Values are checked, so a typo fails here and not as a `400` later.\n */\nexport const controlHeaders = (input: ControlHeaderInput): Record<string, string> => {\n const headers: Record<string, string> = {}\n const set = (key: ControlHeaderName, value: string) => {\n headers[CONTROL_HEADERS[key]] = value\n }\n if (input.namespace !== undefined) set(\"namespace\", name(input.namespace, \"namespace\"))\n if (input.adminKey !== undefined) set(\"adminKey\", input.adminKey)\n if (input.branch !== undefined) set(\"branch\", name(input.branch, \"branch\"))\n if (input.at !== undefined) set(\"at\", input.at)\n if (input.reset === true) set(\"reset\", \"true\")\n if (input.restore !== undefined) set(\"restore\", name(input.restore, \"restore\"))\n if (input.seed !== undefined) set(\"seed\", String(normalizeSeed(input.seed)))\n if (input.time !== undefined) {\n const time = input.time instanceof Date ? input.time.getTime() : input.time\n set(\"time\", new Date(instantMs(time, \"time\")).toISOString())\n }\n if (input.advance !== undefined)\n set(\"advance\", String(durationMs(input.advance, \"advance\", true)))\n if (input.virtualTime !== undefined) set(\"virtualTime\", String(input.virtualTime))\n if (input.delay !== undefined) set(\"delay\", String(durationMs(input.delay, \"delay\")))\n if (input.timeout !== undefined) set(\"timeout\", String(durationMs(input.timeout, \"timeout\")))\n if (input.fault !== undefined) {\n const fault =\n typeof input.fault === \"object\" ? JSON.stringify(input.fault) : String(input.fault)\n parseFaultHeader(fault, \"fault\")\n set(\"fault\", fault)\n }\n if (input.snapshot !== undefined) set(\"snapshot\", name(input.snapshot, \"snapshot\"))\n return headers\n}\n", "import type { Clock } from \"./clock.js\"\nimport {\n assertSnapshotDocument,\n CONTROL_HEADER_REFERENCE,\n CONTROL_HEADERS,\n ControlError,\n type ControlPlan,\n durationMs,\n isRecord,\n KEY_PATTERN,\n normalizeClock,\n normalizeControls,\n normalizeLatency,\n parseInstant,\n type SnapshotDocument,\n} from \"./controls.js\"\nimport type { FaultPresetList } from \"./faults.js\"\nimport type { Journal } from \"./journal.js\"\nimport type { Metrics } from \"./metrics.js\"\nimport { createNamespaceControls, type NamespaceControls } from \"./namespace-controls.js\"\nimport { ADMIN_ROUTE_REFERENCE } from \"./surface.js\"\n\nexport { parseDuration } from \"./controls.js\"\n\n/** Unauthenticated readiness probe, served ahead of every vendor auth gate. */\nexport const HEALTH_PATH = \"/__admin/health\"\n/** Prefix of every control-plane route; never part of a vendor contract. */\nexport const ADMIN_PREFIX = \"/__admin\"\n/** Resolve once at construction; ambiguous URL forms are never accepted. */\nexport const resolveAdminPrefix = (prefix: string = ADMIN_PREFIX): string => {\n if (!/^\\/[A-Za-z0-9_-]+(?:\\/[A-Za-z0-9_-]+)*$/.test(prefix)) {\n throw new Error(\n \"adminPrefix must be an absolute non-root path of literal segments, without a trailing slash\",\n )\n }\n return prefix\n}\n\n/** Segment-boundary matching prevents /__administer from entering the control plane. */\nexport const isAdminPath = (path: string, prefix: string): boolean =>\n path === prefix || path.startsWith(`${prefix}/`)\n\n/** SDK base URL namespace carrier, entirely inside the configured internal route tree. */\nexport const matchNamespacePath = (path: string, prefix: string): RegExpExecArray | null =>\n /^\\/ns\\/([^/]+)(\\/.*)?$/.exec(isAdminPath(path, prefix) ? path.slice(prefix.length) : \"\")\n\n/** Fail before serving when the declared vendor contract overlaps the reserved tree. */\nexport const assertAdminPrefixAvailable = (prefix: string, paths: readonly string[]): void => {\n const reserved = prefix.split(\"/\").slice(1)\n for (const path of paths) {\n const segments = path.split(\"/\").slice(1)\n // Catch-all vendor roots (e.g. S3 /{bucket}/{key}) share the listener.\n // The internal tree is reserved before vendor dispatch, regardless of the wildcard.\n if (segments.length < reserved.length || /^\\{[^}]+\\}$/.test(segments[0] ?? \"\")) continue\n if (\n reserved.every((part, i) => segments[i] === part || /^\\{[^}]+\\}$/.test(segments[i] ?? \"\"))\n ) {\n throw new Error(\n `vendor route ${path} collides with adminPrefix ${prefix}; choose a different adminPrefix`,\n )\n }\n }\n}\n\n/** Carries the admin key, which is separate from any vendor credential. */\nexport const ADMIN_KEY_HEADER = CONTROL_HEADERS.adminKey\n/** Selects the isolated namespace a request reads and writes. */\nexport const NAMESPACE_HEADER = CONTROL_HEADERS.namespace\n/** Where the admin controls are documented, for people and agents. */\nexport const ADMIN_DOCS_URL = \"https://mockingbird.chrisvouga.dev/docs/admin-controls\"\n\n/**\n * The guide's page for each control, with the shared routes (by first path segment) and the\n * request headers that page defines. `GET /__admin` links every route and header to its page,\n * and the guide in `docs/admin-controls/` is checked against this list.\n */\nexport const ADMIN_CONTROL_PAGES: readonly {\n page: string\n title: string\n routes: readonly string[]\n headers: readonly string[]\n}[] = [\n {\n page: \"namespaces\",\n title: \"Namespaces\",\n routes: [\"/namespaces\", \"/credentials\"],\n headers: [CONTROL_HEADERS.namespace],\n },\n { page: \"reset\", title: \"Reset\", routes: [\"/reset\"], headers: [CONTROL_HEADERS.reset] },\n {\n page: \"snapshot-and-restore\",\n title: \"Snapshot and restore\",\n routes: [\"/snapshots\"],\n headers: [CONTROL_HEADERS.restore, CONTROL_HEADERS.snapshot],\n },\n {\n page: \"clock\",\n title: \"Clock\",\n routes: [\"/clock\"],\n headers: [CONTROL_HEADERS.time, CONTROL_HEADERS.advance],\n },\n {\n page: \"checkpoints-and-branches\",\n title: \"Checkpoints and branches\",\n routes: [\"/timeline\", \"/checkpoints\", \"/branches\"],\n headers: [CONTROL_HEADERS.branch, CONTROL_HEADERS.at],\n },\n { page: \"faults\", title: \"Faults\", routes: [\"/faults\"], headers: [CONTROL_HEADERS.fault] },\n {\n page: \"latency-and-timeouts\",\n title: \"Latency and timeouts\",\n routes: [\"/latency\"],\n headers: [CONTROL_HEADERS.delay, CONTROL_HEADERS.timeout, CONTROL_HEADERS.virtualTime],\n },\n {\n page: \"seed-and-determinism\",\n title: \"Seed and determinism\",\n routes: [],\n headers: [CONTROL_HEADERS.seed],\n },\n { page: \"control-document\", title: \"The control document\", routes: [\"/controls\"], headers: [] },\n { page: \"boot\", title: \"Boot\", routes: [], headers: [] },\n { page: \"request-headers\", title: \"Request headers\", routes: [], headers: [] },\n {\n page: \"journal-and-state\",\n title: \"Journal, metrics and state\",\n routes: [\"/requests\", \"/metrics\", \"/state\", \"/ui\"],\n headers: [],\n },\n {\n page: \"reference\",\n title: \"Reference\",\n routes: [\"/\", \"/health\"],\n headers: [CONTROL_HEADERS.adminKey],\n },\n]\n\nconst pageUrl = (page: string): string => `${ADMIN_DOCS_URL}/${page}`\n\n/** The guide page that defines a shared route (`\"GET /snapshots/:id\"`), if it is one. */\nconst routeDocs = (route: string): string | undefined => {\n if (!Object.hasOwn(ADMIN_ROUTE_REFERENCE, route)) return undefined\n const path = route.slice(route.indexOf(\" \") + 1)\n const segment = `/${path.split(\"/\")[1] ?? \"\"}`\n const found = ADMIN_CONTROL_PAGES.find((each) => each.routes.includes(segment))\n return found && pageUrl(found.page)\n}\n\nconst headerDocs = (header: string): string | undefined => {\n const found = ADMIN_CONTROL_PAGES.find((each) => each.headers.includes(header))\n return found && pageUrl(found.page)\n}\n\nexport type AdminRequest = {\n request: Request\n url: URL\n /** `:param` segments of the matched route. */\n params: Record<string, string>\n /** Namespace the request targets: `?namespace=`, then the header, then the default. */\n namespace: string\n /** Parsed JSON body, or `undefined` when there is none. */\n body: unknown\n}\n\nexport type AdminRoute = (request: AdminRequest) => Response | Promise<Response>\n\n/**\n * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with\n * `:param` segments \u2014 e.g. `\"POST /orders/:id/transition\"`.\n */\nexport type AdminRoutes = Record<string, AdminRoute>\n\n/** What `GET /__admin/snapshots` lists for each snapshot. */\nexport type SnapshotInfo = {\n id: string\n namespace: string\n /** Stored rows in the snapshot. */\n records: number\n /** The namespace clock when it was taken, epoch ms. */\n at: number\n /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */\n portable: boolean\n}\n\n/** Named snapshots of a namespace. Ids are unique within a namespace, never across them. */\nexport type SnapshotStore = {\n /** Capture the namespace now. Reusing an id replaces that snapshot. */\n create(namespace: string, id?: string): SnapshotInfo\n list(namespace: string): SnapshotInfo[]\n get(namespace: string, id: string): SnapshotInfo | undefined\n /** The snapshot as portable JSON; `undefined` when there is none or it cannot leave the process. */\n export(namespace: string, id: string): SnapshotDocument | undefined\n /** Store a document as a snapshot without restoring it. Throws {@link ControlError}. */\n import(namespace: string, id: string | undefined, document: SnapshotDocument): SnapshotInfo\n /** Replace the namespace with the snapshot. `false` when there is none. */\n restore(namespace: string, id: string): boolean\n remove(namespace: string, id: string): boolean\n /** Forget one namespace's snapshots, or every namespace's. */\n clear(namespace?: string): void\n}\n\nexport type ControlContext = {\n name: string\n startedAt: number\n wallNow: () => number\n clock: Clock\n namespaceClock?(namespace: string): Clock\n metrics: Metrics\n journal: Journal\n defaultNamespace: string\n namespaces(): string[]\n reset(namespace: string | \"*\"): Promise<void>\n timeTravel: {\n checkpoint(\n namespace: string,\n branch: string,\n ): { id: string; branch: string; parent: string | null; at: number; records?: number }\n branch(\n name: string,\n options: { namespace: string; at?: string },\n ): { id: string; branch: string; parent: string | null; at: number }\n checkout(checkpoint: string, options: { namespace: string; branch: string }): void\n retain(namespace: string, checkpoint: string): void\n release(namespace: string, checkpoint: string): boolean\n inspect(namespace: string): {\n branches: Readonly<Record<string, string>>\n checkpoints: readonly { id: string; branch: string; parent: string | null; at: number }[]\n }\n }\n /** Extra fields for `GET /__admin/health`, such as the loaded corpus version. */\n describe(): Record<string, unknown>\n routes: AdminRoutes\n adminPrefix?: string\n adminKey: string | undefined\n /** Reported by `GET /__admin`. */\n version?: string\n /**\n * Per-namespace seed, clock settings, latency and faults. Default: controls over this\n * context's clock, with the standard presets and no boot controls.\n */\n controls?: NamespaceControls\n /** Named snapshots. Default: pinned `timeTravel` checkpoints, which are not portable. */\n snapshots?: SnapshotStore\n /** Apply a control document, including its `snapshot`. Default: `controls.apply`. */\n applyControls?(namespace: string, plan: ControlPlan): void\n /** Reset a namespace and forget it. Default: reset. */\n dropNamespace?(namespace: string): Promise<void>\n}\n\nexport type ControlPlane = {\n /** The control-plane response for `request`, or `undefined` for a vendor request. */\n handle(request: Request): Promise<Response | undefined>\n /**\n * Namespace a vendor request targets, from {@link NAMESPACE_HEADER}. Only admin routes\n * also accept `?namespace=`, so a vendor query parameter of that name can never\n * silently reroute a request.\n */\n namespaceOf(request: Request): string\n /** The per-namespace controls behind the routes. */\n readonly controls: NamespaceControls\n readonly snapshots: SnapshotStore\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n })\n\n/** Admin errors use one documented shape, distinct from any vendor's error body. */\nexport const adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\n/** Parameters before literals lose, so `/faults/presets` is never read as `/faults/:id`. */\nconst paramCount = (pattern: string): number => (pattern.match(/\\/:/g) ?? []).length\n\nconst matchRoute = (pattern: string, path: string): Record<string, string> | undefined => {\n const want = pattern.split(\"/\").filter(Boolean)\n const have = path.split(\"/\").filter(Boolean)\n if (want.length !== have.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < want.length; i++) {\n const segment = want[i] as string\n const actual = have[i] as string\n if (segment.startsWith(\":\")) params[segment.slice(1)] = decodeURIComponent(actual)\n else if (segment !== actual) return undefined\n }\n return params\n}\n\nconst readJson = async (request: Request): Promise<unknown> => {\n const text = await request.text()\n if (text.trim() === \"\") return undefined\n return JSON.parse(text) as unknown\n}\n\n/** Snapshots as pinned Timeline checkpoints, for engines whose state is not rows of JSON. */\nconst timelineSnapshots = (timeTravel: ControlContext[\"timeTravel\"]): SnapshotStore => {\n const stored = new Map<string, Map<string, { checkpoint: string; info: SnapshotInfo }>>()\n const counters = new Map<string, number>()\n const of = (namespace: string) => {\n let found = stored.get(namespace)\n if (!found) {\n found = new Map()\n stored.set(namespace, found)\n }\n return found\n }\n const remove = (namespace: string, id: string): boolean => {\n const found = stored.get(namespace)?.get(id)\n if (!found) return false\n stored.get(namespace)?.delete(id)\n timeTravel.release(namespace, found.checkpoint)\n return true\n }\n return {\n create(namespace, given) {\n const point = timeTravel.checkpoint(namespace, \"main\")\n timeTravel.retain(namespace, point.id)\n let id = given\n if (id === undefined) {\n let next = counters.get(namespace) ?? 0\n do id = `snap_${++next}`\n while (of(namespace).has(id))\n counters.set(namespace, next)\n } else remove(namespace, id)\n const info = { id, namespace, records: point.records ?? 0, at: point.at, portable: false }\n of(namespace).set(id, { checkpoint: point.id, info })\n return info\n },\n list: (namespace) => [...(stored.get(namespace)?.values() ?? [])].map((each) => each.info),\n get: (namespace, id) => stored.get(namespace)?.get(id)?.info,\n export: () => undefined,\n import() {\n throw new ControlError(\"this emulator's snapshots cannot be imported or exported\")\n },\n restore(namespace, id) {\n const found = stored.get(namespace)?.get(id)\n if (!found) return false\n timeTravel.checkout(found.checkpoint, { namespace, branch: \"main\" })\n return true\n },\n remove,\n clear(namespace) {\n for (const [name, snapshots] of stored) {\n if (namespace !== undefined && name !== namespace) continue\n for (const id of [...snapshots.keys()]) {\n try {\n remove(name, id)\n } catch {\n // The checkpoint went with the history a reset discarded.\n snapshots.delete(id)\n }\n }\n stored.delete(name)\n counters.delete(name)\n }\n },\n }\n}\n\nexport const createControlPlane = (context: ControlContext): ControlPlane => {\n const adminPrefix = resolveAdminPrefix(context.adminPrefix)\n const controls =\n context.controls ??\n createNamespaceControls({\n seed: 0,\n clock: (namespace) => context.namespaceClock?.(namespace) ?? context.clock,\n })\n const { faults } = controls\n const snapshots = context.snapshots ?? timelineSnapshots(context.timeTravel)\n /** A store the runtime owns is cleared by the runtime's own reset. */\n const forgetSnapshots = (namespace?: string) => {\n if (!context.snapshots) snapshots.clear(namespace)\n }\n const applyControls =\n context.applyControls ??\n ((namespace: string, plan: ControlPlan) => {\n if (plan.snapshot !== undefined)\n throw new ControlError(\"this emulator cannot start from a snapshot document\")\n controls.apply(namespace, plan)\n })\n\n const headerNamespace = (request: Request): string =>\n request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace\n const adminNamespace = (request: Request, url: URL): string =>\n url.searchParams.get(\"namespace\") ?? headerNamespace(request)\n /** Whether the caller named a namespace, as opposed to landing on the default one. */\n const explicitNamespace = (request: Request, url: URL): boolean =>\n url.searchParams.has(\"namespace\") || request.headers.has(NAMESPACE_HEADER)\n\n const health = (): Response => {\n return json(200, {\n ...context.describe(),\n status: \"ok\",\n service: context.name,\n uptimeMs: context.wallNow() - context.startedAt,\n clock: context.clock.state(),\n namespaces: context.namespaces().length,\n adminPrefix,\n adminUi: `${adminPrefix}/ui`,\n })\n }\n\n const describe = (namespace: string) => ({\n ...controls.describe(namespace),\n snapshots: snapshots.list(namespace),\n })\n\n /** Run a control change, answering `400` for a {@link ControlError}. */\n const guard = (run: () => Response): Response => {\n try {\n return run()\n } catch (error) {\n if (error instanceof ControlError) return adminError(400, error.message)\n throw error\n }\n }\n\n const presetList = (): FaultPresetList => ({\n presets: Object.entries(controls.presets).map(([name, preset]) => ({ name, ...preset })),\n })\n\n const removeFault = (id: string, namespace: string, everyNamespace: boolean): Response =>\n faults.remove(id, everyNamespace ? undefined : namespace)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no fault ${id}`)\n\n const builtin: AdminRoutes = {\n \"GET /health\": health,\n \"GET /\": ({ namespace }) => {\n const routes = [...Object.keys(builtin), ...Object.keys(context.routes)].sort()\n const reference: Record<string, string> = ADMIN_ROUTE_REFERENCE\n return json(200, {\n service: context.name,\n ...(context.version !== undefined ? { version: context.version } : {}),\n namespace,\n adminPrefix,\n docs: ADMIN_DOCS_URL,\n guide: ADMIN_CONTROL_PAGES.map((each) => ({ title: each.title, docs: pageUrl(each.page) })),\n routes,\n reference: routes.map((route) => {\n const docs = routeDocs(route)\n return {\n route,\n summary: reference[route] ?? `Specific to ${context.name}.`,\n ...(docs !== undefined ? { docs } : {}),\n }\n }),\n headers: CONTROL_HEADER_REFERENCE.map((each) => ({\n ...each,\n docs: headerDocs(each.header) ?? ADMIN_DOCS_URL,\n })),\n })\n },\n\n \"GET /controls\": ({ namespace }) => json(200, describe(namespace)),\n \"PUT /controls\": ({ body, namespace }) =>\n guard(() => {\n applyControls(namespace, normalizeControls(body ?? {}, \"controls\"))\n return json(200, describe(namespace))\n }),\n \"DELETE /controls\": ({ namespace }) => {\n controls.reboot(namespace, \"controls\")\n return json(200, describe(namespace))\n },\n\n \"POST /reset\": async ({ url, namespace }) => {\n const target = url.searchParams.get(\"all\") === \"1\" ? \"*\" : namespace\n await context.reset(target)\n forgetSnapshots(target === \"*\" ? undefined : target)\n return json(200, { status: \"ok\", reset: target === \"*\" ? context.namespaces() : [target] })\n },\n\n \"GET /namespaces\": () =>\n json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),\n \"DELETE /namespaces/:name\": async ({ params }) => {\n const name = params.name as string\n if (!KEY_PATTERN.test(name)) return adminError(400, \"invalid namespace\")\n if (context.dropNamespace) await context.dropNamespace(name)\n else await context.reset(name)\n forgetSnapshots(name)\n return json(200, { status: \"ok\", namespaces: context.namespaces() })\n },\n\n \"GET /clock\": ({ namespace }) => json(200, controls.clock(namespace)),\n \"POST /clock\": ({ body, namespace }) =>\n guard(() => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n const { advance, reset, ...rest } = body\n if (reset !== undefined && typeof reset !== \"boolean\")\n return adminError(400, \"reset: expected a boolean\")\n return json(\n 200,\n controls.changeClock(namespace, {\n ...normalizeClock(rest),\n ...(advance !== undefined ? { advanceMs: durationMs(advance, \"advance\", true) } : {}),\n ...(reset === true ? { reset: true } : {}),\n }),\n )\n }),\n\n \"GET /latency\": ({ namespace }) => {\n controls.ensure(namespace)\n return json(200, controls.latency.get(namespace))\n },\n \"PUT /latency\": ({ body, namespace }) =>\n guard(() => {\n controls.ensure(namespace)\n return json(200, controls.latency.set(namespace, normalizeLatency(body ?? {})))\n }),\n \"DELETE /latency\": ({ namespace }) => {\n controls.ensure(namespace)\n controls.latency.clear(namespace)\n return json(200, controls.latency.get(namespace))\n },\n\n \"GET /faults\": ({ url, namespace }) => {\n controls.ensure(namespace)\n return json(200, {\n faults: faults.list(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace),\n })\n },\n \"POST /faults\": ({ body, namespace }) =>\n guard(() => {\n const preset = isRecord(body) && typeof body.preset === \"string\" ? body.preset : undefined\n if (preset !== undefined && !controls.presets[preset])\n return adminError(\n 404,\n `no fault preset ${JSON.stringify(preset)}; GET ${adminPrefix}/faults/presets`,\n )\n const added = controls.addFault(namespace, body)\n return preset !== undefined ? json(201, { preset, rules: added }) : json(201, added[0])\n }),\n \"PUT /faults\": ({ body, namespace }) =>\n guard(() => {\n const list = isRecord(body) ? body.faults : undefined\n if (!Array.isArray(list)) return adminError(400, 'expected {\"faults\": [...]}')\n controls.apply(namespace, normalizeControls({ faults: list }))\n return json(200, { faults: faults.list(namespace) })\n }),\n \"DELETE /faults\": ({ url, namespace }) => {\n controls.ensure(namespace)\n const everyNamespace = url.searchParams.get(\"all\") === \"1\"\n const id = url.searchParams.get(\"id\")\n if (id !== null) return removeFault(id, namespace, everyNamespace)\n faults.clear(everyNamespace ? undefined : namespace)\n return json(200, { status: \"ok\" })\n },\n \"GET /faults/presets\": () => json(200, presetList()),\n \"POST /faults/presets/:name\": ({ params, body, namespace }) =>\n guard(() => {\n const name = params.name as string\n if (!controls.presets[name])\n return adminError(404, `no fault preset ${name}; GET ${adminPrefix}/faults/presets`)\n return json(201, {\n preset: name,\n rules: controls.addFault(namespace, { ...(isRecord(body) ? body : {}), preset: name }),\n })\n }),\n \"GET /faults/:id\": ({ params, namespace }) => {\n controls.ensure(namespace)\n const found = faults.get(params.id as string, namespace)\n return found ? json(200, found) : adminError(404, `no fault ${params.id}`)\n },\n \"DELETE /faults/:id\": ({ params, url, namespace }) => {\n controls.ensure(namespace)\n return removeFault(params.id as string, namespace, url.searchParams.get(\"all\") === \"1\")\n },\n\n \"GET /snapshots\": ({ namespace }) => json(200, { snapshots: snapshots.list(namespace) }),\n \"POST /snapshots\": ({ body, namespace }) =>\n guard(() => {\n const id = isRecord(body) ? body.name : undefined\n if (id !== undefined && (typeof id !== \"string\" || !KEY_PATTERN.test(id)))\n return adminError(400, `name: must match ${KEY_PATTERN}`)\n return json(201, snapshots.create(namespace, id))\n }),\n \"GET /snapshots/:id\": ({ params, namespace }) => {\n const id = params.id as string\n const info = snapshots.get(namespace, id)\n if (!info) return adminError(404, `no snapshot ${id} in namespace ${namespace}`)\n return json(200, snapshots.export(namespace, id) ?? info)\n },\n \"PUT /snapshots/:id\": ({ params, body, namespace }) =>\n guard(() => {\n const id = params.id as string\n if (!KEY_PATTERN.test(id)) return adminError(400, `id: must match ${KEY_PATTERN}`)\n return json(200, snapshots.import(namespace, id, assertSnapshotDocument(body)))\n }),\n \"POST /snapshots/:id/restore\": ({ params, namespace }) =>\n guard(() => {\n const id = params.id as string\n if (!snapshots.restore(namespace, id))\n return adminError(404, `no snapshot ${id} in namespace ${namespace}`)\n return json(200, { status: \"ok\", id, namespace })\n }),\n \"DELETE /snapshots/:id\": ({ params, namespace }) => {\n const id = params.id as string\n return snapshots.remove(namespace, id)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no snapshot ${id} in namespace ${namespace}`)\n },\n\n \"GET /timeline\": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),\n \"POST /checkpoints\": ({ body, namespace }) => {\n const branch = isRecord(body) && typeof body.branch === \"string\" ? body.branch : \"main\"\n try {\n return json(201, context.timeTravel.checkpoint(namespace, branch))\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name\": ({ params, body, namespace }) => {\n const at = isRecord(body) && typeof body.at === \"string\" ? body.at : undefined\n try {\n return json(\n 201,\n context.timeTravel.branch(params.name as string, {\n namespace,\n ...(at !== undefined ? { at } : {}),\n }),\n )\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name/checkout\": ({ params, body, namespace }) => {\n if (!isRecord(body) || typeof body.checkpoint !== \"string\") {\n return adminError(400, 'expected {\"checkpoint\":\"cp_...\"}')\n }\n try {\n context.timeTravel.checkout(body.checkpoint, {\n namespace,\n branch: params.name as string,\n })\n return json(200, { status: \"ok\", branch: params.name, checkpoint: body.checkpoint })\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n\n \"GET /requests\": ({ url, namespace }) => {\n const status = url.searchParams.get(\"status\")\n const since = url.searchParams.get(\"since\")\n const limit = url.searchParams.get(\"limit\")\n const sinceMs = since === null ? undefined : parseInstant(since)\n if (since !== null && sinceMs === undefined) {\n return adminError(400, \"since: expected epoch ms or ISO-8601\")\n }\n // `0` is a status here: it is how the journal records a dropped connection.\n if (status !== null && !/^(0|\\d{3})$/.test(status))\n return adminError(400, \"status: expected an HTTP status, or 0 for a dropped connection\")\n if (limit !== null && !/^\\d+$/.test(limit)) return adminError(400, \"limit: expected a count\")\n const operationId = url.searchParams.get(\"operationId\")\n const method = url.searchParams.get(\"method\")\n const path = url.searchParams.get(\"path\")\n const faultId = url.searchParams.get(\"faultId\")\n const everyNamespace = url.searchParams.get(\"all\") === \"1\"\n return json(200, {\n size: context.journal.size,\n requests: context.journal.list({\n ...(everyNamespace ? {} : { namespace }),\n ...(operationId !== null ? { operationId } : {}),\n ...(method !== null ? { method } : {}),\n ...(path !== null ? { path } : {}),\n ...(faultId !== null ? { faultId } : {}),\n ...(status !== null ? { status: Number(status) } : {}),\n ...(sinceMs !== undefined ? { since: sinceMs } : {}),\n ...(limit !== null ? { limit: Number(limit) } : {}),\n }),\n })\n },\n \"DELETE /requests\": ({ url, namespace }) => {\n context.journal.clear(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n return json(200, { status: \"ok\" })\n },\n\n // Totals across every namespace, unless the caller names one.\n \"GET /metrics\": ({ request, url, namespace }) =>\n json(200, context.metrics.report(explicitNamespace(request, url) ? namespace : undefined)),\n \"DELETE /metrics\": ({ request, url, namespace }) => {\n context.metrics.reset(explicitNamespace(request, url) ? namespace : undefined)\n return json(200, { status: \"ok\" })\n },\n }\n\n for (const key of Object.keys(context.routes)) {\n if (Object.hasOwn(builtin, key)) throw new Error(`admin route ${key} overrides a shared route`)\n const path = key.slice(key.indexOf(\" \") + 1)\n if (isAdminPath(path, \"/ns\") || isAdminPath(path, \"/blobs\"))\n throw new Error(`admin route ${key} overlaps an internal transport`)\n }\n const routes = [...Object.entries(builtin), ...Object.entries(context.routes)]\n .map(([key, handler]) => {\n const space = key.indexOf(\" \")\n return { method: key.slice(0, space), pattern: key.slice(space + 1), handler }\n })\n // Stable: among equally specific routes the shared ones still come first.\n .sort((a, b) => paramCount(a.pattern) - paramCount(b.pattern))\n\n return {\n namespaceOf: headerNamespace,\n controls,\n snapshots,\n async handle(request) {\n const url = new URL(request.url)\n if (url.pathname === `${adminPrefix}/health` && request.method === \"GET\") {\n return health()\n }\n if (!isAdminPath(url.pathname, adminPrefix)) {\n return undefined\n }\n const path = url.pathname.slice(adminPrefix.length) || \"/\"\n // The shell has no data. Panel markup stays on GET /ui/manifest, which is locked.\n const shell = request.method === \"GET\" && (path === \"/ui\" || path === \"/ui/\")\n if (\n !shell &&\n context.adminKey !== undefined &&\n request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey\n ) {\n return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`)\n }\n for (const route of routes) {\n if (route.method !== request.method) continue\n let params: Record<string, string> | undefined\n try {\n params = matchRoute(route.pattern, path)\n } catch {\n return adminError(400, \"invalid path encoding\")\n }\n if (!params) continue\n let body: unknown\n try {\n body = await readJson(request)\n } catch {\n return adminError(400, \"request body is not valid JSON\")\n }\n const namespace = adminNamespace(request, url)\n if (!KEY_PATTERN.test(namespace)) return adminError(400, \"invalid namespace\")\n return route.handler({\n request,\n url,\n params,\n namespace,\n body,\n })\n }\n return adminError(\n 404,\n `no admin route ${request.method} ${path}; GET ${adminPrefix} lists them`,\n )\n },\n }\n}\n", "/** Policy only for runtime-owned HTTP sends; it does not sandbox DNS or arbitrary sockets. */\nexport type OutboundPolicy = {\n mode: \"offline\" | \"allowlist\"\n origins?: string[]\n maxRedirects?: number\n maxBodyBytes?: number\n onReject?(event: { namespace: string; policy: string; reason: string }): void\n}\nexport type OwnedTransport = (\n request: Request,\n namespace: string,\n send: typeof fetch,\n) => Promise<Response>\nexport function ownedTransport(policy: OutboundPolicy): OwnedTransport {\n if (\n ![\"offline\", \"allowlist\"].includes(policy.mode) ||\n policy.origins?.some((origin) => {\n try {\n return new URL(origin).origin !== origin\n } catch {\n return true\n }\n })\n )\n throw new Error(\"invalid outbound transport policy\")\n const reject = (namespace: string, reason: string): never => {\n try {\n policy.onReject?.({ namespace, policy: policy.mode, reason })\n } catch {}\n throw new Error(`outbound policy ${policy.mode}: ${reason}`)\n }\n return async (request, namespace, send) => {\n if (policy.mode === \"offline\") return reject(namespace, \"delivery disabled\")\n const allowed = (url: URL) =>\n [\"http:\", \"https:\"].includes(url.protocol) &&\n !url.username &&\n !url.password &&\n (policy.origins ?? []).includes(url.origin)\n let url = new URL(request.url)\n if (!allowed(url)) return reject(namespace, \"destination not allowed\")\n const max = policy.maxBodyBytes ?? 1024 * 1024\n const chunks: Uint8Array[] = []\n let size = 0\n const reader = request.body?.getReader()\n if (reader)\n try {\n for (;;) {\n const item = await reader.read()\n if (item.done) break\n size += item.value.length\n if (size > max) return reject(namespace, \"body limit exceeded\")\n chunks.push(item.value)\n }\n } finally {\n void reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.length\n }\n let method = request.method,\n headers = new Headers(request.headers)\n for (let redirects = 0; ; redirects++) {\n if (!allowed(url)) return reject(namespace, \"redirect destination not allowed\")\n const response = await send(\n new Request(url, {\n method,\n headers,\n ...(method !== \"GET\" && method !== \"HEAD\" ? { body } : {}),\n redirect: \"manual\",\n signal: request.signal,\n }),\n )\n if (![301, 302, 303, 307, 308].includes(response.status)) return response\n const location = response.headers.get(\"location\")\n if (!location) return response\n await response.body?.cancel()\n if (redirects >= (policy.maxRedirects ?? 5))\n return reject(namespace, \"redirect limit exceeded\")\n const next = new URL(location, url)\n if (next.origin !== url.origin) {\n headers = new Headers(headers)\n for (const key of [\"authorization\", \"cookie\", \"proxy-authorization\"]) headers.delete(key)\n }\n if (\n response.status === 303 ||\n ((response.status === 301 || response.status === 302) && method === \"POST\")\n ) {\n method = \"GET\"\n headers.delete(\"content-length\")\n headers.delete(\"content-type\")\n }\n url = next\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;AAAA,SAAS,kBAAkB,oBAA8C;;;ACgClE,IAAM,cAAc,CAAC,SAAuB,KAAK,QAAc;AACpE,MAAI,WAAW;AACf,MAAI;AACJ,QAAM,MAAM,MAAM,YAAY,OAAM,IAAK;AACzC,SAAO;IACL;IACA,KAAK,CAAC,YAAW;AACf,UAAI,aAAa;AAAW,mBAAW;;AAClC,mBAAW,UAAU,OAAM;IAClC;IACA,SAAS,CAAC,YAAW;AACnB,UAAI,aAAa;AAAW,oBAAY;;AACnC,oBAAY;IACnB;IACA,QAAQ,MAAK;AACX,iBAAW,IAAG;IAChB;IACA,UAAU,MAAK;AACb,UAAI,aAAa;AAAW;AAC5B,iBAAW,WAAW,OAAM;AAC5B,iBAAW;IACb;IACA,OAAO,MAAK;AACV,iBAAW;AACX,iBAAW;IACb;;IAEA,OAAO,OAAO;MACZ,KAAK,IAAG;MACR,QAAQ,aAAa;MACrB,UAAU,aAAa,SAAY,IAAI;;;AAG7C;AAiDO,IAAM,eAAe,CAAC,OAAc,UAAiD;AAC1F,QAAM,OAAM;AACZ,QAAM,IAAI,MAAM,GAAG;AACnB,MAAI,CAAC,MAAM;AAAQ,UAAM,SAA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