@crvouga/mockingbird-service-aha 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,3241 @@
1
+ // ../core/dist/clock.js
2
+ var createClock = (source = Date.now) => {
3
+ let offsetMs = 0;
4
+ let frozenAt;
5
+ const now = () => frozenAt ?? source() + offsetMs;
6
+ return {
7
+ now,
8
+ set: (epochMs) => {
9
+ if (frozenAt !== void 0)
10
+ frozenAt = epochMs;
11
+ else
12
+ offsetMs = epochMs - source();
13
+ },
14
+ advance: (deltaMs) => {
15
+ if (frozenAt !== void 0)
16
+ frozenAt += deltaMs;
17
+ else
18
+ offsetMs += deltaMs;
19
+ },
20
+ freeze: () => {
21
+ frozenAt = now();
22
+ },
23
+ unfreeze: () => {
24
+ if (frozenAt === void 0)
25
+ return;
26
+ offsetMs = frozenAt - source();
27
+ frozenAt = void 0;
28
+ },
29
+ reset: () => {
30
+ offsetMs = 0;
31
+ frozenAt = void 0;
32
+ },
33
+ state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
34
+ };
35
+ };
36
+
37
+ // ../core/dist/collection.js
38
+ var Collection = class {
39
+ sqlite;
40
+ namespace;
41
+ name;
42
+ constructor(sqlite, namespace, name) {
43
+ this.sqlite = sqlite;
44
+ this.namespace = namespace;
45
+ this.name = name;
46
+ }
47
+ bumpCollectionSeq() {
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
49
+ const next = (row?.value ?? 0) + 1;
50
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
52
+ return next;
53
+ }
54
+ nextSequence() {
55
+ return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
+ }
57
+ get(id) {
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
59
+ if (!row)
60
+ return void 0;
61
+ return JSON.parse(row.value).value;
62
+ }
63
+ has(id) {
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
65
+ return row !== void 0;
66
+ }
67
+ /** Insert a new record, assigning it the next sequence number. */
68
+ insert(id, value) {
69
+ return this.sqlite.transaction(() => {
70
+ const seq = this.bumpCollectionSeq();
71
+ const stored = { seq, value };
72
+ this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
+ VALUES (?, ?, ?, ?, ?)
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
75
+ return stored;
76
+ });
77
+ }
78
+ /** Replace an existing record's value, keeping its position. */
79
+ update(id, value) {
80
+ return this.sqlite.transaction(() => {
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
82
+ if (!row)
83
+ return void 0;
84
+ const stored = { seq: row.seq, value };
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
86
+ return stored;
87
+ });
88
+ }
89
+ delete(id) {
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
91
+ return result.changes > 0;
92
+ }
93
+ /** How many records the collection holds, without reading them. */
94
+ count() {
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
96
+ return Number(row?.n ?? 0);
97
+ }
98
+ list(options = {}) {
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
100
+ const out = [];
101
+ for (const row of rows) {
102
+ const stored = JSON.parse(row.value);
103
+ if (options.where && !options.where(stored.value, stored.seq))
104
+ continue;
105
+ out.push({ id: row.id, seq: stored.seq, value: stored.value });
106
+ }
107
+ out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
108
+ return out;
109
+ }
110
+ };
111
+
112
+ // ../core/dist/control.js
113
+ var HEALTH_PATH = "/health";
114
+ var ADMIN_PREFIX = "/__admin";
115
+ var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
116
+ var NAMESPACE_HEADER = "x-mockingbird-namespace";
117
+ var json = (status, body) => new Response(JSON.stringify(body), {
118
+ status,
119
+ headers: { "content-type": "application/json" }
120
+ });
121
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
122
+ var UNITS = {
123
+ ms: 1,
124
+ s: 1e3,
125
+ m: 6e4,
126
+ h: 36e5,
127
+ d: 864e5
128
+ };
129
+ var parseDuration = (value) => {
130
+ if (typeof value === "number" && Number.isFinite(value))
131
+ return value;
132
+ if (typeof value !== "string")
133
+ return void 0;
134
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
135
+ if (!match)
136
+ return void 0;
137
+ return Number(match[1]) * UNITS[match[2]];
138
+ };
139
+ var parseInstant = (value) => {
140
+ if (typeof value === "number" && Number.isFinite(value))
141
+ return value;
142
+ if (typeof value !== "string")
143
+ return void 0;
144
+ const parsed = Date.parse(value);
145
+ return Number.isNaN(parsed) ? void 0 : parsed;
146
+ };
147
+ var matchRoute = (pattern, path) => {
148
+ const want = pattern.split("/").filter(Boolean);
149
+ const have = path.split("/").filter(Boolean);
150
+ if (want.length !== have.length)
151
+ return void 0;
152
+ const params = {};
153
+ for (let i = 0; i < want.length; i++) {
154
+ const segment = want[i];
155
+ const actual = have[i];
156
+ if (segment.startsWith(":"))
157
+ params[segment.slice(1)] = decodeURIComponent(actual);
158
+ else if (segment !== actual)
159
+ return void 0;
160
+ }
161
+ return params;
162
+ };
163
+ var readJson = async (request) => {
164
+ const text = await request.text();
165
+ if (text.trim() === "")
166
+ return void 0;
167
+ return JSON.parse(text);
168
+ };
169
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
+ var createControlPlane = (context) => {
171
+ const snapshots = /* @__PURE__ */ new Map();
172
+ let snapshotCounter = 0;
173
+ const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
174
+ const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
175
+ const builtin = {
176
+ "GET /": () => json(200, {
177
+ service: context.name,
178
+ routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
179
+ }),
180
+ "POST /reset": async ({ url, namespace }) => {
181
+ const target = url.searchParams.get("all") === "1" ? "*" : namespace;
182
+ await context.reset(target);
183
+ return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
184
+ },
185
+ "GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
186
+ "GET /clock": () => json(200, context.clock.state()),
187
+ "POST /clock": ({ body }) => {
188
+ if (!isRecord(body))
189
+ return adminError(400, "expected a JSON object");
190
+ if (body.reset === true)
191
+ context.clock.reset();
192
+ if (body.set !== void 0) {
193
+ const instant = parseInstant(body.set);
194
+ if (instant === void 0)
195
+ return adminError(400, "set: expected epoch ms or ISO-8601");
196
+ context.clock.set(instant);
197
+ }
198
+ if (body.advance !== void 0) {
199
+ const delta = parseDuration(body.advance);
200
+ if (delta === void 0)
201
+ return adminError(400, 'advance: expected ms or "15m"-style');
202
+ context.clock.advance(delta);
203
+ }
204
+ if (body.freeze === true)
205
+ context.clock.freeze();
206
+ if (body.freeze === false)
207
+ context.clock.unfreeze();
208
+ return json(200, context.clock.state());
209
+ },
210
+ "GET /faults": () => json(200, { faults: context.faults.list() }),
211
+ "POST /faults": ({ body, namespace }) => {
212
+ if (isRecord(body) && typeof body.preset === "string") {
213
+ if (!context.applyPreset)
214
+ return adminError(400, `${context.name} has no fault presets`);
215
+ const { preset, ...overrides } = body;
216
+ try {
217
+ return json(201, {
218
+ preset,
219
+ rules: context.applyPreset(preset, namespace, overrides)
220
+ });
221
+ } catch (error2) {
222
+ return adminError(404, error2 instanceof Error ? error2.message : String(error2));
223
+ }
224
+ }
225
+ if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
226
+ return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
227
+ }
228
+ const rule = {
229
+ // Scoped to the caller's namespace unless it asks for every one, so one worker's
230
+ // injected failure never lands on another's request.
231
+ namespace,
232
+ ...body,
233
+ id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
234
+ };
235
+ return json(201, context.faults.add(rule));
236
+ },
237
+ "DELETE /faults": ({ url }) => {
238
+ const id = url.searchParams.get("id");
239
+ if (id === null) {
240
+ context.faults.clear();
241
+ return json(200, { status: "ok" });
242
+ }
243
+ return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
244
+ },
245
+ "POST /snapshots": ({ namespace }) => {
246
+ const point = context.timeTravel.checkpoint(namespace, "main");
247
+ context.timeTravel.retain(namespace, point.id);
248
+ snapshotCounter++;
249
+ const id = `snap_${snapshotCounter}`;
250
+ snapshots.set(id, { namespace, checkpoint: point.id });
251
+ return json(201, { id, namespace, records: point.records ?? 0 });
252
+ },
253
+ "POST /snapshots/:id/restore": ({ params, namespace }) => {
254
+ const alias = snapshots.get(params.id);
255
+ if (!alias)
256
+ return adminError(404, `no snapshot ${params.id}`);
257
+ if (alias.namespace !== namespace) {
258
+ return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
259
+ }
260
+ context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
261
+ return json(200, { status: "ok", id: params.id, namespace });
262
+ },
263
+ "DELETE /snapshots/:id": ({ params }) => {
264
+ const id = params.id;
265
+ const alias = snapshots.get(id);
266
+ if (!alias)
267
+ return adminError(404, `no snapshot ${id}`);
268
+ snapshots.delete(id);
269
+ context.timeTravel.release(alias.namespace, alias.checkpoint);
270
+ return json(200, { status: "ok" });
271
+ },
272
+ "GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
273
+ "POST /checkpoints": ({ body, namespace }) => {
274
+ const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
275
+ try {
276
+ return json(201, context.timeTravel.checkpoint(namespace, branch));
277
+ } catch (error2) {
278
+ return adminError(409, error2 instanceof Error ? error2.message : String(error2));
279
+ }
280
+ },
281
+ "POST /branches/:name": ({ params, body, namespace }) => {
282
+ const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
283
+ try {
284
+ return json(201, context.timeTravel.branch(params.name, {
285
+ namespace,
286
+ ...at !== void 0 ? { at } : {}
287
+ }));
288
+ } catch (error2) {
289
+ return adminError(409, error2 instanceof Error ? error2.message : String(error2));
290
+ }
291
+ },
292
+ "POST /branches/:name/checkout": ({ params, body, namespace }) => {
293
+ if (!isRecord(body) || typeof body.checkpoint !== "string") {
294
+ return adminError(400, 'expected {"checkpoint":"cp_..."}');
295
+ }
296
+ try {
297
+ context.timeTravel.checkout(body.checkpoint, {
298
+ namespace,
299
+ branch: params.name
300
+ });
301
+ return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
302
+ } catch (error2) {
303
+ return adminError(409, error2 instanceof Error ? error2.message : String(error2));
304
+ }
305
+ },
306
+ "GET /requests": ({ url, namespace }) => {
307
+ const status = url.searchParams.get("status");
308
+ const since = url.searchParams.get("since");
309
+ const limit = url.searchParams.get("limit");
310
+ const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
311
+ if (since !== null && sinceMs === void 0) {
312
+ return adminError(400, "since: expected epoch ms or ISO-8601");
313
+ }
314
+ if (status !== null && !/^\d{3}$/.test(status))
315
+ return adminError(400, "status: expected an HTTP status");
316
+ if (limit !== null && !/^\d+$/.test(limit))
317
+ return adminError(400, "limit: expected a count");
318
+ const operationId = url.searchParams.get("operationId");
319
+ const everyNamespace = url.searchParams.get("all") === "1";
320
+ return json(200, {
321
+ size: context.journal.size,
322
+ requests: context.journal.list({
323
+ ...everyNamespace ? {} : { namespace },
324
+ ...operationId !== null ? { operationId } : {},
325
+ ...status !== null ? { status: Number(status) } : {},
326
+ ...sinceMs !== void 0 ? { since: sinceMs } : {},
327
+ ...limit !== null ? { limit: Number(limit) } : {}
328
+ })
329
+ });
330
+ },
331
+ "DELETE /requests": ({ url, namespace }) => {
332
+ context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
333
+ return json(200, { status: "ok" });
334
+ },
335
+ "GET /metrics": () => json(200, context.metrics.report()),
336
+ "DELETE /metrics": () => {
337
+ context.metrics.reset();
338
+ return json(200, { status: "ok" });
339
+ }
340
+ };
341
+ const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key2, handler]) => {
342
+ const space = key2.indexOf(" ");
343
+ return { method: key2.slice(0, space), pattern: key2.slice(space + 1), handler };
344
+ });
345
+ return {
346
+ namespaceOf: headerNamespace,
347
+ async handle(request) {
348
+ const url = new URL(request.url);
349
+ if (url.pathname === HEALTH_PATH && request.method === "GET") {
350
+ return json(200, {
351
+ status: "ok",
352
+ service: context.name,
353
+ uptimeMs: context.wallNow() - context.startedAt,
354
+ clock: context.clock.state(),
355
+ namespaces: context.namespaces().length,
356
+ ...context.describe()
357
+ });
358
+ }
359
+ if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
+ return void 0;
361
+ }
362
+ if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
+ }
365
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
+ for (const route of routes) {
367
+ if (route.method !== request.method)
368
+ continue;
369
+ const params = matchRoute(route.pattern, path);
370
+ if (!params)
371
+ continue;
372
+ let body;
373
+ try {
374
+ body = await readJson(request);
375
+ } catch {
376
+ return adminError(400, "request body is not valid JSON");
377
+ }
378
+ return route.handler({
379
+ request,
380
+ url,
381
+ params,
382
+ namespace: adminNamespace(request, url),
383
+ body
384
+ });
385
+ }
386
+ return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
387
+ }
388
+ };
389
+ };
390
+
391
+ // ../core/dist/credentials.js
392
+ var createCredentialRegistry = () => {
393
+ const map = /* @__PURE__ */ new Map();
394
+ return {
395
+ set: (credential, namespace) => {
396
+ map.set(credential, namespace);
397
+ },
398
+ get: (credential) => map.get(credential),
399
+ remove: (credential) => map.delete(credential),
400
+ clear: () => map.clear(),
401
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
402
+ };
403
+ };
404
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
405
+
406
+ // ../core/dist/rng.js
407
+ var seedFrom = (value) => {
408
+ let hash = 2166136261;
409
+ for (let i = 0; i < value.length; i++) {
410
+ hash ^= value.charCodeAt(i);
411
+ hash = Math.imul(hash, 16777619);
412
+ }
413
+ return hash >>> 0;
414
+ };
415
+ var createRng = (seed = 0) => {
416
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
417
+ let state = numeric;
418
+ const next = () => {
419
+ state = state + 1831565813 >>> 0;
420
+ let t = state;
421
+ t = Math.imul(t ^ t >>> 15, t | 1);
422
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
423
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
424
+ };
425
+ return {
426
+ next,
427
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
428
+ reset: () => {
429
+ state = numeric;
430
+ },
431
+ state: () => state,
432
+ setState: (next2) => {
433
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
434
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
435
+ }
436
+ state = next2 >>> 0;
437
+ },
438
+ seed: numeric
439
+ };
440
+ };
441
+
442
+ // ../core/dist/faults.js
443
+ var matches = (rule, candidate) => {
444
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
445
+ return false;
446
+ }
447
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
448
+ return false;
449
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
450
+ return false;
451
+ }
452
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
453
+ return false;
454
+ return true;
455
+ };
456
+ var faultResponse = (rule) => {
457
+ const status = rule.status ?? 500;
458
+ const headers = { "content-type": "application/json", ...rule.headers };
459
+ if (typeof rule.body === "string")
460
+ return new Response(rule.body, { status, headers });
461
+ if (rule.body === null)
462
+ return new Response(null, { status, headers: rule.headers ?? {} });
463
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
464
+ return new Response(JSON.stringify(body), { status, headers });
465
+ };
466
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
467
+ const entries = [];
468
+ return {
469
+ add(rule) {
470
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
471
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
472
+ if (existing >= 0)
473
+ entries[existing] = entry;
474
+ else
475
+ entries.push(entry);
476
+ return rule;
477
+ },
478
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
479
+ remove(id) {
480
+ const index = entries.findIndex((e) => e.rule.id === id);
481
+ if (index < 0)
482
+ return false;
483
+ entries.splice(index, 1);
484
+ return true;
485
+ },
486
+ clear() {
487
+ entries.length = 0;
488
+ },
489
+ async take(candidate) {
490
+ const hits = [];
491
+ for (const entry of entries) {
492
+ if (entry.remaining === 0)
493
+ continue;
494
+ if (!matches(entry.rule, candidate))
495
+ continue;
496
+ const rate = entry.rule.rate ?? 1;
497
+ if (rng.next() >= rate)
498
+ continue;
499
+ entry.hits++;
500
+ if (entry.remaining !== null)
501
+ entry.remaining--;
502
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
503
+ if (delay !== void 0 && delay > 0) {
504
+ await sleep(delay);
505
+ }
506
+ const hit = { id: entry.rule.id };
507
+ if (entry.rule.effect !== void 0) {
508
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
509
+ }
510
+ if (entry.rule.drop === true)
511
+ hit.drop = true;
512
+ else if (entry.rule.status !== void 0)
513
+ hit.response = faultResponse(entry.rule);
514
+ hits.push(hit);
515
+ if (hit.drop || hit.response)
516
+ break;
517
+ }
518
+ return hits;
519
+ }
520
+ };
521
+ };
522
+
523
+ // ../../openapi/core/dist/refs.js
524
+ var OpenAPIReferenceError = class extends Error {
525
+ ref;
526
+ constructor(ref) {
527
+ super(`unresolvable $ref: ${ref}`);
528
+ this.ref = ref;
529
+ this.name = "OpenAPIReferenceError";
530
+ }
531
+ };
532
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
533
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
534
+ var resolveRef = (document2, ref) => {
535
+ if (!ref.startsWith("#/"))
536
+ throw new OpenAPIReferenceError(ref);
537
+ let cursor = document2;
538
+ for (const raw of ref.slice(2).split("/")) {
539
+ const segment = unescapePointer(raw);
540
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
541
+ throw new OpenAPIReferenceError(ref);
542
+ }
543
+ cursor = cursor[segment];
544
+ }
545
+ if (cursor === void 0)
546
+ throw new OpenAPIReferenceError(ref);
547
+ return cursor;
548
+ };
549
+ var deref = (document2, value) => {
550
+ let current = value;
551
+ const seen = /* @__PURE__ */ new Set();
552
+ while (isReference(current)) {
553
+ if (seen.has(current.$ref))
554
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
555
+ seen.add(current.$ref);
556
+ current = resolveRef(document2, current.$ref);
557
+ }
558
+ return current;
559
+ };
560
+
561
+ // ../../openapi/core/dist/types.js
562
+ var HTTP_METHODS = [
563
+ "get",
564
+ "put",
565
+ "post",
566
+ "delete",
567
+ "options",
568
+ "head",
569
+ "patch",
570
+ "trace"
571
+ ];
572
+
573
+ // ../../openapi/core/dist/document.js
574
+ var mergeParameters = (document2, item, own) => {
575
+ const merged = /* @__PURE__ */ new Map();
576
+ for (const raw of item.parameters ?? []) {
577
+ const parameter = deref(document2, raw);
578
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
579
+ }
580
+ for (const raw of own ?? []) {
581
+ const parameter = deref(document2, raw);
582
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
583
+ }
584
+ return [...merged.values()];
585
+ };
586
+ var listOperations = (document2) => {
587
+ const operations = [];
588
+ for (const [path, item] of Object.entries(document2.paths)) {
589
+ for (const method of HTTP_METHODS) {
590
+ const operation = item[method];
591
+ if (operation?.operationId === void 0)
592
+ continue;
593
+ const responses = {};
594
+ for (const [status, response] of Object.entries(operation.responses)) {
595
+ responses[status] = deref(document2, response);
596
+ }
597
+ operations.push({
598
+ operationId: operation.operationId,
599
+ method,
600
+ path,
601
+ operation,
602
+ parameters: mergeParameters(document2, item, operation.parameters),
603
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
604
+ responses
605
+ });
606
+ }
607
+ }
608
+ return operations;
609
+ };
610
+
611
+ // ../../openapi/core/dist/schema.js
612
+ var resolveSchema = (document2, schema) => {
613
+ let current = schema;
614
+ const seen = /* @__PURE__ */ new Set();
615
+ while (typeof current.$ref === "string") {
616
+ const ref = current.$ref;
617
+ if (seen.has(ref))
618
+ break;
619
+ seen.add(ref);
620
+ const { $ref: _ignored, ...siblings } = current;
621
+ const target = resolveRef(document2, ref);
622
+ current = { ...target, ...siblings };
623
+ }
624
+ if (current.nullable === true) {
625
+ const { nullable: _nullable, ...rest } = current;
626
+ const types = schemaTypes(rest);
627
+ if (types.length > 0 && !types.includes("null"))
628
+ current = { ...rest, type: [...types, "null"] };
629
+ else
630
+ current = rest;
631
+ }
632
+ return current;
633
+ };
634
+ var schemaTypes = (schema) => {
635
+ if (Array.isArray(schema.type))
636
+ return schema.type;
637
+ if (schema.type !== void 0)
638
+ return [schema.type];
639
+ const inferred = [];
640
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
641
+ inferred.push("object");
642
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
643
+ inferred.push("array");
644
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
645
+ inferred.push("string");
646
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
647
+ inferred.push("number");
648
+ return inferred;
649
+ };
650
+ var jsonTypeOf = (value) => {
651
+ if (value === null)
652
+ return "null";
653
+ if (Array.isArray(value))
654
+ return "array";
655
+ switch (typeof value) {
656
+ case "string":
657
+ return "string";
658
+ case "boolean":
659
+ return "boolean";
660
+ case "number":
661
+ return Number.isInteger(value) ? "integer" : "number";
662
+ case "object":
663
+ return "object";
664
+ default:
665
+ return "undefined";
666
+ }
667
+ };
668
+ var deepEqual = (a, b) => {
669
+ if (a === b)
670
+ return true;
671
+ if (typeof a !== typeof b || a === null || b === null)
672
+ return false;
673
+ if (Array.isArray(a)) {
674
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
675
+ }
676
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
677
+ const ka = Object.keys(a);
678
+ const kb = Object.keys(b);
679
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
680
+ }
681
+ return false;
682
+ };
683
+ var FORMAT_PATTERNS = {
684
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
685
+ date: /^\d{4}-\d{2}-\d{2}$/,
686
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
687
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
688
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
689
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
690
+ };
691
+ var graphemeLength = (value) => [...value].length;
692
+ var validateValue = (document2, schema, value, path = []) => {
693
+ const errors = [];
694
+ const s = resolveSchema(document2, schema);
695
+ const fail = (message) => errors.push({ path, message });
696
+ const actual = jsonTypeOf(value);
697
+ if (actual === "undefined") {
698
+ fail("value is undefined");
699
+ return errors;
700
+ }
701
+ const types = schemaTypes(s);
702
+ if (types.length > 0) {
703
+ const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
704
+ if (!ok) {
705
+ fail(`expected type ${types.join("|")}, got ${actual}`);
706
+ return errors;
707
+ }
708
+ }
709
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
710
+ fail("value not in enum");
711
+ }
712
+ if (s.const !== void 0 && !deepEqual(s.const, value))
713
+ fail("value does not equal const");
714
+ if (typeof value === "string") {
715
+ const length = graphemeLength(value);
716
+ if (s.minLength !== void 0 && length < s.minLength)
717
+ fail(`length ${length} < minLength ${s.minLength}`);
718
+ if (s.maxLength !== void 0 && length > s.maxLength)
719
+ fail(`length ${length} > maxLength ${s.maxLength}`);
720
+ if (s.pattern !== void 0) {
721
+ try {
722
+ if (!new RegExp(s.pattern, "u").test(value))
723
+ fail(`does not match pattern ${s.pattern}`);
724
+ } catch {
725
+ }
726
+ }
727
+ if (s.format !== void 0) {
728
+ const pattern = FORMAT_PATTERNS[s.format];
729
+ if (pattern && !pattern.test(value))
730
+ fail(`does not match format ${s.format}`);
731
+ }
732
+ }
733
+ if (typeof value === "number") {
734
+ if (s.minimum !== void 0 && value < s.minimum)
735
+ fail(`${value} < minimum ${s.minimum}`);
736
+ if (s.maximum !== void 0 && value > s.maximum)
737
+ fail(`${value} > maximum ${s.maximum}`);
738
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
739
+ fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
740
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
741
+ fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
742
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
743
+ fail(`${value} is not a multiple of ${s.multipleOf}`);
744
+ }
745
+ }
746
+ if (Array.isArray(value)) {
747
+ if (s.minItems !== void 0 && value.length < s.minItems)
748
+ fail(`${value.length} items < minItems ${s.minItems}`);
749
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
750
+ fail(`${value.length} items > maxItems ${s.maxItems}`);
751
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
752
+ fail("items are not unique");
753
+ value.forEach((item, i) => {
754
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
755
+ if (itemSchema)
756
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
757
+ });
758
+ }
759
+ if (actual === "object") {
760
+ const record2 = value;
761
+ const keys = Object.keys(record2);
762
+ for (const name of s.required ?? [])
763
+ if (!(name in record2))
764
+ fail(`missing required property ${name}`);
765
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
766
+ fail(`${keys.length} properties < minProperties ${s.minProperties}`);
767
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
768
+ fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
769
+ for (const key2 of keys) {
770
+ const property = s.properties?.[key2];
771
+ if (property) {
772
+ errors.push(...validateValue(document2, property, record2[key2], [...path, key2]));
773
+ continue;
774
+ }
775
+ if (s.additionalProperties === false)
776
+ fail(`unexpected property ${key2}`);
777
+ else if (typeof s.additionalProperties === "object") {
778
+ errors.push(...validateValue(document2, s.additionalProperties, record2[key2], [...path, key2]));
779
+ }
780
+ if (s.propertyNames) {
781
+ const nameErrors = validateValue(document2, s.propertyNames, key2, [...path, key2]);
782
+ if (nameErrors.length > 0)
783
+ fail(`property name ${key2} is invalid: ${nameErrors[0]?.message}`);
784
+ }
785
+ }
786
+ }
787
+ if (s.allOf)
788
+ for (const branch of s.allOf)
789
+ errors.push(...validateValue(document2, branch, value, path));
790
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
791
+ fail("matches no anyOf branch");
792
+ if (s.oneOf) {
793
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
794
+ if (matches2 !== 1)
795
+ fail(`matches ${matches2} oneOf branches, expected exactly 1`);
796
+ }
797
+ if (s.not && validateValue(document2, s.not, value).length === 0)
798
+ fail("matches forbidden `not` schema");
799
+ return errors;
800
+ };
801
+
802
+ // ../../http/codec/dist/form.js
803
+ var parsePath = (rawKey) => {
804
+ const open = rawKey.indexOf("[");
805
+ if (open === -1)
806
+ return [rawKey];
807
+ const path = [rawKey.slice(0, open)];
808
+ const rest = rawKey.slice(open);
809
+ const pattern = /\[([^\]]*)\]/g;
810
+ let match = pattern.exec(rest);
811
+ let consumed = 0;
812
+ while (match !== null) {
813
+ if (match.index !== consumed)
814
+ return [rawKey];
815
+ path.push(match[1] ?? "");
816
+ consumed = match.index + match[0].length;
817
+ match = pattern.exec(rest);
818
+ }
819
+ if (consumed !== rest.length)
820
+ return [rawKey];
821
+ return path;
822
+ };
823
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
824
+ var put = (target, key2, value) => {
825
+ if (key2 === "__proto__") {
826
+ Object.defineProperty(target, key2, {
827
+ value,
828
+ enumerable: true,
829
+ writable: true,
830
+ configurable: true
831
+ });
832
+ return;
833
+ }
834
+ ;
835
+ target[key2] = value;
836
+ };
837
+ var assign = (target, path, value) => {
838
+ let cursor = target;
839
+ for (let i = 0; i < path.length; i++) {
840
+ const segment = path[i];
841
+ const last = i === path.length - 1;
842
+ if (Array.isArray(cursor)) {
843
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
844
+ if (index === void 0)
845
+ return;
846
+ if (last) {
847
+ put(cursor, index, value);
848
+ return;
849
+ }
850
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
851
+ if (next === void 0 || typeof next === "string") {
852
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
853
+ put(cursor, index, created);
854
+ cursor = created;
855
+ } else {
856
+ cursor = next;
857
+ }
858
+ continue;
859
+ }
860
+ if (typeof cursor === "string")
861
+ return;
862
+ if (last) {
863
+ put(cursor, segment, value);
864
+ return;
865
+ }
866
+ const nextSegment = path[i + 1];
867
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
868
+ if (existing === void 0 || typeof existing === "string") {
869
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
870
+ put(cursor, segment, created);
871
+ cursor = created;
872
+ } else {
873
+ cursor = existing;
874
+ }
875
+ }
876
+ };
877
+ var decodeFormPairs = (pairs) => {
878
+ const out = {};
879
+ for (const [rawKey, value] of pairs)
880
+ assign(out, parsePath(rawKey), value);
881
+ return densify(out);
882
+ };
883
+ var densify = (value) => {
884
+ if (typeof value === "string")
885
+ return value;
886
+ if (Array.isArray(value))
887
+ return value.filter((item) => item !== void 0).map(densify);
888
+ const out = {};
889
+ for (const [key2, item] of Object.entries(value))
890
+ put(out, key2, densify(item));
891
+ return out;
892
+ };
893
+ var decodeForm = (text) => {
894
+ const source = text.startsWith("?") ? text.slice(1) : text;
895
+ return decodeFormPairs(new URLSearchParams(source).entries());
896
+ };
897
+
898
+ // ../../http/codec/dist/content.js
899
+ var JSON_MEDIA_TYPE = "application/json";
900
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
901
+ var mediaTypeOf = (contentType) => {
902
+ if (!contentType)
903
+ return void 0;
904
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
905
+ return essence ? essence : void 0;
906
+ };
907
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
908
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
909
+ var decodeBody = (contentType, bytes) => {
910
+ if (bytes.byteLength === 0)
911
+ return { kind: "empty" };
912
+ const mediaType = mediaTypeOf(contentType);
913
+ if (mediaType === void 0)
914
+ return { kind: "bytes", value: bytes };
915
+ if (isJsonMediaType(mediaType)) {
916
+ const text = utf8.decode(bytes);
917
+ try {
918
+ return { kind: "json", value: JSON.parse(text) };
919
+ } catch (error2) {
920
+ return {
921
+ kind: "invalid",
922
+ mediaType,
923
+ text,
924
+ error: error2 instanceof Error ? error2.message : String(error2)
925
+ };
926
+ }
927
+ }
928
+ if (mediaType === FORM_MEDIA_TYPE) {
929
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
930
+ }
931
+ if (mediaType.startsWith("text/"))
932
+ return { kind: "text", value: utf8.decode(bytes) };
933
+ return { kind: "bytes", value: bytes };
934
+ };
935
+ var readBody = async (message) => {
936
+ const bytes = new Uint8Array(await message.arrayBuffer());
937
+ return decodeBody(message.headers.get("content-type"), bytes);
938
+ };
939
+
940
+ // ../core/dist/http.js
941
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
942
+ status,
943
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
944
+ });
945
+ var HttpError = class extends Error {
946
+ status;
947
+ body;
948
+ headers;
949
+ constructor(status, body, headers = {}) {
950
+ super(`HTTP ${status}`);
951
+ this.status = status;
952
+ this.body = body;
953
+ this.headers = headers;
954
+ this.name = "HttpError";
955
+ }
956
+ toResponse() {
957
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
958
+ if (contentType === "text/plain") {
959
+ return new Response(String(this.body), {
960
+ status: this.status,
961
+ headers: this.headers
962
+ });
963
+ }
964
+ return jsonRes(this.status, this.body, this.headers);
965
+ }
966
+ };
967
+
968
+ // ../core/dist/idempotency.js
969
+ var inFlight = /* @__PURE__ */ new Map();
970
+ var IdempotencyStore = class {
971
+ namespace;
972
+ responses;
973
+ constructor(sqlite, namespace, name = "idempotency") {
974
+ this.namespace = namespace;
975
+ this.responses = new Collection(sqlite, namespace, name);
976
+ }
977
+ /**
978
+ * Run `handler` once per `key`. `fingerprint` identifies the request's parameters (e.g.
979
+ * the method, path and canonical body). Only `replayable` responses are stored (default:
980
+ * every status below 500, as Stripe does), so a transient failure can be retried.
981
+ */
982
+ async run(key2, fingerprint, errors, handler, replayable = (status) => status < 500) {
983
+ const slot = `${this.namespace}\0${key2}`;
984
+ const stored = this.responses.get(key2);
985
+ if (stored) {
986
+ if (stored.fingerprint !== fingerprint)
987
+ return errors.mismatch();
988
+ return new Response(stored.body, {
989
+ status: stored.status,
990
+ headers: [...stored.headers, ["idempotent-replayed", "true"]]
991
+ });
992
+ }
993
+ if (inFlight.has(slot))
994
+ return errors.conflict();
995
+ let release = () => {
996
+ };
997
+ inFlight.set(slot, new Promise((resolve) => {
998
+ release = resolve;
999
+ }));
1000
+ try {
1001
+ const response = await handler();
1002
+ if (!replayable(response.status))
1003
+ return response;
1004
+ const body = await response.clone().text();
1005
+ this.responses.insert(key2, {
1006
+ fingerprint,
1007
+ status: response.status,
1008
+ headers: [...response.headers],
1009
+ body
1010
+ });
1011
+ return response;
1012
+ } finally {
1013
+ inFlight.delete(slot);
1014
+ release();
1015
+ }
1016
+ }
1017
+ };
1018
+ var requestFingerprint = (method, path, body) => `${method.toUpperCase()} ${path} ${stableStringify(body)}`;
1019
+ var stableStringify = (value) => {
1020
+ if (Array.isArray(value))
1021
+ return `[${value.map(stableStringify).join(",")}]`;
1022
+ if (value && typeof value === "object") {
1023
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
1024
+ }
1025
+ return JSON.stringify(value) ?? "undefined";
1026
+ };
1027
+
1028
+ // ../core/dist/ids.js
1029
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1030
+ var mix = (input) => {
1031
+ let hash = 2166136261;
1032
+ for (let i = 0; i < input.length; i++) {
1033
+ hash ^= input.charCodeAt(i);
1034
+ hash = Math.imul(hash, 16777619) >>> 0;
1035
+ }
1036
+ hash ^= hash >>> 16;
1037
+ hash = Math.imul(hash, 2246822507) >>> 0;
1038
+ hash ^= hash >>> 13;
1039
+ return hash >>> 0;
1040
+ };
1041
+ var opaqueToken = (input, length) => {
1042
+ let out = "";
1043
+ let round = 0;
1044
+ while (out.length < length) {
1045
+ let hash = mix(`${input}:${round++}`);
1046
+ for (let i = 0; i < 5 && out.length < length; i++) {
1047
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1048
+ hash = Math.floor(hash / ALPHABET.length);
1049
+ }
1050
+ }
1051
+ return out;
1052
+ };
1053
+ var IdSequence = class {
1054
+ sqlite;
1055
+ namespace;
1056
+ salt;
1057
+ constructor(sqlite, namespace, salt = "mockingbird") {
1058
+ this.sqlite = sqlite;
1059
+ this.namespace = namespace;
1060
+ this.salt = salt;
1061
+ }
1062
+ next(prefix, length = 14) {
1063
+ return this.sqlite.transaction(() => {
1064
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
1065
+ const value = (row?.value ?? 0) + 1;
1066
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
1067
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
1068
+ return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
1069
+ });
1070
+ }
1071
+ };
1072
+
1073
+ // ../core/dist/journal.js
1074
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1075
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1076
+ const capacity = Math.max(0, Math.floor(size));
1077
+ const rings = /* @__PURE__ */ new Map();
1078
+ let sequence = 0;
1079
+ const order = /* @__PURE__ */ new WeakMap();
1080
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1081
+ return {
1082
+ size: capacity,
1083
+ record(entry) {
1084
+ if (capacity === 0)
1085
+ return;
1086
+ order.set(entry, sequence++);
1087
+ let ring = rings.get(entry.namespace);
1088
+ if (!ring) {
1089
+ ring = { entries: [], next: 0 };
1090
+ rings.set(entry.namespace, ring);
1091
+ }
1092
+ if (ring.entries.length < capacity)
1093
+ ring.entries.push(entry);
1094
+ else {
1095
+ ring.entries[ring.next] = entry;
1096
+ ring.next = (ring.next + 1) % capacity;
1097
+ }
1098
+ },
1099
+ list(query = {}) {
1100
+ const source = query.namespace !== void 0 ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 }) : [...rings.values()].flatMap(inOrder).sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1101
+ const matched = source.filter((entry) => (query.operationId === void 0 || entry.operationId === query.operationId) && (query.status === void 0 || entry.status === query.status) && (query.since === void 0 || Date.parse(entry.at) >= query.since));
1102
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1103
+ },
1104
+ clear(namespace) {
1105
+ if (namespace === void 0)
1106
+ rings.clear();
1107
+ else
1108
+ rings.delete(namespace);
1109
+ }
1110
+ };
1111
+ };
1112
+ var notes = /* @__PURE__ */ new WeakMap();
1113
+ var annotateResponse = (response, extra) => {
1114
+ const existing = notes.get(response);
1115
+ notes.set(response, {
1116
+ ...existing,
1117
+ ...extra,
1118
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1119
+ });
1120
+ return response;
1121
+ };
1122
+ var responseNotes = (response) => notes.get(response);
1123
+
1124
+ // ../core/dist/metrics.js
1125
+ var createMetrics = () => {
1126
+ let requests = 0;
1127
+ let faults = 0;
1128
+ let totalDurationMs = 0;
1129
+ const byOperation = /* @__PURE__ */ new Map();
1130
+ const unmatched = /* @__PURE__ */ new Map();
1131
+ return {
1132
+ record(entry) {
1133
+ requests++;
1134
+ totalDurationMs += entry.durationMs;
1135
+ if (entry.faultId !== void 0)
1136
+ faults++;
1137
+ const key2 = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1138
+ byOperation.set(key2, (byOperation.get(key2) ?? 0) + 1);
1139
+ if (entry.unmatched) {
1140
+ const route = `${entry.method} ${entry.path}`;
1141
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1142
+ }
1143
+ },
1144
+ report: () => ({
1145
+ requests,
1146
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1147
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1148
+ const space = route.indexOf(" ");
1149
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1150
+ }),
1151
+ faults,
1152
+ totalDurationMs
1153
+ }),
1154
+ reset() {
1155
+ requests = 0;
1156
+ faults = 0;
1157
+ totalDurationMs = 0;
1158
+ byOperation.clear();
1159
+ unmatched.clear();
1160
+ }
1161
+ };
1162
+ };
1163
+
1164
+ // ../../core/dist/timeline.js
1165
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1166
+ var Timeline = class {
1167
+ maxCheckpoints;
1168
+ now;
1169
+ makeId;
1170
+ nodes = /* @__PURE__ */ new Map();
1171
+ heads = /* @__PURE__ */ new Map();
1172
+ /** Unreferenced nodes in the exact order they became collectible. */
1173
+ evictable = /* @__PURE__ */ new Set();
1174
+ /** Branch heads plus explicit retainers. Absent means zero. */
1175
+ references = /* @__PURE__ */ new Map();
1176
+ explicitPins = /* @__PURE__ */ new Map();
1177
+ sequence = 0;
1178
+ constructor(options = {}) {
1179
+ const max = options.maxCheckpoints ?? 1e3;
1180
+ if (!Number.isSafeInteger(max) || max < 1)
1181
+ throw new RangeError("maxCheckpoints must be a positive integer");
1182
+ this.maxCheckpoints = max;
1183
+ this.now = options.now ?? (() => this.sequence);
1184
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1185
+ }
1186
+ /** Capture a new immutable value and move `branch` to it. */
1187
+ commit(value, options = {}) {
1188
+ const branch = options.branch ?? "main";
1189
+ this.assertBranch(branch);
1190
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1191
+ if (parent !== null && !this.nodes.has(parent))
1192
+ throw new RangeError(`no checkpoint ${parent}`);
1193
+ const id = this.makeId(++this.sequence);
1194
+ if (this.nodes.has(id))
1195
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1196
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1197
+ this.nodes.set(id, checkpoint);
1198
+ this.moveHead(branch, id);
1199
+ this.collect(this.maxCheckpoints);
1200
+ return checkpoint;
1201
+ }
1202
+ /** Create a branch pointer without copying its checkpoint value. */
1203
+ fork(branch, options = {}) {
1204
+ this.assertBranch(branch);
1205
+ if (this.heads.has(branch))
1206
+ throw new RangeError(`branch already exists: ${branch}`);
1207
+ const from = options.from ?? this.heads.get("main");
1208
+ if (from === void 0)
1209
+ return void 0;
1210
+ const checkpoint = this.get(from);
1211
+ this.moveHead(branch, checkpoint.id);
1212
+ return checkpoint;
1213
+ }
1214
+ /** Move a branch pointer to an existing checkpoint. */
1215
+ checkout(branch, id) {
1216
+ this.assertBranch(branch);
1217
+ const checkpoint = this.get(id);
1218
+ this.moveHead(branch, checkpoint.id);
1219
+ return checkpoint;
1220
+ }
1221
+ get(id) {
1222
+ const checkpoint = this.nodes.get(id);
1223
+ if (!checkpoint)
1224
+ throw new RangeError(`no checkpoint ${id}`);
1225
+ return checkpoint;
1226
+ }
1227
+ head(branch = "main") {
1228
+ const id = this.heads.get(branch);
1229
+ return id === void 0 ? void 0 : this.get(id);
1230
+ }
1231
+ hasBranch(branch) {
1232
+ return this.heads.has(branch);
1233
+ }
1234
+ branches() {
1235
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1236
+ }
1237
+ checkpoints() {
1238
+ return [...this.nodes.values()];
1239
+ }
1240
+ /** Number of retained checkpoints without allocating an array. */
1241
+ get size() {
1242
+ return this.nodes.size;
1243
+ }
1244
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1245
+ retain(id) {
1246
+ const checkpoint = this.get(id);
1247
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1248
+ this.addReference(id);
1249
+ return checkpoint;
1250
+ }
1251
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1252
+ release(id) {
1253
+ if (!this.nodes.has(id))
1254
+ return false;
1255
+ const pins = this.explicitPins.get(id) ?? 0;
1256
+ if (pins === 0)
1257
+ return false;
1258
+ if (pins === 1)
1259
+ this.explicitPins.delete(id);
1260
+ else
1261
+ this.explicitPins.set(id, pins - 1);
1262
+ this.removeReference(id);
1263
+ this.collect(this.maxCheckpoints);
1264
+ return true;
1265
+ }
1266
+ deleteBranch(branch) {
1267
+ if (branch === "main")
1268
+ throw new RangeError("cannot delete main branch");
1269
+ const previous = this.heads.get(branch);
1270
+ const deleted = this.heads.delete(branch);
1271
+ if (previous !== void 0)
1272
+ this.removeReference(previous);
1273
+ this.collect(this.maxCheckpoints);
1274
+ return deleted;
1275
+ }
1276
+ /**
1277
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1278
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1279
+ * storage dependency, so a retained node remains usable after pruning.
1280
+ */
1281
+ gc(max = this.maxCheckpoints) {
1282
+ if (!Number.isSafeInteger(max) || max < 1)
1283
+ throw new RangeError("max must be a positive integer");
1284
+ const removed = [];
1285
+ this.collect(max, removed);
1286
+ return removed;
1287
+ }
1288
+ collect(max, removed) {
1289
+ while (this.nodes.size > max && this.evictable.size > 0) {
1290
+ const id = this.evictable.values().next().value;
1291
+ this.evictable.delete(id);
1292
+ this.nodes.delete(id);
1293
+ removed?.push(id);
1294
+ }
1295
+ }
1296
+ moveHead(branch, id) {
1297
+ const previous = this.heads.get(branch);
1298
+ if (previous === id)
1299
+ return;
1300
+ if (previous !== void 0)
1301
+ this.removeReference(previous);
1302
+ this.heads.set(branch, id);
1303
+ this.addReference(id);
1304
+ }
1305
+ addReference(id) {
1306
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1307
+ this.evictable.delete(id);
1308
+ }
1309
+ removeReference(id) {
1310
+ const next = (this.references.get(id) ?? 0) - 1;
1311
+ if (next > 0)
1312
+ this.references.set(id, next);
1313
+ else {
1314
+ this.references.delete(id);
1315
+ if (this.nodes.has(id))
1316
+ this.evictable.add(id);
1317
+ }
1318
+ }
1319
+ assertBranch(branch) {
1320
+ if (!BRANCH_PATTERN.test(branch))
1321
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1322
+ }
1323
+ };
1324
+
1325
+ // ../../sqlite/dist/default.js
1326
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1327
+ var createDefaultSqlite = () => new Database();
1328
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1329
+
1330
+ // ../../sqlite/dist/migrate.js
1331
+ var ensureMigrationsTable = (sqlite) => {
1332
+ sqlite.exec(`
1333
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1334
+ id TEXT PRIMARY KEY NOT NULL,
1335
+ applied_at INTEGER NOT NULL
1336
+ )
1337
+ `);
1338
+ };
1339
+ var migrate = (sqlite, migrations) => {
1340
+ ensureMigrationsTable(sqlite);
1341
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1342
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1343
+ if (pending.length === 0)
1344
+ return;
1345
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1346
+ const now = Math.floor(Date.now() / 1e3);
1347
+ sqlite.transaction(() => {
1348
+ for (const migration of pending) {
1349
+ sqlite.exec(migration.sql);
1350
+ insert.run(migration.id, now);
1351
+ }
1352
+ });
1353
+ };
1354
+
1355
+ // ../../sqlite/dist/schema.js
1356
+ var CORE_MIGRATIONS = [
1357
+ {
1358
+ id: "20260322_core_records_sequences",
1359
+ sql: `
1360
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1361
+ namespace TEXT NOT NULL,
1362
+ collection TEXT NOT NULL,
1363
+ id TEXT NOT NULL,
1364
+ seq INTEGER NOT NULL,
1365
+ value TEXT NOT NULL,
1366
+ PRIMARY KEY (namespace, collection, id)
1367
+ );
1368
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1369
+ ON mockingbird_records (namespace, collection, seq);
1370
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1371
+ namespace TEXT NOT NULL,
1372
+ name TEXT NOT NULL,
1373
+ kind TEXT NOT NULL,
1374
+ value INTEGER NOT NULL,
1375
+ PRIMARY KEY (namespace, name, kind)
1376
+ );
1377
+ `
1378
+ }
1379
+ ];
1380
+ var migrateCore = (sqlite) => {
1381
+ migrate(sqlite, CORE_MIGRATIONS);
1382
+ };
1383
+ var clearNamespace = (sqlite, namespace) => {
1384
+ sqlite.transaction(() => {
1385
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1386
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1387
+ });
1388
+ };
1389
+
1390
+ // ../../openapi/metadata/dist/types.js
1391
+ var EXTENSION_KEYS = {
1392
+ operation: "x-mockingbird",
1393
+ resource: "x-mockingbird-resource",
1394
+ resourceRef: "x-mockingbird-resource-ref",
1395
+ volatile: "x-mockingbird-volatile",
1396
+ scope: "x-mockingbird-scope",
1397
+ unsupported: "x-mockingbird-unsupported",
1398
+ parityHeader: "x-mockingbird-parity-header"
1399
+ };
1400
+
1401
+ // ../../openapi/metadata/dist/read.js
1402
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1403
+ var extensionOf = (holder, key2) => holder[key2];
1404
+ var operationMetadata = (operation) => {
1405
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1406
+ const ext = isRecord2(raw) ? raw : {};
1407
+ const supported = ext.supported ?? true;
1408
+ const parity = ext.parity ?? {};
1409
+ return {
1410
+ supported,
1411
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1412
+ parity: {
1413
+ enabled: supported && (parity.enabled ?? true),
1414
+ safe: parity.safe ?? true,
1415
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1416
+ }
1417
+ };
1418
+ };
1419
+
1420
+ // ../core/dist/service.js
1421
+ import { Hono } from "hono";
1422
+ var defineOperations = (handlers) => handlers;
1423
+ var OperationRegistryError = class extends Error {
1424
+ problems;
1425
+ constructor(problems) {
1426
+ super(`operation registry is inconsistent:
1427
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1428
+ this.problems = problems;
1429
+ this.name = "OperationRegistryError";
1430
+ }
1431
+ };
1432
+ var verifyOperations = (document2, handlers) => {
1433
+ const problems = [];
1434
+ const operations = listOperations(document2);
1435
+ const seen = /* @__PURE__ */ new Set();
1436
+ for (const operation of operations) {
1437
+ if (seen.has(operation.operationId))
1438
+ problems.push(`duplicate operationId ${operation.operationId}`);
1439
+ seen.add(operation.operationId);
1440
+ const supported = operationMetadata(operation.operation).supported;
1441
+ const handler = handlers[operation.operationId];
1442
+ if (supported && !handler)
1443
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1444
+ if (!supported && handler)
1445
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1446
+ }
1447
+ for (const id of Object.keys(handlers)) {
1448
+ if (!seen.has(id))
1449
+ problems.push(`handler ${id} has no OpenAPI operation`);
1450
+ }
1451
+ return problems;
1452
+ };
1453
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1454
+ var routeOrder = (a, b) => {
1455
+ const sa = a.path.split("/");
1456
+ const sb = b.path.split("/");
1457
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1458
+ const x = sa[i] ?? "";
1459
+ const y = sb[i] ?? "";
1460
+ const px = x.startsWith("{");
1461
+ const py = y.startsWith("{");
1462
+ if (px !== py)
1463
+ return px ? 1 : -1;
1464
+ if (x !== y)
1465
+ return x < y ? -1 : 1;
1466
+ }
1467
+ return 0;
1468
+ };
1469
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1470
+ var bootSqlite = (sqlite) => {
1471
+ const client = resolveSqlite(sqlite);
1472
+ migrateCore(client);
1473
+ return client;
1474
+ };
1475
+ var createService = (options) => {
1476
+ const problems = verifyOperations(options.document, options.handlers);
1477
+ if (problems.length > 0)
1478
+ throw new OperationRegistryError(problems);
1479
+ migrateCore(options.sqlite);
1480
+ const now = options.now ?? (() => Date.now());
1481
+ const app = new Hono();
1482
+ app.notFound((c) => options.notFound(c.req.raw));
1483
+ app.onError((error2, c) => options.onError(error2, c.req.raw));
1484
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1485
+ for (const operation of operations) {
1486
+ const metadata = operationMetadata(operation.operation);
1487
+ const handler = options.handlers[operation.operationId];
1488
+ const route = async (c) => {
1489
+ const request = c.req.raw;
1490
+ if (!metadata.supported || !handler) {
1491
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1492
+ }
1493
+ const url = new URL(request.url);
1494
+ const context = {
1495
+ request,
1496
+ url,
1497
+ params: c.req.param(),
1498
+ query: queryOf(url),
1499
+ body: await readBody(request),
1500
+ sqlite: options.sqlite,
1501
+ namespace: options.namespace,
1502
+ operation,
1503
+ document: options.document,
1504
+ now
1505
+ };
1506
+ const short = await options.before?.(context);
1507
+ if (short)
1508
+ return short;
1509
+ return handler(context);
1510
+ };
1511
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1512
+ }
1513
+ return {
1514
+ app,
1515
+ sqlite: options.sqlite,
1516
+ namespace: options.namespace,
1517
+ fetch: async (request) => app.fetch(request),
1518
+ reset: async () => {
1519
+ clearNamespace(options.sqlite, options.namespace);
1520
+ }
1521
+ };
1522
+ };
1523
+
1524
+ // ../core/dist/snapshot.js
1525
+ var snapshotNamespace = (sqlite, namespace) => ({
1526
+ namespace,
1527
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1528
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1529
+ });
1530
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1531
+ sqlite.transaction(() => {
1532
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1533
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1534
+ const record2 = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1535
+ for (const row of snapshot.records) {
1536
+ record2.run(namespace, row.collection, row.id, row.seq, row.value);
1537
+ }
1538
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1539
+ for (const row of snapshot.sequences) {
1540
+ sequence.run(namespace, row.name, row.kind, row.value);
1541
+ }
1542
+ });
1543
+ };
1544
+
1545
+ // ../core/dist/version.js
1546
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1547
+
1548
+ // ../core/dist/signing.js
1549
+ var encoder = new TextEncoder();
1550
+ var toBase64 = (bytes) => {
1551
+ let binary = "";
1552
+ for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
1553
+ binary += String.fromCharCode(byte);
1554
+ }
1555
+ return btoa(binary);
1556
+ };
1557
+ var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1558
+ var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1559
+ var keyBytes = (key2) => typeof key2 === "string" ? encoder.encode(key2) : key2;
1560
+ var hmac = async (algorithm, key2, message, encoding = "hex") => {
1561
+ const imported = await crypto.subtle.importKey("raw", keyBytes(key2), { name: "HMAC", hash: algorithm }, false, ["sign"]);
1562
+ const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
1563
+ return encoding === "hex" ? toHex(signed) : toBase64(signed);
1564
+ };
1565
+ var svixSecretBytes = (secret) => {
1566
+ const raw = secret.replace(/^f?whsec_/, "");
1567
+ try {
1568
+ return fromBase64(raw);
1569
+ } catch {
1570
+ throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
1571
+ }
1572
+ };
1573
+ var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
1574
+ var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
1575
+ var signTwilio = async (authToken, url, params) => {
1576
+ const payload = url + Object.keys(params).sort().map((key2) => `${key2}${params[key2]}`).join("");
1577
+ return hmac("SHA-1", authToken, payload, "base64");
1578
+ };
1579
+ var timingSafeEqual = (a, b) => {
1580
+ if (a.length !== b.length)
1581
+ return false;
1582
+ let diff = 0;
1583
+ for (let i = 0; i < a.length; i++)
1584
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1585
+ return diff === 0;
1586
+ };
1587
+
1588
+ // ../core/dist/webhooks.js
1589
+ var signers = {
1590
+ /** No signature. */
1591
+ none: () => () => ({}),
1592
+ /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
1593
+ svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
1594
+ if (!secret)
1595
+ return {};
1596
+ const prefix = options.prefix ?? "svix";
1597
+ return {
1598
+ [`${prefix}-id`]: messageId,
1599
+ [`${prefix}-timestamp`]: String(timestampSeconds),
1600
+ [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
1601
+ };
1602
+ },
1603
+ /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
1604
+ timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
1605
+ /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
1606
+ twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
1607
+ /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
1608
+ header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
1609
+ /** Anything else: the service computes the headers itself. */
1610
+ custom: (sign) => sign
1611
+ };
1612
+ var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
1613
+ var unref = (timer) => {
1614
+ ;
1615
+ timer.unref?.();
1616
+ };
1617
+ var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
1618
+ var matchesEndpoint = (endpoint, message) => {
1619
+ const events = endpoint.events ?? ["*"];
1620
+ if (!events.includes("*") && !events.includes(message.type))
1621
+ return false;
1622
+ for (const [key2, value] of Object.entries(endpoint.tags ?? {})) {
1623
+ if (message.tags[key2] !== value)
1624
+ return false;
1625
+ }
1626
+ return true;
1627
+ };
1628
+ var createWebhookHub = (options) => {
1629
+ const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
1630
+ const timeoutMs = options.timeoutMs ?? 15e3;
1631
+ const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
1632
+ const send = options.fetch ?? ((request) => fetch(request));
1633
+ const keep = options.keep ?? 500;
1634
+ const now = options.now ?? Date.now;
1635
+ const id = options.id ?? randomId;
1636
+ const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
1637
+ const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
1638
+ const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
1639
+ const own = /* @__PURE__ */ new Map();
1640
+ const messages = [];
1641
+ const deliveries = /* @__PURE__ */ new Map();
1642
+ const pending = /* @__PURE__ */ new Map();
1643
+ const payloads = /* @__PURE__ */ new Map();
1644
+ const faults = /* @__PURE__ */ new Map();
1645
+ const held = /* @__PURE__ */ new Map();
1646
+ const inFlight2 = /* @__PURE__ */ new Set();
1647
+ const track = (work) => {
1648
+ inFlight2.add(work);
1649
+ void work.finally(() => inFlight2.delete(work));
1650
+ };
1651
+ const attempt = async (delivery) => {
1652
+ const entry = payloads.get(delivery.id);
1653
+ if (!entry)
1654
+ return false;
1655
+ const { message, endpoint } = entry;
1656
+ const timestampSeconds = Math.floor(now() / 1e3);
1657
+ const started = now();
1658
+ const record2 = {
1659
+ attempt: delivery.attempts.length + 1,
1660
+ at: new Date(started).toISOString(),
1661
+ status: null,
1662
+ error: null,
1663
+ durationMs: 0,
1664
+ responseBody: null
1665
+ };
1666
+ const controller = new AbortController();
1667
+ const timer = scheduleTimer(() => controller.abort(), timeoutMs);
1668
+ try {
1669
+ const signed = await options.signer({
1670
+ messageId: message.id,
1671
+ body: message.body,
1672
+ timestampSeconds,
1673
+ url: endpoint.url,
1674
+ secret: endpoint.secret,
1675
+ signUrl: endpoint.signUrl ?? endpoint.url,
1676
+ form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
1677
+ type: message.type,
1678
+ tags: message.tags
1679
+ });
1680
+ const response = await send(new Request(endpoint.url, {
1681
+ method: "POST",
1682
+ headers: {
1683
+ "content-type": message.contentType,
1684
+ ...endpoint.headers,
1685
+ ...message.headers,
1686
+ ...signed
1687
+ },
1688
+ body: message.body,
1689
+ signal: controller.signal
1690
+ }));
1691
+ record2.status = response.status;
1692
+ record2.responseBody = await response.text();
1693
+ } catch (error2) {
1694
+ record2.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error2 instanceof Error ? error2.message : String(error2);
1695
+ } finally {
1696
+ cancel(timer);
1697
+ record2.durationMs = now() - started;
1698
+ delivery.attempts.push(record2);
1699
+ }
1700
+ return record2.status !== null && delivered(record2.status);
1701
+ };
1702
+ const schedule = (delivery) => {
1703
+ const index = delivery.attempts.length;
1704
+ if (index >= delays.length) {
1705
+ delivery.state = "failed";
1706
+ pending.delete(delivery.id);
1707
+ return;
1708
+ }
1709
+ const run = () => {
1710
+ pending.delete(delivery.id);
1711
+ track(attempt(delivery).then((ok) => {
1712
+ if (ok)
1713
+ delivery.state = "delivered";
1714
+ else
1715
+ schedule(delivery);
1716
+ }));
1717
+ };
1718
+ const delay = delays[index] ?? 0;
1719
+ if (delay <= 0) {
1720
+ pending.set(delivery.id, void 0);
1721
+ run();
1722
+ return;
1723
+ }
1724
+ const timer = scheduleTimer(run, delay);
1725
+ unref(timer);
1726
+ pending.set(delivery.id, timer);
1727
+ };
1728
+ const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
1729
+ const fanOut = (message, state = "pending") => {
1730
+ for (const endpoint of endpointsFor(message.namespace)) {
1731
+ if (!matchesEndpoint(endpoint, message))
1732
+ continue;
1733
+ const delivery = {
1734
+ id: id("dlv_"),
1735
+ messageId: message.id,
1736
+ namespace: message.namespace,
1737
+ type: message.type,
1738
+ endpointId: endpoint.id ?? "we_unknown",
1739
+ url: endpoint.url,
1740
+ state,
1741
+ attempts: []
1742
+ };
1743
+ deliveries.set(delivery.id, delivery);
1744
+ payloads.set(delivery.id, { message, endpoint });
1745
+ if (state === "pending")
1746
+ schedule(delivery);
1747
+ }
1748
+ };
1749
+ const takeFault = (namespace) => {
1750
+ const queue = faults.get(namespace);
1751
+ const head = queue?.[0];
1752
+ if (!queue || !head)
1753
+ return void 0;
1754
+ head.remaining--;
1755
+ if (head.remaining <= 0)
1756
+ queue.shift();
1757
+ return head.mode;
1758
+ };
1759
+ const releaseHeld = (namespace) => {
1760
+ const waiting = held.get(namespace);
1761
+ if (!waiting)
1762
+ return;
1763
+ held.delete(namespace);
1764
+ for (const message of waiting)
1765
+ fanOut(message);
1766
+ };
1767
+ const hub = {
1768
+ publish(input) {
1769
+ const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
1770
+ const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
1771
+ const message = {
1772
+ id: input.id ?? id("msg_"),
1773
+ namespace: input.namespace,
1774
+ type: input.type,
1775
+ body,
1776
+ contentType,
1777
+ tags: input.tags ?? {},
1778
+ headers: input.headers ?? {},
1779
+ publishedAt: new Date(now()).toISOString()
1780
+ };
1781
+ messages.push(message);
1782
+ const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
1783
+ const oldest = ofNamespace[0];
1784
+ if (ofNamespace.length > keep && oldest)
1785
+ messages.splice(messages.indexOf(oldest), 1);
1786
+ options.onMessage?.(message);
1787
+ const fault = takeFault(message.namespace);
1788
+ if (fault === "drop") {
1789
+ fanOut(message, "dropped");
1790
+ return message;
1791
+ }
1792
+ if (fault === "reorder") {
1793
+ held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
1794
+ return message;
1795
+ }
1796
+ fanOut(message);
1797
+ if (fault === "duplicate")
1798
+ fanOut(message);
1799
+ releaseHeld(message.namespace);
1800
+ return message;
1801
+ },
1802
+ setEndpoints(namespace, endpoints) {
1803
+ const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
1804
+ own.set(namespace, withIds);
1805
+ return withIds;
1806
+ },
1807
+ endpoints: endpointsFor,
1808
+ messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
1809
+ deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
1810
+ async replay(id2) {
1811
+ const delivery = deliveries.get(id2);
1812
+ if (!delivery)
1813
+ return void 0;
1814
+ const ok = await attempt(delivery);
1815
+ if (ok)
1816
+ delivery.state = "delivered";
1817
+ return delivery;
1818
+ },
1819
+ async flush() {
1820
+ for (const namespace of [...held.keys()])
1821
+ releaseHeld(namespace);
1822
+ const waiting = [...pending.entries()];
1823
+ for (const [id2, timer] of waiting) {
1824
+ if (timer === void 0)
1825
+ continue;
1826
+ cancel(timer);
1827
+ pending.delete(id2);
1828
+ const delivery = deliveries.get(id2);
1829
+ if (!delivery)
1830
+ continue;
1831
+ track(attempt(delivery).then((ok) => {
1832
+ if (ok)
1833
+ delivery.state = "delivered";
1834
+ else
1835
+ schedule(delivery);
1836
+ }));
1837
+ }
1838
+ await hub.idle();
1839
+ },
1840
+ async idle() {
1841
+ while (inFlight2.size > 0)
1842
+ await Promise.allSettled([...inFlight2]);
1843
+ },
1844
+ fault(namespace, fault) {
1845
+ const queue = faults.get(namespace) ?? [];
1846
+ queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
1847
+ faults.set(namespace, queue);
1848
+ },
1849
+ clear(namespace) {
1850
+ for (const [id2, delivery] of deliveries) {
1851
+ if (namespace !== void 0 && delivery.namespace !== namespace)
1852
+ continue;
1853
+ const timer = pending.get(id2);
1854
+ if (timer !== void 0)
1855
+ cancel(timer);
1856
+ pending.delete(id2);
1857
+ deliveries.delete(id2);
1858
+ payloads.delete(id2);
1859
+ }
1860
+ for (let i = messages.length - 1; i >= 0; i--) {
1861
+ if (namespace === void 0 || messages[i]?.namespace === namespace)
1862
+ messages.splice(i, 1);
1863
+ }
1864
+ if (namespace === void 0) {
1865
+ held.clear();
1866
+ faults.clear();
1867
+ own.clear();
1868
+ } else {
1869
+ held.delete(namespace);
1870
+ faults.delete(namespace);
1871
+ own.delete(namespace);
1872
+ }
1873
+ }
1874
+ };
1875
+ return hub;
1876
+ };
1877
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1878
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1879
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1880
+ var parseEndpoint = (value) => {
1881
+ if (!isRecord3(value) || typeof value.url !== "string")
1882
+ return "each endpoint needs a url";
1883
+ try {
1884
+ new URL(value.url);
1885
+ } catch {
1886
+ return `not a URL: ${value.url}`;
1887
+ }
1888
+ const endpoint = { url: value.url };
1889
+ if (typeof value.id === "string")
1890
+ endpoint.id = value.id;
1891
+ if (typeof value.secret === "string")
1892
+ endpoint.secret = value.secret;
1893
+ if (typeof value.signUrl === "string")
1894
+ endpoint.signUrl = value.signUrl;
1895
+ const events = value.events ?? value.enabledEvents;
1896
+ if (Array.isArray(events))
1897
+ endpoint.events = events.map(String);
1898
+ if (isRecord3(value.tags)) {
1899
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1900
+ }
1901
+ if (typeof value.account === "string")
1902
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1903
+ if (isRecord3(value.headers)) {
1904
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1905
+ }
1906
+ return endpoint;
1907
+ };
1908
+ var webhookAdminRoutes = (hub) => ({
1909
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1910
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1911
+ const type = url.searchParams.get("type");
1912
+ return type === null || d.type === type;
1913
+ })
1914
+ }),
1915
+ "GET /webhooks/events": ({ url, namespace }) => {
1916
+ const type = url.searchParams.get("type");
1917
+ return json2(200, {
1918
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1919
+ });
1920
+ },
1921
+ "POST /webhooks/:id/replay": async ({ params }) => {
1922
+ const replayed = await hub.replay(params.id);
1923
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1924
+ },
1925
+ "POST /webhooks/flush": async () => {
1926
+ await hub.flush();
1927
+ return json2(200, { status: "ok" });
1928
+ },
1929
+ "POST /webhooks/faults": ({ body, namespace }) => {
1930
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1931
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1932
+ }
1933
+ const fault = { mode: body.mode };
1934
+ if (typeof body.count === "number")
1935
+ fault.count = body.count;
1936
+ hub.fault(namespace, fault);
1937
+ return json2(201, { namespace, ...fault });
1938
+ },
1939
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1940
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1941
+ ...rest,
1942
+ secret: secret ? "(set)" : null
1943
+ }))
1944
+ }),
1945
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1946
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1947
+ if (!Array.isArray(list))
1948
+ return adminError2(400, "expected [{url, secret?, events?}]");
1949
+ const parsed = [];
1950
+ for (const each of list) {
1951
+ const endpoint = parseEndpoint(each);
1952
+ if (typeof endpoint === "string")
1953
+ return adminError2(400, endpoint);
1954
+ parsed.push(endpoint);
1955
+ }
1956
+ const set = hub.setEndpoints(namespace, parsed);
1957
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1958
+ },
1959
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1960
+ hub.setEndpoints(namespace, []);
1961
+ return json2(200, { status: "ok" });
1962
+ }
1963
+ });
1964
+ var parsePayload = (message) => {
1965
+ if (message.contentType.startsWith("application/json")) {
1966
+ try {
1967
+ return JSON.parse(message.body);
1968
+ } catch {
1969
+ return message.body;
1970
+ }
1971
+ }
1972
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1973
+ return Object.fromEntries(new URLSearchParams(message.body));
1974
+ }
1975
+ return message.body;
1976
+ };
1977
+
1978
+ // ../core/dist/runtime.js
1979
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1980
+ var BRANCH_HEADER = "x-mockingbird-branch";
1981
+ var AT_HEADER = "x-mockingbird-at";
1982
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1983
+ var DEFAULT_NAMESPACE = "default";
1984
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1985
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1986
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1987
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1988
+ var effects = /* @__PURE__ */ new WeakMap();
1989
+ var reuseSorted = (fresh, previous, compare, equal) => {
1990
+ if (!previous || previous.length === 0)
1991
+ return fresh.map((row) => Object.freeze(row));
1992
+ const result = new Array(fresh.length);
1993
+ let unchanged = fresh.length === previous.length;
1994
+ let oldIndex = 0;
1995
+ for (let index = 0; index < fresh.length; index++) {
1996
+ const row = fresh[index];
1997
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1998
+ oldIndex++;
1999
+ }
2000
+ const old = previous[oldIndex];
2001
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
2002
+ if (result[index] !== previous[index])
2003
+ unchanged = false;
2004
+ }
2005
+ return unchanged ? previous : result;
2006
+ };
2007
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
2008
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
2009
+ var DroppedConnectionError = class extends TypeError {
2010
+ code = "MOCKINGBIRD_DROP";
2011
+ constructor() {
2012
+ super("fetch failed: connection dropped by Mockingbird fault");
2013
+ this.name = "TypeError";
2014
+ }
2015
+ };
2016
+ var operationMatcher = (document2) => {
2017
+ const matchers = listOperations(document2).map((operation) => ({
2018
+ operationId: operation.operationId,
2019
+ method: operation.method.toUpperCase(),
2020
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
2021
+ params: (operation.path.match(/\{/g) ?? []).length
2022
+ })).sort((a, b) => a.params - b.params);
2023
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2024
+ };
2025
+ var createRuntime = (options) => {
2026
+ const sqlite = bootSqlite(options.sqlite);
2027
+ const clock = options.clock ?? createClock();
2028
+ const rng = createRng(options.seed ?? 0);
2029
+ const wallNow = options.io?.wallNow ?? Date.now;
2030
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
2031
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
2032
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
2033
+ const metrics = createMetrics();
2034
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
2035
+ const version = options.version ?? PACKAGE_VERSION;
2036
+ const instances = /* @__PURE__ */ new Map();
2037
+ const publicNamespaces = /* @__PURE__ */ new Set();
2038
+ const branchRngs = /* @__PURE__ */ new Map();
2039
+ const timelines = /* @__PURE__ */ new Map();
2040
+ const branchStorage = /* @__PURE__ */ new Map();
2041
+ const captured = /* @__PURE__ */ new Map();
2042
+ const credentials = createCredentialRegistry();
2043
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
2044
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
2045
+ const instanceFor = (key2, publicNamespace = key2, isolatedRng) => {
2046
+ const existing = instances.get(key2);
2047
+ if (existing)
2048
+ return existing;
2049
+ if (!NAMESPACE_PATTERN.test(key2) || !NAMESPACE_PATTERN.test(publicNamespace)) {
2050
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
2051
+ }
2052
+ const created = options.create({
2053
+ namespace: storageNamespace(key2),
2054
+ publicNamespace,
2055
+ sqlite,
2056
+ clock,
2057
+ rng: isolatedRng ?? rng
2058
+ });
2059
+ instances.set(key2, created);
2060
+ publicNamespaces.add(publicNamespace);
2061
+ if (isolatedRng)
2062
+ branchRngs.set(key2, isolatedRng);
2063
+ return created;
2064
+ };
2065
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
2066
+ const capture = (storage) => {
2067
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
2068
+ const previous = captured.get(storage);
2069
+ const snapshot2 = {
2070
+ namespace: fresh.namespace,
2071
+ records: reuseSorted(fresh.records, previous?.records, (left, right) => left.collection < right.collection ? -1 : left.collection > right.collection ? 1 : left.seq - right.seq, (left, right) => left.id === right.id && left.value === right.value),
2072
+ sequences: reuseSorted(fresh.sequences, previous?.sequences, (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.kind < right.kind ? -1 : left.kind > right.kind ? 1 : 0, (left, right) => left.value === right.value)
2073
+ };
2074
+ Object.freeze(snapshot2.records);
2075
+ Object.freeze(snapshot2.sequences);
2076
+ Object.freeze(snapshot2);
2077
+ captured.set(storage, snapshot2);
2078
+ return Object.freeze({
2079
+ snapshot: snapshot2,
2080
+ clock: Object.freeze(clock.state()),
2081
+ rngState: (branchRngs.get(storage) ?? rng).state()
2082
+ });
2083
+ };
2084
+ const timeline = (name = DEFAULT_NAMESPACE) => {
2085
+ let found = timelines.get(name);
2086
+ if (found)
2087
+ return found;
2088
+ instance(name);
2089
+ found = new Timeline({
2090
+ now: clock.now,
2091
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
2092
+ });
2093
+ found.commit(capture(name));
2094
+ timelines.set(name, found);
2095
+ return found;
2096
+ };
2097
+ const physicalBranch = (namespace, branch2) => {
2098
+ if (branch2 === "main")
2099
+ return namespace;
2100
+ const mapKey = `${namespace}\0${branch2}`;
2101
+ const existing = branchStorage.get(mapKey);
2102
+ if (existing)
2103
+ return existing;
2104
+ const key2 = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
2105
+ branchStorage.set(mapKey, key2);
2106
+ return key2;
2107
+ };
2108
+ const ensureBranch = (namespace, branch2, at) => {
2109
+ if (!BRANCH_PATTERN2.test(branch2))
2110
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2111
+ const history = timeline(namespace);
2112
+ if (branch2 === "main") {
2113
+ if (at !== void 0) {
2114
+ const point = history.checkout("main", at);
2115
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2116
+ captured.set(namespace, point.value.snapshot);
2117
+ rng.setState(point.value.rngState);
2118
+ clock.set(point.value.clock.now);
2119
+ if (point.value.clock.frozen)
2120
+ clock.freeze();
2121
+ else
2122
+ clock.unfreeze();
2123
+ }
2124
+ return namespace;
2125
+ }
2126
+ const storage = physicalBranch(namespace, branch2);
2127
+ if (!history.hasBranch(branch2)) {
2128
+ if (at === void 0)
2129
+ history.commit(capture(namespace));
2130
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
2131
+ const branchRng = createRng(options.seed ?? 0);
2132
+ if (point)
2133
+ branchRng.setState(point.value.rngState);
2134
+ instanceFor(storage, namespace, branchRng);
2135
+ if (point)
2136
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2137
+ if (point)
2138
+ captured.set(storage, point.value.snapshot);
2139
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2140
+ const point = history.checkout(branch2, at);
2141
+ if (!instances.has(storage)) {
2142
+ const branchRng = createRng(options.seed ?? 0);
2143
+ branchRng.setState(point.value.rngState);
2144
+ instanceFor(storage, namespace, branchRng);
2145
+ }
2146
+ branchRngs.get(storage)?.setState(point.value.rngState);
2147
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2148
+ captured.set(storage, point.value.snapshot);
2149
+ } else {
2150
+ if (!instances.has(storage)) {
2151
+ const point = history.head(branch2);
2152
+ const branchRng = createRng(options.seed ?? 0);
2153
+ if (point)
2154
+ branchRng.setState(point.value.rngState);
2155
+ instanceFor(storage, namespace, branchRng);
2156
+ }
2157
+ }
2158
+ return storage;
2159
+ };
2160
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
2161
+ const storage = ensureBranch(namespace, branch2);
2162
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
2163
+ };
2164
+ const branch = (name, branchOptions = {}) => {
2165
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
2166
+ ensureBranch(namespace, name, branchOptions.at);
2167
+ const head = timeline(namespace).head(name);
2168
+ if (!head)
2169
+ throw new RangeError(`branch ${name} has no checkpoint`);
2170
+ return head;
2171
+ };
2172
+ const checkout = (checkpointId, checkoutOptions = {}) => {
2173
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2174
+ const branchName = checkoutOptions.branch ?? "main";
2175
+ const history = timeline(namespace);
2176
+ const point = history.checkout(branchName, checkpointId);
2177
+ const storage = ensureBranch(namespace, branchName);
2178
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2179
+ captured.set(storage, point.value.snapshot);
2180
+ clock.set(point.value.clock.now);
2181
+ if (point.value.clock.frozen)
2182
+ clock.freeze();
2183
+ else
2184
+ clock.unfreeze();
2185
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
2186
+ };
2187
+ const reset = async (name = DEFAULT_NAMESPACE) => {
2188
+ if (name === "*") {
2189
+ options.webhooks?.clear();
2190
+ for (const each of instances.values())
2191
+ await each.reset();
2192
+ timelines.clear();
2193
+ branchStorage.clear();
2194
+ branchRngs.clear();
2195
+ captured.clear();
2196
+ return;
2197
+ }
2198
+ options.webhooks?.clear(name);
2199
+ const target = instances.get(name);
2200
+ if (target)
2201
+ await target.reset();
2202
+ else
2203
+ clearNamespace(sqlite, storageNamespace(name));
2204
+ for (const [mapping, storage] of branchStorage) {
2205
+ if (!mapping.startsWith(`${name}\0`))
2206
+ continue;
2207
+ const branchInstance = instances.get(storage);
2208
+ if (branchInstance)
2209
+ await branchInstance.reset();
2210
+ else
2211
+ clearNamespace(sqlite, storageNamespace(storage));
2212
+ branchStorage.delete(mapping);
2213
+ branchRngs.delete(storage);
2214
+ captured.delete(storage);
2215
+ }
2216
+ timelines.delete(name);
2217
+ captured.delete(name);
2218
+ };
2219
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
2220
+ return checkpoint(name, "main").value.snapshot;
2221
+ };
2222
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
2223
+ instance(name);
2224
+ restoreNamespace(sqlite, storageNamespace(name), from);
2225
+ captured.set(name, from);
2226
+ const history = timelines.get(name);
2227
+ if (history)
2228
+ history.commit(capture(name), { branch: "main" });
2229
+ else
2230
+ timeline(name);
2231
+ };
2232
+ const runtime = {
2233
+ name: options.name,
2234
+ sqlite,
2235
+ clock,
2236
+ faults,
2237
+ metrics,
2238
+ journal,
2239
+ rng,
2240
+ credentials,
2241
+ webhooks: options.webhooks,
2242
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
2243
+ const preset = options.presets?.[name];
2244
+ if (!preset)
2245
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
2246
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
2247
+ namespace,
2248
+ ...rule,
2249
+ ...overrides,
2250
+ preset: name,
2251
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
2252
+ }));
2253
+ if (preset.webhook && options.webhooks) {
2254
+ options.webhooks.fault(namespace, {
2255
+ ...preset.webhook,
2256
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
2257
+ });
2258
+ }
2259
+ return added;
2260
+ },
2261
+ instance,
2262
+ namespaces: () => [...publicNamespaces].sort(),
2263
+ reset,
2264
+ snapshot,
2265
+ restore,
2266
+ checkpoint,
2267
+ branch,
2268
+ checkout,
2269
+ timeline,
2270
+ fetch: async (incoming) => {
2271
+ let request = incoming;
2272
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
2273
+ if (prefixed) {
2274
+ const url2 = new URL(request.url);
2275
+ url2.pathname = prefixed[2] ?? "/";
2276
+ const headers = new Headers(request.headers);
2277
+ if (!headers.has(NAMESPACE_HEADER)) {
2278
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
2279
+ }
2280
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
2281
+ request = new Request(url2, {
2282
+ method: request.method,
2283
+ headers,
2284
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
2285
+ signal: request.signal
2286
+ });
2287
+ }
2288
+ let namespace = control.namespaceOf(request);
2289
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
2290
+ const credential = options.credential(request);
2291
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
2292
+ if (mapped !== void 0)
2293
+ namespace = mapped;
2294
+ }
2295
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
2296
+ const at = request.headers.get(AT_HEADER) ?? void 0;
2297
+ const stamp = (response2) => {
2298
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
2299
+ try {
2300
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
2301
+ return response2;
2302
+ } catch {
2303
+ const copy = new Response(response2.body, response2);
2304
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
2305
+ return copy;
2306
+ }
2307
+ };
2308
+ const handled = await control.handle(request);
2309
+ if (handled)
2310
+ return stamp(handled);
2311
+ const started = monotonicNow();
2312
+ const url = new URL(request.url);
2313
+ const operationId = operationIdFor(request, url.pathname);
2314
+ const log = (status, faultId, response2) => {
2315
+ const noted = response2 ? responseNotes(response2) : void 0;
2316
+ const entry = {
2317
+ service: options.name,
2318
+ namespace,
2319
+ operationId,
2320
+ method: request.method,
2321
+ path: url.pathname,
2322
+ status,
2323
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
2324
+ unmatched: options.document !== void 0 && operationId === void 0,
2325
+ ...faultId !== void 0 ? { faultId } : {},
2326
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
2327
+ ...noted?.adopted ? { adopted: true } : {}
2328
+ };
2329
+ metrics.record(entry);
2330
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
2331
+ options.onLog?.(entry);
2332
+ };
2333
+ if (!NAMESPACE_PATTERN.test(namespace)) {
2334
+ log(400);
2335
+ return stamp(new Response(JSON.stringify({
2336
+ error: {
2337
+ type: "mockingbird_admin",
2338
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
2339
+ }
2340
+ }), { status: 400, headers: { "content-type": "application/json" } }));
2341
+ }
2342
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
2343
+ log(400);
2344
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
2345
+ }
2346
+ let storage;
2347
+ try {
2348
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
2349
+ const point = timeline(namespace).get(at);
2350
+ storage = physicalBranch(namespace, `at_${at}`);
2351
+ let viewRng = branchRngs.get(storage);
2352
+ if (!viewRng) {
2353
+ viewRng = createRng(options.seed ?? 0);
2354
+ instanceFor(storage, namespace, viewRng);
2355
+ }
2356
+ viewRng.setState(point.value.rngState);
2357
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2358
+ captured.set(storage, point.value.snapshot);
2359
+ } else {
2360
+ storage = ensureBranch(namespace, selectedBranch, at);
2361
+ }
2362
+ } catch (error2) {
2363
+ log(409);
2364
+ return stamp(adminFail(409, error2 instanceof Error ? error2.message : String(error2)));
2365
+ }
2366
+ const hits = await faults.take({
2367
+ operationId,
2368
+ method: request.method,
2369
+ path: url.pathname,
2370
+ namespace
2371
+ });
2372
+ const final = hits.find((hit) => hit.drop || hit.response);
2373
+ if (final?.drop) {
2374
+ log(0, final.id);
2375
+ throw new DroppedConnectionError();
2376
+ }
2377
+ if (final?.response) {
2378
+ log(final.response.status, final.id);
2379
+ return stamp(final.response);
2380
+ }
2381
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2382
+ if (fired.length > 0)
2383
+ effects.set(request, fired.map((hit) => hit.effect));
2384
+ let response = await instanceFor(storage, namespace).fetch(request);
2385
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2386
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2387
+ response = mutableResponse(response);
2388
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2389
+ }
2390
+ if (selectedBranch !== "main") {
2391
+ response = mutableResponse(response);
2392
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2393
+ }
2394
+ if (at !== void 0) {
2395
+ response = mutableResponse(response);
2396
+ response.headers.set(AT_HEADER, at);
2397
+ }
2398
+ log(response.status, fired[0]?.id, response);
2399
+ return stamp(response);
2400
+ }
2401
+ };
2402
+ const control = createControlPlane({
2403
+ name: options.name,
2404
+ startedAt: wallNow(),
2405
+ wallNow,
2406
+ clock,
2407
+ faults,
2408
+ metrics,
2409
+ journal,
2410
+ defaultNamespace: DEFAULT_NAMESPACE,
2411
+ namespaces: runtime.namespaces,
2412
+ reset,
2413
+ timeTravel: {
2414
+ checkpoint: (name, branchName) => {
2415
+ const point = checkpoint(name, branchName);
2416
+ return {
2417
+ id: point.id,
2418
+ branch: point.branch,
2419
+ parent: point.parent,
2420
+ at: point.at,
2421
+ records: point.value.snapshot.records.length
2422
+ };
2423
+ },
2424
+ branch: (branchName, branchOptions) => {
2425
+ const point = branch(branchName, branchOptions);
2426
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2427
+ },
2428
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2429
+ retain: (name, checkpointId) => {
2430
+ timeline(name).retain(checkpointId);
2431
+ },
2432
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2433
+ inspect: (name) => {
2434
+ const history = timeline(name);
2435
+ return {
2436
+ branches: history.branches(),
2437
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2438
+ id,
2439
+ branch: branchName,
2440
+ parent,
2441
+ at
2442
+ }))
2443
+ };
2444
+ }
2445
+ },
2446
+ describe: options.describe ?? (() => ({})),
2447
+ ...options.presets ? {
2448
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2449
+ } : {},
2450
+ routes: {
2451
+ ...credentialRoutes(credentials),
2452
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2453
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2454
+ ...options.admin?.(runtime) ?? {}
2455
+ },
2456
+ adminKey: options.adminKey
2457
+ });
2458
+ return runtime;
2459
+ };
2460
+ var mutableResponse = (response) => {
2461
+ try {
2462
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2463
+ response.headers.delete("x-mockingbird-mutable-probe");
2464
+ return response;
2465
+ } catch {
2466
+ return new Response(response.body, response);
2467
+ }
2468
+ };
2469
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2470
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2471
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2472
+ var credentialRoutes = (registry) => ({
2473
+ "GET /credentials": () => adminJson(200, {
2474
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2475
+ credential: maskCredential(credential),
2476
+ namespace
2477
+ }))
2478
+ }),
2479
+ "PUT /credentials": ({ body, namespace }) => {
2480
+ const pairs = [];
2481
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2482
+ if (Array.isArray(list)) {
2483
+ for (const each of list) {
2484
+ if (typeof each === "string")
2485
+ pairs.push([each, namespace]);
2486
+ else if (isObject(each) && typeof each.credential === "string") {
2487
+ pairs.push([
2488
+ each.credential,
2489
+ typeof each.namespace === "string" ? each.namespace : namespace
2490
+ ]);
2491
+ } else
2492
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2493
+ }
2494
+ } else if (isObject(list)) {
2495
+ for (const [credential, target] of Object.entries(list)) {
2496
+ if (typeof target !== "string")
2497
+ return adminFail(400, `namespace for ${credential} must be a string`);
2498
+ pairs.push([credential, target]);
2499
+ }
2500
+ } else if (isObject(body) && typeof body.credential === "string") {
2501
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2502
+ } else {
2503
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2504
+ }
2505
+ for (const [credential, target] of pairs) {
2506
+ if (!NAMESPACE_PATTERN.test(target))
2507
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2508
+ registry.set(credential, target);
2509
+ }
2510
+ return adminJson(200, { mapped: pairs.length });
2511
+ },
2512
+ "DELETE /credentials": ({ url }) => {
2513
+ const credential = url.searchParams.get("credential");
2514
+ if (credential === null)
2515
+ registry.clear();
2516
+ else
2517
+ registry.remove(credential);
2518
+ return adminJson(200, { status: "ok" });
2519
+ }
2520
+ });
2521
+ var presetRoutes = (presets, runtime) => ({
2522
+ "GET /faults/presets": () => adminJson(200, {
2523
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2524
+ }),
2525
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2526
+ const name = params.name;
2527
+ if (!presets[name])
2528
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2529
+ const overrides = isObject(body) ? body : {};
2530
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2531
+ }
2532
+ });
2533
+
2534
+ // ../core/dist/validation.js
2535
+ var bodyIssues = (context, contentType = "application/json") => {
2536
+ const requestBody = context.operation.operation.requestBody;
2537
+ if (!requestBody)
2538
+ return [];
2539
+ const resolved = deref(context.document, requestBody);
2540
+ const schema = resolved.content?.[contentType]?.schema;
2541
+ if (!schema)
2542
+ return [];
2543
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2544
+ if (context.body.kind === "invalid") {
2545
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2546
+ }
2547
+ if (value === void 0) {
2548
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2549
+ }
2550
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2551
+ };
2552
+ var issuesByField = (issues) => {
2553
+ const out = {};
2554
+ for (const issue of issues) {
2555
+ const missing = /^missing required property (.+)$/.exec(issue.message);
2556
+ const field = missing ? [issue.path, missing[1]].filter(Boolean).join(".") : issue.path || "body";
2557
+ const message = missing ? `The ${field} field is required.` : `The ${field} field ${issue.message}.`;
2558
+ out[field] = [...out[field] ?? [], message];
2559
+ }
2560
+ return out;
2561
+ };
2562
+
2563
+ // src/generated/openapi.ts
2564
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"AHA (Advanced Health Academy) partner API (Mockingbird subset)","description":"Stateful mock of the AHA at-home phlebotomy partner API: create-or-update order and cancel.\\nThe vendor has no pull API; order state reaches the partner only as inbound webhooks, which\\nthe mock emits from admin transitions (see the README). Hand-authored from the consumer's\\nwire shapes (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from aha.service.ts, aha.types.ts (zod request/response schemas) and aha.lab-provider.ts. Success responses come in one of two envelopes (raw, or {success, data}) because our two clients disagree (G-A1); the mock serves either."}},"servers":[{"url":"https://stage-api.mobileaha.com"}],"security":[{"hmacKey":[],"hmacTimestamp":[],"hmacSignature":[]},{"legacyKey":[]}],"paths":{"/v1/geviti/create-order":{"post":{"operationId":"CreateOrder","description":"Create an order, or update it when partner_order_id already exists (the same order_number is returned). Honors X-Idempotency-Key.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderBody"}}}},"responses":{"200":{"description":"Order created or updated (raw or wrapped envelope, per namespace setting)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CreateOrderResponse"},{"$ref":"#/components/schemas/WrappedCreateOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/v1/geviti/cancel":{"post":{"operationId":"CancelOrder","description":"Cancel an order by partner_order_id. The mock also accepts the AHA order_number here, because our lab-provider client sends it in that field (G-A1).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderBody"}}}},"responses":{"200":{"description":"Cancel outcome (raw or wrapped envelope; status ERROR when not cancellable)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CancelOrderResponse"},{"$ref":"#/components/schemas/WrappedCancelOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown partner order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"hmacKey":{"type":"apiKey","in":"header","name":"X-API-KEY"},"hmacTimestamp":{"type":"apiKey","in":"header","name":"X-TIMESTAMP","description":"Unix epoch milliseconds."},"hmacSignature":{"type":"apiKey","in":"header","name":"X-SIGNATURE","description":"base64(HMAC-SHA256(apiSecret, \\"<apiKey>:<path>:<timestamp>\\"))."},"legacyKey":{"type":"apiKey","in":"header","name":"X-Geviti-Auth-Key","description":"Legacy mode (AHA_USE_LEGACY_AUTH=true), sent with X-API-Version 1.0."}},"parameters":{"IdempotencyKey":{"name":"X-Idempotency-Key","in":"header","required":false,"description":"Sent by the lab-provider client; the same key and body replays the stored response.","schema":{"type":"string","pattern":"^[A-Za-z0-9:_.-]{1,128}$"}}},"schemas":{"TestCode":{"type":"object","required":["test_code","test_description"],"properties":{"test_code":{"type":"string","minLength":1,"maxLength":64},"test_description":{"type":"string","maxLength":200}}},"CreateOrderBody":{"type":"object","required":["partner_order_id","patient_first_name","patient_id","patient_last_name","biological_sex","patient_dob","patient_phone_number","patient_address_line1","patient_city","patient_state","patient_zipcode","service_type","npi","ordering_physician","test_codes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64},"patient_first_name":{"type":"string","minLength":1,"maxLength":60},"patient_id":{"type":"string","minLength":1,"maxLength":64},"patient_middle_initial":{"type":"string","maxLength":5},"patient_last_name":{"type":"string","minLength":1,"maxLength":60},"biological_sex":{"type":"string","enum":["Male","Female","Non-binary"]},"patient_dob":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"patient_phone_number":{"type":"string","description":"10 digits from AhaService; the lab-provider client may send +1XXXXXXXXXX.","maxLength":20},"patient_email_address":{"type":"string","maxLength":120},"patient_address_line1":{"type":"string","minLength":1,"maxLength":120},"patient_address_line2":{"type":"string","maxLength":120},"patient_city":{"type":"string","minLength":1,"maxLength":60},"patient_state":{"type":"string","minLength":1,"maxLength":20},"patient_zipcode":{"type":"string","minLength":1,"maxLength":10},"service_type":{"type":"string","enum":["Full Service","Draw Only","Pickup Only"]},"preferred_schedule_date":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"preferred_schedule_time":{"type":"string","description":"HH:MM","maxLength":8},"patient_timezone":{"type":"string","description":"IANA zone, e.g. America/New_York","maxLength":64},"npi":{"type":"string","minLength":1,"maxLength":20},"ordering_physician":{"type":"string","minLength":1,"maxLength":120},"test_codes":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/TestCode"}}}},"CancelOrderBody":{"type":"object","required":["partner_order_id","notes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"order","missing":"GV-999999999"}},"notes":{"type":"array","maxItems":5,"items":{"type":"object","required":["note_type","notes"],"properties":{"note_type":{"type":"string","enum":["CANCELLATION"]},"notes":{"type":"string","maxLength":500}}}}}},"CreateOrderResponse":{"type":"object","required":["content","message","status"],"properties":{"content":{"type":"object","required":["partner_order_id","order_number"],"properties":{"partner_order_id":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true}},"order_number":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}},"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCreateOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CreateOrderResponse"}}},"CancelOrderResponse":{"type":"object","required":["message","status"],"properties":{"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCancelOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CancelOrderResponse"}}},"ErrorBody":{"type":"object","required":["status","message"],"properties":{"status":{"type":"string","enum":["ERROR"]},"message":{"type":"string"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}}}}}`);
2565
+ var operationIds = ["CreateOrder", "CancelOrder"];
2566
+ var supportedOperationIds = ["CreateOrder", "CancelOrder"];
2567
+
2568
+ // src/state.ts
2569
+ var DEFAULT_SETTINGS = {
2570
+ envelope: "raw",
2571
+ credentials: [],
2572
+ allowLegacy: true,
2573
+ timestampToleranceMs: 3e5,
2574
+ autoSchedule: null,
2575
+ defaultTimeZone: "America/New_York",
2576
+ cancelWebhook: true
2577
+ };
2578
+ var AhaState = class {
2579
+ constructor(sqlite, namespace, seed) {
2580
+ this.seed = seed;
2581
+ this.orders = new Collection(sqlite, namespace, "orders");
2582
+ this.settings = new Collection(sqlite, namespace, "settings");
2583
+ this.ids = new IdSequence(sqlite, namespace, "aha");
2584
+ this.idempotency = new IdempotencyStore(sqlite, namespace);
2585
+ this.ensureSeeded();
2586
+ }
2587
+ seed;
2588
+ orders;
2589
+ settings;
2590
+ ids;
2591
+ idempotency;
2592
+ ensureSeeded() {
2593
+ if (!this.settings.has("settings")) {
2594
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
2595
+ }
2596
+ }
2597
+ current() {
2598
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2599
+ }
2600
+ update(patch) {
2601
+ const next = { ...this.current(), ...patch };
2602
+ this.settings.insert("settings", next);
2603
+ return next;
2604
+ }
2605
+ /** By partner order id, then by AHA order number (our lab-provider cancels with the latter). */
2606
+ findOrder(id) {
2607
+ return this.orders.get(id) ?? this.orders.list({ where: (order) => order.order_number === id }).at(0)?.value;
2608
+ }
2609
+ nextOrderNumber() {
2610
+ return this.ids.next("AHA-", 10).toUpperCase();
2611
+ }
2612
+ };
2613
+
2614
+ // src/statuses.ts
2615
+ var ORDER_STATUSES = [
2616
+ "Scheduled",
2617
+ "Rescheduled",
2618
+ "Cancelled",
2619
+ "Check In",
2620
+ "Check Out",
2621
+ "Lab Testing In Progress",
2622
+ "Non Scheduled Update"
2623
+ ];
2624
+ var DRAW_STATUSES = [
2625
+ "Sample Collected",
2626
+ "Completed",
2627
+ "Patient Refused",
2628
+ "UTO",
2629
+ "Patient Not Home",
2630
+ "Patient Rescheduled",
2631
+ "Order Cancelled",
2632
+ "Others",
2633
+ "Patient Asked to Reschedule"
2634
+ ];
2635
+ var ORDER_PLACED = "Order Placed";
2636
+ var key = (value) => value.trim().toLowerCase().replace(/[\s_]+/g, " ");
2637
+ var canonical = (known, value) => known.find((candidate) => key(candidate) === key(value)) ?? value.trim();
2638
+ var orderStatus = (value) => canonical(ORDER_STATUSES, value);
2639
+ var drawStatus = (value) => canonical(DRAW_STATUSES, value);
2640
+ var isScheduling = (status) => status === "Scheduled" || status === "Rescheduled";
2641
+ var isDrawn = (draw) => draw === "Sample Collected" || draw === "Completed";
2642
+
2643
+ // src/time.ts
2644
+ var isTimeZone = (zone) => {
2645
+ try {
2646
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
2647
+ return true;
2648
+ } catch {
2649
+ return false;
2650
+ }
2651
+ };
2652
+ var formatters = /* @__PURE__ */ new Map();
2653
+ var formatter = (zone) => {
2654
+ let found = formatters.get(zone);
2655
+ if (!found) {
2656
+ found = new Intl.DateTimeFormat("en-US", {
2657
+ timeZone: zone,
2658
+ hourCycle: "h23",
2659
+ year: "numeric",
2660
+ month: "2-digit",
2661
+ day: "2-digit",
2662
+ hour: "2-digit",
2663
+ minute: "2-digit",
2664
+ second: "2-digit"
2665
+ });
2666
+ formatters.set(zone, found);
2667
+ }
2668
+ return found;
2669
+ };
2670
+ var zonedParts = (epochMs, zone) => {
2671
+ const parts = {};
2672
+ for (const part of formatter(zone).formatToParts(new Date(epochMs))) parts[part.type] = part.value;
2673
+ const hour = parts.hour === "24" ? "00" : parts.hour;
2674
+ return {
2675
+ date: `${parts.year}-${parts.month}-${parts.day}`,
2676
+ time: `${hour}:${parts.minute}`,
2677
+ timeWithSeconds: `${hour}:${parts.minute}:${parts.second}`
2678
+ };
2679
+ };
2680
+ var zonedToEpoch = (date, time, zone) => {
2681
+ const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
2682
+ const t = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(time);
2683
+ if (!d || !t) return void 0;
2684
+ const asUtc = Date.UTC(
2685
+ Number(d[1]),
2686
+ Number(d[2]) - 1,
2687
+ Number(d[3]),
2688
+ Number(t[1]),
2689
+ Number(t[2]),
2690
+ Number(t[3] ?? 0)
2691
+ );
2692
+ let guess = asUtc;
2693
+ for (let i = 0; i < 2; i++) {
2694
+ const local = zonedParts(guess, zone);
2695
+ const localAsUtc = Date.parse(`${local.date}T${local.timeWithSeconds}Z`);
2696
+ guess += asUtc - localAsUtc;
2697
+ }
2698
+ return guess;
2699
+ };
2700
+
2701
+ // src/runtime.ts
2702
+ var WEBHOOK_PATH = "/bloodwork/aha-webhook";
2703
+ var AHA_PRESETS = {
2704
+ bad_signature: {
2705
+ description: "Every call answers 401 Invalid signature (AHA_API_ERROR / upstream)",
2706
+ rules: [{ pathPrefix: "/v1/geviti", effect: "bad_signature" }]
2707
+ },
2708
+ rate_limited: {
2709
+ description: "Every call answers 429 (the lab-provider client maps it to rate_limit, retryable)",
2710
+ rules: [
2711
+ {
2712
+ pathPrefix: "/v1/geviti",
2713
+ status: 429,
2714
+ body: { status: "ERROR", message: "Too many requests" }
2715
+ }
2716
+ ]
2717
+ },
2718
+ server_error: {
2719
+ description: "Every call answers 500",
2720
+ rules: [
2721
+ {
2722
+ pathPrefix: "/v1/geviti",
2723
+ status: 500,
2724
+ body: { status: "ERROR", message: "Internal server error" }
2725
+ }
2726
+ ]
2727
+ },
2728
+ order_error: {
2729
+ description: "create-order / cancel answer 200 with inner status ERROR (the lab provider fails it; AhaService does not check)",
2730
+ rules: [{ pathPrefix: "/v1/geviti", effect: "order_error" }]
2731
+ },
2732
+ invalid_response: {
2733
+ description: "create-order / cancel answer 200 with a body neither client's zod schema accepts",
2734
+ rules: [{ pathPrefix: "/v1/geviti", effect: "invalid_response" }]
2735
+ },
2736
+ webhook_duplicate: {
2737
+ description: "The next webhook is delivered twice",
2738
+ webhook: { mode: "duplicate" }
2739
+ },
2740
+ webhook_reorder: {
2741
+ description: "The next two webhooks arrive swapped",
2742
+ webhook: { mode: "reorder" }
2743
+ },
2744
+ webhook_drop: {
2745
+ description: "The next webhook is never delivered",
2746
+ webhook: { mode: "drop" }
2747
+ }
2748
+ };
2749
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2750
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2751
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2752
+ var parseAutoSchedule = (value) => {
2753
+ if (value === null) return null;
2754
+ if (typeof value === "number" && value >= 0) return { afterMs: value };
2755
+ if (!isRecord4(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
2756
+ return "autoSchedule must be {afterMs, leadMs?}, a number of ms, or null";
2757
+ }
2758
+ if (value.leadMs !== void 0 && typeof value.leadMs !== "number") return "leadMs: number";
2759
+ return {
2760
+ afterMs: value.afterMs,
2761
+ ...typeof value.leadMs === "number" ? { leadMs: value.leadMs } : {}
2762
+ };
2763
+ };
2764
+ var parseCredentials = (value) => {
2765
+ if (!Array.isArray(value)) return "credentials: [{apiKey, apiSecret?}]";
2766
+ const out = [];
2767
+ for (const each of value) {
2768
+ if (!isRecord4(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
2769
+ out.push({
2770
+ apiKey: each.apiKey,
2771
+ ...typeof each.apiSecret === "string" ? { apiSecret: each.apiSecret } : {}
2772
+ });
2773
+ }
2774
+ return out;
2775
+ };
2776
+ var visible = (settings) => ({
2777
+ ...settings,
2778
+ credentials: settings.credentials.map((c) => ({
2779
+ apiKey: c.apiKey,
2780
+ ...c.apiSecret !== void 0 ? { apiSecret: "***" } : {}
2781
+ }))
2782
+ });
2783
+ var adminRoutes = (runtime) => ({
2784
+ "GET /orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).orders() }),
2785
+ "POST /orders/:partnerOrderId/transition": ({ params, body, namespace }) => {
2786
+ if (!isRecord4(body) || typeof body.status !== "string") {
2787
+ return adminError3(
2788
+ 400,
2789
+ 'expected {"status": "<AHA status>", "drawStatus"?, "scheduledAt"?, "timeZone"?}'
2790
+ );
2791
+ }
2792
+ const input = { status: body.status };
2793
+ if (typeof body.drawStatus === "string") input.drawStatus = body.drawStatus;
2794
+ if (typeof body.scheduledAt === "string" || typeof body.scheduledAt === "number") {
2795
+ input.scheduledAt = body.scheduledAt;
2796
+ }
2797
+ if (typeof body.timeZone === "string") input.timeZone = body.timeZone;
2798
+ try {
2799
+ const moved = runtime.instance(namespace).transition(params.partnerOrderId, input);
2800
+ return moved ? json3(200, moved) : adminError3(404, `no order ${params.partnerOrderId}`);
2801
+ } catch (err) {
2802
+ if (err instanceof RangeError) return adminError3(400, err.message);
2803
+ throw err;
2804
+ }
2805
+ },
2806
+ "GET /settings": ({ namespace }) => json3(200, visible(runtime.instance(namespace).state.current())),
2807
+ "PUT /settings": ({ body, namespace }) => {
2808
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2809
+ const patch = {};
2810
+ if (body.envelope !== void 0) {
2811
+ if (body.envelope !== "raw" && body.envelope !== "wrapped")
2812
+ return adminError3(400, 'envelope: "raw" | "wrapped"');
2813
+ patch.envelope = body.envelope;
2814
+ }
2815
+ if (body.credentials !== void 0) {
2816
+ const parsed = parseCredentials(body.credentials);
2817
+ if (typeof parsed === "string") return adminError3(400, parsed);
2818
+ patch.credentials = parsed;
2819
+ }
2820
+ for (const flag of ["allowLegacy", "cancelWebhook"]) {
2821
+ if (body[flag] !== void 0) {
2822
+ if (typeof body[flag] !== "boolean") return adminError3(400, `${flag}: boolean`);
2823
+ patch[flag] = body[flag];
2824
+ }
2825
+ }
2826
+ if (body.timestampToleranceMs !== void 0) {
2827
+ if (typeof body.timestampToleranceMs !== "number")
2828
+ return adminError3(400, "timestampToleranceMs: number");
2829
+ patch.timestampToleranceMs = body.timestampToleranceMs;
2830
+ }
2831
+ if (body.defaultTimeZone !== void 0) {
2832
+ if (typeof body.defaultTimeZone !== "string")
2833
+ return adminError3(400, "defaultTimeZone: IANA zone");
2834
+ patch.defaultTimeZone = body.defaultTimeZone;
2835
+ }
2836
+ if (body.autoSchedule !== void 0) {
2837
+ const parsed = parseAutoSchedule(body.autoSchedule);
2838
+ if (typeof parsed === "string") return adminError3(400, parsed);
2839
+ patch.autoSchedule = parsed;
2840
+ }
2841
+ return json3(200, visible(runtime.instance(namespace).state.update(patch)));
2842
+ },
2843
+ "POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
2844
+ });
2845
+ var createRuntime2 = (options = {}) => {
2846
+ const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
2847
+ const hub = createWebhookHub({
2848
+ signer: signers.header("Authorization", (secret) => `Token ${secret}`),
2849
+ ...retryDelaysMs ? { retryDelaysMs } : {},
2850
+ ...send ? { fetch: send } : {},
2851
+ endpoints: options.webhooks ? [endpoint] : []
2852
+ });
2853
+ const runtime = createRuntime({
2854
+ name: AHA_NAMESPACE,
2855
+ document,
2856
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2857
+ ...options.clock ? { clock: options.clock } : {},
2858
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2859
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2860
+ ...options.onLog ? { onLog: options.onLog } : {},
2861
+ credential: apiKeyCredential,
2862
+ presets: AHA_PRESETS,
2863
+ webhooks: hub,
2864
+ create: ({ sqlite, namespace, publicNamespace, clock }) => new AhaAPI({
2865
+ sqlite,
2866
+ namespace,
2867
+ now: clock.now,
2868
+ ...options.wallClock ? { wallClock: options.wallClock } : {},
2869
+ ...options.settings ? { settings: options.settings } : {},
2870
+ onWebhook: (event) => hub.publish({
2871
+ namespace: publicNamespace,
2872
+ type: event.status,
2873
+ body: event
2874
+ })
2875
+ }),
2876
+ describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
2877
+ admin: adminRoutes
2878
+ });
2879
+ let timer;
2880
+ if (options.tickMs !== void 0 && options.tickMs > 0) {
2881
+ timer = setInterval(() => {
2882
+ for (const name of runtime.namespaces()) runtime.instance(name).tick();
2883
+ }, options.tickMs);
2884
+ timer.unref?.();
2885
+ }
2886
+ return Object.assign(runtime, {
2887
+ webhooks: hub,
2888
+ stop: () => {
2889
+ if (timer !== void 0) clearInterval(timer);
2890
+ }
2891
+ });
2892
+ };
2893
+
2894
+ // src/index.ts
2895
+ var AHA_NAMESPACE = "aha";
2896
+ var DAY_MS = 864e5;
2897
+ var error = (status, message, extra = {}) => jsonRes(status, { status: "ERROR", message, ...extra });
2898
+ var record = (context) => {
2899
+ if (context.body.kind !== "json" || typeof context.body.value !== "object" || !context.body.value || Array.isArray(context.body.value)) {
2900
+ throw new HttpError(400, { status: "ERROR", message: "Request body must be a JSON object" });
2901
+ }
2902
+ return context.body.value;
2903
+ };
2904
+ var isBase64Sha256 = (value) => {
2905
+ try {
2906
+ return fromBase64(value).length === 32;
2907
+ } catch {
2908
+ return false;
2909
+ }
2910
+ };
2911
+ var verifyAuth = async (request, path, settings, wallNow) => {
2912
+ const apiKey = request.headers.get("x-api-key");
2913
+ if (apiKey) {
2914
+ const timestamp = request.headers.get("x-timestamp");
2915
+ const signature = request.headers.get("x-signature");
2916
+ if (!timestamp || !signature) return "Missing X-TIMESTAMP or X-SIGNATURE";
2917
+ if (!/^\d{10,16}$/.test(timestamp)) return "X-TIMESTAMP must be epoch milliseconds";
2918
+ if (settings.timestampToleranceMs > 0 && Math.abs(wallNow - Number(timestamp)) > settings.timestampToleranceMs) {
2919
+ return "Request timestamp outside the allowed window";
2920
+ }
2921
+ const known = settings.credentials.find((c) => c.apiKey === apiKey);
2922
+ if (settings.credentials.length > 0 && !known) return "Invalid API key";
2923
+ if (known?.apiSecret !== void 0) {
2924
+ const expected = await hmac(
2925
+ "SHA-256",
2926
+ known.apiSecret,
2927
+ `${apiKey}:${path}:${timestamp}`,
2928
+ "base64"
2929
+ );
2930
+ return timingSafeEqual(expected, signature) ? void 0 : "Invalid signature";
2931
+ }
2932
+ if (settings.credentials.length > 0) return "API key has no secret; use legacy auth";
2933
+ return isBase64Sha256(signature) ? void 0 : "Invalid signature";
2934
+ }
2935
+ const legacy = request.headers.get("x-geviti-auth-key");
2936
+ if (legacy) {
2937
+ if (!settings.allowLegacy) return "Legacy authentication is disabled";
2938
+ if (settings.credentials.length > 0 && !settings.credentials.some((c) => c.apiKey === legacy)) {
2939
+ return "Invalid API key";
2940
+ }
2941
+ return void 0;
2942
+ }
2943
+ return "Missing authentication headers";
2944
+ };
2945
+ var apiKeyCredential = (request) => request.headers.get("x-api-key") ?? request.headers.get("x-geviti-auth-key") ?? void 0;
2946
+ var AhaAPI = class {
2947
+ app;
2948
+ sqlite;
2949
+ state;
2950
+ service;
2951
+ now;
2952
+ wallClock;
2953
+ onWebhook;
2954
+ constructor(options = {}) {
2955
+ const sqlite = bootSqlite(options.sqlite);
2956
+ const namespace = options.namespace ?? AHA_NAMESPACE;
2957
+ this.now = options.now ?? (() => Date.now());
2958
+ this.wallClock = options.wallClock ?? (() => Date.now());
2959
+ this.onWebhook = options.onWebhook;
2960
+ this.state = new AhaState(sqlite, namespace, options.settings ?? {});
2961
+ const handlers = defineOperations({
2962
+ CreateOrder: (context) => this.idempotent(context, () => this.createOrder(context)),
2963
+ CancelOrder: (context) => this.idempotent(context, () => this.cancelOrder(context))
2964
+ });
2965
+ this.service = createService({
2966
+ document,
2967
+ handlers,
2968
+ sqlite,
2969
+ namespace,
2970
+ now: this.now,
2971
+ notFound: () => error(404, "Not Found"),
2972
+ onError: (err) => {
2973
+ if (err instanceof HttpError) return err.toResponse();
2974
+ throw err;
2975
+ },
2976
+ before: async (context) => {
2977
+ this.tick();
2978
+ if (faultEffect(context.request, "bad_signature") !== void 0) {
2979
+ return error(401, "Invalid signature");
2980
+ }
2981
+ const problem = await verifyAuth(
2982
+ context.request,
2983
+ context.url.pathname,
2984
+ this.state.current(),
2985
+ this.wallClock()
2986
+ );
2987
+ return problem === void 0 ? void 0 : error(401, problem);
2988
+ }
2989
+ });
2990
+ this.app = this.service.app;
2991
+ this.sqlite = this.service.sqlite;
2992
+ }
2993
+ fetch(request) {
2994
+ return this.service.fetch(request);
2995
+ }
2996
+ async reset() {
2997
+ await this.service.reset();
2998
+ this.state.ensureSeeded();
2999
+ }
3000
+ iso() {
3001
+ return new Date(this.now()).toISOString();
3002
+ }
3003
+ /** The success body in the namespace's envelope. */
3004
+ envelope(body) {
3005
+ return jsonRes(
3006
+ 200,
3007
+ this.state.current().envelope === "wrapped" ? { success: true, data: body } : body
3008
+ );
3009
+ }
3010
+ async idempotent(context, handler) {
3011
+ const key2 = context.request.headers.get("x-idempotency-key");
3012
+ if (!key2) return handler();
3013
+ const body = context.body.kind === "json" ? context.body.value : null;
3014
+ return this.state.idempotency.run(
3015
+ key2,
3016
+ requestFingerprint(context.request.method, context.url.pathname, body),
3017
+ {
3018
+ mismatch: () => error(409, "Idempotency key already used with a different request"),
3019
+ conflict: () => error(409, "A request with this idempotency key is still in progress")
3020
+ },
3021
+ handler
3022
+ );
3023
+ }
3024
+ validate(context) {
3025
+ const issues = bodyIssues(context);
3026
+ return issues.length > 0 ? error(400, "Invalid request", { errors: issuesByField(issues) }) : void 0;
3027
+ }
3028
+ createOrder(context) {
3029
+ const body = record(context);
3030
+ const invalid = this.validate(context);
3031
+ if (invalid) return invalid;
3032
+ const partnerOrderId = String(body.partner_order_id);
3033
+ const zone = typeof body.patient_timezone === "string" && isTimeZone(body.patient_timezone) ? body.patient_timezone : this.state.current().defaultTimeZone;
3034
+ const preferred = typeof body.preferred_schedule_date === "string" && typeof body.preferred_schedule_time === "string" ? zonedToEpoch(body.preferred_schedule_date, body.preferred_schedule_time, zone) : void 0;
3035
+ const existing = this.state.orders.get(partnerOrderId);
3036
+ const now = this.iso();
3037
+ const order = existing ? {
3038
+ ...existing,
3039
+ timeZone: zone,
3040
+ scheduledAt: preferred !== void 0 ? new Date(preferred).toISOString() : existing.scheduledAt,
3041
+ updated_at: now
3042
+ } : {
3043
+ partner_order_id: partnerOrderId,
3044
+ order_number: this.state.nextOrderNumber(),
3045
+ status: ORDER_PLACED,
3046
+ drawStatus: null,
3047
+ scheduledAt: preferred !== void 0 ? new Date(preferred).toISOString() : null,
3048
+ timeZone: zone,
3049
+ cancelled: false,
3050
+ created_at: now,
3051
+ updated_at: now,
3052
+ createdAtMs: this.now(),
3053
+ autoScheduled: false
3054
+ };
3055
+ this.state.orders.insert(partnerOrderId, order);
3056
+ const ids = { partnerOrderId, orderNumber: order.order_number };
3057
+ if (faultEffect(context.request, "invalid_response") !== void 0) {
3058
+ return annotateResponse(jsonRes(200, { ok: true }), { ids });
3059
+ }
3060
+ if (faultEffect(context.request, "order_error") !== void 0) {
3061
+ return annotateResponse(
3062
+ this.envelope({
3063
+ content: { partner_order_id: partnerOrderId, order_number: "" },
3064
+ message: "Unable to create order: patient address could not be verified",
3065
+ status: "ERROR"
3066
+ }),
3067
+ { ids }
3068
+ );
3069
+ }
3070
+ return annotateResponse(
3071
+ this.envelope({
3072
+ content: { partner_order_id: partnerOrderId, order_number: order.order_number },
3073
+ message: existing ? "Order updated successfully" : "Order created successfully",
3074
+ status: "SUCCESS"
3075
+ }),
3076
+ { ids }
3077
+ );
3078
+ }
3079
+ cancelOrder(context) {
3080
+ const body = record(context);
3081
+ const invalid = this.validate(context);
3082
+ if (invalid) return invalid;
3083
+ const order = this.state.findOrder(String(body.partner_order_id));
3084
+ if (!order) return error(404, `Order ${String(body.partner_order_id)} not found`);
3085
+ const ids = { partnerOrderId: order.partner_order_id, orderNumber: order.order_number };
3086
+ if (faultEffect(context.request, "invalid_response") !== void 0) {
3087
+ return annotateResponse(jsonRes(200, { ok: true }), { ids });
3088
+ }
3089
+ if (faultEffect(context.request, "order_error") !== void 0 || isDrawn(order.drawStatus)) {
3090
+ return annotateResponse(
3091
+ this.envelope({
3092
+ message: `Order ${order.partner_order_id} cannot be cancelled after the sample was collected`,
3093
+ status: "ERROR"
3094
+ }),
3095
+ { ids }
3096
+ );
3097
+ }
3098
+ if (!order.cancelled) {
3099
+ if (this.state.current().cancelWebhook) {
3100
+ this.transition(order.partner_order_id, { status: "Cancelled" });
3101
+ } else {
3102
+ this.state.orders.update(order.partner_order_id, {
3103
+ ...order,
3104
+ status: "Cancelled",
3105
+ cancelled: true,
3106
+ updated_at: this.iso()
3107
+ });
3108
+ }
3109
+ }
3110
+ return annotateResponse(
3111
+ this.envelope({
3112
+ message: order.cancelled ? "Order already cancelled" : "Order cancelled successfully",
3113
+ status: "SUCCESS"
3114
+ }),
3115
+ { ids }
3116
+ );
3117
+ }
3118
+ /**
3119
+ * Move an order to a vendor status and emit the webhook with every field our handler reads.
3120
+ * Throws `RangeError` for a bad zone or appointment time.
3121
+ */
3122
+ transition(id, input) {
3123
+ const order = this.state.findOrder(id);
3124
+ if (!order) return void 0;
3125
+ const status = orderStatus(input.status);
3126
+ const zone = input.timeZone ?? order.timeZone;
3127
+ if (!isTimeZone(zone))
3128
+ throw new RangeError(`timeZone ${JSON.stringify(zone)} is not an IANA zone`);
3129
+ const nowMs = this.now();
3130
+ const nowLocal = zonedParts(nowMs, zone);
3131
+ const draw = status === "Check Out" ? drawStatus(input.drawStatus ?? "Sample Collected") : null;
3132
+ let scheduledAt = order.scheduledAt;
3133
+ if (isScheduling(status)) {
3134
+ if (input.scheduledAt !== void 0) {
3135
+ const parsed = typeof input.scheduledAt === "number" ? input.scheduledAt : Date.parse(input.scheduledAt);
3136
+ if (!Number.isFinite(parsed)) {
3137
+ throw new RangeError(`scheduledAt ${JSON.stringify(input.scheduledAt)} is not a date`);
3138
+ }
3139
+ scheduledAt = new Date(parsed).toISOString();
3140
+ } else if (status === "Rescheduled" && order.scheduledAt) {
3141
+ scheduledAt = new Date(Date.parse(order.scheduledAt) + DAY_MS).toISOString();
3142
+ } else if (!scheduledAt) {
3143
+ scheduledAt = new Date(Math.ceil((nowMs + DAY_MS) / 36e5) * 36e5).toISOString();
3144
+ }
3145
+ }
3146
+ const webhook = {
3147
+ status,
3148
+ partnerOrderId: order.partner_order_id,
3149
+ ahaOrderId: order.order_number
3150
+ };
3151
+ if (isScheduling(status) && scheduledAt) {
3152
+ const at = zonedParts(Date.parse(scheduledAt), zone);
3153
+ Object.assign(webhook, {
3154
+ scheduleServiceTime: `${at.date}T${at.timeWithSeconds}`,
3155
+ scheduleServiceTimeZone: zone,
3156
+ scheduledServiceDate: at.date,
3157
+ scheduledServiceTime: at.time,
3158
+ scheduledServiceTimeZone: zone,
3159
+ scheduleConfirmationDate: nowLocal.date,
3160
+ scheduleConfirmationTime: nowLocal.time,
3161
+ scheduleConfirmationTimeZone: zone
3162
+ });
3163
+ }
3164
+ if (status === "Check In") {
3165
+ Object.assign(webhook, {
3166
+ checkInDate: nowLocal.date,
3167
+ checkInTime: nowLocal.time,
3168
+ checkInTimeZone: zone
3169
+ });
3170
+ }
3171
+ if (draw !== null) {
3172
+ Object.assign(webhook, {
3173
+ drawStatus: draw,
3174
+ drawStatusDate: nowLocal.date,
3175
+ drawStatusTime: nowLocal.time,
3176
+ drawStatusTimeZone: zone
3177
+ });
3178
+ }
3179
+ if (status === "Lab Testing In Progress") {
3180
+ Object.assign(webhook, {
3181
+ dropOffDate: nowLocal.date,
3182
+ dropOffTime: nowLocal.time,
3183
+ dropOffTimeZone: zone
3184
+ });
3185
+ }
3186
+ const next = {
3187
+ ...order,
3188
+ status,
3189
+ drawStatus: draw ?? order.drawStatus,
3190
+ scheduledAt,
3191
+ timeZone: zone,
3192
+ cancelled: order.cancelled || status === "Cancelled",
3193
+ updated_at: this.iso()
3194
+ };
3195
+ this.state.orders.update(order.partner_order_id, next);
3196
+ this.onWebhook?.(webhook);
3197
+ return { order: next, webhook };
3198
+ }
3199
+ /**
3200
+ * Emit `Scheduled` for every order whose `autoSchedule` delay has passed on the mock clock.
3201
+ * Runs before each vendor request, on `POST /__admin/tick`, and from the served ticker.
3202
+ */
3203
+ tick() {
3204
+ const plan = this.state.current().autoSchedule;
3205
+ if (!plan) return 0;
3206
+ let applied = 0;
3207
+ for (const { value: order } of this.state.orders.list({ order: "oldest" })) {
3208
+ if (order.autoScheduled || order.cancelled || order.status !== ORDER_PLACED) continue;
3209
+ if (this.now() < order.createdAtMs + plan.afterMs) continue;
3210
+ this.state.orders.update(order.partner_order_id, { ...order, autoScheduled: true });
3211
+ this.transition(order.partner_order_id, {
3212
+ status: "Scheduled",
3213
+ ...order.scheduledAt ? {} : { scheduledAt: order.createdAtMs + (plan.leadMs ?? DAY_MS) }
3214
+ });
3215
+ applied++;
3216
+ }
3217
+ return applied;
3218
+ }
3219
+ orders() {
3220
+ return this.state.orders.list({ order: "oldest" }).map((row) => row.value);
3221
+ }
3222
+ };
3223
+
3224
+ export {
3225
+ document,
3226
+ operationIds,
3227
+ supportedOperationIds,
3228
+ ORDER_STATUSES,
3229
+ DRAW_STATUSES,
3230
+ isTimeZone,
3231
+ zonedParts,
3232
+ zonedToEpoch,
3233
+ WEBHOOK_PATH,
3234
+ AHA_PRESETS,
3235
+ createRuntime2 as createRuntime,
3236
+ AHA_NAMESPACE,
3237
+ verifyAuth,
3238
+ apiKeyCredential,
3239
+ AhaAPI
3240
+ };
3241
+ //# sourceMappingURL=chunk-HEWJBQGW.js.map