@crvouga/mockingbird-service-fullscript 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,3412 @@
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 (error) {
222
+ return adminError(404, error instanceof Error ? error.message : String(error));
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 (error) {
278
+ return adminError(409, error instanceof Error ? error.message : String(error));
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 (error) {
289
+ return adminError(409, error instanceof Error ? error.message : String(error));
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 (error) {
303
+ return adminError(409, error instanceof Error ? error.message : String(error));
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(([key, handler]) => {
342
+ const space = key.indexOf(" ");
343
+ return { method: key.slice(0, space), pattern: key.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 bearerToken = (request) => {
393
+ const header = request.headers.get("authorization");
394
+ if (!header)
395
+ return void 0;
396
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
397
+ return match?.[1]?.trim() || void 0;
398
+ };
399
+ var createCredentialRegistry = () => {
400
+ const map = /* @__PURE__ */ new Map();
401
+ return {
402
+ set: (credential, namespace) => {
403
+ map.set(credential, namespace);
404
+ },
405
+ get: (credential) => map.get(credential),
406
+ remove: (credential) => map.delete(credential),
407
+ clear: () => map.clear(),
408
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
409
+ };
410
+ };
411
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
412
+
413
+ // ../core/dist/rng.js
414
+ var seedFrom = (value) => {
415
+ let hash = 2166136261;
416
+ for (let i = 0; i < value.length; i++) {
417
+ hash ^= value.charCodeAt(i);
418
+ hash = Math.imul(hash, 16777619);
419
+ }
420
+ return hash >>> 0;
421
+ };
422
+ var createRng = (seed = 0) => {
423
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
424
+ let state = numeric;
425
+ const next = () => {
426
+ state = state + 1831565813 >>> 0;
427
+ let t = state;
428
+ t = Math.imul(t ^ t >>> 15, t | 1);
429
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
430
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
431
+ };
432
+ return {
433
+ next,
434
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
435
+ reset: () => {
436
+ state = numeric;
437
+ },
438
+ state: () => state,
439
+ setState: (next2) => {
440
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
441
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
442
+ }
443
+ state = next2 >>> 0;
444
+ },
445
+ seed: numeric
446
+ };
447
+ };
448
+
449
+ // ../core/dist/faults.js
450
+ var matches = (rule, candidate) => {
451
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
452
+ return false;
453
+ }
454
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
455
+ return false;
456
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
457
+ return false;
458
+ }
459
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
460
+ return false;
461
+ return true;
462
+ };
463
+ var faultResponse = (rule) => {
464
+ const status = rule.status ?? 500;
465
+ const headers = { "content-type": "application/json", ...rule.headers };
466
+ if (typeof rule.body === "string")
467
+ return new Response(rule.body, { status, headers });
468
+ if (rule.body === null)
469
+ return new Response(null, { status, headers: rule.headers ?? {} });
470
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
471
+ return new Response(JSON.stringify(body), { status, headers });
472
+ };
473
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
474
+ const entries = [];
475
+ return {
476
+ add(rule) {
477
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
478
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
479
+ if (existing >= 0)
480
+ entries[existing] = entry;
481
+ else
482
+ entries.push(entry);
483
+ return rule;
484
+ },
485
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
486
+ remove(id) {
487
+ const index = entries.findIndex((e) => e.rule.id === id);
488
+ if (index < 0)
489
+ return false;
490
+ entries.splice(index, 1);
491
+ return true;
492
+ },
493
+ clear() {
494
+ entries.length = 0;
495
+ },
496
+ async take(candidate) {
497
+ const hits = [];
498
+ for (const entry of entries) {
499
+ if (entry.remaining === 0)
500
+ continue;
501
+ if (!matches(entry.rule, candidate))
502
+ continue;
503
+ const rate = entry.rule.rate ?? 1;
504
+ if (rng.next() >= rate)
505
+ continue;
506
+ entry.hits++;
507
+ if (entry.remaining !== null)
508
+ entry.remaining--;
509
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
510
+ if (delay !== void 0 && delay > 0) {
511
+ await sleep(delay);
512
+ }
513
+ const hit = { id: entry.rule.id };
514
+ if (entry.rule.effect !== void 0) {
515
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
516
+ }
517
+ if (entry.rule.drop === true)
518
+ hit.drop = true;
519
+ else if (entry.rule.status !== void 0)
520
+ hit.response = faultResponse(entry.rule);
521
+ hits.push(hit);
522
+ if (hit.drop || hit.response)
523
+ break;
524
+ }
525
+ return hits;
526
+ }
527
+ };
528
+ };
529
+
530
+ // ../../openapi/core/dist/refs.js
531
+ var OpenAPIReferenceError = class extends Error {
532
+ ref;
533
+ constructor(ref) {
534
+ super(`unresolvable $ref: ${ref}`);
535
+ this.ref = ref;
536
+ this.name = "OpenAPIReferenceError";
537
+ }
538
+ };
539
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
540
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
541
+ var resolveRef = (document2, ref) => {
542
+ if (!ref.startsWith("#/"))
543
+ throw new OpenAPIReferenceError(ref);
544
+ let cursor = document2;
545
+ for (const raw of ref.slice(2).split("/")) {
546
+ const segment = unescapePointer(raw);
547
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
548
+ throw new OpenAPIReferenceError(ref);
549
+ }
550
+ cursor = cursor[segment];
551
+ }
552
+ if (cursor === void 0)
553
+ throw new OpenAPIReferenceError(ref);
554
+ return cursor;
555
+ };
556
+ var deref = (document2, value) => {
557
+ let current = value;
558
+ const seen = /* @__PURE__ */ new Set();
559
+ while (isReference(current)) {
560
+ if (seen.has(current.$ref))
561
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
562
+ seen.add(current.$ref);
563
+ current = resolveRef(document2, current.$ref);
564
+ }
565
+ return current;
566
+ };
567
+
568
+ // ../../openapi/core/dist/types.js
569
+ var HTTP_METHODS = [
570
+ "get",
571
+ "put",
572
+ "post",
573
+ "delete",
574
+ "options",
575
+ "head",
576
+ "patch",
577
+ "trace"
578
+ ];
579
+
580
+ // ../../openapi/core/dist/document.js
581
+ var mergeParameters = (document2, item, own) => {
582
+ const merged = /* @__PURE__ */ new Map();
583
+ for (const raw of item.parameters ?? []) {
584
+ const parameter = deref(document2, raw);
585
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
586
+ }
587
+ for (const raw of own ?? []) {
588
+ const parameter = deref(document2, raw);
589
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
590
+ }
591
+ return [...merged.values()];
592
+ };
593
+ var listOperations = (document2) => {
594
+ const operations = [];
595
+ for (const [path, item] of Object.entries(document2.paths)) {
596
+ for (const method of HTTP_METHODS) {
597
+ const operation = item[method];
598
+ if (operation?.operationId === void 0)
599
+ continue;
600
+ const responses = {};
601
+ for (const [status, response] of Object.entries(operation.responses)) {
602
+ responses[status] = deref(document2, response);
603
+ }
604
+ operations.push({
605
+ operationId: operation.operationId,
606
+ method,
607
+ path,
608
+ operation,
609
+ parameters: mergeParameters(document2, item, operation.parameters),
610
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
611
+ responses
612
+ });
613
+ }
614
+ }
615
+ return operations;
616
+ };
617
+
618
+ // ../../openapi/core/dist/schema.js
619
+ var resolveSchema = (document2, schema) => {
620
+ let current = schema;
621
+ const seen = /* @__PURE__ */ new Set();
622
+ while (typeof current.$ref === "string") {
623
+ const ref = current.$ref;
624
+ if (seen.has(ref))
625
+ break;
626
+ seen.add(ref);
627
+ const { $ref: _ignored, ...siblings } = current;
628
+ const target = resolveRef(document2, ref);
629
+ current = { ...target, ...siblings };
630
+ }
631
+ if (current.nullable === true) {
632
+ const { nullable: _nullable, ...rest } = current;
633
+ const types = schemaTypes(rest);
634
+ if (types.length > 0 && !types.includes("null"))
635
+ current = { ...rest, type: [...types, "null"] };
636
+ else
637
+ current = rest;
638
+ }
639
+ return current;
640
+ };
641
+ var schemaTypes = (schema) => {
642
+ if (Array.isArray(schema.type))
643
+ return schema.type;
644
+ if (schema.type !== void 0)
645
+ return [schema.type];
646
+ const inferred = [];
647
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
648
+ inferred.push("object");
649
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
650
+ inferred.push("array");
651
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
652
+ inferred.push("string");
653
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
654
+ inferred.push("number");
655
+ return inferred;
656
+ };
657
+ var jsonTypeOf = (value) => {
658
+ if (value === null)
659
+ return "null";
660
+ if (Array.isArray(value))
661
+ return "array";
662
+ switch (typeof value) {
663
+ case "string":
664
+ return "string";
665
+ case "boolean":
666
+ return "boolean";
667
+ case "number":
668
+ return Number.isInteger(value) ? "integer" : "number";
669
+ case "object":
670
+ return "object";
671
+ default:
672
+ return "undefined";
673
+ }
674
+ };
675
+ var deepEqual = (a, b) => {
676
+ if (a === b)
677
+ return true;
678
+ if (typeof a !== typeof b || a === null || b === null)
679
+ return false;
680
+ if (Array.isArray(a)) {
681
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
682
+ }
683
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
684
+ const ka = Object.keys(a);
685
+ const kb = Object.keys(b);
686
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
687
+ }
688
+ return false;
689
+ };
690
+ var FORMAT_PATTERNS = {
691
+ 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,
692
+ date: /^\d{4}-\d{2}-\d{2}$/,
693
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
694
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
695
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
696
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
697
+ };
698
+ var graphemeLength = (value) => [...value].length;
699
+ var validateValue = (document2, schema, value, path = []) => {
700
+ const errors = [];
701
+ const s = resolveSchema(document2, schema);
702
+ const fail2 = (message) => errors.push({ path, message });
703
+ const actual = jsonTypeOf(value);
704
+ if (actual === "undefined") {
705
+ fail2("value is undefined");
706
+ return errors;
707
+ }
708
+ const types = schemaTypes(s);
709
+ if (types.length > 0) {
710
+ const ok2 = types.some((t) => t === actual || t === "number" && actual === "integer");
711
+ if (!ok2) {
712
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
713
+ return errors;
714
+ }
715
+ }
716
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
717
+ fail2("value not in enum");
718
+ }
719
+ if (s.const !== void 0 && !deepEqual(s.const, value))
720
+ fail2("value does not equal const");
721
+ if (typeof value === "string") {
722
+ const length = graphemeLength(value);
723
+ if (s.minLength !== void 0 && length < s.minLength)
724
+ fail2(`length ${length} < minLength ${s.minLength}`);
725
+ if (s.maxLength !== void 0 && length > s.maxLength)
726
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
727
+ if (s.pattern !== void 0) {
728
+ try {
729
+ if (!new RegExp(s.pattern, "u").test(value))
730
+ fail2(`does not match pattern ${s.pattern}`);
731
+ } catch {
732
+ }
733
+ }
734
+ if (s.format !== void 0) {
735
+ const pattern = FORMAT_PATTERNS[s.format];
736
+ if (pattern && !pattern.test(value))
737
+ fail2(`does not match format ${s.format}`);
738
+ }
739
+ }
740
+ if (typeof value === "number") {
741
+ if (s.minimum !== void 0 && value < s.minimum)
742
+ fail2(`${value} < minimum ${s.minimum}`);
743
+ if (s.maximum !== void 0 && value > s.maximum)
744
+ fail2(`${value} > maximum ${s.maximum}`);
745
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
751
+ }
752
+ }
753
+ if (Array.isArray(value)) {
754
+ if (s.minItems !== void 0 && value.length < s.minItems)
755
+ fail2(`${value.length} items < minItems ${s.minItems}`);
756
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
757
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
758
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
759
+ fail2("items are not unique");
760
+ value.forEach((item, i) => {
761
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
762
+ if (itemSchema)
763
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
764
+ });
765
+ }
766
+ if (actual === "object") {
767
+ const record = value;
768
+ const keys = Object.keys(record);
769
+ for (const name of s.required ?? [])
770
+ if (!(name in record))
771
+ fail2(`missing required property ${name}`);
772
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
774
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
776
+ for (const key of keys) {
777
+ const property = s.properties?.[key];
778
+ if (property) {
779
+ errors.push(...validateValue(document2, property, record[key], [...path, key]));
780
+ continue;
781
+ }
782
+ if (s.additionalProperties === false)
783
+ fail2(`unexpected property ${key}`);
784
+ else if (typeof s.additionalProperties === "object") {
785
+ errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
786
+ }
787
+ if (s.propertyNames) {
788
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
789
+ if (nameErrors.length > 0)
790
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
791
+ }
792
+ }
793
+ }
794
+ if (s.allOf)
795
+ for (const branch of s.allOf)
796
+ errors.push(...validateValue(document2, branch, value, path));
797
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
798
+ fail2("matches no anyOf branch");
799
+ if (s.oneOf) {
800
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
+ if (matches2 !== 1)
802
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
803
+ }
804
+ if (s.not && validateValue(document2, s.not, value).length === 0)
805
+ fail2("matches forbidden `not` schema");
806
+ return errors;
807
+ };
808
+
809
+ // ../../http/codec/dist/form.js
810
+ var parsePath = (rawKey) => {
811
+ const open = rawKey.indexOf("[");
812
+ if (open === -1)
813
+ return [rawKey];
814
+ const path = [rawKey.slice(0, open)];
815
+ const rest = rawKey.slice(open);
816
+ const pattern = /\[([^\]]*)\]/g;
817
+ let match = pattern.exec(rest);
818
+ let consumed = 0;
819
+ while (match !== null) {
820
+ if (match.index !== consumed)
821
+ return [rawKey];
822
+ path.push(match[1] ?? "");
823
+ consumed = match.index + match[0].length;
824
+ match = pattern.exec(rest);
825
+ }
826
+ if (consumed !== rest.length)
827
+ return [rawKey];
828
+ return path;
829
+ };
830
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
831
+ var put = (target, key, value) => {
832
+ if (key === "__proto__") {
833
+ Object.defineProperty(target, key, {
834
+ value,
835
+ enumerable: true,
836
+ writable: true,
837
+ configurable: true
838
+ });
839
+ return;
840
+ }
841
+ ;
842
+ target[key] = value;
843
+ };
844
+ var assign = (target, path, value) => {
845
+ let cursor = target;
846
+ for (let i = 0; i < path.length; i++) {
847
+ const segment = path[i];
848
+ const last = i === path.length - 1;
849
+ if (Array.isArray(cursor)) {
850
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
851
+ if (index === void 0)
852
+ return;
853
+ if (last) {
854
+ put(cursor, index, value);
855
+ return;
856
+ }
857
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
858
+ if (next === void 0 || typeof next === "string") {
859
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
860
+ put(cursor, index, created);
861
+ cursor = created;
862
+ } else {
863
+ cursor = next;
864
+ }
865
+ continue;
866
+ }
867
+ if (typeof cursor === "string")
868
+ return;
869
+ if (last) {
870
+ put(cursor, segment, value);
871
+ return;
872
+ }
873
+ const nextSegment = path[i + 1];
874
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
875
+ if (existing === void 0 || typeof existing === "string") {
876
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
877
+ put(cursor, segment, created);
878
+ cursor = created;
879
+ } else {
880
+ cursor = existing;
881
+ }
882
+ }
883
+ };
884
+ var decodeFormPairs = (pairs) => {
885
+ const out = {};
886
+ for (const [rawKey, value] of pairs)
887
+ assign(out, parsePath(rawKey), value);
888
+ return densify(out);
889
+ };
890
+ var densify = (value) => {
891
+ if (typeof value === "string")
892
+ return value;
893
+ if (Array.isArray(value))
894
+ return value.filter((item) => item !== void 0).map(densify);
895
+ const out = {};
896
+ for (const [key, item] of Object.entries(value))
897
+ put(out, key, densify(item));
898
+ return out;
899
+ };
900
+ var decodeForm = (text) => {
901
+ const source = text.startsWith("?") ? text.slice(1) : text;
902
+ return decodeFormPairs(new URLSearchParams(source).entries());
903
+ };
904
+
905
+ // ../../http/codec/dist/content.js
906
+ var JSON_MEDIA_TYPE = "application/json";
907
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
908
+ var mediaTypeOf = (contentType) => {
909
+ if (!contentType)
910
+ return void 0;
911
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
912
+ return essence ? essence : void 0;
913
+ };
914
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
915
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
916
+ var decodeBody = (contentType, bytes) => {
917
+ if (bytes.byteLength === 0)
918
+ return { kind: "empty" };
919
+ const mediaType = mediaTypeOf(contentType);
920
+ if (mediaType === void 0)
921
+ return { kind: "bytes", value: bytes };
922
+ if (isJsonMediaType(mediaType)) {
923
+ const text = utf8.decode(bytes);
924
+ try {
925
+ return { kind: "json", value: JSON.parse(text) };
926
+ } catch (error) {
927
+ return {
928
+ kind: "invalid",
929
+ mediaType,
930
+ text,
931
+ error: error instanceof Error ? error.message : String(error)
932
+ };
933
+ }
934
+ }
935
+ if (mediaType === FORM_MEDIA_TYPE) {
936
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
937
+ }
938
+ if (mediaType.startsWith("text/"))
939
+ return { kind: "text", value: utf8.decode(bytes) };
940
+ return { kind: "bytes", value: bytes };
941
+ };
942
+ var readBody = async (message) => {
943
+ const bytes = new Uint8Array(await message.arrayBuffer());
944
+ return decodeBody(message.headers.get("content-type"), bytes);
945
+ };
946
+
947
+ // ../core/dist/http.js
948
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
949
+ status,
950
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
951
+ });
952
+ var HttpError = class extends Error {
953
+ status;
954
+ body;
955
+ headers;
956
+ constructor(status, body, headers = {}) {
957
+ super(`HTTP ${status}`);
958
+ this.status = status;
959
+ this.body = body;
960
+ this.headers = headers;
961
+ this.name = "HttpError";
962
+ }
963
+ toResponse() {
964
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
965
+ if (contentType === "text/plain") {
966
+ return new Response(String(this.body), {
967
+ status: this.status,
968
+ headers: this.headers
969
+ });
970
+ }
971
+ return jsonRes(this.status, this.body, this.headers);
972
+ }
973
+ };
974
+ var ok = (value) => ({ ok: true, value });
975
+ var fail = (reason) => ({ ok: false, reason });
976
+ var coerce = {
977
+ string(value) {
978
+ return typeof value === "string" ? ok(value) : fail("expected a string");
979
+ },
980
+ integer(value) {
981
+ if (typeof value === "number" && Number.isInteger(value))
982
+ return ok(value);
983
+ if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
984
+ const parsed = Number(value);
985
+ return Number.isSafeInteger(parsed) ? ok(parsed) : fail("integer out of range");
986
+ }
987
+ return fail("expected an integer");
988
+ },
989
+ boolean(value) {
990
+ if (typeof value === "boolean")
991
+ return ok(value);
992
+ if (value === "true" || value === "1")
993
+ return ok(true);
994
+ if (value === "false" || value === "0")
995
+ return ok(false);
996
+ return fail("expected a boolean");
997
+ },
998
+ enumeration(value, allowed) {
999
+ const match = allowed.find((candidate) => candidate === value);
1000
+ return match === void 0 ? fail(`expected one of ${allowed.join(", ")}`) : ok(match);
1001
+ },
1002
+ /** Flat string-to-string map, the shape of Stripe-style `metadata`. */
1003
+ stringMap(value) {
1004
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1005
+ return fail("expected an object");
1006
+ const out = {};
1007
+ for (const [key, item] of Object.entries(value)) {
1008
+ if (typeof item !== "string")
1009
+ return fail(`expected a string at ${key}`);
1010
+ out[key] = item;
1011
+ }
1012
+ return ok(out);
1013
+ }
1014
+ };
1015
+
1016
+ // ../core/dist/ids.js
1017
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1018
+ var mix = (input) => {
1019
+ let hash = 2166136261;
1020
+ for (let i = 0; i < input.length; i++) {
1021
+ hash ^= input.charCodeAt(i);
1022
+ hash = Math.imul(hash, 16777619) >>> 0;
1023
+ }
1024
+ hash ^= hash >>> 16;
1025
+ hash = Math.imul(hash, 2246822507) >>> 0;
1026
+ hash ^= hash >>> 13;
1027
+ return hash >>> 0;
1028
+ };
1029
+ var opaqueToken = (input, length) => {
1030
+ let out = "";
1031
+ let round = 0;
1032
+ while (out.length < length) {
1033
+ let hash = mix(`${input}:${round++}`);
1034
+ for (let i = 0; i < 5 && out.length < length; i++) {
1035
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1036
+ hash = Math.floor(hash / ALPHABET.length);
1037
+ }
1038
+ }
1039
+ return out;
1040
+ };
1041
+
1042
+ // ../core/dist/journal.js
1043
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1044
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1045
+ const capacity = Math.max(0, Math.floor(size));
1046
+ const rings = /* @__PURE__ */ new Map();
1047
+ let sequence = 0;
1048
+ const order = /* @__PURE__ */ new WeakMap();
1049
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1050
+ return {
1051
+ size: capacity,
1052
+ record(entry) {
1053
+ if (capacity === 0)
1054
+ return;
1055
+ order.set(entry, sequence++);
1056
+ let ring = rings.get(entry.namespace);
1057
+ if (!ring) {
1058
+ ring = { entries: [], next: 0 };
1059
+ rings.set(entry.namespace, ring);
1060
+ }
1061
+ if (ring.entries.length < capacity)
1062
+ ring.entries.push(entry);
1063
+ else {
1064
+ ring.entries[ring.next] = entry;
1065
+ ring.next = (ring.next + 1) % capacity;
1066
+ }
1067
+ },
1068
+ list(query = {}) {
1069
+ 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));
1070
+ 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));
1071
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1072
+ },
1073
+ clear(namespace) {
1074
+ if (namespace === void 0)
1075
+ rings.clear();
1076
+ else
1077
+ rings.delete(namespace);
1078
+ }
1079
+ };
1080
+ };
1081
+ var notes = /* @__PURE__ */ new WeakMap();
1082
+ var annotateResponse = (response, extra) => {
1083
+ const existing = notes.get(response);
1084
+ notes.set(response, {
1085
+ ...existing,
1086
+ ...extra,
1087
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1088
+ });
1089
+ return response;
1090
+ };
1091
+ var responseNotes = (response) => notes.get(response);
1092
+
1093
+ // ../core/dist/metrics.js
1094
+ var createMetrics = () => {
1095
+ let requests = 0;
1096
+ let faults = 0;
1097
+ let totalDurationMs = 0;
1098
+ const byOperation = /* @__PURE__ */ new Map();
1099
+ const unmatched = /* @__PURE__ */ new Map();
1100
+ return {
1101
+ record(entry) {
1102
+ requests++;
1103
+ totalDurationMs += entry.durationMs;
1104
+ if (entry.faultId !== void 0)
1105
+ faults++;
1106
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1107
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1108
+ if (entry.unmatched) {
1109
+ const route = `${entry.method} ${entry.path}`;
1110
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1111
+ }
1112
+ },
1113
+ report: () => ({
1114
+ requests,
1115
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1116
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1117
+ const space = route.indexOf(" ");
1118
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1119
+ }),
1120
+ faults,
1121
+ totalDurationMs
1122
+ }),
1123
+ reset() {
1124
+ requests = 0;
1125
+ faults = 0;
1126
+ totalDurationMs = 0;
1127
+ byOperation.clear();
1128
+ unmatched.clear();
1129
+ }
1130
+ };
1131
+ };
1132
+
1133
+ // ../../core/dist/timeline.js
1134
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1135
+ var Timeline = class {
1136
+ maxCheckpoints;
1137
+ now;
1138
+ makeId;
1139
+ nodes = /* @__PURE__ */ new Map();
1140
+ heads = /* @__PURE__ */ new Map();
1141
+ /** Unreferenced nodes in the exact order they became collectible. */
1142
+ evictable = /* @__PURE__ */ new Set();
1143
+ /** Branch heads plus explicit retainers. Absent means zero. */
1144
+ references = /* @__PURE__ */ new Map();
1145
+ explicitPins = /* @__PURE__ */ new Map();
1146
+ sequence = 0;
1147
+ constructor(options = {}) {
1148
+ const max = options.maxCheckpoints ?? 1e3;
1149
+ if (!Number.isSafeInteger(max) || max < 1)
1150
+ throw new RangeError("maxCheckpoints must be a positive integer");
1151
+ this.maxCheckpoints = max;
1152
+ this.now = options.now ?? (() => this.sequence);
1153
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1154
+ }
1155
+ /** Capture a new immutable value and move `branch` to it. */
1156
+ commit(value, options = {}) {
1157
+ const branch = options.branch ?? "main";
1158
+ this.assertBranch(branch);
1159
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1160
+ if (parent !== null && !this.nodes.has(parent))
1161
+ throw new RangeError(`no checkpoint ${parent}`);
1162
+ const id = this.makeId(++this.sequence);
1163
+ if (this.nodes.has(id))
1164
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1165
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1166
+ this.nodes.set(id, checkpoint);
1167
+ this.moveHead(branch, id);
1168
+ this.collect(this.maxCheckpoints);
1169
+ return checkpoint;
1170
+ }
1171
+ /** Create a branch pointer without copying its checkpoint value. */
1172
+ fork(branch, options = {}) {
1173
+ this.assertBranch(branch);
1174
+ if (this.heads.has(branch))
1175
+ throw new RangeError(`branch already exists: ${branch}`);
1176
+ const from = options.from ?? this.heads.get("main");
1177
+ if (from === void 0)
1178
+ return void 0;
1179
+ const checkpoint = this.get(from);
1180
+ this.moveHead(branch, checkpoint.id);
1181
+ return checkpoint;
1182
+ }
1183
+ /** Move a branch pointer to an existing checkpoint. */
1184
+ checkout(branch, id) {
1185
+ this.assertBranch(branch);
1186
+ const checkpoint = this.get(id);
1187
+ this.moveHead(branch, checkpoint.id);
1188
+ return checkpoint;
1189
+ }
1190
+ get(id) {
1191
+ const checkpoint = this.nodes.get(id);
1192
+ if (!checkpoint)
1193
+ throw new RangeError(`no checkpoint ${id}`);
1194
+ return checkpoint;
1195
+ }
1196
+ head(branch = "main") {
1197
+ const id = this.heads.get(branch);
1198
+ return id === void 0 ? void 0 : this.get(id);
1199
+ }
1200
+ hasBranch(branch) {
1201
+ return this.heads.has(branch);
1202
+ }
1203
+ branches() {
1204
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1205
+ }
1206
+ checkpoints() {
1207
+ return [...this.nodes.values()];
1208
+ }
1209
+ /** Number of retained checkpoints without allocating an array. */
1210
+ get size() {
1211
+ return this.nodes.size;
1212
+ }
1213
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1214
+ retain(id) {
1215
+ const checkpoint = this.get(id);
1216
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1217
+ this.addReference(id);
1218
+ return checkpoint;
1219
+ }
1220
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1221
+ release(id) {
1222
+ if (!this.nodes.has(id))
1223
+ return false;
1224
+ const pins = this.explicitPins.get(id) ?? 0;
1225
+ if (pins === 0)
1226
+ return false;
1227
+ if (pins === 1)
1228
+ this.explicitPins.delete(id);
1229
+ else
1230
+ this.explicitPins.set(id, pins - 1);
1231
+ this.removeReference(id);
1232
+ this.collect(this.maxCheckpoints);
1233
+ return true;
1234
+ }
1235
+ deleteBranch(branch) {
1236
+ if (branch === "main")
1237
+ throw new RangeError("cannot delete main branch");
1238
+ const previous = this.heads.get(branch);
1239
+ const deleted = this.heads.delete(branch);
1240
+ if (previous !== void 0)
1241
+ this.removeReference(previous);
1242
+ this.collect(this.maxCheckpoints);
1243
+ return deleted;
1244
+ }
1245
+ /**
1246
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1247
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1248
+ * storage dependency, so a retained node remains usable after pruning.
1249
+ */
1250
+ gc(max = this.maxCheckpoints) {
1251
+ if (!Number.isSafeInteger(max) || max < 1)
1252
+ throw new RangeError("max must be a positive integer");
1253
+ const removed = [];
1254
+ this.collect(max, removed);
1255
+ return removed;
1256
+ }
1257
+ collect(max, removed) {
1258
+ while (this.nodes.size > max && this.evictable.size > 0) {
1259
+ const id = this.evictable.values().next().value;
1260
+ this.evictable.delete(id);
1261
+ this.nodes.delete(id);
1262
+ removed?.push(id);
1263
+ }
1264
+ }
1265
+ moveHead(branch, id) {
1266
+ const previous = this.heads.get(branch);
1267
+ if (previous === id)
1268
+ return;
1269
+ if (previous !== void 0)
1270
+ this.removeReference(previous);
1271
+ this.heads.set(branch, id);
1272
+ this.addReference(id);
1273
+ }
1274
+ addReference(id) {
1275
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1276
+ this.evictable.delete(id);
1277
+ }
1278
+ removeReference(id) {
1279
+ const next = (this.references.get(id) ?? 0) - 1;
1280
+ if (next > 0)
1281
+ this.references.set(id, next);
1282
+ else {
1283
+ this.references.delete(id);
1284
+ if (this.nodes.has(id))
1285
+ this.evictable.add(id);
1286
+ }
1287
+ }
1288
+ assertBranch(branch) {
1289
+ if (!BRANCH_PATTERN.test(branch))
1290
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1291
+ }
1292
+ };
1293
+
1294
+ // ../../sqlite/dist/default.js
1295
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1296
+ var createDefaultSqlite = () => new Database();
1297
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1298
+
1299
+ // ../../sqlite/dist/migrate.js
1300
+ var ensureMigrationsTable = (sqlite) => {
1301
+ sqlite.exec(`
1302
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1303
+ id TEXT PRIMARY KEY NOT NULL,
1304
+ applied_at INTEGER NOT NULL
1305
+ )
1306
+ `);
1307
+ };
1308
+ var migrate = (sqlite, migrations) => {
1309
+ ensureMigrationsTable(sqlite);
1310
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1311
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1312
+ if (pending.length === 0)
1313
+ return;
1314
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1315
+ const now = Math.floor(Date.now() / 1e3);
1316
+ sqlite.transaction(() => {
1317
+ for (const migration of pending) {
1318
+ sqlite.exec(migration.sql);
1319
+ insert.run(migration.id, now);
1320
+ }
1321
+ });
1322
+ };
1323
+
1324
+ // ../../sqlite/dist/schema.js
1325
+ var CORE_MIGRATIONS = [
1326
+ {
1327
+ id: "20260322_core_records_sequences",
1328
+ sql: `
1329
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1330
+ namespace TEXT NOT NULL,
1331
+ collection TEXT NOT NULL,
1332
+ id TEXT NOT NULL,
1333
+ seq INTEGER NOT NULL,
1334
+ value TEXT NOT NULL,
1335
+ PRIMARY KEY (namespace, collection, id)
1336
+ );
1337
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1338
+ ON mockingbird_records (namespace, collection, seq);
1339
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1340
+ namespace TEXT NOT NULL,
1341
+ name TEXT NOT NULL,
1342
+ kind TEXT NOT NULL,
1343
+ value INTEGER NOT NULL,
1344
+ PRIMARY KEY (namespace, name, kind)
1345
+ );
1346
+ `
1347
+ }
1348
+ ];
1349
+ var migrateCore = (sqlite) => {
1350
+ migrate(sqlite, CORE_MIGRATIONS);
1351
+ };
1352
+ var clearNamespace = (sqlite, namespace) => {
1353
+ sqlite.transaction(() => {
1354
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1355
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1356
+ });
1357
+ };
1358
+
1359
+ // ../../openapi/metadata/dist/types.js
1360
+ var EXTENSION_KEYS = {
1361
+ operation: "x-mockingbird",
1362
+ resource: "x-mockingbird-resource",
1363
+ resourceRef: "x-mockingbird-resource-ref",
1364
+ volatile: "x-mockingbird-volatile",
1365
+ scope: "x-mockingbird-scope",
1366
+ unsupported: "x-mockingbird-unsupported",
1367
+ parityHeader: "x-mockingbird-parity-header"
1368
+ };
1369
+
1370
+ // ../../openapi/metadata/dist/read.js
1371
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1372
+ var extensionOf = (holder, key) => holder[key];
1373
+ var operationMetadata = (operation) => {
1374
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1375
+ const ext = isRecord2(raw) ? raw : {};
1376
+ const supported = ext.supported ?? true;
1377
+ const parity = ext.parity ?? {};
1378
+ return {
1379
+ supported,
1380
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1381
+ parity: {
1382
+ enabled: supported && (parity.enabled ?? true),
1383
+ safe: parity.safe ?? true,
1384
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1385
+ }
1386
+ };
1387
+ };
1388
+
1389
+ // ../core/dist/service.js
1390
+ import { Hono } from "hono";
1391
+ var defineOperations = (handlers) => handlers;
1392
+ var OperationRegistryError = class extends Error {
1393
+ problems;
1394
+ constructor(problems) {
1395
+ super(`operation registry is inconsistent:
1396
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1397
+ this.problems = problems;
1398
+ this.name = "OperationRegistryError";
1399
+ }
1400
+ };
1401
+ var verifyOperations = (document2, handlers) => {
1402
+ const problems = [];
1403
+ const operations = listOperations(document2);
1404
+ const seen = /* @__PURE__ */ new Set();
1405
+ for (const operation of operations) {
1406
+ if (seen.has(operation.operationId))
1407
+ problems.push(`duplicate operationId ${operation.operationId}`);
1408
+ seen.add(operation.operationId);
1409
+ const supported = operationMetadata(operation.operation).supported;
1410
+ const handler = handlers[operation.operationId];
1411
+ if (supported && !handler)
1412
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1413
+ if (!supported && handler)
1414
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1415
+ }
1416
+ for (const id of Object.keys(handlers)) {
1417
+ if (!seen.has(id))
1418
+ problems.push(`handler ${id} has no OpenAPI operation`);
1419
+ }
1420
+ return problems;
1421
+ };
1422
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1423
+ var routeOrder = (a, b) => {
1424
+ const sa = a.path.split("/");
1425
+ const sb = b.path.split("/");
1426
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1427
+ const x = sa[i] ?? "";
1428
+ const y = sb[i] ?? "";
1429
+ const px = x.startsWith("{");
1430
+ const py = y.startsWith("{");
1431
+ if (px !== py)
1432
+ return px ? 1 : -1;
1433
+ if (x !== y)
1434
+ return x < y ? -1 : 1;
1435
+ }
1436
+ return 0;
1437
+ };
1438
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1439
+ var bootSqlite = (sqlite) => {
1440
+ const client = resolveSqlite(sqlite);
1441
+ migrateCore(client);
1442
+ return client;
1443
+ };
1444
+ var createService = (options) => {
1445
+ const problems = verifyOperations(options.document, options.handlers);
1446
+ if (problems.length > 0)
1447
+ throw new OperationRegistryError(problems);
1448
+ migrateCore(options.sqlite);
1449
+ const now = options.now ?? (() => Date.now());
1450
+ const app = new Hono();
1451
+ app.notFound((c) => options.notFound(c.req.raw));
1452
+ app.onError((error, c) => options.onError(error, c.req.raw));
1453
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1454
+ for (const operation of operations) {
1455
+ const metadata = operationMetadata(operation.operation);
1456
+ const handler = options.handlers[operation.operationId];
1457
+ const route = async (c) => {
1458
+ const request = c.req.raw;
1459
+ if (!metadata.supported || !handler) {
1460
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1461
+ }
1462
+ const url = new URL(request.url);
1463
+ const context = {
1464
+ request,
1465
+ url,
1466
+ params: c.req.param(),
1467
+ query: queryOf(url),
1468
+ body: await readBody(request),
1469
+ sqlite: options.sqlite,
1470
+ namespace: options.namespace,
1471
+ operation,
1472
+ document: options.document,
1473
+ now
1474
+ };
1475
+ const short = await options.before?.(context);
1476
+ if (short)
1477
+ return short;
1478
+ return handler(context);
1479
+ };
1480
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1481
+ }
1482
+ return {
1483
+ app,
1484
+ sqlite: options.sqlite,
1485
+ namespace: options.namespace,
1486
+ fetch: async (request) => app.fetch(request),
1487
+ reset: async () => {
1488
+ clearNamespace(options.sqlite, options.namespace);
1489
+ }
1490
+ };
1491
+ };
1492
+
1493
+ // ../core/dist/snapshot.js
1494
+ var snapshotNamespace = (sqlite, namespace) => ({
1495
+ namespace,
1496
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1497
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1498
+ });
1499
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1500
+ sqlite.transaction(() => {
1501
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1502
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1503
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1504
+ for (const row of snapshot.records) {
1505
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1506
+ }
1507
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1508
+ for (const row of snapshot.sequences) {
1509
+ sequence.run(namespace, row.name, row.kind, row.value);
1510
+ }
1511
+ });
1512
+ };
1513
+
1514
+ // ../core/dist/version.js
1515
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1516
+
1517
+ // ../core/dist/signing.js
1518
+ var encoder = new TextEncoder();
1519
+ var toBase64 = (bytes) => {
1520
+ let binary = "";
1521
+ for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
1522
+ binary += String.fromCharCode(byte);
1523
+ }
1524
+ return btoa(binary);
1525
+ };
1526
+ var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1527
+ var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1528
+ var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
1529
+ var hmac = async (algorithm, key, message, encoding = "hex") => {
1530
+ const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
1531
+ const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
1532
+ return encoding === "hex" ? toHex(signed) : toBase64(signed);
1533
+ };
1534
+ var svixSecretBytes = (secret) => {
1535
+ const raw = secret.replace(/^f?whsec_/, "");
1536
+ try {
1537
+ return fromBase64(raw);
1538
+ } catch {
1539
+ throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
1540
+ }
1541
+ };
1542
+ var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
1543
+ var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
1544
+ var signTwilio = async (authToken, url, params) => {
1545
+ const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
1546
+ return hmac("SHA-1", authToken, payload, "base64");
1547
+ };
1548
+
1549
+ // ../core/dist/webhooks.js
1550
+ var signers = {
1551
+ /** No signature. */
1552
+ none: () => () => ({}),
1553
+ /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
1554
+ svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
1555
+ if (!secret)
1556
+ return {};
1557
+ const prefix = options.prefix ?? "svix";
1558
+ return {
1559
+ [`${prefix}-id`]: messageId,
1560
+ [`${prefix}-timestamp`]: String(timestampSeconds),
1561
+ [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
1562
+ };
1563
+ },
1564
+ /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
1565
+ timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
1566
+ /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
1567
+ twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
1568
+ /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
1569
+ header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
1570
+ /** Anything else: the service computes the headers itself. */
1571
+ custom: (sign2) => sign2
1572
+ };
1573
+ var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
1574
+ var unref = (timer) => {
1575
+ ;
1576
+ timer.unref?.();
1577
+ };
1578
+ var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
1579
+ var matchesEndpoint = (endpoint, message) => {
1580
+ const events = endpoint.events ?? ["*"];
1581
+ if (!events.includes("*") && !events.includes(message.type))
1582
+ return false;
1583
+ for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
1584
+ if (message.tags[key] !== value)
1585
+ return false;
1586
+ }
1587
+ return true;
1588
+ };
1589
+ var createWebhookHub = (options) => {
1590
+ const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
1591
+ const timeoutMs = options.timeoutMs ?? 15e3;
1592
+ const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
1593
+ const send = options.fetch ?? ((request) => fetch(request));
1594
+ const keep = options.keep ?? 500;
1595
+ const now = options.now ?? Date.now;
1596
+ const id = options.id ?? randomId;
1597
+ const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
1598
+ const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
1599
+ const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
1600
+ const own = /* @__PURE__ */ new Map();
1601
+ const messages = [];
1602
+ const deliveries = /* @__PURE__ */ new Map();
1603
+ const pending = /* @__PURE__ */ new Map();
1604
+ const payloads = /* @__PURE__ */ new Map();
1605
+ const faults = /* @__PURE__ */ new Map();
1606
+ const held = /* @__PURE__ */ new Map();
1607
+ const inFlight = /* @__PURE__ */ new Set();
1608
+ const track = (work) => {
1609
+ inFlight.add(work);
1610
+ void work.finally(() => inFlight.delete(work));
1611
+ };
1612
+ const attempt = async (delivery) => {
1613
+ const entry = payloads.get(delivery.id);
1614
+ if (!entry)
1615
+ return false;
1616
+ const { message, endpoint } = entry;
1617
+ const timestampSeconds = Math.floor(now() / 1e3);
1618
+ const started = now();
1619
+ const record = {
1620
+ attempt: delivery.attempts.length + 1,
1621
+ at: new Date(started).toISOString(),
1622
+ status: null,
1623
+ error: null,
1624
+ durationMs: 0,
1625
+ responseBody: null
1626
+ };
1627
+ const controller = new AbortController();
1628
+ const timer = scheduleTimer(() => controller.abort(), timeoutMs);
1629
+ try {
1630
+ const signed = await options.signer({
1631
+ messageId: message.id,
1632
+ body: message.body,
1633
+ timestampSeconds,
1634
+ url: endpoint.url,
1635
+ secret: endpoint.secret,
1636
+ signUrl: endpoint.signUrl ?? endpoint.url,
1637
+ form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
1638
+ type: message.type,
1639
+ tags: message.tags
1640
+ });
1641
+ const response = await send(new Request(endpoint.url, {
1642
+ method: "POST",
1643
+ headers: {
1644
+ "content-type": message.contentType,
1645
+ ...endpoint.headers,
1646
+ ...message.headers,
1647
+ ...signed
1648
+ },
1649
+ body: message.body,
1650
+ signal: controller.signal
1651
+ }));
1652
+ record.status = response.status;
1653
+ record.responseBody = await response.text();
1654
+ } catch (error) {
1655
+ record.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
1656
+ } finally {
1657
+ cancel(timer);
1658
+ record.durationMs = now() - started;
1659
+ delivery.attempts.push(record);
1660
+ }
1661
+ return record.status !== null && delivered(record.status);
1662
+ };
1663
+ const schedule = (delivery) => {
1664
+ const index = delivery.attempts.length;
1665
+ if (index >= delays.length) {
1666
+ delivery.state = "failed";
1667
+ pending.delete(delivery.id);
1668
+ return;
1669
+ }
1670
+ const run = () => {
1671
+ pending.delete(delivery.id);
1672
+ track(attempt(delivery).then((ok2) => {
1673
+ if (ok2)
1674
+ delivery.state = "delivered";
1675
+ else
1676
+ schedule(delivery);
1677
+ }));
1678
+ };
1679
+ const delay = delays[index] ?? 0;
1680
+ if (delay <= 0) {
1681
+ pending.set(delivery.id, void 0);
1682
+ run();
1683
+ return;
1684
+ }
1685
+ const timer = scheduleTimer(run, delay);
1686
+ unref(timer);
1687
+ pending.set(delivery.id, timer);
1688
+ };
1689
+ const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
1690
+ const fanOut = (message, state = "pending") => {
1691
+ for (const endpoint of endpointsFor(message.namespace)) {
1692
+ if (!matchesEndpoint(endpoint, message))
1693
+ continue;
1694
+ const delivery = {
1695
+ id: id("dlv_"),
1696
+ messageId: message.id,
1697
+ namespace: message.namespace,
1698
+ type: message.type,
1699
+ endpointId: endpoint.id ?? "we_unknown",
1700
+ url: endpoint.url,
1701
+ state,
1702
+ attempts: []
1703
+ };
1704
+ deliveries.set(delivery.id, delivery);
1705
+ payloads.set(delivery.id, { message, endpoint });
1706
+ if (state === "pending")
1707
+ schedule(delivery);
1708
+ }
1709
+ };
1710
+ const takeFault = (namespace) => {
1711
+ const queue = faults.get(namespace);
1712
+ const head = queue?.[0];
1713
+ if (!queue || !head)
1714
+ return void 0;
1715
+ head.remaining--;
1716
+ if (head.remaining <= 0)
1717
+ queue.shift();
1718
+ return head.mode;
1719
+ };
1720
+ const releaseHeld = (namespace) => {
1721
+ const waiting = held.get(namespace);
1722
+ if (!waiting)
1723
+ return;
1724
+ held.delete(namespace);
1725
+ for (const message of waiting)
1726
+ fanOut(message);
1727
+ };
1728
+ const hub = {
1729
+ publish(input) {
1730
+ const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
1731
+ const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
1732
+ const message = {
1733
+ id: input.id ?? id("msg_"),
1734
+ namespace: input.namespace,
1735
+ type: input.type,
1736
+ body,
1737
+ contentType,
1738
+ tags: input.tags ?? {},
1739
+ headers: input.headers ?? {},
1740
+ publishedAt: new Date(now()).toISOString()
1741
+ };
1742
+ messages.push(message);
1743
+ const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
1744
+ const oldest = ofNamespace[0];
1745
+ if (ofNamespace.length > keep && oldest)
1746
+ messages.splice(messages.indexOf(oldest), 1);
1747
+ options.onMessage?.(message);
1748
+ const fault = takeFault(message.namespace);
1749
+ if (fault === "drop") {
1750
+ fanOut(message, "dropped");
1751
+ return message;
1752
+ }
1753
+ if (fault === "reorder") {
1754
+ held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
1755
+ return message;
1756
+ }
1757
+ fanOut(message);
1758
+ if (fault === "duplicate")
1759
+ fanOut(message);
1760
+ releaseHeld(message.namespace);
1761
+ return message;
1762
+ },
1763
+ setEndpoints(namespace, endpoints) {
1764
+ const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
1765
+ own.set(namespace, withIds);
1766
+ return withIds;
1767
+ },
1768
+ endpoints: endpointsFor,
1769
+ messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
1770
+ deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
1771
+ async replay(id2) {
1772
+ const delivery = deliveries.get(id2);
1773
+ if (!delivery)
1774
+ return void 0;
1775
+ const ok2 = await attempt(delivery);
1776
+ if (ok2)
1777
+ delivery.state = "delivered";
1778
+ return delivery;
1779
+ },
1780
+ async flush() {
1781
+ for (const namespace of [...held.keys()])
1782
+ releaseHeld(namespace);
1783
+ const waiting = [...pending.entries()];
1784
+ for (const [id2, timer] of waiting) {
1785
+ if (timer === void 0)
1786
+ continue;
1787
+ cancel(timer);
1788
+ pending.delete(id2);
1789
+ const delivery = deliveries.get(id2);
1790
+ if (!delivery)
1791
+ continue;
1792
+ track(attempt(delivery).then((ok2) => {
1793
+ if (ok2)
1794
+ delivery.state = "delivered";
1795
+ else
1796
+ schedule(delivery);
1797
+ }));
1798
+ }
1799
+ await hub.idle();
1800
+ },
1801
+ async idle() {
1802
+ while (inFlight.size > 0)
1803
+ await Promise.allSettled([...inFlight]);
1804
+ },
1805
+ fault(namespace, fault) {
1806
+ const queue = faults.get(namespace) ?? [];
1807
+ queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
1808
+ faults.set(namespace, queue);
1809
+ },
1810
+ clear(namespace) {
1811
+ for (const [id2, delivery] of deliveries) {
1812
+ if (namespace !== void 0 && delivery.namespace !== namespace)
1813
+ continue;
1814
+ const timer = pending.get(id2);
1815
+ if (timer !== void 0)
1816
+ cancel(timer);
1817
+ pending.delete(id2);
1818
+ deliveries.delete(id2);
1819
+ payloads.delete(id2);
1820
+ }
1821
+ for (let i = messages.length - 1; i >= 0; i--) {
1822
+ if (namespace === void 0 || messages[i]?.namespace === namespace)
1823
+ messages.splice(i, 1);
1824
+ }
1825
+ if (namespace === void 0) {
1826
+ held.clear();
1827
+ faults.clear();
1828
+ own.clear();
1829
+ } else {
1830
+ held.delete(namespace);
1831
+ faults.delete(namespace);
1832
+ own.delete(namespace);
1833
+ }
1834
+ }
1835
+ };
1836
+ return hub;
1837
+ };
1838
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1839
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1840
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1841
+ var parseEndpoint = (value) => {
1842
+ if (!isRecord3(value) || typeof value.url !== "string")
1843
+ return "each endpoint needs a url";
1844
+ try {
1845
+ new URL(value.url);
1846
+ } catch {
1847
+ return `not a URL: ${value.url}`;
1848
+ }
1849
+ const endpoint = { url: value.url };
1850
+ if (typeof value.id === "string")
1851
+ endpoint.id = value.id;
1852
+ if (typeof value.secret === "string")
1853
+ endpoint.secret = value.secret;
1854
+ if (typeof value.signUrl === "string")
1855
+ endpoint.signUrl = value.signUrl;
1856
+ const events = value.events ?? value.enabledEvents;
1857
+ if (Array.isArray(events))
1858
+ endpoint.events = events.map(String);
1859
+ if (isRecord3(value.tags)) {
1860
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1861
+ }
1862
+ if (typeof value.account === "string")
1863
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1864
+ if (isRecord3(value.headers)) {
1865
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1866
+ }
1867
+ return endpoint;
1868
+ };
1869
+ var webhookAdminRoutes = (hub) => ({
1870
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1871
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1872
+ const type = url.searchParams.get("type");
1873
+ return type === null || d.type === type;
1874
+ })
1875
+ }),
1876
+ "GET /webhooks/events": ({ url, namespace }) => {
1877
+ const type = url.searchParams.get("type");
1878
+ return json2(200, {
1879
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1880
+ });
1881
+ },
1882
+ "POST /webhooks/:id/replay": async ({ params }) => {
1883
+ const replayed = await hub.replay(params.id);
1884
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1885
+ },
1886
+ "POST /webhooks/flush": async () => {
1887
+ await hub.flush();
1888
+ return json2(200, { status: "ok" });
1889
+ },
1890
+ "POST /webhooks/faults": ({ body, namespace }) => {
1891
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1892
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1893
+ }
1894
+ const fault = { mode: body.mode };
1895
+ if (typeof body.count === "number")
1896
+ fault.count = body.count;
1897
+ hub.fault(namespace, fault);
1898
+ return json2(201, { namespace, ...fault });
1899
+ },
1900
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1901
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1902
+ ...rest,
1903
+ secret: secret ? "(set)" : null
1904
+ }))
1905
+ }),
1906
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1907
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1908
+ if (!Array.isArray(list))
1909
+ return adminError2(400, "expected [{url, secret?, events?}]");
1910
+ const parsed = [];
1911
+ for (const each of list) {
1912
+ const endpoint = parseEndpoint(each);
1913
+ if (typeof endpoint === "string")
1914
+ return adminError2(400, endpoint);
1915
+ parsed.push(endpoint);
1916
+ }
1917
+ const set = hub.setEndpoints(namespace, parsed);
1918
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1919
+ },
1920
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1921
+ hub.setEndpoints(namespace, []);
1922
+ return json2(200, { status: "ok" });
1923
+ }
1924
+ });
1925
+ var parsePayload = (message) => {
1926
+ if (message.contentType.startsWith("application/json")) {
1927
+ try {
1928
+ return JSON.parse(message.body);
1929
+ } catch {
1930
+ return message.body;
1931
+ }
1932
+ }
1933
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1934
+ return Object.fromEntries(new URLSearchParams(message.body));
1935
+ }
1936
+ return message.body;
1937
+ };
1938
+
1939
+ // ../core/dist/runtime.js
1940
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1941
+ var BRANCH_HEADER = "x-mockingbird-branch";
1942
+ var AT_HEADER = "x-mockingbird-at";
1943
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1944
+ var DEFAULT_NAMESPACE = "default";
1945
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1946
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1947
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1948
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1949
+ var effects = /* @__PURE__ */ new WeakMap();
1950
+ var reuseSorted = (fresh, previous, compare, equal) => {
1951
+ if (!previous || previous.length === 0)
1952
+ return fresh.map((row) => Object.freeze(row));
1953
+ const result = new Array(fresh.length);
1954
+ let unchanged = fresh.length === previous.length;
1955
+ let oldIndex = 0;
1956
+ for (let index = 0; index < fresh.length; index++) {
1957
+ const row = fresh[index];
1958
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1959
+ oldIndex++;
1960
+ }
1961
+ const old = previous[oldIndex];
1962
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1963
+ if (result[index] !== previous[index])
1964
+ unchanged = false;
1965
+ }
1966
+ return unchanged ? previous : result;
1967
+ };
1968
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1969
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1970
+ var DroppedConnectionError = class extends TypeError {
1971
+ code = "MOCKINGBIRD_DROP";
1972
+ constructor() {
1973
+ super("fetch failed: connection dropped by Mockingbird fault");
1974
+ this.name = "TypeError";
1975
+ }
1976
+ };
1977
+ var operationMatcher = (document2) => {
1978
+ const matchers = listOperations(document2).map((operation) => ({
1979
+ operationId: operation.operationId,
1980
+ method: operation.method.toUpperCase(),
1981
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1982
+ params: (operation.path.match(/\{/g) ?? []).length
1983
+ })).sort((a, b) => a.params - b.params);
1984
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1985
+ };
1986
+ var createRuntime = (options) => {
1987
+ const sqlite = bootSqlite(options.sqlite);
1988
+ const clock = options.clock ?? createClock();
1989
+ const rng = createRng(options.seed ?? 0);
1990
+ const wallNow = options.io?.wallNow ?? Date.now;
1991
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1992
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1993
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1994
+ const metrics = createMetrics();
1995
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1996
+ const version = options.version ?? PACKAGE_VERSION;
1997
+ const instances = /* @__PURE__ */ new Map();
1998
+ const publicNamespaces = /* @__PURE__ */ new Set();
1999
+ const branchRngs = /* @__PURE__ */ new Map();
2000
+ const timelines = /* @__PURE__ */ new Map();
2001
+ const branchStorage = /* @__PURE__ */ new Map();
2002
+ const captured = /* @__PURE__ */ new Map();
2003
+ const credentials = createCredentialRegistry();
2004
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
2005
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
2006
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
2007
+ const existing = instances.get(key);
2008
+ if (existing)
2009
+ return existing;
2010
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
2011
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
2012
+ }
2013
+ const created = options.create({
2014
+ namespace: storageNamespace(key),
2015
+ publicNamespace,
2016
+ sqlite,
2017
+ clock,
2018
+ rng: isolatedRng ?? rng
2019
+ });
2020
+ instances.set(key, created);
2021
+ publicNamespaces.add(publicNamespace);
2022
+ if (isolatedRng)
2023
+ branchRngs.set(key, isolatedRng);
2024
+ return created;
2025
+ };
2026
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
2027
+ const capture = (storage) => {
2028
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
2029
+ const previous = captured.get(storage);
2030
+ const snapshot2 = {
2031
+ namespace: fresh.namespace,
2032
+ 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),
2033
+ 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)
2034
+ };
2035
+ Object.freeze(snapshot2.records);
2036
+ Object.freeze(snapshot2.sequences);
2037
+ Object.freeze(snapshot2);
2038
+ captured.set(storage, snapshot2);
2039
+ return Object.freeze({
2040
+ snapshot: snapshot2,
2041
+ clock: Object.freeze(clock.state()),
2042
+ rngState: (branchRngs.get(storage) ?? rng).state()
2043
+ });
2044
+ };
2045
+ const timeline = (name = DEFAULT_NAMESPACE) => {
2046
+ let found = timelines.get(name);
2047
+ if (found)
2048
+ return found;
2049
+ instance(name);
2050
+ found = new Timeline({
2051
+ now: clock.now,
2052
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
2053
+ });
2054
+ found.commit(capture(name));
2055
+ timelines.set(name, found);
2056
+ return found;
2057
+ };
2058
+ const physicalBranch = (namespace, branch2) => {
2059
+ if (branch2 === "main")
2060
+ return namespace;
2061
+ const mapKey = `${namespace}\0${branch2}`;
2062
+ const existing = branchStorage.get(mapKey);
2063
+ if (existing)
2064
+ return existing;
2065
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
2066
+ branchStorage.set(mapKey, key);
2067
+ return key;
2068
+ };
2069
+ const ensureBranch = (namespace, branch2, at) => {
2070
+ if (!BRANCH_PATTERN2.test(branch2))
2071
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2072
+ const history = timeline(namespace);
2073
+ if (branch2 === "main") {
2074
+ if (at !== void 0) {
2075
+ const point = history.checkout("main", at);
2076
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2077
+ captured.set(namespace, point.value.snapshot);
2078
+ rng.setState(point.value.rngState);
2079
+ clock.set(point.value.clock.now);
2080
+ if (point.value.clock.frozen)
2081
+ clock.freeze();
2082
+ else
2083
+ clock.unfreeze();
2084
+ }
2085
+ return namespace;
2086
+ }
2087
+ const storage = physicalBranch(namespace, branch2);
2088
+ if (!history.hasBranch(branch2)) {
2089
+ if (at === void 0)
2090
+ history.commit(capture(namespace));
2091
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
2092
+ const branchRng = createRng(options.seed ?? 0);
2093
+ if (point)
2094
+ branchRng.setState(point.value.rngState);
2095
+ instanceFor(storage, namespace, branchRng);
2096
+ if (point)
2097
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2098
+ if (point)
2099
+ captured.set(storage, point.value.snapshot);
2100
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2101
+ const point = history.checkout(branch2, at);
2102
+ if (!instances.has(storage)) {
2103
+ const branchRng = createRng(options.seed ?? 0);
2104
+ branchRng.setState(point.value.rngState);
2105
+ instanceFor(storage, namespace, branchRng);
2106
+ }
2107
+ branchRngs.get(storage)?.setState(point.value.rngState);
2108
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2109
+ captured.set(storage, point.value.snapshot);
2110
+ } else {
2111
+ if (!instances.has(storage)) {
2112
+ const point = history.head(branch2);
2113
+ const branchRng = createRng(options.seed ?? 0);
2114
+ if (point)
2115
+ branchRng.setState(point.value.rngState);
2116
+ instanceFor(storage, namespace, branchRng);
2117
+ }
2118
+ }
2119
+ return storage;
2120
+ };
2121
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
2122
+ const storage = ensureBranch(namespace, branch2);
2123
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
2124
+ };
2125
+ const branch = (name, branchOptions = {}) => {
2126
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
2127
+ ensureBranch(namespace, name, branchOptions.at);
2128
+ const head = timeline(namespace).head(name);
2129
+ if (!head)
2130
+ throw new RangeError(`branch ${name} has no checkpoint`);
2131
+ return head;
2132
+ };
2133
+ const checkout = (checkpointId, checkoutOptions = {}) => {
2134
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2135
+ const branchName = checkoutOptions.branch ?? "main";
2136
+ const history = timeline(namespace);
2137
+ const point = history.checkout(branchName, checkpointId);
2138
+ const storage = ensureBranch(namespace, branchName);
2139
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2140
+ captured.set(storage, point.value.snapshot);
2141
+ clock.set(point.value.clock.now);
2142
+ if (point.value.clock.frozen)
2143
+ clock.freeze();
2144
+ else
2145
+ clock.unfreeze();
2146
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
2147
+ };
2148
+ const reset = async (name = DEFAULT_NAMESPACE) => {
2149
+ if (name === "*") {
2150
+ options.webhooks?.clear();
2151
+ for (const each of instances.values())
2152
+ await each.reset();
2153
+ timelines.clear();
2154
+ branchStorage.clear();
2155
+ branchRngs.clear();
2156
+ captured.clear();
2157
+ return;
2158
+ }
2159
+ options.webhooks?.clear(name);
2160
+ const target = instances.get(name);
2161
+ if (target)
2162
+ await target.reset();
2163
+ else
2164
+ clearNamespace(sqlite, storageNamespace(name));
2165
+ for (const [mapping, storage] of branchStorage) {
2166
+ if (!mapping.startsWith(`${name}\0`))
2167
+ continue;
2168
+ const branchInstance = instances.get(storage);
2169
+ if (branchInstance)
2170
+ await branchInstance.reset();
2171
+ else
2172
+ clearNamespace(sqlite, storageNamespace(storage));
2173
+ branchStorage.delete(mapping);
2174
+ branchRngs.delete(storage);
2175
+ captured.delete(storage);
2176
+ }
2177
+ timelines.delete(name);
2178
+ captured.delete(name);
2179
+ };
2180
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
2181
+ return checkpoint(name, "main").value.snapshot;
2182
+ };
2183
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
2184
+ instance(name);
2185
+ restoreNamespace(sqlite, storageNamespace(name), from);
2186
+ captured.set(name, from);
2187
+ const history = timelines.get(name);
2188
+ if (history)
2189
+ history.commit(capture(name), { branch: "main" });
2190
+ else
2191
+ timeline(name);
2192
+ };
2193
+ const runtime = {
2194
+ name: options.name,
2195
+ sqlite,
2196
+ clock,
2197
+ faults,
2198
+ metrics,
2199
+ journal,
2200
+ rng,
2201
+ credentials,
2202
+ webhooks: options.webhooks,
2203
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
2204
+ const preset = options.presets?.[name];
2205
+ if (!preset)
2206
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
2207
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
2208
+ namespace,
2209
+ ...rule,
2210
+ ...overrides,
2211
+ preset: name,
2212
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
2213
+ }));
2214
+ if (preset.webhook && options.webhooks) {
2215
+ options.webhooks.fault(namespace, {
2216
+ ...preset.webhook,
2217
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
2218
+ });
2219
+ }
2220
+ return added;
2221
+ },
2222
+ instance,
2223
+ namespaces: () => [...publicNamespaces].sort(),
2224
+ reset,
2225
+ snapshot,
2226
+ restore,
2227
+ checkpoint,
2228
+ branch,
2229
+ checkout,
2230
+ timeline,
2231
+ fetch: async (incoming) => {
2232
+ let request = incoming;
2233
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
2234
+ if (prefixed) {
2235
+ const url2 = new URL(request.url);
2236
+ url2.pathname = prefixed[2] ?? "/";
2237
+ const headers = new Headers(request.headers);
2238
+ if (!headers.has(NAMESPACE_HEADER)) {
2239
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
2240
+ }
2241
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
2242
+ request = new Request(url2, {
2243
+ method: request.method,
2244
+ headers,
2245
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
2246
+ signal: request.signal
2247
+ });
2248
+ }
2249
+ let namespace = control.namespaceOf(request);
2250
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
2251
+ const credential = options.credential(request);
2252
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
2253
+ if (mapped !== void 0)
2254
+ namespace = mapped;
2255
+ }
2256
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
2257
+ const at = request.headers.get(AT_HEADER) ?? void 0;
2258
+ const stamp = (response2) => {
2259
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
2260
+ try {
2261
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
2262
+ return response2;
2263
+ } catch {
2264
+ const copy = new Response(response2.body, response2);
2265
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
2266
+ return copy;
2267
+ }
2268
+ };
2269
+ const handled = await control.handle(request);
2270
+ if (handled)
2271
+ return stamp(handled);
2272
+ const started = monotonicNow();
2273
+ const url = new URL(request.url);
2274
+ const operationId = operationIdFor(request, url.pathname);
2275
+ const log = (status, faultId, response2) => {
2276
+ const noted = response2 ? responseNotes(response2) : void 0;
2277
+ const entry = {
2278
+ service: options.name,
2279
+ namespace,
2280
+ operationId,
2281
+ method: request.method,
2282
+ path: url.pathname,
2283
+ status,
2284
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
2285
+ unmatched: options.document !== void 0 && operationId === void 0,
2286
+ ...faultId !== void 0 ? { faultId } : {},
2287
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
2288
+ ...noted?.adopted ? { adopted: true } : {}
2289
+ };
2290
+ metrics.record(entry);
2291
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
2292
+ options.onLog?.(entry);
2293
+ };
2294
+ if (!NAMESPACE_PATTERN.test(namespace)) {
2295
+ log(400);
2296
+ return stamp(new Response(JSON.stringify({
2297
+ error: {
2298
+ type: "mockingbird_admin",
2299
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
2300
+ }
2301
+ }), { status: 400, headers: { "content-type": "application/json" } }));
2302
+ }
2303
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
2304
+ log(400);
2305
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
2306
+ }
2307
+ let storage;
2308
+ try {
2309
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
2310
+ const point = timeline(namespace).get(at);
2311
+ storage = physicalBranch(namespace, `at_${at}`);
2312
+ let viewRng = branchRngs.get(storage);
2313
+ if (!viewRng) {
2314
+ viewRng = createRng(options.seed ?? 0);
2315
+ instanceFor(storage, namespace, viewRng);
2316
+ }
2317
+ viewRng.setState(point.value.rngState);
2318
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2319
+ captured.set(storage, point.value.snapshot);
2320
+ } else {
2321
+ storage = ensureBranch(namespace, selectedBranch, at);
2322
+ }
2323
+ } catch (error) {
2324
+ log(409);
2325
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
2326
+ }
2327
+ const hits = await faults.take({
2328
+ operationId,
2329
+ method: request.method,
2330
+ path: url.pathname,
2331
+ namespace
2332
+ });
2333
+ const final = hits.find((hit) => hit.drop || hit.response);
2334
+ if (final?.drop) {
2335
+ log(0, final.id);
2336
+ throw new DroppedConnectionError();
2337
+ }
2338
+ if (final?.response) {
2339
+ log(final.response.status, final.id);
2340
+ return stamp(final.response);
2341
+ }
2342
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2343
+ if (fired.length > 0)
2344
+ effects.set(request, fired.map((hit) => hit.effect));
2345
+ let response = await instanceFor(storage, namespace).fetch(request);
2346
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2347
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2348
+ response = mutableResponse(response);
2349
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2350
+ }
2351
+ if (selectedBranch !== "main") {
2352
+ response = mutableResponse(response);
2353
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2354
+ }
2355
+ if (at !== void 0) {
2356
+ response = mutableResponse(response);
2357
+ response.headers.set(AT_HEADER, at);
2358
+ }
2359
+ log(response.status, fired[0]?.id, response);
2360
+ return stamp(response);
2361
+ }
2362
+ };
2363
+ const control = createControlPlane({
2364
+ name: options.name,
2365
+ startedAt: wallNow(),
2366
+ wallNow,
2367
+ clock,
2368
+ faults,
2369
+ metrics,
2370
+ journal,
2371
+ defaultNamespace: DEFAULT_NAMESPACE,
2372
+ namespaces: runtime.namespaces,
2373
+ reset,
2374
+ timeTravel: {
2375
+ checkpoint: (name, branchName) => {
2376
+ const point = checkpoint(name, branchName);
2377
+ return {
2378
+ id: point.id,
2379
+ branch: point.branch,
2380
+ parent: point.parent,
2381
+ at: point.at,
2382
+ records: point.value.snapshot.records.length
2383
+ };
2384
+ },
2385
+ branch: (branchName, branchOptions) => {
2386
+ const point = branch(branchName, branchOptions);
2387
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2388
+ },
2389
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2390
+ retain: (name, checkpointId) => {
2391
+ timeline(name).retain(checkpointId);
2392
+ },
2393
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2394
+ inspect: (name) => {
2395
+ const history = timeline(name);
2396
+ return {
2397
+ branches: history.branches(),
2398
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2399
+ id,
2400
+ branch: branchName,
2401
+ parent,
2402
+ at
2403
+ }))
2404
+ };
2405
+ }
2406
+ },
2407
+ describe: options.describe ?? (() => ({})),
2408
+ ...options.presets ? {
2409
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2410
+ } : {},
2411
+ routes: {
2412
+ ...credentialRoutes(credentials),
2413
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2414
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2415
+ ...options.admin?.(runtime) ?? {}
2416
+ },
2417
+ adminKey: options.adminKey
2418
+ });
2419
+ return runtime;
2420
+ };
2421
+ var mutableResponse = (response) => {
2422
+ try {
2423
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2424
+ response.headers.delete("x-mockingbird-mutable-probe");
2425
+ return response;
2426
+ } catch {
2427
+ return new Response(response.body, response);
2428
+ }
2429
+ };
2430
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2431
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2432
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2433
+ var credentialRoutes = (registry) => ({
2434
+ "GET /credentials": () => adminJson(200, {
2435
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2436
+ credential: maskCredential(credential),
2437
+ namespace
2438
+ }))
2439
+ }),
2440
+ "PUT /credentials": ({ body, namespace }) => {
2441
+ const pairs = [];
2442
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2443
+ if (Array.isArray(list)) {
2444
+ for (const each of list) {
2445
+ if (typeof each === "string")
2446
+ pairs.push([each, namespace]);
2447
+ else if (isObject(each) && typeof each.credential === "string") {
2448
+ pairs.push([
2449
+ each.credential,
2450
+ typeof each.namespace === "string" ? each.namespace : namespace
2451
+ ]);
2452
+ } else
2453
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2454
+ }
2455
+ } else if (isObject(list)) {
2456
+ for (const [credential, target] of Object.entries(list)) {
2457
+ if (typeof target !== "string")
2458
+ return adminFail(400, `namespace for ${credential} must be a string`);
2459
+ pairs.push([credential, target]);
2460
+ }
2461
+ } else if (isObject(body) && typeof body.credential === "string") {
2462
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2463
+ } else {
2464
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2465
+ }
2466
+ for (const [credential, target] of pairs) {
2467
+ if (!NAMESPACE_PATTERN.test(target))
2468
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2469
+ registry.set(credential, target);
2470
+ }
2471
+ return adminJson(200, { mapped: pairs.length });
2472
+ },
2473
+ "DELETE /credentials": ({ url }) => {
2474
+ const credential = url.searchParams.get("credential");
2475
+ if (credential === null)
2476
+ registry.clear();
2477
+ else
2478
+ registry.remove(credential);
2479
+ return adminJson(200, { status: "ok" });
2480
+ }
2481
+ });
2482
+ var presetRoutes = (presets, runtime) => ({
2483
+ "GET /faults/presets": () => adminJson(200, {
2484
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2485
+ }),
2486
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2487
+ const name = params.name;
2488
+ if (!presets[name])
2489
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2490
+ const overrides = isObject(body) ? body : {};
2491
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2492
+ }
2493
+ });
2494
+
2495
+ // ../core/dist/validation.js
2496
+ var bodyIssues = (context, contentType = "application/json") => {
2497
+ const requestBody = context.operation.operation.requestBody;
2498
+ if (!requestBody)
2499
+ return [];
2500
+ const resolved = deref(context.document, requestBody);
2501
+ const schema = resolved.content?.[contentType]?.schema;
2502
+ if (!schema)
2503
+ return [];
2504
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2505
+ if (context.body.kind === "invalid") {
2506
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2507
+ }
2508
+ if (value === void 0) {
2509
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2510
+ }
2511
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2512
+ };
2513
+
2514
+ // src/generated/openapi.ts
2515
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Fullscript API (Mockingbird subset)","description":"Stateful mock subset of the Fullscript API for lab ordering: per-practitioner OAuth (authorize, token with authorization_code and refresh_token grants, revoke), clinic, embeddable session grants, lab orders, lab-order events, expiring result PDFs, and signed webhooks. Hand-authored from the EMR consumer (fullscript-api-client.ts, fullscript-event-model.ts, fullscript-webhook-signature.ts).\\n","version":"1","x-mockingbird-upstream":{"note":"Wire shapes from apps/geviti-emr-backend/src/services/fullscript-*.ts and routers/v1/fullscript/*; the vendor's API reference is behind a partner login."}},"servers":[{"url":"https://api-us-snd.fullscript.io"}],"security":[{"bearerAuth":[]}],"paths":{"/api/oauth/token":{"post":{"operationId":"OAuthToken","description":"Exchange an authorization code, or rotate a refresh token (the old refresh token stops working).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthTokenResponse"}}}},"400":{"description":"invalid_grant / unsupported_grant_type / invalid_request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthError"}}}},"401":{"description":"invalid_client","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthError"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TokenRequest"}}}}}},"/api/oauth/revoke":{"post":{"operationId":"OAuthRevoke","description":"Revoke an access or refresh token (RFC 7009: always 200).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Revoked","content":{"application/json":{"schema":{"type":"object"}}}},"400":{"description":"invalid_request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthError"}}}},"401":{"description":"invalid_client","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthError"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RevokeRequest"}}}}}},"/api/clinic":{"get":{"operationId":"GetClinic","description":"The token's clinic.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Clinic","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicResponse"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}}}},"/api/clinic/embeddable/session_grants":{"post":{"operationId":"CreateSessionGrant","description":"A short-lived secret for the embedded Fullscript widget.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"201":{"description":"Grant","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SessionGrant"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}}}},"/api/clinic/labs/orders":{"get":{"operationId":"ListLabOrders","description":"The clinic's lab orders (optionally one patient's), paged.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LabOrdersPage"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"parameters":[{"name":"patient_id","in":"query","required":false,"schema":{"type":"string","enum":["pat_seed_1","pat_seed_2","pat_missing"]}},{"name":"page[number]","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":3}},{"name":"page[size]","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}}]}},"/api/clinic/labs/orders/{orderId}":{"get":{"operationId":"GetLabOrder","description":"One lab order with tests, per-test results and the aggregated result.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LabOrderResponse"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"404":{"description":"Unknown order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"parameters":[{"name":"orderId","in":"path","required":true,"schema":{"type":"string","enum":["lo_seed_1","lo_seed_2","lo_seed_3","lo_missing"]}}]}},"/api/events/lab_orders":{"get":{"operationId":"ListLabOrderEvents","description":"The clinic's lab_order.updated events, newest first by default.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EventsPage"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"parameters":[{"name":"order_by","in":"query","required":false,"schema":{"type":"string","enum":["DESC","ASC"]}},{"name":"page[number]","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":3}},{"name":"page[size]","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}}]}},"/api/events/{eventId}":{"get":{"operationId":"GetEvent","description":"One event with its data.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EventResponse"}}}},"401":{"description":"Missing, invalid, expired or revoked access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"404":{"description":"Unknown event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiErrors"}}}}},"parameters":[{"name":"eventId","in":"path","required":true,"schema":{"type":"string","enum":["evt_1","evt_2","evt_3","evt_missing"]}}]}},"/oauth/authorize":{"get":{"operationId":"Authorize","description":"The consent page: auto-approves as the requested (or default) practitioner and redirects to redirect_uri with code and state.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Browser redirect flow; covered by acceptance tests."}},"parameters":[{"name":"client_id","in":"query","required":true,"schema":{"type":"string"}},{"name":"redirect_uri","in":"query","required":true,"schema":{"type":"string"}},{"name":"response_type","in":"query","required":true,"schema":{"type":"string","enum":["code"]}},{"name":"state","in":"query","required":false,"schema":{"type":"string"}},{"name":"scope","in":"query","required":false,"schema":{"type":"string"}},{"name":"practitioner_id","in":"query","required":false,"schema":{"type":"string"}}],"responses":{"302":{"description":"Redirect back with ?code=&state="},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthError"}}}}}}},"/results/{artifactId}":{"get":{"operationId":"GetResultPdf","description":"An expiring result PDF URL (what pdf_url points at).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Binary PDF behind an expiring signed URL; covered by acceptance tests."}},"parameters":[{"name":"artifactId","in":"path","required":true,"schema":{"type":"string"}},{"name":"expires","in":"query","required":true,"schema":{"type":"string"}},{"name":"signature","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"The PDF","content":{"application/pdf":{"schema":{"type":"string","format":"binary"}}}},"403":{"description":"Expired or bad signature"},"404":{"description":"Unknown artifact"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"schemas":{"TokenRequest":{"type":"object","required":["grant_type","client_id","client_secret"],"properties":{"grant_type":{"type":"string","enum":["authorization_code","refresh_token"]},"client_id":{"type":"string","minLength":1,"maxLength":64,"examples":["parity-client"]},"client_secret":{"type":"string","minLength":1,"maxLength":64,"examples":["parity-secret"]},"code":{"type":"string","maxLength":64},"refresh_token":{"type":"string","maxLength":200},"redirect_uri":{"type":"string","maxLength":200,"examples":["https://emr.example.com/v1/fullscript/oauth/callback"]}}},"RevokeRequest":{"type":"object","required":["client_id","client_secret","token"],"properties":{"client_id":{"type":"string","minLength":1,"maxLength":64},"client_secret":{"type":"string","minLength":1,"maxLength":64},"token":{"type":"string","minLength":1,"maxLength":200}}},"OAuthTokenResponse":{"type":"object","required":["oauth"],"properties":{"oauth":{"type":"object","required":["access_token","token_type","expires_in","refresh_token","scope","created_at","resource_owner"],"properties":{"access_token":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"token_type":{"type":"string","enum":["Bearer"]},"expires_in":{"type":"integer"},"refresh_token":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"scope":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"resource_owner":{"type":"object","required":["id","type"],"properties":{"id":{"type":"string"},"type":{"type":"string","enum":["Practitioner","Staff"]},"clinic_id":{"type":"string"}}}}}}},"OAuthError":{"type":"object","required":["error"],"properties":{"error":{"type":"string"},"error_description":{"type":"string"}}},"ApiErrors":{"type":"object","required":["errors"],"properties":{"errors":{"type":"array","items":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string"},"message":{"type":"string"}}}}}},"ClinicResponse":{"type":"object","required":["clinic"],"properties":{"clinic":{"type":"object","required":["id","name"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}}}},"SessionGrant":{"type":"object","required":["secret_token","expires_at"],"properties":{"secret_token":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"expires_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"LabOrderSummary":{"type":"object","required":["id","state","treatment_plan_id","patient_id","created_at","updated_at"],"properties":{"id":{"type":"string"},"state":{"type":"string","enum":["not_purchased","purchased","schedule_appointment","upcoming_appointment","processing","partial_results","results_ready","interpretation_shared","results_amended"]},"treatment_plan_id":{"type":["string","null"]},"patient_id":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"LabOrdersPage":{"type":"object","required":["orders","meta"],"properties":{"orders":{"type":"array","items":{"$ref":"#/components/schemas/LabOrderSummary"}},"meta":{"type":"object","required":["current_page","next_page","prev_page","total_pages","total_count"],"properties":{"current_page":{"type":"integer"},"next_page":{"type":["integer","null"]},"prev_page":{"type":["integer","null"]},"total_pages":{"type":"integer"},"total_count":{"type":"integer"}}}}},"LabOrderResponse":{"type":"object","required":["order"],"properties":{"order":{"type":"object","required":["id","state","treatment_plan_id","tests","results","latest_aggregated_result"],"properties":{"id":{"type":"string"},"state":{"type":"string","enum":["not_purchased","purchased","schedule_appointment","upcoming_appointment","processing","partial_results","results_ready","interpretation_shared","results_amended"]},"treatment_plan_id":{"type":["string","null"]},"patient_id":{"type":"string"},"name":{"type":"string"},"collection_method":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"tests":{"type":"array","items":{"type":"object","required":["id","name"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"lab_type":{"type":"string"}}}},"results":{"type":"array","items":{"type":"object","required":["id","name","state","pdf_url"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"state":{"type":"string"},"pdf_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}}},"latest_aggregated_result":{"type":["object","null"],"properties":{"id":{"type":"string"},"artifact_id":{"type":"string"},"pdf_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"status":{"type":"string"}}}}}}},"EventSummary":{"type":"object","required":["id","type","clinic_id","created_at"],"properties":{"id":{"type":"string"},"type":{"type":"string","enum":["lab_order.updated"]},"clinic_id":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"EventsPage":{"type":"object","required":["events","meta"],"properties":{"events":{"type":"array","items":{"$ref":"#/components/schemas/EventSummary"}},"meta":{"type":"object","required":["current_page","next_page","prev_page","total_pages","total_count"],"properties":{"current_page":{"type":"integer"},"next_page":{"type":["integer","null"]},"prev_page":{"type":["integer","null"]},"total_pages":{"type":"integer"},"total_count":{"type":"integer"}}}}},"EventResponse":{"type":"object","required":["event"],"properties":{"event":{"type":"object","required":["id","type","clinic_id","created_at","data"],"properties":{"id":{"type":"string"},"type":{"type":"string"},"clinic_id":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"data":{"type":"object"}}}}}}}}`);
2516
+ var operationIds = ["OAuthToken", "OAuthRevoke", "GetClinic", "CreateSessionGrant", "ListLabOrders", "GetLabOrder", "ListLabOrderEvents", "GetEvent", "Authorize", "GetResultPdf"];
2517
+ var supportedOperationIds = ["OAuthToken", "OAuthRevoke", "GetClinic", "CreateSessionGrant", "ListLabOrders", "GetLabOrder", "ListLabOrderEvents", "GetEvent", "Authorize", "GetResultPdf"];
2518
+
2519
+ // src/pdf.ts
2520
+ var RESULT_PDF = new TextEncoder().encode(
2521
+ "%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n4 0 obj\n<< /Length 64 >>\nstream\nBT /F1 18 Tf 72 720 Td (Mockingbird Fullscript lab result) Tj ET\nendstream\nendobj\n5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\nxref\n0 6\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \n0000000241 00000 n \n0000000355 00000 n \ntrailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n425\n%%EOF\n"
2522
+ );
2523
+
2524
+ // src/state.ts
2525
+ var LAB_ORDER_STATES = [
2526
+ "not_purchased",
2527
+ "purchased",
2528
+ "schedule_appointment",
2529
+ "upcoming_appointment",
2530
+ "processing",
2531
+ "partial_results",
2532
+ "results_ready",
2533
+ "interpretation_shared",
2534
+ "results_amended"
2535
+ ];
2536
+ var isLabOrderState = (value) => typeof value === "string" && LAB_ORDER_STATES.includes(value);
2537
+ var stateRank = (state) => LAB_ORDER_STATES.indexOf(state);
2538
+ var DEFAULT_SETTINGS = {
2539
+ clients: [],
2540
+ accessTokenTtlSeconds: 7200,
2541
+ codeTtlSeconds: 600,
2542
+ pdfUrlTtlSeconds: 900,
2543
+ resultsBaseUrl: null
2544
+ };
2545
+ var DEFAULT_CLINIC = {
2546
+ id: "clinic_mock_1",
2547
+ name: "Geviti Mock Clinic",
2548
+ created_at: "2025-01-01T00:00:00.000Z"
2549
+ };
2550
+ var DEFAULT_PRACTITIONER = {
2551
+ id: "prac_mock_1",
2552
+ type: "Practitioner",
2553
+ clinicId: DEFAULT_CLINIC.id
2554
+ };
2555
+ var FullscriptState = class {
2556
+ constructor(sqlite, namespace, seed) {
2557
+ this.seed = seed;
2558
+ this.practitioners = new Collection(sqlite, namespace, "practitioners");
2559
+ this.clinics = new Collection(sqlite, namespace, "clinics");
2560
+ this.codes = new Collection(sqlite, namespace, "codes");
2561
+ this.refresh = new Collection(sqlite, namespace, "refresh_tokens");
2562
+ this.revoked = new Collection(sqlite, namespace, "revoked_tokens");
2563
+ this.orders = new Collection(sqlite, namespace, "lab_orders");
2564
+ this.events = new Collection(sqlite, namespace, "events");
2565
+ this.settings = new Collection(sqlite, namespace, "settings");
2566
+ this.counters = new Collection(sqlite, namespace, "counters");
2567
+ this.ensureSeeded();
2568
+ }
2569
+ seed;
2570
+ practitioners;
2571
+ clinics;
2572
+ codes;
2573
+ refresh;
2574
+ revoked;
2575
+ orders;
2576
+ events;
2577
+ settings;
2578
+ counters;
2579
+ ensureSeeded() {
2580
+ if (this.clinics.count() === 0) this.clinics.insert(DEFAULT_CLINIC.id, DEFAULT_CLINIC);
2581
+ if (this.practitioners.count() === 0) {
2582
+ this.practitioners.insert(DEFAULT_PRACTITIONER.id, DEFAULT_PRACTITIONER);
2583
+ }
2584
+ if (!this.settings.has("settings")) {
2585
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
2586
+ }
2587
+ }
2588
+ current() {
2589
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2590
+ }
2591
+ update(patch) {
2592
+ const next = { ...this.current(), ...patch };
2593
+ this.settings.insert("settings", next);
2594
+ return next;
2595
+ }
2596
+ next(kind) {
2597
+ const current = this.counters.get("counters") ?? {
2598
+ code: 0,
2599
+ refresh: 0,
2600
+ order: 0,
2601
+ event: 0,
2602
+ artifact: 0
2603
+ };
2604
+ const next = { ...current, [kind]: current[kind] + 1 };
2605
+ this.counters.insert("counters", next);
2606
+ return next[kind];
2607
+ }
2608
+ };
2609
+
2610
+ // src/runtime.ts
2611
+ var SIGNATURE_HEADER = "Fullscript-Signature";
2612
+ var API = "/api/";
2613
+ var FULLSCRIPT_PRESETS = {
2614
+ token_expired: {
2615
+ description: "API calls answer 401 token_expired before the token's 2 h (our token service refreshes)",
2616
+ rules: [
2617
+ { pathPrefix: "/api/clinic", effect: "token_expired" },
2618
+ { pathPrefix: "/api/events", effect: "token_expired" }
2619
+ ]
2620
+ },
2621
+ invalid_grant: {
2622
+ description: "The refresh_token grant answers 400 invalid_grant (the practitioner must reconnect)",
2623
+ rules: [{ operationId: "OAuthToken", effect: "invalid_grant" }]
2624
+ },
2625
+ rate_limited: {
2626
+ description: "API calls answer 429 rate_limited",
2627
+ rules: [
2628
+ {
2629
+ pathPrefix: API,
2630
+ status: 429,
2631
+ body: { errors: [{ code: "rate_limited", message: "Too many requests" }] }
2632
+ }
2633
+ ]
2634
+ },
2635
+ server_error: {
2636
+ description: "API calls answer 500",
2637
+ rules: [
2638
+ {
2639
+ pathPrefix: API,
2640
+ status: 500,
2641
+ body: { errors: [{ code: "internal_server_error", message: "Something went wrong" }] }
2642
+ }
2643
+ ]
2644
+ },
2645
+ events_schema_drift: {
2646
+ description: "The lab-order events list answers an unexpected event type (our zod literal rejects it)",
2647
+ rules: [{ operationId: "ListLabOrderEvents", effect: "events_schema_drift" }]
2648
+ },
2649
+ pdf_not_pdf: {
2650
+ description: "Result PDF URLs answer 200 text/html (our downloader rejects the content type)",
2651
+ rules: [
2652
+ {
2653
+ operationId: "GetResultPdf",
2654
+ status: 200,
2655
+ body: "<html>Sign in</html>",
2656
+ headers: { "content-type": "text/html" }
2657
+ }
2658
+ ]
2659
+ },
2660
+ pdf_redirect: {
2661
+ description: "Result PDF URLs answer a 302 (our downloader refuses redirects)",
2662
+ rules: [
2663
+ {
2664
+ operationId: "GetResultPdf",
2665
+ status: 302,
2666
+ body: "",
2667
+ headers: { location: "https://login.fullscript.com/" }
2668
+ }
2669
+ ]
2670
+ },
2671
+ pdf_expired: {
2672
+ description: "Result PDF URLs answer 403 as if expired",
2673
+ rules: [
2674
+ {
2675
+ operationId: "GetResultPdf",
2676
+ status: 403,
2677
+ body: "Request has expired",
2678
+ headers: { "content-type": "text/plain" }
2679
+ }
2680
+ ]
2681
+ },
2682
+ connection_drop: {
2683
+ description: "The connection drops before any answer (fetch rejects)",
2684
+ rules: [{ pathPrefix: API, drop: true }]
2685
+ },
2686
+ slow: {
2687
+ description: "API calls answer after 12 s (past our client's 10 s timeout)",
2688
+ rules: [{ pathPrefix: API, latencyMs: 12e3 }]
2689
+ },
2690
+ webhook_duplicate: {
2691
+ description: "The next webhook is delivered twice",
2692
+ webhook: { mode: "duplicate" }
2693
+ },
2694
+ webhook_reorder: {
2695
+ description: "The next two webhooks arrive swapped",
2696
+ webhook: { mode: "reorder" }
2697
+ },
2698
+ webhook_drop: { description: "The next webhook is never delivered", webhook: { mode: "drop" } }
2699
+ };
2700
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2701
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2702
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2703
+ var echoes = async (response, challenge) => {
2704
+ try {
2705
+ const body = await response.clone().json();
2706
+ return body.challenge === challenge;
2707
+ } catch {
2708
+ return false;
2709
+ }
2710
+ };
2711
+ var adminRoutes = (send, challenge) => (runtime) => ({
2712
+ "POST /oauth/codes": ({ body, namespace }) => {
2713
+ const input = isRecord4(body) ? body : {};
2714
+ const api = runtime.instance(namespace);
2715
+ const practitionerId = typeof input.practitionerId === "string" ? input.practitionerId : "prac_mock_1";
2716
+ if (!api.state.practitioners.get(practitionerId))
2717
+ return adminError3(404, `no practitioner ${practitionerId}`);
2718
+ const code = api.issueCode(
2719
+ practitionerId,
2720
+ typeof input.clientId === "string" ? input.clientId : "any",
2721
+ typeof input.redirectUri === "string" ? input.redirectUri : null
2722
+ );
2723
+ return json3(201, { code });
2724
+ },
2725
+ "POST /practitioners": ({ body, namespace }) => {
2726
+ if (!isRecord4(body) || typeof body.id !== "string" || typeof body.clinicId !== "string") {
2727
+ return adminError3(
2728
+ 400,
2729
+ 'expected {"id", "clinicId", "type"?: "Practitioner"|"Staff", "clinicName"?}'
2730
+ );
2731
+ }
2732
+ const api = runtime.instance(namespace);
2733
+ if (!api.state.clinics.get(body.clinicId)) {
2734
+ api.state.clinics.insert(body.clinicId, {
2735
+ id: body.clinicId,
2736
+ name: typeof body.clinicName === "string" ? body.clinicName : body.clinicId,
2737
+ created_at: new Date(runtime.clock.now()).toISOString()
2738
+ });
2739
+ }
2740
+ const practitioner = {
2741
+ id: body.id,
2742
+ clinicId: body.clinicId,
2743
+ type: body.type === "Staff" ? "Staff" : "Practitioner"
2744
+ };
2745
+ api.state.practitioners.insert(practitioner.id, practitioner);
2746
+ return json3(201, practitioner);
2747
+ },
2748
+ "GET /lab-orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).labOrders() }),
2749
+ "POST /lab-orders": ({ body, namespace }) => {
2750
+ if (!isRecord4(body) || typeof body.patientId !== "string") {
2751
+ return adminError3(
2752
+ 400,
2753
+ 'expected {"patientId", "id"?, "clinicId"?, "treatmentPlanId"?, "name"?, "collectionMethod"?, "tests"?: [names]}'
2754
+ );
2755
+ }
2756
+ const text = (key) => typeof body[key] === "string" ? { [key]: body[key] } : {};
2757
+ const order = runtime.instance(namespace).createOrder({
2758
+ patientId: body.patientId,
2759
+ ...text("id"),
2760
+ ...text("clinicId"),
2761
+ ...text("treatmentPlanId"),
2762
+ ...text("name"),
2763
+ ...text("collectionMethod"),
2764
+ ...Array.isArray(body.tests) ? { tests: body.tests.map(String) } : {}
2765
+ });
2766
+ return json3(201, order);
2767
+ },
2768
+ "POST /lab-orders/:id/transition": ({ params, body, namespace }) => {
2769
+ if (!isRecord4(body) || !isLabOrderState(body.to)) {
2770
+ return adminError3(
2771
+ 400,
2772
+ 'expected {"to": "<purchased|schedule_appointment|upcoming_appointment|processing|partial_results|results_ready|interpretation_shared|results_amended>"}'
2773
+ );
2774
+ }
2775
+ try {
2776
+ return json3(200, runtime.instance(namespace).transition(params.id, body.to));
2777
+ } catch (error) {
2778
+ if (error instanceof HttpError) return error.toResponse();
2779
+ throw error;
2780
+ }
2781
+ },
2782
+ "GET /events": ({ namespace }) => json3(200, { events: runtime.instance(namespace).eventsList() }),
2783
+ "POST /webhooks/verify": async ({ namespace }) => {
2784
+ const endpoints = runtime.webhooks?.endpoints(namespace) ?? [];
2785
+ const results = await Promise.all(
2786
+ endpoints.map(async (endpoint) => {
2787
+ try {
2788
+ const response = await send(
2789
+ new Request(endpoint.url, {
2790
+ method: "POST",
2791
+ headers: { "content-type": "application/json" }
2792
+ })
2793
+ );
2794
+ return {
2795
+ url: endpoint.url,
2796
+ status: response.status,
2797
+ challengeEchoed: challenge ? await echoes(response, challenge) : null
2798
+ };
2799
+ } catch (error) {
2800
+ return {
2801
+ url: endpoint.url,
2802
+ status: null,
2803
+ error: error instanceof Error ? error.message : String(error)
2804
+ };
2805
+ }
2806
+ })
2807
+ );
2808
+ return json3(200, { endpoints: results });
2809
+ },
2810
+ "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
2811
+ "PUT /settings": ({ body, namespace }) => {
2812
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2813
+ const patch = {};
2814
+ for (const key of ["accessTokenTtlSeconds", "codeTtlSeconds", "pdfUrlTtlSeconds"]) {
2815
+ if (body[key] !== void 0) {
2816
+ if (typeof body[key] !== "number") return adminError3(400, `${key}: number`);
2817
+ patch[key] = body[key];
2818
+ }
2819
+ }
2820
+ if (body.resultsBaseUrl !== void 0) {
2821
+ if (body.resultsBaseUrl !== null && typeof body.resultsBaseUrl !== "string")
2822
+ return adminError3(400, "resultsBaseUrl: string | null");
2823
+ patch.resultsBaseUrl = body.resultsBaseUrl;
2824
+ }
2825
+ if (body.clients !== void 0) {
2826
+ if (!Array.isArray(body.clients))
2827
+ return adminError3(400, "clients: [{clientId, clientSecret}]");
2828
+ patch.clients = body.clients.filter(isRecord4).map((c) => ({ clientId: String(c.clientId), clientSecret: String(c.clientSecret) }));
2829
+ }
2830
+ return json3(200, runtime.instance(namespace).state.update(patch));
2831
+ }
2832
+ });
2833
+ var createRuntime2 = (options = {}) => {
2834
+ const { retryDelaysMs, fetch: rawSend, challenge, ...endpoint } = options.webhooks ?? { url: "" };
2835
+ const send = rawSend ?? ((request) => fetch(request));
2836
+ const hub = createWebhookHub({
2837
+ signer: signers.timestamped(SIGNATURE_HEADER),
2838
+ ...retryDelaysMs ? { retryDelaysMs } : {},
2839
+ // Fullscript counts a delivery as acknowledged only when the receiver echoes the
2840
+ // challenge key; anything else is retried (recorded as a 502).
2841
+ fetch: async (request) => {
2842
+ const response = await send(request);
2843
+ if (!challenge || !response.ok || await echoes(response, challenge)) return response;
2844
+ return new Response(null, { status: 502, statusText: "challenge not echoed" });
2845
+ },
2846
+ endpoints: options.webhooks ? [endpoint] : []
2847
+ });
2848
+ const runtime = createRuntime({
2849
+ name: FULLSCRIPT_NAMESPACE,
2850
+ document,
2851
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2852
+ ...options.clock ? { clock: options.clock } : {},
2853
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2854
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2855
+ ...options.onLog ? { onLog: options.onLog } : {},
2856
+ credential: tokenCredential,
2857
+ presets: FULLSCRIPT_PRESETS,
2858
+ webhooks: hub,
2859
+ create: ({ sqlite, namespace, publicNamespace, clock }) => new FullscriptAPI({
2860
+ sqlite,
2861
+ namespace,
2862
+ publicNamespace,
2863
+ now: clock.now,
2864
+ ...options.settings ? { settings: options.settings } : {},
2865
+ ...options.orders ? { orders: options.orders } : {},
2866
+ onEvent: (event) => hub.publish({
2867
+ namespace: publicNamespace,
2868
+ type: event.type,
2869
+ id: event.id,
2870
+ body: envelope(event)
2871
+ })
2872
+ }),
2873
+ describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
2874
+ admin: adminRoutes(send, challenge)
2875
+ });
2876
+ return Object.assign(runtime, { webhooks: hub });
2877
+ };
2878
+
2879
+ // src/index.ts
2880
+ var FULLSCRIPT_NAMESPACE = "fullscript";
2881
+ var SCOPE = "clinic:read labs:read labs:write patients:read";
2882
+ var TOKEN_PREFIX = "fsat_";
2883
+ var apiErrors = (status, code, message) => jsonRes(status, { errors: [{ code, message }] });
2884
+ var oauthError = (status, error, description) => jsonRes(status, { error, error_description: description });
2885
+ var INVALID_GRANT = "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.";
2886
+ var INVALID_CLIENT = "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.";
2887
+ var base64url = (value) => toBase64(new TextEncoder().encode(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2888
+ var fromBase64url = (value) => {
2889
+ try {
2890
+ return new TextDecoder("utf-8", { fatal: true }).decode(
2891
+ fromBase64(value.replace(/-/g, "+").replace(/_/g, "/"))
2892
+ );
2893
+ } catch {
2894
+ return void 0;
2895
+ }
2896
+ };
2897
+ var sign = (payload, issuedAt) => opaqueToken(`fullscript:${payload}:${issuedAt}`, 32);
2898
+ var issueAccessToken = (claims, issuedAtSeconds) => {
2899
+ const payload = base64url(
2900
+ JSON.stringify([claims.clientId, claims.practitionerId, claims.clinicId, claims.type])
2901
+ );
2902
+ return `${TOKEN_PREFIX}${payload}.${issuedAtSeconds}.${sign(payload, issuedAtSeconds)}`;
2903
+ };
2904
+ var readAccessToken = (token) => {
2905
+ if (!token.startsWith(TOKEN_PREFIX)) return void 0;
2906
+ const [payload, issued, signature] = token.slice(TOKEN_PREFIX.length).split(".");
2907
+ const issuedAt = Number(issued);
2908
+ if (!payload || !Number.isInteger(issuedAt) || signature !== sign(payload, issuedAt))
2909
+ return void 0;
2910
+ const decoded = fromBase64url(payload);
2911
+ try {
2912
+ const [clientId, practitionerId, clinicId, type] = JSON.parse(decoded ?? "");
2913
+ if (!clientId || !practitionerId || !clinicId) return void 0;
2914
+ return {
2915
+ clientId,
2916
+ practitionerId,
2917
+ clinicId,
2918
+ type: type === "Staff" ? "Staff" : "Practitioner",
2919
+ issuedAt
2920
+ };
2921
+ } catch {
2922
+ return void 0;
2923
+ }
2924
+ };
2925
+ var tokenCredential = (request) => {
2926
+ const token = bearerToken(request);
2927
+ return token ? readAccessToken(token)?.clientId ?? token : void 0;
2928
+ };
2929
+ var publicEvent = (event) => ({
2930
+ id: event.id,
2931
+ type: event.type,
2932
+ clinic_id: event.clinic_id,
2933
+ created_at: event.created_at,
2934
+ data: event.data
2935
+ });
2936
+ var envelope = (event) => ({ event_payload: { event: publicEvent(event) } });
2937
+ var page = (context) => {
2938
+ const q = context.query;
2939
+ const block = q.page ?? {};
2940
+ const number = coerce.integer(block.number ?? "1");
2941
+ const size = coerce.integer(block.size ?? "20");
2942
+ return {
2943
+ number: number.ok && number.value > 0 ? number.value : 1,
2944
+ size: size.ok && size.value > 0 ? Math.min(size.value, 100) : 20
2945
+ };
2946
+ };
2947
+ var meta = (current, size, total) => {
2948
+ const totalPages = Math.max(1, Math.ceil(total / size));
2949
+ return {
2950
+ current_page: current,
2951
+ next_page: current < totalPages ? current + 1 : null,
2952
+ prev_page: current > 1 ? current - 1 : null,
2953
+ total_pages: totalPages,
2954
+ total_count: total
2955
+ };
2956
+ };
2957
+ var FullscriptAPI = class {
2958
+ app;
2959
+ sqlite;
2960
+ state;
2961
+ service;
2962
+ now;
2963
+ prefix;
2964
+ onEvent;
2965
+ constructor(options = {}) {
2966
+ const sqlite = bootSqlite(options.sqlite);
2967
+ const namespace = options.namespace ?? FULLSCRIPT_NAMESPACE;
2968
+ this.now = options.now ?? (() => Date.now());
2969
+ this.onEvent = options.onEvent;
2970
+ this.prefix = options.publicNamespace && options.publicNamespace !== "default" ? `/ns/${encodeURIComponent(options.publicNamespace)}` : "";
2971
+ this.state = new FullscriptState(sqlite, namespace, options.settings ?? {});
2972
+ const handlers = defineOperations({
2973
+ OAuthToken: (context) => this.token(context),
2974
+ OAuthRevoke: (context) => this.revoke(context),
2975
+ GetClinic: (context) => {
2976
+ const claims = this.claims(context);
2977
+ const clinic = this.state.clinics.get(claims.clinicId);
2978
+ if (!clinic) return apiErrors(404, "not_found", "Clinic not found");
2979
+ return jsonRes(200, { clinic });
2980
+ },
2981
+ CreateSessionGrant: (context) => {
2982
+ const claims = this.claims(context);
2983
+ const expires = this.now() + 5 * 6e4;
2984
+ return jsonRes(201, {
2985
+ secret_token: `sg_${opaqueToken(`${claims.practitionerId}:${this.now()}`, 40)}`,
2986
+ expires_at: new Date(expires).toISOString()
2987
+ });
2988
+ },
2989
+ ListLabOrders: (context) => {
2990
+ const claims = this.claims(context);
2991
+ const patient = typeof context.query.patient_id === "string" ? context.query.patient_id : void 0;
2992
+ const rows = this.state.orders.list({
2993
+ order: "oldest",
2994
+ where: (o) => o.clinicId === claims.clinicId && (!patient || o.patientId === patient)
2995
+ }).map((r) => r.value);
2996
+ const p = page(context);
2997
+ return jsonRes(200, {
2998
+ orders: rows.slice((p.number - 1) * p.size, p.number * p.size).map((o) => this.summary(o)),
2999
+ meta: meta(p.number, p.size, rows.length)
3000
+ });
3001
+ },
3002
+ GetLabOrder: (context) => {
3003
+ const claims = this.claims(context);
3004
+ const order = this.state.orders.get(context.params.orderId ?? "");
3005
+ if (!order || order.clinicId !== claims.clinicId)
3006
+ return apiErrors(404, "not_found", "Lab order not found");
3007
+ return annotateResponse(jsonRes(200, { order: this.detail(order, context) }), {
3008
+ ids: { orderId: order.id }
3009
+ });
3010
+ },
3011
+ ListLabOrderEvents: (context) => {
3012
+ const claims = this.claims(context);
3013
+ const ascending = context.query.order_by === "ASC";
3014
+ const rows = this.state.events.list({
3015
+ order: ascending ? "oldest" : "newest",
3016
+ where: (e) => e.clinic_id === claims.clinicId && e.type === "lab_order.updated"
3017
+ }).map((r) => r.value);
3018
+ const p = page(context);
3019
+ const drift = faultEffect(context.request, "events_schema_drift") !== void 0;
3020
+ return jsonRes(200, {
3021
+ events: rows.slice((p.number - 1) * p.size, p.number * p.size).map((e) => ({
3022
+ id: e.id,
3023
+ type: drift ? "lab_order.changed" : e.type,
3024
+ clinic_id: e.clinic_id,
3025
+ created_at: e.created_at
3026
+ })),
3027
+ meta: meta(p.number, p.size, rows.length)
3028
+ });
3029
+ },
3030
+ GetEvent: (context) => {
3031
+ const claims = this.claims(context);
3032
+ const event = this.state.events.get(context.params.eventId ?? "");
3033
+ if (!event || event.clinic_id !== claims.clinicId)
3034
+ return apiErrors(404, "not_found", "Event not found");
3035
+ return jsonRes(200, { event: this.publicEvent(event) });
3036
+ },
3037
+ Authorize: (context) => this.authorize(context),
3038
+ GetResultPdf: (context) => this.pdf(context)
3039
+ });
3040
+ this.service = createService({
3041
+ document,
3042
+ handlers,
3043
+ sqlite,
3044
+ namespace,
3045
+ now: this.now,
3046
+ notFound: () => apiErrors(404, "not_found", "Not Found"),
3047
+ onError: (error) => {
3048
+ if (error instanceof HttpError) return error.toResponse();
3049
+ throw error;
3050
+ },
3051
+ before: (context) => {
3052
+ const id = context.operation.operationId;
3053
+ if (id === "OAuthToken" || id === "OAuthRevoke" || id === "Authorize" || id === "GetResultPdf") {
3054
+ return void 0;
3055
+ }
3056
+ const token = bearerToken(context.request);
3057
+ if (!token)
3058
+ return apiErrors(401, "unauthorized", "You need to sign in or authenticate first");
3059
+ if (faultEffect(context.request, "token_expired") !== void 0) {
3060
+ return apiErrors(401, "token_expired", "The access token expired");
3061
+ }
3062
+ const claims = readAccessToken(token);
3063
+ if (!claims || this.state.revoked.has(token)) {
3064
+ return apiErrors(401, "invalid_token", "The access token is invalid");
3065
+ }
3066
+ if (this.now() / 1e3 >= claims.issuedAt + this.state.current().accessTokenTtlSeconds) {
3067
+ return apiErrors(401, "token_expired", "The access token expired");
3068
+ }
3069
+ return void 0;
3070
+ }
3071
+ });
3072
+ this.app = this.service.app;
3073
+ this.sqlite = this.service.sqlite;
3074
+ for (const seed of options.orders ?? []) this.seedOrder(seed);
3075
+ }
3076
+ fetch(request) {
3077
+ return this.service.fetch(request);
3078
+ }
3079
+ async reset() {
3080
+ await this.service.reset();
3081
+ this.state.ensureSeeded();
3082
+ }
3083
+ iso() {
3084
+ return new Date(this.now()).toISOString();
3085
+ }
3086
+ claims(context) {
3087
+ return readAccessToken(bearerToken(context.request) ?? "");
3088
+ }
3089
+ clientOk(clientId, secret) {
3090
+ const clients = this.state.current().clients;
3091
+ if (typeof clientId !== "string" || typeof secret !== "string" || !clientId || !secret)
3092
+ return false;
3093
+ return clients.length === 0 || clients.some((c) => c.clientId === clientId && c.clientSecret === secret);
3094
+ }
3095
+ body(context) {
3096
+ const issues = bodyIssues(context);
3097
+ if (issues.length > 0) {
3098
+ throw new HttpError(400, {
3099
+ error: "invalid_request",
3100
+ error_description: `The request is missing a required parameter or is otherwise malformed: ${issues.map((i) => `${i.path || "body"} ${i.message}`).join("; ")}`
3101
+ });
3102
+ }
3103
+ return context.body.kind === "json" ? context.body.value : {};
3104
+ }
3105
+ /** Mint an authorization code for a practitioner (what the consent page does). */
3106
+ issueCode(practitionerId, clientId, redirectUri) {
3107
+ const code = `code_${opaqueToken(`${practitionerId}:${this.state.next("code")}`, 32)}`;
3108
+ this.state.codes.insert(code, {
3109
+ code,
3110
+ practitionerId,
3111
+ clientId,
3112
+ redirectUri,
3113
+ expiresAtMs: this.now() + this.state.current().codeTtlSeconds * 1e3,
3114
+ used: false
3115
+ });
3116
+ return code;
3117
+ }
3118
+ tokenPair(practitioner, clientId) {
3119
+ const refresh = `fsrt_${opaqueToken(`${practitioner.id}:${this.state.next("refresh")}`, 40)}`;
3120
+ this.state.refresh.insert(refresh, {
3121
+ token: refresh,
3122
+ practitionerId: practitioner.id,
3123
+ clientId,
3124
+ revoked: false
3125
+ });
3126
+ const issuedAt = Math.floor(this.now() / 1e3);
3127
+ return jsonRes(200, {
3128
+ oauth: {
3129
+ access_token: issueAccessToken(
3130
+ {
3131
+ clientId,
3132
+ practitionerId: practitioner.id,
3133
+ clinicId: practitioner.clinicId,
3134
+ type: practitioner.type
3135
+ },
3136
+ issuedAt
3137
+ ),
3138
+ token_type: "Bearer",
3139
+ expires_in: this.state.current().accessTokenTtlSeconds,
3140
+ refresh_token: refresh,
3141
+ scope: SCOPE,
3142
+ created_at: new Date(issuedAt * 1e3).toISOString(),
3143
+ resource_owner: {
3144
+ id: practitioner.id,
3145
+ type: practitioner.type,
3146
+ clinic_id: practitioner.clinicId
3147
+ }
3148
+ }
3149
+ });
3150
+ }
3151
+ token(context) {
3152
+ const body = this.body(context);
3153
+ const clientId = String(body.client_id);
3154
+ if (!this.clientOk(body.client_id, body.client_secret))
3155
+ return oauthError(401, "invalid_client", INVALID_CLIENT);
3156
+ if (body.grant_type === "authorization_code") {
3157
+ if (typeof body.code !== "string" || !body.code) {
3158
+ return oauthError(400, "invalid_request", "Missing required parameter: code.");
3159
+ }
3160
+ const code = this.state.codes.get(body.code);
3161
+ if (!code || code.used || code.clientId !== clientId || this.now() > code.expiresAtMs || code.redirectUri !== null && body.redirect_uri !== code.redirectUri) {
3162
+ return oauthError(400, "invalid_grant", INVALID_GRANT);
3163
+ }
3164
+ this.state.codes.update(code.code, { ...code, used: true });
3165
+ const practitioner2 = this.state.practitioners.get(code.practitionerId) ?? DEFAULT_PRACTITIONER;
3166
+ return this.tokenPair(practitioner2, clientId);
3167
+ }
3168
+ if (typeof body.refresh_token !== "string" || !body.refresh_token) {
3169
+ return oauthError(400, "invalid_request", "Missing required parameter: refresh_token.");
3170
+ }
3171
+ if (faultEffect(context.request, "invalid_grant") !== void 0) {
3172
+ return oauthError(400, "invalid_grant", INVALID_GRANT);
3173
+ }
3174
+ const refresh = this.state.refresh.get(body.refresh_token);
3175
+ if (!refresh || refresh.revoked || refresh.clientId !== clientId) {
3176
+ return oauthError(400, "invalid_grant", INVALID_GRANT);
3177
+ }
3178
+ this.state.refresh.update(refresh.token, { ...refresh, revoked: true });
3179
+ const practitioner = this.state.practitioners.get(refresh.practitionerId) ?? DEFAULT_PRACTITIONER;
3180
+ return this.tokenPair(practitioner, clientId);
3181
+ }
3182
+ revoke(context) {
3183
+ const body = this.body(context);
3184
+ if (!this.clientOk(body.client_id, body.client_secret))
3185
+ return oauthError(401, "invalid_client", INVALID_CLIENT);
3186
+ const token = String(body.token);
3187
+ const refresh = this.state.refresh.get(token);
3188
+ if (refresh) this.state.refresh.update(token, { ...refresh, revoked: true });
3189
+ else if (readAccessToken(token)) this.state.revoked.insert(token, { token });
3190
+ return jsonRes(200, {});
3191
+ }
3192
+ authorize(context) {
3193
+ const url = context.url;
3194
+ const redirect = url.searchParams.get("redirect_uri");
3195
+ const clientId = url.searchParams.get("client_id");
3196
+ if (!redirect || !clientId || url.searchParams.get("response_type") !== "code") {
3197
+ return oauthError(
3198
+ 400,
3199
+ "invalid_request",
3200
+ "client_id, redirect_uri and response_type=code are required."
3201
+ );
3202
+ }
3203
+ const practitionerId = url.searchParams.get("practitioner_id") ?? DEFAULT_PRACTITIONER.id;
3204
+ if (!this.state.practitioners.get(practitionerId)) {
3205
+ return oauthError(400, "invalid_request", `Unknown practitioner ${practitionerId}.`);
3206
+ }
3207
+ const code = this.issueCode(practitionerId, clientId, redirect);
3208
+ const location = new URL(redirect);
3209
+ location.searchParams.set("code", code);
3210
+ const state = url.searchParams.get("state");
3211
+ if (state !== null) location.searchParams.set("state", state);
3212
+ return new Response(null, { status: 302, headers: { location: location.toString() } });
3213
+ }
3214
+ summary(order) {
3215
+ return {
3216
+ id: order.id,
3217
+ state: order.state,
3218
+ treatment_plan_id: order.treatmentPlanId,
3219
+ patient_id: order.patientId,
3220
+ name: order.name,
3221
+ created_at: order.created_at,
3222
+ updated_at: order.updated_at
3223
+ };
3224
+ }
3225
+ /** A signed, expiring URL for a result artifact, on the mock itself (or `resultsBaseUrl`). */
3226
+ pdfUrl(artifactId, context) {
3227
+ const base = this.state.current().resultsBaseUrl ?? `${context.url.origin}${this.prefix}`;
3228
+ const expires = this.now() + this.state.current().pdfUrlTtlSeconds * 1e3;
3229
+ return `${base.replace(/\/$/, "")}/results/${artifactId}?expires=${expires}&signature=${opaqueToken(`${artifactId}:${expires}`, 24)}`;
3230
+ }
3231
+ detail(order, context) {
3232
+ return {
3233
+ ...this.summary(order),
3234
+ collection_method: order.collectionMethod,
3235
+ tests: order.tests,
3236
+ results: order.results.map((r) => ({
3237
+ id: r.id,
3238
+ name: r.name,
3239
+ state: r.state,
3240
+ pdf_url: this.pdfUrl(r.artifactId, context)
3241
+ })),
3242
+ latest_aggregated_result: order.aggregated ? {
3243
+ id: order.aggregated.id,
3244
+ artifact_id: order.aggregated.artifactId,
3245
+ pdf_url: this.pdfUrl(order.aggregated.artifactId, context),
3246
+ status: order.aggregated.status
3247
+ } : null
3248
+ };
3249
+ }
3250
+ pdf(context) {
3251
+ const artifactId = context.params.artifactId ?? "";
3252
+ const expires = Number(context.url.searchParams.get("expires"));
3253
+ const signature = context.url.searchParams.get("signature");
3254
+ if (signature !== opaqueToken(`${artifactId}:${expires}`, 24)) {
3255
+ return new Response("Forbidden", { status: 403, headers: { "content-type": "text/plain" } });
3256
+ }
3257
+ if (this.now() > expires)
3258
+ return new Response("Expired", { status: 403, headers: { "content-type": "text/plain" } });
3259
+ const known = this.state.orders.list().some(
3260
+ ({ value: o }) => o.aggregated?.artifactId === artifactId || o.results.some((r) => r.artifactId === artifactId)
3261
+ );
3262
+ if (!known) return new Response(null, { status: 404 });
3263
+ return new Response(new Blob([RESULT_PDF]), {
3264
+ status: 200,
3265
+ headers: {
3266
+ "content-type": "application/pdf",
3267
+ "content-length": String(RESULT_PDF.byteLength)
3268
+ }
3269
+ });
3270
+ }
3271
+ publicEvent(event) {
3272
+ return {
3273
+ id: event.id,
3274
+ type: event.type,
3275
+ clinic_id: event.clinic_id,
3276
+ created_at: event.created_at,
3277
+ data: event.data
3278
+ };
3279
+ }
3280
+ emit(type, order, data) {
3281
+ const seq = this.state.next("event");
3282
+ const event = {
3283
+ id: `evt_${seq}`,
3284
+ type,
3285
+ clinic_id: order.clinicId,
3286
+ created_at: this.iso(),
3287
+ data,
3288
+ seq
3289
+ };
3290
+ this.state.events.insert(event.id, event);
3291
+ this.onEvent?.(event);
3292
+ return event;
3293
+ }
3294
+ /** Create a lab order in `not_purchased` (a practitioner recommended labs in a treatment plan). */
3295
+ createOrder(input) {
3296
+ const id = input.id ?? `lo_${this.state.next("order")}`;
3297
+ const now = this.iso();
3298
+ const order = {
3299
+ id,
3300
+ clinicId: input.clinicId ?? DEFAULT_PRACTITIONER.clinicId,
3301
+ patientId: input.patientId,
3302
+ treatmentPlanId: input.treatmentPlanId === void 0 ? `tp_${id}` : input.treatmentPlanId,
3303
+ name: input.name ?? "Comprehensive Wellness Panel",
3304
+ collectionMethod: input.collectionMethod ?? "at_home_phlebotomy",
3305
+ state: "not_purchased",
3306
+ tests: (input.tests ?? ["Lipid Panel", "Comprehensive Metabolic Panel"]).map((name, i) => ({
3307
+ id: `lt_${id}_${i + 1}`,
3308
+ name,
3309
+ lab_type: "labs"
3310
+ })),
3311
+ results: [],
3312
+ aggregated: null,
3313
+ created_at: now,
3314
+ updated_at: now
3315
+ };
3316
+ this.state.orders.insert(id, order);
3317
+ return order;
3318
+ }
3319
+ /**
3320
+ * Move an order forward (never back) and emit its events: `order.placed` on purchase and
3321
+ * `lab_order.updated` for every move. Results-bearing states attach result artifacts.
3322
+ */
3323
+ transition(orderId, to) {
3324
+ const order = this.state.orders.get(orderId);
3325
+ if (!order)
3326
+ throw new HttpError(404, {
3327
+ error: { type: "mockingbird_admin", message: `no lab order ${orderId}` }
3328
+ });
3329
+ if (stateRank(to) <= stateRank(order.state)) {
3330
+ throw new HttpError(409, {
3331
+ error: {
3332
+ type: "mockingbird_admin",
3333
+ message: `lab orders only move forward: ${order.state} \u2192 ${to} is not allowed`
3334
+ }
3335
+ });
3336
+ }
3337
+ const artifact = () => `art_${opaqueToken(`${order.id}:${this.state.next("artifact")}`, 16)}`;
3338
+ const next = { ...order, state: to, updated_at: this.iso() };
3339
+ const rank = stateRank(to);
3340
+ if (rank >= stateRank("partial_results")) {
3341
+ const wanted = rank >= stateRank("results_ready") ? next.tests.length : 1;
3342
+ const results = [...next.results];
3343
+ for (const test of next.tests.slice(results.length, wanted)) {
3344
+ results.push({
3345
+ id: `res_${test.id}`,
3346
+ name: test.name,
3347
+ state: "final",
3348
+ artifactId: artifact()
3349
+ });
3350
+ }
3351
+ next.results = results;
3352
+ }
3353
+ if (rank >= stateRank("results_ready") && (!next.aggregated || to === "results_amended")) {
3354
+ next.aggregated = {
3355
+ id: `agg_${order.id}${to === "results_amended" ? "_amended" : ""}`,
3356
+ artifactId: artifact(),
3357
+ status: to === "results_amended" ? "amended" : "final"
3358
+ };
3359
+ }
3360
+ this.state.orders.update(order.id, next);
3361
+ if (to === "purchased" || order.state === "not_purchased" && rank > stateRank("purchased")) {
3362
+ this.emit("order.placed", next, {
3363
+ id: next.id,
3364
+ treatment_plan_ids: next.treatmentPlanId ? [next.treatmentPlanId] : [],
3365
+ patient_id: next.patientId,
3366
+ line_items: [{ type: "labs", lab_type: "labs", name: next.name }]
3367
+ });
3368
+ }
3369
+ this.emit("lab_order.updated", next, {
3370
+ lab_order: {
3371
+ id: next.id,
3372
+ state: next.state,
3373
+ treatment_plan_id: next.treatmentPlanId,
3374
+ patient_id: next.patientId
3375
+ }
3376
+ });
3377
+ return next;
3378
+ }
3379
+ seedOrder(seed) {
3380
+ const order = this.state.orders.get(seed.id) ?? this.createOrder(seed);
3381
+ return seed.state === order.state ? order : this.transition(order.id, seed.state);
3382
+ }
3383
+ labOrders() {
3384
+ return this.state.orders.list({ order: "oldest" }).map((r) => r.value);
3385
+ }
3386
+ eventsList() {
3387
+ return this.state.events.list({ order: "oldest" }).map((r) => r.value);
3388
+ }
3389
+ };
3390
+
3391
+ export {
3392
+ document,
3393
+ operationIds,
3394
+ supportedOperationIds,
3395
+ RESULT_PDF,
3396
+ LAB_ORDER_STATES,
3397
+ isLabOrderState,
3398
+ DEFAULT_CLINIC,
3399
+ DEFAULT_PRACTITIONER,
3400
+ SIGNATURE_HEADER,
3401
+ FULLSCRIPT_PRESETS,
3402
+ createRuntime2 as createRuntime,
3403
+ FULLSCRIPT_NAMESPACE,
3404
+ apiErrors,
3405
+ oauthError,
3406
+ issueAccessToken,
3407
+ tokenCredential,
3408
+ publicEvent,
3409
+ envelope,
3410
+ FullscriptAPI
3411
+ };
3412
+ //# sourceMappingURL=chunk-RJH5A4X5.js.map