@emulates/daily 2.3.1

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,1174 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Emulates service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /** Bind values accepted by the Emulates SQLite port (matches sqlite-mem / better-sqlite3). */
14
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
15
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
16
+ type SqliteRunResult$1 = {
17
+ changes: number;
18
+ lastInsertRowid: number | bigint;
19
+ };
20
+ /**
21
+ * Prepared statement bound to a {@link SqliteClient}.
22
+ *
23
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
24
+ */
25
+ interface SqliteStatement$1 {
26
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
27
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
28
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
29
+ }
30
+ /**
31
+ * Sync SQLite client port owned by Emulates.
32
+ *
33
+ * Duck-typed so `@emulates/sqlite` `Database`, better-sqlite3, and wrapped
34
+ * `bun:sqlite` instances all work when they expose this surface.
35
+ */
36
+ interface SqliteClient$1 {
37
+ exec(sql: string): void;
38
+ prepare(sql: string): SqliteStatement$1;
39
+ transaction<T>(fn: () => T): T;
40
+ }
41
+
42
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
43
+ type Stored<T> = {
44
+ seq: number;
45
+ value: T;
46
+ };
47
+ type ListRecordsOptions<T> = {
48
+ /** Keep only records passing the predicate. */
49
+ where?: (value: T, seq: number) => boolean;
50
+ /** Sort order; default newest first. */
51
+ order?: "newest" | "oldest";
52
+ };
53
+ /**
54
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
55
+ * sequence, never by id lexicographic order, so list semantics stay stable.
56
+ */
57
+ declare class Collection<T> {
58
+ private readonly sqlite;
59
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
60
+ readonly namespace: string;
61
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
62
+ readonly collectionName: string;
63
+ constructor(sqlite: SqliteClient$1,
64
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
65
+ namespace: string,
66
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
67
+ collectionName: string);
68
+ private bumpCollectionSeq;
69
+ nextSequence(): number;
70
+ get(id: string): T | undefined;
71
+ has(id: string): boolean;
72
+ /** Insert a new record, assigning it the next sequence number. */
73
+ insert(id: string, value: T): Stored<T>;
74
+ /** Replace an existing record's value, keeping its position. */
75
+ update(id: string, value: T): Stored<T> | undefined;
76
+ delete(id: string): boolean;
77
+ /** How many records the collection holds, without reading them. */
78
+ count(): number;
79
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
80
+ id: string;
81
+ }>;
82
+ }
83
+
84
+ /**
85
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
86
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
87
+ */
88
+ declare class IdSequence {
89
+ private readonly sqlite;
90
+ private readonly namespace;
91
+ private readonly salt;
92
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
93
+ next(prefix: string, length?: number): string;
94
+ }
95
+
96
+ /** A stable identifier for a point in a {@link Timeline}. */
97
+ type CheckpointId = string;
98
+ /** An immutable node in a timeline's checkpoint DAG. */
99
+ type Checkpoint<T> = Readonly<{
100
+ id: CheckpointId;
101
+ branch: string;
102
+ parent: CheckpointId | null;
103
+ /** Logical time supplied by the timeline's injected clock. */
104
+ at: number;
105
+ value: T;
106
+ }>;
107
+ type TimelineOptions = {
108
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
109
+ now?: () => number;
110
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
111
+ maxCheckpoints?: number;
112
+ /** Customize deterministic checkpoint IDs. */
113
+ id?: (sequence: number) => CheckpointId;
114
+ };
115
+ type CommitOptions = {
116
+ branch?: string;
117
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
118
+ parent?: CheckpointId | null;
119
+ };
120
+ type ForkOptions = {
121
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
122
+ from?: CheckpointId;
123
+ };
124
+ /**
125
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
126
+ * records, namespace images, or copy-on-write SQL engine snapshots.
127
+ *
128
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
129
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
130
+ * (the logical clock) is injected.
131
+ */
132
+ declare class Timeline<T> {
133
+ readonly maxCheckpoints: number;
134
+ private readonly now;
135
+ private readonly makeId;
136
+ private readonly nodes;
137
+ private readonly heads;
138
+ /** Unreferenced nodes in the exact order they became collectible. */
139
+ private readonly evictable;
140
+ /** Branch heads plus explicit retainers. Absent means zero. */
141
+ private readonly references;
142
+ private readonly explicitPins;
143
+ private sequence;
144
+ constructor(options?: TimelineOptions);
145
+ /** Capture a new immutable value and move `branch` to it. */
146
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
147
+ /** Create a branch pointer without copying its checkpoint value. */
148
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
149
+ /** Move a branch pointer to an existing checkpoint. */
150
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
151
+ get(id: CheckpointId): Checkpoint<T>;
152
+ head(branch?: string): Checkpoint<T> | undefined;
153
+ hasBranch(branch: string): boolean;
154
+ branches(): Readonly<Record<string, CheckpointId>>;
155
+ checkpoints(): readonly Checkpoint<T>[];
156
+ /** Number of retained checkpoints without allocating an array. */
157
+ get size(): number;
158
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
159
+ retain(id: CheckpointId): Checkpoint<T>;
160
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
161
+ release(id: CheckpointId): boolean;
162
+ deleteBranch(branch: string): boolean;
163
+ /**
164
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
165
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
166
+ * storage dependency, so a retained node remains usable after pruning.
167
+ */
168
+ gc(max?: number): CheckpointId[];
169
+ private collect;
170
+ private moveHead;
171
+ private addReference;
172
+ private removeReference;
173
+ private assertBranch;
174
+ }
175
+
176
+ /**
177
+ * Anything that can answer a Fetch `Request` with a `Response`.
178
+ *
179
+ * Every Emulates service implements this, and every runtime adapter consumes it.
180
+ * It is the only contract shared across the whole graph.
181
+ */
182
+ interface FetchAPI {
183
+ fetch(request: Request): Promise<Response>;
184
+ }
185
+
186
+ /** Options every provider constructor accepts. */
187
+ type APIOptions = {
188
+ /** Sync SQLite client. Defaults to `@emulates/sqlite`. */
189
+ sqlite?: SqliteClient$1;
190
+ /** Clock used for `created`-style fields. Default `Date.now`. */
191
+ now?: () => number;
192
+ /**
193
+ * Storage namespace for this instance's records. Instances sharing one SQLite
194
+ * client stay isolated when their namespaces differ. Defaults to the service name.
195
+ */
196
+ namespace?: string;
197
+ };
198
+
199
+ /**
200
+ * The single source of time for a service.
201
+ *
202
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
203
+ * sleeping: appointment windows, result delays and expiries become reachable in
204
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
205
+ */
206
+ type ClockState = {
207
+ /** Current epoch milliseconds. */
208
+ now: number;
209
+ /** True while time does not advance on its own. */
210
+ frozen: boolean;
211
+ /** Milliseconds this clock adds to its underlying source. */
212
+ offsetMs: number;
213
+ };
214
+ type Clock = {
215
+ now(): number;
216
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
217
+ set(epochMs: number): void;
218
+ /** Move the clock forward, or back with a negative delta. */
219
+ advance(deltaMs: number): void;
220
+ /** Stop time at the current instant. */
221
+ freeze(): void;
222
+ /** Resume from the current instant. */
223
+ unfreeze(): void;
224
+ /** Drop back to the underlying source, live. */
225
+ reset(): void;
226
+ state(): ClockState;
227
+ };
228
+
229
+ /**
230
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
231
+ * request a percentage fault hits — is reproducible from a seed.
232
+ *
233
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
234
+ * than statistical quality.
235
+ */
236
+ type Rng = {
237
+ /** Next value in `[0, 1)`. */
238
+ next(): number;
239
+ /** Next integer in `[min, max]`. */
240
+ int(min: number, max: number): number;
241
+ /** Restart the stream from its seed. */
242
+ reset(): void;
243
+ /** Serializable engine state used by deterministic checkpoints. */
244
+ state(): number;
245
+ /** Restore a state previously returned by {@link state}. */
246
+ setState(state: number): void;
247
+ seed: number;
248
+ };
249
+
250
+ /**
251
+ * A deliberate failure injected in front of an operation.
252
+ *
253
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
254
+ * quota error that only appears when a shared sandbox is full, the 429 that only
255
+ * appears under load, the 5xx that proves a retry path works.
256
+ */
257
+ type FaultRule = {
258
+ /** Stable id, so a suite can retire exactly the rule it added. */
259
+ id: string;
260
+ /** Fault only this operation. Omit to match every operation. */
261
+ operationId?: string;
262
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
263
+ method?: string;
264
+ /** Fault only paths starting with this prefix. Omit to match every path. */
265
+ pathPrefix?: string;
266
+ /**
267
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
268
+ * an in-process caller usually wants, and what a parallel worker usually does not:
269
+ * rules added through `POST /__admin/faults` default to the calling namespace.
270
+ */
271
+ namespace?: string;
272
+ /**
273
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
274
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
275
+ * the request then still reaches the service.
276
+ */
277
+ status?: number;
278
+ /** Response body, serialized as JSON. A string is sent as-is. */
279
+ body?: unknown;
280
+ headers?: Record<string, string>;
281
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
282
+ count?: number;
283
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
284
+ rate?: number;
285
+ /** Hold the response back this long, to exercise timeouts. */
286
+ delayMs?: number;
287
+ /** Alias of `delayMs`. */
288
+ latencyMs?: number;
289
+ /**
290
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
291
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
292
+ */
293
+ drop?: boolean;
294
+ /**
295
+ * A named service behaviour to switch on for the matching request instead of (or
296
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
297
+ * read it with `faultEffects(request)`.
298
+ */
299
+ effect?: string;
300
+ /** Parameters for `effect`. */
301
+ params?: Record<string, unknown>;
302
+ /** From the preset this rule was expanded from, if any. */
303
+ preset?: string;
304
+ };
305
+ /** A fault that fired for one request. */
306
+ type FaultHit = {
307
+ id: string;
308
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
309
+ response?: Response;
310
+ drop?: boolean;
311
+ effect?: {
312
+ name: string;
313
+ params: Record<string, unknown>;
314
+ };
315
+ };
316
+ /**
317
+ * A named, documented fault a suite switches on by name
318
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
319
+ * webhook delivery fault.
320
+ */
321
+ type FaultPreset = {
322
+ description: string;
323
+ rules?: Omit<FaultRule, "id">[];
324
+ webhook?: {
325
+ mode: "duplicate" | "reorder" | "drop";
326
+ count?: number;
327
+ };
328
+ };
329
+ /** What a request looks like to the fault matcher. */
330
+ type FaultCandidate = {
331
+ operationId: string | undefined;
332
+ method: string;
333
+ path: string;
334
+ namespace: string;
335
+ };
336
+ type FaultRegistry = {
337
+ isolateNamespaces(): void;
338
+ snapshot(namespace: string): {
339
+ rules: (FaultRule & {
340
+ remaining: number | null;
341
+ hits: number;
342
+ position: number;
343
+ })[];
344
+ rngState: number;
345
+ };
346
+ add(rule: FaultRule): FaultRule;
347
+ list(): (FaultRule & {
348
+ remaining: number | null;
349
+ hits: number;
350
+ })[];
351
+ remove(id: string): boolean;
352
+ clear(): void;
353
+ restore(namespace: string, state: {
354
+ rules: (FaultRule & {
355
+ remaining: number | null;
356
+ hits: number;
357
+ position: number;
358
+ })[];
359
+ rngState: number;
360
+ }): void;
361
+ /**
362
+ * Every fault this request should get, in rule order, stopping at the first that answers
363
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
364
+ * each matching rule's remaining uses.
365
+ */
366
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
367
+ };
368
+
369
+ /**
370
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
371
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
372
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
373
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
374
+ */
375
+ type BodyIssue = {
376
+ path: string;
377
+ message: string;
378
+ kind?: "media_type" | "syntax" | "required" | "schema";
379
+ };
380
+
381
+ /**
382
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
383
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
384
+ */
385
+ type RejectedRequest = {
386
+ /** The raw `content-type` header, or `null` when the request sent none. */
387
+ contentType: string | null;
388
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
389
+ bodyBytes: number | null;
390
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
391
+ transferEncoding: string | null;
392
+ };
393
+ /** One handled request, as the structured log sees it. */
394
+ type RequestLog = {
395
+ service: string;
396
+ namespace: string;
397
+ operationId: string | undefined;
398
+ method: string;
399
+ path: string;
400
+ status: number;
401
+ durationMs: number;
402
+ /** True when the path matched no operation in the contract. */
403
+ unmatched: boolean;
404
+ /** Set when a fault rule produced the response. */
405
+ faultId?: string;
406
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
407
+ ids?: Record<string, string>;
408
+ /** Set when the service created a resource the request referred to but that did not exist. */
409
+ adopted?: boolean;
410
+ /** Explicit durable acceptance, independent of response delivery. */
411
+ accepted?: boolean;
412
+ /** Checkpoint captured at explicit acceptance. */
413
+ checkpoint?: string;
414
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
415
+ request?: RejectedRequest;
416
+ /** The validation issues behind a rejection, when the service found any. */
417
+ issues?: BodyIssue[];
418
+ };
419
+ type MetricsReport = {
420
+ requests: number;
421
+ /** Counts keyed `<operationId> <status>`. */
422
+ byOperation: Record<string, number>;
423
+ /**
424
+ * Paths that matched no operation, most frequent first.
425
+ *
426
+ * This is the early-warning signal: a consumer calling something the mock does
427
+ * not implement shows up here as a count, before it fails a suite as a 404.
428
+ */
429
+ unmatched: {
430
+ method: string;
431
+ path: string;
432
+ count: number;
433
+ }[];
434
+ faults: number;
435
+ totalDurationMs: number;
436
+ };
437
+ type Metrics = {
438
+ record(entry: RequestLog): void;
439
+ report(namespace?: string): MetricsReport;
440
+ reset(namespace?: string): void;
441
+ };
442
+
443
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
444
+ type JournalEntry = RequestLog & {
445
+ at: string;
446
+ };
447
+ type JournalQuery = {
448
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
449
+ namespace?: string;
450
+ operationId?: string;
451
+ status?: number;
452
+ /** Only entries at or after this instant (epoch ms). */
453
+ since?: number;
454
+ /** At most this many, the most recent kept. */
455
+ limit?: number;
456
+ };
457
+ type Journal = {
458
+ readonly size: number;
459
+ record(entry: JournalEntry): void;
460
+ list(query?: JournalQuery): JournalEntry[];
461
+ /** Forget one namespace's entries, or every namespace's. */
462
+ clear(namespace?: string): void;
463
+ };
464
+
465
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
466
+ type CredentialRegistry = {
467
+ set(credential: string, namespace: string): void;
468
+ get(credential: string): string | undefined;
469
+ remove(credential: string): boolean;
470
+ clear(): void;
471
+ entries(): {
472
+ credential: string;
473
+ namespace: string;
474
+ }[];
475
+ };
476
+
477
+ /**
478
+ * A point-in-time copy of everything a service namespace holds.
479
+ *
480
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
481
+ * is generic: any service gets per-test rollback without knowing its own schema.
482
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
483
+ */
484
+ type NamespaceSnapshot = {
485
+ namespace: string;
486
+ records: {
487
+ collection: string;
488
+ id: string;
489
+ seq: number;
490
+ value: string;
491
+ }[];
492
+ sequences: {
493
+ name: string;
494
+ kind: string;
495
+ value: number;
496
+ }[];
497
+ };
498
+
499
+ declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
500
+ type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
501
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
502
+ type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
503
+ type StateField = {
504
+ name: string;
505
+ kind: StateFieldKind;
506
+ optional: boolean;
507
+ description?: string;
508
+ /** One level of nested object fields. */
509
+ fields?: StateField[];
510
+ meta?: StateMeta;
511
+ };
512
+ type StateCollectionView = {
513
+ name: string;
514
+ label: string;
515
+ description?: string;
516
+ count: number;
517
+ /** `mixed` when a declaration and stored rows both contribute fields. */
518
+ source: "declared" | "inferred" | "mixed";
519
+ fields: StateField[];
520
+ meta?: StateMeta;
521
+ };
522
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
523
+ type StateView = {
524
+ namespace: string;
525
+ storageNamespace: string;
526
+ collections: StateCollectionView[];
527
+ };
528
+
529
+ /**
530
+ * Outbound webhooks, shared by every service that has them.
531
+ *
532
+ * A service publishes a message (the exact bytes the vendor would send); the hub fans it out
533
+ * to every matching endpoint, signs each delivery with the vendor's scheme, retries on the
534
+ * vendor's schedule, and keeps a record a suite can read, replay or flush through
535
+ * `/__admin/webhooks*`. Signature timestamps use the wall clock unless a service injects
536
+ * `now`: receivers check them against their own time, and an advanced mock clock would
537
+ * otherwise fail every delivery. A service whose caller injected the clock (Stripe) passes it,
538
+ * so a virtual-time receiver verifies at the mock's time.
539
+ */
540
+ /** What a signer sees for one delivery attempt. */
541
+ type SignInput = {
542
+ messageId: string;
543
+ /** Exact bytes about to be sent. */
544
+ body: string;
545
+ /** Unix seconds of this attempt: wall clock, or the hub's injected `now`. */
546
+ timestampSeconds: number;
547
+ /** Where the delivery is posted. */
548
+ url: string;
549
+ /** The endpoint's secret, if it has one. */
550
+ secret: string | undefined;
551
+ /** The endpoint's `signUrl` (the public URL the receiver verifies against), else `url`. */
552
+ signUrl: string;
553
+ /** Form parameters, when the body is form-encoded (Twilio signs these, not the body). */
554
+ form: Record<string, string> | undefined;
555
+ /** Stable event type and metadata captured with the message; avoids signer side-channel state. */
556
+ type: string;
557
+ tags: Readonly<Record<string, string>>;
558
+ };
559
+ /** Headers to add to one delivery. */
560
+ type WebhookSigner = (input: SignInput) => Record<string, string> | Promise<Record<string, string>>;
561
+ type WebhookEndpoint = {
562
+ /** Stable id; generated when omitted. */
563
+ id?: string;
564
+ url: string;
565
+ secret?: string;
566
+ /** Event types to deliver; omit or include `"*"` for every type. */
567
+ events?: string[];
568
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
569
+ tags?: Record<string, string>;
570
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
571
+ signUrl?: string;
572
+ headers?: Record<string, string>;
573
+ };
574
+ type WebhookMessage = {
575
+ id: string;
576
+ namespace: string;
577
+ type: string;
578
+ body: string;
579
+ contentType: string;
580
+ tags: Record<string, string>;
581
+ headers?: Record<string, string>;
582
+ /** Wall-clock ISO-8601 time of publication. */
583
+ publishedAt: string;
584
+ };
585
+ type WebhookAttempt = {
586
+ attempt: number;
587
+ at: string;
588
+ status: number | null;
589
+ error: string | null;
590
+ durationMs: number;
591
+ /** Exact receiver response body, when one was returned. */
592
+ responseBody?: string | null;
593
+ };
594
+ type WebhookDelivery$1 = {
595
+ id: string;
596
+ messageId: string;
597
+ namespace: string;
598
+ type: string;
599
+ endpointId: string;
600
+ url: string;
601
+ state: "pending" | "delivered" | "failed" | "dropped";
602
+ attempts: WebhookAttempt[];
603
+ };
604
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
605
+ type WebhookFault = {
606
+ mode: "duplicate" | "reorder" | "drop";
607
+ /** Messages affected; default 1. */
608
+ count?: number;
609
+ };
610
+ type PublishInput = {
611
+ namespace: string;
612
+ type: string;
613
+ /** Exact body; objects are JSON-encoded. */
614
+ body: string | Record<string, unknown> | unknown[];
615
+ /** Default `application/json`, or form-encoded when `form` is given. */
616
+ contentType?: string;
617
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
618
+ form?: Record<string, string>;
619
+ tags?: Record<string, string>;
620
+ /** Message-specific delivery headers, captured as part of durable message state. */
621
+ headers?: Record<string, string>;
622
+ /** Message id; generated when omitted. */
623
+ id?: string;
624
+ };
625
+ type WebhookHub = {
626
+ pending(namespace: string): number;
627
+ snapshot(namespace: string): unknown;
628
+ restore(namespace: string, snapshot: unknown): void;
629
+ publish(input: PublishInput): WebhookMessage;
630
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
631
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
632
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
633
+ endpoints(namespace: string): WebhookEndpoint[];
634
+ messages(namespace?: string): WebhookMessage[];
635
+ deliveries(namespace?: string): WebhookDelivery$1[];
636
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
637
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
638
+ flush(): Promise<void>;
639
+ /** Resolve once nothing is in flight. */
640
+ idle(): Promise<void>;
641
+ fault(namespace: string, fault: WebhookFault): void;
642
+ clear(namespace?: string): void;
643
+ };
644
+
645
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
646
+ type ServiceInstance = FetchAPI & {
647
+ reset(): Promise<void>;
648
+ };
649
+ type ServiceTimelineState = Readonly<{
650
+ snapshot: NamespaceSnapshot;
651
+ clock: Readonly<ReturnType<Clock["state"]>>;
652
+ rngState: number;
653
+ }>;
654
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
655
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
656
+ /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
657
+ stop?(): void;
658
+ readonly name: string;
659
+ readonly sqlite: SqliteClient$1;
660
+ readonly clock: Clock;
661
+ readonly faults: FaultRegistry;
662
+ readonly metrics: Metrics;
663
+ readonly journal: Journal;
664
+ readonly rng: Rng;
665
+ readonly credentials: CredentialRegistry;
666
+ /** The webhook hub, when the service has outbound webhooks. */
667
+ readonly webhooks: WebhookHub | undefined;
668
+ /** Enable independent namespace clocks and PRNGs before serving a fleet. */
669
+ isolateNamespaces(): void;
670
+ namespaceClock(namespace?: string): Clock;
671
+ namespaceOf(request: Request): string;
672
+ /** Opaque in-process checkpoint including records, controls and webhook history. */
673
+ fleetSnapshot(namespace: string): object;
674
+ fleetRestore(snapshot: unknown, namespace: string): void;
675
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
676
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
677
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
678
+ instance(namespace?: string): T;
679
+ /** Public names of every namespace created so far. */
680
+ namespaces(): string[];
681
+ /** Reset one namespace, or every namespace with `"*"`. */
682
+ reset(namespace?: string): Promise<void>;
683
+ snapshot(namespace?: string): NamespaceSnapshot;
684
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
685
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
686
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
687
+ /** Create an isolated branch, optionally from a historical checkpoint. */
688
+ branch(name: string, options?: {
689
+ namespace?: string;
690
+ at?: string;
691
+ }): ServiceCheckpoint;
692
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
693
+ checkout(checkpoint: string, options?: {
694
+ namespace?: string;
695
+ branch?: string;
696
+ }): void;
697
+ /** Inspect the retained history for a namespace. */
698
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
699
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
700
+ state(namespace?: string): StateView;
701
+ };
702
+
703
+ /**
704
+ * A minimal S3 `PutObject` for mocks whose vendor hands the app an `s3://` object (GxG
705
+ * results, Daily transcripts): the mock writes the object into the stack's local S3
706
+ * (s3rver, MinIO) so the app's own `GetObject` / `CopyObject` finds it. Path-style
707
+ * addressing, SigV4-signed, no SDK.
708
+ */
709
+ type S3Target = {
710
+ /** e.g. `http://127.0.0.1:4569`. */
711
+ endpoint: string;
712
+ bucket: string;
713
+ region?: string;
714
+ accessKeyId?: string;
715
+ secretAccessKey?: string;
716
+ fetch?: (request: Request) => Promise<Response>;
717
+ };
718
+
719
+ /** Bind values accepted by the Emulates SQLite port (matches sqlite-mem / better-sqlite3). */
720
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
721
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
722
+ type SqliteRunResult = {
723
+ changes: number;
724
+ lastInsertRowid: number | bigint;
725
+ };
726
+ /**
727
+ * Prepared statement bound to a {@link SqliteClient}.
728
+ *
729
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
730
+ */
731
+ interface SqliteStatement {
732
+ run(...params: SqliteValue[]): SqliteRunResult;
733
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
734
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
735
+ }
736
+ /**
737
+ * Sync SQLite client port owned by Emulates.
738
+ *
739
+ * Duck-typed so `@emulates/sqlite` `Database`, better-sqlite3, and wrapped
740
+ * `bun:sqlite` instances all work when they expose this surface.
741
+ */
742
+ interface SqliteClient {
743
+ exec(sql: string): void;
744
+ prepare(sql: string): SqliteStatement;
745
+ transaction<T>(fn: () => T): T;
746
+ }
747
+
748
+ type PresenceRecord = {
749
+ /** Daily's participant session id. */
750
+ id: string;
751
+ userId: string;
752
+ userName: string;
753
+ /** Mock-clock epoch ms the participant joined. */
754
+ joinedAtMs: number;
755
+ };
756
+ type SessionRecord = {
757
+ sessionId: string;
758
+ durationSec: number;
759
+ participants: number;
760
+ /** `s3://bucket/key` of the transcript, when S3 is configured. */
761
+ transcript: string | null;
762
+ endedAt: string;
763
+ };
764
+ /** One room as Daily tracks it: the properties it was given, echoed back as `config`. */
765
+ type RoomRecord = {
766
+ id: string;
767
+ name: string;
768
+ privacy: "public" | "private";
769
+ url: string;
770
+ created_at: string;
771
+ config: Record<string, unknown>;
772
+ presence: PresenceRecord[];
773
+ sessions: SessionRecord[];
774
+ };
775
+ /** Something odd a caller sent that the mock tolerated (Daily would too, or would misread it). */
776
+ type WarningRecord = {
777
+ at: string;
778
+ operationId: string;
779
+ subject: string;
780
+ field: string;
781
+ value: unknown;
782
+ message: string;
783
+ };
784
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
785
+ type Settings = {
786
+ /** Accepted `DAILY_API_KEY`s. Empty: any bearer key is accepted. */
787
+ apiKeys: string[];
788
+ /** `DAILY_API_DOMAIN_ID`, stamped as `d` in minted tokens and checked in decoded ones. */
789
+ domainId: string;
790
+ /** Room URLs are `<roomUrlBase><name>` (`https://<domain>.daily.co/`). */
791
+ roomUrlBase: string;
792
+ };
793
+ declare class DailyState {
794
+ private readonly seed;
795
+ readonly rooms: Collection<RoomRecord>;
796
+ readonly warnings: Collection<WarningRecord>;
797
+ readonly settings: Collection<Settings>;
798
+ readonly ids: IdSequence;
799
+ constructor(sqlite: SqliteClient, namespace: string, seed: Partial<Settings>);
800
+ ensureSeeded(): void;
801
+ current(): Settings;
802
+ update(patch: Partial<Settings>): Settings;
803
+ warn(warning: WarningRecord): void;
804
+ /** A Daily-style random room name (20 alphanumerics), deterministic per sequence. */
805
+ nextRoomName(): string;
806
+ /** A UUID-shaped id, deterministic per sequence. */
807
+ nextUuid(kind: string): string;
808
+ }
809
+
810
+ /**
811
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Emulates understands.
812
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
813
+ */
814
+ type JsonPrimitive = string | number | boolean | null;
815
+ type JsonValue = JsonPrimitive | JsonValue[] | {
816
+ [key: string]: JsonValue;
817
+ };
818
+ type ReferenceObject = {
819
+ $ref: string;
820
+ description?: string;
821
+ summary?: string;
822
+ };
823
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
824
+ type SchemaObject = {
825
+ $ref?: string;
826
+ type?: SchemaType | SchemaType[];
827
+ title?: string;
828
+ description?: string;
829
+ format?: string;
830
+ enum?: JsonValue[];
831
+ const?: JsonValue;
832
+ default?: JsonValue;
833
+ example?: JsonValue;
834
+ examples?: JsonValue[];
835
+ nullable?: boolean;
836
+ deprecated?: boolean;
837
+ readOnly?: boolean;
838
+ writeOnly?: boolean;
839
+ minimum?: number;
840
+ maximum?: number;
841
+ exclusiveMinimum?: number;
842
+ exclusiveMaximum?: number;
843
+ multipleOf?: number;
844
+ minLength?: number;
845
+ maxLength?: number;
846
+ pattern?: string;
847
+ minItems?: number;
848
+ maxItems?: number;
849
+ uniqueItems?: boolean;
850
+ items?: SchemaObject;
851
+ prefixItems?: SchemaObject[];
852
+ minProperties?: number;
853
+ maxProperties?: number;
854
+ required?: string[];
855
+ properties?: Record<string, SchemaObject>;
856
+ additionalProperties?: boolean | SchemaObject;
857
+ propertyNames?: SchemaObject;
858
+ oneOf?: SchemaObject[];
859
+ anyOf?: SchemaObject[];
860
+ allOf?: SchemaObject[];
861
+ not?: SchemaObject;
862
+ discriminator?: {
863
+ propertyName: string;
864
+ mapping?: Record<string, string>;
865
+ };
866
+ [extension: `x-${string}`]: unknown;
867
+ };
868
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
869
+ type ParameterObject = {
870
+ name: string;
871
+ in: ParameterLocation;
872
+ description?: string;
873
+ required?: boolean;
874
+ deprecated?: boolean;
875
+ style?: string;
876
+ explode?: boolean;
877
+ schema?: SchemaObject;
878
+ content?: Record<string, MediaTypeObject>;
879
+ example?: JsonValue;
880
+ [extension: `x-${string}`]: unknown;
881
+ };
882
+ type MediaTypeObject = {
883
+ schema?: SchemaObject;
884
+ example?: JsonValue;
885
+ examples?: Record<string, unknown>;
886
+ encoding?: Record<string, unknown>;
887
+ [extension: `x-${string}`]: unknown;
888
+ };
889
+ type RequestBodyObject = {
890
+ description?: string;
891
+ required?: boolean;
892
+ content: Record<string, MediaTypeObject>;
893
+ [extension: `x-${string}`]: unknown;
894
+ };
895
+ type HeaderObject = {
896
+ description?: string;
897
+ required?: boolean;
898
+ schema?: SchemaObject;
899
+ [extension: `x-${string}`]: unknown;
900
+ };
901
+ type ResponseObject = {
902
+ description: string;
903
+ headers?: Record<string, HeaderObject | ReferenceObject>;
904
+ content?: Record<string, MediaTypeObject>;
905
+ [extension: `x-${string}`]: unknown;
906
+ };
907
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
908
+ type SecurityRequirementObject = Record<string, string[]>;
909
+ type OperationObject = {
910
+ operationId?: string;
911
+ summary?: string;
912
+ description?: string;
913
+ tags?: string[];
914
+ deprecated?: boolean;
915
+ parameters?: Array<ParameterObject | ReferenceObject>;
916
+ requestBody?: RequestBodyObject | ReferenceObject;
917
+ responses: ResponsesObject;
918
+ security?: SecurityRequirementObject[];
919
+ [extension: `x-${string}`]: unknown;
920
+ };
921
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
922
+ type HttpMethod = (typeof HTTP_METHODS)[number];
923
+ type PathItemObject = {
924
+ summary?: string;
925
+ description?: string;
926
+ parameters?: Array<ParameterObject | ReferenceObject>;
927
+ [extension: `x-${string}`]: unknown;
928
+ } & Partial<Record<HttpMethod, OperationObject>>;
929
+ type SecuritySchemeObject = {
930
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
931
+ description?: string;
932
+ name?: string;
933
+ in?: ParameterLocation;
934
+ scheme?: string;
935
+ bearerFormat?: string;
936
+ flows?: Record<string, unknown>;
937
+ openIdConnectUrl?: string;
938
+ [extension: `x-${string}`]: unknown;
939
+ };
940
+ type ComponentsObject = {
941
+ schemas?: Record<string, SchemaObject>;
942
+ responses?: Record<string, ResponseObject>;
943
+ parameters?: Record<string, ParameterObject>;
944
+ requestBodies?: Record<string, RequestBodyObject>;
945
+ headers?: Record<string, HeaderObject>;
946
+ securitySchemes?: Record<string, SecuritySchemeObject>;
947
+ [extension: `x-${string}`]: unknown;
948
+ };
949
+ type ServerObject = {
950
+ url: string;
951
+ description?: string;
952
+ variables?: Record<string, unknown>;
953
+ [extension: `x-${string}`]: unknown;
954
+ };
955
+ type InfoObject = {
956
+ title: string;
957
+ version: string;
958
+ description?: string;
959
+ [extension: `x-${string}`]: unknown;
960
+ };
961
+ type OpenAPIDocument = {
962
+ openapi: string;
963
+ info: InfoObject;
964
+ servers?: ServerObject[];
965
+ paths: Record<string, PathItemObject>;
966
+ components?: ComponentsObject;
967
+ security?: SecurityRequirementObject[];
968
+ tags?: Array<{
969
+ name: string;
970
+ description?: string;
971
+ }>;
972
+ [extension: `x-${string}`]: unknown;
973
+ };
974
+
975
+ declare const document: OpenAPIDocument;
976
+ type OperationId = "ListRooms" | "CreateRoom" | "GetRoom" | "UpdateRoom" | "DeleteRoom" | "GetRoomPresence" | "EjectParticipants" | "CreateMeetingToken" | "ValidateMeetingToken";
977
+ type SupportedOperationId = "ListRooms" | "CreateRoom" | "GetRoom" | "UpdateRoom" | "DeleteRoom" | "GetRoomPresence" | "EjectParticipants" | "CreateMeetingToken" | "ValidateMeetingToken";
978
+ declare const operationIds: readonly ["ListRooms", "CreateRoom", "GetRoom", "UpdateRoom", "DeleteRoom", "GetRoomPresence", "EjectParticipants", "CreateMeetingToken", "ValidateMeetingToken"];
979
+ declare const supportedOperationIds: readonly ["ListRooms", "CreateRoom", "GetRoom", "UpdateRoom", "DeleteRoom", "GetRoomPresence", "EjectParticipants", "CreateMeetingToken", "ValidateMeetingToken"];
980
+
981
+ /**
982
+ * Daily meeting tokens are HS256 JWTs signed with the domain's API key, their claims using
983
+ * Daily's abbreviated property names. Our backend mints its own (self-signed) tokens the same
984
+ * way, so the mock signs and verifies with the same scheme.
985
+ */
986
+ /** Full property name → abbreviated JWT claim, as Daily documents them. */
987
+ declare const CLAIM_NAMES: Record<string, string>;
988
+ /** Claims → full property names (unknown claims keep their name). */
989
+ declare const claimsToProperties: (claims: Record<string, unknown>) => Record<string, unknown>;
990
+ /** Full property names → claims (properties without an abbreviation keep their name). */
991
+ declare const propertiesToClaims: (properties: Record<string, unknown>) => Record<string, unknown>;
992
+ /** Sign `claims` as an HS256 JWT with `key` (the Daily API key). */
993
+ declare const signToken: (claims: Record<string, unknown>, key: string) => Promise<string>;
994
+ type DecodedToken = {
995
+ header: Record<string, unknown>;
996
+ claims: Record<string, unknown>;
997
+ /** The signed part and the signature, for verification. */
998
+ signingInput: string;
999
+ signature: string;
1000
+ };
1001
+ /** Split and parse a JWT without verifying it; `undefined` when it is not a JWT at all. */
1002
+ declare const decodeToken: (token: string) => DecodedToken | undefined;
1003
+ /** Whether `decoded` is an HS256 token signed with `key`. */
1004
+ declare const verifySignature: (decoded: DecodedToken, key: string) => Promise<boolean>;
1005
+
1006
+ /** Where our EMR receives Daily webhooks. */
1007
+ declare const WEBHOOK_PATH = "/v1/webhooks/daily";
1008
+ /**
1009
+ * Every named Daily misbehaviour our consumers branch on, switched on with
1010
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it).
1011
+ */
1012
+ declare const DAILY_PRESETS: Record<string, FaultPreset>;
1013
+ /**
1014
+ * Our EMR's scheme: `x-webhook-signature` = hex HMAC-SHA256(DAILY_WEBHOOK_SECRET, rawBody).
1015
+ * (Daily's documented scheme differs: base64 HMAC over `"<timestamp>.<body>"` with a
1016
+ * base64-decoded secret. See the README.) `x-webhook-timestamp` rides along.
1017
+ */
1018
+ declare const dailyWebhookSigner: WebhookSigner;
1019
+ type WebhookDelivery = {
1020
+ retryDelaysMs?: readonly number[];
1021
+ fetch?: (request: Request) => Promise<Response>;
1022
+ };
1023
+ type DailyRuntimeOptions = {
1024
+ sqlite?: SqliteClient;
1025
+ clock?: Clock;
1026
+ seed?: number | string;
1027
+ adminPrefix?: string;
1028
+ adminKey?: string;
1029
+ onLog?: (entry: RequestLog) => void;
1030
+ settings?: Partial<Settings>;
1031
+ /** Where webhooks go (`POST /v1/webhooks/daily`); `secret` is `DAILY_WEBHOOK_SECRET`. */
1032
+ webhooks?: Omit<WebhookEndpoint, "id"> & WebhookDelivery;
1033
+ /** Where admin sessions write transcripts (the stack's s3rver). */
1034
+ transcripts?: TranscriptStore;
1035
+ };
1036
+ type DailyRuntime = ServiceRuntime<DailyAPI> & {
1037
+ readonly webhooks: WebhookHub;
1038
+ };
1039
+ /**
1040
+ * The Daily emulator with the full Emulates service contract: `/__admin/health`, `/__admin/*`, namespaces
1041
+ * by header, by `/__admin/ns/<name>` prefix on `DAILY_API_BASE_URL`, or by API key
1042
+ * (`PUT /__admin/credentials {"credentials": {"<DAILY_API_KEY>": "<namespace>"}}`), clock
1043
+ * control, fault presets, signed webhooks and a request journal.
1044
+ */
1045
+ declare const createRuntime: (options?: DailyRuntimeOptions) => DailyRuntime;
1046
+
1047
+ declare const DAILY_NAMESPACE = "daily";
1048
+ /** The transcript object our scribe reads from S3: `[{s: speaker userId, t, ts, te}]`. */
1049
+ type TranscriptEntry = {
1050
+ s: string;
1051
+ t: string;
1052
+ ts: number;
1053
+ te: number;
1054
+ };
1055
+ /** A Daily webhook event (`transcription.stopped`, `recording.ready-to-download`). */
1056
+ type DailyWebhook = {
1057
+ version: string;
1058
+ type: string;
1059
+ /** Our receiver reads `event`; Daily's documented envelope says `type`. Both are sent. */
1060
+ event: string;
1061
+ id: string;
1062
+ event_ts: number;
1063
+ payload: Record<string, unknown>;
1064
+ };
1065
+ type SessionInput = {
1066
+ participants: {
1067
+ userId: string;
1068
+ userName?: string;
1069
+ }[];
1070
+ durationSec: number;
1071
+ /** The transcript to write; a synthetic one alternating between participants when omitted. */
1072
+ transcript?: TranscriptEntry[];
1073
+ sessionId?: string;
1074
+ /** Also emit `recording.ready-to-download`. Default true. */
1075
+ recording?: boolean;
1076
+ };
1077
+ type SessionResult = {
1078
+ sessionId: string;
1079
+ s3Key: string;
1080
+ /** `s3://bucket/key`, or `null` when no S3 target is configured. */
1081
+ transcript: string | null;
1082
+ events: string[];
1083
+ };
1084
+ /** Where `POST /__admin/rooms/:name/session` writes transcripts (the stack's s3rver / MinIO). */
1085
+ type TranscriptStore = S3Target & {
1086
+ /** Default `{roomName}/{sessionId}.json` (the EMR's `DAILY_TRANSCRIPT_S3_KEY_PATTERN`). */
1087
+ keyPattern?: string;
1088
+ };
1089
+ type TokenInspection = {
1090
+ /** Parsed as a JWT at all. */
1091
+ decodable: boolean;
1092
+ header: Record<string, unknown> | null;
1093
+ claims: Record<string, unknown> | null;
1094
+ properties: Record<string, unknown> | null;
1095
+ /** `true`/`false` when a key was available to check with, else `null`. */
1096
+ signatureValid: boolean | null;
1097
+ room: {
1098
+ name: string;
1099
+ exists: boolean;
1100
+ nbf: number | null;
1101
+ exp: number | null;
1102
+ } | null;
1103
+ /** Whether the token would admit its holder now (signature, token window, room window). */
1104
+ joinable: boolean;
1105
+ problems: string[];
1106
+ warnings: string[];
1107
+ };
1108
+ type DailyAPIOptions = APIOptions & {
1109
+ settings?: Partial<Settings>;
1110
+ /** Called for every webhook event; the runtime signs and delivers it. */
1111
+ onWebhook?: (event: DailyWebhook) => void;
1112
+ /** Transcript destination for admin sessions. */
1113
+ transcripts?: TranscriptStore;
1114
+ };
1115
+ /**
1116
+ * Stateful mock of the Daily.co REST API.
1117
+ *
1118
+ * Rooms echo the properties they were given as `config`; tokens are HS256 JWTs signed with
1119
+ * the caller's API key (like Daily's, and like the ones our backend self-signs), so any of
1120
+ * them can be verified and decoded. Media never flows: presence and sessions are set by
1121
+ * admin routes.
1122
+ */
1123
+ declare class DailyAPI implements FetchAPI$1 {
1124
+ readonly app: Hono;
1125
+ readonly sqlite: SqliteClient;
1126
+ readonly state: DailyState;
1127
+ private readonly service;
1128
+ private readonly now;
1129
+ private readonly onWebhook;
1130
+ private readonly transcripts;
1131
+ constructor(options?: DailyAPIOptions);
1132
+ fetch(request: Request): Promise<Response>;
1133
+ reset(): Promise<void>;
1134
+ private iso;
1135
+ private nowSeconds;
1136
+ /** Validate the body against the contract, as Daily's `invalid-request-error`. */
1137
+ private validate;
1138
+ /** Journal (and keep) a warning for each nbf/exp that is really milliseconds. */
1139
+ private checkTimes;
1140
+ private withRoom;
1141
+ private createRoom;
1142
+ private listRooms;
1143
+ private updateRoom;
1144
+ private deleteRoom;
1145
+ private eject;
1146
+ private createToken;
1147
+ private validateToken;
1148
+ /**
1149
+ * Everything the mock can say about a token: decoded claims, signature (checked against
1150
+ * `keys`, else the namespace's `apiKeys`), the backend's strict claim schema, millisecond
1151
+ * timestamps, and the token/room time windows on the mock clock.
1152
+ */
1153
+ inspectToken(token: string, keys?: readonly string[]): Promise<TokenInspection>;
1154
+ /** Put participants in a room (what `GET /v1/rooms/:name/presence` reports). */
1155
+ setPresence(name: string, participants: {
1156
+ userId: string;
1157
+ userName?: string;
1158
+ joinedAt?: string | number;
1159
+ }[]): RoomRecord | undefined;
1160
+ /**
1161
+ * End a call: write the transcript to S3 at `{room}/{session}.json`, then emit
1162
+ * `transcription.stopped` (and `recording.ready-to-download`). The transcript text is
1163
+ * never kept in the mock's state.
1164
+ */
1165
+ endSession(name: string, input: SessionInput): Promise<SessionResult | undefined>;
1166
+ rooms(): RoomRecord[];
1167
+ }
1168
+ /** A plausible transcript alternating between the participants across `durationSec`. */
1169
+ declare const synthesizeTranscript: (participants: {
1170
+ userId: string;
1171
+ }[], durationSec: number) => TranscriptEntry[];
1172
+
1173
+ export { CLAIM_NAMES, DAILY_NAMESPACE, DAILY_PRESETS, DailyAPI, WEBHOOK_PATH, claimsToProperties, createRuntime, dailyWebhookSigner, decodeToken, document, operationIds, propertiesToClaims, signToken, supportedOperationIds, synthesizeTranscript, verifySignature };
1174
+ export type { DailyAPIOptions, DailyRuntime, DailyRuntimeOptions, DailyWebhook, FetchAPI$1 as FetchAPI, OperationId, PresenceRecord, RoomRecord, S3Target, SessionInput, SessionRecord, SessionResult, Settings, SqliteClient, SupportedOperationId, TokenInspection, TranscriptEntry, TranscriptStore, WarningRecord };