@crvouga/mockingbird-service-resend 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,1040 @@
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
+ /** A stable identifier for a point in a {@link Timeline}. */
326
+ type CheckpointId = string;
327
+ /** An immutable node in a timeline's checkpoint DAG. */
328
+ type Checkpoint<T> = Readonly<{
329
+ id: CheckpointId;
330
+ branch: string;
331
+ parent: CheckpointId | null;
332
+ /** Logical time supplied by the timeline's injected clock. */
333
+ at: number;
334
+ value: T;
335
+ }>;
336
+ type TimelineOptions = {
337
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
338
+ now?: () => number;
339
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
340
+ maxCheckpoints?: number;
341
+ /** Customize deterministic checkpoint IDs. */
342
+ id?: (sequence: number) => CheckpointId;
343
+ };
344
+ type CommitOptions = {
345
+ branch?: string;
346
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
347
+ parent?: CheckpointId | null;
348
+ };
349
+ type ForkOptions = {
350
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
351
+ from?: CheckpointId;
352
+ };
353
+ /**
354
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
355
+ * records, namespace images, or copy-on-write SQL engine snapshots.
356
+ *
357
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
358
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
359
+ * (the logical clock) is injected.
360
+ */
361
+ declare class Timeline<T> {
362
+ readonly maxCheckpoints: number;
363
+ private readonly now;
364
+ private readonly makeId;
365
+ private readonly nodes;
366
+ private readonly heads;
367
+ /** Unreferenced nodes in the exact order they became collectible. */
368
+ private readonly evictable;
369
+ /** Branch heads plus explicit retainers. Absent means zero. */
370
+ private readonly references;
371
+ private readonly explicitPins;
372
+ private sequence;
373
+ constructor(options?: TimelineOptions);
374
+ /** Capture a new immutable value and move `branch` to it. */
375
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
376
+ /** Create a branch pointer without copying its checkpoint value. */
377
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
378
+ /** Move a branch pointer to an existing checkpoint. */
379
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
380
+ get(id: CheckpointId): Checkpoint<T>;
381
+ head(branch?: string): Checkpoint<T> | undefined;
382
+ hasBranch(branch: string): boolean;
383
+ branches(): Readonly<Record<string, CheckpointId>>;
384
+ checkpoints(): readonly Checkpoint<T>[];
385
+ /** Number of retained checkpoints without allocating an array. */
386
+ get size(): number;
387
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
388
+ retain(id: CheckpointId): Checkpoint<T>;
389
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
390
+ release(id: CheckpointId): boolean;
391
+ deleteBranch(branch: string): boolean;
392
+ /**
393
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
394
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
395
+ * storage dependency, so a retained node remains usable after pruning.
396
+ */
397
+ gc(max?: number): CheckpointId[];
398
+ private collect;
399
+ private moveHead;
400
+ private addReference;
401
+ private removeReference;
402
+ private assertBranch;
403
+ }
404
+
405
+ /**
406
+ * Anything that can answer a Fetch `Request` with a `Response`.
407
+ *
408
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
409
+ * It is the only contract shared across the whole graph.
410
+ */
411
+ interface FetchAPI {
412
+ fetch(request: Request): Promise<Response>;
413
+ }
414
+
415
+ /**
416
+ * A point-in-time copy of everything a service namespace holds.
417
+ *
418
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
419
+ * is generic: any service gets per-test rollback without knowing its own schema.
420
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
421
+ */
422
+ type NamespaceSnapshot = {
423
+ namespace: string;
424
+ records: {
425
+ collection: string;
426
+ id: string;
427
+ seq: number;
428
+ value: string;
429
+ }[];
430
+ sequences: {
431
+ name: string;
432
+ kind: string;
433
+ value: number;
434
+ }[];
435
+ };
436
+
437
+ type WebhookEndpoint = {
438
+ /** Stable id; generated when omitted. */
439
+ id?: string;
440
+ url: string;
441
+ secret?: string;
442
+ /** Event types to deliver; omit or include `"*"` for every type. */
443
+ events?: string[];
444
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
445
+ tags?: Record<string, string>;
446
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
447
+ signUrl?: string;
448
+ headers?: Record<string, string>;
449
+ };
450
+ type WebhookMessage = {
451
+ id: string;
452
+ namespace: string;
453
+ type: string;
454
+ body: string;
455
+ contentType: string;
456
+ tags: Record<string, string>;
457
+ headers?: Record<string, string>;
458
+ /** Wall-clock ISO-8601 time of publication. */
459
+ publishedAt: string;
460
+ };
461
+ type WebhookAttempt = {
462
+ attempt: number;
463
+ at: string;
464
+ status: number | null;
465
+ error: string | null;
466
+ durationMs: number;
467
+ /** Exact receiver response body, when one was returned. */
468
+ responseBody?: string | null;
469
+ };
470
+ type WebhookDelivery = {
471
+ id: string;
472
+ messageId: string;
473
+ namespace: string;
474
+ type: string;
475
+ endpointId: string;
476
+ url: string;
477
+ state: "pending" | "delivered" | "failed" | "dropped";
478
+ attempts: WebhookAttempt[];
479
+ };
480
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
481
+ type WebhookFault = {
482
+ mode: "duplicate" | "reorder" | "drop";
483
+ /** Messages affected; default 1. */
484
+ count?: number;
485
+ };
486
+ type PublishInput = {
487
+ namespace: string;
488
+ type: string;
489
+ /** Exact body; objects are JSON-encoded. */
490
+ body: string | Record<string, unknown> | unknown[];
491
+ /** Default `application/json`, or form-encoded when `form` is given. */
492
+ contentType?: string;
493
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
494
+ form?: Record<string, string>;
495
+ tags?: Record<string, string>;
496
+ /** Message-specific delivery headers, captured as part of durable message state. */
497
+ headers?: Record<string, string>;
498
+ /** Message id; generated when omitted. */
499
+ id?: string;
500
+ };
501
+ type WebhookHub = {
502
+ publish(input: PublishInput): WebhookMessage;
503
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
504
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
505
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
506
+ endpoints(namespace: string): WebhookEndpoint[];
507
+ messages(namespace?: string): WebhookMessage[];
508
+ deliveries(namespace?: string): WebhookDelivery[];
509
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
510
+ /** Run every pending retry (and release held reordered messages) now. */
511
+ flush(): Promise<void>;
512
+ /** Resolve once nothing is in flight. */
513
+ idle(): Promise<void>;
514
+ fault(namespace: string, fault: WebhookFault): void;
515
+ clear(namespace?: string): void;
516
+ };
517
+
518
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
519
+ type ServiceInstance = FetchAPI & {
520
+ reset(): Promise<void>;
521
+ };
522
+ type ServiceTimelineState = Readonly<{
523
+ snapshot: NamespaceSnapshot;
524
+ clock: Readonly<ReturnType<Clock["state"]>>;
525
+ rngState: number;
526
+ }>;
527
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
528
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
529
+ readonly name: string;
530
+ readonly sqlite: SqliteClient$1;
531
+ readonly clock: Clock;
532
+ readonly faults: FaultRegistry;
533
+ readonly metrics: Metrics;
534
+ readonly journal: Journal;
535
+ readonly rng: Rng;
536
+ readonly credentials: CredentialRegistry;
537
+ /** The webhook hub, when the service has outbound webhooks. */
538
+ readonly webhooks: WebhookHub | undefined;
539
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
540
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
541
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
542
+ instance(namespace?: string): T;
543
+ /** Public names of every namespace created so far. */
544
+ namespaces(): string[];
545
+ /** Reset one namespace, or every namespace with `"*"`. */
546
+ reset(namespace?: string): Promise<void>;
547
+ snapshot(namespace?: string): NamespaceSnapshot;
548
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
549
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
550
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
551
+ /** Create an isolated branch, optionally from a historical checkpoint. */
552
+ branch(name: string, options?: {
553
+ namespace?: string;
554
+ at?: string;
555
+ }): ServiceCheckpoint;
556
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
557
+ checkout(checkpoint: string, options?: {
558
+ namespace?: string;
559
+ branch?: string;
560
+ }): void;
561
+ /** Inspect the retained history for a namespace. */
562
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
563
+ };
564
+
565
+ /**
566
+ * What a comms vendor "sent" (an SMS, an email, a Slack post), kept per namespace so a
567
+ * suite can assert on it and read codes and links out of it. Stored in SQLite beside the
568
+ * service's other records, so reset, snapshot and restore cover it.
569
+ */
570
+ type OutboxItem = {
571
+ id: string;
572
+ /** Recipient(s): a phone number, email address, channel or webhook path. */
573
+ to: string | string[];
574
+ /** ISO-8601 on the mock clock. */
575
+ createdAt: string;
576
+ };
577
+ type OutboxQuery = {
578
+ /** Case-insensitive match on any recipient. */
579
+ to?: string;
580
+ /** Only items at or after this instant (epoch ms). */
581
+ since?: number;
582
+ /** Extra filter over the item. */
583
+ where?: (item: Record<string, unknown>) => boolean;
584
+ limit?: number;
585
+ };
586
+ declare class OutboxStore<T extends OutboxItem = OutboxItem> {
587
+ private readonly items;
588
+ constructor(sqlite: SqliteClient$1, namespace: string, name?: string);
589
+ record(item: T): T;
590
+ get(id: string): T | undefined;
591
+ update(id: string, item: T): void;
592
+ /** Oldest first, so a suite reads messages in the order they were sent. */
593
+ list(query?: OutboxQuery): T[];
594
+ }
595
+
596
+ /** Options every provider constructor accepts. */
597
+ type APIOptions = {
598
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
599
+ sqlite?: SqliteClient$1;
600
+ /** Clock used for `created`-style fields. Default `Date.now`. */
601
+ now?: () => number;
602
+ /**
603
+ * Storage namespace for this instance's records. Instances sharing one SQLite
604
+ * client stay isolated when their namespaces differ. Defaults to the service name.
605
+ */
606
+ namespace?: string;
607
+ };
608
+
609
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
610
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
611
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
612
+ type SqliteRunResult = {
613
+ changes: number;
614
+ lastInsertRowid: number | bigint;
615
+ };
616
+ /**
617
+ * Prepared statement bound to a {@link SqliteClient}.
618
+ *
619
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
620
+ */
621
+ interface SqliteStatement {
622
+ run(...params: SqliteValue[]): SqliteRunResult;
623
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
624
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
625
+ }
626
+ /**
627
+ * Sync SQLite client port owned by Mockingbird.
628
+ *
629
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
630
+ * `bun:sqlite` instances all work when they expose this surface.
631
+ */
632
+ interface SqliteClient {
633
+ exec(sql: string): void;
634
+ prepare(sql: string): SqliteStatement;
635
+ transaction<T>(fn: () => T): T;
636
+ }
637
+
638
+ /**
639
+ * One email the app "sent" (`POST /emails`): what `GET /__admin/outbox` returns. `to`, `cc` and
640
+ * `bcc` hold bare lower-cased addresses (so `?to=` matches `Name <a@b.co>` recipients);
641
+ * `toHeader` keeps them as sent. Attachments keep metadata only.
642
+ */
643
+ type SentEmail = {
644
+ id: string;
645
+ from: string;
646
+ to: string[];
647
+ toHeader: string[];
648
+ cc: string[];
649
+ bcc: string[];
650
+ replyTo: string[];
651
+ subject: string;
652
+ html: string | null;
653
+ text: string | null;
654
+ tags: {
655
+ name: string;
656
+ value: string;
657
+ }[];
658
+ headers: Record<string, string>;
659
+ attachments: {
660
+ filename: string;
661
+ contentType: string | null;
662
+ size: number;
663
+ }[];
664
+ idempotencyKey: string | null;
665
+ scheduledAt: string | null;
666
+ createdAt: string;
667
+ };
668
+ type ReceivedAttachmentRecord = {
669
+ id: string;
670
+ filename: string;
671
+ content_type: string;
672
+ content_disposition: string | null;
673
+ content_id: string | null;
674
+ size: number;
675
+ /** Base64 bytes, served by the download URL. */
676
+ content: string;
677
+ };
678
+ /** One inbound email (`POST /__admin/inbound`), as `GET /emails/receiving/{id}` serves it. */
679
+ type ReceivedEmail = {
680
+ id: string;
681
+ from: string;
682
+ to: string[];
683
+ cc: string[];
684
+ bcc: string[];
685
+ replyTo: string[];
686
+ subject: string | null;
687
+ html: string | null;
688
+ text: string | null;
689
+ headers: Record<string, string>;
690
+ messageId: string;
691
+ attachments: ReceivedAttachmentRecord[];
692
+ createdAt: string;
693
+ };
694
+ declare class ResendState {
695
+ readonly outbox: OutboxStore<SentEmail>;
696
+ readonly received: Collection<ReceivedEmail>;
697
+ /** Attachment id → received email id, for the unauthenticated download URL. */
698
+ readonly attachmentIndex: Collection<{
699
+ emailId: string;
700
+ }>;
701
+ readonly idempotency: IdempotencyStore;
702
+ private readonly ids;
703
+ constructor(sqlite: SqliteClient, namespace: string);
704
+ /** A UUID-shaped id, deterministic for a given history (Resend ids are UUIDs). */
705
+ nextId(kind: "email" | "received" | "attachment"): string;
706
+ }
707
+
708
+ /**
709
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
710
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
711
+ */
712
+ type JsonPrimitive = string | number | boolean | null;
713
+ type JsonValue = JsonPrimitive | JsonValue[] | {
714
+ [key: string]: JsonValue;
715
+ };
716
+ type ReferenceObject = {
717
+ $ref: string;
718
+ description?: string;
719
+ summary?: string;
720
+ };
721
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
722
+ type SchemaObject = {
723
+ $ref?: string;
724
+ type?: SchemaType | SchemaType[];
725
+ title?: string;
726
+ description?: string;
727
+ format?: string;
728
+ enum?: JsonValue[];
729
+ const?: JsonValue;
730
+ default?: JsonValue;
731
+ example?: JsonValue;
732
+ examples?: JsonValue[];
733
+ nullable?: boolean;
734
+ deprecated?: boolean;
735
+ readOnly?: boolean;
736
+ writeOnly?: boolean;
737
+ minimum?: number;
738
+ maximum?: number;
739
+ exclusiveMinimum?: number;
740
+ exclusiveMaximum?: number;
741
+ multipleOf?: number;
742
+ minLength?: number;
743
+ maxLength?: number;
744
+ pattern?: string;
745
+ minItems?: number;
746
+ maxItems?: number;
747
+ uniqueItems?: boolean;
748
+ items?: SchemaObject;
749
+ prefixItems?: SchemaObject[];
750
+ minProperties?: number;
751
+ maxProperties?: number;
752
+ required?: string[];
753
+ properties?: Record<string, SchemaObject>;
754
+ additionalProperties?: boolean | SchemaObject;
755
+ propertyNames?: SchemaObject;
756
+ oneOf?: SchemaObject[];
757
+ anyOf?: SchemaObject[];
758
+ allOf?: SchemaObject[];
759
+ not?: SchemaObject;
760
+ discriminator?: {
761
+ propertyName: string;
762
+ mapping?: Record<string, string>;
763
+ };
764
+ [extension: `x-${string}`]: unknown;
765
+ };
766
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
767
+ type ParameterObject = {
768
+ name: string;
769
+ in: ParameterLocation;
770
+ description?: string;
771
+ required?: boolean;
772
+ deprecated?: boolean;
773
+ style?: string;
774
+ explode?: boolean;
775
+ schema?: SchemaObject;
776
+ content?: Record<string, MediaTypeObject>;
777
+ example?: JsonValue;
778
+ [extension: `x-${string}`]: unknown;
779
+ };
780
+ type MediaTypeObject = {
781
+ schema?: SchemaObject;
782
+ example?: JsonValue;
783
+ examples?: Record<string, unknown>;
784
+ encoding?: Record<string, unknown>;
785
+ [extension: `x-${string}`]: unknown;
786
+ };
787
+ type RequestBodyObject = {
788
+ description?: string;
789
+ required?: boolean;
790
+ content: Record<string, MediaTypeObject>;
791
+ [extension: `x-${string}`]: unknown;
792
+ };
793
+ type HeaderObject = {
794
+ description?: string;
795
+ required?: boolean;
796
+ schema?: SchemaObject;
797
+ [extension: `x-${string}`]: unknown;
798
+ };
799
+ type ResponseObject = {
800
+ description: string;
801
+ headers?: Record<string, HeaderObject | ReferenceObject>;
802
+ content?: Record<string, MediaTypeObject>;
803
+ [extension: `x-${string}`]: unknown;
804
+ };
805
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
806
+ type SecurityRequirementObject = Record<string, string[]>;
807
+ type OperationObject = {
808
+ operationId?: string;
809
+ summary?: string;
810
+ description?: string;
811
+ tags?: string[];
812
+ deprecated?: boolean;
813
+ parameters?: Array<ParameterObject | ReferenceObject>;
814
+ requestBody?: RequestBodyObject | ReferenceObject;
815
+ responses: ResponsesObject;
816
+ security?: SecurityRequirementObject[];
817
+ [extension: `x-${string}`]: unknown;
818
+ };
819
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
820
+ type HttpMethod = (typeof HTTP_METHODS)[number];
821
+ type PathItemObject = {
822
+ summary?: string;
823
+ description?: string;
824
+ parameters?: Array<ParameterObject | ReferenceObject>;
825
+ [extension: `x-${string}`]: unknown;
826
+ } & Partial<Record<HttpMethod, OperationObject>>;
827
+ type SecuritySchemeObject = {
828
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
829
+ description?: string;
830
+ name?: string;
831
+ in?: ParameterLocation;
832
+ scheme?: string;
833
+ bearerFormat?: string;
834
+ flows?: Record<string, unknown>;
835
+ openIdConnectUrl?: string;
836
+ [extension: `x-${string}`]: unknown;
837
+ };
838
+ type ComponentsObject = {
839
+ schemas?: Record<string, SchemaObject>;
840
+ responses?: Record<string, ResponseObject>;
841
+ parameters?: Record<string, ParameterObject>;
842
+ requestBodies?: Record<string, RequestBodyObject>;
843
+ headers?: Record<string, HeaderObject>;
844
+ securitySchemes?: Record<string, SecuritySchemeObject>;
845
+ [extension: `x-${string}`]: unknown;
846
+ };
847
+ type ServerObject = {
848
+ url: string;
849
+ description?: string;
850
+ variables?: Record<string, unknown>;
851
+ [extension: `x-${string}`]: unknown;
852
+ };
853
+ type InfoObject = {
854
+ title: string;
855
+ version: string;
856
+ description?: string;
857
+ [extension: `x-${string}`]: unknown;
858
+ };
859
+ type OpenAPIDocument = {
860
+ openapi: string;
861
+ info: InfoObject;
862
+ servers?: ServerObject[];
863
+ paths: Record<string, PathItemObject>;
864
+ components?: ComponentsObject;
865
+ security?: SecurityRequirementObject[];
866
+ tags?: Array<{
867
+ name: string;
868
+ description?: string;
869
+ }>;
870
+ [extension: `x-${string}`]: unknown;
871
+ };
872
+
873
+ declare const document: OpenAPIDocument;
874
+ type OperationId = "SendEmail" | "GetEmail" | "GetReceivedEmail" | "ListReceivedEmailAttachments" | "DownloadReceivedAttachment";
875
+ type SupportedOperationId = "SendEmail" | "GetEmail" | "GetReceivedEmail" | "ListReceivedEmailAttachments" | "DownloadReceivedAttachment";
876
+ declare const operationIds: readonly ["SendEmail", "GetEmail", "GetReceivedEmail", "ListReceivedEmailAttachments", "DownloadReceivedAttachment"];
877
+ declare const supportedOperationIds: readonly ["SendEmail", "GetEmail", "GetReceivedEmail", "ListReceivedEmailAttachments", "DownloadReceivedAttachment"];
878
+
879
+ /**
880
+ * Every named Resend misbehaviour our consumer branches on, switched on with
881
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it). The SDK turns each
882
+ * into its `{data: null, error}` result (it never throws).
883
+ */
884
+ declare const RESEND_PRESETS: Record<string, FaultPreset>;
885
+ /** Where sent emails are copied: the Mailosaur mock's `POST /__admin/ingest`. */
886
+ type ForwardTarget = {
887
+ /** The Mailosaur mock's base URL, e.g. `http://127.0.0.1:8793`. */
888
+ url: string;
889
+ /** Its `x-mockingbird-admin-key`, when it has one. */
890
+ adminKey?: string;
891
+ /** Give up on a forward after this long (the send still succeeds). Default 2000 ms. */
892
+ timeoutMs?: number;
893
+ fetch?: (request: Request) => Promise<Response>;
894
+ };
895
+ type ForwardStats = {
896
+ forwarded: number;
897
+ failed: number;
898
+ lastError: string | null;
899
+ };
900
+ /**
901
+ * Copy one sent email into the Mailosaur mock's inbox under the same namespace name, so a test
902
+ * reads codes and links through the Mailosaur SDK. Resolves `true` when the inbox took it.
903
+ */
904
+ declare const forwardToInbox: (target: ForwardTarget, email: SentEmail, namespace: string) => Promise<boolean>;
905
+ type ResendRuntimeOptions = {
906
+ sqlite?: SqliteClient;
907
+ clock?: Clock;
908
+ seed?: number | string;
909
+ adminKey?: string;
910
+ onLog?: (entry: RequestLog) => void;
911
+ /**
912
+ * Where `email.received` webhooks go (`POST /messaging/inbound/email`), signed with the
913
+ * endpoint's `whsec_…` secret the Svix way (`svix-id`, `svix-timestamp`, `svix-signature`).
914
+ */
915
+ webhooks?: Omit<WebhookEndpoint, "id"> & {
916
+ retryDelaysMs?: readonly number[];
917
+ fetch?: (request: Request) => Promise<Response>;
918
+ };
919
+ /** Copy every accepted send into a Mailosaur mock (`--forward-to-inbox`). */
920
+ forwardToInbox?: ForwardTarget;
921
+ };
922
+ type ResendRuntime = ServiceRuntime<ResendAPI> & {
923
+ readonly webhooks: WebhookHub;
924
+ /** Forwarding counters, when `forwardToInbox` is set. */
925
+ forwarding(): ForwardStats;
926
+ };
927
+ /**
928
+ * The Resend mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
929
+ * namespaces by header, by `/ns/<name>` path prefix, or by API key
930
+ * (`PUT /__admin/credentials {"credentials": {"<RESEND_API_KEY>": "<namespace>"}}`),
931
+ * clock control, fault presets, an outbox, Svix-signed inbound webhooks and a request journal.
932
+ */
933
+ declare const createRuntime: (options?: ResendRuntimeOptions) => ResendRuntime;
934
+
935
+ declare const RESEND_NAMESPACE = "resend";
936
+ /** How long a received attachment's `download_url` is advertised to live. */
937
+ declare const DOWNLOAD_URL_TTL_MS = 3600000;
938
+ /** The `email.received` webhook body (what our `POST /messaging/inbound/email` parses). */
939
+ type EmailReceivedEvent = {
940
+ type: "email.received";
941
+ created_at: string;
942
+ data: {
943
+ email_id: string;
944
+ created_at: string;
945
+ from: string;
946
+ to: string[];
947
+ cc: string[];
948
+ bcc: string[];
949
+ subject: string | null;
950
+ message_id: string;
951
+ attachments: {
952
+ id: string;
953
+ filename: string;
954
+ content_type: string;
955
+ content_disposition: string | null;
956
+ content_id: string | null;
957
+ size?: number;
958
+ download_url?: string;
959
+ }[];
960
+ text?: string | null;
961
+ html?: string | null;
962
+ headers?: {
963
+ name: string;
964
+ value: string;
965
+ }[];
966
+ };
967
+ };
968
+ /** What `POST /__admin/inbound` accepts: an email arriving at one of the app's addresses. */
969
+ type InboundInput = {
970
+ from: string;
971
+ to: string | string[];
972
+ cc?: string | string[];
973
+ bcc?: string | string[];
974
+ replyTo?: string | string[];
975
+ subject?: string | null;
976
+ text?: string | null;
977
+ html?: string | null;
978
+ headers?: Record<string, string>;
979
+ messageId?: string;
980
+ attachments?: {
981
+ filename: string;
982
+ /** Base64 bytes. */
983
+ content: string;
984
+ contentType?: string;
985
+ contentDisposition?: string | null;
986
+ contentId?: string | null;
987
+ }[];
988
+ /**
989
+ * Put `text`, `html`, `headers` and each attachment's `size` / `download_url` in the webhook
990
+ * body. Default `false`, as Resend does: the receiver then hydrates them through
991
+ * `GET /emails/receiving/{id}` and `…/attachments`.
992
+ */
993
+ inline?: boolean;
994
+ };
995
+ type ResendAPIOptions = APIOptions & {
996
+ /** The public namespace name, for `/ns/<name>` download URLs. Default: the default namespace. */
997
+ publicNamespace?: string;
998
+ /** Called after every accepted send (not replays); awaited before the response. */
999
+ onSent?: (email: SentEmail) => Promise<void> | void;
1000
+ };
1001
+ /** `Ada <ada@x.co>` → `ada@x.co` (lower-cased), as the outbox's `?to=` compares. */
1002
+ declare const bareAddress: (value: string) => string;
1003
+ /**
1004
+ * Stateful mock of the Resend email API: sends land in an outbox (read with
1005
+ * `GET /__admin/outbox`), `Idempotency-Key` replays return the first send's id, and inbound
1006
+ * emails (`POST /__admin/inbound`) are served by the received-email endpoints.
1007
+ */
1008
+ declare class ResendAPI implements FetchAPI$1 {
1009
+ readonly app: Hono;
1010
+ readonly sqlite: SqliteClient;
1011
+ readonly state: ResendState;
1012
+ private readonly service;
1013
+ private readonly now;
1014
+ private readonly publicNamespace;
1015
+ private readonly onSent;
1016
+ constructor(options?: ResendAPIOptions);
1017
+ fetch(request: Request): Promise<Response>;
1018
+ reset(): Promise<void>;
1019
+ /** Every sent email, oldest first. */
1020
+ sent(): SentEmail[];
1021
+ private iso;
1022
+ private send;
1023
+ private create;
1024
+ private getEmail;
1025
+ /** Store an inbound email and build the `email.received` event for it. */
1026
+ receive(input: InboundInput, origin: string): {
1027
+ email: ReceivedEmail;
1028
+ event: EmailReceivedEvent;
1029
+ };
1030
+ /** Every received email, oldest first. */
1031
+ inbound(): ReceivedEmail[];
1032
+ private attachmentMeta;
1033
+ private downloadUrl;
1034
+ private getReceived;
1035
+ private listAttachments;
1036
+ private download;
1037
+ }
1038
+
1039
+ export { DOWNLOAD_URL_TTL_MS, RESEND_NAMESPACE, RESEND_PRESETS, ResendAPI, bareAddress, createRuntime, document, forwardToInbox, operationIds, supportedOperationIds };
1040
+ export type { EmailReceivedEvent, FetchAPI$1 as FetchAPI, InboundInput, OperationId, ReceivedAttachmentRecord, ReceivedEmail, ResendAPIOptions, ResendRuntime, ResendRuntimeOptions, SentEmail, SqliteClient, SupportedOperationId };