@crvouga/mockingbird-service-wholescripts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1295 @@
1
+ import { Server } from 'node:http';
2
+ import { Hono } from 'hono';
3
+
4
+ /**
5
+ * The single source of time for a service.
6
+ *
7
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
8
+ * sleeping: appointment windows, result delays and expiries become reachable in
9
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
10
+ */
11
+ type ClockState$1 = {
12
+ /** Current epoch milliseconds. */
13
+ now: number;
14
+ /** True while time does not advance on its own. */
15
+ frozen: boolean;
16
+ /** Milliseconds this clock adds to its underlying source. */
17
+ offsetMs: number;
18
+ };
19
+ type Clock$1 = {
20
+ now(): number;
21
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
22
+ set(epochMs: number): void;
23
+ /** Move the clock forward, or back with a negative delta. */
24
+ advance(deltaMs: number): void;
25
+ /** Stop time at the current instant. */
26
+ freeze(): void;
27
+ /** Resume from the current instant. */
28
+ unfreeze(): void;
29
+ /** Drop back to the underlying source, live. */
30
+ reset(): void;
31
+ state(): ClockState$1;
32
+ };
33
+
34
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
35
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
36
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
37
+ type SqliteRunResult$2 = {
38
+ changes: number;
39
+ lastInsertRowid: number | bigint;
40
+ };
41
+ /**
42
+ * Prepared statement bound to a {@link SqliteClient}.
43
+ *
44
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
45
+ */
46
+ interface SqliteStatement$2 {
47
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
48
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
49
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
50
+ }
51
+ /**
52
+ * Sync SQLite client port owned by Mockingbird.
53
+ *
54
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
55
+ * `bun:sqlite` instances all work when they expose this surface.
56
+ */
57
+ interface SqliteClient$2 {
58
+ exec(sql: string): void;
59
+ prepare(sql: string): SqliteStatement$2;
60
+ transaction<T>(fn: () => T): T;
61
+ }
62
+
63
+ /**
64
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
65
+ * request a percentage fault hits — is reproducible from a seed.
66
+ *
67
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
68
+ * than statistical quality.
69
+ */
70
+ type Rng$1 = {
71
+ /** Next value in `[0, 1)`. */
72
+ next(): number;
73
+ /** Next integer in `[min, max]`. */
74
+ int(min: number, max: number): number;
75
+ /** Restart the stream from its seed. */
76
+ reset(): void;
77
+ /** Serializable engine state used by deterministic checkpoints. */
78
+ state(): number;
79
+ /** Restore a state previously returned by {@link state}. */
80
+ setState(state: number): void;
81
+ seed: number;
82
+ };
83
+
84
+ /**
85
+ * A deliberate failure injected in front of an operation.
86
+ *
87
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
88
+ * quota error that only appears when a shared sandbox is full, the 429 that only
89
+ * appears under load, the 5xx that proves a retry path works.
90
+ */
91
+ type FaultRule$1 = {
92
+ /** Stable id, so a suite can retire exactly the rule it added. */
93
+ id: string;
94
+ /** Fault only this operation. Omit to match every operation. */
95
+ operationId?: string;
96
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
97
+ method?: string;
98
+ /** Fault only paths starting with this prefix. Omit to match every path. */
99
+ pathPrefix?: string;
100
+ /**
101
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
102
+ * an in-process caller usually wants, and what a parallel worker usually does not:
103
+ * rules added through `POST /__admin/faults` default to the calling namespace.
104
+ */
105
+ namespace?: string;
106
+ /**
107
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
108
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
109
+ * the request then still reaches the service.
110
+ */
111
+ status?: number;
112
+ /** Response body, serialized as JSON. A string is sent as-is. */
113
+ body?: unknown;
114
+ headers?: Record<string, string>;
115
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
116
+ count?: number;
117
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
118
+ rate?: number;
119
+ /** Hold the response back this long, to exercise timeouts. */
120
+ delayMs?: number;
121
+ /** Alias of `delayMs`. */
122
+ latencyMs?: number;
123
+ /**
124
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
125
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
126
+ */
127
+ drop?: boolean;
128
+ /**
129
+ * A named service behaviour to switch on for the matching request instead of (or
130
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
131
+ * read it with `faultEffects(request)`.
132
+ */
133
+ effect?: string;
134
+ /** Parameters for `effect`. */
135
+ params?: Record<string, unknown>;
136
+ /** From the preset this rule was expanded from, if any. */
137
+ preset?: string;
138
+ };
139
+ /** A fault that fired for one request. */
140
+ type FaultHit$1 = {
141
+ id: string;
142
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
143
+ response?: Response;
144
+ drop?: boolean;
145
+ effect?: {
146
+ name: string;
147
+ params: Record<string, unknown>;
148
+ };
149
+ };
150
+ /** What a request looks like to the fault matcher. */
151
+ type FaultCandidate$1 = {
152
+ operationId: string | undefined;
153
+ method: string;
154
+ path: string;
155
+ namespace: string;
156
+ };
157
+ type FaultRegistry$1 = {
158
+ add(rule: FaultRule$1): FaultRule$1;
159
+ list(): (FaultRule$1 & {
160
+ remaining: number | null;
161
+ hits: number;
162
+ })[];
163
+ remove(id: string): boolean;
164
+ clear(): void;
165
+ /**
166
+ * Every fault this request should get, in rule order, stopping at the first that answers
167
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
168
+ * each matching rule's remaining uses.
169
+ */
170
+ take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
171
+ };
172
+
173
+ /** One handled request, as the structured log sees it. */
174
+ type RequestLog$1 = {
175
+ service: string;
176
+ namespace: string;
177
+ operationId: string | undefined;
178
+ method: string;
179
+ path: string;
180
+ status: number;
181
+ durationMs: number;
182
+ /** True when the path matched no operation in the contract. */
183
+ unmatched: boolean;
184
+ /** Set when a fault rule produced the response. */
185
+ faultId?: string;
186
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
187
+ ids?: Record<string, string>;
188
+ /** Set when the service created a resource the request referred to but that did not exist. */
189
+ adopted?: boolean;
190
+ };
191
+ type MetricsReport$1 = {
192
+ requests: number;
193
+ /** Counts keyed `<operationId> <status>`. */
194
+ byOperation: Record<string, number>;
195
+ /**
196
+ * Paths that matched no operation, most frequent first.
197
+ *
198
+ * This is the early-warning signal: a consumer calling something the mock does
199
+ * not implement shows up here as a count, before it fails a suite as a 404.
200
+ */
201
+ unmatched: {
202
+ method: string;
203
+ path: string;
204
+ count: number;
205
+ }[];
206
+ faults: number;
207
+ totalDurationMs: number;
208
+ };
209
+ type Metrics$1 = {
210
+ record(entry: RequestLog$1): void;
211
+ report(): MetricsReport$1;
212
+ reset(): void;
213
+ };
214
+
215
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
216
+ type JournalEntry$1 = RequestLog$1 & {
217
+ at: string;
218
+ };
219
+ type JournalQuery$1 = {
220
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
221
+ namespace?: string;
222
+ operationId?: string;
223
+ status?: number;
224
+ /** Only entries at or after this instant (epoch ms). */
225
+ since?: number;
226
+ /** At most this many, the most recent kept. */
227
+ limit?: number;
228
+ };
229
+ type Journal$1 = {
230
+ readonly size: number;
231
+ record(entry: JournalEntry$1): void;
232
+ list(query?: JournalQuery$1): JournalEntry$1[];
233
+ /** Forget one namespace's entries, or every namespace's. */
234
+ clear(namespace?: string): void;
235
+ };
236
+
237
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
238
+ type CredentialRegistry$1 = {
239
+ set(credential: string, namespace: string): void;
240
+ get(credential: string): string | undefined;
241
+ remove(credential: string): boolean;
242
+ clear(): void;
243
+ entries(): {
244
+ credential: string;
245
+ namespace: string;
246
+ }[];
247
+ };
248
+
249
+ /** A stable identifier for a point in a {@link Timeline}. */
250
+ type CheckpointId$1 = string;
251
+ /** An immutable node in a timeline's checkpoint DAG. */
252
+ type Checkpoint$1<T> = Readonly<{
253
+ id: CheckpointId$1;
254
+ branch: string;
255
+ parent: CheckpointId$1 | null;
256
+ /** Logical time supplied by the timeline's injected clock. */
257
+ at: number;
258
+ value: T;
259
+ }>;
260
+ type TimelineOptions$1 = {
261
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
262
+ now?: () => number;
263
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
264
+ maxCheckpoints?: number;
265
+ /** Customize deterministic checkpoint IDs. */
266
+ id?: (sequence: number) => CheckpointId$1;
267
+ };
268
+ type CommitOptions$1 = {
269
+ branch?: string;
270
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
271
+ parent?: CheckpointId$1 | null;
272
+ };
273
+ type ForkOptions$1 = {
274
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
275
+ from?: CheckpointId$1;
276
+ };
277
+ /**
278
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
279
+ * records, namespace images, or copy-on-write SQL engine snapshots.
280
+ *
281
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
282
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
283
+ * (the logical clock) is injected.
284
+ */
285
+ declare class Timeline$1<T> {
286
+ readonly maxCheckpoints: number;
287
+ private readonly now;
288
+ private readonly makeId;
289
+ private readonly nodes;
290
+ private readonly heads;
291
+ /** Unreferenced nodes in the exact order they became collectible. */
292
+ private readonly evictable;
293
+ /** Branch heads plus explicit retainers. Absent means zero. */
294
+ private readonly references;
295
+ private readonly explicitPins;
296
+ private sequence;
297
+ constructor(options?: TimelineOptions$1);
298
+ /** Capture a new immutable value and move `branch` to it. */
299
+ commit(value: T, options?: CommitOptions$1): Checkpoint$1<T>;
300
+ /** Create a branch pointer without copying its checkpoint value. */
301
+ fork(branch: string, options?: ForkOptions$1): Checkpoint$1<T> | undefined;
302
+ /** Move a branch pointer to an existing checkpoint. */
303
+ checkout(branch: string, id: CheckpointId$1): Checkpoint$1<T>;
304
+ get(id: CheckpointId$1): Checkpoint$1<T>;
305
+ head(branch?: string): Checkpoint$1<T> | undefined;
306
+ hasBranch(branch: string): boolean;
307
+ branches(): Readonly<Record<string, CheckpointId$1>>;
308
+ checkpoints(): readonly Checkpoint$1<T>[];
309
+ /** Number of retained checkpoints without allocating an array. */
310
+ get size(): number;
311
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
312
+ retain(id: CheckpointId$1): Checkpoint$1<T>;
313
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
314
+ release(id: CheckpointId$1): boolean;
315
+ deleteBranch(branch: string): boolean;
316
+ /**
317
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
318
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
319
+ * storage dependency, so a retained node remains usable after pruning.
320
+ */
321
+ gc(max?: number): CheckpointId$1[];
322
+ private collect;
323
+ private moveHead;
324
+ private addReference;
325
+ private removeReference;
326
+ private assertBranch;
327
+ }
328
+
329
+ /**
330
+ * Anything that can answer a Fetch `Request` with a `Response`.
331
+ *
332
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
333
+ * It is the only contract shared across the whole graph.
334
+ */
335
+ interface FetchAPI$2 {
336
+ fetch(request: Request): Promise<Response>;
337
+ }
338
+
339
+ /**
340
+ * A point-in-time copy of everything a service namespace holds.
341
+ *
342
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
343
+ * is generic: any service gets per-test rollback without knowing its own schema.
344
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
345
+ */
346
+ type NamespaceSnapshot$1 = {
347
+ namespace: string;
348
+ records: {
349
+ collection: string;
350
+ id: string;
351
+ seq: number;
352
+ value: string;
353
+ }[];
354
+ sequences: {
355
+ name: string;
356
+ kind: string;
357
+ value: number;
358
+ }[];
359
+ };
360
+
361
+ type WebhookEndpoint$1 = {
362
+ /** Stable id; generated when omitted. */
363
+ id?: string;
364
+ url: string;
365
+ secret?: string;
366
+ /** Event types to deliver; omit or include `"*"` for every type. */
367
+ events?: string[];
368
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
369
+ tags?: Record<string, string>;
370
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
371
+ signUrl?: string;
372
+ headers?: Record<string, string>;
373
+ };
374
+ type WebhookMessage$1 = {
375
+ id: string;
376
+ namespace: string;
377
+ type: string;
378
+ body: string;
379
+ contentType: string;
380
+ tags: Record<string, string>;
381
+ headers?: Record<string, string>;
382
+ /** Wall-clock ISO-8601 time of publication. */
383
+ publishedAt: string;
384
+ };
385
+ type WebhookAttempt$1 = {
386
+ attempt: number;
387
+ at: string;
388
+ status: number | null;
389
+ error: string | null;
390
+ durationMs: number;
391
+ /** Exact receiver response body, when one was returned. */
392
+ responseBody?: string | null;
393
+ };
394
+ type WebhookDelivery$1 = {
395
+ id: string;
396
+ messageId: string;
397
+ namespace: string;
398
+ type: string;
399
+ endpointId: string;
400
+ url: string;
401
+ state: "pending" | "delivered" | "failed" | "dropped";
402
+ attempts: WebhookAttempt$1[];
403
+ };
404
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
405
+ type WebhookFault$1 = {
406
+ mode: "duplicate" | "reorder" | "drop";
407
+ /** Messages affected; default 1. */
408
+ count?: number;
409
+ };
410
+ type PublishInput$1 = {
411
+ namespace: string;
412
+ type: string;
413
+ /** Exact body; objects are JSON-encoded. */
414
+ body: string | Record<string, unknown> | unknown[];
415
+ /** Default `application/json`, or form-encoded when `form` is given. */
416
+ contentType?: string;
417
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
418
+ form?: Record<string, string>;
419
+ tags?: Record<string, string>;
420
+ /** Message-specific delivery headers, captured as part of durable message state. */
421
+ headers?: Record<string, string>;
422
+ /** Message id; generated when omitted. */
423
+ id?: string;
424
+ };
425
+ type WebhookHub$1 = {
426
+ publish(input: PublishInput$1): WebhookMessage$1;
427
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
428
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint$1[]): WebhookEndpoint$1[];
429
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
430
+ endpoints(namespace: string): WebhookEndpoint$1[];
431
+ messages(namespace?: string): WebhookMessage$1[];
432
+ deliveries(namespace?: string): WebhookDelivery$1[];
433
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
434
+ /** Run every pending retry (and release held reordered messages) now. */
435
+ flush(): Promise<void>;
436
+ /** Resolve once nothing is in flight. */
437
+ idle(): Promise<void>;
438
+ fault(namespace: string, fault: WebhookFault$1): void;
439
+ clear(namespace?: string): void;
440
+ };
441
+
442
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
443
+ type ServiceInstance$1 = FetchAPI$2 & {
444
+ reset(): Promise<void>;
445
+ };
446
+ type ServiceTimelineState$1 = Readonly<{
447
+ snapshot: NamespaceSnapshot$1;
448
+ clock: Readonly<ReturnType<Clock$1["state"]>>;
449
+ rngState: number;
450
+ }>;
451
+ type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
452
+ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
453
+ readonly name: string;
454
+ readonly sqlite: SqliteClient$2;
455
+ readonly clock: Clock$1;
456
+ readonly faults: FaultRegistry$1;
457
+ readonly metrics: Metrics$1;
458
+ readonly journal: Journal$1;
459
+ readonly rng: Rng$1;
460
+ readonly credentials: CredentialRegistry$1;
461
+ /** The webhook hub, when the service has outbound webhooks. */
462
+ readonly webhooks: WebhookHub$1 | undefined;
463
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
464
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule$1>): FaultRule$1[];
465
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
466
+ instance(namespace?: string): T;
467
+ /** Public names of every namespace created so far. */
468
+ namespaces(): string[];
469
+ /** Reset one namespace, or every namespace with `"*"`. */
470
+ reset(namespace?: string): Promise<void>;
471
+ snapshot(namespace?: string): NamespaceSnapshot$1;
472
+ restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
473
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
474
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint$1;
475
+ /** Create an isolated branch, optionally from a historical checkpoint. */
476
+ branch(name: string, options?: {
477
+ namespace?: string;
478
+ at?: string;
479
+ }): ServiceCheckpoint$1;
480
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
481
+ checkout(checkpoint: string, options?: {
482
+ namespace?: string;
483
+ branch?: string;
484
+ }): void;
485
+ /** Inspect the retained history for a namespace. */
486
+ timeline(namespace?: string): Timeline$1<ServiceTimelineState$1>;
487
+ };
488
+
489
+ type CliOption = {
490
+ type: "string" | "boolean";
491
+ description: string;
492
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
493
+ value?: string;
494
+ default?: string | boolean;
495
+ };
496
+ type CliValues = Record<string, string | boolean | undefined>;
497
+ type CommonServeOptions = {
498
+ adminKey: string | undefined;
499
+ seed: string | undefined;
500
+ onLog: ((entry: RequestLog$1) => void) | undefined;
501
+ };
502
+ /**
503
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
504
+ * and what to say at startup. Every service's `./server` entry exports one as
505
+ * `serveTarget`, which is also how `serve --config` finds services by name.
506
+ */
507
+ type ServeTarget = {
508
+ name: string;
509
+ defaultPort: number;
510
+ /** Serve flags beyond the common ones. */
511
+ options?: Record<string, CliOption>;
512
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
513
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
514
+ banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
515
+ };
516
+
517
+ /** A running server, with the address it actually bound. */
518
+ type Listening = {
519
+ url: string;
520
+ port: number;
521
+ host: string;
522
+ server: Server;
523
+ close(): Promise<void>;
524
+ };
525
+
526
+ /**
527
+ * The single source of time for a service.
528
+ *
529
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
530
+ * sleeping: appointment windows, result delays and expiries become reachable in
531
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
532
+ */
533
+ type ClockState = {
534
+ /** Current epoch milliseconds. */
535
+ now: number;
536
+ /** True while time does not advance on its own. */
537
+ frozen: boolean;
538
+ /** Milliseconds this clock adds to its underlying source. */
539
+ offsetMs: number;
540
+ };
541
+ type Clock = {
542
+ now(): number;
543
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
544
+ set(epochMs: number): void;
545
+ /** Move the clock forward, or back with a negative delta. */
546
+ advance(deltaMs: number): void;
547
+ /** Stop time at the current instant. */
548
+ freeze(): void;
549
+ /** Resume from the current instant. */
550
+ unfreeze(): void;
551
+ /** Drop back to the underlying source, live. */
552
+ reset(): void;
553
+ state(): ClockState;
554
+ };
555
+
556
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
557
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
558
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
559
+ type SqliteRunResult$1 = {
560
+ changes: number;
561
+ lastInsertRowid: number | bigint;
562
+ };
563
+ /**
564
+ * Prepared statement bound to a {@link SqliteClient}.
565
+ *
566
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
567
+ */
568
+ interface SqliteStatement$1 {
569
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
570
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
571
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
572
+ }
573
+ /**
574
+ * Sync SQLite client port owned by Mockingbird.
575
+ *
576
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
577
+ * `bun:sqlite` instances all work when they expose this surface.
578
+ */
579
+ interface SqliteClient$1 {
580
+ exec(sql: string): void;
581
+ prepare(sql: string): SqliteStatement$1;
582
+ transaction<T>(fn: () => T): T;
583
+ }
584
+
585
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
586
+ type Stored<T> = {
587
+ seq: number;
588
+ value: T;
589
+ };
590
+ type ListRecordsOptions<T> = {
591
+ /** Keep only records passing the predicate. */
592
+ where?: (value: T, seq: number) => boolean;
593
+ /** Sort order; default newest first. */
594
+ order?: "newest" | "oldest";
595
+ };
596
+ /**
597
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
598
+ * sequence, never by id lexicographic order, so list semantics stay stable.
599
+ */
600
+ declare class Collection<T> {
601
+ private readonly sqlite;
602
+ private readonly namespace;
603
+ private readonly name;
604
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
605
+ private bumpCollectionSeq;
606
+ nextSequence(): number;
607
+ get(id: string): T | undefined;
608
+ has(id: string): boolean;
609
+ /** Insert a new record, assigning it the next sequence number. */
610
+ insert(id: string, value: T): Stored<T>;
611
+ /** Replace an existing record's value, keeping its position. */
612
+ update(id: string, value: T): Stored<T> | undefined;
613
+ delete(id: string): boolean;
614
+ /** How many records the collection holds, without reading them. */
615
+ count(): number;
616
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
617
+ id: string;
618
+ }>;
619
+ }
620
+
621
+ /**
622
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
623
+ * request a percentage fault hits — is reproducible from a seed.
624
+ *
625
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
626
+ * than statistical quality.
627
+ */
628
+ type Rng = {
629
+ /** Next value in `[0, 1)`. */
630
+ next(): number;
631
+ /** Next integer in `[min, max]`. */
632
+ int(min: number, max: number): number;
633
+ /** Restart the stream from its seed. */
634
+ reset(): void;
635
+ /** Serializable engine state used by deterministic checkpoints. */
636
+ state(): number;
637
+ /** Restore a state previously returned by {@link state}. */
638
+ setState(state: number): void;
639
+ seed: number;
640
+ };
641
+
642
+ /**
643
+ * A deliberate failure injected in front of an operation.
644
+ *
645
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
646
+ * quota error that only appears when a shared sandbox is full, the 429 that only
647
+ * appears under load, the 5xx that proves a retry path works.
648
+ */
649
+ type FaultRule = {
650
+ /** Stable id, so a suite can retire exactly the rule it added. */
651
+ id: string;
652
+ /** Fault only this operation. Omit to match every operation. */
653
+ operationId?: string;
654
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
655
+ method?: string;
656
+ /** Fault only paths starting with this prefix. Omit to match every path. */
657
+ pathPrefix?: string;
658
+ /**
659
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
660
+ * an in-process caller usually wants, and what a parallel worker usually does not:
661
+ * rules added through `POST /__admin/faults` default to the calling namespace.
662
+ */
663
+ namespace?: string;
664
+ /**
665
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
666
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
667
+ * the request then still reaches the service.
668
+ */
669
+ status?: number;
670
+ /** Response body, serialized as JSON. A string is sent as-is. */
671
+ body?: unknown;
672
+ headers?: Record<string, string>;
673
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
674
+ count?: number;
675
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
676
+ rate?: number;
677
+ /** Hold the response back this long, to exercise timeouts. */
678
+ delayMs?: number;
679
+ /** Alias of `delayMs`. */
680
+ latencyMs?: number;
681
+ /**
682
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
683
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
684
+ */
685
+ drop?: boolean;
686
+ /**
687
+ * A named service behaviour to switch on for the matching request instead of (or
688
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
689
+ * read it with `faultEffects(request)`.
690
+ */
691
+ effect?: string;
692
+ /** Parameters for `effect`. */
693
+ params?: Record<string, unknown>;
694
+ /** From the preset this rule was expanded from, if any. */
695
+ preset?: string;
696
+ };
697
+ /** A fault that fired for one request. */
698
+ type FaultHit = {
699
+ id: string;
700
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
701
+ response?: Response;
702
+ drop?: boolean;
703
+ effect?: {
704
+ name: string;
705
+ params: Record<string, unknown>;
706
+ };
707
+ };
708
+ /** What a request looks like to the fault matcher. */
709
+ type FaultCandidate = {
710
+ operationId: string | undefined;
711
+ method: string;
712
+ path: string;
713
+ namespace: string;
714
+ };
715
+ type FaultRegistry = {
716
+ add(rule: FaultRule): FaultRule;
717
+ list(): (FaultRule & {
718
+ remaining: number | null;
719
+ hits: number;
720
+ })[];
721
+ remove(id: string): boolean;
722
+ clear(): void;
723
+ /**
724
+ * Every fault this request should get, in rule order, stopping at the first that answers
725
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
726
+ * each matching rule's remaining uses.
727
+ */
728
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
729
+ };
730
+
731
+ /** One handled request, as the structured log sees it. */
732
+ type RequestLog = {
733
+ service: string;
734
+ namespace: string;
735
+ operationId: string | undefined;
736
+ method: string;
737
+ path: string;
738
+ status: number;
739
+ durationMs: number;
740
+ /** True when the path matched no operation in the contract. */
741
+ unmatched: boolean;
742
+ /** Set when a fault rule produced the response. */
743
+ faultId?: string;
744
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
745
+ ids?: Record<string, string>;
746
+ /** Set when the service created a resource the request referred to but that did not exist. */
747
+ adopted?: boolean;
748
+ };
749
+ type MetricsReport = {
750
+ requests: number;
751
+ /** Counts keyed `<operationId> <status>`. */
752
+ byOperation: Record<string, number>;
753
+ /**
754
+ * Paths that matched no operation, most frequent first.
755
+ *
756
+ * This is the early-warning signal: a consumer calling something the mock does
757
+ * not implement shows up here as a count, before it fails a suite as a 404.
758
+ */
759
+ unmatched: {
760
+ method: string;
761
+ path: string;
762
+ count: number;
763
+ }[];
764
+ faults: number;
765
+ totalDurationMs: number;
766
+ };
767
+ type Metrics = {
768
+ record(entry: RequestLog): void;
769
+ report(): MetricsReport;
770
+ reset(): void;
771
+ };
772
+
773
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
774
+ type JournalEntry = RequestLog & {
775
+ at: string;
776
+ };
777
+ type JournalQuery = {
778
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
779
+ namespace?: string;
780
+ operationId?: string;
781
+ status?: number;
782
+ /** Only entries at or after this instant (epoch ms). */
783
+ since?: number;
784
+ /** At most this many, the most recent kept. */
785
+ limit?: number;
786
+ };
787
+ type Journal = {
788
+ readonly size: number;
789
+ record(entry: JournalEntry): void;
790
+ list(query?: JournalQuery): JournalEntry[];
791
+ /** Forget one namespace's entries, or every namespace's. */
792
+ clear(namespace?: string): void;
793
+ };
794
+
795
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
796
+ type CredentialRegistry = {
797
+ set(credential: string, namespace: string): void;
798
+ get(credential: string): string | undefined;
799
+ remove(credential: string): boolean;
800
+ clear(): void;
801
+ entries(): {
802
+ credential: string;
803
+ namespace: string;
804
+ }[];
805
+ };
806
+
807
+ /** A stable identifier for a point in a {@link Timeline}. */
808
+ type CheckpointId = string;
809
+ /** An immutable node in a timeline's checkpoint DAG. */
810
+ type Checkpoint<T> = Readonly<{
811
+ id: CheckpointId;
812
+ branch: string;
813
+ parent: CheckpointId | null;
814
+ /** Logical time supplied by the timeline's injected clock. */
815
+ at: number;
816
+ value: T;
817
+ }>;
818
+ type TimelineOptions = {
819
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
820
+ now?: () => number;
821
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
822
+ maxCheckpoints?: number;
823
+ /** Customize deterministic checkpoint IDs. */
824
+ id?: (sequence: number) => CheckpointId;
825
+ };
826
+ type CommitOptions = {
827
+ branch?: string;
828
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
829
+ parent?: CheckpointId | null;
830
+ };
831
+ type ForkOptions = {
832
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
833
+ from?: CheckpointId;
834
+ };
835
+ /**
836
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
837
+ * records, namespace images, or copy-on-write SQL engine snapshots.
838
+ *
839
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
840
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
841
+ * (the logical clock) is injected.
842
+ */
843
+ declare class Timeline<T> {
844
+ readonly maxCheckpoints: number;
845
+ private readonly now;
846
+ private readonly makeId;
847
+ private readonly nodes;
848
+ private readonly heads;
849
+ /** Unreferenced nodes in the exact order they became collectible. */
850
+ private readonly evictable;
851
+ /** Branch heads plus explicit retainers. Absent means zero. */
852
+ private readonly references;
853
+ private readonly explicitPins;
854
+ private sequence;
855
+ constructor(options?: TimelineOptions);
856
+ /** Capture a new immutable value and move `branch` to it. */
857
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
858
+ /** Create a branch pointer without copying its checkpoint value. */
859
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
860
+ /** Move a branch pointer to an existing checkpoint. */
861
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
862
+ get(id: CheckpointId): Checkpoint<T>;
863
+ head(branch?: string): Checkpoint<T> | undefined;
864
+ hasBranch(branch: string): boolean;
865
+ branches(): Readonly<Record<string, CheckpointId>>;
866
+ checkpoints(): readonly Checkpoint<T>[];
867
+ /** Number of retained checkpoints without allocating an array. */
868
+ get size(): number;
869
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
870
+ retain(id: CheckpointId): Checkpoint<T>;
871
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
872
+ release(id: CheckpointId): boolean;
873
+ deleteBranch(branch: string): boolean;
874
+ /**
875
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
876
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
877
+ * storage dependency, so a retained node remains usable after pruning.
878
+ */
879
+ gc(max?: number): CheckpointId[];
880
+ private collect;
881
+ private moveHead;
882
+ private addReference;
883
+ private removeReference;
884
+ private assertBranch;
885
+ }
886
+
887
+ /**
888
+ * Anything that can answer a Fetch `Request` with a `Response`.
889
+ *
890
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
891
+ * It is the only contract shared across the whole graph.
892
+ */
893
+ interface FetchAPI$1 {
894
+ fetch(request: Request): Promise<Response>;
895
+ }
896
+
897
+ /**
898
+ * A point-in-time copy of everything a service namespace holds.
899
+ *
900
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
901
+ * is generic: any service gets per-test rollback without knowing its own schema.
902
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
903
+ */
904
+ type NamespaceSnapshot = {
905
+ namespace: string;
906
+ records: {
907
+ collection: string;
908
+ id: string;
909
+ seq: number;
910
+ value: string;
911
+ }[];
912
+ sequences: {
913
+ name: string;
914
+ kind: string;
915
+ value: number;
916
+ }[];
917
+ };
918
+
919
+ type WebhookEndpoint = {
920
+ /** Stable id; generated when omitted. */
921
+ id?: string;
922
+ url: string;
923
+ secret?: string;
924
+ /** Event types to deliver; omit or include `"*"` for every type. */
925
+ events?: string[];
926
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
927
+ tags?: Record<string, string>;
928
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
929
+ signUrl?: string;
930
+ headers?: Record<string, string>;
931
+ };
932
+ type WebhookMessage = {
933
+ id: string;
934
+ namespace: string;
935
+ type: string;
936
+ body: string;
937
+ contentType: string;
938
+ tags: Record<string, string>;
939
+ headers?: Record<string, string>;
940
+ /** Wall-clock ISO-8601 time of publication. */
941
+ publishedAt: string;
942
+ };
943
+ type WebhookAttempt = {
944
+ attempt: number;
945
+ at: string;
946
+ status: number | null;
947
+ error: string | null;
948
+ durationMs: number;
949
+ /** Exact receiver response body, when one was returned. */
950
+ responseBody?: string | null;
951
+ };
952
+ type WebhookDelivery = {
953
+ id: string;
954
+ messageId: string;
955
+ namespace: string;
956
+ type: string;
957
+ endpointId: string;
958
+ url: string;
959
+ state: "pending" | "delivered" | "failed" | "dropped";
960
+ attempts: WebhookAttempt[];
961
+ };
962
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
963
+ type WebhookFault = {
964
+ mode: "duplicate" | "reorder" | "drop";
965
+ /** Messages affected; default 1. */
966
+ count?: number;
967
+ };
968
+ type PublishInput = {
969
+ namespace: string;
970
+ type: string;
971
+ /** Exact body; objects are JSON-encoded. */
972
+ body: string | Record<string, unknown> | unknown[];
973
+ /** Default `application/json`, or form-encoded when `form` is given. */
974
+ contentType?: string;
975
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
976
+ form?: Record<string, string>;
977
+ tags?: Record<string, string>;
978
+ /** Message-specific delivery headers, captured as part of durable message state. */
979
+ headers?: Record<string, string>;
980
+ /** Message id; generated when omitted. */
981
+ id?: string;
982
+ };
983
+ type WebhookHub = {
984
+ publish(input: PublishInput): WebhookMessage;
985
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
986
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
987
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
988
+ endpoints(namespace: string): WebhookEndpoint[];
989
+ messages(namespace?: string): WebhookMessage[];
990
+ deliveries(namespace?: string): WebhookDelivery[];
991
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
992
+ /** Run every pending retry (and release held reordered messages) now. */
993
+ flush(): Promise<void>;
994
+ /** Resolve once nothing is in flight. */
995
+ idle(): Promise<void>;
996
+ fault(namespace: string, fault: WebhookFault): void;
997
+ clear(namespace?: string): void;
998
+ };
999
+
1000
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
1001
+ type ServiceInstance = FetchAPI$1 & {
1002
+ reset(): Promise<void>;
1003
+ };
1004
+ type ServiceTimelineState = Readonly<{
1005
+ snapshot: NamespaceSnapshot;
1006
+ clock: Readonly<ReturnType<Clock["state"]>>;
1007
+ rngState: number;
1008
+ }>;
1009
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1010
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
1011
+ readonly name: string;
1012
+ readonly sqlite: SqliteClient$1;
1013
+ readonly clock: Clock;
1014
+ readonly faults: FaultRegistry;
1015
+ readonly metrics: Metrics;
1016
+ readonly journal: Journal;
1017
+ readonly rng: Rng;
1018
+ readonly credentials: CredentialRegistry;
1019
+ /** The webhook hub, when the service has outbound webhooks. */
1020
+ readonly webhooks: WebhookHub | undefined;
1021
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1022
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1023
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
1024
+ instance(namespace?: string): T;
1025
+ /** Public names of every namespace created so far. */
1026
+ namespaces(): string[];
1027
+ /** Reset one namespace, or every namespace with `"*"`. */
1028
+ reset(namespace?: string): Promise<void>;
1029
+ snapshot(namespace?: string): NamespaceSnapshot;
1030
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1031
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
1032
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1033
+ /** Create an isolated branch, optionally from a historical checkpoint. */
1034
+ branch(name: string, options?: {
1035
+ namespace?: string;
1036
+ at?: string;
1037
+ }): ServiceCheckpoint;
1038
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
1039
+ checkout(checkpoint: string, options?: {
1040
+ namespace?: string;
1041
+ branch?: string;
1042
+ }): void;
1043
+ /** Inspect the retained history for a namespace. */
1044
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
1045
+ };
1046
+
1047
+ /** Options every provider constructor accepts. */
1048
+ type APIOptions = {
1049
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
1050
+ sqlite?: SqliteClient$1;
1051
+ /** Clock used for `created`-style fields. Default `Date.now`. */
1052
+ now?: () => number;
1053
+ /**
1054
+ * Storage namespace for this instance's records. Instances sharing one SQLite
1055
+ * client stay isolated when their namespaces differ. Defaults to the service name.
1056
+ */
1057
+ namespace?: string;
1058
+ };
1059
+
1060
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1061
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1062
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1063
+ type SqliteRunResult = {
1064
+ changes: number;
1065
+ lastInsertRowid: number | bigint;
1066
+ };
1067
+ /**
1068
+ * Prepared statement bound to a {@link SqliteClient}.
1069
+ *
1070
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1071
+ */
1072
+ interface SqliteStatement {
1073
+ run(...params: SqliteValue[]): SqliteRunResult;
1074
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
1075
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1076
+ }
1077
+ /**
1078
+ * Sync SQLite client port owned by Mockingbird.
1079
+ *
1080
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1081
+ * `bun:sqlite` instances all work when they expose this surface.
1082
+ */
1083
+ interface SqliteClient {
1084
+ exec(sql: string): void;
1085
+ prepare(sql: string): SqliteStatement;
1086
+ transaction<T>(fn: () => T): T;
1087
+ }
1088
+
1089
+ /** MedPax-specific pricing and stock, present on products that can go into a MedPax pack. */
1090
+ type MedPaxDetails = {
1091
+ name: string;
1092
+ genericName: string;
1093
+ quantity: number;
1094
+ wholesalePrice: number;
1095
+ retailPrice: number;
1096
+ };
1097
+ /** One `GET /api/Orders/ProductList` row, in the field names our consumers parse. */
1098
+ type Product = {
1099
+ productName: string;
1100
+ sku: string;
1101
+ medPaxSku: string;
1102
+ categories: string;
1103
+ retailPrice: number;
1104
+ upc: string;
1105
+ descriptionShort: string;
1106
+ descriptionFull?: string;
1107
+ brand: string;
1108
+ productImage: string;
1109
+ quantity: number;
1110
+ countUnit: string;
1111
+ wholesalePrice: number;
1112
+ supplementFactsHTML: string;
1113
+ defaultDosing: {
1114
+ time: string;
1115
+ qty: number;
1116
+ }[];
1117
+ medPaxDetails?: MedPaxDetails | null;
1118
+ };
1119
+ /** One `medPaxPills` row of `GET /api/Orders/PrivateLabelProductList`. */
1120
+ type MedPaxPill = {
1121
+ sku: string;
1122
+ genericName: string;
1123
+ privateLabelName: string;
1124
+ quantity: number;
1125
+ };
1126
+ /** One `privateLabelCartons` row of `GET /api/Orders/PrivateLabelProductList`. */
1127
+ type PrivateLabelCarton = {
1128
+ sku: string;
1129
+ name: string;
1130
+ cartonImage: string;
1131
+ quantity: number;
1132
+ };
1133
+ type Catalog = {
1134
+ products: Product[];
1135
+ medPaxPills: MedPaxPill[];
1136
+ privateLabelCartons: PrivateLabelCarton[];
1137
+ };
1138
+
1139
+ /**
1140
+ * Anything that can answer a Fetch `Request` with a `Response`.
1141
+ *
1142
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
1143
+ * It is the only contract shared across the whole graph.
1144
+ */
1145
+ interface FetchAPI {
1146
+ fetch(request: Request): Promise<Response>;
1147
+ }
1148
+
1149
+ type Tracking = {
1150
+ trackingNumber: string;
1151
+ carrier: string;
1152
+ trackingUrl?: string;
1153
+ };
1154
+ /**
1155
+ * One order as Wholescripts reports it on `GET /api/Orders/Status`. The shipping address and
1156
+ * recipient (PHI) are validated on submit but never stored; only the SKUs and quantities are
1157
+ * kept, to price the order.
1158
+ */
1159
+ type OrderRecord = {
1160
+ orderNumber: string;
1161
+ orderDate: string;
1162
+ salesOrder: string;
1163
+ status: string;
1164
+ tracking: Tracking[];
1165
+ message: string;
1166
+ subTotal: number;
1167
+ shipMethod: string;
1168
+ shipCharge: number;
1169
+ discount: number;
1170
+ tax: number;
1171
+ serviceFee: number;
1172
+ orderTotal: number;
1173
+ items: {
1174
+ sku: string;
1175
+ quantity: number;
1176
+ }[];
1177
+ /** Mock-clock epoch ms of creation, for auto-advance. */
1178
+ createdAtMs: number;
1179
+ /** Steps of `autoAdvance.path` already applied. */
1180
+ advanced: number;
1181
+ };
1182
+ type AutoAdvance = {
1183
+ /** Mock-clock delay between steps. */
1184
+ afterMs: number;
1185
+ /** Statuses to walk through, e.g. `["Processing", "Complete"]`. */
1186
+ path: string[];
1187
+ };
1188
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
1189
+ type Settings = {
1190
+ /** Only these Basic credentials are accepted; empty means any non-empty pair is. */
1191
+ accounts: {
1192
+ username: string;
1193
+ password: string;
1194
+ }[];
1195
+ autoAdvance: AutoAdvance | null;
1196
+ };
1197
+ declare class WholescriptsState {
1198
+ private readonly seed;
1199
+ readonly orders: Collection<OrderRecord>;
1200
+ readonly catalogs: Collection<Catalog>;
1201
+ readonly settings: Collection<Settings>;
1202
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
1203
+ catalog: Catalog | undefined;
1204
+ settings: Partial<Settings>;
1205
+ });
1206
+ /** Re-apply the catalog and settings after a reset. */
1207
+ ensureSeeded(): void;
1208
+ catalog(): Catalog;
1209
+ replaceCatalog(catalog: Catalog): Catalog;
1210
+ current(): Settings;
1211
+ update(patch: Partial<Settings>): Settings;
1212
+ nextOrderNumber(): string;
1213
+ }
1214
+
1215
+ type WholescriptsAPIOptions = APIOptions & {
1216
+ /** The catalog every namespace starts with. Default: {@link DEFAULT_CATALOG}. */
1217
+ catalog?: Catalog;
1218
+ /** Initial per-namespace settings (accounts, auto-advance). */
1219
+ settings?: Partial<Settings>;
1220
+ };
1221
+ type TransitionInput = {
1222
+ to: string;
1223
+ trackingNumber?: string;
1224
+ carrier?: string;
1225
+ trackingUrl?: string;
1226
+ message?: string;
1227
+ };
1228
+ /**
1229
+ * Stateful mock of the Wholescripts supplement fulfilment API.
1230
+ *
1231
+ * Orders start `Pending` and move only through admin transitions or auto-advance; nothing is
1232
+ * pushed to the app (Wholescripts has no webhooks), so the app sees each change on its next
1233
+ * `GET /api/Orders/Status` poll.
1234
+ */
1235
+ declare class WholescriptsAPI implements FetchAPI {
1236
+ readonly app: Hono;
1237
+ readonly sqlite: SqliteClient;
1238
+ readonly state: WholescriptsState;
1239
+ private readonly service;
1240
+ private readonly now;
1241
+ constructor(options?: WholescriptsAPIOptions);
1242
+ fetch(request: Request): Promise<Response>;
1243
+ reset(): Promise<void>;
1244
+ private iso;
1245
+ private productList;
1246
+ private submit;
1247
+ private status;
1248
+ private cancel;
1249
+ /** Move an order to a vendor status; `Complete` (or a tracking number) adds tracking. */
1250
+ transition(orderNumber: string, input: TransitionInput): OrderRecord | undefined;
1251
+ /**
1252
+ * Apply every auto-advance step that is due on the mock clock. Runs before each vendor
1253
+ * request, on `POST /__admin/tick`, and from the served runtime's background ticker.
1254
+ */
1255
+ tick(): number;
1256
+ orders(): OrderRecord[];
1257
+ }
1258
+
1259
+ type WholescriptsRuntimeOptions = {
1260
+ sqlite?: SqliteClient;
1261
+ clock?: Clock;
1262
+ seed?: number | string;
1263
+ adminKey?: string;
1264
+ onLog?: (entry: RequestLog) => void;
1265
+ catalog?: Catalog;
1266
+ settings?: Partial<Settings>;
1267
+ /**
1268
+ * Run auto-advance on this real-time interval (ms). The served mock uses 100 ms; in-process
1269
+ * runtimes default to off (requests and `POST /__admin/tick` still advance).
1270
+ */
1271
+ tickMs?: number;
1272
+ };
1273
+ type WholescriptsRuntime = ServiceRuntime<WholescriptsAPI> & {
1274
+ /** Stop the background ticker, if one runs. */
1275
+ stop(): void;
1276
+ };
1277
+
1278
+ /** Port `mockingbird-wholescripts serve` listens on when none is given. */
1279
+ declare const DEFAULT_PORT = 8803;
1280
+ type WholescriptsServerOptions = WholescriptsRuntimeOptions & {
1281
+ /** Default `0`: the OS picks a free port. */
1282
+ port?: number;
1283
+ /** Default `127.0.0.1`. */
1284
+ host?: string;
1285
+ };
1286
+ type WholescriptsServer = Listening & {
1287
+ runtime: WholescriptsRuntime;
1288
+ };
1289
+ /** Serve the Wholescripts mock over `node:http`, with auto-advance ticking every 100 ms. */
1290
+ declare const createServer: (options?: WholescriptsServerOptions) => Promise<WholescriptsServer>;
1291
+ /** How `serve` (and `serve --config`) builds the Wholescripts mock from flags. */
1292
+ declare const serveTarget: ServeTarget;
1293
+
1294
+ export { DEFAULT_PORT, createServer, serveTarget };
1295
+ export type { WholescriptsServer, WholescriptsServerOptions };