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