@crvouga/mockingbird-service-mailosaur 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,2882 @@
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 basicAuth = (request) => {
393
+ const header = request.headers.get("authorization");
394
+ if (!header)
395
+ return void 0;
396
+ const match = /^Basic\s+(.+)$/i.exec(header.trim());
397
+ if (!match?.[1])
398
+ return void 0;
399
+ let decoded;
400
+ try {
401
+ decoded = atob(match[1].trim());
402
+ } catch {
403
+ return void 0;
404
+ }
405
+ const colon = decoded.indexOf(":");
406
+ if (colon < 0)
407
+ return { username: decoded, password: "" };
408
+ return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };
409
+ };
410
+ var createCredentialRegistry = () => {
411
+ const map = /* @__PURE__ */ new Map();
412
+ return {
413
+ set: (credential, namespace) => {
414
+ map.set(credential, namespace);
415
+ },
416
+ get: (credential) => map.get(credential),
417
+ remove: (credential) => map.delete(credential),
418
+ clear: () => map.clear(),
419
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
420
+ };
421
+ };
422
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
423
+
424
+ // ../core/dist/rng.js
425
+ var seedFrom = (value) => {
426
+ let hash = 2166136261;
427
+ for (let i = 0; i < value.length; i++) {
428
+ hash ^= value.charCodeAt(i);
429
+ hash = Math.imul(hash, 16777619);
430
+ }
431
+ return hash >>> 0;
432
+ };
433
+ var createRng = (seed = 0) => {
434
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
435
+ let state = numeric;
436
+ const next = () => {
437
+ state = state + 1831565813 >>> 0;
438
+ let t = state;
439
+ t = Math.imul(t ^ t >>> 15, t | 1);
440
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
441
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
442
+ };
443
+ return {
444
+ next,
445
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
446
+ reset: () => {
447
+ state = numeric;
448
+ },
449
+ state: () => state,
450
+ setState: (next2) => {
451
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
452
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
453
+ }
454
+ state = next2 >>> 0;
455
+ },
456
+ seed: numeric
457
+ };
458
+ };
459
+
460
+ // ../core/dist/faults.js
461
+ var matches = (rule, candidate) => {
462
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
463
+ return false;
464
+ }
465
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
466
+ return false;
467
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
468
+ return false;
469
+ }
470
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
471
+ return false;
472
+ return true;
473
+ };
474
+ var faultResponse = (rule) => {
475
+ const status = rule.status ?? 500;
476
+ const headers = { "content-type": "application/json", ...rule.headers };
477
+ if (typeof rule.body === "string")
478
+ return new Response(rule.body, { status, headers });
479
+ if (rule.body === null)
480
+ return new Response(null, { status, headers: rule.headers ?? {} });
481
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
482
+ return new Response(JSON.stringify(body), { status, headers });
483
+ };
484
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
485
+ const entries = [];
486
+ return {
487
+ add(rule) {
488
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
489
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
490
+ if (existing >= 0)
491
+ entries[existing] = entry;
492
+ else
493
+ entries.push(entry);
494
+ return rule;
495
+ },
496
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
497
+ remove(id) {
498
+ const index = entries.findIndex((e) => e.rule.id === id);
499
+ if (index < 0)
500
+ return false;
501
+ entries.splice(index, 1);
502
+ return true;
503
+ },
504
+ clear() {
505
+ entries.length = 0;
506
+ },
507
+ async take(candidate) {
508
+ const hits = [];
509
+ for (const entry of entries) {
510
+ if (entry.remaining === 0)
511
+ continue;
512
+ if (!matches(entry.rule, candidate))
513
+ continue;
514
+ const rate = entry.rule.rate ?? 1;
515
+ if (rng.next() >= rate)
516
+ continue;
517
+ entry.hits++;
518
+ if (entry.remaining !== null)
519
+ entry.remaining--;
520
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
521
+ if (delay !== void 0 && delay > 0) {
522
+ await sleep(delay);
523
+ }
524
+ const hit = { id: entry.rule.id };
525
+ if (entry.rule.effect !== void 0) {
526
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
527
+ }
528
+ if (entry.rule.drop === true)
529
+ hit.drop = true;
530
+ else if (entry.rule.status !== void 0)
531
+ hit.response = faultResponse(entry.rule);
532
+ hits.push(hit);
533
+ if (hit.drop || hit.response)
534
+ break;
535
+ }
536
+ return hits;
537
+ }
538
+ };
539
+ };
540
+
541
+ // ../../openapi/core/dist/refs.js
542
+ var OpenAPIReferenceError = class extends Error {
543
+ ref;
544
+ constructor(ref) {
545
+ super(`unresolvable $ref: ${ref}`);
546
+ this.ref = ref;
547
+ this.name = "OpenAPIReferenceError";
548
+ }
549
+ };
550
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
551
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
552
+ var resolveRef = (document2, ref) => {
553
+ if (!ref.startsWith("#/"))
554
+ throw new OpenAPIReferenceError(ref);
555
+ let cursor = document2;
556
+ for (const raw of ref.slice(2).split("/")) {
557
+ const segment = unescapePointer(raw);
558
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
559
+ throw new OpenAPIReferenceError(ref);
560
+ }
561
+ cursor = cursor[segment];
562
+ }
563
+ if (cursor === void 0)
564
+ throw new OpenAPIReferenceError(ref);
565
+ return cursor;
566
+ };
567
+ var deref = (document2, value) => {
568
+ let current = value;
569
+ const seen = /* @__PURE__ */ new Set();
570
+ while (isReference(current)) {
571
+ if (seen.has(current.$ref))
572
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
573
+ seen.add(current.$ref);
574
+ current = resolveRef(document2, current.$ref);
575
+ }
576
+ return current;
577
+ };
578
+
579
+ // ../../openapi/core/dist/types.js
580
+ var HTTP_METHODS = [
581
+ "get",
582
+ "put",
583
+ "post",
584
+ "delete",
585
+ "options",
586
+ "head",
587
+ "patch",
588
+ "trace"
589
+ ];
590
+
591
+ // ../../openapi/core/dist/document.js
592
+ var mergeParameters = (document2, item, own) => {
593
+ const merged = /* @__PURE__ */ new Map();
594
+ for (const raw of item.parameters ?? []) {
595
+ const parameter = deref(document2, raw);
596
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
597
+ }
598
+ for (const raw of own ?? []) {
599
+ const parameter = deref(document2, raw);
600
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
601
+ }
602
+ return [...merged.values()];
603
+ };
604
+ var listOperations = (document2) => {
605
+ const operations = [];
606
+ for (const [path, item] of Object.entries(document2.paths)) {
607
+ for (const method of HTTP_METHODS) {
608
+ const operation = item[method];
609
+ if (operation?.operationId === void 0)
610
+ continue;
611
+ const responses = {};
612
+ for (const [status, response] of Object.entries(operation.responses)) {
613
+ responses[status] = deref(document2, response);
614
+ }
615
+ operations.push({
616
+ operationId: operation.operationId,
617
+ method,
618
+ path,
619
+ operation,
620
+ parameters: mergeParameters(document2, item, operation.parameters),
621
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
622
+ responses
623
+ });
624
+ }
625
+ }
626
+ return operations;
627
+ };
628
+
629
+ // ../../openapi/core/dist/schema.js
630
+ var resolveSchema = (document2, schema) => {
631
+ let current = schema;
632
+ const seen = /* @__PURE__ */ new Set();
633
+ while (typeof current.$ref === "string") {
634
+ const ref = current.$ref;
635
+ if (seen.has(ref))
636
+ break;
637
+ seen.add(ref);
638
+ const { $ref: _ignored, ...siblings } = current;
639
+ const target = resolveRef(document2, ref);
640
+ current = { ...target, ...siblings };
641
+ }
642
+ if (current.nullable === true) {
643
+ const { nullable: _nullable, ...rest } = current;
644
+ const types = schemaTypes(rest);
645
+ if (types.length > 0 && !types.includes("null"))
646
+ current = { ...rest, type: [...types, "null"] };
647
+ else
648
+ current = rest;
649
+ }
650
+ return current;
651
+ };
652
+ var schemaTypes = (schema) => {
653
+ if (Array.isArray(schema.type))
654
+ return schema.type;
655
+ if (schema.type !== void 0)
656
+ return [schema.type];
657
+ const inferred = [];
658
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
659
+ inferred.push("object");
660
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
661
+ inferred.push("array");
662
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
663
+ inferred.push("string");
664
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
665
+ inferred.push("number");
666
+ return inferred;
667
+ };
668
+ var jsonTypeOf = (value) => {
669
+ if (value === null)
670
+ return "null";
671
+ if (Array.isArray(value))
672
+ return "array";
673
+ switch (typeof value) {
674
+ case "string":
675
+ return "string";
676
+ case "boolean":
677
+ return "boolean";
678
+ case "number":
679
+ return Number.isInteger(value) ? "integer" : "number";
680
+ case "object":
681
+ return "object";
682
+ default:
683
+ return "undefined";
684
+ }
685
+ };
686
+ var deepEqual = (a, b) => {
687
+ if (a === b)
688
+ return true;
689
+ if (typeof a !== typeof b || a === null || b === null)
690
+ return false;
691
+ if (Array.isArray(a)) {
692
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
693
+ }
694
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
695
+ const ka = Object.keys(a);
696
+ const kb = Object.keys(b);
697
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
698
+ }
699
+ return false;
700
+ };
701
+ var FORMAT_PATTERNS = {
702
+ 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,
703
+ date: /^\d{4}-\d{2}-\d{2}$/,
704
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
705
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
706
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
707
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
708
+ };
709
+ var graphemeLength = (value) => [...value].length;
710
+ var validateValue = (document2, schema, value, path = []) => {
711
+ const errors = [];
712
+ const s = resolveSchema(document2, schema);
713
+ const fail = (message) => errors.push({ path, message });
714
+ const actual = jsonTypeOf(value);
715
+ if (actual === "undefined") {
716
+ fail("value is undefined");
717
+ return errors;
718
+ }
719
+ const types = schemaTypes(s);
720
+ if (types.length > 0) {
721
+ const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
722
+ if (!ok) {
723
+ fail(`expected type ${types.join("|")}, got ${actual}`);
724
+ return errors;
725
+ }
726
+ }
727
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
728
+ fail("value not in enum");
729
+ }
730
+ if (s.const !== void 0 && !deepEqual(s.const, value))
731
+ fail("value does not equal const");
732
+ if (typeof value === "string") {
733
+ const length = graphemeLength(value);
734
+ if (s.minLength !== void 0 && length < s.minLength)
735
+ fail(`length ${length} < minLength ${s.minLength}`);
736
+ if (s.maxLength !== void 0 && length > s.maxLength)
737
+ fail(`length ${length} > maxLength ${s.maxLength}`);
738
+ if (s.pattern !== void 0) {
739
+ try {
740
+ if (!new RegExp(s.pattern, "u").test(value))
741
+ fail(`does not match pattern ${s.pattern}`);
742
+ } catch {
743
+ }
744
+ }
745
+ if (s.format !== void 0) {
746
+ const pattern = FORMAT_PATTERNS[s.format];
747
+ if (pattern && !pattern.test(value))
748
+ fail(`does not match format ${s.format}`);
749
+ }
750
+ }
751
+ if (typeof value === "number") {
752
+ if (s.minimum !== void 0 && value < s.minimum)
753
+ fail(`${value} < minimum ${s.minimum}`);
754
+ if (s.maximum !== void 0 && value > s.maximum)
755
+ fail(`${value} > maximum ${s.maximum}`);
756
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
757
+ fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
758
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
759
+ fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
760
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
761
+ fail(`${value} is not a multiple of ${s.multipleOf}`);
762
+ }
763
+ }
764
+ if (Array.isArray(value)) {
765
+ if (s.minItems !== void 0 && value.length < s.minItems)
766
+ fail(`${value.length} items < minItems ${s.minItems}`);
767
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
768
+ fail(`${value.length} items > maxItems ${s.maxItems}`);
769
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
770
+ fail("items are not unique");
771
+ value.forEach((item, i) => {
772
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
773
+ if (itemSchema)
774
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
775
+ });
776
+ }
777
+ if (actual === "object") {
778
+ const record = value;
779
+ const keys = Object.keys(record);
780
+ for (const name of s.required ?? [])
781
+ if (!(name in record))
782
+ fail(`missing required property ${name}`);
783
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
784
+ fail(`${keys.length} properties < minProperties ${s.minProperties}`);
785
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
786
+ fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
787
+ for (const key of keys) {
788
+ const property = s.properties?.[key];
789
+ if (property) {
790
+ errors.push(...validateValue(document2, property, record[key], [...path, key]));
791
+ continue;
792
+ }
793
+ if (s.additionalProperties === false)
794
+ fail(`unexpected property ${key}`);
795
+ else if (typeof s.additionalProperties === "object") {
796
+ errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
797
+ }
798
+ if (s.propertyNames) {
799
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
800
+ if (nameErrors.length > 0)
801
+ fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
802
+ }
803
+ }
804
+ }
805
+ if (s.allOf)
806
+ for (const branch of s.allOf)
807
+ errors.push(...validateValue(document2, branch, value, path));
808
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
809
+ fail("matches no anyOf branch");
810
+ if (s.oneOf) {
811
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
812
+ if (matches2 !== 1)
813
+ fail(`matches ${matches2} oneOf branches, expected exactly 1`);
814
+ }
815
+ if (s.not && validateValue(document2, s.not, value).length === 0)
816
+ fail("matches forbidden `not` schema");
817
+ return errors;
818
+ };
819
+
820
+ // ../../http/codec/dist/form.js
821
+ var parsePath = (rawKey) => {
822
+ const open = rawKey.indexOf("[");
823
+ if (open === -1)
824
+ return [rawKey];
825
+ const path = [rawKey.slice(0, open)];
826
+ const rest = rawKey.slice(open);
827
+ const pattern = /\[([^\]]*)\]/g;
828
+ let match = pattern.exec(rest);
829
+ let consumed = 0;
830
+ while (match !== null) {
831
+ if (match.index !== consumed)
832
+ return [rawKey];
833
+ path.push(match[1] ?? "");
834
+ consumed = match.index + match[0].length;
835
+ match = pattern.exec(rest);
836
+ }
837
+ if (consumed !== rest.length)
838
+ return [rawKey];
839
+ return path;
840
+ };
841
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
842
+ var put = (target, key, value) => {
843
+ if (key === "__proto__") {
844
+ Object.defineProperty(target, key, {
845
+ value,
846
+ enumerable: true,
847
+ writable: true,
848
+ configurable: true
849
+ });
850
+ return;
851
+ }
852
+ ;
853
+ target[key] = value;
854
+ };
855
+ var assign = (target, path, value) => {
856
+ let cursor = target;
857
+ for (let i = 0; i < path.length; i++) {
858
+ const segment = path[i];
859
+ const last = i === path.length - 1;
860
+ if (Array.isArray(cursor)) {
861
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
862
+ if (index === void 0)
863
+ return;
864
+ if (last) {
865
+ put(cursor, index, value);
866
+ return;
867
+ }
868
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
869
+ if (next === void 0 || typeof next === "string") {
870
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
871
+ put(cursor, index, created);
872
+ cursor = created;
873
+ } else {
874
+ cursor = next;
875
+ }
876
+ continue;
877
+ }
878
+ if (typeof cursor === "string")
879
+ return;
880
+ if (last) {
881
+ put(cursor, segment, value);
882
+ return;
883
+ }
884
+ const nextSegment = path[i + 1];
885
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
886
+ if (existing === void 0 || typeof existing === "string") {
887
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
888
+ put(cursor, segment, created);
889
+ cursor = created;
890
+ } else {
891
+ cursor = existing;
892
+ }
893
+ }
894
+ };
895
+ var decodeFormPairs = (pairs) => {
896
+ const out = {};
897
+ for (const [rawKey, value] of pairs)
898
+ assign(out, parsePath(rawKey), value);
899
+ return densify(out);
900
+ };
901
+ var densify = (value) => {
902
+ if (typeof value === "string")
903
+ return value;
904
+ if (Array.isArray(value))
905
+ return value.filter((item) => item !== void 0).map(densify);
906
+ const out = {};
907
+ for (const [key, item] of Object.entries(value))
908
+ put(out, key, densify(item));
909
+ return out;
910
+ };
911
+ var decodeForm = (text) => {
912
+ const source = text.startsWith("?") ? text.slice(1) : text;
913
+ return decodeFormPairs(new URLSearchParams(source).entries());
914
+ };
915
+
916
+ // ../../http/codec/dist/content.js
917
+ var JSON_MEDIA_TYPE = "application/json";
918
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
919
+ var mediaTypeOf = (contentType) => {
920
+ if (!contentType)
921
+ return void 0;
922
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
923
+ return essence ? essence : void 0;
924
+ };
925
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
926
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
927
+ var decodeBody = (contentType, bytes) => {
928
+ if (bytes.byteLength === 0)
929
+ return { kind: "empty" };
930
+ const mediaType = mediaTypeOf(contentType);
931
+ if (mediaType === void 0)
932
+ return { kind: "bytes", value: bytes };
933
+ if (isJsonMediaType(mediaType)) {
934
+ const text = utf8.decode(bytes);
935
+ try {
936
+ return { kind: "json", value: JSON.parse(text) };
937
+ } catch (error) {
938
+ return {
939
+ kind: "invalid",
940
+ mediaType,
941
+ text,
942
+ error: error instanceof Error ? error.message : String(error)
943
+ };
944
+ }
945
+ }
946
+ if (mediaType === FORM_MEDIA_TYPE) {
947
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
948
+ }
949
+ if (mediaType.startsWith("text/"))
950
+ return { kind: "text", value: utf8.decode(bytes) };
951
+ return { kind: "bytes", value: bytes };
952
+ };
953
+ var readBody = async (message) => {
954
+ const bytes = new Uint8Array(await message.arrayBuffer());
955
+ return decodeBody(message.headers.get("content-type"), bytes);
956
+ };
957
+
958
+ // ../core/dist/http.js
959
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
960
+ status,
961
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
962
+ });
963
+ var HttpError = class extends Error {
964
+ status;
965
+ body;
966
+ headers;
967
+ constructor(status, body, headers = {}) {
968
+ super(`HTTP ${status}`);
969
+ this.status = status;
970
+ this.body = body;
971
+ this.headers = headers;
972
+ this.name = "HttpError";
973
+ }
974
+ toResponse() {
975
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
976
+ if (contentType === "text/plain") {
977
+ return new Response(String(this.body), {
978
+ status: this.status,
979
+ headers: this.headers
980
+ });
981
+ }
982
+ return jsonRes(this.status, this.body, this.headers);
983
+ }
984
+ };
985
+
986
+ // ../core/dist/ids.js
987
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
988
+ var mix = (input) => {
989
+ let hash = 2166136261;
990
+ for (let i = 0; i < input.length; i++) {
991
+ hash ^= input.charCodeAt(i);
992
+ hash = Math.imul(hash, 16777619) >>> 0;
993
+ }
994
+ hash ^= hash >>> 16;
995
+ hash = Math.imul(hash, 2246822507) >>> 0;
996
+ hash ^= hash >>> 13;
997
+ return hash >>> 0;
998
+ };
999
+ var opaqueToken = (input, length) => {
1000
+ let out = "";
1001
+ let round = 0;
1002
+ while (out.length < length) {
1003
+ let hash = mix(`${input}:${round++}`);
1004
+ for (let i = 0; i < 5 && out.length < length; i++) {
1005
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1006
+ hash = Math.floor(hash / ALPHABET.length);
1007
+ }
1008
+ }
1009
+ return out;
1010
+ };
1011
+ var IdSequence = class {
1012
+ sqlite;
1013
+ namespace;
1014
+ salt;
1015
+ constructor(sqlite, namespace, salt = "mockingbird") {
1016
+ this.sqlite = sqlite;
1017
+ this.namespace = namespace;
1018
+ this.salt = salt;
1019
+ }
1020
+ next(prefix, length = 14) {
1021
+ return this.sqlite.transaction(() => {
1022
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
1023
+ const value = (row?.value ?? 0) + 1;
1024
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
1025
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
1026
+ return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
1027
+ });
1028
+ }
1029
+ };
1030
+
1031
+ // ../core/dist/journal.js
1032
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1033
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1034
+ const capacity = Math.max(0, Math.floor(size));
1035
+ const rings = /* @__PURE__ */ new Map();
1036
+ let sequence = 0;
1037
+ const order = /* @__PURE__ */ new WeakMap();
1038
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1039
+ return {
1040
+ size: capacity,
1041
+ record(entry) {
1042
+ if (capacity === 0)
1043
+ return;
1044
+ order.set(entry, sequence++);
1045
+ let ring = rings.get(entry.namespace);
1046
+ if (!ring) {
1047
+ ring = { entries: [], next: 0 };
1048
+ rings.set(entry.namespace, ring);
1049
+ }
1050
+ if (ring.entries.length < capacity)
1051
+ ring.entries.push(entry);
1052
+ else {
1053
+ ring.entries[ring.next] = entry;
1054
+ ring.next = (ring.next + 1) % capacity;
1055
+ }
1056
+ },
1057
+ list(query = {}) {
1058
+ 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));
1059
+ 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));
1060
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1061
+ },
1062
+ clear(namespace) {
1063
+ if (namespace === void 0)
1064
+ rings.clear();
1065
+ else
1066
+ rings.delete(namespace);
1067
+ }
1068
+ };
1069
+ };
1070
+ var notes = /* @__PURE__ */ new WeakMap();
1071
+ var annotateResponse = (response, extra) => {
1072
+ const existing = notes.get(response);
1073
+ notes.set(response, {
1074
+ ...existing,
1075
+ ...extra,
1076
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1077
+ });
1078
+ return response;
1079
+ };
1080
+ var responseNotes = (response) => notes.get(response);
1081
+
1082
+ // ../core/dist/metrics.js
1083
+ var createMetrics = () => {
1084
+ let requests = 0;
1085
+ let faults = 0;
1086
+ let totalDurationMs = 0;
1087
+ const byOperation = /* @__PURE__ */ new Map();
1088
+ const unmatched = /* @__PURE__ */ new Map();
1089
+ return {
1090
+ record(entry) {
1091
+ requests++;
1092
+ totalDurationMs += entry.durationMs;
1093
+ if (entry.faultId !== void 0)
1094
+ faults++;
1095
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1096
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1097
+ if (entry.unmatched) {
1098
+ const route = `${entry.method} ${entry.path}`;
1099
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1100
+ }
1101
+ },
1102
+ report: () => ({
1103
+ requests,
1104
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1105
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1106
+ const space = route.indexOf(" ");
1107
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1108
+ }),
1109
+ faults,
1110
+ totalDurationMs
1111
+ }),
1112
+ reset() {
1113
+ requests = 0;
1114
+ faults = 0;
1115
+ totalDurationMs = 0;
1116
+ byOperation.clear();
1117
+ unmatched.clear();
1118
+ }
1119
+ };
1120
+ };
1121
+
1122
+ // ../core/dist/outbox.js
1123
+ var OutboxStore = class {
1124
+ items;
1125
+ constructor(sqlite, namespace, name = "outbox") {
1126
+ this.items = new Collection(sqlite, namespace, name);
1127
+ }
1128
+ record(item) {
1129
+ this.items.insert(item.id, item);
1130
+ return item;
1131
+ }
1132
+ get(id) {
1133
+ return this.items.get(id);
1134
+ }
1135
+ update(id, item) {
1136
+ this.items.update(id, item);
1137
+ }
1138
+ /** Oldest first, so a suite reads messages in the order they were sent. */
1139
+ list(query = {}) {
1140
+ const to = query.to?.toLowerCase();
1141
+ const matched = this.items.list({ order: "oldest" }).map((row) => row.value).filter((item) => {
1142
+ if (to !== void 0) {
1143
+ const recipients = Array.isArray(item.to) ? item.to : [item.to];
1144
+ if (!recipients.some((r) => r.toLowerCase() === to))
1145
+ return false;
1146
+ }
1147
+ if (query.since !== void 0 && Date.parse(item.createdAt) < query.since)
1148
+ return false;
1149
+ if (query.where && !query.where(item))
1150
+ return false;
1151
+ return true;
1152
+ });
1153
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1154
+ }
1155
+ };
1156
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1157
+ var parseSince = (value) => {
1158
+ if (value === null)
1159
+ return void 0;
1160
+ const parsed = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
1161
+ return Number.isNaN(parsed) ? null : parsed;
1162
+ };
1163
+ var outboxAdminRoutes = (runtime, pick, filter) => ({
1164
+ "GET /outbox": ({ url, namespace }) => {
1165
+ const since = parseSince(url.searchParams.get("since"));
1166
+ if (since === null) {
1167
+ return json2(400, {
1168
+ error: { type: "mockingbird_admin", message: "since: expected epoch ms or ISO-8601" }
1169
+ });
1170
+ }
1171
+ const limit = url.searchParams.get("limit");
1172
+ const where = filter?.(url.searchParams);
1173
+ const to = url.searchParams.get("to");
1174
+ return json2(200, {
1175
+ messages: pick(runtime.instance(namespace)).list({
1176
+ ...to !== null ? { to } : {},
1177
+ ...since !== void 0 ? { since } : {},
1178
+ ...where ? { where } : {},
1179
+ ...limit !== null && /^\d+$/.test(limit) ? { limit: Number(limit) } : {}
1180
+ })
1181
+ });
1182
+ },
1183
+ "GET /outbox/:id": ({ params, namespace }) => {
1184
+ const item = pick(runtime.instance(namespace)).get(params.id);
1185
+ return item ? json2(200, item) : json2(404, { error: { type: "mockingbird_admin", message: `no message ${params.id}` } });
1186
+ }
1187
+ });
1188
+ var extractCodes = (text, length) => {
1189
+ const pattern = length === void 0 ? /\b\d{4,8}\b/g : new RegExp(`\\b\\d{${length}}\\b`, "g");
1190
+ return [...new Set(text.match(pattern) ?? [])];
1191
+ };
1192
+
1193
+ // ../../core/dist/timeline.js
1194
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1195
+ var Timeline = class {
1196
+ maxCheckpoints;
1197
+ now;
1198
+ makeId;
1199
+ nodes = /* @__PURE__ */ new Map();
1200
+ heads = /* @__PURE__ */ new Map();
1201
+ /** Unreferenced nodes in the exact order they became collectible. */
1202
+ evictable = /* @__PURE__ */ new Set();
1203
+ /** Branch heads plus explicit retainers. Absent means zero. */
1204
+ references = /* @__PURE__ */ new Map();
1205
+ explicitPins = /* @__PURE__ */ new Map();
1206
+ sequence = 0;
1207
+ constructor(options = {}) {
1208
+ const max = options.maxCheckpoints ?? 1e3;
1209
+ if (!Number.isSafeInteger(max) || max < 1)
1210
+ throw new RangeError("maxCheckpoints must be a positive integer");
1211
+ this.maxCheckpoints = max;
1212
+ this.now = options.now ?? (() => this.sequence);
1213
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1214
+ }
1215
+ /** Capture a new immutable value and move `branch` to it. */
1216
+ commit(value, options = {}) {
1217
+ const branch = options.branch ?? "main";
1218
+ this.assertBranch(branch);
1219
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1220
+ if (parent !== null && !this.nodes.has(parent))
1221
+ throw new RangeError(`no checkpoint ${parent}`);
1222
+ const id = this.makeId(++this.sequence);
1223
+ if (this.nodes.has(id))
1224
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1225
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1226
+ this.nodes.set(id, checkpoint);
1227
+ this.moveHead(branch, id);
1228
+ this.collect(this.maxCheckpoints);
1229
+ return checkpoint;
1230
+ }
1231
+ /** Create a branch pointer without copying its checkpoint value. */
1232
+ fork(branch, options = {}) {
1233
+ this.assertBranch(branch);
1234
+ if (this.heads.has(branch))
1235
+ throw new RangeError(`branch already exists: ${branch}`);
1236
+ const from = options.from ?? this.heads.get("main");
1237
+ if (from === void 0)
1238
+ return void 0;
1239
+ const checkpoint = this.get(from);
1240
+ this.moveHead(branch, checkpoint.id);
1241
+ return checkpoint;
1242
+ }
1243
+ /** Move a branch pointer to an existing checkpoint. */
1244
+ checkout(branch, id) {
1245
+ this.assertBranch(branch);
1246
+ const checkpoint = this.get(id);
1247
+ this.moveHead(branch, checkpoint.id);
1248
+ return checkpoint;
1249
+ }
1250
+ get(id) {
1251
+ const checkpoint = this.nodes.get(id);
1252
+ if (!checkpoint)
1253
+ throw new RangeError(`no checkpoint ${id}`);
1254
+ return checkpoint;
1255
+ }
1256
+ head(branch = "main") {
1257
+ const id = this.heads.get(branch);
1258
+ return id === void 0 ? void 0 : this.get(id);
1259
+ }
1260
+ hasBranch(branch) {
1261
+ return this.heads.has(branch);
1262
+ }
1263
+ branches() {
1264
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1265
+ }
1266
+ checkpoints() {
1267
+ return [...this.nodes.values()];
1268
+ }
1269
+ /** Number of retained checkpoints without allocating an array. */
1270
+ get size() {
1271
+ return this.nodes.size;
1272
+ }
1273
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1274
+ retain(id) {
1275
+ const checkpoint = this.get(id);
1276
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1277
+ this.addReference(id);
1278
+ return checkpoint;
1279
+ }
1280
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1281
+ release(id) {
1282
+ if (!this.nodes.has(id))
1283
+ return false;
1284
+ const pins = this.explicitPins.get(id) ?? 0;
1285
+ if (pins === 0)
1286
+ return false;
1287
+ if (pins === 1)
1288
+ this.explicitPins.delete(id);
1289
+ else
1290
+ this.explicitPins.set(id, pins - 1);
1291
+ this.removeReference(id);
1292
+ this.collect(this.maxCheckpoints);
1293
+ return true;
1294
+ }
1295
+ deleteBranch(branch) {
1296
+ if (branch === "main")
1297
+ throw new RangeError("cannot delete main branch");
1298
+ const previous = this.heads.get(branch);
1299
+ const deleted = this.heads.delete(branch);
1300
+ if (previous !== void 0)
1301
+ this.removeReference(previous);
1302
+ this.collect(this.maxCheckpoints);
1303
+ return deleted;
1304
+ }
1305
+ /**
1306
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1307
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1308
+ * storage dependency, so a retained node remains usable after pruning.
1309
+ */
1310
+ gc(max = this.maxCheckpoints) {
1311
+ if (!Number.isSafeInteger(max) || max < 1)
1312
+ throw new RangeError("max must be a positive integer");
1313
+ const removed = [];
1314
+ this.collect(max, removed);
1315
+ return removed;
1316
+ }
1317
+ collect(max, removed) {
1318
+ while (this.nodes.size > max && this.evictable.size > 0) {
1319
+ const id = this.evictable.values().next().value;
1320
+ this.evictable.delete(id);
1321
+ this.nodes.delete(id);
1322
+ removed?.push(id);
1323
+ }
1324
+ }
1325
+ moveHead(branch, id) {
1326
+ const previous = this.heads.get(branch);
1327
+ if (previous === id)
1328
+ return;
1329
+ if (previous !== void 0)
1330
+ this.removeReference(previous);
1331
+ this.heads.set(branch, id);
1332
+ this.addReference(id);
1333
+ }
1334
+ addReference(id) {
1335
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1336
+ this.evictable.delete(id);
1337
+ }
1338
+ removeReference(id) {
1339
+ const next = (this.references.get(id) ?? 0) - 1;
1340
+ if (next > 0)
1341
+ this.references.set(id, next);
1342
+ else {
1343
+ this.references.delete(id);
1344
+ if (this.nodes.has(id))
1345
+ this.evictable.add(id);
1346
+ }
1347
+ }
1348
+ assertBranch(branch) {
1349
+ if (!BRANCH_PATTERN.test(branch))
1350
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1351
+ }
1352
+ };
1353
+
1354
+ // ../../sqlite/dist/default.js
1355
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1356
+ var createDefaultSqlite = () => new Database();
1357
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1358
+
1359
+ // ../../sqlite/dist/migrate.js
1360
+ var ensureMigrationsTable = (sqlite) => {
1361
+ sqlite.exec(`
1362
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1363
+ id TEXT PRIMARY KEY NOT NULL,
1364
+ applied_at INTEGER NOT NULL
1365
+ )
1366
+ `);
1367
+ };
1368
+ var migrate = (sqlite, migrations) => {
1369
+ ensureMigrationsTable(sqlite);
1370
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1371
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1372
+ if (pending.length === 0)
1373
+ return;
1374
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1375
+ const now = Math.floor(Date.now() / 1e3);
1376
+ sqlite.transaction(() => {
1377
+ for (const migration of pending) {
1378
+ sqlite.exec(migration.sql);
1379
+ insert.run(migration.id, now);
1380
+ }
1381
+ });
1382
+ };
1383
+
1384
+ // ../../sqlite/dist/schema.js
1385
+ var CORE_MIGRATIONS = [
1386
+ {
1387
+ id: "20260322_core_records_sequences",
1388
+ sql: `
1389
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1390
+ namespace TEXT NOT NULL,
1391
+ collection TEXT NOT NULL,
1392
+ id TEXT NOT NULL,
1393
+ seq INTEGER NOT NULL,
1394
+ value TEXT NOT NULL,
1395
+ PRIMARY KEY (namespace, collection, id)
1396
+ );
1397
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1398
+ ON mockingbird_records (namespace, collection, seq);
1399
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1400
+ namespace TEXT NOT NULL,
1401
+ name TEXT NOT NULL,
1402
+ kind TEXT NOT NULL,
1403
+ value INTEGER NOT NULL,
1404
+ PRIMARY KEY (namespace, name, kind)
1405
+ );
1406
+ `
1407
+ }
1408
+ ];
1409
+ var migrateCore = (sqlite) => {
1410
+ migrate(sqlite, CORE_MIGRATIONS);
1411
+ };
1412
+ var clearNamespace = (sqlite, namespace) => {
1413
+ sqlite.transaction(() => {
1414
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1415
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1416
+ });
1417
+ };
1418
+
1419
+ // ../../openapi/metadata/dist/types.js
1420
+ var EXTENSION_KEYS = {
1421
+ operation: "x-mockingbird",
1422
+ resource: "x-mockingbird-resource",
1423
+ resourceRef: "x-mockingbird-resource-ref",
1424
+ volatile: "x-mockingbird-volatile",
1425
+ scope: "x-mockingbird-scope",
1426
+ unsupported: "x-mockingbird-unsupported",
1427
+ parityHeader: "x-mockingbird-parity-header"
1428
+ };
1429
+
1430
+ // ../../openapi/metadata/dist/read.js
1431
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1432
+ var extensionOf = (holder, key) => holder[key];
1433
+ var operationMetadata = (operation) => {
1434
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1435
+ const ext = isRecord2(raw) ? raw : {};
1436
+ const supported = ext.supported ?? true;
1437
+ const parity = ext.parity ?? {};
1438
+ return {
1439
+ supported,
1440
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1441
+ parity: {
1442
+ enabled: supported && (parity.enabled ?? true),
1443
+ safe: parity.safe ?? true,
1444
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1445
+ }
1446
+ };
1447
+ };
1448
+
1449
+ // ../core/dist/service.js
1450
+ import { Hono } from "hono";
1451
+ var defineOperations = (handlers) => handlers;
1452
+ var OperationRegistryError = class extends Error {
1453
+ problems;
1454
+ constructor(problems) {
1455
+ super(`operation registry is inconsistent:
1456
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1457
+ this.problems = problems;
1458
+ this.name = "OperationRegistryError";
1459
+ }
1460
+ };
1461
+ var verifyOperations = (document2, handlers) => {
1462
+ const problems = [];
1463
+ const operations = listOperations(document2);
1464
+ const seen = /* @__PURE__ */ new Set();
1465
+ for (const operation of operations) {
1466
+ if (seen.has(operation.operationId))
1467
+ problems.push(`duplicate operationId ${operation.operationId}`);
1468
+ seen.add(operation.operationId);
1469
+ const supported = operationMetadata(operation.operation).supported;
1470
+ const handler = handlers[operation.operationId];
1471
+ if (supported && !handler)
1472
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1473
+ if (!supported && handler)
1474
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1475
+ }
1476
+ for (const id of Object.keys(handlers)) {
1477
+ if (!seen.has(id))
1478
+ problems.push(`handler ${id} has no OpenAPI operation`);
1479
+ }
1480
+ return problems;
1481
+ };
1482
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1483
+ var routeOrder = (a, b) => {
1484
+ const sa = a.path.split("/");
1485
+ const sb = b.path.split("/");
1486
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1487
+ const x = sa[i] ?? "";
1488
+ const y = sb[i] ?? "";
1489
+ const px = x.startsWith("{");
1490
+ const py = y.startsWith("{");
1491
+ if (px !== py)
1492
+ return px ? 1 : -1;
1493
+ if (x !== y)
1494
+ return x < y ? -1 : 1;
1495
+ }
1496
+ return 0;
1497
+ };
1498
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1499
+ var bootSqlite = (sqlite) => {
1500
+ const client = resolveSqlite(sqlite);
1501
+ migrateCore(client);
1502
+ return client;
1503
+ };
1504
+ var createService = (options) => {
1505
+ const problems = verifyOperations(options.document, options.handlers);
1506
+ if (problems.length > 0)
1507
+ throw new OperationRegistryError(problems);
1508
+ migrateCore(options.sqlite);
1509
+ const now = options.now ?? (() => Date.now());
1510
+ const app = new Hono();
1511
+ app.notFound((c) => options.notFound(c.req.raw));
1512
+ app.onError((error, c) => options.onError(error, c.req.raw));
1513
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1514
+ for (const operation of operations) {
1515
+ const metadata = operationMetadata(operation.operation);
1516
+ const handler = options.handlers[operation.operationId];
1517
+ const route = async (c) => {
1518
+ const request = c.req.raw;
1519
+ if (!metadata.supported || !handler) {
1520
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1521
+ }
1522
+ const url = new URL(request.url);
1523
+ const context = {
1524
+ request,
1525
+ url,
1526
+ params: c.req.param(),
1527
+ query: queryOf(url),
1528
+ body: await readBody(request),
1529
+ sqlite: options.sqlite,
1530
+ namespace: options.namespace,
1531
+ operation,
1532
+ document: options.document,
1533
+ now
1534
+ };
1535
+ const short = await options.before?.(context);
1536
+ if (short)
1537
+ return short;
1538
+ return handler(context);
1539
+ };
1540
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1541
+ }
1542
+ return {
1543
+ app,
1544
+ sqlite: options.sqlite,
1545
+ namespace: options.namespace,
1546
+ fetch: async (request) => app.fetch(request),
1547
+ reset: async () => {
1548
+ clearNamespace(options.sqlite, options.namespace);
1549
+ }
1550
+ };
1551
+ };
1552
+
1553
+ // ../core/dist/snapshot.js
1554
+ var snapshotNamespace = (sqlite, namespace) => ({
1555
+ namespace,
1556
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1557
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1558
+ });
1559
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1560
+ sqlite.transaction(() => {
1561
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1562
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1563
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1564
+ for (const row of snapshot.records) {
1565
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1566
+ }
1567
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1568
+ for (const row of snapshot.sequences) {
1569
+ sequence.run(namespace, row.name, row.kind, row.value);
1570
+ }
1571
+ });
1572
+ };
1573
+
1574
+ // ../core/dist/version.js
1575
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1576
+
1577
+ // ../core/dist/signing.js
1578
+ var encoder = new TextEncoder();
1579
+ var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1580
+
1581
+ // ../core/dist/webhooks.js
1582
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1583
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
1584
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1585
+ var parseEndpoint = (value) => {
1586
+ if (!isRecord3(value) || typeof value.url !== "string")
1587
+ return "each endpoint needs a url";
1588
+ try {
1589
+ new URL(value.url);
1590
+ } catch {
1591
+ return `not a URL: ${value.url}`;
1592
+ }
1593
+ const endpoint = { url: value.url };
1594
+ if (typeof value.id === "string")
1595
+ endpoint.id = value.id;
1596
+ if (typeof value.secret === "string")
1597
+ endpoint.secret = value.secret;
1598
+ if (typeof value.signUrl === "string")
1599
+ endpoint.signUrl = value.signUrl;
1600
+ const events = value.events ?? value.enabledEvents;
1601
+ if (Array.isArray(events))
1602
+ endpoint.events = events.map(String);
1603
+ if (isRecord3(value.tags)) {
1604
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1605
+ }
1606
+ if (typeof value.account === "string")
1607
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1608
+ if (isRecord3(value.headers)) {
1609
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1610
+ }
1611
+ return endpoint;
1612
+ };
1613
+ var webhookAdminRoutes = (hub) => ({
1614
+ "GET /webhooks": ({ url, namespace }) => json3(200, {
1615
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1616
+ const type = url.searchParams.get("type");
1617
+ return type === null || d.type === type;
1618
+ })
1619
+ }),
1620
+ "GET /webhooks/events": ({ url, namespace }) => {
1621
+ const type = url.searchParams.get("type");
1622
+ return json3(200, {
1623
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1624
+ });
1625
+ },
1626
+ "POST /webhooks/:id/replay": async ({ params }) => {
1627
+ const replayed = await hub.replay(params.id);
1628
+ return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1629
+ },
1630
+ "POST /webhooks/flush": async () => {
1631
+ await hub.flush();
1632
+ return json3(200, { status: "ok" });
1633
+ },
1634
+ "POST /webhooks/faults": ({ body, namespace }) => {
1635
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1636
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1637
+ }
1638
+ const fault = { mode: body.mode };
1639
+ if (typeof body.count === "number")
1640
+ fault.count = body.count;
1641
+ hub.fault(namespace, fault);
1642
+ return json3(201, { namespace, ...fault });
1643
+ },
1644
+ "GET /webhook-endpoints": ({ namespace }) => json3(200, {
1645
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1646
+ ...rest,
1647
+ secret: secret ? "(set)" : null
1648
+ }))
1649
+ }),
1650
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1651
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1652
+ if (!Array.isArray(list))
1653
+ return adminError2(400, "expected [{url, secret?, events?}]");
1654
+ const parsed = [];
1655
+ for (const each of list) {
1656
+ const endpoint = parseEndpoint(each);
1657
+ if (typeof endpoint === "string")
1658
+ return adminError2(400, endpoint);
1659
+ parsed.push(endpoint);
1660
+ }
1661
+ const set = hub.setEndpoints(namespace, parsed);
1662
+ return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1663
+ },
1664
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1665
+ hub.setEndpoints(namespace, []);
1666
+ return json3(200, { status: "ok" });
1667
+ }
1668
+ });
1669
+ var parsePayload = (message) => {
1670
+ if (message.contentType.startsWith("application/json")) {
1671
+ try {
1672
+ return JSON.parse(message.body);
1673
+ } catch {
1674
+ return message.body;
1675
+ }
1676
+ }
1677
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1678
+ return Object.fromEntries(new URLSearchParams(message.body));
1679
+ }
1680
+ return message.body;
1681
+ };
1682
+
1683
+ // ../core/dist/runtime.js
1684
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1685
+ var BRANCH_HEADER = "x-mockingbird-branch";
1686
+ var AT_HEADER = "x-mockingbird-at";
1687
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1688
+ var DEFAULT_NAMESPACE = "default";
1689
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1690
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1691
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1692
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1693
+ var effects = /* @__PURE__ */ new WeakMap();
1694
+ var reuseSorted = (fresh, previous, compare, equal) => {
1695
+ if (!previous || previous.length === 0)
1696
+ return fresh.map((row) => Object.freeze(row));
1697
+ const result = new Array(fresh.length);
1698
+ let unchanged = fresh.length === previous.length;
1699
+ let oldIndex = 0;
1700
+ for (let index = 0; index < fresh.length; index++) {
1701
+ const row = fresh[index];
1702
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1703
+ oldIndex++;
1704
+ }
1705
+ const old = previous[oldIndex];
1706
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1707
+ if (result[index] !== previous[index])
1708
+ unchanged = false;
1709
+ }
1710
+ return unchanged ? previous : result;
1711
+ };
1712
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1713
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1714
+ var DroppedConnectionError = class extends TypeError {
1715
+ code = "MOCKINGBIRD_DROP";
1716
+ constructor() {
1717
+ super("fetch failed: connection dropped by Mockingbird fault");
1718
+ this.name = "TypeError";
1719
+ }
1720
+ };
1721
+ var operationMatcher = (document2) => {
1722
+ const matchers = listOperations(document2).map((operation) => ({
1723
+ operationId: operation.operationId,
1724
+ method: operation.method.toUpperCase(),
1725
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1726
+ params: (operation.path.match(/\{/g) ?? []).length
1727
+ })).sort((a, b) => a.params - b.params);
1728
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1729
+ };
1730
+ var createRuntime = (options) => {
1731
+ const sqlite = bootSqlite(options.sqlite);
1732
+ const clock = options.clock ?? createClock();
1733
+ const rng = createRng(options.seed ?? 0);
1734
+ const wallNow = options.io?.wallNow ?? Date.now;
1735
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1736
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1737
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1738
+ const metrics = createMetrics();
1739
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1740
+ const version = options.version ?? PACKAGE_VERSION;
1741
+ const instances = /* @__PURE__ */ new Map();
1742
+ const publicNamespaces = /* @__PURE__ */ new Set();
1743
+ const branchRngs = /* @__PURE__ */ new Map();
1744
+ const timelines = /* @__PURE__ */ new Map();
1745
+ const branchStorage = /* @__PURE__ */ new Map();
1746
+ const captured = /* @__PURE__ */ new Map();
1747
+ const credentials = createCredentialRegistry();
1748
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
1749
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
1750
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
1751
+ const existing = instances.get(key);
1752
+ if (existing)
1753
+ return existing;
1754
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
1755
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
1756
+ }
1757
+ const created = options.create({
1758
+ namespace: storageNamespace(key),
1759
+ publicNamespace,
1760
+ sqlite,
1761
+ clock,
1762
+ rng: isolatedRng ?? rng
1763
+ });
1764
+ instances.set(key, created);
1765
+ publicNamespaces.add(publicNamespace);
1766
+ if (isolatedRng)
1767
+ branchRngs.set(key, isolatedRng);
1768
+ return created;
1769
+ };
1770
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
1771
+ const capture = (storage) => {
1772
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
1773
+ const previous = captured.get(storage);
1774
+ const snapshot2 = {
1775
+ namespace: fresh.namespace,
1776
+ 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),
1777
+ 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)
1778
+ };
1779
+ Object.freeze(snapshot2.records);
1780
+ Object.freeze(snapshot2.sequences);
1781
+ Object.freeze(snapshot2);
1782
+ captured.set(storage, snapshot2);
1783
+ return Object.freeze({
1784
+ snapshot: snapshot2,
1785
+ clock: Object.freeze(clock.state()),
1786
+ rngState: (branchRngs.get(storage) ?? rng).state()
1787
+ });
1788
+ };
1789
+ const timeline = (name = DEFAULT_NAMESPACE) => {
1790
+ let found = timelines.get(name);
1791
+ if (found)
1792
+ return found;
1793
+ instance(name);
1794
+ found = new Timeline({
1795
+ now: clock.now,
1796
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
1797
+ });
1798
+ found.commit(capture(name));
1799
+ timelines.set(name, found);
1800
+ return found;
1801
+ };
1802
+ const physicalBranch = (namespace, branch2) => {
1803
+ if (branch2 === "main")
1804
+ return namespace;
1805
+ const mapKey = `${namespace}\0${branch2}`;
1806
+ const existing = branchStorage.get(mapKey);
1807
+ if (existing)
1808
+ return existing;
1809
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
1810
+ branchStorage.set(mapKey, key);
1811
+ return key;
1812
+ };
1813
+ const ensureBranch = (namespace, branch2, at) => {
1814
+ if (!BRANCH_PATTERN2.test(branch2))
1815
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1816
+ const history = timeline(namespace);
1817
+ if (branch2 === "main") {
1818
+ if (at !== void 0) {
1819
+ const point = history.checkout("main", at);
1820
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1821
+ captured.set(namespace, point.value.snapshot);
1822
+ rng.setState(point.value.rngState);
1823
+ clock.set(point.value.clock.now);
1824
+ if (point.value.clock.frozen)
1825
+ clock.freeze();
1826
+ else
1827
+ clock.unfreeze();
1828
+ }
1829
+ return namespace;
1830
+ }
1831
+ const storage = physicalBranch(namespace, branch2);
1832
+ if (!history.hasBranch(branch2)) {
1833
+ if (at === void 0)
1834
+ history.commit(capture(namespace));
1835
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
1836
+ const branchRng = createRng(options.seed ?? 0);
1837
+ if (point)
1838
+ branchRng.setState(point.value.rngState);
1839
+ instanceFor(storage, namespace, branchRng);
1840
+ if (point)
1841
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1842
+ if (point)
1843
+ captured.set(storage, point.value.snapshot);
1844
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1845
+ const point = history.checkout(branch2, at);
1846
+ if (!instances.has(storage)) {
1847
+ const branchRng = createRng(options.seed ?? 0);
1848
+ branchRng.setState(point.value.rngState);
1849
+ instanceFor(storage, namespace, branchRng);
1850
+ }
1851
+ branchRngs.get(storage)?.setState(point.value.rngState);
1852
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1853
+ captured.set(storage, point.value.snapshot);
1854
+ } else {
1855
+ if (!instances.has(storage)) {
1856
+ const point = history.head(branch2);
1857
+ const branchRng = createRng(options.seed ?? 0);
1858
+ if (point)
1859
+ branchRng.setState(point.value.rngState);
1860
+ instanceFor(storage, namespace, branchRng);
1861
+ }
1862
+ }
1863
+ return storage;
1864
+ };
1865
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
1866
+ const storage = ensureBranch(namespace, branch2);
1867
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
1868
+ };
1869
+ const branch = (name, branchOptions = {}) => {
1870
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
1871
+ ensureBranch(namespace, name, branchOptions.at);
1872
+ const head = timeline(namespace).head(name);
1873
+ if (!head)
1874
+ throw new RangeError(`branch ${name} has no checkpoint`);
1875
+ return head;
1876
+ };
1877
+ const checkout = (checkpointId, checkoutOptions = {}) => {
1878
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1879
+ const branchName = checkoutOptions.branch ?? "main";
1880
+ const history = timeline(namespace);
1881
+ const point = history.checkout(branchName, checkpointId);
1882
+ const storage = ensureBranch(namespace, branchName);
1883
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1884
+ captured.set(storage, point.value.snapshot);
1885
+ clock.set(point.value.clock.now);
1886
+ if (point.value.clock.frozen)
1887
+ clock.freeze();
1888
+ else
1889
+ clock.unfreeze();
1890
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
1891
+ };
1892
+ const reset = async (name = DEFAULT_NAMESPACE) => {
1893
+ if (name === "*") {
1894
+ options.webhooks?.clear();
1895
+ for (const each of instances.values())
1896
+ await each.reset();
1897
+ timelines.clear();
1898
+ branchStorage.clear();
1899
+ branchRngs.clear();
1900
+ captured.clear();
1901
+ return;
1902
+ }
1903
+ options.webhooks?.clear(name);
1904
+ const target = instances.get(name);
1905
+ if (target)
1906
+ await target.reset();
1907
+ else
1908
+ clearNamespace(sqlite, storageNamespace(name));
1909
+ for (const [mapping, storage] of branchStorage) {
1910
+ if (!mapping.startsWith(`${name}\0`))
1911
+ continue;
1912
+ const branchInstance = instances.get(storage);
1913
+ if (branchInstance)
1914
+ await branchInstance.reset();
1915
+ else
1916
+ clearNamespace(sqlite, storageNamespace(storage));
1917
+ branchStorage.delete(mapping);
1918
+ branchRngs.delete(storage);
1919
+ captured.delete(storage);
1920
+ }
1921
+ timelines.delete(name);
1922
+ captured.delete(name);
1923
+ };
1924
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
1925
+ return checkpoint(name, "main").value.snapshot;
1926
+ };
1927
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
1928
+ instance(name);
1929
+ restoreNamespace(sqlite, storageNamespace(name), from);
1930
+ captured.set(name, from);
1931
+ const history = timelines.get(name);
1932
+ if (history)
1933
+ history.commit(capture(name), { branch: "main" });
1934
+ else
1935
+ timeline(name);
1936
+ };
1937
+ const runtime = {
1938
+ name: options.name,
1939
+ sqlite,
1940
+ clock,
1941
+ faults,
1942
+ metrics,
1943
+ journal,
1944
+ rng,
1945
+ credentials,
1946
+ webhooks: options.webhooks,
1947
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
1948
+ const preset = options.presets?.[name];
1949
+ if (!preset)
1950
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
1951
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
1952
+ namespace,
1953
+ ...rule,
1954
+ ...overrides,
1955
+ preset: name,
1956
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
1957
+ }));
1958
+ if (preset.webhook && options.webhooks) {
1959
+ options.webhooks.fault(namespace, {
1960
+ ...preset.webhook,
1961
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
1962
+ });
1963
+ }
1964
+ return added;
1965
+ },
1966
+ instance,
1967
+ namespaces: () => [...publicNamespaces].sort(),
1968
+ reset,
1969
+ snapshot,
1970
+ restore,
1971
+ checkpoint,
1972
+ branch,
1973
+ checkout,
1974
+ timeline,
1975
+ fetch: async (incoming) => {
1976
+ let request = incoming;
1977
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
1978
+ if (prefixed) {
1979
+ const url2 = new URL(request.url);
1980
+ url2.pathname = prefixed[2] ?? "/";
1981
+ const headers = new Headers(request.headers);
1982
+ if (!headers.has(NAMESPACE_HEADER)) {
1983
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
1984
+ }
1985
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
1986
+ request = new Request(url2, {
1987
+ method: request.method,
1988
+ headers,
1989
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
1990
+ signal: request.signal
1991
+ });
1992
+ }
1993
+ let namespace = control.namespaceOf(request);
1994
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
1995
+ const credential = options.credential(request);
1996
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
1997
+ if (mapped !== void 0)
1998
+ namespace = mapped;
1999
+ }
2000
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
2001
+ const at = request.headers.get(AT_HEADER) ?? void 0;
2002
+ const stamp = (response2) => {
2003
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
2004
+ try {
2005
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
2006
+ return response2;
2007
+ } catch {
2008
+ const copy = new Response(response2.body, response2);
2009
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
2010
+ return copy;
2011
+ }
2012
+ };
2013
+ const handled = await control.handle(request);
2014
+ if (handled)
2015
+ return stamp(handled);
2016
+ const started = monotonicNow();
2017
+ const url = new URL(request.url);
2018
+ const operationId = operationIdFor(request, url.pathname);
2019
+ const log = (status, faultId, response2) => {
2020
+ const noted = response2 ? responseNotes(response2) : void 0;
2021
+ const entry = {
2022
+ service: options.name,
2023
+ namespace,
2024
+ operationId,
2025
+ method: request.method,
2026
+ path: url.pathname,
2027
+ status,
2028
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
2029
+ unmatched: options.document !== void 0 && operationId === void 0,
2030
+ ...faultId !== void 0 ? { faultId } : {},
2031
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
2032
+ ...noted?.adopted ? { adopted: true } : {}
2033
+ };
2034
+ metrics.record(entry);
2035
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
2036
+ options.onLog?.(entry);
2037
+ };
2038
+ if (!NAMESPACE_PATTERN.test(namespace)) {
2039
+ log(400);
2040
+ return stamp(new Response(JSON.stringify({
2041
+ error: {
2042
+ type: "mockingbird_admin",
2043
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
2044
+ }
2045
+ }), { status: 400, headers: { "content-type": "application/json" } }));
2046
+ }
2047
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
2048
+ log(400);
2049
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
2050
+ }
2051
+ let storage;
2052
+ try {
2053
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
2054
+ const point = timeline(namespace).get(at);
2055
+ storage = physicalBranch(namespace, `at_${at}`);
2056
+ let viewRng = branchRngs.get(storage);
2057
+ if (!viewRng) {
2058
+ viewRng = createRng(options.seed ?? 0);
2059
+ instanceFor(storage, namespace, viewRng);
2060
+ }
2061
+ viewRng.setState(point.value.rngState);
2062
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2063
+ captured.set(storage, point.value.snapshot);
2064
+ } else {
2065
+ storage = ensureBranch(namespace, selectedBranch, at);
2066
+ }
2067
+ } catch (error) {
2068
+ log(409);
2069
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
2070
+ }
2071
+ const hits = await faults.take({
2072
+ operationId,
2073
+ method: request.method,
2074
+ path: url.pathname,
2075
+ namespace
2076
+ });
2077
+ const final = hits.find((hit) => hit.drop || hit.response);
2078
+ if (final?.drop) {
2079
+ log(0, final.id);
2080
+ throw new DroppedConnectionError();
2081
+ }
2082
+ if (final?.response) {
2083
+ log(final.response.status, final.id);
2084
+ return stamp(final.response);
2085
+ }
2086
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2087
+ if (fired.length > 0)
2088
+ effects.set(request, fired.map((hit) => hit.effect));
2089
+ let response = await instanceFor(storage, namespace).fetch(request);
2090
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2091
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2092
+ response = mutableResponse(response);
2093
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2094
+ }
2095
+ if (selectedBranch !== "main") {
2096
+ response = mutableResponse(response);
2097
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2098
+ }
2099
+ if (at !== void 0) {
2100
+ response = mutableResponse(response);
2101
+ response.headers.set(AT_HEADER, at);
2102
+ }
2103
+ log(response.status, fired[0]?.id, response);
2104
+ return stamp(response);
2105
+ }
2106
+ };
2107
+ const control = createControlPlane({
2108
+ name: options.name,
2109
+ startedAt: wallNow(),
2110
+ wallNow,
2111
+ clock,
2112
+ faults,
2113
+ metrics,
2114
+ journal,
2115
+ defaultNamespace: DEFAULT_NAMESPACE,
2116
+ namespaces: runtime.namespaces,
2117
+ reset,
2118
+ timeTravel: {
2119
+ checkpoint: (name, branchName) => {
2120
+ const point = checkpoint(name, branchName);
2121
+ return {
2122
+ id: point.id,
2123
+ branch: point.branch,
2124
+ parent: point.parent,
2125
+ at: point.at,
2126
+ records: point.value.snapshot.records.length
2127
+ };
2128
+ },
2129
+ branch: (branchName, branchOptions) => {
2130
+ const point = branch(branchName, branchOptions);
2131
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2132
+ },
2133
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2134
+ retain: (name, checkpointId) => {
2135
+ timeline(name).retain(checkpointId);
2136
+ },
2137
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2138
+ inspect: (name) => {
2139
+ const history = timeline(name);
2140
+ return {
2141
+ branches: history.branches(),
2142
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2143
+ id,
2144
+ branch: branchName,
2145
+ parent,
2146
+ at
2147
+ }))
2148
+ };
2149
+ }
2150
+ },
2151
+ describe: options.describe ?? (() => ({})),
2152
+ ...options.presets ? {
2153
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2154
+ } : {},
2155
+ routes: {
2156
+ ...credentialRoutes(credentials),
2157
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2158
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2159
+ ...options.admin?.(runtime) ?? {}
2160
+ },
2161
+ adminKey: options.adminKey
2162
+ });
2163
+ return runtime;
2164
+ };
2165
+ var mutableResponse = (response) => {
2166
+ try {
2167
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2168
+ response.headers.delete("x-mockingbird-mutable-probe");
2169
+ return response;
2170
+ } catch {
2171
+ return new Response(response.body, response);
2172
+ }
2173
+ };
2174
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2175
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2176
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2177
+ var credentialRoutes = (registry) => ({
2178
+ "GET /credentials": () => adminJson(200, {
2179
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2180
+ credential: maskCredential(credential),
2181
+ namespace
2182
+ }))
2183
+ }),
2184
+ "PUT /credentials": ({ body, namespace }) => {
2185
+ const pairs = [];
2186
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2187
+ if (Array.isArray(list)) {
2188
+ for (const each of list) {
2189
+ if (typeof each === "string")
2190
+ pairs.push([each, namespace]);
2191
+ else if (isObject(each) && typeof each.credential === "string") {
2192
+ pairs.push([
2193
+ each.credential,
2194
+ typeof each.namespace === "string" ? each.namespace : namespace
2195
+ ]);
2196
+ } else
2197
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2198
+ }
2199
+ } else if (isObject(list)) {
2200
+ for (const [credential, target] of Object.entries(list)) {
2201
+ if (typeof target !== "string")
2202
+ return adminFail(400, `namespace for ${credential} must be a string`);
2203
+ pairs.push([credential, target]);
2204
+ }
2205
+ } else if (isObject(body) && typeof body.credential === "string") {
2206
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2207
+ } else {
2208
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2209
+ }
2210
+ for (const [credential, target] of pairs) {
2211
+ if (!NAMESPACE_PATTERN.test(target))
2212
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2213
+ registry.set(credential, target);
2214
+ }
2215
+ return adminJson(200, { mapped: pairs.length });
2216
+ },
2217
+ "DELETE /credentials": ({ url }) => {
2218
+ const credential = url.searchParams.get("credential");
2219
+ if (credential === null)
2220
+ registry.clear();
2221
+ else
2222
+ registry.remove(credential);
2223
+ return adminJson(200, { status: "ok" });
2224
+ }
2225
+ });
2226
+ var presetRoutes = (presets, runtime) => ({
2227
+ "GET /faults/presets": () => adminJson(200, {
2228
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2229
+ }),
2230
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2231
+ const name = params.name;
2232
+ if (!presets[name])
2233
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2234
+ const overrides = isObject(body) ? body : {};
2235
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2236
+ }
2237
+ });
2238
+
2239
+ // ../core/dist/validation.js
2240
+ var bodyIssues = (context, contentType = "application/json") => {
2241
+ const requestBody = context.operation.operation.requestBody;
2242
+ if (!requestBody)
2243
+ return [];
2244
+ const resolved = deref(context.document, requestBody);
2245
+ const schema = resolved.content?.[contentType]?.schema;
2246
+ if (!schema)
2247
+ return [];
2248
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2249
+ if (context.body.kind === "invalid") {
2250
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2251
+ }
2252
+ if (value === void 0) {
2253
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2254
+ }
2255
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2256
+ };
2257
+
2258
+ // src/content.ts
2259
+ var ENTITIES = {
2260
+ amp: "&",
2261
+ lt: "<",
2262
+ gt: ">",
2263
+ quot: '"',
2264
+ apos: "'",
2265
+ nbsp: " ",
2266
+ copy: "\xA9"
2267
+ };
2268
+ var decodeEntities = (value) => value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, entity) => {
2269
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
2270
+ return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
2271
+ }
2272
+ if (entity.startsWith("#")) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
2273
+ return ENTITIES[entity.toLowerCase()] ?? whole;
2274
+ });
2275
+ var visibleText = (html) => decodeEntities(
2276
+ html.replace(/<!--[\s\S]*?-->/g, " ").replace(/<(head|style|script|title)\b[\s\S]*?<\/\1\s*>/gi, " ").replace(/<[^>]*>/g, " ")
2277
+ ).replace(/\s+/g, " ").trim();
2278
+ var URL_PATTERN = /\bhttps?:\/\/[^\s<>"')\]]+/gi;
2279
+ var findCodes = (readable) => extractCodes(readable.replace(URL_PATTERN, " ")).map((value) => ({ value }));
2280
+ var htmlLinks = (html) => {
2281
+ const links = [];
2282
+ for (const match of html.matchAll(/<a\b([^>]*)>([\s\S]*?)<\/a\s*>/gi)) {
2283
+ const attributes = match[1] ?? "";
2284
+ const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attributes);
2285
+ const raw = href?.[1] ?? href?.[2] ?? href?.[3];
2286
+ if (raw === void 0 || raw.trim() === "") continue;
2287
+ links.push({ href: decodeEntities(raw.trim()), text: visibleText(match[2] ?? "") });
2288
+ }
2289
+ return links;
2290
+ };
2291
+ var htmlImages = (html) => {
2292
+ const images = [];
2293
+ for (const match of html.matchAll(/<img\b([^>]*)>/gi)) {
2294
+ const attributes = match[1] ?? "";
2295
+ const src = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attributes);
2296
+ const alt = /\balt\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attributes);
2297
+ const value = src?.[1] ?? src?.[2];
2298
+ if (value)
2299
+ images.push({ src: decodeEntities(value), alt: decodeEntities(alt?.[1] ?? alt?.[2] ?? "") });
2300
+ }
2301
+ return images;
2302
+ };
2303
+ var textLinks = (text) => [...text.matchAll(URL_PATTERN)].map((match) => ({ href: match[0], text: match[0] }));
2304
+ var htmlContent = (html) => {
2305
+ if (html === null || html === void 0 || html === "") {
2306
+ return { body: null, links: [], codes: [], images: [] };
2307
+ }
2308
+ return {
2309
+ body: html,
2310
+ links: htmlLinks(html),
2311
+ codes: findCodes(visibleText(html)),
2312
+ images: htmlImages(html)
2313
+ };
2314
+ };
2315
+ var textContent = (text) => {
2316
+ if (text === null || text === void 0 || text === "")
2317
+ return { body: null, links: [], codes: [] };
2318
+ return { body: text, links: textLinks(text), codes: findCodes(text) };
2319
+ };
2320
+ var PHONE = /^\+?[0-9][0-9\s().-]{5,}$/;
2321
+ var parseAddress = (value) => {
2322
+ if (typeof value === "object" && value !== null) {
2323
+ const record = value;
2324
+ const email = typeof record.email === "string" ? record.email.trim() : void 0;
2325
+ const phone = typeof record.phone === "string" ? record.phone.trim() : void 0;
2326
+ if (!email && !phone) return void 0;
2327
+ return {
2328
+ name: typeof record.name === "string" ? record.name : "",
2329
+ ...email ? { email } : {},
2330
+ ...phone ? { phone } : {}
2331
+ };
2332
+ }
2333
+ if (typeof value !== "string" || value.trim() === "") return void 0;
2334
+ const trimmed = value.trim();
2335
+ const angle = /^(.*?)\s*<([^<>]+)>\s*$/.exec(trimmed);
2336
+ if (angle) {
2337
+ return {
2338
+ name: (angle[1] ?? "").replace(/^"(.*)"$/, "$1").trim(),
2339
+ email: (angle[2] ?? "").trim()
2340
+ };
2341
+ }
2342
+ if (!trimmed.includes("@") && PHONE.test(trimmed)) return { name: "", phone: trimmed };
2343
+ return { name: "", email: trimmed };
2344
+ };
2345
+ var parseAddresses = (value) => {
2346
+ const list = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : value === void 0 || value === null ? [] : [value];
2347
+ return list.map(parseAddress).filter((a) => a !== void 0);
2348
+ };
2349
+ var addressKey = (address) => (address.email ?? address.phone ?? "").toLowerCase();
2350
+
2351
+ // src/generated/openapi.ts
2352
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Mailosaur API (Mockingbird subset)","description":"Stateful mock subset of the Mailosaur email/SMS testing API: message search (the SDK's\\nclient-side long-poll behind \`messages.get\`), list, get by id, delete, delete-all, create,\\nand the server-side \`await\` long-poll. Hand-authored from the \`mailosaur@11.1.0\` Node SDK\\n(the exact requests it sends and the fields its models read) and our consumer's\\n\`mailosaur-client.ts\`.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from mailosaur@11.1.0 (esm/operations/messages.js, esm/models/*.js) and apps/backend/src/modules/dev-tools/lib/mailosaur-client.ts."}},"servers":[{"url":"https://mailosaur.com"}],"security":[{"basicAuth":[]}],"paths":{"/api/messages/search":{"post":{"operationId":"SearchMessages","description":"Message summaries matching the criteria, newest first. Answers at once; when nothing matches, \`x-ms-delay\` tells the SDK how long to wait before polling again (the mock's default is 20 ms, so \`messages.get\` returns within ~20 ms of a message arriving).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Server"},{"$ref":"#/components/parameters/Page"},{"$ref":"#/components/parameters/ItemsPerPage"},{"$ref":"#/components/parameters/ReceivedAfter"},{"$ref":"#/components/parameters/Dir"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchCriteria"}}}},"responses":{"200":{"description":"Matching summaries (possibly none)","headers":{"x-ms-delay":{"description":"Comma-separated poll delays in ms the SDK uses while nothing matches.","schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageListResult"}}}},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/messages/await":{"post":{"operationId":"AwaitMessage","description":"Server-side long-poll: hold the request until a message matching the criteria arrives (answering with the full message within milliseconds of its arrival) or \`timeout\` ms pass (404 \`search_timeout\`).","x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Holds the request open for up to \`timeout\` ms; exercised by the acceptance tests."}},"parameters":[{"$ref":"#/components/parameters/Server"},{"$ref":"#/components/parameters/ReceivedAfter"},{"$ref":"#/components/parameters/Timeout"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchCriteria"}}}},"responses":{"200":{"description":"The first matching message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Nothing matched in time","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"get":{"operationId":"AwaitMessageByQuery","description":"The same long-poll with the criteria as query parameters.","x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Holds the request open for up to \`timeout\` ms; exercised by the acceptance tests."}},"parameters":[{"$ref":"#/components/parameters/Server"},{"$ref":"#/components/parameters/ReceivedAfter"},{"$ref":"#/components/parameters/Timeout"},{"name":"sentTo","in":"query","schema":{"type":"string"}},{"name":"sentFrom","in":"query","schema":{"type":"string"}},{"name":"subject","in":"query","schema":{"type":"string"}},{"name":"body","in":"query","schema":{"type":"string"}},{"name":"match","in":"query","schema":{"type":"string","enum":["ALL","ANY"]}}],"responses":{"200":{"description":"The first matching message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Nothing matched in time","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/messages":{"get":{"operationId":"ListMessages","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Server"},{"$ref":"#/components/parameters/Page"},{"$ref":"#/components/parameters/ItemsPerPage"},{"$ref":"#/components/parameters/ReceivedAfter"},{"$ref":"#/components/parameters/Dir"}],"responses":{"200":{"description":"Summaries, newest first","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageListResult"}}}},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"post":{"operationId":"CreateMessage","description":"\`messages.create\`: a new message in the server's inbox (the vendor would also send it to a verified address when \`send\` is true; the mock only stores it).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Server"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageCreateOptions"}}}},"responses":{"200":{"description":"The created message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"delete":{"operationId":"DeleteAllMessages","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Server"}],"responses":{"204":{"description":"Every message in the server deleted"},"400":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/messages/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"message","missing":"00000000-0000-4000-8000-000000000000"}}}],"get":{"operationId":"GetMessage","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The full message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"No such message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"delete":{"operationId":"DeleteMessage","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"204":{"description":"Deleted"},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"No such message","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"basicAuth":{"type":"http","scheme":"basic","description":"\`Authorization: Basic base64(<api key>:)\` (the SDK sends the key as the username)."}},"parameters":{"Server":{"name":"server","in":"query","required":true,"description":"The 8-character server (inbox) id.","schema":{"type":"string","pattern":"^[a-z0-9]{8}$"}},"Page":{"name":"page","in":"query","schema":{"type":"integer","minimum":0,"maximum":100}},"ItemsPerPage":{"name":"itemsPerPage","in":"query","schema":{"type":"integer","minimum":1,"maximum":1000}},"ReceivedAfter":{"name":"receivedAfter","in":"query","description":"ISO-8601; only messages received at or after it.","schema":{"type":"string","format":"date-time"}},"Dir":{"name":"dir","in":"query","schema":{"type":"string","enum":["Ascending","Descending"]}},"Timeout":{"name":"timeout","in":"query","description":"How long to hold the request, in ms (default 10000, at most 300000).","schema":{"type":"integer","minimum":0,"maximum":300000}}},"schemas":{"SearchCriteria":{"type":"object","properties":{"sentFrom":{"type":"string","maxLength":200},"sentTo":{"type":"string","maxLength":200},"subject":{"type":"string","maxLength":200},"body":{"type":"string","maxLength":200},"match":{"type":"string","enum":["ALL","ANY"]}}},"MessageCreateOptions":{"type":"object","required":["to","subject"],"properties":{"to":{"type":"string","format":"email","maxLength":120},"cc":{"type":"string","format":"email","maxLength":120},"from":{"type":"string","format":"email","maxLength":120},"send":{"type":"boolean"},"subject":{"type":"string","minLength":1,"maxLength":200},"text":{"type":"string","maxLength":2000},"html":{"type":"string","maxLength":2000}}},"MessageAddress":{"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}},"Link":{"type":"object","required":["href"],"properties":{"href":{"type":"string"},"text":{"type":"string"}}},"Code":{"type":"object","required":["value"],"properties":{"value":{"type":"string"}}},"MessageContent":{"type":"object","required":["links","codes"],"properties":{"body":{"type":["string","null"]},"links":{"type":"array","items":{"$ref":"#/components/schemas/Link"}},"codes":{"type":"array","items":{"$ref":"#/components/schemas/Code"}},"images":{"type":"array","items":{"type":"object","properties":{"src":{"type":"string"},"alt":{"type":"string"}}}}}},"Attachment":{"type":"object","required":["id","fileName","contentType","length"],"properties":{"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"contentType":{"type":"string"},"fileName":{"type":"string"},"contentId":{"type":["string","null"]},"length":{"type":"integer"},"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"Message":{"type":"object","required":["id","type","from","to","cc","bcc","received","subject","html","text","attachments","metadata","server"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"message","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string","enum":["Email","SMS"]},"from":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"to":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"cc":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"bcc":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"received":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"subject":{"type":"string"},"html":{"$ref":"#/components/schemas/MessageContent"},"text":{"$ref":"#/components/schemas/MessageContent"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/Attachment"}},"metadata":{"type":"object","properties":{"headers":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"value":{"type":"string"}}}},"ehlo":{"type":["string","null"]},"mailFrom":{"type":["string","null"]},"rcptTo":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}}}},"server":{"type":"string"}}},"MessageSummary":{"type":"object","required":["id","type","server","from","to","received","subject","summary","attachments"],"properties":{"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string","enum":["Email","SMS"]},"server":{"type":"string"},"from":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"to":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"cc":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"bcc":{"type":"array","items":{"$ref":"#/components/schemas/MessageAddress"}},"received":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"subject":{"type":"string"},"summary":{"type":"string"},"attachments":{"type":"integer"}}},"MessageListResult":{"type":"object","required":["items"],"properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/MessageSummary"}}}},"ErrorBody":{"type":"object","required":["type","message"],"properties":{"type":{"type":"string"},"message":{"type":"string"}}},"ValidationError":{"type":"object","required":["type","errors"],"properties":{"type":{"type":"string"},"errors":{"type":"array","items":{"type":"object","required":["field","detail"],"properties":{"field":{"type":"string"},"detail":{"type":"array","items":{"type":"object","required":["description"],"properties":{"description":{"type":"string"}}}}}}}}}}}}`);
2353
+ var operationIds = ["SearchMessages", "AwaitMessageByQuery", "AwaitMessage", "ListMessages", "CreateMessage", "DeleteAllMessages", "GetMessage", "DeleteMessage"];
2354
+ var supportedOperationIds = ["SearchMessages", "AwaitMessageByQuery", "AwaitMessage", "ListMessages", "CreateMessage", "DeleteAllMessages", "GetMessage", "DeleteMessage"];
2355
+
2356
+ // src/state.ts
2357
+ var DEFAULT_SETTINGS = { pollDelaysMs: [20] };
2358
+ var MailosaurState = class {
2359
+ constructor(sqlite, namespace, seed) {
2360
+ this.seed = seed;
2361
+ this.messages = new Collection(sqlite, namespace, "messages");
2362
+ this.outbox = new OutboxStore(sqlite, namespace, "messages");
2363
+ this.settings = new Collection(sqlite, namespace, "settings");
2364
+ this.ids = new IdSequence(sqlite, namespace, "mailosaur");
2365
+ }
2366
+ seed;
2367
+ messages;
2368
+ outbox;
2369
+ settings;
2370
+ ids;
2371
+ current() {
2372
+ return this.settings.get("settings") ?? { ...DEFAULT_SETTINGS, ...this.seed };
2373
+ }
2374
+ update(patch) {
2375
+ const next = { ...this.current(), ...patch };
2376
+ if (this.settings.has("settings")) this.settings.update("settings", next);
2377
+ else this.settings.insert("settings", next);
2378
+ return next;
2379
+ }
2380
+ /** A GUID-shaped id, deterministic for a given history (Mailosaur ids are GUIDs). */
2381
+ nextId(prefix = "msg") {
2382
+ const token = this.ids.next(`${prefix}_`, 32).slice(prefix.length + 1);
2383
+ const hex = [...token].map((c) => (c.charCodeAt(0) % 16).toString(16)).join("");
2384
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
2385
+ }
2386
+ };
2387
+
2388
+ // src/runtime.ts
2389
+ var MAILOSAUR_PRESETS = {
2390
+ auth_failed: {
2391
+ description: "Every API call answers 401 (the SDK raises authentication_error)",
2392
+ rules: [
2393
+ {
2394
+ pathPrefix: "/api/",
2395
+ status: 401,
2396
+ body: {
2397
+ type: "authentication_error",
2398
+ message: "Authentication failed, check your API key."
2399
+ }
2400
+ }
2401
+ ]
2402
+ },
2403
+ rate_limited: {
2404
+ description: "Searches answer 429 (the SDK raises api_error)",
2405
+ rules: [
2406
+ {
2407
+ operationId: "SearchMessages",
2408
+ status: 429,
2409
+ body: { type: "rate_limit_exceeded", message: "Too many requests." }
2410
+ }
2411
+ ]
2412
+ },
2413
+ server_error: {
2414
+ description: "Every API call answers 500",
2415
+ rules: [
2416
+ {
2417
+ pathPrefix: "/api/",
2418
+ status: 500,
2419
+ body: { type: "api_error", message: "An unexpected error occurred." }
2420
+ }
2421
+ ]
2422
+ },
2423
+ search_never_matches: {
2424
+ description: "Searches find nothing even when mail has arrived, so `messages.get` times out (search_timeout)",
2425
+ rules: [{ operationId: "SearchMessages", effect: "search_never_matches" }]
2426
+ },
2427
+ slow_search: {
2428
+ description: "Searches take 2 s to answer",
2429
+ rules: [{ operationId: "SearchMessages", latencyMs: 2e3 }]
2430
+ }
2431
+ };
2432
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2433
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2434
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2435
+ var nullableText = (value) => typeof value === "string" ? value : null;
2436
+ var ingestInput = (body) => {
2437
+ if (body.to === void 0)
2438
+ return 'expected {"to": "<address>" | [...], "from"?, "subject"?, "html"?, "text"?}';
2439
+ if (body.server !== void 0 && (typeof body.server !== "string" || body.server === "")) {
2440
+ return "server: an 8-character server id";
2441
+ }
2442
+ if (body.type !== void 0 && body.type !== "Email" && body.type !== "SMS") {
2443
+ return 'type: "Email" or "SMS"';
2444
+ }
2445
+ if (body.attachments !== void 0 && !Array.isArray(body.attachments)) {
2446
+ return "attachments: [{filename, content (base64), contentType}]";
2447
+ }
2448
+ return {
2449
+ ...typeof body.server === "string" ? { server: body.server } : {},
2450
+ ...body.type === "SMS" || body.type === "Email" ? { type: body.type } : {},
2451
+ from: body.from,
2452
+ to: body.to,
2453
+ cc: body.cc,
2454
+ bcc: body.bcc,
2455
+ subject: typeof body.subject === "string" ? body.subject : null,
2456
+ html: nullableText(body.html),
2457
+ text: nullableText(body.text),
2458
+ headers: body.headers,
2459
+ ...Array.isArray(body.attachments) ? {
2460
+ attachments: body.attachments.filter(isRecord4)
2461
+ } : {}
2462
+ };
2463
+ };
2464
+ var adminRoutes = (runtime) => ({
2465
+ "POST /ingest": ({ body, namespace }) => {
2466
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2467
+ const input = ingestInput(body);
2468
+ if (typeof input === "string") return adminError3(400, input);
2469
+ try {
2470
+ return json4(201, runtime.instance(namespace).ingest(input));
2471
+ } catch (error) {
2472
+ return adminError3(400, error instanceof Error ? error.message : String(error));
2473
+ }
2474
+ },
2475
+ ...outboxAdminRoutes(
2476
+ runtime,
2477
+ (api) => api.state.outbox,
2478
+ (params) => {
2479
+ const server = params.get("server");
2480
+ return server === null ? void 0 : (item) => item.server === server || item.server === "*";
2481
+ }
2482
+ ),
2483
+ "GET /outbox/:id/links": ({ params, namespace }) => {
2484
+ const record = runtime.instance(namespace).state.outbox.get(params.id);
2485
+ if (!record) return adminError3(404, `no message ${params.id}`);
2486
+ const { html, text } = record.message;
2487
+ return json4(200, {
2488
+ id: record.id,
2489
+ links: (html.links.length > 0 ? html.links : text.links).map((link) => link.href),
2490
+ codes: [...html.codes, ...text.codes].map((code) => code.value)
2491
+ });
2492
+ },
2493
+ "GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
2494
+ "PUT /settings": ({ body, namespace }) => {
2495
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2496
+ const patch = {};
2497
+ if (body.pollDelaysMs !== void 0) {
2498
+ const delays = body.pollDelaysMs;
2499
+ if (!Array.isArray(delays) || delays.length === 0 || delays.some((d) => typeof d !== "number" || !Number.isInteger(d) || d < 0)) {
2500
+ return adminError3(400, "pollDelaysMs: a non-empty list of whole milliseconds");
2501
+ }
2502
+ patch.pollDelaysMs = delays;
2503
+ }
2504
+ return json4(200, runtime.instance(namespace).state.update(patch));
2505
+ }
2506
+ });
2507
+ var createRuntime2 = (options = {}) => createRuntime({
2508
+ name: MAILOSAUR_NAMESPACE,
2509
+ document,
2510
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2511
+ ...options.clock ? { clock: options.clock } : {},
2512
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2513
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2514
+ ...options.onLog ? { onLog: options.onLog } : {},
2515
+ credential: (request) => basicAuth(request)?.username || void 0,
2516
+ presets: MAILOSAUR_PRESETS,
2517
+ create: ({ sqlite, namespace, clock }) => new MailosaurAPI({
2518
+ sqlite,
2519
+ namespace,
2520
+ now: clock.now,
2521
+ ...options.settings ? { settings: options.settings } : {}
2522
+ }),
2523
+ admin: adminRoutes
2524
+ });
2525
+
2526
+ // src/index.ts
2527
+ var MAILOSAUR_NAMESPACE = "mailosaur";
2528
+ var ANY_SERVER = "*";
2529
+ var DEFAULT_AWAIT_TIMEOUT_MS = 1e4;
2530
+ var MAX_AWAIT_TIMEOUT_MS = 3e5;
2531
+ var SERVER_DOMAIN = /^([a-z0-9]{8})\.mailosaur\.(?:net|io)$/i;
2532
+ var errorBody = (type, message) => ({ type, message });
2533
+ var invalid = (field, description) => jsonRes(400, { type: "ValidationError", errors: [{ field, detail: [{ description }] }] });
2534
+ var lower = (value) => value?.trim().toLowerCase() ?? "";
2535
+ var matchesCriteria = (message, criteria) => {
2536
+ const checks = [];
2537
+ if (criteria.sentTo) {
2538
+ const want = lower(criteria.sentTo);
2539
+ checks.push(
2540
+ [...message.to, ...message.cc, ...message.bcc].some(
2541
+ (address) => addressKey(address) === want
2542
+ )
2543
+ );
2544
+ }
2545
+ if (criteria.sentFrom) {
2546
+ const want = lower(criteria.sentFrom);
2547
+ checks.push(message.from.some((address) => addressKey(address) === want));
2548
+ }
2549
+ if (criteria.subject) checks.push(lower(message.subject).includes(lower(criteria.subject)));
2550
+ if (criteria.body) {
2551
+ const want = lower(criteria.body);
2552
+ checks.push(
2553
+ lower(message.text.body ?? "").includes(want) || lower(visibleText(message.html.body ?? "")).includes(want)
2554
+ );
2555
+ }
2556
+ if (checks.length === 0) return true;
2557
+ return criteria.match === "ANY" ? checks.some(Boolean) : checks.every(Boolean);
2558
+ };
2559
+ var summaryOf = (message) => {
2560
+ const text = message.text.body ?? visibleText(message.html.body ?? "");
2561
+ return {
2562
+ id: message.id,
2563
+ type: message.type,
2564
+ server: message.server,
2565
+ from: message.from,
2566
+ to: message.to,
2567
+ cc: message.cc,
2568
+ bcc: message.bcc,
2569
+ received: message.received,
2570
+ subject: message.subject,
2571
+ summary: text.replace(/\s+/g, " ").trim().slice(0, 100),
2572
+ attachments: message.attachments.length
2573
+ };
2574
+ };
2575
+ var headerList = (value) => {
2576
+ if (Array.isArray(value)) {
2577
+ return value.flatMap((entry) => {
2578
+ if (typeof entry !== "object" || entry === null) return [];
2579
+ const record = entry;
2580
+ const field = record.field ?? record.name;
2581
+ return typeof field === "string" ? [{ field, value: String(record.value ?? "") }] : [];
2582
+ });
2583
+ }
2584
+ if (typeof value === "object" && value !== null) {
2585
+ return Object.entries(value).map(([field, v]) => ({
2586
+ field,
2587
+ value: String(v)
2588
+ }));
2589
+ }
2590
+ return [];
2591
+ };
2592
+ var criteriaFrom = (value) => {
2593
+ if (typeof value !== "object" || value === null) return {};
2594
+ const record = value;
2595
+ const text = (key) => typeof record[key] === "string" && record[key].length > 0 ? { [key]: record[key] } : {};
2596
+ return {
2597
+ ...text("sentFrom"),
2598
+ ...text("sentTo"),
2599
+ ...text("subject"),
2600
+ ...text("body"),
2601
+ ...record.match === "ANY" || record.match === "ALL" ? { match: record.match } : {}
2602
+ };
2603
+ };
2604
+ var MailosaurAPI = class {
2605
+ app;
2606
+ sqlite;
2607
+ state;
2608
+ service;
2609
+ now;
2610
+ waiters = /* @__PURE__ */ new Set();
2611
+ constructor(options = {}) {
2612
+ const sqlite = bootSqlite(options.sqlite);
2613
+ const namespace = options.namespace ?? MAILOSAUR_NAMESPACE;
2614
+ this.now = options.now ?? (() => Date.now());
2615
+ this.state = new MailosaurState(sqlite, namespace, options.settings ?? {});
2616
+ const handlers = defineOperations({
2617
+ SearchMessages: (context) => this.search(context),
2618
+ AwaitMessage: (context) => this.await(context, criteriaFrom(this.jsonBody(context))),
2619
+ AwaitMessageByQuery: (context) => this.await(context, criteriaFrom(context.query)),
2620
+ ListMessages: (context) => this.list(context),
2621
+ CreateMessage: (context) => this.create(context),
2622
+ DeleteAllMessages: (context) => this.deleteAll(context),
2623
+ GetMessage: (context) => this.get(context),
2624
+ DeleteMessage: (context) => this.remove(context)
2625
+ });
2626
+ this.service = createService({
2627
+ document,
2628
+ handlers,
2629
+ sqlite,
2630
+ namespace,
2631
+ now: this.now,
2632
+ notFound: () => jsonRes(404, errorBody("invalid_request", "Not found")),
2633
+ onError: (error) => {
2634
+ if (error instanceof HttpError) return error.toResponse();
2635
+ throw error;
2636
+ },
2637
+ before: (context) => {
2638
+ const key = basicAuth(context.request)?.username;
2639
+ if (!key) {
2640
+ return jsonRes(
2641
+ 401,
2642
+ errorBody("authentication_error", "Authentication failed, check your API key.")
2643
+ );
2644
+ }
2645
+ return void 0;
2646
+ }
2647
+ });
2648
+ this.app = this.service.app;
2649
+ this.sqlite = this.service.sqlite;
2650
+ }
2651
+ fetch(request) {
2652
+ return this.service.fetch(request);
2653
+ }
2654
+ async reset() {
2655
+ await this.service.reset();
2656
+ for (const waiter of this.waiters) waiter.resolve(void 0);
2657
+ this.waiters.clear();
2658
+ }
2659
+ /** Store a message and wake every long-poll it satisfies. */
2660
+ ingest(input) {
2661
+ const type = input.type === "SMS" ? "SMS" : "Email";
2662
+ const to = parseAddresses(input.to);
2663
+ const cc = parseAddresses(input.cc);
2664
+ const bcc = parseAddresses(input.bcc);
2665
+ if (to.length + cc.length + bcc.length === 0) throw new RangeError("to: at least one recipient");
2666
+ const from = parseAddresses(input.from);
2667
+ const derived = [...to, ...cc, ...bcc].map((a) => SERVER_DOMAIN.exec(a.email?.split("@")[1] ?? "")?.[1]?.toLowerCase()).find((s) => s !== void 0);
2668
+ const server = input.server ?? derived ?? ANY_SERVER;
2669
+ const id = this.state.nextId();
2670
+ const receivedMs = this.now();
2671
+ const attachments = (input.attachments ?? []).map((attachment, index) => {
2672
+ const bytes = attachment.content ? fromBase64(attachment.content) : new Uint8Array();
2673
+ const attachmentId = `${id.slice(0, 24)}${String(index).padStart(12, "0")}`;
2674
+ return {
2675
+ id: attachmentId,
2676
+ contentType: attachment.contentType ?? attachment.content_type ?? "application/octet-stream",
2677
+ fileName: attachment.filename ?? attachment.fileName ?? `attachment-${index + 1}`,
2678
+ contentId: attachment.contentId ?? null,
2679
+ length: bytes.length,
2680
+ url: `https://mailosaur.com/api/files/attachments/${attachmentId}`
2681
+ };
2682
+ });
2683
+ const message = {
2684
+ id,
2685
+ type,
2686
+ from,
2687
+ to,
2688
+ cc,
2689
+ bcc,
2690
+ received: new Date(receivedMs).toISOString(),
2691
+ subject: input.subject ?? "",
2692
+ html: htmlContent(input.html),
2693
+ text: textContent(input.text),
2694
+ attachments,
2695
+ metadata: {
2696
+ headers: headerList(input.headers),
2697
+ ehlo: null,
2698
+ mailFrom: from[0]?.email ?? null,
2699
+ rcptTo: [...to, ...cc, ...bcc]
2700
+ },
2701
+ server
2702
+ };
2703
+ const record = {
2704
+ id,
2705
+ to: [...to, ...cc, ...bcc].map(addressKey),
2706
+ createdAt: message.received,
2707
+ receivedMs,
2708
+ server,
2709
+ message
2710
+ };
2711
+ this.state.outbox.record(record);
2712
+ for (const waiter of [...this.waiters]) {
2713
+ if (this.visible(record, waiter.server, waiter.receivedAfter, waiter.criteria)) {
2714
+ this.waiters.delete(waiter);
2715
+ waiter.resolve(record);
2716
+ }
2717
+ }
2718
+ return message;
2719
+ }
2720
+ /** Every stored message, newest first. */
2721
+ messages() {
2722
+ return this.state.messages.list().map((row) => row.value.message);
2723
+ }
2724
+ jsonBody(context) {
2725
+ return context.body.kind === "json" ? context.body.value : void 0;
2726
+ }
2727
+ visible(record, server, receivedAfter, criteria) {
2728
+ if (record.server !== server && record.server !== ANY_SERVER) return false;
2729
+ if (receivedAfter !== void 0 && record.receivedMs < receivedAfter) return false;
2730
+ return matchesCriteria(record.message, criteria);
2731
+ }
2732
+ /** `server` (required) and `receivedAfter` from the query, or a 400 response. */
2733
+ scope(context) {
2734
+ const server = context.url.searchParams.get("server");
2735
+ if (!server) return invalid("server", "The server field is required.");
2736
+ const raw = context.url.searchParams.get("receivedAfter");
2737
+ if (raw === null || raw === "") return { server, after: void 0 };
2738
+ const after = Date.parse(raw);
2739
+ if (Number.isNaN(after)) return invalid("receivedAfter", "The value is not a valid date.");
2740
+ return { server, after };
2741
+ }
2742
+ page(context, records) {
2743
+ const number = (name, fallback) => {
2744
+ const raw = context.url.searchParams.get(name);
2745
+ const value = raw === null ? Number.NaN : Number(raw);
2746
+ return Number.isInteger(value) && value >= 0 ? value : fallback;
2747
+ };
2748
+ const size = Math.max(1, Math.min(1e3, number("itemsPerPage", 50)));
2749
+ const page = number("page", 0);
2750
+ const ordered = context.url.searchParams.get("dir") === "Ascending" ? [...records].reverse() : records;
2751
+ return ordered.slice(page * size, page * size + size);
2752
+ }
2753
+ matching(server, after, criteria) {
2754
+ return this.state.messages.list({ where: (record) => this.visible(record, server, after, criteria) }).map((row) => row.value);
2755
+ }
2756
+ search(context) {
2757
+ const scope = this.scope(context);
2758
+ if (scope instanceof Response) return scope;
2759
+ if (bodyIssues(context).length > 0) {
2760
+ return invalid("criteria", "The search criteria are invalid.");
2761
+ }
2762
+ const criteria = criteriaFrom(this.jsonBody(context));
2763
+ const found = faultEffect(context.request, "search_never_matches") !== void 0 ? [] : this.matching(scope.server, scope.after, criteria);
2764
+ const items = this.page(context, found).map((record) => summaryOf(record.message));
2765
+ const response = jsonRes(200, { items });
2766
+ response.headers.set("x-ms-delay", this.state.current().pollDelaysMs.join(","));
2767
+ return annotateResponse(response, {
2768
+ ids: items[0] ? { messageId: items[0].id } : {}
2769
+ });
2770
+ }
2771
+ async await(context, criteria) {
2772
+ const scope = this.scope(context);
2773
+ if (scope instanceof Response) return scope;
2774
+ const rawTimeout = context.url.searchParams.get("timeout");
2775
+ const timeout = rawTimeout === null ? DEFAULT_AWAIT_TIMEOUT_MS : Number(rawTimeout);
2776
+ if (!Number.isInteger(timeout) || timeout < 0 || timeout > MAX_AWAIT_TIMEOUT_MS) {
2777
+ return invalid("timeout", `The timeout must be between 0 and ${MAX_AWAIT_TIMEOUT_MS} ms.`);
2778
+ }
2779
+ const found = this.matching(scope.server, scope.after, criteria);
2780
+ const hit = found[0] ?? await new Promise((resolve) => {
2781
+ const waiter = {
2782
+ server: scope.server,
2783
+ criteria,
2784
+ receivedAfter: scope.after,
2785
+ resolve: (record) => {
2786
+ clearTimeout(timer);
2787
+ context.request.signal.removeEventListener("abort", abort);
2788
+ resolve(record);
2789
+ }
2790
+ };
2791
+ const abort = () => {
2792
+ this.waiters.delete(waiter);
2793
+ waiter.resolve(void 0);
2794
+ };
2795
+ const timer = setTimeout(abort, timeout);
2796
+ context.request.signal.addEventListener("abort", abort);
2797
+ this.waiters.add(waiter);
2798
+ });
2799
+ if (!hit) {
2800
+ return jsonRes(
2801
+ 404,
2802
+ errorBody(
2803
+ "search_timeout",
2804
+ `No matching messages found in time. The search criteria used for this query was [${JSON.stringify(criteria)}] which timed out after ${timeout}ms`
2805
+ )
2806
+ );
2807
+ }
2808
+ return annotateResponse(jsonRes(200, hit.message), { ids: { messageId: hit.id } });
2809
+ }
2810
+ list(context) {
2811
+ const scope = this.scope(context);
2812
+ if (scope instanceof Response) return scope;
2813
+ const items = this.page(context, this.matching(scope.server, scope.after, {})).map(
2814
+ (record) => summaryOf(record.message)
2815
+ );
2816
+ return jsonRes(200, { items });
2817
+ }
2818
+ create(context) {
2819
+ const server = context.url.searchParams.get("server");
2820
+ if (!server) return invalid("server", "The server field is required.");
2821
+ const issues = bodyIssues(context);
2822
+ if (issues.length > 0) {
2823
+ const first = issues[0];
2824
+ const field = /^missing required property (.+)$/.exec(first.message)?.[1] ?? first.path;
2825
+ return invalid(field || "body", `The ${field || "request"} field is invalid.`);
2826
+ }
2827
+ const body = this.jsonBody(context);
2828
+ const message = this.ingest({
2829
+ server,
2830
+ from: parseAddress(body.from) ?? { name: "", email: `mock@${server}.mailosaur.net` },
2831
+ to: body.to,
2832
+ cc: body.cc,
2833
+ subject: String(body.subject ?? ""),
2834
+ html: typeof body.html === "string" ? body.html : null,
2835
+ text: typeof body.text === "string" ? body.text : null
2836
+ });
2837
+ return annotateResponse(jsonRes(200, message), { ids: { messageId: message.id } });
2838
+ }
2839
+ deleteAll(context) {
2840
+ const server = context.url.searchParams.get("server");
2841
+ if (!server) return invalid("server", "The server field is required.");
2842
+ for (const row of this.state.messages.list()) {
2843
+ if (row.value.server === server || row.value.server === ANY_SERVER) {
2844
+ this.state.messages.delete(row.id);
2845
+ }
2846
+ }
2847
+ return new Response(null, { status: 204 });
2848
+ }
2849
+ get(context) {
2850
+ const record = this.state.messages.get(context.params.id ?? "");
2851
+ if (!record)
2852
+ return jsonRes(404, errorBody("invalid_request", "Not found, check input parameters."));
2853
+ return annotateResponse(jsonRes(200, record.message), { ids: { messageId: record.id } });
2854
+ }
2855
+ remove(context) {
2856
+ const id = context.params.id ?? "";
2857
+ if (!this.state.messages.delete(id)) {
2858
+ return jsonRes(404, errorBody("invalid_request", "Not found, check input parameters."));
2859
+ }
2860
+ return annotateResponse(new Response(null, { status: 204 }), { ids: { messageId: id } });
2861
+ }
2862
+ };
2863
+
2864
+ export {
2865
+ findCodes,
2866
+ htmlContent,
2867
+ textContent,
2868
+ parseAddresses,
2869
+ document,
2870
+ operationIds,
2871
+ supportedOperationIds,
2872
+ DEFAULT_SETTINGS,
2873
+ MAILOSAUR_PRESETS,
2874
+ createRuntime2 as createRuntime,
2875
+ MAILOSAUR_NAMESPACE,
2876
+ ANY_SERVER,
2877
+ DEFAULT_AWAIT_TIMEOUT_MS,
2878
+ MAX_AWAIT_TIMEOUT_MS,
2879
+ matchesCriteria,
2880
+ MailosaurAPI
2881
+ };
2882
+ //# sourceMappingURL=chunk-C46JZZ56.js.map