@crvouga/mockingbird-service-paddle 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,1836 @@
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
+ /** A stable identifier for a point in a {@link Timeline}. */
174
+ type CheckpointId$1 = string;
175
+ /** An immutable node in a timeline's checkpoint DAG. */
176
+ type Checkpoint$1<T> = Readonly<{
177
+ id: CheckpointId$1;
178
+ branch: string;
179
+ parent: CheckpointId$1 | null;
180
+ /** Logical time supplied by the timeline's injected clock. */
181
+ at: number;
182
+ value: T;
183
+ }>;
184
+ type TimelineOptions$1 = {
185
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
186
+ now?: () => number;
187
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
188
+ maxCheckpoints?: number;
189
+ /** Customize deterministic checkpoint IDs. */
190
+ id?: (sequence: number) => CheckpointId$1;
191
+ };
192
+ type CommitOptions$1 = {
193
+ branch?: string;
194
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
195
+ parent?: CheckpointId$1 | null;
196
+ };
197
+ type ForkOptions$1 = {
198
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
199
+ from?: CheckpointId$1;
200
+ };
201
+ /**
202
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
203
+ * records, namespace images, or copy-on-write SQL engine snapshots.
204
+ *
205
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
206
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
207
+ * (the logical clock) is injected.
208
+ */
209
+ declare class Timeline$1<T> {
210
+ readonly maxCheckpoints: number;
211
+ private readonly now;
212
+ private readonly makeId;
213
+ private readonly nodes;
214
+ private readonly heads;
215
+ /** Unreferenced nodes in the exact order they became collectible. */
216
+ private readonly evictable;
217
+ /** Branch heads plus explicit retainers. Absent means zero. */
218
+ private readonly references;
219
+ private readonly explicitPins;
220
+ private sequence;
221
+ constructor(options?: TimelineOptions$1);
222
+ /** Capture a new immutable value and move `branch` to it. */
223
+ commit(value: T, options?: CommitOptions$1): Checkpoint$1<T>;
224
+ /** Create a branch pointer without copying its checkpoint value. */
225
+ fork(branch: string, options?: ForkOptions$1): Checkpoint$1<T> | undefined;
226
+ /** Move a branch pointer to an existing checkpoint. */
227
+ checkout(branch: string, id: CheckpointId$1): Checkpoint$1<T>;
228
+ get(id: CheckpointId$1): Checkpoint$1<T>;
229
+ head(branch?: string): Checkpoint$1<T> | undefined;
230
+ hasBranch(branch: string): boolean;
231
+ branches(): Readonly<Record<string, CheckpointId$1>>;
232
+ checkpoints(): readonly Checkpoint$1<T>[];
233
+ /** Number of retained checkpoints without allocating an array. */
234
+ get size(): number;
235
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
236
+ retain(id: CheckpointId$1): Checkpoint$1<T>;
237
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
238
+ release(id: CheckpointId$1): boolean;
239
+ deleteBranch(branch: string): boolean;
240
+ /**
241
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
242
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
243
+ * storage dependency, so a retained node remains usable after pruning.
244
+ */
245
+ gc(max?: number): CheckpointId$1[];
246
+ private collect;
247
+ private moveHead;
248
+ private addReference;
249
+ private removeReference;
250
+ private assertBranch;
251
+ }
252
+
253
+ /**
254
+ * Anything that can answer a Fetch `Request` with a `Response`.
255
+ *
256
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
257
+ * It is the only contract shared across the whole graph.
258
+ */
259
+ interface FetchAPI$2 {
260
+ fetch(request: Request): Promise<Response>;
261
+ }
262
+
263
+ /**
264
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
265
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
266
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
267
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
268
+ */
269
+ type BodyIssue$1 = {
270
+ path: string;
271
+ message: string;
272
+ kind?: "media_type" | "syntax" | "required" | "schema";
273
+ };
274
+
275
+ /**
276
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
277
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
278
+ */
279
+ type RejectedRequest$1 = {
280
+ /** The raw `content-type` header, or `null` when the request sent none. */
281
+ contentType: string | null;
282
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
283
+ bodyBytes: number | null;
284
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
285
+ transferEncoding: string | null;
286
+ };
287
+ /** One handled request, as the structured log sees it. */
288
+ type RequestLog$1 = {
289
+ service: string;
290
+ namespace: string;
291
+ operationId: string | undefined;
292
+ method: string;
293
+ path: string;
294
+ status: number;
295
+ durationMs: number;
296
+ /** True when the path matched no operation in the contract. */
297
+ unmatched: boolean;
298
+ /** Set when a fault rule produced the response. */
299
+ faultId?: string;
300
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
301
+ ids?: Record<string, string>;
302
+ /** Set when the service created a resource the request referred to but that did not exist. */
303
+ adopted?: boolean;
304
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
305
+ request?: RejectedRequest$1;
306
+ /** The validation issues behind a rejection, when the service found any. */
307
+ issues?: BodyIssue$1[];
308
+ };
309
+ type MetricsReport$1 = {
310
+ requests: number;
311
+ /** Counts keyed `<operationId> <status>`. */
312
+ byOperation: Record<string, number>;
313
+ /**
314
+ * Paths that matched no operation, most frequent first.
315
+ *
316
+ * This is the early-warning signal: a consumer calling something the mock does
317
+ * not implement shows up here as a count, before it fails a suite as a 404.
318
+ */
319
+ unmatched: {
320
+ method: string;
321
+ path: string;
322
+ count: number;
323
+ }[];
324
+ faults: number;
325
+ totalDurationMs: number;
326
+ };
327
+ type Metrics$1 = {
328
+ record(entry: RequestLog$1): void;
329
+ report(): MetricsReport$1;
330
+ reset(): void;
331
+ };
332
+
333
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
334
+ type JournalEntry$1 = RequestLog$1 & {
335
+ at: string;
336
+ };
337
+ type JournalQuery$1 = {
338
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
339
+ namespace?: string;
340
+ operationId?: string;
341
+ status?: number;
342
+ /** Only entries at or after this instant (epoch ms). */
343
+ since?: number;
344
+ /** At most this many, the most recent kept. */
345
+ limit?: number;
346
+ };
347
+ type Journal$1 = {
348
+ readonly size: number;
349
+ record(entry: JournalEntry$1): void;
350
+ list(query?: JournalQuery$1): JournalEntry$1[];
351
+ /** Forget one namespace's entries, or every namespace's. */
352
+ clear(namespace?: string): void;
353
+ };
354
+
355
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
356
+ type CredentialRegistry$1 = {
357
+ set(credential: string, namespace: string): void;
358
+ get(credential: string): string | undefined;
359
+ remove(credential: string): boolean;
360
+ clear(): void;
361
+ entries(): {
362
+ credential: string;
363
+ namespace: string;
364
+ }[];
365
+ };
366
+
367
+ /**
368
+ * A point-in-time copy of everything a service namespace holds.
369
+ *
370
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
371
+ * is generic: any service gets per-test rollback without knowing its own schema.
372
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
373
+ */
374
+ type NamespaceSnapshot$1 = {
375
+ namespace: string;
376
+ records: {
377
+ collection: string;
378
+ id: string;
379
+ seq: number;
380
+ value: string;
381
+ }[];
382
+ sequences: {
383
+ name: string;
384
+ kind: string;
385
+ value: number;
386
+ }[];
387
+ };
388
+
389
+ declare const STATE_FIELD_KINDS$1: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
390
+ type StateFieldKind$1 = (typeof STATE_FIELD_KINDS$1)[number];
391
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
392
+ type StateMeta$1 = Readonly<Record<string, string | number | boolean | null>>;
393
+ type StateField$1 = {
394
+ name: string;
395
+ kind: StateFieldKind$1;
396
+ optional: boolean;
397
+ description?: string;
398
+ /** One level of nested object fields. */
399
+ fields?: StateField$1[];
400
+ meta?: StateMeta$1;
401
+ };
402
+ type StateCollectionView$1 = {
403
+ name: string;
404
+ label: string;
405
+ description?: string;
406
+ count: number;
407
+ /** `mixed` when a declaration and stored rows both contribute fields. */
408
+ source: "declared" | "inferred" | "mixed";
409
+ fields: StateField$1[];
410
+ meta?: StateMeta$1;
411
+ };
412
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
413
+ type StateView$1 = {
414
+ namespace: string;
415
+ storageNamespace: string;
416
+ collections: StateCollectionView$1[];
417
+ };
418
+
419
+ type WebhookEndpoint$1 = {
420
+ /** Stable id; generated when omitted. */
421
+ id?: string;
422
+ url: string;
423
+ secret?: string;
424
+ /** Event types to deliver; omit or include `"*"` for every type. */
425
+ events?: string[];
426
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
427
+ tags?: Record<string, string>;
428
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
429
+ signUrl?: string;
430
+ headers?: Record<string, string>;
431
+ };
432
+ type WebhookMessage$1 = {
433
+ id: string;
434
+ namespace: string;
435
+ type: string;
436
+ body: string;
437
+ contentType: string;
438
+ tags: Record<string, string>;
439
+ headers?: Record<string, string>;
440
+ /** Wall-clock ISO-8601 time of publication. */
441
+ publishedAt: string;
442
+ };
443
+ type WebhookAttempt$1 = {
444
+ attempt: number;
445
+ at: string;
446
+ status: number | null;
447
+ error: string | null;
448
+ durationMs: number;
449
+ /** Exact receiver response body, when one was returned. */
450
+ responseBody?: string | null;
451
+ };
452
+ type WebhookDelivery$1 = {
453
+ id: string;
454
+ messageId: string;
455
+ namespace: string;
456
+ type: string;
457
+ endpointId: string;
458
+ url: string;
459
+ state: "pending" | "delivered" | "failed" | "dropped";
460
+ attempts: WebhookAttempt$1[];
461
+ };
462
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
463
+ type WebhookFault$1 = {
464
+ mode: "duplicate" | "reorder" | "drop";
465
+ /** Messages affected; default 1. */
466
+ count?: number;
467
+ };
468
+ type PublishInput$1 = {
469
+ namespace: string;
470
+ type: string;
471
+ /** Exact body; objects are JSON-encoded. */
472
+ body: string | Record<string, unknown> | unknown[];
473
+ /** Default `application/json`, or form-encoded when `form` is given. */
474
+ contentType?: string;
475
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
476
+ form?: Record<string, string>;
477
+ tags?: Record<string, string>;
478
+ /** Message-specific delivery headers, captured as part of durable message state. */
479
+ headers?: Record<string, string>;
480
+ /** Message id; generated when omitted. */
481
+ id?: string;
482
+ };
483
+ type WebhookHub$1 = {
484
+ publish(input: PublishInput$1): WebhookMessage$1;
485
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
486
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint$1[]): WebhookEndpoint$1[];
487
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
488
+ endpoints(namespace: string): WebhookEndpoint$1[];
489
+ messages(namespace?: string): WebhookMessage$1[];
490
+ deliveries(namespace?: string): WebhookDelivery$1[];
491
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
492
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
493
+ flush(): Promise<void>;
494
+ /** Resolve once nothing is in flight. */
495
+ idle(): Promise<void>;
496
+ fault(namespace: string, fault: WebhookFault$1): void;
497
+ clear(namespace?: string): void;
498
+ };
499
+
500
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
501
+ type ServiceInstance$1 = FetchAPI$2 & {
502
+ reset(): Promise<void>;
503
+ };
504
+ type ServiceTimelineState$1 = Readonly<{
505
+ snapshot: NamespaceSnapshot$1;
506
+ clock: Readonly<ReturnType<Clock$1["state"]>>;
507
+ rngState: number;
508
+ }>;
509
+ type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
510
+ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
511
+ readonly name: string;
512
+ readonly sqlite: SqliteClient$2;
513
+ readonly clock: Clock$1;
514
+ readonly faults: FaultRegistry$1;
515
+ readonly metrics: Metrics$1;
516
+ readonly journal: Journal$1;
517
+ readonly rng: Rng$1;
518
+ readonly credentials: CredentialRegistry$1;
519
+ /** The webhook hub, when the service has outbound webhooks. */
520
+ readonly webhooks: WebhookHub$1 | undefined;
521
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
522
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule$1>): FaultRule$1[];
523
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
524
+ instance(namespace?: string): T;
525
+ /** Public names of every namespace created so far. */
526
+ namespaces(): string[];
527
+ /** Reset one namespace, or every namespace with `"*"`. */
528
+ reset(namespace?: string): Promise<void>;
529
+ snapshot(namespace?: string): NamespaceSnapshot$1;
530
+ restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
531
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
532
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint$1;
533
+ /** Create an isolated branch, optionally from a historical checkpoint. */
534
+ branch(name: string, options?: {
535
+ namespace?: string;
536
+ at?: string;
537
+ }): ServiceCheckpoint$1;
538
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
539
+ checkout(checkpoint: string, options?: {
540
+ namespace?: string;
541
+ branch?: string;
542
+ }): void;
543
+ /** Inspect the retained history for a namespace. */
544
+ timeline(namespace?: string): Timeline$1<ServiceTimelineState$1>;
545
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
546
+ state(namespace?: string): StateView$1;
547
+ };
548
+
549
+ type CliOption = {
550
+ type: "string" | "boolean";
551
+ description: string;
552
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
553
+ value?: string;
554
+ default?: string | boolean;
555
+ };
556
+ type CliValues = Record<string, string | boolean | undefined>;
557
+ type CommonServeOptions = {
558
+ adminKey: string | undefined;
559
+ seed: string | undefined;
560
+ onLog: ((entry: RequestLog$1) => void) | undefined;
561
+ };
562
+ /**
563
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
564
+ * and what to say at startup. Every service's `./server` entry exports one as
565
+ * `serveTarget`, which is also how `serve --config` finds services by name.
566
+ */
567
+ type ServeTarget = {
568
+ name: string;
569
+ defaultPort: number;
570
+ /** Serve flags beyond the common ones. */
571
+ options?: Record<string, CliOption>;
572
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
573
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
574
+ banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
575
+ };
576
+
577
+ /** A running server, with the address it actually bound. */
578
+ type Listening = {
579
+ url: string;
580
+ port: number;
581
+ host: string;
582
+ server: Server;
583
+ close(): Promise<void>;
584
+ };
585
+
586
+ /**
587
+ * The single source of time for a service.
588
+ *
589
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
590
+ * sleeping: appointment windows, result delays and expiries become reachable in
591
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
592
+ */
593
+ type ClockState = {
594
+ /** Current epoch milliseconds. */
595
+ now: number;
596
+ /** True while time does not advance on its own. */
597
+ frozen: boolean;
598
+ /** Milliseconds this clock adds to its underlying source. */
599
+ offsetMs: number;
600
+ };
601
+ type Clock = {
602
+ now(): number;
603
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
604
+ set(epochMs: number): void;
605
+ /** Move the clock forward, or back with a negative delta. */
606
+ advance(deltaMs: number): void;
607
+ /** Stop time at the current instant. */
608
+ freeze(): void;
609
+ /** Resume from the current instant. */
610
+ unfreeze(): void;
611
+ /** Drop back to the underlying source, live. */
612
+ reset(): void;
613
+ state(): ClockState;
614
+ };
615
+
616
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
617
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
618
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
619
+ type SqliteRunResult$1 = {
620
+ changes: number;
621
+ lastInsertRowid: number | bigint;
622
+ };
623
+ /**
624
+ * Prepared statement bound to a {@link SqliteClient}.
625
+ *
626
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
627
+ */
628
+ interface SqliteStatement$1 {
629
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
630
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
631
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
632
+ }
633
+ /**
634
+ * Sync SQLite client port owned by Mockingbird.
635
+ *
636
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
637
+ * `bun:sqlite` instances all work when they expose this surface.
638
+ */
639
+ interface SqliteClient$1 {
640
+ exec(sql: string): void;
641
+ prepare(sql: string): SqliteStatement$1;
642
+ transaction<T>(fn: () => T): T;
643
+ }
644
+
645
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
646
+ type Stored<T> = {
647
+ seq: number;
648
+ value: T;
649
+ };
650
+ type ListRecordsOptions<T> = {
651
+ /** Keep only records passing the predicate. */
652
+ where?: (value: T, seq: number) => boolean;
653
+ /** Sort order; default newest first. */
654
+ order?: "newest" | "oldest";
655
+ };
656
+ /**
657
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
658
+ * sequence, never by id lexicographic order, so list semantics stay stable.
659
+ */
660
+ declare class Collection<T> {
661
+ private readonly sqlite;
662
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
663
+ readonly namespace: string;
664
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
665
+ readonly collectionName: string;
666
+ constructor(sqlite: SqliteClient$1,
667
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
668
+ namespace: string,
669
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
670
+ collectionName: string);
671
+ private bumpCollectionSeq;
672
+ nextSequence(): number;
673
+ get(id: string): T | undefined;
674
+ has(id: string): boolean;
675
+ /** Insert a new record, assigning it the next sequence number. */
676
+ insert(id: string, value: T): Stored<T>;
677
+ /** Replace an existing record's value, keeping its position. */
678
+ update(id: string, value: T): Stored<T> | undefined;
679
+ delete(id: string): boolean;
680
+ /** How many records the collection holds, without reading them. */
681
+ count(): number;
682
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
683
+ id: string;
684
+ }>;
685
+ }
686
+
687
+ /**
688
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
689
+ * request a percentage fault hits — is reproducible from a seed.
690
+ *
691
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
692
+ * than statistical quality.
693
+ */
694
+ type Rng = {
695
+ /** Next value in `[0, 1)`. */
696
+ next(): number;
697
+ /** Next integer in `[min, max]`. */
698
+ int(min: number, max: number): number;
699
+ /** Restart the stream from its seed. */
700
+ reset(): void;
701
+ /** Serializable engine state used by deterministic checkpoints. */
702
+ state(): number;
703
+ /** Restore a state previously returned by {@link state}. */
704
+ setState(state: number): void;
705
+ seed: number;
706
+ };
707
+
708
+ /**
709
+ * A deliberate failure injected in front of an operation.
710
+ *
711
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
712
+ * quota error that only appears when a shared sandbox is full, the 429 that only
713
+ * appears under load, the 5xx that proves a retry path works.
714
+ */
715
+ type FaultRule = {
716
+ /** Stable id, so a suite can retire exactly the rule it added. */
717
+ id: string;
718
+ /** Fault only this operation. Omit to match every operation. */
719
+ operationId?: string;
720
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
721
+ method?: string;
722
+ /** Fault only paths starting with this prefix. Omit to match every path. */
723
+ pathPrefix?: string;
724
+ /**
725
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
726
+ * an in-process caller usually wants, and what a parallel worker usually does not:
727
+ * rules added through `POST /__admin/faults` default to the calling namespace.
728
+ */
729
+ namespace?: string;
730
+ /**
731
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
732
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
733
+ * the request then still reaches the service.
734
+ */
735
+ status?: number;
736
+ /** Response body, serialized as JSON. A string is sent as-is. */
737
+ body?: unknown;
738
+ headers?: Record<string, string>;
739
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
740
+ count?: number;
741
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
742
+ rate?: number;
743
+ /** Hold the response back this long, to exercise timeouts. */
744
+ delayMs?: number;
745
+ /** Alias of `delayMs`. */
746
+ latencyMs?: number;
747
+ /**
748
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
749
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
750
+ */
751
+ drop?: boolean;
752
+ /**
753
+ * A named service behaviour to switch on for the matching request instead of (or
754
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
755
+ * read it with `faultEffects(request)`.
756
+ */
757
+ effect?: string;
758
+ /** Parameters for `effect`. */
759
+ params?: Record<string, unknown>;
760
+ /** From the preset this rule was expanded from, if any. */
761
+ preset?: string;
762
+ };
763
+ /** A fault that fired for one request. */
764
+ type FaultHit = {
765
+ id: string;
766
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
767
+ response?: Response;
768
+ drop?: boolean;
769
+ effect?: {
770
+ name: string;
771
+ params: Record<string, unknown>;
772
+ };
773
+ };
774
+ /** What a request looks like to the fault matcher. */
775
+ type FaultCandidate = {
776
+ operationId: string | undefined;
777
+ method: string;
778
+ path: string;
779
+ namespace: string;
780
+ };
781
+ type FaultRegistry = {
782
+ add(rule: FaultRule): FaultRule;
783
+ list(): (FaultRule & {
784
+ remaining: number | null;
785
+ hits: number;
786
+ })[];
787
+ remove(id: string): boolean;
788
+ clear(): void;
789
+ /**
790
+ * Every fault this request should get, in rule order, stopping at the first that answers
791
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
792
+ * each matching rule's remaining uses.
793
+ */
794
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
795
+ };
796
+
797
+ /** A stable identifier for a point in a {@link Timeline}. */
798
+ type CheckpointId = string;
799
+ /** An immutable node in a timeline's checkpoint DAG. */
800
+ type Checkpoint<T> = Readonly<{
801
+ id: CheckpointId;
802
+ branch: string;
803
+ parent: CheckpointId | null;
804
+ /** Logical time supplied by the timeline's injected clock. */
805
+ at: number;
806
+ value: T;
807
+ }>;
808
+ type TimelineOptions = {
809
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
810
+ now?: () => number;
811
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
812
+ maxCheckpoints?: number;
813
+ /** Customize deterministic checkpoint IDs. */
814
+ id?: (sequence: number) => CheckpointId;
815
+ };
816
+ type CommitOptions = {
817
+ branch?: string;
818
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
819
+ parent?: CheckpointId | null;
820
+ };
821
+ type ForkOptions = {
822
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
823
+ from?: CheckpointId;
824
+ };
825
+ /**
826
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
827
+ * records, namespace images, or copy-on-write SQL engine snapshots.
828
+ *
829
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
830
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
831
+ * (the logical clock) is injected.
832
+ */
833
+ declare class Timeline<T> {
834
+ readonly maxCheckpoints: number;
835
+ private readonly now;
836
+ private readonly makeId;
837
+ private readonly nodes;
838
+ private readonly heads;
839
+ /** Unreferenced nodes in the exact order they became collectible. */
840
+ private readonly evictable;
841
+ /** Branch heads plus explicit retainers. Absent means zero. */
842
+ private readonly references;
843
+ private readonly explicitPins;
844
+ private sequence;
845
+ constructor(options?: TimelineOptions);
846
+ /** Capture a new immutable value and move `branch` to it. */
847
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
848
+ /** Create a branch pointer without copying its checkpoint value. */
849
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
850
+ /** Move a branch pointer to an existing checkpoint. */
851
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
852
+ get(id: CheckpointId): Checkpoint<T>;
853
+ head(branch?: string): Checkpoint<T> | undefined;
854
+ hasBranch(branch: string): boolean;
855
+ branches(): Readonly<Record<string, CheckpointId>>;
856
+ checkpoints(): readonly Checkpoint<T>[];
857
+ /** Number of retained checkpoints without allocating an array. */
858
+ get size(): number;
859
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
860
+ retain(id: CheckpointId): Checkpoint<T>;
861
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
862
+ release(id: CheckpointId): boolean;
863
+ deleteBranch(branch: string): boolean;
864
+ /**
865
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
866
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
867
+ * storage dependency, so a retained node remains usable after pruning.
868
+ */
869
+ gc(max?: number): CheckpointId[];
870
+ private collect;
871
+ private moveHead;
872
+ private addReference;
873
+ private removeReference;
874
+ private assertBranch;
875
+ }
876
+
877
+ /**
878
+ * Anything that can answer a Fetch `Request` with a `Response`.
879
+ *
880
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
881
+ * It is the only contract shared across the whole graph.
882
+ */
883
+ interface FetchAPI$1 {
884
+ fetch(request: Request): Promise<Response>;
885
+ }
886
+
887
+ /** Options every provider constructor accepts. */
888
+ type APIOptions = {
889
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
890
+ sqlite?: SqliteClient$1;
891
+ /** Clock used for `created`-style fields. Default `Date.now`. */
892
+ now?: () => number;
893
+ /**
894
+ * Storage namespace for this instance's records. Instances sharing one SQLite
895
+ * client stay isolated when their namespaces differ. Defaults to the service name.
896
+ */
897
+ namespace?: string;
898
+ };
899
+
900
+ /**
901
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
902
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
903
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
904
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
905
+ */
906
+ type BodyIssue = {
907
+ path: string;
908
+ message: string;
909
+ kind?: "media_type" | "syntax" | "required" | "schema";
910
+ };
911
+
912
+ /**
913
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
914
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
915
+ */
916
+ type RejectedRequest = {
917
+ /** The raw `content-type` header, or `null` when the request sent none. */
918
+ contentType: string | null;
919
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
920
+ bodyBytes: number | null;
921
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
922
+ transferEncoding: string | null;
923
+ };
924
+ /** One handled request, as the structured log sees it. */
925
+ type RequestLog = {
926
+ service: string;
927
+ namespace: string;
928
+ operationId: string | undefined;
929
+ method: string;
930
+ path: string;
931
+ status: number;
932
+ durationMs: number;
933
+ /** True when the path matched no operation in the contract. */
934
+ unmatched: boolean;
935
+ /** Set when a fault rule produced the response. */
936
+ faultId?: string;
937
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
938
+ ids?: Record<string, string>;
939
+ /** Set when the service created a resource the request referred to but that did not exist. */
940
+ adopted?: boolean;
941
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
942
+ request?: RejectedRequest;
943
+ /** The validation issues behind a rejection, when the service found any. */
944
+ issues?: BodyIssue[];
945
+ };
946
+ type MetricsReport = {
947
+ requests: number;
948
+ /** Counts keyed `<operationId> <status>`. */
949
+ byOperation: Record<string, number>;
950
+ /**
951
+ * Paths that matched no operation, most frequent first.
952
+ *
953
+ * This is the early-warning signal: a consumer calling something the mock does
954
+ * not implement shows up here as a count, before it fails a suite as a 404.
955
+ */
956
+ unmatched: {
957
+ method: string;
958
+ path: string;
959
+ count: number;
960
+ }[];
961
+ faults: number;
962
+ totalDurationMs: number;
963
+ };
964
+ type Metrics = {
965
+ record(entry: RequestLog): void;
966
+ report(): MetricsReport;
967
+ reset(): void;
968
+ };
969
+
970
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
971
+ type JournalEntry = RequestLog & {
972
+ at: string;
973
+ };
974
+ type JournalQuery = {
975
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
976
+ namespace?: string;
977
+ operationId?: string;
978
+ status?: number;
979
+ /** Only entries at or after this instant (epoch ms). */
980
+ since?: number;
981
+ /** At most this many, the most recent kept. */
982
+ limit?: number;
983
+ };
984
+ type Journal = {
985
+ readonly size: number;
986
+ record(entry: JournalEntry): void;
987
+ list(query?: JournalQuery): JournalEntry[];
988
+ /** Forget one namespace's entries, or every namespace's. */
989
+ clear(namespace?: string): void;
990
+ };
991
+
992
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
993
+ type CredentialRegistry = {
994
+ set(credential: string, namespace: string): void;
995
+ get(credential: string): string | undefined;
996
+ remove(credential: string): boolean;
997
+ clear(): void;
998
+ entries(): {
999
+ credential: string;
1000
+ namespace: string;
1001
+ }[];
1002
+ };
1003
+
1004
+ /**
1005
+ * A point-in-time copy of everything a service namespace holds.
1006
+ *
1007
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
1008
+ * is generic: any service gets per-test rollback without knowing its own schema.
1009
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
1010
+ */
1011
+ type NamespaceSnapshot = {
1012
+ namespace: string;
1013
+ records: {
1014
+ collection: string;
1015
+ id: string;
1016
+ seq: number;
1017
+ value: string;
1018
+ }[];
1019
+ sequences: {
1020
+ name: string;
1021
+ kind: string;
1022
+ value: number;
1023
+ }[];
1024
+ };
1025
+
1026
+ declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
1027
+ type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
1028
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
1029
+ type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
1030
+ type StateField = {
1031
+ name: string;
1032
+ kind: StateFieldKind;
1033
+ optional: boolean;
1034
+ description?: string;
1035
+ /** One level of nested object fields. */
1036
+ fields?: StateField[];
1037
+ meta?: StateMeta;
1038
+ };
1039
+ type StateCollectionView = {
1040
+ name: string;
1041
+ label: string;
1042
+ description?: string;
1043
+ count: number;
1044
+ /** `mixed` when a declaration and stored rows both contribute fields. */
1045
+ source: "declared" | "inferred" | "mixed";
1046
+ fields: StateField[];
1047
+ meta?: StateMeta;
1048
+ };
1049
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
1050
+ type StateView = {
1051
+ namespace: string;
1052
+ storageNamespace: string;
1053
+ collections: StateCollectionView[];
1054
+ };
1055
+
1056
+ type WebhookEndpoint = {
1057
+ /** Stable id; generated when omitted. */
1058
+ id?: string;
1059
+ url: string;
1060
+ secret?: string;
1061
+ /** Event types to deliver; omit or include `"*"` for every type. */
1062
+ events?: string[];
1063
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
1064
+ tags?: Record<string, string>;
1065
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
1066
+ signUrl?: string;
1067
+ headers?: Record<string, string>;
1068
+ };
1069
+ type WebhookMessage = {
1070
+ id: string;
1071
+ namespace: string;
1072
+ type: string;
1073
+ body: string;
1074
+ contentType: string;
1075
+ tags: Record<string, string>;
1076
+ headers?: Record<string, string>;
1077
+ /** Wall-clock ISO-8601 time of publication. */
1078
+ publishedAt: string;
1079
+ };
1080
+ type WebhookAttempt = {
1081
+ attempt: number;
1082
+ at: string;
1083
+ status: number | null;
1084
+ error: string | null;
1085
+ durationMs: number;
1086
+ /** Exact receiver response body, when one was returned. */
1087
+ responseBody?: string | null;
1088
+ };
1089
+ type WebhookDelivery = {
1090
+ id: string;
1091
+ messageId: string;
1092
+ namespace: string;
1093
+ type: string;
1094
+ endpointId: string;
1095
+ url: string;
1096
+ state: "pending" | "delivered" | "failed" | "dropped";
1097
+ attempts: WebhookAttempt[];
1098
+ };
1099
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
1100
+ type WebhookFault = {
1101
+ mode: "duplicate" | "reorder" | "drop";
1102
+ /** Messages affected; default 1. */
1103
+ count?: number;
1104
+ };
1105
+ type PublishInput = {
1106
+ namespace: string;
1107
+ type: string;
1108
+ /** Exact body; objects are JSON-encoded. */
1109
+ body: string | Record<string, unknown> | unknown[];
1110
+ /** Default `application/json`, or form-encoded when `form` is given. */
1111
+ contentType?: string;
1112
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
1113
+ form?: Record<string, string>;
1114
+ tags?: Record<string, string>;
1115
+ /** Message-specific delivery headers, captured as part of durable message state. */
1116
+ headers?: Record<string, string>;
1117
+ /** Message id; generated when omitted. */
1118
+ id?: string;
1119
+ };
1120
+ type WebhookHub = {
1121
+ publish(input: PublishInput): WebhookMessage;
1122
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
1123
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
1124
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
1125
+ endpoints(namespace: string): WebhookEndpoint[];
1126
+ messages(namespace?: string): WebhookMessage[];
1127
+ deliveries(namespace?: string): WebhookDelivery[];
1128
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
1129
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
1130
+ flush(): Promise<void>;
1131
+ /** Resolve once nothing is in flight. */
1132
+ idle(): Promise<void>;
1133
+ fault(namespace: string, fault: WebhookFault): void;
1134
+ clear(namespace?: string): void;
1135
+ };
1136
+
1137
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
1138
+ type ServiceInstance = FetchAPI$1 & {
1139
+ reset(): Promise<void>;
1140
+ };
1141
+ type ServiceTimelineState = Readonly<{
1142
+ snapshot: NamespaceSnapshot;
1143
+ clock: Readonly<ReturnType<Clock["state"]>>;
1144
+ rngState: number;
1145
+ }>;
1146
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1147
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
1148
+ readonly name: string;
1149
+ readonly sqlite: SqliteClient$1;
1150
+ readonly clock: Clock;
1151
+ readonly faults: FaultRegistry;
1152
+ readonly metrics: Metrics;
1153
+ readonly journal: Journal;
1154
+ readonly rng: Rng;
1155
+ readonly credentials: CredentialRegistry;
1156
+ /** The webhook hub, when the service has outbound webhooks. */
1157
+ readonly webhooks: WebhookHub | undefined;
1158
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1159
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1160
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
1161
+ instance(namespace?: string): T;
1162
+ /** Public names of every namespace created so far. */
1163
+ namespaces(): string[];
1164
+ /** Reset one namespace, or every namespace with `"*"`. */
1165
+ reset(namespace?: string): Promise<void>;
1166
+ snapshot(namespace?: string): NamespaceSnapshot;
1167
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1168
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
1169
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1170
+ /** Create an isolated branch, optionally from a historical checkpoint. */
1171
+ branch(name: string, options?: {
1172
+ namespace?: string;
1173
+ at?: string;
1174
+ }): ServiceCheckpoint;
1175
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
1176
+ checkout(checkpoint: string, options?: {
1177
+ namespace?: string;
1178
+ branch?: string;
1179
+ }): void;
1180
+ /** Inspect the retained history for a namespace. */
1181
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
1182
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
1183
+ state(namespace?: string): StateView;
1184
+ };
1185
+
1186
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1187
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1188
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1189
+ type SqliteRunResult = {
1190
+ changes: number;
1191
+ lastInsertRowid: number | bigint;
1192
+ };
1193
+ /**
1194
+ * Prepared statement bound to a {@link SqliteClient}.
1195
+ *
1196
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1197
+ */
1198
+ interface SqliteStatement {
1199
+ run(...params: SqliteValue[]): SqliteRunResult;
1200
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
1201
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1202
+ }
1203
+ /**
1204
+ * Sync SQLite client port owned by Mockingbird.
1205
+ *
1206
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1207
+ * `bun:sqlite` instances all work when they expose this surface.
1208
+ */
1209
+ interface SqliteClient {
1210
+ exec(sql: string): void;
1211
+ prepare(sql: string): SqliteStatement;
1212
+ transaction<T>(fn: () => T): T;
1213
+ }
1214
+
1215
+ /**
1216
+ * Anything that can answer a Fetch `Request` with a `Response`.
1217
+ *
1218
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
1219
+ * It is the only contract shared across the whole graph.
1220
+ */
1221
+ interface FetchAPI {
1222
+ fetch(request: Request): Promise<Response>;
1223
+ }
1224
+
1225
+ /**
1226
+ * Stored records are the wire shape Paddle returns as `data` (snake_case), so a handler can
1227
+ * serve them as-is and `include=` relations are layered on at response time.
1228
+ */
1229
+ type Status = "active" | "archived";
1230
+ type CatalogType = "standard" | "custom";
1231
+ type Interval = "day" | "week" | "month" | "year";
1232
+ type CollectionMode = "automatic" | "manual";
1233
+ type TransactionStatus = "draft" | "ready" | "billed" | "paid" | "completed" | "canceled" | "past_due";
1234
+ type TransactionOrigin = "api" | "subscription_charge" | "subscription_payment_method_change" | "subscription_recurring" | "subscription_update" | "web";
1235
+ type SubscriptionStatus = "active" | "canceled" | "past_due" | "paused" | "trialing";
1236
+ type CustomData = Record<string, unknown> | null;
1237
+ type TimePeriod = {
1238
+ interval: Interval;
1239
+ frequency: number;
1240
+ };
1241
+ type TrialPeriod = TimePeriod & {
1242
+ requires_payment_method?: boolean;
1243
+ };
1244
+ type Money = {
1245
+ amount: string;
1246
+ currency_code: string;
1247
+ };
1248
+ type Period = {
1249
+ starts_at: string;
1250
+ ends_at: string;
1251
+ };
1252
+ type BillingDetails = {
1253
+ enable_checkout: boolean;
1254
+ purchase_order_number: string | null;
1255
+ additional_information: string | null;
1256
+ payment_terms: TimePeriod;
1257
+ };
1258
+ type CustomerRecord = {
1259
+ id: string;
1260
+ name: string | null;
1261
+ email: string;
1262
+ marketing_consent: boolean;
1263
+ status: Status;
1264
+ custom_data: CustomData;
1265
+ locale: string;
1266
+ created_at: string;
1267
+ updated_at: string;
1268
+ import_meta: null;
1269
+ };
1270
+ type AddressRecord = {
1271
+ id: string;
1272
+ customer_id: string;
1273
+ description: string | null;
1274
+ first_line: string | null;
1275
+ second_line: string | null;
1276
+ city: string | null;
1277
+ postal_code: string | null;
1278
+ region: string | null;
1279
+ country_code: string;
1280
+ custom_data: CustomData;
1281
+ status: Status;
1282
+ created_at: string;
1283
+ updated_at: string;
1284
+ import_meta: null;
1285
+ };
1286
+ type BusinessRecord = {
1287
+ id: string;
1288
+ customer_id: string;
1289
+ name: string;
1290
+ company_number: string | null;
1291
+ tax_identifier: string | null;
1292
+ status: Status;
1293
+ contacts: {
1294
+ name: string | null;
1295
+ email: string;
1296
+ }[] | null;
1297
+ created_at: string;
1298
+ updated_at: string;
1299
+ custom_data: CustomData;
1300
+ import_meta: null;
1301
+ };
1302
+ type ProductRecord = {
1303
+ id: string;
1304
+ name: string;
1305
+ type: CatalogType;
1306
+ description: string | null;
1307
+ tax_category: string;
1308
+ image_url: string | null;
1309
+ custom_data: CustomData;
1310
+ status: Status;
1311
+ created_at: string;
1312
+ updated_at: string;
1313
+ import_meta: null;
1314
+ };
1315
+ type PriceRecord = {
1316
+ id: string;
1317
+ product_id: string;
1318
+ description: string;
1319
+ type: CatalogType;
1320
+ name: string | null;
1321
+ billing_cycle: TimePeriod | null;
1322
+ trial_period: TrialPeriod | null;
1323
+ tax_mode: string;
1324
+ unit_price: Money;
1325
+ unit_price_overrides: {
1326
+ country_codes: string[];
1327
+ unit_price: Money;
1328
+ }[];
1329
+ quantity: {
1330
+ minimum: number;
1331
+ maximum: number;
1332
+ };
1333
+ status: Status;
1334
+ created_at: string;
1335
+ updated_at: string;
1336
+ custom_data: CustomData;
1337
+ import_meta: null;
1338
+ };
1339
+ type Totals = {
1340
+ subtotal: string;
1341
+ discount: string;
1342
+ tax: string;
1343
+ total: string;
1344
+ };
1345
+ type TransactionTotals = Totals & {
1346
+ credit: string;
1347
+ credit_to_balance: string;
1348
+ balance: string;
1349
+ grand_total: string;
1350
+ grand_total_tax: string;
1351
+ fee: string | null;
1352
+ earnings: string | null;
1353
+ currency_code: string;
1354
+ };
1355
+ type LineItem = {
1356
+ id: string;
1357
+ price_id: string;
1358
+ quantity: number;
1359
+ proration: null;
1360
+ tax_rate: string;
1361
+ unit_totals: Totals;
1362
+ totals: Totals;
1363
+ product: ProductRecord;
1364
+ };
1365
+ type TransactionDetails = {
1366
+ tax_rates_used: {
1367
+ tax_rate: string;
1368
+ totals: Totals;
1369
+ }[];
1370
+ totals: TransactionTotals;
1371
+ adjusted_totals: {
1372
+ subtotal: string;
1373
+ tax: string;
1374
+ total: string;
1375
+ grand_total: string;
1376
+ grand_total_tax: string;
1377
+ fee: string | null;
1378
+ earnings: string | null;
1379
+ currency_code: string;
1380
+ retained_fee: string;
1381
+ };
1382
+ payout_totals: null;
1383
+ adjusted_payout_totals: null;
1384
+ line_items: LineItem[];
1385
+ };
1386
+ type PaymentAttempt = {
1387
+ payment_attempt_id: string;
1388
+ stored_payment_method_id: string;
1389
+ payment_method_id: string | null;
1390
+ amount: string;
1391
+ status: "captured" | "error";
1392
+ error_code: string | null;
1393
+ method_details: {
1394
+ type: "card";
1395
+ card: {
1396
+ type: string;
1397
+ last4: string;
1398
+ expiry_month: number;
1399
+ expiry_year: number;
1400
+ cardholder_name: string;
1401
+ };
1402
+ paypal: null;
1403
+ south_korea_local_card: null;
1404
+ underlying_details: null;
1405
+ } | null;
1406
+ created_at: string;
1407
+ captured_at: string | null;
1408
+ };
1409
+ type TransactionItem = {
1410
+ price_id: string;
1411
+ /** The price as it was when the transaction was written, as Paddle embeds it. */
1412
+ price: PriceRecord;
1413
+ quantity: number;
1414
+ proration: null;
1415
+ };
1416
+ type TransactionRecord = {
1417
+ id: string;
1418
+ status: TransactionStatus;
1419
+ customer_id: string | null;
1420
+ address_id: string | null;
1421
+ business_id: string | null;
1422
+ custom_data: CustomData;
1423
+ currency_code: string;
1424
+ origin: TransactionOrigin;
1425
+ subscription_id: string | null;
1426
+ invoice_id: string | null;
1427
+ invoice_number: string | null;
1428
+ collection_mode: CollectionMode;
1429
+ discount_id: null;
1430
+ billing_details: BillingDetails | null;
1431
+ billing_period: Period | null;
1432
+ items: TransactionItem[];
1433
+ details: TransactionDetails;
1434
+ payments: PaymentAttempt[];
1435
+ checkout: {
1436
+ url: string | null;
1437
+ } | null;
1438
+ created_at: string;
1439
+ updated_at: string;
1440
+ billed_at: string | null;
1441
+ revised_at: null;
1442
+ };
1443
+ type SubscriptionItem = {
1444
+ status: "active" | "inactive" | "trialing";
1445
+ quantity: number;
1446
+ recurring: boolean;
1447
+ created_at: string;
1448
+ updated_at: string;
1449
+ previously_billed_at: string | null;
1450
+ next_billed_at: string | null;
1451
+ trial_dates: Period | null;
1452
+ price: PriceRecord;
1453
+ product: ProductRecord;
1454
+ };
1455
+ type ScheduledChange = {
1456
+ action: "cancel" | "pause" | "resume";
1457
+ effective_at: string;
1458
+ resume_at: string | null;
1459
+ };
1460
+ type SubscriptionRecord = {
1461
+ id: string;
1462
+ status: SubscriptionStatus;
1463
+ customer_id: string;
1464
+ address_id: string;
1465
+ business_id: string | null;
1466
+ currency_code: string;
1467
+ created_at: string;
1468
+ updated_at: string;
1469
+ started_at: string | null;
1470
+ first_billed_at: string | null;
1471
+ next_billed_at: string | null;
1472
+ paused_at: string | null;
1473
+ canceled_at: string | null;
1474
+ discount: null;
1475
+ collection_mode: CollectionMode;
1476
+ billing_details: BillingDetails | null;
1477
+ current_billing_period: Period | null;
1478
+ billing_cycle: TimePeriod;
1479
+ scheduled_change: ScheduledChange | null;
1480
+ management_urls: {
1481
+ update_payment_method: string | null;
1482
+ cancel: string;
1483
+ };
1484
+ items: SubscriptionItem[];
1485
+ custom_data: CustomData;
1486
+ import_meta: null;
1487
+ };
1488
+ /** One-time charges queued with `effective_from: next_billing_period`, billed at the next renewal. */
1489
+ type PendingCharge = {
1490
+ price_id: string;
1491
+ quantity: number;
1492
+ };
1493
+ type EventRecord = {
1494
+ event_id: string;
1495
+ event_type: string;
1496
+ occurred_at: string;
1497
+ notification_id: null;
1498
+ data: Record<string, unknown>;
1499
+ };
1500
+
1501
+ /** Paddle id prefixes, per entity. */
1502
+ declare const ID_PREFIX: {
1503
+ readonly customer: "ctm";
1504
+ readonly address: "add";
1505
+ readonly business: "biz";
1506
+ readonly product: "pro";
1507
+ readonly price: "pri";
1508
+ readonly transaction: "txn";
1509
+ readonly subscription: "sub";
1510
+ readonly event: "evt";
1511
+ readonly notification: "ntf";
1512
+ readonly line_item: "txnitm";
1513
+ readonly payment_attempt: "payatt";
1514
+ readonly payment_method: "paymtd";
1515
+ readonly invoice: "inv";
1516
+ };
1517
+ type IdKind = keyof typeof ID_PREFIX;
1518
+ declare class PaddleState {
1519
+ readonly customers: Collection<CustomerRecord>;
1520
+ readonly addresses: Collection<AddressRecord>;
1521
+ readonly businesses: Collection<BusinessRecord>;
1522
+ readonly products: Collection<ProductRecord>;
1523
+ readonly prices: Collection<PriceRecord>;
1524
+ readonly transactions: Collection<TransactionRecord>;
1525
+ readonly subscriptions: Collection<SubscriptionRecord>;
1526
+ /** Queued one-time charges per subscription id. */
1527
+ readonly pendingCharges: Collection<PendingCharge[]>;
1528
+ readonly events: Collection<EventRecord>;
1529
+ private readonly ids;
1530
+ constructor(sqlite: SqliteClient, namespace: string);
1531
+ /**
1532
+ * A Paddle-shaped id: `<prefix>_01` followed by 24 lower-case alphanumerics (Paddle ids are a
1533
+ * prefix plus a 26-character ULID), deterministic for a given history.
1534
+ */
1535
+ nextId(kind: IdKind): string;
1536
+ /** An opaque token (auth tokens, signing material), deterministic for a given history. */
1537
+ nextToken(prefix: string, length: number): string;
1538
+ }
1539
+
1540
+ type Json = Record<string, unknown>;
1541
+ /** What `POST /__admin/checkout` accepts: a hosted-checkout completion, in one call. */
1542
+ type CheckoutInput = {
1543
+ /** An existing customer, or an email to find or create one by. */
1544
+ customer_id?: string;
1545
+ email?: string;
1546
+ name?: string;
1547
+ /** An existing address of the customer, or a country to create one for. Default `US`. */
1548
+ address_id?: string;
1549
+ country_code?: string;
1550
+ postal_code?: string;
1551
+ business_id?: string;
1552
+ items: {
1553
+ price_id: string;
1554
+ quantity?: number;
1555
+ }[];
1556
+ custom_data?: CustomData;
1557
+ currency_code?: string;
1558
+ };
1559
+ type CardInput = {
1560
+ type?: string;
1561
+ last4?: string;
1562
+ expiry_month?: number;
1563
+ expiry_year?: number;
1564
+ cardholder_name?: string;
1565
+ };
1566
+ type PaddleAPIOptions = APIOptions & {
1567
+ /** The public namespace name, for `/ns/<name>` in `meta.pagination.next` and management URLs. */
1568
+ publicNamespace?: string;
1569
+ /**
1570
+ * The default payment link: a `ready` automatic-collection transaction gets
1571
+ * `checkout.url = <paymentLink>?_ptxn=<id>`. Default none (`checkout.url` is `null`).
1572
+ */
1573
+ paymentLink?: string;
1574
+ /** Called with every event the account produces (the body a webhook would carry). */
1575
+ onEvent?: (event: EventRecord) => void;
1576
+ /**
1577
+ * Seed the fixture account (`seedFixtures`) on construction when the namespace is empty, and
1578
+ * again after every `reset()`. Fixture events are recorded (`GET /events`) but not passed to
1579
+ * `onEvent`: they are the account's pre-existing state, not new activity.
1580
+ */
1581
+ fixtures?: boolean;
1582
+ };
1583
+ /**
1584
+ * Stateful mock of the Paddle Billing API. Catalog and customer records behave as Paddle's do;
1585
+ * transactions carry computed totals (no tax, no discounts); subscriptions are created when a
1586
+ * transaction with recurring prices is paid, which the admin routes simulate (`payTransaction`,
1587
+ * `checkout`), and renewed or failed on demand (`renewSubscription`, `failPayment`).
1588
+ */
1589
+ declare class PaddleAPI implements FetchAPI {
1590
+ readonly app: Hono;
1591
+ readonly sqlite: SqliteClient;
1592
+ readonly state: PaddleState;
1593
+ private readonly service;
1594
+ private readonly now;
1595
+ private readonly publicNamespace;
1596
+ private readonly paymentLink;
1597
+ private readonly onEvent;
1598
+ private readonly fixtures;
1599
+ private readonly requestIds;
1600
+ private requestCounter;
1601
+ /** While seeding fixtures: events are recorded but not published. */
1602
+ private seeding;
1603
+ constructor(options?: PaddleAPIOptions);
1604
+ fetch(request: Request): Promise<Response>;
1605
+ /** Empty the namespace; with `fixtures`, the fixture account is seeded again. */
1606
+ reset(): Promise<void>;
1607
+ /** Every event the account produced, oldest first. */
1608
+ events(): EventRecord[];
1609
+ private requestId;
1610
+ private iso;
1611
+ private prefix;
1612
+ private emit;
1613
+ /** The JSON body, validated against the contract; an absent body is `{}` when allowed. */
1614
+ private body;
1615
+ private includes;
1616
+ private statusFilter;
1617
+ private page;
1618
+ private ok;
1619
+ private mustCustomer;
1620
+ createCustomer(input: {
1621
+ email: string;
1622
+ name?: string | null;
1623
+ custom_data?: CustomData;
1624
+ locale?: string;
1625
+ }): CustomerRecord;
1626
+ private listCustomers;
1627
+ private createCustomerOp;
1628
+ private getCustomer;
1629
+ private updateCustomer;
1630
+ private creditBalances;
1631
+ private authToken;
1632
+ createAddress(customerId: string, input: Partial<Omit<AddressRecord, "id" | "customer_id" | "status" | "created_at" | "updated_at" | "import_meta">> & {
1633
+ country_code: string;
1634
+ }): AddressRecord;
1635
+ private mustAddress;
1636
+ private listAddresses;
1637
+ private createAddressOp;
1638
+ private getAddress;
1639
+ private updateAddress;
1640
+ createBusiness(customerId: string, input: {
1641
+ name: string;
1642
+ company_number?: string | null;
1643
+ tax_identifier?: string | null;
1644
+ contacts?: {
1645
+ name?: string | null;
1646
+ email: string;
1647
+ }[] | null;
1648
+ custom_data?: CustomData;
1649
+ }): BusinessRecord;
1650
+ private mustBusiness;
1651
+ private listBusinesses;
1652
+ private contacts;
1653
+ private createBusinessOp;
1654
+ private getBusiness;
1655
+ private updateBusiness;
1656
+ /** The product record for an input, not yet stored (`commitProduct` stores and announces it). */
1657
+ private buildProduct;
1658
+ private commitProduct;
1659
+ createProduct(input: Parameters<PaddleAPI["buildProduct"]>[0]): ProductRecord;
1660
+ private mustProduct;
1661
+ private renderProduct;
1662
+ private listProducts;
1663
+ private createProductOp;
1664
+ private getProduct;
1665
+ private updateProduct;
1666
+ private timePeriod;
1667
+ /**
1668
+ * The validated price record for an input, not yet stored (`commitPrice` stores and announces
1669
+ * it). `product` is a product that is itself not stored yet (a non-catalog item's product).
1670
+ */
1671
+ private buildPrice;
1672
+ private commitPrice;
1673
+ createPrice(input: Parameters<PaddleAPI["buildPrice"]>[0]): PriceRecord;
1674
+ private mustPrice;
1675
+ private renderPrice;
1676
+ private listPrices;
1677
+ private priceInput;
1678
+ private createPriceOp;
1679
+ private getPrice;
1680
+ private updatePrice;
1681
+ /**
1682
+ * The priced items of a request: catalog prices by `price_id`, or non-catalog `price`
1683
+ * objects, whose `type: custom` price (and product) are only stored once the whole request
1684
+ * has validated: the caller runs `catalog` after its last check (a preview never does).
1685
+ */
1686
+ private resolveItems;
1687
+ private resolveParties;
1688
+ private billingDetails;
1689
+ private period;
1690
+ private countryOf;
1691
+ private lineItems;
1692
+ private checkoutFor;
1693
+ /** Build (or rebuild) a transaction from request fields; shared by create and update. */
1694
+ private transactionFrom;
1695
+ /** Sequential and unique: one more than the invoices issued so far (`MOCK-01001` first). */
1696
+ private nextInvoiceNumber;
1697
+ private transactionEvents;
1698
+ /** `POST /transactions` as a method: what the hosted checkout and the admin routes call. */
1699
+ createTransaction(input: Json, origin?: TransactionOrigin): TransactionRecord;
1700
+ private mustTransaction;
1701
+ private renderTransaction;
1702
+ private dateFilter;
1703
+ private listTransactions;
1704
+ private createTransactionOp;
1705
+ private previewTransaction;
1706
+ private getTransaction;
1707
+ private updateTransaction;
1708
+ private transactionInvoice;
1709
+ private captured;
1710
+ private subscriptionItems;
1711
+ /**
1712
+ * Complete a `ready`, `billed` or `past_due` transaction as if the customer paid: a captured
1713
+ * card payment, `completed` status, an invoice, and, for recurring items, the subscription
1714
+ * (`trialing` when a price has a trial, else `active`) or the recovery of a past-due one.
1715
+ */
1716
+ payTransaction(id: string, card?: CardInput): {
1717
+ transaction: TransactionRecord;
1718
+ subscription: SubscriptionRecord | null;
1719
+ };
1720
+ private mustSubscription;
1721
+ private saveSubscription;
1722
+ private recurringPriced;
1723
+ private applyScheduledChange;
1724
+ /** A completed transaction for a subscription's billing period (renewal, charge, update). */
1725
+ private billSubscription;
1726
+ /**
1727
+ * Run the next billing date: a scheduled cancel or pause takes effect instead, a paused
1728
+ * subscription with a scheduled resume resumes (billed from its `effective_at`); otherwise a
1729
+ * `subscription_recurring` transaction is created (plus any queued one-time charges), the
1730
+ * billing period advances, and a trial ends into `active`.
1731
+ */
1732
+ renewSubscription(id: string): {
1733
+ subscription: SubscriptionRecord;
1734
+ transaction: TransactionRecord | null;
1735
+ };
1736
+ /** The next renewal's payment is declined: a `past_due` transaction and subscription. */
1737
+ failPayment(id: string): {
1738
+ subscription: SubscriptionRecord;
1739
+ transaction: TransactionRecord;
1740
+ };
1741
+ /** A hosted-checkout completion in one call: find or create the customer and address, then pay. */
1742
+ checkout(input: CheckoutInput): {
1743
+ transaction: TransactionRecord;
1744
+ subscription: SubscriptionRecord | null;
1745
+ };
1746
+ private nextTransactionPreview;
1747
+ private renderSubscription;
1748
+ private listSubscriptions;
1749
+ private subscriptionResponse;
1750
+ private getSubscription;
1751
+ private notCanceled;
1752
+ private updateSubscription;
1753
+ private activateSubscription;
1754
+ private pauseSubscription;
1755
+ private resumeSubscription;
1756
+ /**
1757
+ * A paused subscription becomes active for `period`; a period starting now (or one a
1758
+ * scheduled resume set) is billed at once, a continued one is not.
1759
+ */
1760
+ private resumeInto;
1761
+ private cancelSubscription;
1762
+ private chargeSubscription;
1763
+ private listEvents;
1764
+ /**
1765
+ * A small account to start from: a customer with an address and a business, a "Pro" product
1766
+ * with monthly, yearly and one-time prices, a "Starter" price with a 14-day trial, an active
1767
+ * monthly subscription, a trialing one, an unpaid `ready` transaction and a manual invoice.
1768
+ * Deterministic: two instances seeded at the same clock hold identical ids.
1769
+ */
1770
+ seedFixtures(): {
1771
+ customer: CustomerRecord;
1772
+ address: AddressRecord;
1773
+ business: BusinessRecord;
1774
+ product: ProductRecord;
1775
+ prices: {
1776
+ monthly: PriceRecord;
1777
+ yearly: PriceRecord;
1778
+ setup: PriceRecord;
1779
+ starter: PriceRecord;
1780
+ };
1781
+ subscriptions: {
1782
+ active: SubscriptionRecord;
1783
+ trialing: SubscriptionRecord;
1784
+ };
1785
+ transactions: {
1786
+ ready: TransactionRecord;
1787
+ invoice: TransactionRecord;
1788
+ };
1789
+ };
1790
+ private seedAccount;
1791
+ }
1792
+
1793
+ type PaddleRuntimeOptions = {
1794
+ sqlite?: SqliteClient;
1795
+ clock?: Clock;
1796
+ seed?: number | string;
1797
+ adminKey?: string;
1798
+ onLog?: (entry: RequestLog) => void;
1799
+ /**
1800
+ * Where notifications go, signed with the endpoint's `pdl_ntfset_…` secret in
1801
+ * `Paddle-Signature`. `events` limits the event types (default all).
1802
+ */
1803
+ webhooks?: Omit<WebhookEndpoint, "id"> & {
1804
+ retryDelaysMs?: readonly number[];
1805
+ fetch?: (request: Request) => Promise<Response>;
1806
+ };
1807
+ /** The default payment link `checkout.url` is built from (`<link>?_ptxn=<id>`). */
1808
+ paymentLink?: string;
1809
+ /** Seed every namespace with the fixture account on first use (`seedFixtures`). */
1810
+ fixtures?: boolean;
1811
+ };
1812
+ type PaddleRuntime = ServiceRuntime<PaddleAPI> & {
1813
+ readonly webhooks: WebhookHub;
1814
+ };
1815
+
1816
+ /** Port `mockingbird-paddle serve` listens on when none is given. */
1817
+ declare const DEFAULT_PORT = 8795;
1818
+ type PaddleServerOptions = PaddleRuntimeOptions & {
1819
+ /** Default `0`: the OS picks a free port. */
1820
+ port?: number;
1821
+ /** Default `127.0.0.1`. */
1822
+ host?: string;
1823
+ };
1824
+ type PaddleServer = Listening & {
1825
+ runtime: PaddleRuntime;
1826
+ };
1827
+ /**
1828
+ * Serve the Paddle mock over `node:http`. Point the SDK at `url`:
1829
+ * `new Paddle(key, { environment: url as Environment })`.
1830
+ */
1831
+ declare const createServer: (options?: PaddleServerOptions) => Promise<PaddleServer>;
1832
+ /** How `serve` (and `serve --config`) builds the Paddle mock from flags. */
1833
+ declare const serveTarget: ServeTarget;
1834
+
1835
+ export { DEFAULT_PORT, createServer, serveTarget };
1836
+ export type { PaddleServer, PaddleServerOptions };