@crvouga/mockingbird-service-edamam 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,988 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /**
14
+ * The single source of time for a service.
15
+ *
16
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
17
+ * sleeping: appointment windows, result delays and expiries become reachable in
18
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
19
+ */
20
+ type ClockState = {
21
+ /** Current epoch milliseconds. */
22
+ now: number;
23
+ /** True while time does not advance on its own. */
24
+ frozen: boolean;
25
+ /** Milliseconds this clock adds to its underlying source. */
26
+ offsetMs: number;
27
+ };
28
+ type Clock = {
29
+ now(): number;
30
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
31
+ set(epochMs: number): void;
32
+ /** Move the clock forward, or back with a negative delta. */
33
+ advance(deltaMs: number): void;
34
+ /** Stop time at the current instant. */
35
+ freeze(): void;
36
+ /** Resume from the current instant. */
37
+ unfreeze(): void;
38
+ /** Drop back to the underlying source, live. */
39
+ reset(): void;
40
+ state(): ClockState;
41
+ };
42
+
43
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
45
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
46
+ type SqliteRunResult$1 = {
47
+ changes: number;
48
+ lastInsertRowid: number | bigint;
49
+ };
50
+ /**
51
+ * Prepared statement bound to a {@link SqliteClient}.
52
+ *
53
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
+ */
55
+ interface SqliteStatement$1 {
56
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
57
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
58
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
59
+ }
60
+ /**
61
+ * Sync SQLite client port owned by Mockingbird.
62
+ *
63
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
+ * `bun:sqlite` instances all work when they expose this surface.
65
+ */
66
+ interface SqliteClient$1 {
67
+ exec(sql: string): void;
68
+ prepare(sql: string): SqliteStatement$1;
69
+ transaction<T>(fn: () => T): T;
70
+ }
71
+
72
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
+ type Stored<T> = {
74
+ seq: number;
75
+ value: T;
76
+ };
77
+ type ListRecordsOptions<T> = {
78
+ /** Keep only records passing the predicate. */
79
+ where?: (value: T, seq: number) => boolean;
80
+ /** Sort order; default newest first. */
81
+ order?: "newest" | "oldest";
82
+ };
83
+ /**
84
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
+ * sequence, never by id lexicographic order, so list semantics stay stable.
86
+ */
87
+ declare class Collection<T> {
88
+ private readonly sqlite;
89
+ private readonly namespace;
90
+ private readonly name;
91
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
92
+ private bumpCollectionSeq;
93
+ nextSequence(): number;
94
+ get(id: string): T | undefined;
95
+ has(id: string): boolean;
96
+ /** Insert a new record, assigning it the next sequence number. */
97
+ insert(id: string, value: T): Stored<T>;
98
+ /** Replace an existing record's value, keeping its position. */
99
+ update(id: string, value: T): Stored<T> | undefined;
100
+ delete(id: string): boolean;
101
+ /** How many records the collection holds, without reading them. */
102
+ count(): number;
103
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
104
+ id: string;
105
+ }>;
106
+ }
107
+
108
+ /**
109
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
110
+ * request a percentage fault hits — is reproducible from a seed.
111
+ *
112
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
113
+ * than statistical quality.
114
+ */
115
+ type Rng = {
116
+ /** Next value in `[0, 1)`. */
117
+ next(): number;
118
+ /** Next integer in `[min, max]`. */
119
+ int(min: number, max: number): number;
120
+ /** Restart the stream from its seed. */
121
+ reset(): void;
122
+ /** Serializable engine state used by deterministic checkpoints. */
123
+ state(): number;
124
+ /** Restore a state previously returned by {@link state}. */
125
+ setState(state: number): void;
126
+ seed: number;
127
+ };
128
+
129
+ /**
130
+ * A deliberate failure injected in front of an operation.
131
+ *
132
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
133
+ * quota error that only appears when a shared sandbox is full, the 429 that only
134
+ * appears under load, the 5xx that proves a retry path works.
135
+ */
136
+ type FaultRule = {
137
+ /** Stable id, so a suite can retire exactly the rule it added. */
138
+ id: string;
139
+ /** Fault only this operation. Omit to match every operation. */
140
+ operationId?: string;
141
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
142
+ method?: string;
143
+ /** Fault only paths starting with this prefix. Omit to match every path. */
144
+ pathPrefix?: string;
145
+ /**
146
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
147
+ * an in-process caller usually wants, and what a parallel worker usually does not:
148
+ * rules added through `POST /__admin/faults` default to the calling namespace.
149
+ */
150
+ namespace?: string;
151
+ /**
152
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
153
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
154
+ * the request then still reaches the service.
155
+ */
156
+ status?: number;
157
+ /** Response body, serialized as JSON. A string is sent as-is. */
158
+ body?: unknown;
159
+ headers?: Record<string, string>;
160
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
161
+ count?: number;
162
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
163
+ rate?: number;
164
+ /** Hold the response back this long, to exercise timeouts. */
165
+ delayMs?: number;
166
+ /** Alias of `delayMs`. */
167
+ latencyMs?: number;
168
+ /**
169
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
170
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
171
+ */
172
+ drop?: boolean;
173
+ /**
174
+ * A named service behaviour to switch on for the matching request instead of (or
175
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
176
+ * read it with `faultEffects(request)`.
177
+ */
178
+ effect?: string;
179
+ /** Parameters for `effect`. */
180
+ params?: Record<string, unknown>;
181
+ /** From the preset this rule was expanded from, if any. */
182
+ preset?: string;
183
+ };
184
+ /** A fault that fired for one request. */
185
+ type FaultHit = {
186
+ id: string;
187
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
188
+ response?: Response;
189
+ drop?: boolean;
190
+ effect?: {
191
+ name: string;
192
+ params: Record<string, unknown>;
193
+ };
194
+ };
195
+ /**
196
+ * A named, documented fault a suite switches on by name
197
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
198
+ * webhook delivery fault.
199
+ */
200
+ type FaultPreset = {
201
+ description: string;
202
+ rules?: Omit<FaultRule, "id">[];
203
+ webhook?: {
204
+ mode: "duplicate" | "reorder" | "drop";
205
+ count?: number;
206
+ };
207
+ };
208
+ /** What a request looks like to the fault matcher. */
209
+ type FaultCandidate = {
210
+ operationId: string | undefined;
211
+ method: string;
212
+ path: string;
213
+ namespace: string;
214
+ };
215
+ type FaultRegistry = {
216
+ add(rule: FaultRule): FaultRule;
217
+ list(): (FaultRule & {
218
+ remaining: number | null;
219
+ hits: number;
220
+ })[];
221
+ remove(id: string): boolean;
222
+ clear(): void;
223
+ /**
224
+ * Every fault this request should get, in rule order, stopping at the first that answers
225
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
226
+ * each matching rule's remaining uses.
227
+ */
228
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
229
+ };
230
+
231
+ /** One handled request, as the structured log sees it. */
232
+ type RequestLog = {
233
+ service: string;
234
+ namespace: string;
235
+ operationId: string | undefined;
236
+ method: string;
237
+ path: string;
238
+ status: number;
239
+ durationMs: number;
240
+ /** True when the path matched no operation in the contract. */
241
+ unmatched: boolean;
242
+ /** Set when a fault rule produced the response. */
243
+ faultId?: string;
244
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
245
+ ids?: Record<string, string>;
246
+ /** Set when the service created a resource the request referred to but that did not exist. */
247
+ adopted?: boolean;
248
+ };
249
+ type MetricsReport = {
250
+ requests: number;
251
+ /** Counts keyed `<operationId> <status>`. */
252
+ byOperation: Record<string, number>;
253
+ /**
254
+ * Paths that matched no operation, most frequent first.
255
+ *
256
+ * This is the early-warning signal: a consumer calling something the mock does
257
+ * not implement shows up here as a count, before it fails a suite as a 404.
258
+ */
259
+ unmatched: {
260
+ method: string;
261
+ path: string;
262
+ count: number;
263
+ }[];
264
+ faults: number;
265
+ totalDurationMs: number;
266
+ };
267
+ type Metrics = {
268
+ record(entry: RequestLog): void;
269
+ report(): MetricsReport;
270
+ reset(): void;
271
+ };
272
+
273
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
274
+ type JournalEntry = RequestLog & {
275
+ at: string;
276
+ };
277
+ type JournalQuery = {
278
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
279
+ namespace?: string;
280
+ operationId?: string;
281
+ status?: number;
282
+ /** Only entries at or after this instant (epoch ms). */
283
+ since?: number;
284
+ /** At most this many, the most recent kept. */
285
+ limit?: number;
286
+ };
287
+ type Journal = {
288
+ readonly size: number;
289
+ record(entry: JournalEntry): void;
290
+ list(query?: JournalQuery): JournalEntry[];
291
+ /** Forget one namespace's entries, or every namespace's. */
292
+ clear(namespace?: string): void;
293
+ };
294
+
295
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
296
+ type CredentialRegistry = {
297
+ set(credential: string, namespace: string): void;
298
+ get(credential: string): string | undefined;
299
+ remove(credential: string): boolean;
300
+ clear(): void;
301
+ entries(): {
302
+ credential: string;
303
+ namespace: string;
304
+ }[];
305
+ };
306
+
307
+ /** A stable identifier for a point in a {@link Timeline}. */
308
+ type CheckpointId = string;
309
+ /** An immutable node in a timeline's checkpoint DAG. */
310
+ type Checkpoint<T> = Readonly<{
311
+ id: CheckpointId;
312
+ branch: string;
313
+ parent: CheckpointId | null;
314
+ /** Logical time supplied by the timeline's injected clock. */
315
+ at: number;
316
+ value: T;
317
+ }>;
318
+ type TimelineOptions = {
319
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
320
+ now?: () => number;
321
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
322
+ maxCheckpoints?: number;
323
+ /** Customize deterministic checkpoint IDs. */
324
+ id?: (sequence: number) => CheckpointId;
325
+ };
326
+ type CommitOptions = {
327
+ branch?: string;
328
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
329
+ parent?: CheckpointId | null;
330
+ };
331
+ type ForkOptions = {
332
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
333
+ from?: CheckpointId;
334
+ };
335
+ /**
336
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
337
+ * records, namespace images, or copy-on-write SQL engine snapshots.
338
+ *
339
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
340
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
341
+ * (the logical clock) is injected.
342
+ */
343
+ declare class Timeline<T> {
344
+ readonly maxCheckpoints: number;
345
+ private readonly now;
346
+ private readonly makeId;
347
+ private readonly nodes;
348
+ private readonly heads;
349
+ /** Unreferenced nodes in the exact order they became collectible. */
350
+ private readonly evictable;
351
+ /** Branch heads plus explicit retainers. Absent means zero. */
352
+ private readonly references;
353
+ private readonly explicitPins;
354
+ private sequence;
355
+ constructor(options?: TimelineOptions);
356
+ /** Capture a new immutable value and move `branch` to it. */
357
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
358
+ /** Create a branch pointer without copying its checkpoint value. */
359
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
360
+ /** Move a branch pointer to an existing checkpoint. */
361
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
362
+ get(id: CheckpointId): Checkpoint<T>;
363
+ head(branch?: string): Checkpoint<T> | undefined;
364
+ hasBranch(branch: string): boolean;
365
+ branches(): Readonly<Record<string, CheckpointId>>;
366
+ checkpoints(): readonly Checkpoint<T>[];
367
+ /** Number of retained checkpoints without allocating an array. */
368
+ get size(): number;
369
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
370
+ retain(id: CheckpointId): Checkpoint<T>;
371
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
372
+ release(id: CheckpointId): boolean;
373
+ deleteBranch(branch: string): boolean;
374
+ /**
375
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
376
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
377
+ * storage dependency, so a retained node remains usable after pruning.
378
+ */
379
+ gc(max?: number): CheckpointId[];
380
+ private collect;
381
+ private moveHead;
382
+ private addReference;
383
+ private removeReference;
384
+ private assertBranch;
385
+ }
386
+
387
+ /**
388
+ * Anything that can answer a Fetch `Request` with a `Response`.
389
+ *
390
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
391
+ * It is the only contract shared across the whole graph.
392
+ */
393
+ interface FetchAPI {
394
+ fetch(request: Request): Promise<Response>;
395
+ }
396
+
397
+ /**
398
+ * A point-in-time copy of everything a service namespace holds.
399
+ *
400
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
401
+ * is generic: any service gets per-test rollback without knowing its own schema.
402
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
403
+ */
404
+ type NamespaceSnapshot = {
405
+ namespace: string;
406
+ records: {
407
+ collection: string;
408
+ id: string;
409
+ seq: number;
410
+ value: string;
411
+ }[];
412
+ sequences: {
413
+ name: string;
414
+ kind: string;
415
+ value: number;
416
+ }[];
417
+ };
418
+
419
+ type WebhookEndpoint = {
420
+ /** Stable id; generated when omitted. */
421
+ id?: string;
422
+ url: string;
423
+ secret?: string;
424
+ /** Event types to deliver; omit or include `"*"` for every type. */
425
+ events?: string[];
426
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
427
+ tags?: Record<string, string>;
428
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
429
+ signUrl?: string;
430
+ headers?: Record<string, string>;
431
+ };
432
+ type WebhookMessage = {
433
+ id: string;
434
+ namespace: string;
435
+ type: string;
436
+ body: string;
437
+ contentType: string;
438
+ tags: Record<string, string>;
439
+ headers?: Record<string, string>;
440
+ /** Wall-clock ISO-8601 time of publication. */
441
+ publishedAt: string;
442
+ };
443
+ type WebhookAttempt = {
444
+ attempt: number;
445
+ at: string;
446
+ status: number | null;
447
+ error: string | null;
448
+ durationMs: number;
449
+ /** Exact receiver response body, when one was returned. */
450
+ responseBody?: string | null;
451
+ };
452
+ type WebhookDelivery = {
453
+ id: string;
454
+ messageId: string;
455
+ namespace: string;
456
+ type: string;
457
+ endpointId: string;
458
+ url: string;
459
+ state: "pending" | "delivered" | "failed" | "dropped";
460
+ attempts: WebhookAttempt[];
461
+ };
462
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
463
+ type WebhookFault = {
464
+ mode: "duplicate" | "reorder" | "drop";
465
+ /** Messages affected; default 1. */
466
+ count?: number;
467
+ };
468
+ type PublishInput = {
469
+ namespace: string;
470
+ type: string;
471
+ /** Exact body; objects are JSON-encoded. */
472
+ body: string | Record<string, unknown> | unknown[];
473
+ /** Default `application/json`, or form-encoded when `form` is given. */
474
+ contentType?: string;
475
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
476
+ form?: Record<string, string>;
477
+ tags?: Record<string, string>;
478
+ /** Message-specific delivery headers, captured as part of durable message state. */
479
+ headers?: Record<string, string>;
480
+ /** Message id; generated when omitted. */
481
+ id?: string;
482
+ };
483
+ type WebhookHub = {
484
+ publish(input: PublishInput): WebhookMessage;
485
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
486
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
487
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
488
+ endpoints(namespace: string): WebhookEndpoint[];
489
+ messages(namespace?: string): WebhookMessage[];
490
+ deliveries(namespace?: string): WebhookDelivery[];
491
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
492
+ /** Run every pending retry (and release held reordered messages) now. */
493
+ flush(): Promise<void>;
494
+ /** Resolve once nothing is in flight. */
495
+ idle(): Promise<void>;
496
+ fault(namespace: string, fault: WebhookFault): void;
497
+ clear(namespace?: string): void;
498
+ };
499
+
500
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
501
+ type ServiceInstance = FetchAPI & {
502
+ reset(): Promise<void>;
503
+ };
504
+ type ServiceTimelineState = Readonly<{
505
+ snapshot: NamespaceSnapshot;
506
+ clock: Readonly<ReturnType<Clock["state"]>>;
507
+ rngState: number;
508
+ }>;
509
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
510
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
511
+ readonly name: string;
512
+ readonly sqlite: SqliteClient$1;
513
+ readonly clock: Clock;
514
+ readonly faults: FaultRegistry;
515
+ readonly metrics: Metrics;
516
+ readonly journal: Journal;
517
+ readonly rng: Rng;
518
+ readonly credentials: CredentialRegistry;
519
+ /** The webhook hub, when the service has outbound webhooks. */
520
+ readonly webhooks: WebhookHub | undefined;
521
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
522
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
523
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
524
+ instance(namespace?: string): T;
525
+ /** Public names of every namespace created so far. */
526
+ namespaces(): string[];
527
+ /** Reset one namespace, or every namespace with `"*"`. */
528
+ reset(namespace?: string): Promise<void>;
529
+ snapshot(namespace?: string): NamespaceSnapshot;
530
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
531
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
532
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
533
+ /** Create an isolated branch, optionally from a historical checkpoint. */
534
+ branch(name: string, options?: {
535
+ namespace?: string;
536
+ at?: string;
537
+ }): ServiceCheckpoint;
538
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
539
+ checkout(checkpoint: string, options?: {
540
+ namespace?: string;
541
+ branch?: string;
542
+ }): void;
543
+ /** Inspect the retained history for a namespace. */
544
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
545
+ };
546
+
547
+ /** Options every provider constructor accepts. */
548
+ type APIOptions = {
549
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
550
+ sqlite?: SqliteClient$1;
551
+ /** Clock used for `created`-style fields. Default `Date.now`. */
552
+ now?: () => number;
553
+ /**
554
+ * Storage namespace for this instance's records. Instances sharing one SQLite
555
+ * client stay isolated when their namespaces differ. Defaults to the service name.
556
+ */
557
+ namespace?: string;
558
+ };
559
+
560
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
561
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
562
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
563
+ type SqliteRunResult = {
564
+ changes: number;
565
+ lastInsertRowid: number | bigint;
566
+ };
567
+ /**
568
+ * Prepared statement bound to a {@link SqliteClient}.
569
+ *
570
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
571
+ */
572
+ interface SqliteStatement {
573
+ run(...params: SqliteValue[]): SqliteRunResult;
574
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
575
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
576
+ }
577
+ /**
578
+ * Sync SQLite client port owned by Mockingbird.
579
+ *
580
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
581
+ * `bun:sqlite` instances all work when they expose this surface.
582
+ */
583
+ interface SqliteClient {
584
+ exec(sql: string): void;
585
+ prepare(sql: string): SqliteStatement;
586
+ transaction<T>(fn: () => T): T;
587
+ }
588
+
589
+ /**
590
+ * The built-in food and recipe corpus. Edamam's databases are proprietary, so these rows are
591
+ * synthesised in Edamam's exact shapes with realistic per-100 g nutrients (USDA-like values),
592
+ * enough for the parser, nutrients, recipe search, meal planner and shopping list to answer
593
+ * the questions our apps ask. Recipes are built from corpus foods, so their totals, per-serving
594
+ * values and shopping lists stay consistent with the food database.
595
+ */
596
+ declare const MEASURE_URI = "http://www.edamam.com/ontologies/edamam.owl#Measure_";
597
+ declare const RECIPE_URI = "http://www.edamam.com/ontologies/edamam.owl#recipe_";
598
+ type NutrientCode = "ENERC_KCAL" | "PROCNT" | "FAT" | "CHOCDF" | "FIBTG" | "SUGAR";
599
+ declare const NUTRIENTS: Record<NutrientCode, {
600
+ label: string;
601
+ unit: string;
602
+ daily: number;
603
+ }>;
604
+ type Measure = {
605
+ uri: string;
606
+ label: string;
607
+ weight: number;
608
+ };
609
+ type Food = {
610
+ foodId: string;
611
+ label: string;
612
+ knownAs: string;
613
+ /** Per 100 g. Empty for a product Edamam knows by UPC but has no nutrition data for. */
614
+ nutrients: Partial<Record<NutrientCode, number>>;
615
+ category: "Generic foods" | "Packaged foods" | "Generic meals";
616
+ categoryLabel: "food" | "meal";
617
+ image: string;
618
+ brand?: string;
619
+ foodContentsLabel?: string;
620
+ servingSizes?: {
621
+ uri: string;
622
+ label: string;
623
+ quantity: number;
624
+ }[];
625
+ /** Internal: the measures a hint lists, and what the parser accepts. */
626
+ measures: Measure[];
627
+ /** Internal: barcode for UPC lookups. */
628
+ upc?: string;
629
+ /** Internal: for the `health` filter. */
630
+ healthLabels: string[];
631
+ };
632
+ declare const DEFAULT_FOODS: readonly Food[];
633
+ type RecipeIngredient = {
634
+ foodId: string;
635
+ quantity: number;
636
+ measure: string;
637
+ text: string;
638
+ };
639
+ type RecipeSeed = {
640
+ id: string;
641
+ label: string;
642
+ yield: number;
643
+ totalTime: number;
644
+ mealType: string[];
645
+ dishType: string[];
646
+ cuisineType: string[];
647
+ dietLabels: string[];
648
+ healthLabels: string[];
649
+ cautions: string[];
650
+ ingredients: RecipeIngredient[];
651
+ };
652
+ declare const DEFAULT_RECIPES: readonly RecipeSeed[];
653
+
654
+ type ParsedLine = {
655
+ food: Food;
656
+ quantity?: number;
657
+ measure?: Measure;
658
+ } | undefined;
659
+ /**
660
+ * Parse an ingredient line the way Edamam's NLP does for our purposes: a leading quantity
661
+ * ("2", "1/2", "1 1/2", "a", "two"), an optional measure the food has ("cup", "large", "g"),
662
+ * and the food whose label (or known-as name) appears in the rest.
663
+ */
664
+ declare const parseLine: (text: string, foods: readonly Food[]) => ParsedLine;
665
+ type NutrientMap = Record<string, {
666
+ label: string;
667
+ quantity: number;
668
+ unit: string;
669
+ }>;
670
+ type Recipe = ReturnType<typeof buildRecipe>;
671
+ /** A recipe in Recipe Search v2's shape, with totals computed from the food corpus. */
672
+ declare const buildRecipe: (seed: RecipeSeed, foods: readonly Food[]) => {
673
+ uri: string;
674
+ label: string;
675
+ image: string;
676
+ source: string;
677
+ url: string;
678
+ shareAs: string;
679
+ yield: number;
680
+ dietLabels: string[];
681
+ healthLabels: string[];
682
+ cautions: string[];
683
+ ingredientLines: string[];
684
+ ingredients: {
685
+ text: string;
686
+ quantity: number;
687
+ measure: string;
688
+ food: string;
689
+ weight: number;
690
+ foodCategory: string | null;
691
+ foodId: string;
692
+ image: string | null;
693
+ }[];
694
+ calories: number;
695
+ totalWeight: number;
696
+ totalTime: number;
697
+ cuisineType: string[];
698
+ mealType: string[];
699
+ dishType: string[];
700
+ totalNutrients: NutrientMap;
701
+ totalDaily: NutrientMap;
702
+ };
703
+ /** Per-serving value of a nutrient code (or calories) of a built recipe. */
704
+ declare const perServing: (recipe: Recipe, code: NutrientCode) => number;
705
+
706
+ /** What `nutrients-from-image` recognises, when a test pins it. */
707
+ type VisionOverride = {
708
+ foodId: string;
709
+ quantity?: number;
710
+ measure?: string;
711
+ } | {
712
+ notFound: true;
713
+ };
714
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
715
+ type Settings = {
716
+ /** Only these app_id / app_key pairs authenticate; empty means any pair does. */
717
+ apps: {
718
+ appId: string;
719
+ appKey: string;
720
+ }[];
721
+ /** Answer 401 to recipe / meal-planner / shopping-list calls without `Edamam-Account-User`. */
722
+ requireAccountUser: boolean;
723
+ vision: VisionOverride | null;
724
+ };
725
+ declare class EdamamState {
726
+ private readonly seed;
727
+ readonly foods: Collection<Food>;
728
+ readonly recipes: Collection<RecipeSeed>;
729
+ readonly settings: Collection<Settings>;
730
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
731
+ foods: readonly Food[];
732
+ recipes: readonly RecipeSeed[];
733
+ settings: Partial<Settings>;
734
+ });
735
+ ensureSeeded(): void;
736
+ current(): Settings;
737
+ update(patch: Partial<Settings>): Settings;
738
+ allFoods(): Food[];
739
+ allRecipes(): RecipeSeed[];
740
+ }
741
+
742
+ /**
743
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
744
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
745
+ */
746
+ type JsonPrimitive = string | number | boolean | null;
747
+ type JsonValue = JsonPrimitive | JsonValue[] | {
748
+ [key: string]: JsonValue;
749
+ };
750
+ type ReferenceObject = {
751
+ $ref: string;
752
+ description?: string;
753
+ summary?: string;
754
+ };
755
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
756
+ type SchemaObject = {
757
+ $ref?: string;
758
+ type?: SchemaType | SchemaType[];
759
+ title?: string;
760
+ description?: string;
761
+ format?: string;
762
+ enum?: JsonValue[];
763
+ const?: JsonValue;
764
+ default?: JsonValue;
765
+ example?: JsonValue;
766
+ examples?: JsonValue[];
767
+ nullable?: boolean;
768
+ deprecated?: boolean;
769
+ readOnly?: boolean;
770
+ writeOnly?: boolean;
771
+ minimum?: number;
772
+ maximum?: number;
773
+ exclusiveMinimum?: number;
774
+ exclusiveMaximum?: number;
775
+ multipleOf?: number;
776
+ minLength?: number;
777
+ maxLength?: number;
778
+ pattern?: string;
779
+ minItems?: number;
780
+ maxItems?: number;
781
+ uniqueItems?: boolean;
782
+ items?: SchemaObject;
783
+ prefixItems?: SchemaObject[];
784
+ minProperties?: number;
785
+ maxProperties?: number;
786
+ required?: string[];
787
+ properties?: Record<string, SchemaObject>;
788
+ additionalProperties?: boolean | SchemaObject;
789
+ propertyNames?: SchemaObject;
790
+ oneOf?: SchemaObject[];
791
+ anyOf?: SchemaObject[];
792
+ allOf?: SchemaObject[];
793
+ not?: SchemaObject;
794
+ discriminator?: {
795
+ propertyName: string;
796
+ mapping?: Record<string, string>;
797
+ };
798
+ [extension: `x-${string}`]: unknown;
799
+ };
800
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
801
+ type ParameterObject = {
802
+ name: string;
803
+ in: ParameterLocation;
804
+ description?: string;
805
+ required?: boolean;
806
+ deprecated?: boolean;
807
+ style?: string;
808
+ explode?: boolean;
809
+ schema?: SchemaObject;
810
+ content?: Record<string, MediaTypeObject>;
811
+ example?: JsonValue;
812
+ [extension: `x-${string}`]: unknown;
813
+ };
814
+ type MediaTypeObject = {
815
+ schema?: SchemaObject;
816
+ example?: JsonValue;
817
+ examples?: Record<string, unknown>;
818
+ encoding?: Record<string, unknown>;
819
+ [extension: `x-${string}`]: unknown;
820
+ };
821
+ type RequestBodyObject = {
822
+ description?: string;
823
+ required?: boolean;
824
+ content: Record<string, MediaTypeObject>;
825
+ [extension: `x-${string}`]: unknown;
826
+ };
827
+ type HeaderObject = {
828
+ description?: string;
829
+ required?: boolean;
830
+ schema?: SchemaObject;
831
+ [extension: `x-${string}`]: unknown;
832
+ };
833
+ type ResponseObject = {
834
+ description: string;
835
+ headers?: Record<string, HeaderObject | ReferenceObject>;
836
+ content?: Record<string, MediaTypeObject>;
837
+ [extension: `x-${string}`]: unknown;
838
+ };
839
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
840
+ type SecurityRequirementObject = Record<string, string[]>;
841
+ type OperationObject = {
842
+ operationId?: string;
843
+ summary?: string;
844
+ description?: string;
845
+ tags?: string[];
846
+ deprecated?: boolean;
847
+ parameters?: Array<ParameterObject | ReferenceObject>;
848
+ requestBody?: RequestBodyObject | ReferenceObject;
849
+ responses: ResponsesObject;
850
+ security?: SecurityRequirementObject[];
851
+ [extension: `x-${string}`]: unknown;
852
+ };
853
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
854
+ type HttpMethod = (typeof HTTP_METHODS)[number];
855
+ type PathItemObject = {
856
+ summary?: string;
857
+ description?: string;
858
+ parameters?: Array<ParameterObject | ReferenceObject>;
859
+ [extension: `x-${string}`]: unknown;
860
+ } & Partial<Record<HttpMethod, OperationObject>>;
861
+ type SecuritySchemeObject = {
862
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
863
+ description?: string;
864
+ name?: string;
865
+ in?: ParameterLocation;
866
+ scheme?: string;
867
+ bearerFormat?: string;
868
+ flows?: Record<string, unknown>;
869
+ openIdConnectUrl?: string;
870
+ [extension: `x-${string}`]: unknown;
871
+ };
872
+ type ComponentsObject = {
873
+ schemas?: Record<string, SchemaObject>;
874
+ responses?: Record<string, ResponseObject>;
875
+ parameters?: Record<string, ParameterObject>;
876
+ requestBodies?: Record<string, RequestBodyObject>;
877
+ headers?: Record<string, HeaderObject>;
878
+ securitySchemes?: Record<string, SecuritySchemeObject>;
879
+ [extension: `x-${string}`]: unknown;
880
+ };
881
+ type ServerObject = {
882
+ url: string;
883
+ description?: string;
884
+ variables?: Record<string, unknown>;
885
+ [extension: `x-${string}`]: unknown;
886
+ };
887
+ type InfoObject = {
888
+ title: string;
889
+ version: string;
890
+ description?: string;
891
+ [extension: `x-${string}`]: unknown;
892
+ };
893
+ type OpenAPIDocument = {
894
+ openapi: string;
895
+ info: InfoObject;
896
+ servers?: ServerObject[];
897
+ paths: Record<string, PathItemObject>;
898
+ components?: ComponentsObject;
899
+ security?: SecurityRequirementObject[];
900
+ tags?: Array<{
901
+ name: string;
902
+ description?: string;
903
+ }>;
904
+ [extension: `x-${string}`]: unknown;
905
+ };
906
+
907
+ declare const document: OpenAPIDocument;
908
+ type OperationId = "FoodParser" | "FoodNutrients" | "FoodFromImage" | "NutritionData" | "NutritionDetails" | "RecipeSearch" | "RecipesByUri" | "RecipeById" | "MealPlanSelect" | "ShoppingList";
909
+ type SupportedOperationId = "FoodParser" | "FoodNutrients" | "FoodFromImage" | "NutritionData" | "NutritionDetails" | "RecipeSearch" | "RecipesByUri" | "RecipeById" | "MealPlanSelect" | "ShoppingList";
910
+ declare const operationIds: readonly ["FoodParser", "FoodNutrients", "FoodFromImage", "NutritionData", "NutritionDetails", "RecipeSearch", "RecipesByUri", "RecipeById", "MealPlanSelect", "ShoppingList"];
911
+ declare const supportedOperationIds: readonly ["FoodParser", "FoodNutrients", "FoodFromImage", "NutritionData", "NutritionDetails", "RecipeSearch", "RecipesByUri", "RecipeById", "MealPlanSelect", "ShoppingList"];
912
+
913
+ /**
914
+ * Every Edamam failure our adapters branch on, switched on with
915
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it).
916
+ */
917
+ declare const EDAMAM_PRESETS: Record<string, FaultPreset>;
918
+ type EdamamRuntimeOptions = {
919
+ sqlite?: SqliteClient;
920
+ clock?: Clock;
921
+ seed?: number | string;
922
+ adminKey?: string;
923
+ onLog?: (entry: RequestLog) => void;
924
+ foods?: readonly Food[];
925
+ recipes?: readonly RecipeSeed[];
926
+ settings?: Partial<Settings>;
927
+ };
928
+ type EdamamRuntime = ServiceRuntime<EdamamAPI>;
929
+ /**
930
+ * The Edamam mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
931
+ * namespaces by header, by `/ns/<name>` path prefix, or by application id
932
+ * (`PUT /__admin/credentials {"credentials": {"<app_id>": "<namespace>"}}`), clock control,
933
+ * fault presets and a request journal.
934
+ */
935
+ declare const createRuntime: (options?: EdamamRuntimeOptions) => EdamamRuntime;
936
+
937
+ declare const EDAMAM_NAMESPACE = "edamam";
938
+ declare const ACCOUNT_USER_HEADER = "edamam-account-user";
939
+ type EdamamAPIOptions = APIOptions & {
940
+ foods?: readonly Food[];
941
+ recipes?: readonly RecipeSeed[];
942
+ settings?: Partial<Settings>;
943
+ };
944
+ /** Food Database and Nutrition Analysis errors: `{status: "error", error, message}`. */
945
+ declare const foodError: (status: number, error: string, message: string) => Response;
946
+ /** Recipe Search, Meal Planner and Shopping List errors: `[{errorCode, message, params}]`. */
947
+ declare const recipeErrors: (status: number, errorCode: string, message: string, params?: string[]) => Response;
948
+ /** The application id a request carries (`app_id` query, else the Basic username). */
949
+ declare const appIdCredential: (request: Request) => string | undefined;
950
+ /**
951
+ * Stateful mock of the Edamam APIs our apps call, answering from a per-namespace food and
952
+ * recipe corpus (the built-in one by default; admin routes add rows).
953
+ */
954
+ declare class EdamamAPI implements FetchAPI$1 {
955
+ readonly app: Hono;
956
+ readonly sqlite: SqliteClient;
957
+ readonly state: EdamamState;
958
+ private readonly service;
959
+ private readonly now;
960
+ constructor(options?: EdamamAPIOptions);
961
+ fetch(request: Request): Promise<Response>;
962
+ reset(): Promise<void>;
963
+ private authenticate;
964
+ private foods;
965
+ private recipe;
966
+ private hit;
967
+ private jsonBody;
968
+ private foodFilter;
969
+ private parser;
970
+ private nutrients;
971
+ private vision;
972
+ private portionOf;
973
+ private nutritionData;
974
+ private nutritionDetails;
975
+ private recipeFilters;
976
+ private recipeSearch;
977
+ private recipesByUri;
978
+ /** Whether a recipe satisfies a plan section's `accept` predicates and per-serving `fit`. */
979
+ private fits;
980
+ private mealPlan;
981
+ private shoppingList;
982
+ addFood(food: Food): Food;
983
+ addRecipe(seed: RecipeSeed): Recipe;
984
+ recipes(): Recipe[];
985
+ }
986
+
987
+ export { ACCOUNT_USER_HEADER, DEFAULT_FOODS, DEFAULT_RECIPES, EDAMAM_NAMESPACE, EDAMAM_PRESETS, EdamamAPI, MEASURE_URI, NUTRIENTS, RECIPE_URI, appIdCredential, buildRecipe, createRuntime, document, foodError, operationIds, parseLine, perServing, recipeErrors, supportedOperationIds };
988
+ export type { EdamamAPIOptions, EdamamRuntime, EdamamRuntimeOptions, FetchAPI$1 as FetchAPI, Food, Measure, NutrientCode, OperationId, RecipeIngredient, RecipeSeed, Settings, SqliteClient, SupportedOperationId, VisionOverride };