@crvouga/mockingbird-service-aha 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,1025 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /**
14
+ * The single source of time for a service.
15
+ *
16
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
17
+ * sleeping: appointment windows, result delays and expiries become reachable in
18
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
19
+ */
20
+ type ClockState = {
21
+ /** Current epoch milliseconds. */
22
+ now: number;
23
+ /** True while time does not advance on its own. */
24
+ frozen: boolean;
25
+ /** Milliseconds this clock adds to its underlying source. */
26
+ offsetMs: number;
27
+ };
28
+ type Clock = {
29
+ now(): number;
30
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
31
+ set(epochMs: number): void;
32
+ /** Move the clock forward, or back with a negative delta. */
33
+ advance(deltaMs: number): void;
34
+ /** Stop time at the current instant. */
35
+ freeze(): void;
36
+ /** Resume from the current instant. */
37
+ unfreeze(): void;
38
+ /** Drop back to the underlying source, live. */
39
+ reset(): void;
40
+ state(): ClockState;
41
+ };
42
+
43
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
45
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
46
+ type SqliteRunResult$1 = {
47
+ changes: number;
48
+ lastInsertRowid: number | bigint;
49
+ };
50
+ /**
51
+ * Prepared statement bound to a {@link SqliteClient}.
52
+ *
53
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
+ */
55
+ interface SqliteStatement$1 {
56
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
57
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
58
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
59
+ }
60
+ /**
61
+ * Sync SQLite client port owned by Mockingbird.
62
+ *
63
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
+ * `bun:sqlite` instances all work when they expose this surface.
65
+ */
66
+ interface SqliteClient$1 {
67
+ exec(sql: string): void;
68
+ prepare(sql: string): SqliteStatement$1;
69
+ transaction<T>(fn: () => T): T;
70
+ }
71
+
72
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
+ type Stored<T> = {
74
+ seq: number;
75
+ value: T;
76
+ };
77
+ type ListRecordsOptions<T> = {
78
+ /** Keep only records passing the predicate. */
79
+ where?: (value: T, seq: number) => boolean;
80
+ /** Sort order; default newest first. */
81
+ order?: "newest" | "oldest";
82
+ };
83
+ /**
84
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
+ * sequence, never by id lexicographic order, so list semantics stay stable.
86
+ */
87
+ declare class Collection<T> {
88
+ private readonly sqlite;
89
+ private readonly namespace;
90
+ private readonly name;
91
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
92
+ private bumpCollectionSeq;
93
+ nextSequence(): number;
94
+ get(id: string): T | undefined;
95
+ has(id: string): boolean;
96
+ /** Insert a new record, assigning it the next sequence number. */
97
+ insert(id: string, value: T): Stored<T>;
98
+ /** Replace an existing record's value, keeping its position. */
99
+ update(id: string, value: T): Stored<T> | undefined;
100
+ delete(id: string): boolean;
101
+ /** How many records the collection holds, without reading them. */
102
+ count(): number;
103
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
104
+ id: string;
105
+ }>;
106
+ }
107
+
108
+ /**
109
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
110
+ * request a percentage fault hits — is reproducible from a seed.
111
+ *
112
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
113
+ * than statistical quality.
114
+ */
115
+ type Rng = {
116
+ /** Next value in `[0, 1)`. */
117
+ next(): number;
118
+ /** Next integer in `[min, max]`. */
119
+ int(min: number, max: number): number;
120
+ /** Restart the stream from its seed. */
121
+ reset(): void;
122
+ /** Serializable engine state used by deterministic checkpoints. */
123
+ state(): number;
124
+ /** Restore a state previously returned by {@link state}. */
125
+ setState(state: number): void;
126
+ seed: number;
127
+ };
128
+
129
+ /**
130
+ * A deliberate failure injected in front of an operation.
131
+ *
132
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
133
+ * quota error that only appears when a shared sandbox is full, the 429 that only
134
+ * appears under load, the 5xx that proves a retry path works.
135
+ */
136
+ type FaultRule = {
137
+ /** Stable id, so a suite can retire exactly the rule it added. */
138
+ id: string;
139
+ /** Fault only this operation. Omit to match every operation. */
140
+ operationId?: string;
141
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
142
+ method?: string;
143
+ /** Fault only paths starting with this prefix. Omit to match every path. */
144
+ pathPrefix?: string;
145
+ /**
146
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
147
+ * an in-process caller usually wants, and what a parallel worker usually does not:
148
+ * rules added through `POST /__admin/faults` default to the calling namespace.
149
+ */
150
+ namespace?: string;
151
+ /**
152
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
153
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
154
+ * the request then still reaches the service.
155
+ */
156
+ status?: number;
157
+ /** Response body, serialized as JSON. A string is sent as-is. */
158
+ body?: unknown;
159
+ headers?: Record<string, string>;
160
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
161
+ count?: number;
162
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
163
+ rate?: number;
164
+ /** Hold the response back this long, to exercise timeouts. */
165
+ delayMs?: number;
166
+ /** Alias of `delayMs`. */
167
+ latencyMs?: number;
168
+ /**
169
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
170
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
171
+ */
172
+ drop?: boolean;
173
+ /**
174
+ * A named service behaviour to switch on for the matching request instead of (or
175
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
176
+ * read it with `faultEffects(request)`.
177
+ */
178
+ effect?: string;
179
+ /** Parameters for `effect`. */
180
+ params?: Record<string, unknown>;
181
+ /** From the preset this rule was expanded from, if any. */
182
+ preset?: string;
183
+ };
184
+ /** A fault that fired for one request. */
185
+ type FaultHit = {
186
+ id: string;
187
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
188
+ response?: Response;
189
+ drop?: boolean;
190
+ effect?: {
191
+ name: string;
192
+ params: Record<string, unknown>;
193
+ };
194
+ };
195
+ /**
196
+ * A named, documented fault a suite switches on by name
197
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
198
+ * webhook delivery fault.
199
+ */
200
+ type FaultPreset = {
201
+ description: string;
202
+ rules?: Omit<FaultRule, "id">[];
203
+ webhook?: {
204
+ mode: "duplicate" | "reorder" | "drop";
205
+ count?: number;
206
+ };
207
+ };
208
+ /** What a request looks like to the fault matcher. */
209
+ type FaultCandidate = {
210
+ operationId: string | undefined;
211
+ method: string;
212
+ path: string;
213
+ namespace: string;
214
+ };
215
+ type FaultRegistry = {
216
+ add(rule: FaultRule): FaultRule;
217
+ list(): (FaultRule & {
218
+ remaining: number | null;
219
+ hits: number;
220
+ })[];
221
+ remove(id: string): boolean;
222
+ clear(): void;
223
+ /**
224
+ * Every fault this request should get, in rule order, stopping at the first that answers
225
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
226
+ * each matching rule's remaining uses.
227
+ */
228
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
229
+ };
230
+
231
+ /** One handled request, as the structured log sees it. */
232
+ type RequestLog = {
233
+ service: string;
234
+ namespace: string;
235
+ operationId: string | undefined;
236
+ method: string;
237
+ path: string;
238
+ status: number;
239
+ durationMs: number;
240
+ /** True when the path matched no operation in the contract. */
241
+ unmatched: boolean;
242
+ /** Set when a fault rule produced the response. */
243
+ faultId?: string;
244
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
245
+ ids?: Record<string, string>;
246
+ /** Set when the service created a resource the request referred to but that did not exist. */
247
+ adopted?: boolean;
248
+ };
249
+ type MetricsReport = {
250
+ requests: number;
251
+ /** Counts keyed `<operationId> <status>`. */
252
+ byOperation: Record<string, number>;
253
+ /**
254
+ * Paths that matched no operation, most frequent first.
255
+ *
256
+ * This is the early-warning signal: a consumer calling something the mock does
257
+ * not implement shows up here as a count, before it fails a suite as a 404.
258
+ */
259
+ unmatched: {
260
+ method: string;
261
+ path: string;
262
+ count: number;
263
+ }[];
264
+ faults: number;
265
+ totalDurationMs: number;
266
+ };
267
+ type Metrics = {
268
+ record(entry: RequestLog): void;
269
+ report(): MetricsReport;
270
+ reset(): void;
271
+ };
272
+
273
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
274
+ type JournalEntry = RequestLog & {
275
+ at: string;
276
+ };
277
+ type JournalQuery = {
278
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
279
+ namespace?: string;
280
+ operationId?: string;
281
+ status?: number;
282
+ /** Only entries at or after this instant (epoch ms). */
283
+ since?: number;
284
+ /** At most this many, the most recent kept. */
285
+ limit?: number;
286
+ };
287
+ type Journal = {
288
+ readonly size: number;
289
+ record(entry: JournalEntry): void;
290
+ list(query?: JournalQuery): JournalEntry[];
291
+ /** Forget one namespace's entries, or every namespace's. */
292
+ clear(namespace?: string): void;
293
+ };
294
+
295
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
296
+ type CredentialRegistry = {
297
+ set(credential: string, namespace: string): void;
298
+ get(credential: string): string | undefined;
299
+ remove(credential: string): boolean;
300
+ clear(): void;
301
+ entries(): {
302
+ credential: string;
303
+ namespace: string;
304
+ }[];
305
+ };
306
+
307
+ type IdempotencyErrors = {
308
+ /** Same key, different parameters. */
309
+ mismatch: () => Response;
310
+ /** Same key while the first request is still being handled. */
311
+ conflict: () => Response;
312
+ };
313
+ declare class IdempotencyStore {
314
+ private readonly namespace;
315
+ private readonly responses;
316
+ constructor(sqlite: SqliteClient$1, namespace: string, name?: string);
317
+ /**
318
+ * Run `handler` once per `key`. `fingerprint` identifies the request's parameters (e.g.
319
+ * the method, path and canonical body). Only `replayable` responses are stored (default:
320
+ * every status below 500, as Stripe does), so a transient failure can be retried.
321
+ */
322
+ run(key: string, fingerprint: string, errors: IdempotencyErrors, handler: () => Promise<Response> | Response, replayable?: (status: number) => boolean): Promise<Response>;
323
+ }
324
+
325
+ /**
326
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
327
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
328
+ */
329
+ declare class IdSequence {
330
+ private readonly sqlite;
331
+ private readonly namespace;
332
+ private readonly salt;
333
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
334
+ next(prefix: string, length?: number): string;
335
+ }
336
+
337
+ /** A stable identifier for a point in a {@link Timeline}. */
338
+ type CheckpointId = string;
339
+ /** An immutable node in a timeline's checkpoint DAG. */
340
+ type Checkpoint<T> = Readonly<{
341
+ id: CheckpointId;
342
+ branch: string;
343
+ parent: CheckpointId | null;
344
+ /** Logical time supplied by the timeline's injected clock. */
345
+ at: number;
346
+ value: T;
347
+ }>;
348
+ type TimelineOptions = {
349
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
350
+ now?: () => number;
351
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
352
+ maxCheckpoints?: number;
353
+ /** Customize deterministic checkpoint IDs. */
354
+ id?: (sequence: number) => CheckpointId;
355
+ };
356
+ type CommitOptions = {
357
+ branch?: string;
358
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
359
+ parent?: CheckpointId | null;
360
+ };
361
+ type ForkOptions = {
362
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
363
+ from?: CheckpointId;
364
+ };
365
+ /**
366
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
367
+ * records, namespace images, or copy-on-write SQL engine snapshots.
368
+ *
369
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
370
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
371
+ * (the logical clock) is injected.
372
+ */
373
+ declare class Timeline<T> {
374
+ readonly maxCheckpoints: number;
375
+ private readonly now;
376
+ private readonly makeId;
377
+ private readonly nodes;
378
+ private readonly heads;
379
+ /** Unreferenced nodes in the exact order they became collectible. */
380
+ private readonly evictable;
381
+ /** Branch heads plus explicit retainers. Absent means zero. */
382
+ private readonly references;
383
+ private readonly explicitPins;
384
+ private sequence;
385
+ constructor(options?: TimelineOptions);
386
+ /** Capture a new immutable value and move `branch` to it. */
387
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
388
+ /** Create a branch pointer without copying its checkpoint value. */
389
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
390
+ /** Move a branch pointer to an existing checkpoint. */
391
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
392
+ get(id: CheckpointId): Checkpoint<T>;
393
+ head(branch?: string): Checkpoint<T> | undefined;
394
+ hasBranch(branch: string): boolean;
395
+ branches(): Readonly<Record<string, CheckpointId>>;
396
+ checkpoints(): readonly Checkpoint<T>[];
397
+ /** Number of retained checkpoints without allocating an array. */
398
+ get size(): number;
399
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
400
+ retain(id: CheckpointId): Checkpoint<T>;
401
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
402
+ release(id: CheckpointId): boolean;
403
+ deleteBranch(branch: string): boolean;
404
+ /**
405
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
406
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
407
+ * storage dependency, so a retained node remains usable after pruning.
408
+ */
409
+ gc(max?: number): CheckpointId[];
410
+ private collect;
411
+ private moveHead;
412
+ private addReference;
413
+ private removeReference;
414
+ private assertBranch;
415
+ }
416
+
417
+ /**
418
+ * Anything that can answer a Fetch `Request` with a `Response`.
419
+ *
420
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
421
+ * It is the only contract shared across the whole graph.
422
+ */
423
+ interface FetchAPI {
424
+ fetch(request: Request): Promise<Response>;
425
+ }
426
+
427
+ /**
428
+ * A point-in-time copy of everything a service namespace holds.
429
+ *
430
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
431
+ * is generic: any service gets per-test rollback without knowing its own schema.
432
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
433
+ */
434
+ type NamespaceSnapshot = {
435
+ namespace: string;
436
+ records: {
437
+ collection: string;
438
+ id: string;
439
+ seq: number;
440
+ value: string;
441
+ }[];
442
+ sequences: {
443
+ name: string;
444
+ kind: string;
445
+ value: number;
446
+ }[];
447
+ };
448
+
449
+ type WebhookEndpoint = {
450
+ /** Stable id; generated when omitted. */
451
+ id?: string;
452
+ url: string;
453
+ secret?: string;
454
+ /** Event types to deliver; omit or include `"*"` for every type. */
455
+ events?: string[];
456
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
457
+ tags?: Record<string, string>;
458
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
459
+ signUrl?: string;
460
+ headers?: Record<string, string>;
461
+ };
462
+ type WebhookMessage = {
463
+ id: string;
464
+ namespace: string;
465
+ type: string;
466
+ body: string;
467
+ contentType: string;
468
+ tags: Record<string, string>;
469
+ headers?: Record<string, string>;
470
+ /** Wall-clock ISO-8601 time of publication. */
471
+ publishedAt: string;
472
+ };
473
+ type WebhookAttempt = {
474
+ attempt: number;
475
+ at: string;
476
+ status: number | null;
477
+ error: string | null;
478
+ durationMs: number;
479
+ /** Exact receiver response body, when one was returned. */
480
+ responseBody?: string | null;
481
+ };
482
+ type WebhookDelivery$1 = {
483
+ id: string;
484
+ messageId: string;
485
+ namespace: string;
486
+ type: string;
487
+ endpointId: string;
488
+ url: string;
489
+ state: "pending" | "delivered" | "failed" | "dropped";
490
+ attempts: WebhookAttempt[];
491
+ };
492
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
493
+ type WebhookFault = {
494
+ mode: "duplicate" | "reorder" | "drop";
495
+ /** Messages affected; default 1. */
496
+ count?: number;
497
+ };
498
+ type PublishInput = {
499
+ namespace: string;
500
+ type: string;
501
+ /** Exact body; objects are JSON-encoded. */
502
+ body: string | Record<string, unknown> | unknown[];
503
+ /** Default `application/json`, or form-encoded when `form` is given. */
504
+ contentType?: string;
505
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
506
+ form?: Record<string, string>;
507
+ tags?: Record<string, string>;
508
+ /** Message-specific delivery headers, captured as part of durable message state. */
509
+ headers?: Record<string, string>;
510
+ /** Message id; generated when omitted. */
511
+ id?: string;
512
+ };
513
+ type WebhookHub = {
514
+ publish(input: PublishInput): WebhookMessage;
515
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
516
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
517
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
518
+ endpoints(namespace: string): WebhookEndpoint[];
519
+ messages(namespace?: string): WebhookMessage[];
520
+ deliveries(namespace?: string): WebhookDelivery$1[];
521
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
522
+ /** Run every pending retry (and release held reordered messages) now. */
523
+ flush(): Promise<void>;
524
+ /** Resolve once nothing is in flight. */
525
+ idle(): Promise<void>;
526
+ fault(namespace: string, fault: WebhookFault): void;
527
+ clear(namespace?: string): void;
528
+ };
529
+
530
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
531
+ type ServiceInstance = FetchAPI & {
532
+ reset(): Promise<void>;
533
+ };
534
+ type ServiceTimelineState = Readonly<{
535
+ snapshot: NamespaceSnapshot;
536
+ clock: Readonly<ReturnType<Clock["state"]>>;
537
+ rngState: number;
538
+ }>;
539
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
540
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
541
+ readonly name: string;
542
+ readonly sqlite: SqliteClient$1;
543
+ readonly clock: Clock;
544
+ readonly faults: FaultRegistry;
545
+ readonly metrics: Metrics;
546
+ readonly journal: Journal;
547
+ readonly rng: Rng;
548
+ readonly credentials: CredentialRegistry;
549
+ /** The webhook hub, when the service has outbound webhooks. */
550
+ readonly webhooks: WebhookHub | undefined;
551
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
552
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
553
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
554
+ instance(namespace?: string): T;
555
+ /** Public names of every namespace created so far. */
556
+ namespaces(): string[];
557
+ /** Reset one namespace, or every namespace with `"*"`. */
558
+ reset(namespace?: string): Promise<void>;
559
+ snapshot(namespace?: string): NamespaceSnapshot;
560
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
561
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
562
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
563
+ /** Create an isolated branch, optionally from a historical checkpoint. */
564
+ branch(name: string, options?: {
565
+ namespace?: string;
566
+ at?: string;
567
+ }): ServiceCheckpoint;
568
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
569
+ checkout(checkpoint: string, options?: {
570
+ namespace?: string;
571
+ branch?: string;
572
+ }): void;
573
+ /** Inspect the retained history for a namespace. */
574
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
575
+ };
576
+
577
+ /** Options every provider constructor accepts. */
578
+ type APIOptions = {
579
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
580
+ sqlite?: SqliteClient$1;
581
+ /** Clock used for `created`-style fields. Default `Date.now`. */
582
+ now?: () => number;
583
+ /**
584
+ * Storage namespace for this instance's records. Instances sharing one SQLite
585
+ * client stay isolated when their namespaces differ. Defaults to the service name.
586
+ */
587
+ namespace?: string;
588
+ };
589
+
590
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
591
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
592
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
593
+ type SqliteRunResult = {
594
+ changes: number;
595
+ lastInsertRowid: number | bigint;
596
+ };
597
+ /**
598
+ * Prepared statement bound to a {@link SqliteClient}.
599
+ *
600
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
601
+ */
602
+ interface SqliteStatement {
603
+ run(...params: SqliteValue[]): SqliteRunResult;
604
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
605
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
606
+ }
607
+ /**
608
+ * Sync SQLite client port owned by Mockingbird.
609
+ *
610
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
611
+ * `bun:sqlite` instances all work when they expose this surface.
612
+ */
613
+ interface SqliteClient {
614
+ exec(sql: string): void;
615
+ prepare(sql: string): SqliteStatement;
616
+ transaction<T>(fn: () => T): T;
617
+ }
618
+
619
+ /**
620
+ * One order as the mock tracks it. Patient details are validated but never stored: the mock
621
+ * keeps only what it needs to emit consistent webhooks (ids, status, appointment time, zone).
622
+ */
623
+ type OrderRecord = {
624
+ partner_order_id: string;
625
+ /** AHA's own order id (`ahaOrderId` in webhooks). */
626
+ order_number: string;
627
+ /** The last status reported (`Order Placed` until a webhook goes out). */
628
+ status: string;
629
+ drawStatus: string | null;
630
+ /** The appointment instant (ISO-8601), once scheduled or preferred. */
631
+ scheduledAt: string | null;
632
+ /** IANA zone every local time in this order's webhooks is expressed in. */
633
+ timeZone: string;
634
+ cancelled: boolean;
635
+ created_at: string;
636
+ updated_at: string;
637
+ /** Mock-clock epoch ms of creation, for `autoSchedule`. */
638
+ createdAtMs: number;
639
+ autoScheduled: boolean;
640
+ };
641
+ type AutoSchedule = {
642
+ /** Emit `Scheduled` this long (mock clock) after the order is created. */
643
+ afterMs: number;
644
+ /** Appointment time relative to creation when the order carries no preferred time. Default 24 h. */
645
+ leadMs?: number;
646
+ };
647
+ type ApiCredential = {
648
+ apiKey: string;
649
+ /** HMAC secret (`AHA_API_SECRET`); omit to accept the key in legacy mode only. */
650
+ apiSecret?: string;
651
+ };
652
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
653
+ type Settings = {
654
+ /** `raw` `{content, message, status}` (AhaService) or `wrapped` `{success, data}` (AhaLabProvider). */
655
+ envelope: "raw" | "wrapped";
656
+ /**
657
+ * Known keys. Empty: any key is accepted and HMAC signatures are checked for shape only
658
+ * (the mock cannot know the secret). Non-empty: the key must match, and a key with a
659
+ * secret has its signature verified exactly.
660
+ */
661
+ credentials: ApiCredential[];
662
+ /** Accept `X-Geviti-Auth-Key` (legacy mode). Default true. */
663
+ allowLegacy: boolean;
664
+ /** Reject an `X-TIMESTAMP` further than this from wall-clock time; 0 disables. Default 5 min. */
665
+ timestampToleranceMs: number;
666
+ autoSchedule: AutoSchedule | null;
667
+ /** Zone for orders that send no `patient_timezone`. */
668
+ defaultTimeZone: string;
669
+ /** Emit a `Cancelled` webhook when the partner cancels through the API. Default true. */
670
+ cancelWebhook: boolean;
671
+ };
672
+ declare class AhaState {
673
+ private readonly seed;
674
+ readonly orders: Collection<OrderRecord>;
675
+ readonly settings: Collection<Settings>;
676
+ readonly ids: IdSequence;
677
+ readonly idempotency: IdempotencyStore;
678
+ constructor(sqlite: SqliteClient, namespace: string, seed: Partial<Settings>);
679
+ ensureSeeded(): void;
680
+ current(): Settings;
681
+ update(patch: Partial<Settings>): Settings;
682
+ /** By partner order id, then by AHA order number (our lab-provider cancels with the latter). */
683
+ findOrder(id: string): OrderRecord | undefined;
684
+ nextOrderNumber(): string;
685
+ }
686
+
687
+ /**
688
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
689
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
690
+ */
691
+ type JsonPrimitive = string | number | boolean | null;
692
+ type JsonValue = JsonPrimitive | JsonValue[] | {
693
+ [key: string]: JsonValue;
694
+ };
695
+ type ReferenceObject = {
696
+ $ref: string;
697
+ description?: string;
698
+ summary?: string;
699
+ };
700
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
701
+ type SchemaObject = {
702
+ $ref?: string;
703
+ type?: SchemaType | SchemaType[];
704
+ title?: string;
705
+ description?: string;
706
+ format?: string;
707
+ enum?: JsonValue[];
708
+ const?: JsonValue;
709
+ default?: JsonValue;
710
+ example?: JsonValue;
711
+ examples?: JsonValue[];
712
+ nullable?: boolean;
713
+ deprecated?: boolean;
714
+ readOnly?: boolean;
715
+ writeOnly?: boolean;
716
+ minimum?: number;
717
+ maximum?: number;
718
+ exclusiveMinimum?: number;
719
+ exclusiveMaximum?: number;
720
+ multipleOf?: number;
721
+ minLength?: number;
722
+ maxLength?: number;
723
+ pattern?: string;
724
+ minItems?: number;
725
+ maxItems?: number;
726
+ uniqueItems?: boolean;
727
+ items?: SchemaObject;
728
+ prefixItems?: SchemaObject[];
729
+ minProperties?: number;
730
+ maxProperties?: number;
731
+ required?: string[];
732
+ properties?: Record<string, SchemaObject>;
733
+ additionalProperties?: boolean | SchemaObject;
734
+ propertyNames?: SchemaObject;
735
+ oneOf?: SchemaObject[];
736
+ anyOf?: SchemaObject[];
737
+ allOf?: SchemaObject[];
738
+ not?: SchemaObject;
739
+ discriminator?: {
740
+ propertyName: string;
741
+ mapping?: Record<string, string>;
742
+ };
743
+ [extension: `x-${string}`]: unknown;
744
+ };
745
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
746
+ type ParameterObject = {
747
+ name: string;
748
+ in: ParameterLocation;
749
+ description?: string;
750
+ required?: boolean;
751
+ deprecated?: boolean;
752
+ style?: string;
753
+ explode?: boolean;
754
+ schema?: SchemaObject;
755
+ content?: Record<string, MediaTypeObject>;
756
+ example?: JsonValue;
757
+ [extension: `x-${string}`]: unknown;
758
+ };
759
+ type MediaTypeObject = {
760
+ schema?: SchemaObject;
761
+ example?: JsonValue;
762
+ examples?: Record<string, unknown>;
763
+ encoding?: Record<string, unknown>;
764
+ [extension: `x-${string}`]: unknown;
765
+ };
766
+ type RequestBodyObject = {
767
+ description?: string;
768
+ required?: boolean;
769
+ content: Record<string, MediaTypeObject>;
770
+ [extension: `x-${string}`]: unknown;
771
+ };
772
+ type HeaderObject = {
773
+ description?: string;
774
+ required?: boolean;
775
+ schema?: SchemaObject;
776
+ [extension: `x-${string}`]: unknown;
777
+ };
778
+ type ResponseObject = {
779
+ description: string;
780
+ headers?: Record<string, HeaderObject | ReferenceObject>;
781
+ content?: Record<string, MediaTypeObject>;
782
+ [extension: `x-${string}`]: unknown;
783
+ };
784
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
785
+ type SecurityRequirementObject = Record<string, string[]>;
786
+ type OperationObject = {
787
+ operationId?: string;
788
+ summary?: string;
789
+ description?: string;
790
+ tags?: string[];
791
+ deprecated?: boolean;
792
+ parameters?: Array<ParameterObject | ReferenceObject>;
793
+ requestBody?: RequestBodyObject | ReferenceObject;
794
+ responses: ResponsesObject;
795
+ security?: SecurityRequirementObject[];
796
+ [extension: `x-${string}`]: unknown;
797
+ };
798
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
799
+ type HttpMethod = (typeof HTTP_METHODS)[number];
800
+ type PathItemObject = {
801
+ summary?: string;
802
+ description?: string;
803
+ parameters?: Array<ParameterObject | ReferenceObject>;
804
+ [extension: `x-${string}`]: unknown;
805
+ } & Partial<Record<HttpMethod, OperationObject>>;
806
+ type SecuritySchemeObject = {
807
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
808
+ description?: string;
809
+ name?: string;
810
+ in?: ParameterLocation;
811
+ scheme?: string;
812
+ bearerFormat?: string;
813
+ flows?: Record<string, unknown>;
814
+ openIdConnectUrl?: string;
815
+ [extension: `x-${string}`]: unknown;
816
+ };
817
+ type ComponentsObject = {
818
+ schemas?: Record<string, SchemaObject>;
819
+ responses?: Record<string, ResponseObject>;
820
+ parameters?: Record<string, ParameterObject>;
821
+ requestBodies?: Record<string, RequestBodyObject>;
822
+ headers?: Record<string, HeaderObject>;
823
+ securitySchemes?: Record<string, SecuritySchemeObject>;
824
+ [extension: `x-${string}`]: unknown;
825
+ };
826
+ type ServerObject = {
827
+ url: string;
828
+ description?: string;
829
+ variables?: Record<string, unknown>;
830
+ [extension: `x-${string}`]: unknown;
831
+ };
832
+ type InfoObject = {
833
+ title: string;
834
+ version: string;
835
+ description?: string;
836
+ [extension: `x-${string}`]: unknown;
837
+ };
838
+ type OpenAPIDocument = {
839
+ openapi: string;
840
+ info: InfoObject;
841
+ servers?: ServerObject[];
842
+ paths: Record<string, PathItemObject>;
843
+ components?: ComponentsObject;
844
+ security?: SecurityRequirementObject[];
845
+ tags?: Array<{
846
+ name: string;
847
+ description?: string;
848
+ }>;
849
+ [extension: `x-${string}`]: unknown;
850
+ };
851
+
852
+ declare const document: OpenAPIDocument;
853
+ type OperationId = "CreateOrder" | "CancelOrder";
854
+ type SupportedOperationId = "CreateOrder" | "CancelOrder";
855
+ declare const operationIds: readonly ["CreateOrder", "CancelOrder"];
856
+ declare const supportedOperationIds: readonly ["CreateOrder", "CancelOrder"];
857
+
858
+ /**
859
+ * The status strings AHA sends in webhooks. Our handler lowercases them and replaces
860
+ * whitespace with `_`, so spelling and spacing matter; an admin transition may name them in
861
+ * any case and is normalised to the vendor spelling here.
862
+ */
863
+ declare const ORDER_STATUSES: readonly ["Scheduled", "Rescheduled", "Cancelled", "Check In", "Check Out", "Lab Testing In Progress", "Non Scheduled Update"];
864
+ /** `drawStatus` values sent with `Check Out` (the first two mean the sample was drawn). */
865
+ declare const DRAW_STATUSES: readonly ["Sample Collected", "Completed", "Patient Refused", "UTO", "Patient Not Home", "Patient Rescheduled", "Order Cancelled", "Others", "Patient Asked to Reschedule"];
866
+
867
+ /**
868
+ * Wall-clock formatting in an IANA zone, over `Intl` so it runs anywhere the mock does. AHA
869
+ * reports every event time as separate local date / time / zone fields, and our handler
870
+ * rebuilds the instant with `moment.tz(localString, zone)`.
871
+ */
872
+ /** Whether `zone` is an IANA time zone this runtime knows. */
873
+ declare const isTimeZone: (zone: string) => boolean;
874
+ type ZonedParts = {
875
+ /** `YYYY-MM-DD` */
876
+ date: string;
877
+ /** `HH:mm` */
878
+ time: string;
879
+ /** `HH:mm:ss` */
880
+ timeWithSeconds: string;
881
+ };
882
+ /** The local date and time of `epochMs` in `zone`. */
883
+ declare const zonedParts: (epochMs: number, zone: string) => ZonedParts;
884
+ /** The instant a local `YYYY-MM-DD` + `HH:mm[:ss]` names in `zone` (the earlier one in a DST fold). */
885
+ declare const zonedToEpoch: (date: string, time: string, zone: string) => number | undefined;
886
+
887
+ /** Where our backend receives AHA webhooks. */
888
+ declare const WEBHOOK_PATH = "/bloodwork/aha-webhook";
889
+ /**
890
+ * Every named AHA misbehaviour our consumers branch on, switched on with
891
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it).
892
+ */
893
+ declare const AHA_PRESETS: Record<string, FaultPreset>;
894
+ type WebhookDelivery = {
895
+ retryDelaysMs?: readonly number[];
896
+ fetch?: (request: Request) => Promise<Response>;
897
+ };
898
+ type AhaRuntimeOptions = {
899
+ sqlite?: SqliteClient;
900
+ clock?: Clock;
901
+ seed?: number | string;
902
+ adminKey?: string;
903
+ onLog?: (entry: RequestLog) => void;
904
+ settings?: Partial<Settings>;
905
+ /**
906
+ * Where webhooks go (`POST /bloodwork/aha-webhook`); `secret` is `AHA_WEBHOOK_SECRET`,
907
+ * sent as `Authorization: Token <secret>`.
908
+ */
909
+ webhooks?: Omit<WebhookEndpoint, "id"> & WebhookDelivery;
910
+ /** Wall clock for `X-TIMESTAMP` tolerance. Default `Date.now`. */
911
+ wallClock?: () => number;
912
+ /** Run `autoSchedule` on this real-time interval (ms). The served mock uses 100 ms. */
913
+ tickMs?: number;
914
+ };
915
+ type AhaRuntime = ServiceRuntime<AhaAPI> & {
916
+ readonly webhooks: WebhookHub;
917
+ /** Stop the background ticker, if one runs. */
918
+ stop(): void;
919
+ };
920
+ /**
921
+ * The AHA mock with Mockingbird's full service contract: `/health`, `/__admin/*`, namespaces
922
+ * by header, by `/ns/<name>` prefix on `AHA_API_URL`, or by API key
923
+ * (`PUT /__admin/credentials {"credentials": {"<AHA_API_KEY>": "<namespace>"}}`), clock
924
+ * control, fault presets, webhooks and a request journal.
925
+ */
926
+ declare const createRuntime: (options?: AhaRuntimeOptions) => AhaRuntime;
927
+
928
+ declare const AHA_NAMESPACE = "aha";
929
+ /**
930
+ * The webhook body AHA posts to `POST /bloodwork/aha-webhook` (`AhaWebhookGenericDto`).
931
+ * `status` and `partnerOrderId` are always present; the rest depend on the status.
932
+ * `scheduleServiceTime` / `scheduleServiceTimeZone` are not in the DTO, but our handler
933
+ * requires them on `Scheduled` and `Rescheduled`.
934
+ */
935
+ type AhaWebhook = {
936
+ status: string;
937
+ partnerOrderId: string;
938
+ ahaOrderId: string;
939
+ scheduleServiceTime?: string;
940
+ scheduleServiceTimeZone?: string;
941
+ scheduledServiceDate?: string;
942
+ scheduledServiceTime?: string;
943
+ scheduledServiceTimeZone?: string;
944
+ scheduleConfirmationDate?: string;
945
+ scheduleConfirmationTime?: string;
946
+ scheduleConfirmationTimeZone?: string;
947
+ checkInDate?: string;
948
+ checkInTime?: string;
949
+ checkInTimeZone?: string;
950
+ drawStatus?: string;
951
+ drawStatusDate?: string;
952
+ drawStatusTime?: string;
953
+ drawStatusTimeZone?: string;
954
+ dropOffDate?: string;
955
+ dropOffTime?: string;
956
+ dropOffTimeZone?: string;
957
+ };
958
+ type TransitionInput = {
959
+ /** A vendor order status (`Scheduled`, `Check Out`, …); case and `_` are forgiven. */
960
+ status: string;
961
+ /** Sent with `Check Out`; defaults to `Sample Collected` there. */
962
+ drawStatus?: string;
963
+ /** The appointment instant (ISO-8601 or epoch ms) for `Scheduled` / `Rescheduled`. */
964
+ scheduledAt?: string | number;
965
+ /** IANA zone for every local time in the webhook; defaults to the order's zone. */
966
+ timeZone?: string;
967
+ };
968
+ type AhaAPIOptions = APIOptions & {
969
+ /** Initial per-namespace settings (envelope, credentials, autoSchedule, …). */
970
+ settings?: Partial<Settings>;
971
+ /** Called for every emitted webhook; the runtime delivers it with `Authorization: Token …`. */
972
+ onWebhook?: (event: AhaWebhook) => void;
973
+ /** Wall clock for `X-TIMESTAMP` tolerance (the consumer signs with real time). Default `Date.now`. */
974
+ wallClock?: () => number;
975
+ };
976
+ /**
977
+ * Verify AHA partner authentication: HMAC mode (`X-API-KEY`, `X-TIMESTAMP`,
978
+ * `X-SIGNATURE` over `"<apiKey>:<path>:<timestamp>"`) or legacy `X-Geviti-Auth-Key`.
979
+ * Returns an error message, or `undefined` when the request is authentic.
980
+ */
981
+ declare const verifyAuth: (request: Request, path: string, settings: Settings, wallNow: number) => Promise<string | undefined>;
982
+ /** The credential a request carries (`X-API-KEY`, else `X-Geviti-Auth-Key`), for namespaces. */
983
+ declare const apiKeyCredential: (request: Request) => string | undefined;
984
+ /**
985
+ * Stateful mock of the AHA partner API.
986
+ *
987
+ * Orders start `Order Placed` and move only through admin transitions (or `autoSchedule`),
988
+ * each of which emits the webhook AHA would send, with every field our handler reads.
989
+ */
990
+ declare class AhaAPI implements FetchAPI$1 {
991
+ readonly app: Hono;
992
+ readonly sqlite: SqliteClient;
993
+ readonly state: AhaState;
994
+ private readonly service;
995
+ private readonly now;
996
+ private readonly wallClock;
997
+ private readonly onWebhook;
998
+ constructor(options?: AhaAPIOptions);
999
+ fetch(request: Request): Promise<Response>;
1000
+ reset(): Promise<void>;
1001
+ private iso;
1002
+ /** The success body in the namespace's envelope. */
1003
+ private envelope;
1004
+ private idempotent;
1005
+ private validate;
1006
+ private createOrder;
1007
+ private cancelOrder;
1008
+ /**
1009
+ * Move an order to a vendor status and emit the webhook with every field our handler reads.
1010
+ * Throws `RangeError` for a bad zone or appointment time.
1011
+ */
1012
+ transition(id: string, input: TransitionInput): {
1013
+ order: OrderRecord;
1014
+ webhook: AhaWebhook;
1015
+ } | undefined;
1016
+ /**
1017
+ * Emit `Scheduled` for every order whose `autoSchedule` delay has passed on the mock clock.
1018
+ * Runs before each vendor request, on `POST /__admin/tick`, and from the served ticker.
1019
+ */
1020
+ tick(): number;
1021
+ orders(): OrderRecord[];
1022
+ }
1023
+
1024
+ export { AHA_NAMESPACE, AHA_PRESETS, AhaAPI, DRAW_STATUSES, ORDER_STATUSES, WEBHOOK_PATH, apiKeyCredential, createRuntime, document, isTimeZone, operationIds, supportedOperationIds, verifyAuth, zonedParts, zonedToEpoch };
1025
+ export type { AhaAPIOptions, AhaRuntime, AhaRuntimeOptions, AhaWebhook, ApiCredential, AutoSchedule, FetchAPI$1 as FetchAPI, OperationId, OrderRecord, Settings, SqliteClient, SupportedOperationId, TransitionInput };