@crvouga/mockingbird-service-google-maps 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,948 @@
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 addresses the mock knows, matching our QA fixtures: every row of `ROUTING_ZIP_CORPUS`
591
+ * (`packages/qa/src/world/gen/addresses.ts`, ≥1 real ZIP per state + DC, ids kept stable), the
592
+ * `packages/app/src/test-addresses` members it reuses (the Phoenix AZ at-home demo member
593
+ * `ADDRESS_AT_HOME_PHLEBOTOMY` among them), and `ADDRESS_AT_HOME_PHLEBOTOMY_2`. Coordinates are
594
+ * the city's civic centre, rounded; counties are the real ones.
595
+ */
596
+ type CorpusAddress = {
597
+ /** Stable row id (the QA corpus id). */
598
+ id: string;
599
+ line1: string;
600
+ city: string;
601
+ /** Two-letter code. */
602
+ state: string;
603
+ zip: string;
604
+ county: string;
605
+ lat: number;
606
+ lng: number;
607
+ };
608
+ declare const DEFAULT_CORPUS: readonly CorpusAddress[];
609
+ /** The Phoenix AZ at-home demo member (`ADDRESS_AT_HOME_PHLEBOTOMY`). */
610
+ declare const PHOENIX_DEMO_ADDRESS: CorpusAddress;
611
+ declare const STATE_NAMES: Readonly<Record<string, string>>;
612
+
613
+ /**
614
+ * Address resolution over the corpus, in Google's response shapes.
615
+ *
616
+ * Every answer is a pure function of the request and the namespace's corpus, so two instances
617
+ * always agree. Addresses the corpus does not hold but whose city (and state/ZIP) it does are
618
+ * *synthesized*: QA types `"<fuzzed number and street> <corpus city>"`, and the mock answers
619
+ * with that street in the corpus row's city, state and ZIP. A synthesized place id carries the
620
+ * whole address (`Ei…`, as Google's own address-only place ids carry theirs), so Place Details
621
+ * resolves it without any stored state.
622
+ */
623
+ /** One resolvable place: a corpus row, a synthesized street address, or a ZIP centroid. */
624
+ type Place = {
625
+ placeId: string;
626
+ kind: "street_address" | "postal_code";
627
+ line1: string;
628
+ city: string;
629
+ state: string;
630
+ zip: string;
631
+ county: string;
632
+ lat: number;
633
+ lng: number;
634
+ };
635
+ type AddressComponent = {
636
+ long_name: string;
637
+ short_name: string;
638
+ types: string[];
639
+ };
640
+ type Prediction = {
641
+ description: string;
642
+ matched_substrings: {
643
+ length: number;
644
+ offset: number;
645
+ }[];
646
+ place_id: string;
647
+ reference: string;
648
+ structured_formatting: {
649
+ main_text: string;
650
+ main_text_matched_substrings: {
651
+ length: number;
652
+ offset: number;
653
+ }[];
654
+ secondary_text: string;
655
+ };
656
+ terms: {
657
+ offset: number;
658
+ value: string;
659
+ }[];
660
+ types: string[];
661
+ };
662
+ declare const normalize: (value: string) => string;
663
+ /** The stable place id of a corpus row. */
664
+ declare const corpusPlaceId: (row: Pick<CorpusAddress, "id">) => string;
665
+
666
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
667
+ type Settings = {
668
+ /** Only these API keys are accepted; empty means any non-empty key is. */
669
+ keys: string[];
670
+ /**
671
+ * Origin the Maps JavaScript shim calls back to, when the browser reaches the mock at a
672
+ * different address than the request that loaded the script (a rewriting proxy).
673
+ */
674
+ publicUrl: string | null;
675
+ };
676
+ declare class GoogleMapsState {
677
+ private readonly seed;
678
+ /** Addresses a suite added to this namespace, on top of the built-in corpus. */
679
+ readonly custom: Collection<CorpusAddress>;
680
+ readonly settings: Collection<Settings>;
681
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
682
+ corpus: readonly CorpusAddress[];
683
+ settings: Partial<Settings>;
684
+ });
685
+ ensureSeeded(): void;
686
+ current(): Settings;
687
+ update(patch: Partial<Settings>): Settings;
688
+ /** Custom rows first (a suite's own addresses win ties), then the built-in corpus. */
689
+ corpus(): CorpusAddress[];
690
+ replaceCustom(rows: CorpusAddress[]): void;
691
+ }
692
+
693
+ /**
694
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
695
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
696
+ */
697
+ type JsonPrimitive = string | number | boolean | null;
698
+ type JsonValue = JsonPrimitive | JsonValue[] | {
699
+ [key: string]: JsonValue;
700
+ };
701
+ type ReferenceObject = {
702
+ $ref: string;
703
+ description?: string;
704
+ summary?: string;
705
+ };
706
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
707
+ type SchemaObject = {
708
+ $ref?: string;
709
+ type?: SchemaType | SchemaType[];
710
+ title?: string;
711
+ description?: string;
712
+ format?: string;
713
+ enum?: JsonValue[];
714
+ const?: JsonValue;
715
+ default?: JsonValue;
716
+ example?: JsonValue;
717
+ examples?: JsonValue[];
718
+ nullable?: boolean;
719
+ deprecated?: boolean;
720
+ readOnly?: boolean;
721
+ writeOnly?: boolean;
722
+ minimum?: number;
723
+ maximum?: number;
724
+ exclusiveMinimum?: number;
725
+ exclusiveMaximum?: number;
726
+ multipleOf?: number;
727
+ minLength?: number;
728
+ maxLength?: number;
729
+ pattern?: string;
730
+ minItems?: number;
731
+ maxItems?: number;
732
+ uniqueItems?: boolean;
733
+ items?: SchemaObject;
734
+ prefixItems?: SchemaObject[];
735
+ minProperties?: number;
736
+ maxProperties?: number;
737
+ required?: string[];
738
+ properties?: Record<string, SchemaObject>;
739
+ additionalProperties?: boolean | SchemaObject;
740
+ propertyNames?: SchemaObject;
741
+ oneOf?: SchemaObject[];
742
+ anyOf?: SchemaObject[];
743
+ allOf?: SchemaObject[];
744
+ not?: SchemaObject;
745
+ discriminator?: {
746
+ propertyName: string;
747
+ mapping?: Record<string, string>;
748
+ };
749
+ [extension: `x-${string}`]: unknown;
750
+ };
751
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
752
+ type ParameterObject = {
753
+ name: string;
754
+ in: ParameterLocation;
755
+ description?: string;
756
+ required?: boolean;
757
+ deprecated?: boolean;
758
+ style?: string;
759
+ explode?: boolean;
760
+ schema?: SchemaObject;
761
+ content?: Record<string, MediaTypeObject>;
762
+ example?: JsonValue;
763
+ [extension: `x-${string}`]: unknown;
764
+ };
765
+ type MediaTypeObject = {
766
+ schema?: SchemaObject;
767
+ example?: JsonValue;
768
+ examples?: Record<string, unknown>;
769
+ encoding?: Record<string, unknown>;
770
+ [extension: `x-${string}`]: unknown;
771
+ };
772
+ type RequestBodyObject = {
773
+ description?: string;
774
+ required?: boolean;
775
+ content: Record<string, MediaTypeObject>;
776
+ [extension: `x-${string}`]: unknown;
777
+ };
778
+ type HeaderObject = {
779
+ description?: string;
780
+ required?: boolean;
781
+ schema?: SchemaObject;
782
+ [extension: `x-${string}`]: unknown;
783
+ };
784
+ type ResponseObject = {
785
+ description: string;
786
+ headers?: Record<string, HeaderObject | ReferenceObject>;
787
+ content?: Record<string, MediaTypeObject>;
788
+ [extension: `x-${string}`]: unknown;
789
+ };
790
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
791
+ type SecurityRequirementObject = Record<string, string[]>;
792
+ type OperationObject = {
793
+ operationId?: string;
794
+ summary?: string;
795
+ description?: string;
796
+ tags?: string[];
797
+ deprecated?: boolean;
798
+ parameters?: Array<ParameterObject | ReferenceObject>;
799
+ requestBody?: RequestBodyObject | ReferenceObject;
800
+ responses: ResponsesObject;
801
+ security?: SecurityRequirementObject[];
802
+ [extension: `x-${string}`]: unknown;
803
+ };
804
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
805
+ type HttpMethod = (typeof HTTP_METHODS)[number];
806
+ type PathItemObject = {
807
+ summary?: string;
808
+ description?: string;
809
+ parameters?: Array<ParameterObject | ReferenceObject>;
810
+ [extension: `x-${string}`]: unknown;
811
+ } & Partial<Record<HttpMethod, OperationObject>>;
812
+ type SecuritySchemeObject = {
813
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
814
+ description?: string;
815
+ name?: string;
816
+ in?: ParameterLocation;
817
+ scheme?: string;
818
+ bearerFormat?: string;
819
+ flows?: Record<string, unknown>;
820
+ openIdConnectUrl?: string;
821
+ [extension: `x-${string}`]: unknown;
822
+ };
823
+ type ComponentsObject = {
824
+ schemas?: Record<string, SchemaObject>;
825
+ responses?: Record<string, ResponseObject>;
826
+ parameters?: Record<string, ParameterObject>;
827
+ requestBodies?: Record<string, RequestBodyObject>;
828
+ headers?: Record<string, HeaderObject>;
829
+ securitySchemes?: Record<string, SecuritySchemeObject>;
830
+ [extension: `x-${string}`]: unknown;
831
+ };
832
+ type ServerObject = {
833
+ url: string;
834
+ description?: string;
835
+ variables?: Record<string, unknown>;
836
+ [extension: `x-${string}`]: unknown;
837
+ };
838
+ type InfoObject = {
839
+ title: string;
840
+ version: string;
841
+ description?: string;
842
+ [extension: `x-${string}`]: unknown;
843
+ };
844
+ type OpenAPIDocument = {
845
+ openapi: string;
846
+ info: InfoObject;
847
+ servers?: ServerObject[];
848
+ paths: Record<string, PathItemObject>;
849
+ components?: ComponentsObject;
850
+ security?: SecurityRequirementObject[];
851
+ tags?: Array<{
852
+ name: string;
853
+ description?: string;
854
+ }>;
855
+ [extension: `x-${string}`]: unknown;
856
+ };
857
+
858
+ declare const document: OpenAPIDocument;
859
+ type OperationId = "PlaceAutocomplete" | "PlaceDetails" | "Geocode" | "FindPlaceFromText" | "MapsJavaScriptApi";
860
+ type SupportedOperationId = "PlaceAutocomplete" | "PlaceDetails" | "Geocode" | "FindPlaceFromText" | "MapsJavaScriptApi";
861
+ declare const operationIds: readonly ["PlaceAutocomplete", "PlaceDetails", "Geocode", "FindPlaceFromText", "MapsJavaScriptApi"];
862
+ declare const supportedOperationIds: readonly ["PlaceAutocomplete", "PlaceDetails", "Geocode", "FindPlaceFromText", "MapsJavaScriptApi"];
863
+
864
+ /**
865
+ * The Maps JavaScript API shim served at `GET /maps/api/js`: `google.maps.places.*` and
866
+ * `google.maps.Geocoder`, backed by this mock's own REST endpoints (same corpus, same faults,
867
+ * same namespace), in the callback shapes and status enums the real script uses.
868
+ */
869
+ type ShimOptions = {
870
+ /** Origin (plus any `/ns/<name>` prefix) the shim's `fetch` calls go to. */
871
+ base: string;
872
+ key: string;
873
+ /** The key was refused: the shim calls `window.gm_authFailure()` once loaded. */
874
+ authFailed: boolean;
875
+ /** `&callback=` from the script URL, called once `google.maps` is ready. */
876
+ callback: string | null;
877
+ };
878
+ declare const mapsJavaScript: (options: ShimOptions) => string;
879
+
880
+ /**
881
+ * Every named Google misbehaviour our consumer branches on, switched on with
882
+ * `POST /__admin/faults {"preset": "<name>", "count"?: n}`. Google answers these with HTTP 200
883
+ * and a non-OK `status`, which is what our client's consecutive-failure counter reads.
884
+ */
885
+ declare const GOOGLE_MAPS_PRESETS: Record<string, FaultPreset>;
886
+ type GoogleMapsRuntimeOptions = {
887
+ sqlite?: SqliteClient;
888
+ clock?: Clock;
889
+ seed?: number | string;
890
+ adminKey?: string;
891
+ onLog?: (entry: RequestLog) => void;
892
+ /** Addresses every namespace resolves. Default: the QA corpus. */
893
+ corpus?: readonly CorpusAddress[];
894
+ settings?: Partial<Settings>;
895
+ };
896
+ type GoogleMapsRuntime = ServiceRuntime<GoogleMapsAPI>;
897
+ /**
898
+ * The Google Maps mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
899
+ * namespaces by header, by `/ns/<name>` path prefix, or by API key
900
+ * (`PUT /__admin/credentials {"credentials": {"<PLACES_KEY>": "<namespace>"}}`), clock control,
901
+ * fault presets and a request journal. Google Maps sends no webhooks.
902
+ */
903
+ declare const createRuntime: (options?: GoogleMapsRuntimeOptions) => GoogleMapsRuntime;
904
+
905
+ declare const GOOGLE_MAPS_NAMESPACE = "google-maps";
906
+ /** Google's own wording for the two ways a key is refused. */
907
+ declare const MISSING_KEY_MESSAGE = "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account";
908
+ declare const INVALID_KEY_MESSAGE = "The provided API key is invalid. ";
909
+ /** Google statuses the mock answers with (always HTTP 200, as Google does). */
910
+ type GoogleStatus = "OK" | "ZERO_RESULTS" | "INVALID_REQUEST" | "OVER_QUERY_LIMIT" | "REQUEST_DENIED" | "UNKNOWN_ERROR" | "NOT_FOUND";
911
+ type GoogleMapsAPIOptions = APIOptions & {
912
+ /** Addresses every namespace resolves. Default: {@link DEFAULT_CORPUS}. */
913
+ corpus?: readonly CorpusAddress[];
914
+ /** Initial per-namespace settings (accepted keys, public URL for the JS shim). */
915
+ settings?: Partial<Settings>;
916
+ /** The public namespace name, so the JS shim can call back into the same namespace. */
917
+ publicNamespace?: string;
918
+ };
919
+ /** The API key a request carries (`?key=`): how keys map to namespaces. */
920
+ declare const keyCredential: (request: Request) => string | undefined;
921
+ /**
922
+ * Stateless-over-a-corpus mock of Google Places Autocomplete / Details / Find Place, the
923
+ * Geocoding API and a Maps JavaScript shim. Every answer is HTTP 200 with Google's `status`.
924
+ */
925
+ declare class GoogleMapsAPI implements FetchAPI$1 {
926
+ readonly app: Hono;
927
+ readonly sqlite: SqliteClient;
928
+ readonly state: GoogleMapsState;
929
+ private readonly service;
930
+ private readonly publicNamespace;
931
+ constructor(options?: GoogleMapsAPIOptions);
932
+ fetch(request: Request): Promise<Response>;
933
+ reset(): Promise<void>;
934
+ /** The addresses this namespace resolves (custom rows first). */
935
+ corpus(): CorpusAddress[];
936
+ private status;
937
+ /** Key check and status-effect faults, before every web-service call. */
938
+ private gate;
939
+ private noted;
940
+ private autocomplete;
941
+ private details;
942
+ private geocode;
943
+ private findPlace;
944
+ private script;
945
+ }
946
+
947
+ export { DEFAULT_CORPUS, GOOGLE_MAPS_NAMESPACE, GOOGLE_MAPS_PRESETS, GoogleMapsAPI, INVALID_KEY_MESSAGE, MISSING_KEY_MESSAGE, PHOENIX_DEMO_ADDRESS, STATE_NAMES, corpusPlaceId, createRuntime, document, keyCredential, mapsJavaScript, normalize, operationIds, supportedOperationIds };
948
+ export type { AddressComponent, CorpusAddress, FetchAPI$1 as FetchAPI, GoogleMapsAPIOptions, GoogleMapsRuntime, GoogleMapsRuntimeOptions, GoogleStatus, OperationId, Place, Prediction, Settings, ShimOptions, SqliteClient, SupportedOperationId };