@emulates/docker 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1804 @@
1
+ import { Server } from 'node:http';
2
+ import { Hono } from 'hono';
3
+
4
+ /** Bind values accepted by the Emulates SQLite port (matches sqlite-mem / better-sqlite3). */
5
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
6
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
7
+ type SqliteRunResult$2 = {
8
+ changes: number;
9
+ lastInsertRowid: number | bigint;
10
+ };
11
+ /**
12
+ * Prepared statement bound to a {@link SqliteClient}.
13
+ *
14
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
15
+ */
16
+ interface SqliteStatement$2 {
17
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
18
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
19
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
20
+ }
21
+ /**
22
+ * Sync SQLite client port owned by Emulates.
23
+ *
24
+ * Duck-typed so `@emulates/sqlite` `Database`, better-sqlite3, and wrapped
25
+ * `bun:sqlite` instances all work when they expose this surface.
26
+ */
27
+ interface SqliteClient$2 {
28
+ exec(sql: string): void;
29
+ prepare(sql: string): SqliteStatement$2;
30
+ transaction<T>(fn: () => T): T;
31
+ }
32
+
33
+ /** A stable identifier for a point in a {@link Timeline}. */
34
+ type CheckpointId$1 = string;
35
+ /** An immutable node in a timeline's checkpoint DAG. */
36
+ type Checkpoint$1<T> = Readonly<{
37
+ id: CheckpointId$1;
38
+ branch: string;
39
+ parent: CheckpointId$1 | null;
40
+ /** Logical time supplied by the timeline's injected clock. */
41
+ at: number;
42
+ value: T;
43
+ }>;
44
+ type TimelineOptions$1 = {
45
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
46
+ now?: () => number;
47
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
48
+ maxCheckpoints?: number;
49
+ /** Customize deterministic checkpoint IDs. */
50
+ id?: (sequence: number) => CheckpointId$1;
51
+ };
52
+ type CommitOptions$1 = {
53
+ branch?: string;
54
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
55
+ parent?: CheckpointId$1 | null;
56
+ };
57
+ type ForkOptions$1 = {
58
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
59
+ from?: CheckpointId$1;
60
+ };
61
+ /**
62
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
63
+ * records, namespace images, or copy-on-write SQL engine snapshots.
64
+ *
65
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
66
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
67
+ * (the logical clock) is injected.
68
+ */
69
+ declare class Timeline$1<T> {
70
+ readonly maxCheckpoints: number;
71
+ private readonly now;
72
+ private readonly makeId;
73
+ private readonly nodes;
74
+ private readonly heads;
75
+ /** Unreferenced nodes in the exact order they became collectible. */
76
+ private readonly evictable;
77
+ /** Branch heads plus explicit retainers. Absent means zero. */
78
+ private readonly references;
79
+ private readonly explicitPins;
80
+ private sequence;
81
+ constructor(options?: TimelineOptions$1);
82
+ /** Capture a new immutable value and move `branch` to it. */
83
+ commit(value: T, options?: CommitOptions$1): Checkpoint$1<T>;
84
+ /** Create a branch pointer without copying its checkpoint value. */
85
+ fork(branch: string, options?: ForkOptions$1): Checkpoint$1<T> | undefined;
86
+ /** Move a branch pointer to an existing checkpoint. */
87
+ checkout(branch: string, id: CheckpointId$1): Checkpoint$1<T>;
88
+ get(id: CheckpointId$1): Checkpoint$1<T>;
89
+ head(branch?: string): Checkpoint$1<T> | undefined;
90
+ hasBranch(branch: string): boolean;
91
+ branches(): Readonly<Record<string, CheckpointId$1>>;
92
+ checkpoints(): readonly Checkpoint$1<T>[];
93
+ /** Number of retained checkpoints without allocating an array. */
94
+ get size(): number;
95
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
96
+ retain(id: CheckpointId$1): Checkpoint$1<T>;
97
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
98
+ release(id: CheckpointId$1): boolean;
99
+ deleteBranch(branch: string): boolean;
100
+ /**
101
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
102
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
103
+ * storage dependency, so a retained node remains usable after pruning.
104
+ */
105
+ gc(max?: number): CheckpointId$1[];
106
+ private collect;
107
+ private moveHead;
108
+ private addReference;
109
+ private removeReference;
110
+ private assertBranch;
111
+ }
112
+
113
+ /**
114
+ * Anything that can answer a Fetch `Request` with a `Response`.
115
+ *
116
+ * Every Emulates service implements this, and every runtime adapter consumes it.
117
+ * It is the only contract shared across the whole graph.
118
+ */
119
+ interface FetchAPI$2 {
120
+ fetch(request: Request): Promise<Response>;
121
+ }
122
+
123
+ /**
124
+ * The single source of time for a service.
125
+ *
126
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
127
+ * sleeping: appointment windows, result delays and expiries become reachable in
128
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
129
+ */
130
+ type ClockState$1 = {
131
+ /** Current epoch milliseconds. */
132
+ now: number;
133
+ /** True while time does not advance on its own. */
134
+ frozen: boolean;
135
+ /** Milliseconds this clock adds to its underlying source. */
136
+ offsetMs: number;
137
+ };
138
+ type Clock$1 = {
139
+ now(): number;
140
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
141
+ set(epochMs: number): void;
142
+ /** Move the clock forward, or back with a negative delta. */
143
+ advance(deltaMs: number): void;
144
+ /** Stop time at the current instant. */
145
+ freeze(): void;
146
+ /** Resume from the current instant. */
147
+ unfreeze(): void;
148
+ /** Drop back to the underlying source, live. */
149
+ reset(): void;
150
+ state(): ClockState$1;
151
+ };
152
+
153
+ /**
154
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
155
+ * request a percentage fault hits — is reproducible from a seed.
156
+ *
157
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
158
+ * than statistical quality.
159
+ */
160
+ type Rng$1 = {
161
+ /** Next value in `[0, 1)`. */
162
+ next(): number;
163
+ /** Next integer in `[min, max]`. */
164
+ int(min: number, max: number): number;
165
+ /** Restart the stream from its seed. */
166
+ reset(): void;
167
+ /** Serializable engine state used by deterministic checkpoints. */
168
+ state(): number;
169
+ /** Restore a state previously returned by {@link state}. */
170
+ setState(state: number): void;
171
+ seed: number;
172
+ };
173
+
174
+ /**
175
+ * A deliberate failure injected in front of an operation.
176
+ *
177
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
178
+ * quota error that only appears when a shared sandbox is full, the 429 that only
179
+ * appears under load, the 5xx that proves a retry path works.
180
+ */
181
+ type FaultRule$1 = {
182
+ /** Stable id, so a suite can retire exactly the rule it added. */
183
+ id: string;
184
+ /** Fault only this operation. Omit to match every operation. */
185
+ operationId?: string;
186
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
187
+ method?: string;
188
+ /** Fault only paths starting with this prefix. Omit to match every path. */
189
+ pathPrefix?: string;
190
+ /**
191
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
192
+ * an in-process caller usually wants, and what a parallel worker usually does not:
193
+ * rules added through `POST /__admin/faults` default to the calling namespace.
194
+ */
195
+ namespace?: string;
196
+ /**
197
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
198
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
199
+ * the request then still reaches the service.
200
+ */
201
+ status?: number;
202
+ /** Response body, serialized as JSON. A string is sent as-is. */
203
+ body?: unknown;
204
+ headers?: Record<string, string>;
205
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
206
+ count?: number;
207
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
208
+ rate?: number;
209
+ /** Hold the response back this long, to exercise timeouts. */
210
+ delayMs?: number;
211
+ /** Alias of `delayMs`. */
212
+ latencyMs?: number;
213
+ /**
214
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
215
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
216
+ */
217
+ drop?: boolean;
218
+ /**
219
+ * A named service behaviour to switch on for the matching request instead of (or
220
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
221
+ * read it with `faultEffects(request)`.
222
+ */
223
+ effect?: string;
224
+ /** Parameters for `effect`. */
225
+ params?: Record<string, unknown>;
226
+ /** From the preset this rule was expanded from, if any. */
227
+ preset?: string;
228
+ };
229
+ /** A fault that fired for one request. */
230
+ type FaultHit$1 = {
231
+ id: string;
232
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
233
+ response?: Response;
234
+ drop?: boolean;
235
+ effect?: {
236
+ name: string;
237
+ params: Record<string, unknown>;
238
+ };
239
+ };
240
+ /** What a request looks like to the fault matcher. */
241
+ type FaultCandidate$1 = {
242
+ operationId: string | undefined;
243
+ method: string;
244
+ path: string;
245
+ namespace: string;
246
+ };
247
+ type FaultRegistry$1 = {
248
+ isolateNamespaces(): void;
249
+ snapshot(namespace: string): {
250
+ rules: (FaultRule$1 & {
251
+ remaining: number | null;
252
+ hits: number;
253
+ position: number;
254
+ })[];
255
+ rngState: number;
256
+ };
257
+ add(rule: FaultRule$1): FaultRule$1;
258
+ list(): (FaultRule$1 & {
259
+ remaining: number | null;
260
+ hits: number;
261
+ })[];
262
+ remove(id: string): boolean;
263
+ clear(): void;
264
+ restore(namespace: string, state: {
265
+ rules: (FaultRule$1 & {
266
+ remaining: number | null;
267
+ hits: number;
268
+ position: number;
269
+ })[];
270
+ rngState: number;
271
+ }): void;
272
+ /**
273
+ * Every fault this request should get, in rule order, stopping at the first that answers
274
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
275
+ * each matching rule's remaining uses.
276
+ */
277
+ take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
278
+ };
279
+
280
+ /**
281
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
282
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
283
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
284
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
285
+ */
286
+ type BodyIssue$1 = {
287
+ path: string;
288
+ message: string;
289
+ kind?: "media_type" | "syntax" | "required" | "schema";
290
+ };
291
+
292
+ /**
293
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
294
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
295
+ */
296
+ type RejectedRequest$1 = {
297
+ /** The raw `content-type` header, or `null` when the request sent none. */
298
+ contentType: string | null;
299
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
300
+ bodyBytes: number | null;
301
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
302
+ transferEncoding: string | null;
303
+ };
304
+ /** One handled request, as the structured log sees it. */
305
+ type RequestLog$1 = {
306
+ service: string;
307
+ namespace: string;
308
+ operationId: string | undefined;
309
+ method: string;
310
+ path: string;
311
+ status: number;
312
+ durationMs: number;
313
+ /** True when the path matched no operation in the contract. */
314
+ unmatched: boolean;
315
+ /** Set when a fault rule produced the response. */
316
+ faultId?: string;
317
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
318
+ ids?: Record<string, string>;
319
+ /** Set when the service created a resource the request referred to but that did not exist. */
320
+ adopted?: boolean;
321
+ /** Explicit durable acceptance, independent of response delivery. */
322
+ accepted?: boolean;
323
+ /** Checkpoint captured at explicit acceptance. */
324
+ checkpoint?: string;
325
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
326
+ request?: RejectedRequest$1;
327
+ /** The validation issues behind a rejection, when the service found any. */
328
+ issues?: BodyIssue$1[];
329
+ };
330
+ type MetricsReport$1 = {
331
+ requests: number;
332
+ /** Counts keyed `<operationId> <status>`. */
333
+ byOperation: Record<string, number>;
334
+ /**
335
+ * Paths that matched no operation, most frequent first.
336
+ *
337
+ * This is the early-warning signal: a consumer calling something the mock does
338
+ * not implement shows up here as a count, before it fails a suite as a 404.
339
+ */
340
+ unmatched: {
341
+ method: string;
342
+ path: string;
343
+ count: number;
344
+ }[];
345
+ faults: number;
346
+ totalDurationMs: number;
347
+ };
348
+ type Metrics$1 = {
349
+ record(entry: RequestLog$1): void;
350
+ report(namespace?: string): MetricsReport$1;
351
+ reset(namespace?: string): void;
352
+ };
353
+
354
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
355
+ type JournalEntry$1 = RequestLog$1 & {
356
+ at: string;
357
+ };
358
+ type JournalQuery$1 = {
359
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
360
+ namespace?: string;
361
+ operationId?: string;
362
+ status?: number;
363
+ /** Only entries at or after this instant (epoch ms). */
364
+ since?: number;
365
+ /** At most this many, the most recent kept. */
366
+ limit?: number;
367
+ };
368
+ type Journal$1 = {
369
+ readonly size: number;
370
+ record(entry: JournalEntry$1): void;
371
+ list(query?: JournalQuery$1): JournalEntry$1[];
372
+ /** Forget one namespace's entries, or every namespace's. */
373
+ clear(namespace?: string): void;
374
+ };
375
+
376
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
377
+ type CredentialRegistry$1 = {
378
+ set(credential: string, namespace: string): void;
379
+ get(credential: string): string | undefined;
380
+ remove(credential: string): boolean;
381
+ clear(): void;
382
+ entries(): {
383
+ credential: string;
384
+ namespace: string;
385
+ }[];
386
+ };
387
+
388
+ /**
389
+ * A point-in-time copy of everything a service namespace holds.
390
+ *
391
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
392
+ * is generic: any service gets per-test rollback without knowing its own schema.
393
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
394
+ */
395
+ type NamespaceSnapshot$1 = {
396
+ namespace: string;
397
+ records: {
398
+ collection: string;
399
+ id: string;
400
+ seq: number;
401
+ value: string;
402
+ }[];
403
+ sequences: {
404
+ name: string;
405
+ kind: string;
406
+ value: number;
407
+ }[];
408
+ };
409
+
410
+ declare const STATE_FIELD_KINDS$1: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
411
+ type StateFieldKind$1 = (typeof STATE_FIELD_KINDS$1)[number];
412
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
413
+ type StateMeta$1 = Readonly<Record<string, string | number | boolean | null>>;
414
+ type StateField$1 = {
415
+ name: string;
416
+ kind: StateFieldKind$1;
417
+ optional: boolean;
418
+ description?: string;
419
+ /** One level of nested object fields. */
420
+ fields?: StateField$1[];
421
+ meta?: StateMeta$1;
422
+ };
423
+ type StateCollectionView$1 = {
424
+ name: string;
425
+ label: string;
426
+ description?: string;
427
+ count: number;
428
+ /** `mixed` when a declaration and stored rows both contribute fields. */
429
+ source: "declared" | "inferred" | "mixed";
430
+ fields: StateField$1[];
431
+ meta?: StateMeta$1;
432
+ };
433
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
434
+ type StateView$1 = {
435
+ namespace: string;
436
+ storageNamespace: string;
437
+ collections: StateCollectionView$1[];
438
+ };
439
+
440
+ type WebhookEndpoint$1 = {
441
+ /** Stable id; generated when omitted. */
442
+ id?: string;
443
+ url: string;
444
+ secret?: string;
445
+ /** Event types to deliver; omit or include `"*"` for every type. */
446
+ events?: string[];
447
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
448
+ tags?: Record<string, string>;
449
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
450
+ signUrl?: string;
451
+ headers?: Record<string, string>;
452
+ };
453
+ type WebhookMessage$1 = {
454
+ id: string;
455
+ namespace: string;
456
+ type: string;
457
+ body: string;
458
+ contentType: string;
459
+ tags: Record<string, string>;
460
+ headers?: Record<string, string>;
461
+ /** Wall-clock ISO-8601 time of publication. */
462
+ publishedAt: string;
463
+ };
464
+ type WebhookAttempt$1 = {
465
+ attempt: number;
466
+ at: string;
467
+ status: number | null;
468
+ error: string | null;
469
+ durationMs: number;
470
+ /** Exact receiver response body, when one was returned. */
471
+ responseBody?: string | null;
472
+ };
473
+ type WebhookDelivery$1 = {
474
+ id: string;
475
+ messageId: string;
476
+ namespace: string;
477
+ type: string;
478
+ endpointId: string;
479
+ url: string;
480
+ state: "pending" | "delivered" | "failed" | "dropped";
481
+ attempts: WebhookAttempt$1[];
482
+ };
483
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
484
+ type WebhookFault$1 = {
485
+ mode: "duplicate" | "reorder" | "drop";
486
+ /** Messages affected; default 1. */
487
+ count?: number;
488
+ };
489
+ type PublishInput$1 = {
490
+ namespace: string;
491
+ type: string;
492
+ /** Exact body; objects are JSON-encoded. */
493
+ body: string | Record<string, unknown> | unknown[];
494
+ /** Default `application/json`, or form-encoded when `form` is given. */
495
+ contentType?: string;
496
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
497
+ form?: Record<string, string>;
498
+ tags?: Record<string, string>;
499
+ /** Message-specific delivery headers, captured as part of durable message state. */
500
+ headers?: Record<string, string>;
501
+ /** Message id; generated when omitted. */
502
+ id?: string;
503
+ };
504
+ type WebhookHub$1 = {
505
+ pending(namespace: string): number;
506
+ snapshot(namespace: string): unknown;
507
+ restore(namespace: string, snapshot: unknown): void;
508
+ publish(input: PublishInput$1): WebhookMessage$1;
509
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
510
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint$1[]): WebhookEndpoint$1[];
511
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
512
+ endpoints(namespace: string): WebhookEndpoint$1[];
513
+ messages(namespace?: string): WebhookMessage$1[];
514
+ deliveries(namespace?: string): WebhookDelivery$1[];
515
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
516
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
517
+ flush(): Promise<void>;
518
+ /** Resolve once nothing is in flight. */
519
+ idle(): Promise<void>;
520
+ fault(namespace: string, fault: WebhookFault$1): void;
521
+ clear(namespace?: string): void;
522
+ };
523
+
524
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
525
+ type ServiceInstance$1 = FetchAPI$2 & {
526
+ reset(): Promise<void>;
527
+ };
528
+ type ServiceTimelineState$1 = Readonly<{
529
+ snapshot: NamespaceSnapshot$1;
530
+ clock: Readonly<ReturnType<Clock$1["state"]>>;
531
+ rngState: number;
532
+ }>;
533
+ type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
534
+ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
535
+ /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
536
+ stop?(): void;
537
+ readonly name: string;
538
+ readonly sqlite: SqliteClient$2;
539
+ readonly clock: Clock$1;
540
+ readonly faults: FaultRegistry$1;
541
+ readonly metrics: Metrics$1;
542
+ readonly journal: Journal$1;
543
+ readonly rng: Rng$1;
544
+ readonly credentials: CredentialRegistry$1;
545
+ /** The webhook hub, when the service has outbound webhooks. */
546
+ readonly webhooks: WebhookHub$1 | undefined;
547
+ /** Enable independent namespace clocks and PRNGs before serving a fleet. */
548
+ isolateNamespaces(): void;
549
+ namespaceClock(namespace?: string): Clock$1;
550
+ namespaceOf(request: Request): string;
551
+ /** Opaque in-process checkpoint including records, controls and webhook history. */
552
+ fleetSnapshot(namespace: string): object;
553
+ fleetRestore(snapshot: unknown, namespace: string): void;
554
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
555
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule$1>): FaultRule$1[];
556
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
557
+ instance(namespace?: string): T;
558
+ /** Public names of every namespace created so far. */
559
+ namespaces(): string[];
560
+ /** Reset one namespace, or every namespace with `"*"`. */
561
+ reset(namespace?: string): Promise<void>;
562
+ snapshot(namespace?: string): NamespaceSnapshot$1;
563
+ restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
564
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
565
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint$1;
566
+ /** Create an isolated branch, optionally from a historical checkpoint. */
567
+ branch(name: string, options?: {
568
+ namespace?: string;
569
+ at?: string;
570
+ }): ServiceCheckpoint$1;
571
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
572
+ checkout(checkpoint: string, options?: {
573
+ namespace?: string;
574
+ branch?: string;
575
+ }): void;
576
+ /** Inspect the retained history for a namespace. */
577
+ timeline(namespace?: string): Timeline$1<ServiceTimelineState$1>;
578
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
579
+ state(namespace?: string): StateView$1;
580
+ };
581
+
582
+ /** A running server, with the address it actually bound. */
583
+ type Listening = {
584
+ url: string;
585
+ port: number;
586
+ host: string;
587
+ server: Server;
588
+ close(): Promise<void>;
589
+ };
590
+
591
+ type CliOption = {
592
+ type: "string" | "boolean";
593
+ description: string;
594
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
595
+ value?: string;
596
+ default?: string | boolean;
597
+ };
598
+ type CliValues = Record<string, string | boolean | undefined>;
599
+ type CommonServeOptions = {
600
+ adminPrefix?: string;
601
+ adminKey: string | undefined;
602
+ seed: string | undefined;
603
+ onLog: ((entry: RequestLog$1) => void) | undefined;
604
+ };
605
+ /**
606
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
607
+ * and what to say at startup. Every service's `./server` entry exports one as
608
+ * `serveTarget`, which is also how `serve --config` finds services by name.
609
+ */
610
+ type ServeTarget = {
611
+ name: string;
612
+ defaultPort: number;
613
+ /** Serve flags beyond the common ones. */
614
+ options?: Record<string, CliOption>;
615
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
616
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
617
+ banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
618
+ /** After the HTTP server is bound. A service that speaks more than HTTP attaches it here. */
619
+ listening?(server: Listening): void;
620
+ };
621
+
622
+ /**
623
+ * Anything that can answer a Fetch `Request` with a `Response`.
624
+ *
625
+ * Every Emulates service implements this, and every runtime adapter consumes it.
626
+ * It is the only contract shared across the whole graph.
627
+ */
628
+ interface FetchAPI$1 {
629
+ fetch(request: Request): Promise<Response>;
630
+ }
631
+
632
+ /** Bind values accepted by the Emulates SQLite port (matches sqlite-mem / better-sqlite3). */
633
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
634
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
635
+ type SqliteRunResult$1 = {
636
+ changes: number;
637
+ lastInsertRowid: number | bigint;
638
+ };
639
+ /**
640
+ * Prepared statement bound to a {@link SqliteClient}.
641
+ *
642
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
643
+ */
644
+ interface SqliteStatement$1 {
645
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
646
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
647
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
648
+ }
649
+ /**
650
+ * Sync SQLite client port owned by Emulates.
651
+ *
652
+ * Duck-typed so `@emulates/sqlite` `Database`, better-sqlite3, and wrapped
653
+ * `bun:sqlite` instances all work when they expose this surface.
654
+ */
655
+ interface SqliteClient$1 {
656
+ exec(sql: string): void;
657
+ prepare(sql: string): SqliteStatement$1;
658
+ transaction<T>(fn: () => T): T;
659
+ }
660
+
661
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
662
+ type Stored<T> = {
663
+ seq: number;
664
+ value: T;
665
+ };
666
+ type ListRecordsOptions<T> = {
667
+ /** Keep only records passing the predicate. */
668
+ where?: (value: T, seq: number) => boolean;
669
+ /** Sort order; default newest first. */
670
+ order?: "newest" | "oldest";
671
+ };
672
+ /**
673
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
674
+ * sequence, never by id lexicographic order, so list semantics stay stable.
675
+ */
676
+ declare class Collection<T> {
677
+ private readonly sqlite;
678
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
679
+ readonly namespace: string;
680
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
681
+ readonly collectionName: string;
682
+ constructor(sqlite: SqliteClient$1,
683
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
684
+ namespace: string,
685
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
686
+ collectionName: string);
687
+ private bumpCollectionSeq;
688
+ nextSequence(): number;
689
+ get(id: string): T | undefined;
690
+ has(id: string): boolean;
691
+ /** Insert a new record, assigning it the next sequence number. */
692
+ insert(id: string, value: T): Stored<T>;
693
+ /** Replace an existing record's value, keeping its position. */
694
+ update(id: string, value: T): Stored<T> | undefined;
695
+ delete(id: string): boolean;
696
+ /** How many records the collection holds, without reading them. */
697
+ count(): number;
698
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
699
+ id: string;
700
+ }>;
701
+ }
702
+
703
+ /** A stable identifier for a point in a {@link Timeline}. */
704
+ type CheckpointId = string;
705
+ /** An immutable node in a timeline's checkpoint DAG. */
706
+ type Checkpoint<T> = Readonly<{
707
+ id: CheckpointId;
708
+ branch: string;
709
+ parent: CheckpointId | null;
710
+ /** Logical time supplied by the timeline's injected clock. */
711
+ at: number;
712
+ value: T;
713
+ }>;
714
+ type TimelineOptions = {
715
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
716
+ now?: () => number;
717
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
718
+ maxCheckpoints?: number;
719
+ /** Customize deterministic checkpoint IDs. */
720
+ id?: (sequence: number) => CheckpointId;
721
+ };
722
+ type CommitOptions = {
723
+ branch?: string;
724
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
725
+ parent?: CheckpointId | null;
726
+ };
727
+ type ForkOptions = {
728
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
729
+ from?: CheckpointId;
730
+ };
731
+ /**
732
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
733
+ * records, namespace images, or copy-on-write SQL engine snapshots.
734
+ *
735
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
736
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
737
+ * (the logical clock) is injected.
738
+ */
739
+ declare class Timeline<T> {
740
+ readonly maxCheckpoints: number;
741
+ private readonly now;
742
+ private readonly makeId;
743
+ private readonly nodes;
744
+ private readonly heads;
745
+ /** Unreferenced nodes in the exact order they became collectible. */
746
+ private readonly evictable;
747
+ /** Branch heads plus explicit retainers. Absent means zero. */
748
+ private readonly references;
749
+ private readonly explicitPins;
750
+ private sequence;
751
+ constructor(options?: TimelineOptions);
752
+ /** Capture a new immutable value and move `branch` to it. */
753
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
754
+ /** Create a branch pointer without copying its checkpoint value. */
755
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
756
+ /** Move a branch pointer to an existing checkpoint. */
757
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
758
+ get(id: CheckpointId): Checkpoint<T>;
759
+ head(branch?: string): Checkpoint<T> | undefined;
760
+ hasBranch(branch: string): boolean;
761
+ branches(): Readonly<Record<string, CheckpointId>>;
762
+ checkpoints(): readonly Checkpoint<T>[];
763
+ /** Number of retained checkpoints without allocating an array. */
764
+ get size(): number;
765
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
766
+ retain(id: CheckpointId): Checkpoint<T>;
767
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
768
+ release(id: CheckpointId): boolean;
769
+ deleteBranch(branch: string): boolean;
770
+ /**
771
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
772
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
773
+ * storage dependency, so a retained node remains usable after pruning.
774
+ */
775
+ gc(max?: number): CheckpointId[];
776
+ private collect;
777
+ private moveHead;
778
+ private addReference;
779
+ private removeReference;
780
+ private assertBranch;
781
+ }
782
+
783
+ /**
784
+ * Anything that can answer a Fetch `Request` with a `Response`.
785
+ *
786
+ * Every Emulates service implements this, and every runtime adapter consumes it.
787
+ * It is the only contract shared across the whole graph.
788
+ */
789
+ interface FetchAPI {
790
+ fetch(request: Request): Promise<Response>;
791
+ }
792
+
793
+ /**
794
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Emulates understands.
795
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
796
+ */
797
+ type JsonPrimitive = string | number | boolean | null;
798
+ type JsonValue = JsonPrimitive | JsonValue[] | {
799
+ [key: string]: JsonValue;
800
+ };
801
+ type ReferenceObject = {
802
+ $ref: string;
803
+ description?: string;
804
+ summary?: string;
805
+ };
806
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
807
+ type SchemaObject = {
808
+ $ref?: string;
809
+ type?: SchemaType | SchemaType[];
810
+ title?: string;
811
+ description?: string;
812
+ format?: string;
813
+ enum?: JsonValue[];
814
+ const?: JsonValue;
815
+ default?: JsonValue;
816
+ example?: JsonValue;
817
+ examples?: JsonValue[];
818
+ nullable?: boolean;
819
+ deprecated?: boolean;
820
+ readOnly?: boolean;
821
+ writeOnly?: boolean;
822
+ minimum?: number;
823
+ maximum?: number;
824
+ exclusiveMinimum?: number;
825
+ exclusiveMaximum?: number;
826
+ multipleOf?: number;
827
+ minLength?: number;
828
+ maxLength?: number;
829
+ pattern?: string;
830
+ minItems?: number;
831
+ maxItems?: number;
832
+ uniqueItems?: boolean;
833
+ items?: SchemaObject;
834
+ prefixItems?: SchemaObject[];
835
+ minProperties?: number;
836
+ maxProperties?: number;
837
+ required?: string[];
838
+ properties?: Record<string, SchemaObject>;
839
+ additionalProperties?: boolean | SchemaObject;
840
+ propertyNames?: SchemaObject;
841
+ oneOf?: SchemaObject[];
842
+ anyOf?: SchemaObject[];
843
+ allOf?: SchemaObject[];
844
+ not?: SchemaObject;
845
+ discriminator?: {
846
+ propertyName: string;
847
+ mapping?: Record<string, string>;
848
+ };
849
+ [extension: `x-${string}`]: unknown;
850
+ };
851
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
852
+ type ParameterObject = {
853
+ name: string;
854
+ in: ParameterLocation;
855
+ description?: string;
856
+ required?: boolean;
857
+ deprecated?: boolean;
858
+ style?: string;
859
+ explode?: boolean;
860
+ schema?: SchemaObject;
861
+ content?: Record<string, MediaTypeObject>;
862
+ example?: JsonValue;
863
+ [extension: `x-${string}`]: unknown;
864
+ };
865
+ type MediaTypeObject = {
866
+ schema?: SchemaObject;
867
+ example?: JsonValue;
868
+ examples?: Record<string, unknown>;
869
+ encoding?: Record<string, unknown>;
870
+ [extension: `x-${string}`]: unknown;
871
+ };
872
+ type RequestBodyObject = {
873
+ description?: string;
874
+ required?: boolean;
875
+ content: Record<string, MediaTypeObject>;
876
+ [extension: `x-${string}`]: unknown;
877
+ };
878
+ type HeaderObject = {
879
+ description?: string;
880
+ required?: boolean;
881
+ schema?: SchemaObject;
882
+ [extension: `x-${string}`]: unknown;
883
+ };
884
+ type ResponseObject = {
885
+ description: string;
886
+ headers?: Record<string, HeaderObject | ReferenceObject>;
887
+ content?: Record<string, MediaTypeObject>;
888
+ [extension: `x-${string}`]: unknown;
889
+ };
890
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
891
+ type SecurityRequirementObject = Record<string, string[]>;
892
+ type OperationObject = {
893
+ operationId?: string;
894
+ summary?: string;
895
+ description?: string;
896
+ tags?: string[];
897
+ deprecated?: boolean;
898
+ parameters?: Array<ParameterObject | ReferenceObject>;
899
+ requestBody?: RequestBodyObject | ReferenceObject;
900
+ responses: ResponsesObject;
901
+ security?: SecurityRequirementObject[];
902
+ [extension: `x-${string}`]: unknown;
903
+ };
904
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
905
+ type HttpMethod = (typeof HTTP_METHODS)[number];
906
+ type PathItemObject = {
907
+ summary?: string;
908
+ description?: string;
909
+ parameters?: Array<ParameterObject | ReferenceObject>;
910
+ [extension: `x-${string}`]: unknown;
911
+ } & Partial<Record<HttpMethod, OperationObject>>;
912
+ type SecuritySchemeObject = {
913
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
914
+ description?: string;
915
+ name?: string;
916
+ in?: ParameterLocation;
917
+ scheme?: string;
918
+ bearerFormat?: string;
919
+ flows?: Record<string, unknown>;
920
+ openIdConnectUrl?: string;
921
+ [extension: `x-${string}`]: unknown;
922
+ };
923
+ type ComponentsObject = {
924
+ schemas?: Record<string, SchemaObject>;
925
+ responses?: Record<string, ResponseObject>;
926
+ parameters?: Record<string, ParameterObject>;
927
+ requestBodies?: Record<string, RequestBodyObject>;
928
+ headers?: Record<string, HeaderObject>;
929
+ securitySchemes?: Record<string, SecuritySchemeObject>;
930
+ [extension: `x-${string}`]: unknown;
931
+ };
932
+ type ServerObject = {
933
+ url: string;
934
+ description?: string;
935
+ variables?: Record<string, unknown>;
936
+ [extension: `x-${string}`]: unknown;
937
+ };
938
+ type InfoObject = {
939
+ title: string;
940
+ version: string;
941
+ description?: string;
942
+ [extension: `x-${string}`]: unknown;
943
+ };
944
+ type OpenAPIDocument = {
945
+ openapi: string;
946
+ info: InfoObject;
947
+ servers?: ServerObject[];
948
+ paths: Record<string, PathItemObject>;
949
+ components?: ComponentsObject;
950
+ security?: SecurityRequirementObject[];
951
+ tags?: Array<{
952
+ name: string;
953
+ description?: string;
954
+ }>;
955
+ [extension: `x-${string}`]: unknown;
956
+ };
957
+
958
+ /** Options every provider constructor accepts. */
959
+ type APIOptions = {
960
+ /** Sync SQLite client. Defaults to `@emulates/sqlite`. */
961
+ sqlite?: SqliteClient$1;
962
+ /** Clock used for `created`-style fields. Default `Date.now`. */
963
+ now?: () => number;
964
+ /**
965
+ * Storage namespace for this instance's records. Instances sharing one SQLite
966
+ * client stay isolated when their namespaces differ. Defaults to the service name.
967
+ */
968
+ namespace?: string;
969
+ };
970
+
971
+ /**
972
+ * The single source of time for a service.
973
+ *
974
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
975
+ * sleeping: appointment windows, result delays and expiries become reachable in
976
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
977
+ */
978
+ type ClockState = {
979
+ /** Current epoch milliseconds. */
980
+ now: number;
981
+ /** True while time does not advance on its own. */
982
+ frozen: boolean;
983
+ /** Milliseconds this clock adds to its underlying source. */
984
+ offsetMs: number;
985
+ };
986
+ type Clock = {
987
+ now(): number;
988
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
989
+ set(epochMs: number): void;
990
+ /** Move the clock forward, or back with a negative delta. */
991
+ advance(deltaMs: number): void;
992
+ /** Stop time at the current instant. */
993
+ freeze(): void;
994
+ /** Resume from the current instant. */
995
+ unfreeze(): void;
996
+ /** Drop back to the underlying source, live. */
997
+ reset(): void;
998
+ state(): ClockState;
999
+ };
1000
+
1001
+ /**
1002
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
1003
+ * request a percentage fault hits — is reproducible from a seed.
1004
+ *
1005
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
1006
+ * than statistical quality.
1007
+ */
1008
+ type Rng = {
1009
+ /** Next value in `[0, 1)`. */
1010
+ next(): number;
1011
+ /** Next integer in `[min, max]`. */
1012
+ int(min: number, max: number): number;
1013
+ /** Restart the stream from its seed. */
1014
+ reset(): void;
1015
+ /** Serializable engine state used by deterministic checkpoints. */
1016
+ state(): number;
1017
+ /** Restore a state previously returned by {@link state}. */
1018
+ setState(state: number): void;
1019
+ seed: number;
1020
+ };
1021
+
1022
+ /**
1023
+ * A deliberate failure injected in front of an operation.
1024
+ *
1025
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
1026
+ * quota error that only appears when a shared sandbox is full, the 429 that only
1027
+ * appears under load, the 5xx that proves a retry path works.
1028
+ */
1029
+ type FaultRule = {
1030
+ /** Stable id, so a suite can retire exactly the rule it added. */
1031
+ id: string;
1032
+ /** Fault only this operation. Omit to match every operation. */
1033
+ operationId?: string;
1034
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
1035
+ method?: string;
1036
+ /** Fault only paths starting with this prefix. Omit to match every path. */
1037
+ pathPrefix?: string;
1038
+ /**
1039
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
1040
+ * an in-process caller usually wants, and what a parallel worker usually does not:
1041
+ * rules added through `POST /__admin/faults` default to the calling namespace.
1042
+ */
1043
+ namespace?: string;
1044
+ /**
1045
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
1046
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
1047
+ * the request then still reaches the service.
1048
+ */
1049
+ status?: number;
1050
+ /** Response body, serialized as JSON. A string is sent as-is. */
1051
+ body?: unknown;
1052
+ headers?: Record<string, string>;
1053
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
1054
+ count?: number;
1055
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
1056
+ rate?: number;
1057
+ /** Hold the response back this long, to exercise timeouts. */
1058
+ delayMs?: number;
1059
+ /** Alias of `delayMs`. */
1060
+ latencyMs?: number;
1061
+ /**
1062
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
1063
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
1064
+ */
1065
+ drop?: boolean;
1066
+ /**
1067
+ * A named service behaviour to switch on for the matching request instead of (or
1068
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
1069
+ * read it with `faultEffects(request)`.
1070
+ */
1071
+ effect?: string;
1072
+ /** Parameters for `effect`. */
1073
+ params?: Record<string, unknown>;
1074
+ /** From the preset this rule was expanded from, if any. */
1075
+ preset?: string;
1076
+ };
1077
+ /** A fault that fired for one request. */
1078
+ type FaultHit = {
1079
+ id: string;
1080
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
1081
+ response?: Response;
1082
+ drop?: boolean;
1083
+ effect?: {
1084
+ name: string;
1085
+ params: Record<string, unknown>;
1086
+ };
1087
+ };
1088
+ /**
1089
+ * A named, documented fault a suite switches on by name
1090
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
1091
+ * webhook delivery fault.
1092
+ */
1093
+ type FaultPreset = {
1094
+ description: string;
1095
+ rules?: Omit<FaultRule, "id">[];
1096
+ webhook?: {
1097
+ mode: "duplicate" | "reorder" | "drop";
1098
+ count?: number;
1099
+ };
1100
+ };
1101
+ /** What a request looks like to the fault matcher. */
1102
+ type FaultCandidate = {
1103
+ operationId: string | undefined;
1104
+ method: string;
1105
+ path: string;
1106
+ namespace: string;
1107
+ };
1108
+ type FaultRegistry = {
1109
+ isolateNamespaces(): void;
1110
+ snapshot(namespace: string): {
1111
+ rules: (FaultRule & {
1112
+ remaining: number | null;
1113
+ hits: number;
1114
+ position: number;
1115
+ })[];
1116
+ rngState: number;
1117
+ };
1118
+ add(rule: FaultRule): FaultRule;
1119
+ list(): (FaultRule & {
1120
+ remaining: number | null;
1121
+ hits: number;
1122
+ })[];
1123
+ remove(id: string): boolean;
1124
+ clear(): void;
1125
+ restore(namespace: string, state: {
1126
+ rules: (FaultRule & {
1127
+ remaining: number | null;
1128
+ hits: number;
1129
+ position: number;
1130
+ })[];
1131
+ rngState: number;
1132
+ }): void;
1133
+ /**
1134
+ * Every fault this request should get, in rule order, stopping at the first that answers
1135
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
1136
+ * each matching rule's remaining uses.
1137
+ */
1138
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
1139
+ };
1140
+
1141
+ /**
1142
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
1143
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
1144
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
1145
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
1146
+ */
1147
+ type BodyIssue = {
1148
+ path: string;
1149
+ message: string;
1150
+ kind?: "media_type" | "syntax" | "required" | "schema";
1151
+ };
1152
+
1153
+ /**
1154
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
1155
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
1156
+ */
1157
+ type RejectedRequest = {
1158
+ /** The raw `content-type` header, or `null` when the request sent none. */
1159
+ contentType: string | null;
1160
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
1161
+ bodyBytes: number | null;
1162
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
1163
+ transferEncoding: string | null;
1164
+ };
1165
+ /** One handled request, as the structured log sees it. */
1166
+ type RequestLog = {
1167
+ service: string;
1168
+ namespace: string;
1169
+ operationId: string | undefined;
1170
+ method: string;
1171
+ path: string;
1172
+ status: number;
1173
+ durationMs: number;
1174
+ /** True when the path matched no operation in the contract. */
1175
+ unmatched: boolean;
1176
+ /** Set when a fault rule produced the response. */
1177
+ faultId?: string;
1178
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
1179
+ ids?: Record<string, string>;
1180
+ /** Set when the service created a resource the request referred to but that did not exist. */
1181
+ adopted?: boolean;
1182
+ /** Explicit durable acceptance, independent of response delivery. */
1183
+ accepted?: boolean;
1184
+ /** Checkpoint captured at explicit acceptance. */
1185
+ checkpoint?: string;
1186
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
1187
+ request?: RejectedRequest;
1188
+ /** The validation issues behind a rejection, when the service found any. */
1189
+ issues?: BodyIssue[];
1190
+ };
1191
+ type MetricsReport = {
1192
+ requests: number;
1193
+ /** Counts keyed `<operationId> <status>`. */
1194
+ byOperation: Record<string, number>;
1195
+ /**
1196
+ * Paths that matched no operation, most frequent first.
1197
+ *
1198
+ * This is the early-warning signal: a consumer calling something the mock does
1199
+ * not implement shows up here as a count, before it fails a suite as a 404.
1200
+ */
1201
+ unmatched: {
1202
+ method: string;
1203
+ path: string;
1204
+ count: number;
1205
+ }[];
1206
+ faults: number;
1207
+ totalDurationMs: number;
1208
+ };
1209
+ type Metrics = {
1210
+ record(entry: RequestLog): void;
1211
+ report(namespace?: string): MetricsReport;
1212
+ reset(namespace?: string): void;
1213
+ };
1214
+
1215
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
1216
+ type JournalEntry = RequestLog & {
1217
+ at: string;
1218
+ };
1219
+ type JournalQuery = {
1220
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
1221
+ namespace?: string;
1222
+ operationId?: string;
1223
+ status?: number;
1224
+ /** Only entries at or after this instant (epoch ms). */
1225
+ since?: number;
1226
+ /** At most this many, the most recent kept. */
1227
+ limit?: number;
1228
+ };
1229
+ type Journal = {
1230
+ readonly size: number;
1231
+ record(entry: JournalEntry): void;
1232
+ list(query?: JournalQuery): JournalEntry[];
1233
+ /** Forget one namespace's entries, or every namespace's. */
1234
+ clear(namespace?: string): void;
1235
+ };
1236
+
1237
+ type AdminRequest = {
1238
+ request: Request;
1239
+ url: URL;
1240
+ /** `:param` segments of the matched route. */
1241
+ params: Record<string, string>;
1242
+ /** Namespace the request targets: `?namespace=`, then the header, then the default. */
1243
+ namespace: string;
1244
+ /** Parsed JSON body, or `undefined` when there is none. */
1245
+ body: unknown;
1246
+ };
1247
+ type AdminRoute = (request: AdminRequest) => Response | Promise<Response>;
1248
+ /**
1249
+ * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with
1250
+ * `:param` segments — e.g. `"POST /orders/:id/transition"`.
1251
+ */
1252
+ type AdminRoutes = Record<string, AdminRoute>;
1253
+
1254
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
1255
+ type CredentialRegistry = {
1256
+ set(credential: string, namespace: string): void;
1257
+ get(credential: string): string | undefined;
1258
+ remove(credential: string): boolean;
1259
+ clear(): void;
1260
+ entries(): {
1261
+ credential: string;
1262
+ namespace: string;
1263
+ }[];
1264
+ };
1265
+
1266
+ /**
1267
+ * A point-in-time copy of everything a service namespace holds.
1268
+ *
1269
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
1270
+ * is generic: any service gets per-test rollback without knowing its own schema.
1271
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
1272
+ */
1273
+ type NamespaceSnapshot = {
1274
+ namespace: string;
1275
+ records: {
1276
+ collection: string;
1277
+ id: string;
1278
+ seq: number;
1279
+ value: string;
1280
+ }[];
1281
+ sequences: {
1282
+ name: string;
1283
+ kind: string;
1284
+ value: number;
1285
+ }[];
1286
+ };
1287
+
1288
+ declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
1289
+ type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
1290
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
1291
+ type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
1292
+ type StateField = {
1293
+ name: string;
1294
+ kind: StateFieldKind;
1295
+ optional: boolean;
1296
+ description?: string;
1297
+ /** One level of nested object fields. */
1298
+ fields?: StateField[];
1299
+ meta?: StateMeta;
1300
+ };
1301
+ /**
1302
+ * What a service knows about a collection before any row exists.
1303
+ * Stored rows still appear, including fields this declaration does not mention.
1304
+ */
1305
+ type StateDeclaration = {
1306
+ name: string;
1307
+ label?: string;
1308
+ description?: string;
1309
+ fields?: readonly StateField[];
1310
+ meta?: StateMeta;
1311
+ };
1312
+ type StateCollectionView = {
1313
+ name: string;
1314
+ label: string;
1315
+ description?: string;
1316
+ count: number;
1317
+ /** `mixed` when a declaration and stored rows both contribute fields. */
1318
+ source: "declared" | "inferred" | "mixed";
1319
+ fields: StateField[];
1320
+ meta?: StateMeta;
1321
+ };
1322
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
1323
+ type StateView = {
1324
+ namespace: string;
1325
+ storageNamespace: string;
1326
+ collections: StateCollectionView[];
1327
+ };
1328
+
1329
+ /**
1330
+ * A contribution the admin shell mounts beside the shared views.
1331
+ * `panel` is author-owned markup. `sql` turns on the built-in table explorer
1332
+ * and query runner, which call `GET /sql/tables` and `POST /sql/query`.
1333
+ * `route` presents an admin action with the shell's prebuilt form and response view.
1334
+ */
1335
+ type AdminExtension = {
1336
+ kind: "route";
1337
+ id: string;
1338
+ title: string;
1339
+ description?: string;
1340
+ /** An existing admin route, including its method and any path parameters. */
1341
+ route: string;
1342
+ /** Initial JSON body shown in the request form. */
1343
+ body?: unknown;
1344
+ } | {
1345
+ kind: "panel";
1346
+ id: string;
1347
+ title: string;
1348
+ description?: string;
1349
+ html: string;
1350
+ script?: string;
1351
+ } | {
1352
+ kind: "sql";
1353
+ /** DOM id suffix. Default `sql`. */
1354
+ id?: string;
1355
+ title?: string;
1356
+ description?: string;
1357
+ };
1358
+ /** A panel the default admin shell mounts after the shared views. */
1359
+ type AdminPanel = {
1360
+ /** DOM id suffix. Lowercase letters, digits, and hyphens. */
1361
+ id: string;
1362
+ title: string;
1363
+ description?: string;
1364
+ /** Markup placed inside the panel body. The service author owns it. */
1365
+ html: string;
1366
+ /**
1367
+ * Function body called as `(root, api) => void` once the shell has loaded.
1368
+ * `root` is the panel body. `api` is `{ get, send, namespace }` against `/__admin`.
1369
+ */
1370
+ script?: string;
1371
+ };
1372
+ /**
1373
+ * How a service customizes the admin UI without leaving the shared shell.
1374
+ * `panels` add views. `render` replaces the document and can call `defaultHtml()`
1375
+ * to wrap the shared shell instead of discarding it.
1376
+ */
1377
+ type AdminUi = {
1378
+ panels?: readonly AdminPanel[];
1379
+ /** First-class shell contributions. `sql` mounts the shared database explorer. */
1380
+ extensions?: readonly AdminExtension[];
1381
+ render?: (input: {
1382
+ service: string;
1383
+ defaultHtml: () => string;
1384
+ }) => string;
1385
+ };
1386
+
1387
+ type WebhookEndpoint = {
1388
+ /** Stable id; generated when omitted. */
1389
+ id?: string;
1390
+ url: string;
1391
+ secret?: string;
1392
+ /** Event types to deliver; omit or include `"*"` for every type. */
1393
+ events?: string[];
1394
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
1395
+ tags?: Record<string, string>;
1396
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
1397
+ signUrl?: string;
1398
+ headers?: Record<string, string>;
1399
+ };
1400
+ type WebhookMessage = {
1401
+ id: string;
1402
+ namespace: string;
1403
+ type: string;
1404
+ body: string;
1405
+ contentType: string;
1406
+ tags: Record<string, string>;
1407
+ headers?: Record<string, string>;
1408
+ /** Wall-clock ISO-8601 time of publication. */
1409
+ publishedAt: string;
1410
+ };
1411
+ type WebhookAttempt = {
1412
+ attempt: number;
1413
+ at: string;
1414
+ status: number | null;
1415
+ error: string | null;
1416
+ durationMs: number;
1417
+ /** Exact receiver response body, when one was returned. */
1418
+ responseBody?: string | null;
1419
+ };
1420
+ type WebhookDelivery = {
1421
+ id: string;
1422
+ messageId: string;
1423
+ namespace: string;
1424
+ type: string;
1425
+ endpointId: string;
1426
+ url: string;
1427
+ state: "pending" | "delivered" | "failed" | "dropped";
1428
+ attempts: WebhookAttempt[];
1429
+ };
1430
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
1431
+ type WebhookFault = {
1432
+ mode: "duplicate" | "reorder" | "drop";
1433
+ /** Messages affected; default 1. */
1434
+ count?: number;
1435
+ };
1436
+ type PublishInput = {
1437
+ namespace: string;
1438
+ type: string;
1439
+ /** Exact body; objects are JSON-encoded. */
1440
+ body: string | Record<string, unknown> | unknown[];
1441
+ /** Default `application/json`, or form-encoded when `form` is given. */
1442
+ contentType?: string;
1443
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
1444
+ form?: Record<string, string>;
1445
+ tags?: Record<string, string>;
1446
+ /** Message-specific delivery headers, captured as part of durable message state. */
1447
+ headers?: Record<string, string>;
1448
+ /** Message id; generated when omitted. */
1449
+ id?: string;
1450
+ };
1451
+ type WebhookHub = {
1452
+ pending(namespace: string): number;
1453
+ snapshot(namespace: string): unknown;
1454
+ restore(namespace: string, snapshot: unknown): void;
1455
+ publish(input: PublishInput): WebhookMessage;
1456
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
1457
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
1458
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
1459
+ endpoints(namespace: string): WebhookEndpoint[];
1460
+ messages(namespace?: string): WebhookMessage[];
1461
+ deliveries(namespace?: string): WebhookDelivery[];
1462
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
1463
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
1464
+ flush(): Promise<void>;
1465
+ /** Resolve once nothing is in flight. */
1466
+ idle(): Promise<void>;
1467
+ fault(namespace: string, fault: WebhookFault): void;
1468
+ clear(namespace?: string): void;
1469
+ };
1470
+
1471
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
1472
+ type ServiceInstance = FetchAPI & {
1473
+ reset(): Promise<void>;
1474
+ };
1475
+ /** Everything an instance shares with the runtime that owns it. */
1476
+ type InstanceContext = {
1477
+ /** Storage namespace for this instance's records. */
1478
+ namespace: string;
1479
+ /** The public namespace name a request selects it by. */
1480
+ adminPrefix: string;
1481
+ publicNamespace: string;
1482
+ sqlite: SqliteClient$1;
1483
+ clock: Clock;
1484
+ rng: Rng;
1485
+ };
1486
+ type RuntimeOptions<T extends ServiceInstance> = {
1487
+ /** Service name, e.g. `"junction"`. Also the default namespace's storage key. */
1488
+ name: string;
1489
+ /** Build the instance backing one namespace. Called once per namespace, on first use. */
1490
+ create: (context: InstanceContext) => T;
1491
+ /** The vendor contract, used to name each request's operation in logs, metrics and faults. */
1492
+ document?: OpenAPIDocument;
1493
+ /** Shared by every namespace. Defaults to a fresh `@emulates/sqlite`. */
1494
+ sqlite?: SqliteClient$1;
1495
+ /** Defaults to a live clock over `Date.now`. */
1496
+ clock?: Clock;
1497
+ /** Seeds every random choice the runtime makes (fault rates). Default `0`. */
1498
+ seed?: number | string;
1499
+ /** Extra `GET /__admin/health` fields, such as the loaded corpus version. */
1500
+ describe?: () => Record<string, unknown>;
1501
+ /** Service-specific admin routes, given the runtime so they can reach any namespace. */
1502
+ admin?: (runtime: ServiceRuntime<T>) => AdminRoutes;
1503
+ /** Reserved tree for every internal HTTP endpoint, UI and namespace carrier. Default /__admin. */
1504
+ adminPrefix?: string;
1505
+ /** Invalidate transient handles before replacing an existing instance's stored state. */
1506
+ beforeRestore?: (instance: T) => void;
1507
+ /** Require this value in `x-emulates-admin-key` on admin data routes. */
1508
+ adminKey?: string;
1509
+ /** Structured request log sink, called once per request. */
1510
+ onLog?: (entry: RequestLog) => void;
1511
+ /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000; 0 turns it off. */
1512
+ journalSize?: number;
1513
+ /** Reported in the `x-emulates` header. Default: the bundled package's version. */
1514
+ version?: string;
1515
+ /**
1516
+ * The vendor credential a request carries (API key, token, account SID, AWS access key
1517
+ * id), for SDKs that cannot send `x-emulates-namespace`: a suite maps credentials to
1518
+ * namespaces with `PUT /__admin/credentials`. See `bearerToken`, `basicAuth`,
1519
+ * `sigV4AccessKeyId`.
1520
+ */
1521
+ credential?: (request: Request) => string | undefined;
1522
+ /** Named faults, switched on with `POST /__admin/faults {"preset": "<name>"}`. */
1523
+ presets?: Record<string, FaultPreset>;
1524
+ /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */
1525
+ webhooks?: WebhookHub;
1526
+ /** Retained time-travel checkpoints per namespace. Default 1,000. */
1527
+ maxCheckpoints?: number;
1528
+ /** Injectable process IO used for observability and delays; logical service time uses `clock`. */
1529
+ io?: Partial<RuntimeIO>;
1530
+ /**
1531
+ * Collections the admin UI should show even before any row exists.
1532
+ * Stored collections are always included, whether or not they are declared.
1533
+ * A function may describe collections that depend on the live instance.
1534
+ */
1535
+ state?: readonly StateDeclaration[] | ((api: T, namespace: string) => readonly StateDeclaration[]);
1536
+ /**
1537
+ * Panels added to the default admin UI, or a function that replaces the document.
1538
+ * `render` receives `defaultHtml()` so a bespoke UI can wrap the shared shell.
1539
+ */
1540
+ adminUi?: AdminUi;
1541
+ };
1542
+ type RuntimeIO = {
1543
+ wallNow(): number;
1544
+ monotonicNow(): number;
1545
+ sleep(ms: number): Promise<void>;
1546
+ };
1547
+ type ServiceTimelineState = Readonly<{
1548
+ snapshot: NamespaceSnapshot;
1549
+ clock: Readonly<ReturnType<Clock["state"]>>;
1550
+ rngState: number;
1551
+ }>;
1552
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1553
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1554
+ /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1555
+ stop?(): void;
1556
+ readonly name: string;
1557
+ readonly sqlite: SqliteClient$1;
1558
+ readonly clock: Clock;
1559
+ readonly faults: FaultRegistry;
1560
+ readonly metrics: Metrics;
1561
+ readonly journal: Journal;
1562
+ readonly rng: Rng;
1563
+ readonly credentials: CredentialRegistry;
1564
+ /** The webhook hub, when the service has outbound webhooks. */
1565
+ readonly webhooks: WebhookHub | undefined;
1566
+ /** Enable independent namespace clocks and PRNGs before serving a fleet. */
1567
+ isolateNamespaces(): void;
1568
+ namespaceClock(namespace?: string): Clock;
1569
+ namespaceOf(request: Request): string;
1570
+ /** Opaque in-process checkpoint including records, controls and webhook history. */
1571
+ fleetSnapshot(namespace: string): object;
1572
+ fleetRestore(snapshot: unknown, namespace: string): void;
1573
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1574
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1575
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
1576
+ instance(namespace?: string): T;
1577
+ /** Public names of every namespace created so far. */
1578
+ namespaces(): string[];
1579
+ /** Reset one namespace, or every namespace with `"*"`. */
1580
+ reset(namespace?: string): Promise<void>;
1581
+ snapshot(namespace?: string): NamespaceSnapshot;
1582
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1583
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
1584
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1585
+ /** Create an isolated branch, optionally from a historical checkpoint. */
1586
+ branch(name: string, options?: {
1587
+ namespace?: string;
1588
+ at?: string;
1589
+ }): ServiceCheckpoint;
1590
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
1591
+ checkout(checkpoint: string, options?: {
1592
+ namespace?: string;
1593
+ branch?: string;
1594
+ }): void;
1595
+ /** Inspect the retained history for a namespace. */
1596
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
1597
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
1598
+ state(namespace?: string): StateView;
1599
+ };
1600
+
1601
+ /** Bind values accepted by the Emulates SQLite port (matches sqlite-mem / better-sqlite3). */
1602
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1603
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1604
+ type SqliteRunResult = {
1605
+ changes: number;
1606
+ lastInsertRowid: number | bigint;
1607
+ };
1608
+ /**
1609
+ * Prepared statement bound to a {@link SqliteClient}.
1610
+ *
1611
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1612
+ */
1613
+ interface SqliteStatement {
1614
+ run(...params: SqliteValue[]): SqliteRunResult;
1615
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
1616
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1617
+ }
1618
+ /**
1619
+ * Sync SQLite client port owned by Emulates.
1620
+ *
1621
+ * Duck-typed so `@emulates/sqlite` `Database`, better-sqlite3, and wrapped
1622
+ * `bun:sqlite` instances all work when they expose this surface.
1623
+ */
1624
+ interface SqliteClient {
1625
+ exec(sql: string): void;
1626
+ prepare(sql: string): SqliteStatement;
1627
+ transaction<T>(fn: () => T): T;
1628
+ }
1629
+
1630
+ declare const statuses: readonly ["created", "running", "paused", "restarting", "removing", "exited", "dead"];
1631
+ type Status = (typeof statuses)[number];
1632
+ type ImageRecord = {
1633
+ id: string;
1634
+ tags: string[];
1635
+ platform?: string;
1636
+ config?: Record<string, unknown>;
1637
+ };
1638
+ type ContainerRecord = {
1639
+ id: string;
1640
+ name: string;
1641
+ image: string;
1642
+ imageId: string;
1643
+ status: Status;
1644
+ created: string;
1645
+ startedAt: string;
1646
+ finishedAt: string;
1647
+ exitCode: number;
1648
+ labels: Record<string, string>;
1649
+ cmd: string[];
1650
+ entrypoint: string[];
1651
+ env: string[];
1652
+ workingDir: string;
1653
+ user: string;
1654
+ hostConfig: Record<string, unknown>;
1655
+ networkSettings: Record<string, unknown>;
1656
+ sizeRw: number;
1657
+ sizeRootFs: number;
1658
+ config?: Record<string, unknown>;
1659
+ termination?: {
1660
+ operation: "stop" | "kill" | "remove";
1661
+ signal: number;
1662
+ timeout?: number;
1663
+ requestedAt: string;
1664
+ };
1665
+ removalPending?: boolean;
1666
+ stdinClosed?: boolean;
1667
+ };
1668
+ type DaemonSettings = {
1669
+ available: boolean;
1670
+ rootless: boolean;
1671
+ };
1672
+ /** Synthetic records only. No host state, images or processes are accessed. */
1673
+ declare class DockerState {
1674
+ private readonly sqlite;
1675
+ private readonly now;
1676
+ readonly images: Collection<ImageRecord>;
1677
+ readonly containers: Collection<ContainerRecord>;
1678
+ private readonly settings;
1679
+ private readonly ids;
1680
+ constructor(sqlite: SqliteClient, namespace: string, now: () => number);
1681
+ create(value: unknown, url: URL): {
1682
+ Id: string;
1683
+ Warnings: string[];
1684
+ };
1685
+ daemon(): DaemonSettings;
1686
+ updateDaemon(value: unknown): DaemonSettings;
1687
+ seed(value: unknown): {
1688
+ images: number;
1689
+ containers: number;
1690
+ };
1691
+ find(id: string): ContainerRecord;
1692
+ }
1693
+
1694
+ /** Persist transitions; keep only live response handles outside shared storage. */
1695
+ declare class DockerLifecycle {
1696
+ private readonly state;
1697
+ private readonly now;
1698
+ private closed;
1699
+ private readonly exits;
1700
+ onExit(listener: (id: string) => void): () => void;
1701
+ private notifyExit;
1702
+ private readonly waiters;
1703
+ constructor(state: DockerState, now: () => number);
1704
+ get pending(): number;
1705
+ start(id: string, url: URL, accepted?: (id: string) => void): Response;
1706
+ terminate(id: string, url: URL, signal: AbortSignal, operation: "stop" | "kill", accepted?: (id: string) => void): Response | Promise<Response>;
1707
+ remove(id: string, url: URL, signal: AbortSignal, accepted?: (id: string) => void): Response | Promise<Response>;
1708
+ private checkOpen;
1709
+ private terminationReply;
1710
+ private notify;
1711
+ complete(id: string, value: unknown): {
1712
+ id: string;
1713
+ exitCode: number;
1714
+ removed: boolean;
1715
+ simulated: boolean;
1716
+ };
1717
+ wait(id: string, url: URL, signal: AbortSignal): Response;
1718
+ close(): void;
1719
+ cancelWaits(): void;
1720
+ }
1721
+
1722
+ type DockerRuntimeOptions = Pick<RuntimeOptions<DockerAPI>, "sqlite" | "clock" | "seed" | "adminKey" | "onLog" | "journalSize" | "maxCheckpoints"> & Pick<DockerAPIOptions, "onAttach">;
1723
+ type DockerRuntime = ServiceRuntime<DockerAPI> & {
1724
+ close(): void;
1725
+ };
1726
+
1727
+ type DockerAPIOptions = APIOptions & {
1728
+ /** Transport-owned admission callback; ordinary Fetch attach remains unsupported. */
1729
+ onAttach?: (api: DockerAPI, request: Request) => Response;
1730
+ };
1731
+ declare class DockerAPI implements FetchAPI$1 {
1732
+ readonly app: Hono;
1733
+ readonly sqlite: SqliteClient;
1734
+ readonly namespace: string;
1735
+ readonly state: DockerState;
1736
+ readonly lifecycle: DockerLifecycle;
1737
+ private closed;
1738
+ private readonly invalidators;
1739
+ private epoch;
1740
+ get generation(): number;
1741
+ onInvalidate(listener: () => void): () => void;
1742
+ cancelTransient(): void;
1743
+ private readonly service;
1744
+ constructor(options?: DockerAPIOptions);
1745
+ fetch(request: Request): Promise<Response>;
1746
+ close(): void;
1747
+ reset(): Promise<void>;
1748
+ }
1749
+
1750
+ type AttachStreamOptions = {
1751
+ frameChunkBytes?: number;
1752
+ maxQueuedBytes?: number;
1753
+ maxStdinBytes?: number;
1754
+ };
1755
+ /** Node-owned live handle. Retaining one across restore never addresses a successor. */
1756
+ type DockerAttachment = {
1757
+ readonly id: number;
1758
+ readonly containerId: string;
1759
+ readonly namespace: string;
1760
+ readonly branch: string;
1761
+ readonly closed: boolean;
1762
+ readonly stdinClosed: boolean;
1763
+ readonly queuedBytes: number;
1764
+ write(channel: "stdout" | "stderr", data: Uint8Array): Promise<void>;
1765
+ takeStdin(): Uint8Array;
1766
+ end(): Promise<void>;
1767
+ cancel(): void;
1768
+ };
1769
+
1770
+ type AttachHandshakeOptions = {
1771
+ /** Deterministic mock writes; network packet boundaries remain OS-controlled. */
1772
+ chunkBytes?: number;
1773
+ /** Synthetic already-framed output delivered with the final header fragment. */
1774
+ initialStreamBytes?: Uint8Array;
1775
+ };
1776
+
1777
+ type TransportOptions = {
1778
+ port?: number;
1779
+ host?: string;
1780
+ socketPath?: string;
1781
+ /** Maximum buffered request bytes. Default 1 MiB. */
1782
+ maxBodyBytes?: number;
1783
+ /** Deadline for receiving a body, independent of long-running responses. */
1784
+ bodyTimeoutMs?: number;
1785
+ /** Maximum simultaneous owned connections. Default 128. */
1786
+ maxConnections?: number;
1787
+ };
1788
+
1789
+ declare const DEFAULT_PORT = 8826;
1790
+ type DockerServerOptions = Omit<DockerRuntimeOptions, "onAttach"> & TransportOptions & {
1791
+ attachHandshake?: AttachHandshakeOptions;
1792
+ attachStreams?: AttachStreamOptions;
1793
+ };
1794
+ type DockerServer = Listening & {
1795
+ runtime: DockerRuntime;
1796
+ socketPath?: string;
1797
+ attachments(): DockerAttachment[];
1798
+ };
1799
+ /** Node-only bounded HTTP transport over TCP or a test-owned Unix socket. */
1800
+ declare const createServer: (options?: DockerServerOptions) => Promise<DockerServer>;
1801
+ declare const serveTarget: ServeTarget;
1802
+
1803
+ export { DEFAULT_PORT, createServer, serveTarget };
1804
+ export type { AttachStreamOptions, DockerAttachment, DockerServer, DockerServerOptions };