@crvouga/mockingbird-service-cloudcontrol 1.11.0 → 1.12.1

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
@@ -1,997 +1,5 @@
1
1
  import { Server } from 'node:http';
2
-
3
- type MountedAPI$1 = FetchAPI$1 & {
4
- readonly prefix: string;
5
- GET: FetchHandler$1;
6
- POST: FetchHandler$1;
7
- PUT: FetchHandler$1;
8
- PATCH: FetchHandler$1;
9
- DELETE: FetchHandler$1;
10
- HEAD: FetchHandler$1;
11
- OPTIONS: FetchHandler$1;
12
- };
13
-
14
- /** A stable identifier for a point in a {@link Timeline}. */
15
- type CheckpointId$1 = string;
16
- /** An immutable node in a timeline's checkpoint DAG. */
17
- type Checkpoint$1<T> = Readonly<{
18
- id: CheckpointId$1;
19
- branch: string;
20
- parent: CheckpointId$1 | null;
21
- /** Logical time supplied by the timeline's injected clock. */
22
- at: number;
23
- value: T;
24
- }>;
25
- type TimelineOptions$1 = {
26
- /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
27
- now?: () => number;
28
- /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
29
- maxCheckpoints?: number;
30
- /** Customize deterministic checkpoint IDs. */
31
- id?: (sequence: number) => CheckpointId$1;
32
- };
33
- type CommitOptions$1 = {
34
- branch?: string;
35
- /** Parent checkpoint. Defaults to the selected branch's current head. */
36
- parent?: CheckpointId$1 | null;
37
- };
38
- type ForkOptions$1 = {
39
- /** Checkpoint to fork from. Defaults to the main branch's head. */
40
- from?: CheckpointId$1;
41
- };
42
- /**
43
- * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
44
- * records, namespace images, or copy-on-write SQL engine snapshots.
45
- *
46
- * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
47
- * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
48
- * (the logical clock) is injected.
49
- */
50
- declare class Timeline$1<T> {
51
- readonly maxCheckpoints: number;
52
- private readonly now;
53
- private readonly makeId;
54
- private readonly nodes;
55
- private readonly heads;
56
- /** Unreferenced nodes in the exact order they became collectible. */
57
- private readonly evictable;
58
- /** Branch heads plus explicit retainers. Absent means zero. */
59
- private readonly references;
60
- private readonly explicitPins;
61
- private sequence;
62
- constructor(options?: TimelineOptions$1);
63
- /** Capture a new immutable value and move `branch` to it. */
64
- commit(value: T, options?: CommitOptions$1): Checkpoint$1<T>;
65
- /** Create a branch pointer without copying its checkpoint value. */
66
- fork(branch: string, options?: ForkOptions$1): Checkpoint$1<T> | undefined;
67
- /** Move a branch pointer to an existing checkpoint. */
68
- checkout(branch: string, id: CheckpointId$1): Checkpoint$1<T>;
69
- get(id: CheckpointId$1): Checkpoint$1<T>;
70
- head(branch?: string): Checkpoint$1<T> | undefined;
71
- hasBranch(branch: string): boolean;
72
- branches(): Readonly<Record<string, CheckpointId$1>>;
73
- checkpoints(): readonly Checkpoint$1<T>[];
74
- /** Number of retained checkpoints without allocating an array. */
75
- get size(): number;
76
- /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
77
- retain(id: CheckpointId$1): Checkpoint$1<T>;
78
- /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
79
- release(id: CheckpointId$1): boolean;
80
- deleteBranch(branch: string): boolean;
81
- /**
82
- * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
83
- * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
84
- * storage dependency, so a retained node remains usable after pruning.
85
- */
86
- gc(max?: number): CheckpointId$1[];
87
- private collect;
88
- private moveHead;
89
- private addReference;
90
- private removeReference;
91
- private assertBranch;
92
- }
93
-
94
- /**
95
- * Anything that can answer a Fetch `Request` with a `Response`.
96
- *
97
- * Every Mockingbird service implements this, and every runtime adapter consumes it.
98
- * It is the only contract shared across the whole graph.
99
- */
100
- interface FetchAPI$1 {
101
- fetch(request: Request): Promise<Response>;
102
- }
103
- /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
104
- type FetchHandler$1 = (request: Request) => Promise<Response>;
105
-
106
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
107
- type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
108
- /** Mutation counters returned by {@link SqliteStatement.run}. */
109
- type SqliteRunResult$2 = {
110
- changes: number;
111
- lastInsertRowid: number | bigint;
112
- };
113
- /**
114
- * Prepared statement bound to a {@link SqliteClient}.
115
- *
116
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
117
- */
118
- interface SqliteStatement$2 {
119
- run(...params: SqliteValue$2[]): SqliteRunResult$2;
120
- all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
121
- get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
122
- }
123
- /**
124
- * Sync SQLite client port owned by Mockingbird.
125
- *
126
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
127
- * `bun:sqlite` instances all work when they expose this surface.
128
- */
129
- interface SqliteClient$2 {
130
- exec(sql: string): void;
131
- prepare(sql: string): SqliteStatement$2;
132
- transaction<T>(fn: () => T): T;
133
- }
134
-
135
- /**
136
- * What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
137
- * which derives the base from the wall clock when the runtime is created.
138
- */
139
- type IdBase$1 = number | string;
140
-
141
- /**
142
- * The single source of time for a service.
143
- *
144
- * Every timestamp a mock writes reads from here, so a suite moves time instead of
145
- * sleeping: appointment windows, result delays and expiries become reachable in
146
- * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
147
- */
148
- type ClockState$1 = {
149
- /** Current epoch milliseconds. */
150
- now: number;
151
- /** True while time does not advance on its own. */
152
- frozen: boolean;
153
- /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
154
- offsetMs: number;
155
- };
156
- type Clock$1 = {
157
- now(): number;
158
- /** Pin the clock to an exact instant, keeping it frozen if it already was. */
159
- set(epochMs: number): void;
160
- /** Move the clock forward, or back with a negative delta. */
161
- advance(deltaMs: number): void;
162
- /** Stop time at the current instant. */
163
- freeze(): void;
164
- /** Resume from the current instant. */
165
- unfreeze(): void;
166
- /** Drop back to the underlying source, live. */
167
- reset(): void;
168
- state(): ClockState$1;
169
- };
170
-
171
- /**
172
- * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
173
- * request a percentage fault hits — is reproducible from a seed.
174
- *
175
- * mulberry32: small, fast, and stable across runtimes, which matters more here
176
- * than statistical quality.
177
- */
178
- type Rng$1 = {
179
- /** Next value in `[0, 1)`. */
180
- next(): number;
181
- /** Next integer in `[min, max]`. */
182
- int(min: number, max: number): number;
183
- /** Restart the stream from its seed. */
184
- reset(): void;
185
- /** Serializable engine state used by deterministic checkpoints. */
186
- state(): number;
187
- /** Restore a state previously returned by {@link state}. */
188
- setState(state: number): void;
189
- /** Restart the stream from a new seed. `reset` then returns to this seed. */
190
- reseed(seed: number | string): void;
191
- /** The seed the stream currently starts from. */
192
- readonly seed: number;
193
- };
194
-
195
- /**
196
- * A deliberate failure injected in front of an operation.
197
- *
198
- * This is how a suite reaches the vendor's failure modes without the vendor: the
199
- * quota error that only appears when a shared sandbox is full, the 429 that only
200
- * appears under load, the 5xx that proves a retry path works.
201
- *
202
- * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
203
- * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
204
- * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
205
- */
206
- type FaultRule$1 = {
207
- /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
208
- id: string;
209
- /** Fault only this operation. Omit to match every operation. */
210
- operationId?: string;
211
- /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
212
- method?: string;
213
- /** Fault only this exact path. */
214
- path?: string;
215
- /** Fault only paths starting with this prefix. Omit to match every path. */
216
- pathPrefix?: string;
217
- /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
218
- pathPattern?: string;
219
- /** Fault only requests carrying these headers. `"*"` matches any value. */
220
- requestHeaders?: Record<string, string>;
221
- /** Fault only requests carrying these query parameters. `"*"` matches any value. */
222
- query?: Record<string, string>;
223
- /**
224
- * Fault only requests whose JSON body carries these fields. Each key is a dotted path into
225
- * the parsed body (`"patient_details.email"`; a number steps into an array, `"items.0.sku"`)
226
- * and each value is what the field must equal: a string, number, boolean or `null`, compared
227
- * strictly (`3` is not `"3"`). `"*"` matches any value that is present. A request whose body
228
- * is missing, is not JSON, or is not a JSON object never matches. Not `body`, which is the
229
- * response a rule injects.
230
- */
231
- requestBody?: Record<string, RequestBodyValue$1>;
232
- /**
233
- * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
234
- * an in-process caller usually wants, and what a parallel worker usually does not:
235
- * rules added through `POST /__admin/faults` default to the calling namespace.
236
- */
237
- namespace?: string;
238
- /** Let this many matching requests through first. */
239
- after?: number;
240
- /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
241
- every?: number;
242
- /** Retire the rule after this many faults. Omit to keep it until removed. */
243
- count?: number;
244
- /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
245
- rate?: number;
246
- /**
247
- * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
248
- * clock when the rule was added. Listed as epoch ms.
249
- */
250
- from?: Instant$1 | Duration$1;
251
- /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
252
- until?: Instant$1 | Duration$1;
253
- /**
254
- * Status of the injected response. Omit for a rule that only delays, times out, drops,
255
- * truncates, or switches on an `effect`: the request then still reaches the service.
256
- */
257
- status?: number;
258
- /** Response body, serialized as JSON. A string is sent as-is. */
259
- body?: unknown;
260
- /** Response headers. */
261
- headers?: Record<string, string>;
262
- /** Hold the response back this long. Listed as `delayMs`. */
263
- delay?: Duration$1;
264
- /** `delay`, in milliseconds. */
265
- delayMs?: number;
266
- /** Alias of `delayMs`. */
267
- latencyMs?: number;
268
- /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
269
- jitter?: Duration$1;
270
- jitterMs?: number;
271
- /**
272
- * Never answer: hold the request this long, then drop the connection. Listed as
273
- * `timeoutMs`. With virtual time the wait is spent on the mock clock.
274
- */
275
- timeout?: Duration$1;
276
- timeoutMs?: number;
277
- /**
278
- * Drop the connection instead of answering: an in-process `fetch` rejects with a
279
- * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
280
- */
281
- drop?: boolean;
282
- /**
283
- * Cut the response body off after this many bytes: the status and headers arrive, then
284
- * the connection dies mid-body.
285
- */
286
- truncate?: number;
287
- /**
288
- * A named service behaviour to switch on for the matching request instead of (or
289
- * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
290
- * read it with `faultEffects(request)`.
291
- */
292
- effect?: string;
293
- /** Parameters for `effect`. */
294
- params?: Record<string, unknown>;
295
- /** The preset this rule was expanded from, if any. */
296
- fromPreset?: string;
297
- };
298
- /** What a field of the request body must equal in {@link FaultRule.requestBody}. */
299
- type RequestBodyValue$1 = string | number | boolean | null;
300
- /** A fault that fired for one request. */
301
- type FaultHit$1 = {
302
- id: string;
303
- /** The injected response; absent when the rule only delays, drops, or sets an effect. */
304
- response?: Response;
305
- drop?: boolean;
306
- /** Set with `drop` when the rule held the request for its `timeout` first. */
307
- timeout?: boolean;
308
- /** Bytes of response body to let through before the connection dies. */
309
- truncate?: number;
310
- effect?: {
311
- name: string;
312
- params: Record<string, unknown>;
313
- };
314
- };
315
- /** What a request looks like to the fault matcher. */
316
- type FaultCandidate$1 = {
317
- operationId: string | undefined;
318
- method: string;
319
- path: string;
320
- namespace: string;
321
- /** Request headers and query, for rules that match on them. */
322
- headers?: Headers;
323
- query?: URLSearchParams;
324
- /**
325
- * The request body parsed as JSON, read only when a rule matches on `requestBody`. Resolve
326
- * `undefined` for a body that is missing or not JSON. It must leave the request readable.
327
- */
328
- readJson?: () => Promise<unknown>;
329
- /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
330
- now?: number;
331
- /** How to spend a delay for this request. Default: the registry's own sleep. */
332
- wait?: (ms: number) => Promise<void>;
333
- };
334
- /** A stored rule and how often it was consulted. */
335
- type FaultListing$1 = FaultRule$1 & {
336
- /** Faults left before the rule retires. `null` when it has no `count`. */
337
- remaining: number | null;
338
- /** Times the rule faulted a request. */
339
- hits: number;
340
- /** Requests that matched the rule, faulted or not. */
341
- seen: number;
342
- };
343
- /** A namespace's own rules, with their counters, in the order they are tried. */
344
- type FaultSnapshot$1 = {
345
- /**
346
- * `position` is how many `"*"` rules are tried before the rule, which is what its place
347
- * in the order means to a request and holds in any process.
348
- */
349
- rules: (FaultListing$1 & {
350
- position?: number;
351
- })[];
352
- /** How many `fault_<n>` ids the namespace has handed out. */
353
- nextId?: number;
354
- };
355
- type FaultRegistry$1 = {
356
- snapshot(namespace: string): FaultSnapshot$1;
357
- /** Add a rule, or replace the rule with the same id in the same namespace. */
358
- add(rule: FaultRule$1): FaultRule$1;
359
- /** The next unused `fault_<n>` id in `namespace`. */
360
- nextId(namespace: string): string;
361
- /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
362
- list(namespace?: string): FaultListing$1[];
363
- get(id: string, namespace?: string): FaultListing$1 | undefined;
364
- /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
365
- remove(id: string, namespace?: string): boolean;
366
- /** Remove every rule, or one namespace's own rules. */
367
- clear(namespace?: string): void;
368
- /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
369
- restore(namespace: string, state: FaultSnapshot$1): void;
370
- /**
371
- * Every fault this request should get, in rule order, stopping at the first that answers
372
- * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
373
- * each matching rule's remaining uses.
374
- */
375
- take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
376
- /**
377
- * Fire these rules at one request without storing them: no matching, no schedule, in order,
378
- * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
379
- */
380
- fire(rules: readonly FaultRule$1[], candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
381
- };
382
-
383
- /**
384
- * The admin controls every mock shares, as one document.
385
- *
386
- * The same shape is accepted in three places, and means the same thing in each:
387
- *
388
- * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
389
- * `MOCKINGBIRD_ADMIN_CONTROLS`
390
- * - over HTTP: `PUT /__admin/controls`
391
- * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
392
- *
393
- * Every control is deterministic: given the same seed, clock and requests, a mock answers
394
- * the same bytes. Nothing here reads the wall clock or `Math.random`.
395
- */
396
- /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
397
- type Duration$1 = number | string;
398
- /** Epoch milliseconds, or an ISO-8601 string. */
399
- type Instant$1 = number | string;
400
- type ClockControls$1 = {
401
- /** Move the clock to this instant. */
402
- now?: Instant$1;
403
- /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
404
- frozen?: boolean;
405
- /**
406
- * Step the clock forward by this much before every vendor request. With a frozen clock
407
- * each request still gets its own, reproducible timestamp.
408
- */
409
- autoAdvance?: Duration$1;
410
- };
411
- /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
412
- type LatencyRuleInput$1 = {
413
- delay?: Duration$1;
414
- jitter?: Duration$1;
415
- };
416
- type LatencyControls$1 = LatencyRuleInput$1 & {
417
- /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
418
- operations?: Record<string, Duration$1 | LatencyRuleInput$1>;
419
- };
420
- /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
421
- type FaultInput$1 = (Omit<FaultRule$1, "id"> & {
422
- id?: string;
423
- }) | ({
424
- preset: string;
425
- } & Partial<FaultRule$1>);
426
- /** Identifies a {@link SnapshotDocument}. */
427
- declare const SNAPSHOT_FORMAT$1 = "mockingbird.snapshot/v1";
428
- /**
429
- * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
430
- * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
431
- * `records` are required, so a hand-written seed file is a valid snapshot.
432
- */
433
- type SnapshotDocument$1 = {
434
- format: typeof SNAPSHOT_FORMAT$1;
435
- /** The service that wrote it. A snapshot is rejected by any other service. */
436
- service?: string;
437
- /**
438
- * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
439
- * the stored text of a row that is not a plain record, and replaces `value` when present.
440
- */
441
- records: {
442
- collection: string;
443
- id: string;
444
- seq?: number;
445
- value?: unknown;
446
- raw?: string;
447
- }[];
448
- /** Id counters, so the next generated id continues where the snapshot left off. */
449
- sequences?: {
450
- name: string;
451
- kind: string;
452
- value: number;
453
- }[];
454
- clock?: {
455
- now: number;
456
- frozen: boolean;
457
- autoAdvanceMs?: number;
458
- };
459
- seed?: number | string;
460
- /** Positions of the seeded random streams. */
461
- rng?: {
462
- state: number;
463
- faults?: number;
464
- latency?: number;
465
- };
466
- faults?: unknown;
467
- latency?: unknown;
468
- virtualTime?: boolean;
469
- /** Quiescent webhook endpoints, delivery history and fault state. Contains private configuration. */
470
- webhooks?: unknown;
471
- };
472
- /** Controls for one namespace. */
473
- type NamespaceControls$1 = {
474
- /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
475
- seed?: number | string;
476
- clock?: ClockControls$1;
477
- /**
478
- * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
479
- * wall clock: the request returns at once, the clock has moved, and the journal records
480
- * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
481
- */
482
- virtualTime?: boolean;
483
- /** Baseline response time for every vendor request. A bare duration is its `delay`. */
484
- latency?: Duration$1 | LatencyControls$1;
485
- faults?: readonly FaultInput$1[];
486
- /** Start from this state instead of the service's own seed data. */
487
- snapshot?: SnapshotDocument$1;
488
- };
489
- /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
490
- type MockControls$1 = NamespaceControls$1 & {
491
- /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
492
- credentials?: Record<string, string>;
493
- /** Overrides for named namespaces. A key given here replaces the shared value. */
494
- namespaces?: Record<string, NamespaceControls$1>;
495
- };
496
- /** A latency rule in milliseconds. */
497
- type LatencyRule$1 = {
498
- delayMs: number;
499
- jitterMs: number;
500
- };
501
- /** Baseline latency for a namespace, normalized. */
502
- type LatencyState$1 = LatencyRule$1 & {
503
- operations: Record<string, LatencyRule$1>;
504
- };
505
- /** What {@link controlHeaders} turns into request headers. */
506
- type ControlHeaderInput$1 = {
507
- namespace?: string;
508
- adminKey?: string;
509
- branch?: string;
510
- at?: string;
511
- reset?: boolean;
512
- restore?: string;
513
- seed?: number | string;
514
- time?: Instant$1 | Date;
515
- advance?: Duration$1;
516
- virtualTime?: boolean;
517
- delay?: Duration$1;
518
- timeout?: Duration$1;
519
- /** A status, `"drop"`, a preset name, or a fault rule. */
520
- fault?: number | string | Record<string, unknown>;
521
- snapshot?: string;
522
- };
523
-
524
- /**
525
- * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
526
- * `kind` is `media_type` when the body is present but its media type is not one the operation
527
- * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
528
- * the operation needs a body and none arrived, and `schema` for a contract violation.
529
- */
530
- type BodyIssue$1 = {
531
- path: string;
532
- message: string;
533
- kind?: "media_type" | "syntax" | "required" | "schema";
534
- };
535
-
536
- /**
537
- * What the mock received from a request it rejected, so a 4xx can be attributed after the
538
- * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
539
- */
540
- type RejectedRequest$1 = {
541
- /** The raw `content-type` header, or `null` when the request sent none. */
542
- contentType: string | null;
543
- /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
544
- bodyBytes: number | null;
545
- /** The raw `transfer-encoding` header (`chunked`), or `null`. */
546
- transferEncoding: string | null;
547
- };
548
- /** One handled request, as the structured log sees it. */
549
- type RequestLog$1 = {
550
- service: string;
551
- namespace: string;
552
- operationId: string | undefined;
553
- method: string;
554
- path: string;
555
- status: number;
556
- durationMs: number;
557
- /** True when the path matched no operation in the contract. */
558
- unmatched: boolean;
559
- /** Set when a fault rule produced the response. */
560
- faultId?: string;
561
- /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
562
- delayMs?: number;
563
- /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
564
- ids?: Record<string, string>;
565
- /** Set when the service created a resource the request referred to but that did not exist. */
566
- adopted?: boolean;
567
- /** Explicit durable acceptance, independent of response delivery. */
568
- accepted?: boolean;
569
- /** Checkpoint captured at explicit acceptance. */
570
- checkpoint?: string;
571
- /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
572
- request?: RejectedRequest$1;
573
- /** The validation issues behind a rejection, when the service found any. */
574
- issues?: BodyIssue$1[];
575
- };
576
- type MetricsReport$1 = {
577
- requests: number;
578
- /** Counts keyed `<operationId> <status>`. */
579
- byOperation: Record<string, number>;
580
- /**
581
- * Paths that matched no operation, most frequent first.
582
- *
583
- * This is the early-warning signal: a consumer calling something the mock does
584
- * not implement shows up here as a count, before it fails a suite as a 404.
585
- */
586
- unmatched: {
587
- method: string;
588
- path: string;
589
- count: number;
590
- }[];
591
- faults: number;
592
- totalDurationMs: number;
593
- };
594
- type Metrics$1 = {
595
- record(entry: RequestLog$1): void;
596
- report(namespace?: string): MetricsReport$1;
597
- reset(namespace?: string): void;
598
- };
599
-
600
- /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
601
- type JournalEntry$1 = RequestLog$1 & {
602
- at: string;
603
- };
604
- type JournalQuery$1 = {
605
- /** Only this namespace. Omit for every namespace, oldest first across all of them. */
606
- namespace?: string;
607
- operationId?: string;
608
- /** Only this HTTP method, case-insensitive. */
609
- method?: string;
610
- /** Only this exact path. */
611
- path?: string;
612
- /** Only requests this fault rule answered or shaped. */
613
- faultId?: string;
614
- status?: number;
615
- /** Only entries at or after this instant (epoch ms). */
616
- since?: number;
617
- /** At most this many, the most recent kept. */
618
- limit?: number;
619
- };
620
- type Journal$1 = {
621
- readonly size: number;
622
- record(entry: JournalEntry$1): void;
623
- list(query?: JournalQuery$1): JournalEntry$1[];
624
- /** Forget one namespace's entries, or every namespace's. */
625
- clear(namespace?: string): void;
626
- };
627
-
628
- /**
629
- * Baseline response time, per namespace: how long every vendor request takes before any
630
- * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
631
- * separate from the fault stream, so adding latency never shifts which requests a `rate`
632
- * fault hits.
633
- */
634
- type LatencyRegistry$1 = {
635
- get(namespace: string): LatencyState$1;
636
- set(namespace: string, state: LatencyState$1): LatencyState$1;
637
- /** Remove one namespace's latency, or every namespace's. */
638
- clear(namespace?: string): void;
639
- /** Milliseconds this request waits. Draws jitter, so call it once per request. */
640
- take(namespace: string, operationId: string | undefined): number;
641
- };
642
-
643
- /** Clock state as the admin API reports it. */
644
- type ControlClock$1 = ClockState$1 & {
645
- /** `now`, as ISO-8601. */
646
- iso: string;
647
- /** Milliseconds the clock steps before every vendor request. */
648
- autoAdvanceMs: number;
649
- };
650
- /** One namespace's controls: the body of `GET /__admin/controls`. */
651
- type ControlState$1 = {
652
- namespace: string;
653
- seed: number | string;
654
- clock: ControlClock$1;
655
- virtualTime: boolean;
656
- latency: LatencyState$1;
657
- faults: FaultListing$1[];
658
- };
659
-
660
- /** What `GET /__admin/snapshots` lists for each snapshot. */
661
- type SnapshotInfo$1 = {
662
- id: string;
663
- namespace: string;
664
- /** Stored rows in the snapshot. */
665
- records: number;
666
- /** The namespace clock when it was taken, epoch ms. */
667
- at: number;
668
- /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
669
- portable: boolean;
670
- };
671
-
672
- /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
673
- type CredentialRegistry$1 = {
674
- set(credential: string, namespace: string): void;
675
- get(credential: string): string | undefined;
676
- remove(credential: string): boolean;
677
- clear(): void;
678
- entries(): {
679
- credential: string;
680
- namespace: string;
681
- }[];
682
- };
683
-
684
- type OwnedTransport$1 = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
685
-
686
- /**
687
- * A point-in-time copy of everything a service namespace holds.
688
- *
689
- * All service state lives in the two core tables keyed by namespace, so a snapshot
690
- * is generic: any service gets per-test rollback without knowing its own schema.
691
- * Restoring is much cheaper than rebuilding a namespace from a corpus.
692
- */
693
- type NamespaceSnapshot$1 = {
694
- namespace: string;
695
- records: {
696
- collection: string;
697
- id: string;
698
- seq: number;
699
- value: string;
700
- }[];
701
- sequences: {
702
- name: string;
703
- kind: string;
704
- value: number;
705
- }[];
706
- };
707
-
708
- declare const STATE_FIELD_KINDS$1: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
709
- type StateFieldKind$1 = (typeof STATE_FIELD_KINDS$1)[number];
710
- /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
711
- type StateMeta$1 = Readonly<Record<string, string | number | boolean | null>>;
712
- type StateField$1 = {
713
- name: string;
714
- kind: StateFieldKind$1;
715
- optional: boolean;
716
- description?: string;
717
- /** One level of nested object fields. */
718
- fields?: StateField$1[];
719
- meta?: StateMeta$1;
720
- };
721
- type StateCollectionView$1 = {
722
- name: string;
723
- label: string;
724
- description?: string;
725
- count: number;
726
- /** `mixed` when a declaration and stored rows both contribute fields. */
727
- source: "declared" | "inferred" | "mixed";
728
- fields: StateField$1[];
729
- meta?: StateMeta$1;
730
- };
731
- /** The shape of one namespace, for an admin UI that has never seen the service before. */
732
- type StateView$1 = {
733
- namespace: string;
734
- storageNamespace: string;
735
- collections: StateCollectionView$1[];
736
- };
737
-
738
- type WebhookEndpoint$1 = {
739
- /** Stable id; generated when omitted. */
740
- id?: string;
741
- url: string;
742
- secret?: string;
743
- /** Event types to deliver; omit or include `"*"` for every type. */
744
- events?: string[];
745
- /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
746
- tags?: Record<string, string>;
747
- /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
748
- signUrl?: string;
749
- headers?: Record<string, string>;
750
- };
751
- type WebhookMessage$1 = {
752
- id: string;
753
- namespace: string;
754
- type: string;
755
- body: string;
756
- contentType: string;
757
- tags: Record<string, string>;
758
- headers?: Record<string, string>;
759
- /** Wall-clock ISO-8601 time of publication. */
760
- publishedAt: string;
761
- };
762
- type WebhookAttempt$1 = {
763
- attempt: number;
764
- at: string;
765
- status: number | null;
766
- error: string | null;
767
- durationMs: number;
768
- /** Exact receiver response body, when one was returned. */
769
- responseBody?: string | null;
770
- };
771
- type WebhookDelivery$1 = {
772
- id: string;
773
- messageId: string;
774
- namespace: string;
775
- type: string;
776
- endpointId: string;
777
- url: string;
778
- state: "pending" | "delivered" | "failed" | "dropped";
779
- attempts: WebhookAttempt$1[];
780
- };
781
- /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
782
- type WebhookFault$1 = {
783
- mode: "duplicate" | "reorder" | "drop";
784
- /** Messages affected; default 1. */
785
- count?: number;
786
- };
787
- type PublishInput$1 = {
788
- namespace: string;
789
- type: string;
790
- /** Exact body; objects are JSON-encoded. */
791
- body: string | Record<string, unknown> | unknown[];
792
- /** Default `application/json`, or form-encoded when `form` is given. */
793
- contentType?: string;
794
- /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
795
- form?: Record<string, string>;
796
- tags?: Record<string, string>;
797
- /** Message-specific delivery headers, captured as part of durable message state. */
798
- headers?: Record<string, string>;
799
- /** Message id; generated when omitted. */
800
- id?: string;
801
- };
802
- type WebhookHub$1 = {
803
- observeDeliveries(listener: (event: {
804
- namespace: string;
805
- state: string;
806
- deliveryId: string;
807
- }) => void): () => void;
808
- setTransportPolicy(policy: OwnedTransport$1): void;
809
- pending(namespace: string): number;
810
- snapshot(namespace: string): unknown;
811
- exportSnapshot(handle: unknown): unknown;
812
- importSnapshot(namespace: string, document: unknown): unknown;
813
- restore(namespace: string, snapshot: unknown): void;
814
- publish(input: PublishInput$1): WebhookMessage$1;
815
- /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
816
- setEndpoints(namespace: string, endpoints: WebhookEndpoint$1[]): WebhookEndpoint$1[];
817
- /** The endpoints a namespace delivers to: its own, plus the global ones. */
818
- endpoints(namespace: string): WebhookEndpoint$1[];
819
- messages(namespace?: string): WebhookMessage$1[];
820
- deliveries(namespace?: string): WebhookDelivery$1[];
821
- replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
822
- /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
823
- flush(): Promise<void>;
824
- /** Resolve once nothing is in flight. */
825
- idle(namespace?: string): Promise<void>;
826
- fault(namespace: string, fault: WebhookFault$1): void;
827
- clear(namespace?: string): void;
828
- };
829
-
830
- /** What the runtime needs from a service: a Fetch handler it can reset. */
831
- type ServiceInstance$1 = FetchAPI$1 & {
832
- reset(): Promise<void>;
833
- };
834
- type ServiceTimelineState$1 = Readonly<{
835
- snapshot: NamespaceSnapshot$1;
836
- /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
837
- clock: Readonly<ClockState$1 & {
838
- pinned?: boolean;
839
- }>;
840
- rngState: number;
841
- }>;
842
- type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
843
- type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$1 & {
844
- /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
845
- stop?(): void;
846
- readonly name: string;
847
- /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
848
- mount(prefix: string): MountedAPI$1;
849
- readonly sqlite: SqliteClient$2;
850
- readonly clock: Clock$1;
851
- /**
852
- * Change the id base ({@link RuntimeOptions.idBase}) for ids generated from now on, and
853
- * return the number it resolved to. Set it before the first request so a boot's ids stay
854
- * one run.
855
- */
856
- setIdBase(base: IdBase$1): number;
857
- readonly faults: FaultRegistry$1;
858
- /** Baseline response time per namespace. */
859
- readonly latency: LatencyRegistry$1;
860
- readonly metrics: Metrics$1;
861
- readonly journal: Journal$1;
862
- readonly rng: Rng$1;
863
- readonly credentials: CredentialRegistry$1;
864
- /** The webhook hub, when the service has outbound webhooks. */
865
- readonly webhooks: WebhookHub$1 | undefined;
866
- /**
867
- * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
868
- * offset and a freeze of its own, so moving one never moves another.
869
- */
870
- namespaceClock(namespace?: string): Clock$1;
871
- namespaceOf(request: Request): string;
872
- /** Opaque in-process checkpoint including records, controls and webhook history. */
873
- fleetSnapshot(namespace: string): object;
874
- fleetRestore(snapshot: unknown, namespace: string): void;
875
- fleetExport(snapshot: unknown): SnapshotDocument$1;
876
- fleetImport(namespace: string, document: unknown): object;
877
- /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
878
- applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule$1>): FaultRule$1[];
879
- /** The instance behind `namespace` (the default one when omitted), created on first use. */
880
- instance(namespace?: string): T;
881
- /** Public names of every namespace created so far. */
882
- namespaces(): string[];
883
- /** Return one namespace to its boot state, or every namespace with `"*"`. */
884
- reset(namespace?: string): Promise<void>;
885
- /** Reset a namespace and forget it, releasing everything it held. */
886
- dropNamespace(namespace: string): Promise<void>;
887
- /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
888
- controls(namespace?: string): ControlState$1 & {
889
- snapshots: SnapshotInfo$1[];
890
- };
891
- /** Apply a control document to a namespace. A given key replaces that control. */
892
- configure(controls: NamespaceControls$1, namespace?: string): ControlState$1 & {
893
- snapshots: SnapshotInfo$1[];
894
- };
895
- /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
896
- readonly snapshots: {
897
- /** Capture the namespace now. Reusing a name replaces that snapshot. */
898
- create(options?: {
899
- name?: string;
900
- namespace?: string;
901
- }): SnapshotInfo$1;
902
- list(namespace?: string): SnapshotInfo$1[];
903
- /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
904
- export(id: string, namespace?: string): SnapshotDocument$1;
905
- /** Store a document as a snapshot without restoring it. */
906
- import(document: SnapshotDocument$1, options?: {
907
- name?: string;
908
- namespace?: string;
909
- }): SnapshotInfo$1;
910
- restore(id: string, namespace?: string): void;
911
- delete(id: string, namespace?: string): boolean;
912
- };
913
- /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
914
- headers(input: ControlHeaderInput$1): Record<string, string>;
915
- snapshot(namespace?: string): NamespaceSnapshot$1;
916
- restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
917
- /** Capture the current branch. Mutating HTTP calls do this automatically. */
918
- checkpoint(namespace?: string, branch?: string): ServiceCheckpoint$1;
919
- /** Create an isolated branch, optionally from a historical checkpoint. */
920
- branch(name: string, options?: {
921
- namespace?: string;
922
- at?: string;
923
- }): ServiceCheckpoint$1;
924
- /** Restore a branch, clock, and PRNG to a checkpoint. */
925
- checkout(checkpoint: string, options?: {
926
- namespace?: string;
927
- branch?: string;
928
- }): void;
929
- /** Inspect the retained history for a namespace. */
930
- timeline(namespace?: string): Timeline$1<ServiceTimelineState$1>;
931
- /** Collections in one namespace: declared shape plus what the rows actually hold. */
932
- state(namespace?: string): StateView$1;
933
- };
934
-
935
- /** A running server, with the address it actually bound. */
936
- type Listening = {
937
- url: string;
938
- port: number;
939
- host: string;
940
- server: Server;
941
- close(): Promise<void>;
942
- };
943
-
944
- type CliOption = {
945
- type: "string" | "boolean";
946
- description: string;
947
- /** Shown in help; the value placeholder, e.g. `<port>`. */
948
- value?: string;
949
- default?: string | boolean;
950
- };
951
- type CliValues = Record<string, string | boolean | undefined>;
952
- type CommonServeOptions = {
953
- adminPrefix?: string;
954
- adminKey: string | undefined;
955
- seed: string | undefined;
956
- onLog: ((entry: RequestLog$1) => void) | undefined;
957
- /** Admin controls to boot with: clock, latency, faults, a starting snapshot. */
958
- adminControls?: MockControls$1;
959
- /** Synthetic provider fixture objects supplied by a fleet entry. */
960
- fixtures?: Record<string, unknown>;
961
- baseUrl?: string;
962
- /**
963
- * Boot settings from `--settings`, `MOCKINGBIRD_SETTINGS` or a fleet entry's `settings`,
964
- * already checked by the target's {@link ServeTarget.parseSettings}. Pass them to the
965
- * service's own `settings` option so they become every namespace's defaults.
966
- */
967
- settings?: Record<string, unknown>;
968
- };
969
- /**
970
- * What a service contributes to `serve`: how to build its runtime from CLI flags,
971
- * and what to say at startup. Every service's `./server` entry exports one as
972
- * `serveTarget`, which is also how `serve --config` finds services by name.
973
- */
974
- type ServeTarget = {
975
- packageVersion?: string;
976
- name: string;
977
- defaultPort: number;
978
- /** Serve flags beyond the common ones. */
979
- options?: Record<string, CliOption>;
980
- /**
981
- * Check the boot settings a caller supplied (`--settings`, `MOCKINGBIRD_SETTINGS`, a fleet
982
- * entry's `settings`) against the service's settings schema, returning them normalized
983
- * or throwing a message naming the bad field. A target without one takes no boot settings,
984
- * and supplying some is refused before a port is bound.
985
- */
986
- parseSettings?(settings: Record<string, unknown>): Record<string, unknown>;
987
- create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
988
- /** Largest request body the HTTP server accepts. Default 16 MiB. */
989
- maxBodyBytes?: number;
990
- /** Startup lines after the listen address, e.g. the loaded corpus version. */
991
- banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
992
- /** After the HTTP server is bound. A service that speaks more than HTTP attaches it here. */
993
- listening?(server: Listening): void;
994
- };
2
+ import { RuntimeOptions, Runtime } from './index.js';
995
3
 
996
4
  type MountedAPI = FetchAPI & {
997
5
  readonly prefix: string;
@@ -1097,9 +105,9 @@ interface FetchAPI {
1097
105
  type FetchHandler = (request: Request) => Promise<Response>;
1098
106
 
1099
107
  /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1100
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
108
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1101
109
  /** Mutation counters returned by {@link SqliteStatement.run}. */
1102
- type SqliteRunResult$1 = {
110
+ type SqliteRunResult = {
1103
111
  changes: number;
1104
112
  lastInsertRowid: number | bigint;
1105
113
  };
@@ -1108,10 +116,10 @@ type SqliteRunResult$1 = {
1108
116
  *
1109
117
  * Pass bind values as rest arguments on each call (no sticky `bind()`).
1110
118
  */
1111
- interface SqliteStatement$1 {
1112
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
1113
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
1114
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
119
+ interface SqliteStatement {
120
+ run(...params: SqliteValue[]): SqliteRunResult;
121
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
122
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1115
123
  }
1116
124
  /**
1117
125
  * Sync SQLite client port owned by Mockingbird.
@@ -1119,121 +127,17 @@ interface SqliteStatement$1 {
1119
127
  * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1120
128
  * `bun:sqlite` instances all work when they expose this surface.
1121
129
  */
1122
- interface SqliteClient$1 {
130
+ interface SqliteClient {
1123
131
  exec(sql: string): void;
1124
- prepare(sql: string): SqliteStatement$1;
132
+ prepare(sql: string): SqliteStatement;
1125
133
  transaction<T>(fn: () => T): T;
1126
134
  }
1127
135
 
1128
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
1129
- type Stored<T> = {
1130
- seq: number;
1131
- value: T;
1132
- };
1133
- type ListRecordsOptions<T> = {
1134
- /** Keep only records passing the predicate. */
1135
- where?: (value: T, seq: number) => boolean;
1136
- /** Sort order; default newest first. */
1137
- order?: "newest" | "oldest";
1138
- };
1139
- /**
1140
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
1141
- * sequence, never by id lexicographic order, so list semantics stay stable.
1142
- */
1143
- declare class Collection<T> {
1144
- private readonly sqlite;
1145
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1146
- readonly namespace: string;
1147
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
1148
- readonly collectionName: string;
1149
- private readonly statements;
1150
- private prepare;
1151
- constructor(sqlite: SqliteClient$1,
1152
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1153
- namespace: string,
1154
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
1155
- collectionName: string);
1156
- private bumpCollectionSeq;
1157
- nextSequence(): number;
1158
- get(id: string): T | undefined;
1159
- has(id: string): boolean;
1160
- /** Insert a new record, assigning it the next sequence number. */
1161
- insert(id: string, value: T): Stored<T>;
1162
- /** Replace an existing record's value, keeping its position. */
1163
- update(id: string, value: T): Stored<T> | undefined;
1164
- delete(id: string): boolean;
1165
- /** How many records the collection holds, without reading them. */
1166
- count(): number;
1167
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
1168
- id: string;
1169
- }>;
1170
- }
1171
-
1172
136
  /**
1173
137
  * What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
1174
138
  * which derives the base from the wall clock when the runtime is created.
1175
139
  */
1176
140
  type IdBase = number | string;
1177
- /**
1178
- * Sequential id source persisted in SQLite. Ids are deterministic for a given
1179
- * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
1180
- * A runtime's `idBase` is mixed in, so a different base reissues none of another's ids.
1181
- */
1182
- declare class IdSequence {
1183
- private readonly sqlite;
1184
- private readonly namespace;
1185
- private readonly salt;
1186
- constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
1187
- next(prefix: string, length?: number): string;
1188
- }
1189
-
1190
- /** Options every provider constructor accepts. */
1191
- type APIOptions$1 = {
1192
- /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
1193
- sqlite?: SqliteClient$1;
1194
- /** Clock used for `created`-style fields. Default `Date.now`. */
1195
- now?: () => number;
1196
- /**
1197
- * Storage namespace for this instance's records. Instances sharing one SQLite
1198
- * client stay isolated when their namespaces differ. Defaults to the service name.
1199
- */
1200
- namespace?: string;
1201
- };
1202
-
1203
- type AwsInput = Record<string, unknown>;
1204
- type AwsProtocolOptions = APIOptions$1 & {
1205
- region?: string;
1206
- accountId?: string;
1207
- };
1208
- type AwsOperation = {
1209
- operation: string;
1210
- input: AwsInput;
1211
- request: Request;
1212
- url: URL;
1213
- };
1214
- /** Fetch-native AWS wire transport. Service subclasses own operations and persisted state. */
1215
- declare abstract class AwsProtocolAPI {
1216
- readonly service: string;
1217
- readonly sqlite: SqliteClient$1;
1218
- readonly namespace: string;
1219
- readonly now: () => number;
1220
- readonly region: string;
1221
- readonly accountId: string;
1222
- readonly ids: IdSequence;
1223
- private readonly collections;
1224
- constructor(service: string, options?: AwsProtocolOptions);
1225
- collection(name: string): Collection<AwsInput>;
1226
- arn(type: string, name: string, service?: string): string;
1227
- reset(): Promise<void>;
1228
- abstract dispatch(context: AwsOperation): unknown | Promise<unknown>;
1229
- route(_method: string, _pathname: string): {
1230
- operation: string;
1231
- params: AwsInput;
1232
- } | undefined;
1233
- fetch(request: Request): Promise<Response>;
1234
- unsupported(operation: string): never;
1235
- get(collection: string, id: string, code?: string): AwsInput;
1236
- }
1237
141
 
1238
142
  /**
1239
143
  * The single source of time for a service.
@@ -1943,7 +847,7 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1943
847
  readonly name: string;
1944
848
  /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1945
849
  mount(prefix: string): MountedAPI;
1946
- readonly sqlite: SqliteClient$1;
850
+ readonly sqlite: SqliteClient;
1947
851
  readonly clock: Clock;
1948
852
  /**
1949
853
  * Change the id base ({@link RuntimeOptions.idBase}) for ids generated from now on, and
@@ -2029,54 +933,66 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
2029
933
  state(namespace?: string): StateView;
2030
934
  };
2031
935
 
2032
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
2033
- type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
2034
- /** Mutation counters returned by {@link SqliteStatement.run}. */
2035
- type SqliteRunResult = {
2036
- changes: number;
2037
- lastInsertRowid: number | bigint;
936
+ /** A running server, with the address it actually bound. */
937
+ type Listening = {
938
+ url: string;
939
+ port: number;
940
+ host: string;
941
+ server: Server;
942
+ close(): Promise<void>;
2038
943
  };
2039
- /**
2040
- * Prepared statement bound to a {@link SqliteClient}.
2041
- *
2042
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
2043
- */
2044
- interface SqliteStatement {
2045
- run(...params: SqliteValue[]): SqliteRunResult;
2046
- all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
2047
- get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
2048
- }
2049
- /**
2050
- * Sync SQLite client port owned by Mockingbird.
2051
- *
2052
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
2053
- * `bun:sqlite` instances all work when they expose this surface.
2054
- */
2055
- interface SqliteClient {
2056
- exec(sql: string): void;
2057
- prepare(sql: string): SqliteStatement;
2058
- transaction<T>(fn: () => T): T;
2059
- }
2060
-
2061
- type APIOptions = AwsProtocolOptions;
2062
- declare class CloudcontrolAPI extends AwsProtocolAPI {
2063
- constructor(options?: APIOptions);
2064
- dispatch({ operation }: AwsOperation): unknown;
2065
- }
2066
944
 
2067
- type RuntimeOptions = {
2068
- sqlite?: SqliteClient;
2069
- clock?: Clock;
2070
- seed?: number | string;
2071
- region?: string;
2072
- accountId?: string;
945
+ type CliOption = {
946
+ type: "string" | "boolean";
947
+ description: string;
948
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
949
+ value?: string;
950
+ default?: string | boolean;
951
+ };
952
+ type CliValues = Record<string, string | boolean | undefined>;
953
+ type CommonServeOptions = {
2073
954
  adminPrefix?: string;
2074
- adminKey?: string;
2075
- /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
955
+ adminKey: string | undefined;
956
+ seed: string | undefined;
957
+ onLog: ((entry: RequestLog) => void) | undefined;
958
+ /** Admin controls to boot with: clock, latency, faults, a starting snapshot. */
2076
959
  adminControls?: MockControls;
2077
- onLog?: (entry: RequestLog) => void;
960
+ /** Synthetic provider fixture objects supplied by a fleet entry. */
961
+ fixtures?: Record<string, unknown>;
962
+ baseUrl?: string;
963
+ /**
964
+ * Boot settings from `--settings`, `MOCKINGBIRD_SETTINGS` or a fleet entry's `settings`,
965
+ * already checked by the target's {@link ServeTarget.parseSettings}. Pass them to the
966
+ * service's own `settings` option so they become every namespace's defaults.
967
+ */
968
+ settings?: Record<string, unknown>;
969
+ };
970
+ /**
971
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
972
+ * and what to say at startup. Every service's `./server` entry exports one as
973
+ * `serveTarget`, which is also how `serve --config` finds services by name.
974
+ */
975
+ type ServeTarget = {
976
+ packageVersion?: string;
977
+ name: string;
978
+ defaultPort: number;
979
+ /** Serve flags beyond the common ones. */
980
+ options?: Record<string, CliOption>;
981
+ /**
982
+ * Check the boot settings a caller supplied (`--settings`, `MOCKINGBIRD_SETTINGS`, a fleet
983
+ * entry's `settings`) against the service's settings schema, returning them normalized
984
+ * or throwing a message naming the bad field. A target without one takes no boot settings,
985
+ * and supplying some is refused before a port is bound.
986
+ */
987
+ parseSettings?(settings: Record<string, unknown>): Record<string, unknown>;
988
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime<ServiceInstance>> | ServiceRuntime<ServiceInstance>;
989
+ /** Largest request body the HTTP server accepts. Default 16 MiB. */
990
+ maxBodyBytes?: number;
991
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
992
+ banner?(runtime: ServiceRuntime<ServiceInstance>): string[];
993
+ /** After the HTTP server is bound. A service that speaks more than HTTP attaches it here. */
994
+ listening?(server: Listening): void;
2078
995
  };
2079
- type Runtime = ServiceRuntime<CloudcontrolAPI>;
2080
996
 
2081
997
  declare const DEFAULT_PORT = 8925;
2082
998
  type ServerOptions = RuntimeOptions & {