@crvouga/mockingbird-service-workos 1.0.0 → 1.2.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/server.d.ts CHANGED
@@ -2,34 +2,16 @@ import { Server } from 'node:http';
2
2
  import * as hono from 'hono';
3
3
  import * as hono_types from 'hono/types';
4
4
 
5
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
6
- type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
7
- /** Mutation counters returned by {@link SqliteStatement.run}. */
8
- type SqliteRunResult$2 = {
9
- changes: number;
10
- lastInsertRowid: number | bigint;
5
+ type MountedAPI$1 = FetchAPI$2 & {
6
+ readonly prefix: string;
7
+ GET: FetchHandler$1;
8
+ POST: FetchHandler$1;
9
+ PUT: FetchHandler$1;
10
+ PATCH: FetchHandler$1;
11
+ DELETE: FetchHandler$1;
12
+ HEAD: FetchHandler$1;
13
+ OPTIONS: FetchHandler$1;
11
14
  };
12
- /**
13
- * Prepared statement bound to a {@link SqliteClient}.
14
- *
15
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
16
- */
17
- interface SqliteStatement$2 {
18
- run(...params: SqliteValue$2[]): SqliteRunResult$2;
19
- all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
20
- get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
21
- }
22
- /**
23
- * Sync SQLite client port owned by Mockingbird.
24
- *
25
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
26
- * `bun:sqlite` instances all work when they expose this surface.
27
- */
28
- interface SqliteClient$2 {
29
- exec(sql: string): void;
30
- prepare(sql: string): SqliteStatement$2;
31
- transaction<T>(fn: () => T): T;
32
- }
33
15
 
34
16
  /** A stable identifier for a point in a {@link Timeline}. */
35
17
  type CheckpointId$1 = string;
@@ -120,6 +102,37 @@ declare class Timeline$1<T> {
120
102
  interface FetchAPI$2 {
121
103
  fetch(request: Request): Promise<Response>;
122
104
  }
105
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
106
+ type FetchHandler$1 = (request: Request) => Promise<Response>;
107
+
108
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
109
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
110
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
111
+ type SqliteRunResult$2 = {
112
+ changes: number;
113
+ lastInsertRowid: number | bigint;
114
+ };
115
+ /**
116
+ * Prepared statement bound to a {@link SqliteClient}.
117
+ *
118
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
119
+ */
120
+ interface SqliteStatement$2 {
121
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
122
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
123
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
124
+ }
125
+ /**
126
+ * Sync SQLite client port owned by Mockingbird.
127
+ *
128
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
129
+ * `bun:sqlite` instances all work when they expose this surface.
130
+ */
131
+ interface SqliteClient$2 {
132
+ exec(sql: string): void;
133
+ prepare(sql: string): SqliteStatement$2;
134
+ transaction<T>(fn: () => T): T;
135
+ }
123
136
 
124
137
  /**
125
138
  * The single source of time for a service.
@@ -133,7 +146,7 @@ type ClockState$1 = {
133
146
  now: number;
134
147
  /** True while time does not advance on its own. */
135
148
  frozen: boolean;
136
- /** Milliseconds this clock adds to its underlying source. */
149
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
137
150
  offsetMs: number;
138
151
  };
139
152
  type Clock$1 = {
@@ -169,7 +182,10 @@ type Rng$1 = {
169
182
  state(): number;
170
183
  /** Restore a state previously returned by {@link state}. */
171
184
  setState(state: number): void;
172
- seed: number;
185
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
186
+ reseed(seed: number | string): void;
187
+ /** The seed the stream currently starts from. */
188
+ readonly seed: number;
173
189
  };
174
190
 
175
191
  /**
@@ -178,44 +194,83 @@ type Rng$1 = {
178
194
  * This is how a suite reaches the vendor's failure modes without the vendor: the
179
195
  * quota error that only appears when a shared sandbox is full, the 429 that only
180
196
  * appears under load, the 5xx that proves a retry path works.
197
+ *
198
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
199
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
200
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
181
201
  */
182
202
  type FaultRule$1 = {
183
- /** Stable id, so a suite can retire exactly the rule it added. */
203
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
184
204
  id: string;
185
205
  /** Fault only this operation. Omit to match every operation. */
186
206
  operationId?: string;
187
207
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
188
208
  method?: string;
209
+ /** Fault only this exact path. */
210
+ path?: string;
189
211
  /** Fault only paths starting with this prefix. Omit to match every path. */
190
212
  pathPrefix?: string;
213
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
214
+ pathPattern?: string;
215
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
216
+ requestHeaders?: Record<string, string>;
217
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
218
+ query?: Record<string, string>;
191
219
  /**
192
220
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
193
221
  * an in-process caller usually wants, and what a parallel worker usually does not:
194
222
  * rules added through `POST /__admin/faults` default to the calling namespace.
195
223
  */
196
224
  namespace?: string;
225
+ /** Let this many matching requests through first. */
226
+ after?: number;
227
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
228
+ every?: number;
229
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
230
+ count?: number;
231
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
232
+ rate?: number;
197
233
  /**
198
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
199
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
200
- * the request then still reaches the service.
234
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
235
+ * clock when the rule was added. Listed as epoch ms.
236
+ */
237
+ from?: Instant$1 | Duration$1;
238
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
239
+ until?: Instant$1 | Duration$1;
240
+ /**
241
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
242
+ * truncates, or switches on an `effect`: the request then still reaches the service.
201
243
  */
202
244
  status?: number;
203
245
  /** Response body, serialized as JSON. A string is sent as-is. */
204
246
  body?: unknown;
247
+ /** Response headers. */
205
248
  headers?: Record<string, string>;
206
- /** Retire the rule after this many faults. Omit to keep it until removed. */
207
- count?: number;
208
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
209
- rate?: number;
210
- /** Hold the response back this long, to exercise timeouts. */
249
+ /** Hold the response back this long. Listed as `delayMs`. */
250
+ delay?: Duration$1;
251
+ /** `delay`, in milliseconds. */
211
252
  delayMs?: number;
212
253
  /** Alias of `delayMs`. */
213
254
  latencyMs?: number;
255
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
256
+ jitter?: Duration$1;
257
+ jitterMs?: number;
258
+ /**
259
+ * Never answer: hold the request this long, then drop the connection. Listed as
260
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
261
+ */
262
+ timeout?: Duration$1;
263
+ timeoutMs?: number;
214
264
  /**
215
265
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
216
266
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
217
267
  */
218
268
  drop?: boolean;
269
+ /**
270
+ * Cut the response body off after this many bytes: the status and headers arrive, then
271
+ * the connection dies mid-body.
272
+ */
273
+ truncate?: number;
219
274
  /**
220
275
  * A named service behaviour to switch on for the matching request instead of (or
221
276
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -224,8 +279,8 @@ type FaultRule$1 = {
224
279
  effect?: string;
225
280
  /** Parameters for `effect`. */
226
281
  params?: Record<string, unknown>;
227
- /** From the preset this rule was expanded from, if any. */
228
- preset?: string;
282
+ /** The preset this rule was expanded from, if any. */
283
+ fromPreset?: string;
229
284
  };
230
285
  /** A fault that fired for one request. */
231
286
  type FaultHit$1 = {
@@ -233,6 +288,10 @@ type FaultHit$1 = {
233
288
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
234
289
  response?: Response;
235
290
  drop?: boolean;
291
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
292
+ timeout?: boolean;
293
+ /** Bytes of response body to let through before the connection dies. */
294
+ truncate?: number;
236
295
  effect?: {
237
296
  name: string;
238
297
  params: Record<string, unknown>;
@@ -244,38 +303,200 @@ type FaultCandidate$1 = {
244
303
  method: string;
245
304
  path: string;
246
305
  namespace: string;
306
+ /** Request headers and query, for rules that match on them. */
307
+ headers?: Headers;
308
+ query?: URLSearchParams;
309
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
310
+ now?: number;
311
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
312
+ wait?: (ms: number) => Promise<void>;
313
+ };
314
+ /** A stored rule and how often it was consulted. */
315
+ type FaultListing$1 = FaultRule$1 & {
316
+ /** Faults left before the rule retires. `null` when it has no `count`. */
317
+ remaining: number | null;
318
+ /** Times the rule faulted a request. */
319
+ hits: number;
320
+ /** Requests that matched the rule, faulted or not. */
321
+ seen: number;
322
+ };
323
+ /** A namespace's own rules, with their counters, in the order they are tried. */
324
+ type FaultSnapshot$1 = {
325
+ /**
326
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
327
+ * in the order means to a request and holds in any process.
328
+ */
329
+ rules: (FaultListing$1 & {
330
+ position?: number;
331
+ })[];
332
+ /** How many `fault_<n>` ids the namespace has handed out. */
333
+ nextId?: number;
247
334
  };
248
335
  type FaultRegistry$1 = {
249
- isolateNamespaces(): void;
250
- snapshot(namespace: string): {
251
- rules: (FaultRule$1 & {
252
- remaining: number | null;
253
- hits: number;
254
- position: number;
255
- })[];
256
- rngState: number;
257
- };
336
+ snapshot(namespace: string): FaultSnapshot$1;
337
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
258
338
  add(rule: FaultRule$1): FaultRule$1;
259
- list(): (FaultRule$1 & {
260
- remaining: number | null;
261
- hits: number;
262
- })[];
263
- remove(id: string): boolean;
264
- clear(): void;
265
- restore(namespace: string, state: {
266
- rules: (FaultRule$1 & {
267
- remaining: number | null;
268
- hits: number;
269
- position: number;
270
- })[];
271
- rngState: number;
272
- }): void;
339
+ /** The next unused `fault_<n>` id in `namespace`. */
340
+ nextId(namespace: string): string;
341
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
342
+ list(namespace?: string): FaultListing$1[];
343
+ get(id: string, namespace?: string): FaultListing$1 | undefined;
344
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
345
+ remove(id: string, namespace?: string): boolean;
346
+ /** Remove every rule, or one namespace's own rules. */
347
+ clear(namespace?: string): void;
348
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
349
+ restore(namespace: string, state: FaultSnapshot$1): void;
273
350
  /**
274
351
  * Every fault this request should get, in rule order, stopping at the first that answers
275
352
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
276
353
  * each matching rule's remaining uses.
277
354
  */
278
355
  take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
356
+ /**
357
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
358
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
359
+ */
360
+ fire(rules: readonly FaultRule$1[], candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
361
+ };
362
+
363
+ /**
364
+ * The admin controls every mock shares, as one document.
365
+ *
366
+ * The same shape is accepted in three places, and means the same thing in each:
367
+ *
368
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
369
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
370
+ * - over HTTP: `PUT /__admin/controls`
371
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
372
+ *
373
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
374
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
375
+ */
376
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
377
+ type Duration$1 = number | string;
378
+ /** Epoch milliseconds, or an ISO-8601 string. */
379
+ type Instant$1 = number | string;
380
+ type ClockControls$1 = {
381
+ /** Move the clock to this instant. */
382
+ now?: Instant$1;
383
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
384
+ frozen?: boolean;
385
+ /**
386
+ * Step the clock forward by this much before every vendor request. With a frozen clock
387
+ * each request still gets its own, reproducible timestamp.
388
+ */
389
+ autoAdvance?: Duration$1;
390
+ };
391
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
392
+ type LatencyRuleInput$1 = {
393
+ delay?: Duration$1;
394
+ jitter?: Duration$1;
395
+ };
396
+ type LatencyControls$1 = LatencyRuleInput$1 & {
397
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
398
+ operations?: Record<string, Duration$1 | LatencyRuleInput$1>;
399
+ };
400
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
401
+ type FaultInput$1 = (Omit<FaultRule$1, "id"> & {
402
+ id?: string;
403
+ }) | ({
404
+ preset: string;
405
+ } & Partial<FaultRule$1>);
406
+ /** Identifies a {@link SnapshotDocument}. */
407
+ declare const SNAPSHOT_FORMAT$1 = "mockingbird.snapshot/v1";
408
+ /**
409
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
410
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
411
+ * `records` are required, so a hand-written seed file is a valid snapshot.
412
+ */
413
+ type SnapshotDocument$1 = {
414
+ format: typeof SNAPSHOT_FORMAT$1;
415
+ /** The service that wrote it. A snapshot is rejected by any other service. */
416
+ service?: string;
417
+ /**
418
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
419
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
420
+ */
421
+ records: {
422
+ collection: string;
423
+ id: string;
424
+ seq?: number;
425
+ value?: unknown;
426
+ raw?: string;
427
+ }[];
428
+ /** Id counters, so the next generated id continues where the snapshot left off. */
429
+ sequences?: {
430
+ name: string;
431
+ kind: string;
432
+ value: number;
433
+ }[];
434
+ clock?: {
435
+ now: number;
436
+ frozen: boolean;
437
+ autoAdvanceMs?: number;
438
+ };
439
+ seed?: number | string;
440
+ /** Positions of the seeded random streams. */
441
+ rng?: {
442
+ state: number;
443
+ faults?: number;
444
+ latency?: number;
445
+ };
446
+ faults?: unknown;
447
+ latency?: unknown;
448
+ virtualTime?: boolean;
449
+ };
450
+ /** Controls for one namespace. */
451
+ type NamespaceControls$1 = {
452
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
453
+ seed?: number | string;
454
+ clock?: ClockControls$1;
455
+ /**
456
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
457
+ * wall clock: the request returns at once, the clock has moved, and the journal records
458
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
459
+ */
460
+ virtualTime?: boolean;
461
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
462
+ latency?: Duration$1 | LatencyControls$1;
463
+ faults?: readonly FaultInput$1[];
464
+ /** Start from this state instead of the service's own seed data. */
465
+ snapshot?: SnapshotDocument$1;
466
+ };
467
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
468
+ type MockControls$1 = NamespaceControls$1 & {
469
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
470
+ credentials?: Record<string, string>;
471
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
472
+ namespaces?: Record<string, NamespaceControls$1>;
473
+ };
474
+ /** A latency rule in milliseconds. */
475
+ type LatencyRule$1 = {
476
+ delayMs: number;
477
+ jitterMs: number;
478
+ };
479
+ /** Baseline latency for a namespace, normalized. */
480
+ type LatencyState$1 = LatencyRule$1 & {
481
+ operations: Record<string, LatencyRule$1>;
482
+ };
483
+ /** What {@link controlHeaders} turns into request headers. */
484
+ type ControlHeaderInput$1 = {
485
+ namespace?: string;
486
+ adminKey?: string;
487
+ branch?: string;
488
+ at?: string;
489
+ reset?: boolean;
490
+ restore?: string;
491
+ seed?: number | string;
492
+ time?: Instant$1 | Date;
493
+ advance?: Duration$1;
494
+ virtualTime?: boolean;
495
+ delay?: Duration$1;
496
+ timeout?: Duration$1;
497
+ /** A status, `"drop"`, a preset name, or a fault rule. */
498
+ fault?: number | string | Record<string, unknown>;
499
+ snapshot?: string;
279
500
  };
280
501
 
281
502
  /**
@@ -315,6 +536,8 @@ type RequestLog$1 = {
315
536
  unmatched: boolean;
316
537
  /** Set when a fault rule produced the response. */
317
538
  faultId?: string;
539
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
540
+ delayMs?: number;
318
541
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
319
542
  ids?: Record<string, string>;
320
543
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -360,6 +583,12 @@ type JournalQuery$1 = {
360
583
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
361
584
  namespace?: string;
362
585
  operationId?: string;
586
+ /** Only this HTTP method, case-insensitive. */
587
+ method?: string;
588
+ /** Only this exact path. */
589
+ path?: string;
590
+ /** Only requests this fault rule answered or shaped. */
591
+ faultId?: string;
363
592
  status?: number;
364
593
  /** Only entries at or after this instant (epoch ms). */
365
594
  since?: number;
@@ -374,6 +603,50 @@ type Journal$1 = {
374
603
  clear(namespace?: string): void;
375
604
  };
376
605
 
606
+ /**
607
+ * Baseline response time, per namespace: how long every vendor request takes before any
608
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
609
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
610
+ * fault hits.
611
+ */
612
+ type LatencyRegistry$1 = {
613
+ get(namespace: string): LatencyState$1;
614
+ set(namespace: string, state: LatencyState$1): LatencyState$1;
615
+ /** Remove one namespace's latency, or every namespace's. */
616
+ clear(namespace?: string): void;
617
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
618
+ take(namespace: string, operationId: string | undefined): number;
619
+ };
620
+
621
+ /** Clock state as the admin API reports it. */
622
+ type ControlClock$1 = ClockState$1 & {
623
+ /** `now`, as ISO-8601. */
624
+ iso: string;
625
+ /** Milliseconds the clock steps before every vendor request. */
626
+ autoAdvanceMs: number;
627
+ };
628
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
629
+ type ControlState$1 = {
630
+ namespace: string;
631
+ seed: number | string;
632
+ clock: ControlClock$1;
633
+ virtualTime: boolean;
634
+ latency: LatencyState$1;
635
+ faults: FaultListing$1[];
636
+ };
637
+
638
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
639
+ type SnapshotInfo$1 = {
640
+ id: string;
641
+ namespace: string;
642
+ /** Stored rows in the snapshot. */
643
+ records: number;
644
+ /** The namespace clock when it was taken, epoch ms. */
645
+ at: number;
646
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
647
+ portable: boolean;
648
+ };
649
+
377
650
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
378
651
  type CredentialRegistry$1 = {
379
652
  set(credential: string, namespace: string): void;
@@ -528,7 +801,10 @@ type ServiceInstance$1 = FetchAPI$2 & {
528
801
  };
529
802
  type ServiceTimelineState$1 = Readonly<{
530
803
  snapshot: NamespaceSnapshot$1;
531
- clock: Readonly<ReturnType<Clock$1["state"]>>;
804
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
805
+ clock: Readonly<ClockState$1 & {
806
+ pinned?: boolean;
807
+ }>;
532
808
  rngState: number;
533
809
  }>;
534
810
  type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
@@ -536,17 +812,23 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
536
812
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
537
813
  stop?(): void;
538
814
  readonly name: string;
815
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
816
+ mount(prefix: string): MountedAPI$1;
539
817
  readonly sqlite: SqliteClient$2;
540
818
  readonly clock: Clock$1;
541
819
  readonly faults: FaultRegistry$1;
820
+ /** Baseline response time per namespace. */
821
+ readonly latency: LatencyRegistry$1;
542
822
  readonly metrics: Metrics$1;
543
823
  readonly journal: Journal$1;
544
824
  readonly rng: Rng$1;
545
825
  readonly credentials: CredentialRegistry$1;
546
826
  /** The webhook hub, when the service has outbound webhooks. */
547
827
  readonly webhooks: WebhookHub$1 | undefined;
548
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
549
- isolateNamespaces(): void;
828
+ /**
829
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
830
+ * offset and a freeze of its own, so moving one never moves another.
831
+ */
550
832
  namespaceClock(namespace?: string): Clock$1;
551
833
  namespaceOf(request: Request): string;
552
834
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -558,8 +840,38 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
558
840
  instance(namespace?: string): T;
559
841
  /** Public names of every namespace created so far. */
560
842
  namespaces(): string[];
561
- /** Reset one namespace, or every namespace with `"*"`. */
843
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
562
844
  reset(namespace?: string): Promise<void>;
845
+ /** Reset a namespace and forget it, releasing everything it held. */
846
+ dropNamespace(namespace: string): Promise<void>;
847
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
848
+ controls(namespace?: string): ControlState$1 & {
849
+ snapshots: SnapshotInfo$1[];
850
+ };
851
+ /** Apply a control document to a namespace. A given key replaces that control. */
852
+ configure(controls: NamespaceControls$1, namespace?: string): ControlState$1 & {
853
+ snapshots: SnapshotInfo$1[];
854
+ };
855
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
856
+ readonly snapshots: {
857
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
858
+ create(options?: {
859
+ name?: string;
860
+ namespace?: string;
861
+ }): SnapshotInfo$1;
862
+ list(namespace?: string): SnapshotInfo$1[];
863
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
864
+ export(id: string, namespace?: string): SnapshotDocument$1;
865
+ /** Store a document as a snapshot without restoring it. */
866
+ import(document: SnapshotDocument$1, options?: {
867
+ name?: string;
868
+ namespace?: string;
869
+ }): SnapshotInfo$1;
870
+ restore(id: string, namespace?: string): void;
871
+ delete(id: string, namespace?: string): boolean;
872
+ };
873
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
874
+ headers(input: ControlHeaderInput$1): Record<string, string>;
563
875
  snapshot(namespace?: string): NamespaceSnapshot$1;
564
876
  restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
565
877
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -602,6 +914,11 @@ type CommonServeOptions = {
602
914
  adminKey: string | undefined;
603
915
  seed: string | undefined;
604
916
  onLog: ((entry: RequestLog$1) => void) | undefined;
917
+ /** Admin controls to boot with: clock, latency, faults, a starting snapshot. */
918
+ adminControls?: MockControls$1;
919
+ /** Synthetic provider fixture objects supplied by a fleet entry. */
920
+ fixtures?: Record<string, unknown>;
921
+ baseUrl?: string;
605
922
  };
606
923
  /**
607
924
  * What a service contributes to `serve`: how to build its runtime from CLI flags,
@@ -620,76 +937,16 @@ type ServeTarget = {
620
937
  listening?(server: Listening): void;
621
938
  };
622
939
 
623
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
624
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
625
- /** Mutation counters returned by {@link SqliteStatement.run}. */
626
- type SqliteRunResult$1 = {
627
- changes: number;
628
- lastInsertRowid: number | bigint;
940
+ type MountedAPI = FetchAPI$1 & {
941
+ readonly prefix: string;
942
+ GET: FetchHandler;
943
+ POST: FetchHandler;
944
+ PUT: FetchHandler;
945
+ PATCH: FetchHandler;
946
+ DELETE: FetchHandler;
947
+ HEAD: FetchHandler;
948
+ OPTIONS: FetchHandler;
629
949
  };
630
- /**
631
- * Prepared statement bound to a {@link SqliteClient}.
632
- *
633
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
634
- */
635
- interface SqliteStatement$1 {
636
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
637
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
638
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
639
- }
640
- /**
641
- * Sync SQLite client port owned by Mockingbird.
642
- *
643
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
644
- * `bun:sqlite` instances all work when they expose this surface.
645
- */
646
- interface SqliteClient$1 {
647
- exec(sql: string): void;
648
- prepare(sql: string): SqliteStatement$1;
649
- transaction<T>(fn: () => T): T;
650
- }
651
-
652
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
653
- type Stored<T> = {
654
- seq: number;
655
- value: T;
656
- };
657
- type ListRecordsOptions<T> = {
658
- /** Keep only records passing the predicate. */
659
- where?: (value: T, seq: number) => boolean;
660
- /** Sort order; default newest first. */
661
- order?: "newest" | "oldest";
662
- };
663
- /**
664
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
665
- * sequence, never by id lexicographic order, so list semantics stay stable.
666
- */
667
- declare class Collection<T> {
668
- private readonly sqlite;
669
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
670
- readonly namespace: string;
671
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
672
- readonly collectionName: string;
673
- constructor(sqlite: SqliteClient$1,
674
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
675
- namespace: string,
676
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
677
- collectionName: string);
678
- private bumpCollectionSeq;
679
- nextSequence(): number;
680
- get(id: string): T | undefined;
681
- has(id: string): boolean;
682
- /** Insert a new record, assigning it the next sequence number. */
683
- insert(id: string, value: T): Stored<T>;
684
- /** Replace an existing record's value, keeping its position. */
685
- update(id: string, value: T): Stored<T> | undefined;
686
- delete(id: string): boolean;
687
- /** How many records the collection holds, without reading them. */
688
- count(): number;
689
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
690
- id: string;
691
- }>;
692
- }
693
950
 
694
951
  /** A stable identifier for a point in a {@link Timeline}. */
695
952
  type CheckpointId = string;
@@ -780,6 +1037,79 @@ declare class Timeline<T> {
780
1037
  interface FetchAPI$1 {
781
1038
  fetch(request: Request): Promise<Response>;
782
1039
  }
1040
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
1041
+ type FetchHandler = (request: Request) => Promise<Response>;
1042
+
1043
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1044
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
1045
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1046
+ type SqliteRunResult$1 = {
1047
+ changes: number;
1048
+ lastInsertRowid: number | bigint;
1049
+ };
1050
+ /**
1051
+ * Prepared statement bound to a {@link SqliteClient}.
1052
+ *
1053
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1054
+ */
1055
+ interface SqliteStatement$1 {
1056
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
1057
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
1058
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
1059
+ }
1060
+ /**
1061
+ * Sync SQLite client port owned by Mockingbird.
1062
+ *
1063
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1064
+ * `bun:sqlite` instances all work when they expose this surface.
1065
+ */
1066
+ interface SqliteClient$1 {
1067
+ exec(sql: string): void;
1068
+ prepare(sql: string): SqliteStatement$1;
1069
+ transaction<T>(fn: () => T): T;
1070
+ }
1071
+
1072
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
1073
+ type Stored<T> = {
1074
+ seq: number;
1075
+ value: T;
1076
+ };
1077
+ type ListRecordsOptions<T> = {
1078
+ /** Keep only records passing the predicate. */
1079
+ where?: (value: T, seq: number) => boolean;
1080
+ /** Sort order; default newest first. */
1081
+ order?: "newest" | "oldest";
1082
+ };
1083
+ /**
1084
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
1085
+ * sequence, never by id lexicographic order, so list semantics stay stable.
1086
+ */
1087
+ declare class Collection<T> {
1088
+ private readonly sqlite;
1089
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1090
+ readonly namespace: string;
1091
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1092
+ readonly collectionName: string;
1093
+ constructor(sqlite: SqliteClient$1,
1094
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1095
+ namespace: string,
1096
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1097
+ collectionName: string);
1098
+ private bumpCollectionSeq;
1099
+ nextSequence(): number;
1100
+ get(id: string): T | undefined;
1101
+ has(id: string): boolean;
1102
+ /** Insert a new record, assigning it the next sequence number. */
1103
+ insert(id: string, value: T): Stored<T>;
1104
+ /** Replace an existing record's value, keeping its position. */
1105
+ update(id: string, value: T): Stored<T> | undefined;
1106
+ delete(id: string): boolean;
1107
+ /** How many records the collection holds, without reading them. */
1108
+ count(): number;
1109
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
1110
+ id: string;
1111
+ }>;
1112
+ }
783
1113
 
784
1114
  /** Options every provider constructor accepts. */
785
1115
  type APIOptions = {
@@ -806,7 +1136,7 @@ type ClockState = {
806
1136
  now: number;
807
1137
  /** True while time does not advance on its own. */
808
1138
  frozen: boolean;
809
- /** Milliseconds this clock adds to its underlying source. */
1139
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
810
1140
  offsetMs: number;
811
1141
  };
812
1142
  type Clock = {
@@ -842,7 +1172,10 @@ type Rng = {
842
1172
  state(): number;
843
1173
  /** Restore a state previously returned by {@link state}. */
844
1174
  setState(state: number): void;
845
- seed: number;
1175
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
1176
+ reseed(seed: number | string): void;
1177
+ /** The seed the stream currently starts from. */
1178
+ readonly seed: number;
846
1179
  };
847
1180
 
848
1181
  /**
@@ -851,44 +1184,83 @@ type Rng = {
851
1184
  * This is how a suite reaches the vendor's failure modes without the vendor: the
852
1185
  * quota error that only appears when a shared sandbox is full, the 429 that only
853
1186
  * appears under load, the 5xx that proves a retry path works.
1187
+ *
1188
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
1189
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
1190
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
854
1191
  */
855
1192
  type FaultRule = {
856
- /** Stable id, so a suite can retire exactly the rule it added. */
1193
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
857
1194
  id: string;
858
1195
  /** Fault only this operation. Omit to match every operation. */
859
1196
  operationId?: string;
860
1197
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
861
1198
  method?: string;
1199
+ /** Fault only this exact path. */
1200
+ path?: string;
862
1201
  /** Fault only paths starting with this prefix. Omit to match every path. */
863
1202
  pathPrefix?: string;
1203
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
1204
+ pathPattern?: string;
1205
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
1206
+ requestHeaders?: Record<string, string>;
1207
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
1208
+ query?: Record<string, string>;
864
1209
  /**
865
1210
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
866
1211
  * an in-process caller usually wants, and what a parallel worker usually does not:
867
1212
  * rules added through `POST /__admin/faults` default to the calling namespace.
868
1213
  */
869
1214
  namespace?: string;
1215
+ /** Let this many matching requests through first. */
1216
+ after?: number;
1217
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
1218
+ every?: number;
1219
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
1220
+ count?: number;
1221
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
1222
+ rate?: number;
870
1223
  /**
871
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
872
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
873
- * the request then still reaches the service.
1224
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
1225
+ * clock when the rule was added. Listed as epoch ms.
1226
+ */
1227
+ from?: Instant | Duration;
1228
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
1229
+ until?: Instant | Duration;
1230
+ /**
1231
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
1232
+ * truncates, or switches on an `effect`: the request then still reaches the service.
874
1233
  */
875
1234
  status?: number;
876
1235
  /** Response body, serialized as JSON. A string is sent as-is. */
877
1236
  body?: unknown;
1237
+ /** Response headers. */
878
1238
  headers?: Record<string, string>;
879
- /** Retire the rule after this many faults. Omit to keep it until removed. */
880
- count?: number;
881
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
882
- rate?: number;
883
- /** Hold the response back this long, to exercise timeouts. */
1239
+ /** Hold the response back this long. Listed as `delayMs`. */
1240
+ delay?: Duration;
1241
+ /** `delay`, in milliseconds. */
884
1242
  delayMs?: number;
885
1243
  /** Alias of `delayMs`. */
886
1244
  latencyMs?: number;
1245
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
1246
+ jitter?: Duration;
1247
+ jitterMs?: number;
1248
+ /**
1249
+ * Never answer: hold the request this long, then drop the connection. Listed as
1250
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
1251
+ */
1252
+ timeout?: Duration;
1253
+ timeoutMs?: number;
887
1254
  /**
888
1255
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
889
1256
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
890
1257
  */
891
1258
  drop?: boolean;
1259
+ /**
1260
+ * Cut the response body off after this many bytes: the status and headers arrive, then
1261
+ * the connection dies mid-body.
1262
+ */
1263
+ truncate?: number;
892
1264
  /**
893
1265
  * A named service behaviour to switch on for the matching request instead of (or
894
1266
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -897,8 +1269,8 @@ type FaultRule = {
897
1269
  effect?: string;
898
1270
  /** Parameters for `effect`. */
899
1271
  params?: Record<string, unknown>;
900
- /** From the preset this rule was expanded from, if any. */
901
- preset?: string;
1272
+ /** The preset this rule was expanded from, if any. */
1273
+ fromPreset?: string;
902
1274
  };
903
1275
  /** A fault that fired for one request. */
904
1276
  type FaultHit = {
@@ -906,6 +1278,10 @@ type FaultHit = {
906
1278
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
907
1279
  response?: Response;
908
1280
  drop?: boolean;
1281
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
1282
+ timeout?: boolean;
1283
+ /** Bytes of response body to let through before the connection dies. */
1284
+ truncate?: number;
909
1285
  effect?: {
910
1286
  name: string;
911
1287
  params: Record<string, unknown>;
@@ -917,38 +1293,200 @@ type FaultCandidate = {
917
1293
  method: string;
918
1294
  path: string;
919
1295
  namespace: string;
1296
+ /** Request headers and query, for rules that match on them. */
1297
+ headers?: Headers;
1298
+ query?: URLSearchParams;
1299
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
1300
+ now?: number;
1301
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
1302
+ wait?: (ms: number) => Promise<void>;
1303
+ };
1304
+ /** A stored rule and how often it was consulted. */
1305
+ type FaultListing = FaultRule & {
1306
+ /** Faults left before the rule retires. `null` when it has no `count`. */
1307
+ remaining: number | null;
1308
+ /** Times the rule faulted a request. */
1309
+ hits: number;
1310
+ /** Requests that matched the rule, faulted or not. */
1311
+ seen: number;
1312
+ };
1313
+ /** A namespace's own rules, with their counters, in the order they are tried. */
1314
+ type FaultSnapshot = {
1315
+ /**
1316
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
1317
+ * in the order means to a request and holds in any process.
1318
+ */
1319
+ rules: (FaultListing & {
1320
+ position?: number;
1321
+ })[];
1322
+ /** How many `fault_<n>` ids the namespace has handed out. */
1323
+ nextId?: number;
920
1324
  };
921
1325
  type FaultRegistry = {
922
- isolateNamespaces(): void;
923
- snapshot(namespace: string): {
924
- rules: (FaultRule & {
925
- remaining: number | null;
926
- hits: number;
927
- position: number;
928
- })[];
929
- rngState: number;
930
- };
1326
+ snapshot(namespace: string): FaultSnapshot;
1327
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
931
1328
  add(rule: FaultRule): FaultRule;
932
- list(): (FaultRule & {
933
- remaining: number | null;
934
- hits: number;
935
- })[];
936
- remove(id: string): boolean;
937
- clear(): void;
938
- restore(namespace: string, state: {
939
- rules: (FaultRule & {
940
- remaining: number | null;
941
- hits: number;
942
- position: number;
943
- })[];
944
- rngState: number;
945
- }): void;
1329
+ /** The next unused `fault_<n>` id in `namespace`. */
1330
+ nextId(namespace: string): string;
1331
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
1332
+ list(namespace?: string): FaultListing[];
1333
+ get(id: string, namespace?: string): FaultListing | undefined;
1334
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
1335
+ remove(id: string, namespace?: string): boolean;
1336
+ /** Remove every rule, or one namespace's own rules. */
1337
+ clear(namespace?: string): void;
1338
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
1339
+ restore(namespace: string, state: FaultSnapshot): void;
946
1340
  /**
947
1341
  * Every fault this request should get, in rule order, stopping at the first that answers
948
1342
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
949
1343
  * each matching rule's remaining uses.
950
1344
  */
951
1345
  take(candidate: FaultCandidate): Promise<FaultHit[]>;
1346
+ /**
1347
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
1348
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
1349
+ */
1350
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
1351
+ };
1352
+
1353
+ /**
1354
+ * The admin controls every mock shares, as one document.
1355
+ *
1356
+ * The same shape is accepted in three places, and means the same thing in each:
1357
+ *
1358
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
1359
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
1360
+ * - over HTTP: `PUT /__admin/controls`
1361
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
1362
+ *
1363
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
1364
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
1365
+ */
1366
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
1367
+ type Duration = number | string;
1368
+ /** Epoch milliseconds, or an ISO-8601 string. */
1369
+ type Instant = number | string;
1370
+ type ClockControls = {
1371
+ /** Move the clock to this instant. */
1372
+ now?: Instant;
1373
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
1374
+ frozen?: boolean;
1375
+ /**
1376
+ * Step the clock forward by this much before every vendor request. With a frozen clock
1377
+ * each request still gets its own, reproducible timestamp.
1378
+ */
1379
+ autoAdvance?: Duration;
1380
+ };
1381
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
1382
+ type LatencyRuleInput = {
1383
+ delay?: Duration;
1384
+ jitter?: Duration;
1385
+ };
1386
+ type LatencyControls = LatencyRuleInput & {
1387
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
1388
+ operations?: Record<string, Duration | LatencyRuleInput>;
1389
+ };
1390
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
1391
+ type FaultInput = (Omit<FaultRule, "id"> & {
1392
+ id?: string;
1393
+ }) | ({
1394
+ preset: string;
1395
+ } & Partial<FaultRule>);
1396
+ /** Identifies a {@link SnapshotDocument}. */
1397
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
1398
+ /**
1399
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
1400
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
1401
+ * `records` are required, so a hand-written seed file is a valid snapshot.
1402
+ */
1403
+ type SnapshotDocument = {
1404
+ format: typeof SNAPSHOT_FORMAT;
1405
+ /** The service that wrote it. A snapshot is rejected by any other service. */
1406
+ service?: string;
1407
+ /**
1408
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
1409
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
1410
+ */
1411
+ records: {
1412
+ collection: string;
1413
+ id: string;
1414
+ seq?: number;
1415
+ value?: unknown;
1416
+ raw?: string;
1417
+ }[];
1418
+ /** Id counters, so the next generated id continues where the snapshot left off. */
1419
+ sequences?: {
1420
+ name: string;
1421
+ kind: string;
1422
+ value: number;
1423
+ }[];
1424
+ clock?: {
1425
+ now: number;
1426
+ frozen: boolean;
1427
+ autoAdvanceMs?: number;
1428
+ };
1429
+ seed?: number | string;
1430
+ /** Positions of the seeded random streams. */
1431
+ rng?: {
1432
+ state: number;
1433
+ faults?: number;
1434
+ latency?: number;
1435
+ };
1436
+ faults?: unknown;
1437
+ latency?: unknown;
1438
+ virtualTime?: boolean;
1439
+ };
1440
+ /** Controls for one namespace. */
1441
+ type NamespaceControls = {
1442
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
1443
+ seed?: number | string;
1444
+ clock?: ClockControls;
1445
+ /**
1446
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
1447
+ * wall clock: the request returns at once, the clock has moved, and the journal records
1448
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
1449
+ */
1450
+ virtualTime?: boolean;
1451
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
1452
+ latency?: Duration | LatencyControls;
1453
+ faults?: readonly FaultInput[];
1454
+ /** Start from this state instead of the service's own seed data. */
1455
+ snapshot?: SnapshotDocument;
1456
+ };
1457
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
1458
+ type MockControls = NamespaceControls & {
1459
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
1460
+ credentials?: Record<string, string>;
1461
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
1462
+ namespaces?: Record<string, NamespaceControls>;
1463
+ };
1464
+ /** A latency rule in milliseconds. */
1465
+ type LatencyRule = {
1466
+ delayMs: number;
1467
+ jitterMs: number;
1468
+ };
1469
+ /** Baseline latency for a namespace, normalized. */
1470
+ type LatencyState = LatencyRule & {
1471
+ operations: Record<string, LatencyRule>;
1472
+ };
1473
+ /** What {@link controlHeaders} turns into request headers. */
1474
+ type ControlHeaderInput = {
1475
+ namespace?: string;
1476
+ adminKey?: string;
1477
+ branch?: string;
1478
+ at?: string;
1479
+ reset?: boolean;
1480
+ restore?: string;
1481
+ seed?: number | string;
1482
+ time?: Instant | Date;
1483
+ advance?: Duration;
1484
+ virtualTime?: boolean;
1485
+ delay?: Duration;
1486
+ timeout?: Duration;
1487
+ /** A status, `"drop"`, a preset name, or a fault rule. */
1488
+ fault?: number | string | Record<string, unknown>;
1489
+ snapshot?: string;
952
1490
  };
953
1491
 
954
1492
  /**
@@ -988,6 +1526,8 @@ type RequestLog = {
988
1526
  unmatched: boolean;
989
1527
  /** Set when a fault rule produced the response. */
990
1528
  faultId?: string;
1529
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
1530
+ delayMs?: number;
991
1531
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
992
1532
  ids?: Record<string, string>;
993
1533
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -1033,6 +1573,12 @@ type JournalQuery = {
1033
1573
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
1034
1574
  namespace?: string;
1035
1575
  operationId?: string;
1576
+ /** Only this HTTP method, case-insensitive. */
1577
+ method?: string;
1578
+ /** Only this exact path. */
1579
+ path?: string;
1580
+ /** Only requests this fault rule answered or shaped. */
1581
+ faultId?: string;
1036
1582
  status?: number;
1037
1583
  /** Only entries at or after this instant (epoch ms). */
1038
1584
  since?: number;
@@ -1047,6 +1593,50 @@ type Journal = {
1047
1593
  clear(namespace?: string): void;
1048
1594
  };
1049
1595
 
1596
+ /**
1597
+ * Baseline response time, per namespace: how long every vendor request takes before any
1598
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
1599
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
1600
+ * fault hits.
1601
+ */
1602
+ type LatencyRegistry = {
1603
+ get(namespace: string): LatencyState;
1604
+ set(namespace: string, state: LatencyState): LatencyState;
1605
+ /** Remove one namespace's latency, or every namespace's. */
1606
+ clear(namespace?: string): void;
1607
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
1608
+ take(namespace: string, operationId: string | undefined): number;
1609
+ };
1610
+
1611
+ /** Clock state as the admin API reports it. */
1612
+ type ControlClock = ClockState & {
1613
+ /** `now`, as ISO-8601. */
1614
+ iso: string;
1615
+ /** Milliseconds the clock steps before every vendor request. */
1616
+ autoAdvanceMs: number;
1617
+ };
1618
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
1619
+ type ControlState = {
1620
+ namespace: string;
1621
+ seed: number | string;
1622
+ clock: ControlClock;
1623
+ virtualTime: boolean;
1624
+ latency: LatencyState;
1625
+ faults: FaultListing[];
1626
+ };
1627
+
1628
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
1629
+ type SnapshotInfo = {
1630
+ id: string;
1631
+ namespace: string;
1632
+ /** Stored rows in the snapshot. */
1633
+ records: number;
1634
+ /** The namespace clock when it was taken, epoch ms. */
1635
+ at: number;
1636
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
1637
+ portable: boolean;
1638
+ };
1639
+
1050
1640
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
1051
1641
  type CredentialRegistry = {
1052
1642
  set(credential: string, namespace: string): void;
@@ -1201,7 +1791,10 @@ type ServiceInstance = FetchAPI$1 & {
1201
1791
  };
1202
1792
  type ServiceTimelineState = Readonly<{
1203
1793
  snapshot: NamespaceSnapshot;
1204
- clock: Readonly<ReturnType<Clock["state"]>>;
1794
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
1795
+ clock: Readonly<ClockState & {
1796
+ pinned?: boolean;
1797
+ }>;
1205
1798
  rngState: number;
1206
1799
  }>;
1207
1800
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -1209,17 +1802,23 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
1209
1802
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1210
1803
  stop?(): void;
1211
1804
  readonly name: string;
1805
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1806
+ mount(prefix: string): MountedAPI;
1212
1807
  readonly sqlite: SqliteClient$1;
1213
1808
  readonly clock: Clock;
1214
1809
  readonly faults: FaultRegistry;
1810
+ /** Baseline response time per namespace. */
1811
+ readonly latency: LatencyRegistry;
1215
1812
  readonly metrics: Metrics;
1216
1813
  readonly journal: Journal;
1217
1814
  readonly rng: Rng;
1218
1815
  readonly credentials: CredentialRegistry;
1219
1816
  /** The webhook hub, when the service has outbound webhooks. */
1220
1817
  readonly webhooks: WebhookHub | undefined;
1221
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
1222
- isolateNamespaces(): void;
1818
+ /**
1819
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
1820
+ * offset and a freeze of its own, so moving one never moves another.
1821
+ */
1223
1822
  namespaceClock(namespace?: string): Clock;
1224
1823
  namespaceOf(request: Request): string;
1225
1824
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -1231,8 +1830,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
1231
1830
  instance(namespace?: string): T;
1232
1831
  /** Public names of every namespace created so far. */
1233
1832
  namespaces(): string[];
1234
- /** Reset one namespace, or every namespace with `"*"`. */
1833
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
1235
1834
  reset(namespace?: string): Promise<void>;
1835
+ /** Reset a namespace and forget it, releasing everything it held. */
1836
+ dropNamespace(namespace: string): Promise<void>;
1837
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
1838
+ controls(namespace?: string): ControlState & {
1839
+ snapshots: SnapshotInfo[];
1840
+ };
1841
+ /** Apply a control document to a namespace. A given key replaces that control. */
1842
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
1843
+ snapshots: SnapshotInfo[];
1844
+ };
1845
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
1846
+ readonly snapshots: {
1847
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
1848
+ create(options?: {
1849
+ name?: string;
1850
+ namespace?: string;
1851
+ }): SnapshotInfo;
1852
+ list(namespace?: string): SnapshotInfo[];
1853
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
1854
+ export(id: string, namespace?: string): SnapshotDocument;
1855
+ /** Store a document as a snapshot without restoring it. */
1856
+ import(document: SnapshotDocument, options?: {
1857
+ name?: string;
1858
+ namespace?: string;
1859
+ }): SnapshotInfo;
1860
+ restore(id: string, namespace?: string): void;
1861
+ delete(id: string, namespace?: string): boolean;
1862
+ };
1863
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
1864
+ headers(input: ControlHeaderInput): Record<string, string>;
1236
1865
  snapshot(namespace?: string): NamespaceSnapshot;
1237
1866
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1238
1867
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -1371,6 +2000,8 @@ type WorkOSRuntimeOptions = Omit<WorkOSAPIOptions, "namespace" | "now"> & {
1371
2000
  seed?: string | number;
1372
2001
  adminPrefix?: string;
1373
2002
  adminKey?: string;
2003
+ /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
2004
+ adminControls?: MockControls;
1374
2005
  onLog?: (entry: RequestLog) => void;
1375
2006
  };
1376
2007
  type WorkOSRuntime = ServiceRuntime<WorkOSAPI>;