@crvouga/mockingbird-service-payload-cms 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,2429 @@
1
+ // ../../http/codec/dist/form.js
2
+ var parsePath = (rawKey) => {
3
+ const open = rawKey.indexOf("[");
4
+ if (open === -1)
5
+ return [rawKey];
6
+ const path = [rawKey.slice(0, open)];
7
+ const rest = rawKey.slice(open);
8
+ const pattern = /\[([^\]]*)\]/g;
9
+ let match = pattern.exec(rest);
10
+ let consumed = 0;
11
+ while (match !== null) {
12
+ if (match.index !== consumed)
13
+ return [rawKey];
14
+ path.push(match[1] ?? "");
15
+ consumed = match.index + match[0].length;
16
+ match = pattern.exec(rest);
17
+ }
18
+ if (consumed !== rest.length)
19
+ return [rawKey];
20
+ return path;
21
+ };
22
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
23
+ var put = (target, key, value) => {
24
+ if (key === "__proto__") {
25
+ Object.defineProperty(target, key, {
26
+ value,
27
+ enumerable: true,
28
+ writable: true,
29
+ configurable: true
30
+ });
31
+ return;
32
+ }
33
+ ;
34
+ target[key] = value;
35
+ };
36
+ var assign = (target, path, value) => {
37
+ let cursor = target;
38
+ for (let i = 0; i < path.length; i++) {
39
+ const segment = path[i];
40
+ const last = i === path.length - 1;
41
+ if (Array.isArray(cursor)) {
42
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
43
+ if (index === void 0)
44
+ return;
45
+ if (last) {
46
+ put(cursor, index, value);
47
+ return;
48
+ }
49
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
50
+ if (next === void 0 || typeof next === "string") {
51
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
52
+ put(cursor, index, created);
53
+ cursor = created;
54
+ } else {
55
+ cursor = next;
56
+ }
57
+ continue;
58
+ }
59
+ if (typeof cursor === "string")
60
+ return;
61
+ if (last) {
62
+ put(cursor, segment, value);
63
+ return;
64
+ }
65
+ const nextSegment = path[i + 1];
66
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
67
+ if (existing === void 0 || typeof existing === "string") {
68
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
69
+ put(cursor, segment, created);
70
+ cursor = created;
71
+ } else {
72
+ cursor = existing;
73
+ }
74
+ }
75
+ };
76
+ var decodeFormPairs = (pairs) => {
77
+ const out = {};
78
+ for (const [rawKey, value] of pairs)
79
+ assign(out, parsePath(rawKey), value);
80
+ return densify(out);
81
+ };
82
+ var densify = (value) => {
83
+ if (typeof value === "string")
84
+ return value;
85
+ if (Array.isArray(value))
86
+ return value.filter((item) => item !== void 0).map(densify);
87
+ const out = {};
88
+ for (const [key, item] of Object.entries(value))
89
+ put(out, key, densify(item));
90
+ return out;
91
+ };
92
+ var decodeForm = (text) => {
93
+ const source = text.startsWith("?") ? text.slice(1) : text;
94
+ return decodeFormPairs(new URLSearchParams(source).entries());
95
+ };
96
+
97
+ // ../../http/codec/dist/content.js
98
+ var JSON_MEDIA_TYPE = "application/json";
99
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
100
+ var mediaTypeOf = (contentType) => {
101
+ if (!contentType)
102
+ return void 0;
103
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
104
+ return essence ? essence : void 0;
105
+ };
106
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
107
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
108
+ var decodeBody = (contentType, bytes) => {
109
+ if (bytes.byteLength === 0)
110
+ return { kind: "empty" };
111
+ const mediaType = mediaTypeOf(contentType);
112
+ if (mediaType === void 0)
113
+ return { kind: "bytes", value: bytes };
114
+ if (isJsonMediaType(mediaType)) {
115
+ const text = utf8.decode(bytes);
116
+ try {
117
+ return { kind: "json", value: JSON.parse(text) };
118
+ } catch (error) {
119
+ return {
120
+ kind: "invalid",
121
+ mediaType,
122
+ text,
123
+ error: error instanceof Error ? error.message : String(error)
124
+ };
125
+ }
126
+ }
127
+ if (mediaType === FORM_MEDIA_TYPE) {
128
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
129
+ }
130
+ if (mediaType.startsWith("text/"))
131
+ return { kind: "text", value: utf8.decode(bytes) };
132
+ return { kind: "bytes", value: bytes };
133
+ };
134
+ var readBody = async (message) => {
135
+ const bytes = new Uint8Array(await message.arrayBuffer());
136
+ return decodeBody(message.headers.get("content-type"), bytes);
137
+ };
138
+
139
+ // ../core/dist/clock.js
140
+ var createClock = (source = Date.now) => {
141
+ let offsetMs = 0;
142
+ let frozenAt;
143
+ const now = () => frozenAt ?? source() + offsetMs;
144
+ return {
145
+ now,
146
+ set: (epochMs) => {
147
+ if (frozenAt !== void 0)
148
+ frozenAt = epochMs;
149
+ else
150
+ offsetMs = epochMs - source();
151
+ },
152
+ advance: (deltaMs) => {
153
+ if (frozenAt !== void 0)
154
+ frozenAt += deltaMs;
155
+ else
156
+ offsetMs += deltaMs;
157
+ },
158
+ freeze: () => {
159
+ frozenAt = now();
160
+ },
161
+ unfreeze: () => {
162
+ if (frozenAt === void 0)
163
+ return;
164
+ offsetMs = frozenAt - source();
165
+ frozenAt = void 0;
166
+ },
167
+ reset: () => {
168
+ offsetMs = 0;
169
+ frozenAt = void 0;
170
+ },
171
+ state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
172
+ };
173
+ };
174
+
175
+ // ../core/dist/collection.js
176
+ var Collection = class {
177
+ sqlite;
178
+ namespace;
179
+ name;
180
+ constructor(sqlite, namespace, name) {
181
+ this.sqlite = sqlite;
182
+ this.namespace = namespace;
183
+ this.name = name;
184
+ }
185
+ bumpCollectionSeq() {
186
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
187
+ const next = (row?.value ?? 0) + 1;
188
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
189
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
190
+ return next;
191
+ }
192
+ nextSequence() {
193
+ return this.sqlite.transaction(() => this.bumpCollectionSeq());
194
+ }
195
+ get(id) {
196
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
197
+ if (!row)
198
+ return void 0;
199
+ return JSON.parse(row.value).value;
200
+ }
201
+ has(id) {
202
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
203
+ return row !== void 0;
204
+ }
205
+ /** Insert a new record, assigning it the next sequence number. */
206
+ insert(id, value) {
207
+ return this.sqlite.transaction(() => {
208
+ const seq = this.bumpCollectionSeq();
209
+ const stored = { seq, value };
210
+ this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
211
+ VALUES (?, ?, ?, ?, ?)
212
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
213
+ return stored;
214
+ });
215
+ }
216
+ /** Replace an existing record's value, keeping its position. */
217
+ update(id, value) {
218
+ return this.sqlite.transaction(() => {
219
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
220
+ if (!row)
221
+ return void 0;
222
+ const stored = { seq: row.seq, value };
223
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
224
+ return stored;
225
+ });
226
+ }
227
+ delete(id) {
228
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
229
+ return result.changes > 0;
230
+ }
231
+ /** How many records the collection holds, without reading them. */
232
+ count() {
233
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
234
+ return Number(row?.n ?? 0);
235
+ }
236
+ list(options = {}) {
237
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
238
+ const out = [];
239
+ for (const row of rows) {
240
+ const stored = JSON.parse(row.value);
241
+ if (options.where && !options.where(stored.value, stored.seq))
242
+ continue;
243
+ out.push({ id: row.id, seq: stored.seq, value: stored.value });
244
+ }
245
+ out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
246
+ return out;
247
+ }
248
+ };
249
+
250
+ // ../core/dist/control.js
251
+ var HEALTH_PATH = "/health";
252
+ var ADMIN_PREFIX = "/__admin";
253
+ var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
254
+ var NAMESPACE_HEADER = "x-mockingbird-namespace";
255
+ var json = (status, body) => new Response(JSON.stringify(body), {
256
+ status,
257
+ headers: { "content-type": "application/json" }
258
+ });
259
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
260
+ var UNITS = {
261
+ ms: 1,
262
+ s: 1e3,
263
+ m: 6e4,
264
+ h: 36e5,
265
+ d: 864e5
266
+ };
267
+ var parseDuration = (value) => {
268
+ if (typeof value === "number" && Number.isFinite(value))
269
+ return value;
270
+ if (typeof value !== "string")
271
+ return void 0;
272
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
273
+ if (!match)
274
+ return void 0;
275
+ return Number(match[1]) * UNITS[match[2]];
276
+ };
277
+ var parseInstant = (value) => {
278
+ if (typeof value === "number" && Number.isFinite(value))
279
+ return value;
280
+ if (typeof value !== "string")
281
+ return void 0;
282
+ const parsed = Date.parse(value);
283
+ return Number.isNaN(parsed) ? void 0 : parsed;
284
+ };
285
+ var matchRoute = (pattern, path) => {
286
+ const want = pattern.split("/").filter(Boolean);
287
+ const have = path.split("/").filter(Boolean);
288
+ if (want.length !== have.length)
289
+ return void 0;
290
+ const params = {};
291
+ for (let i = 0; i < want.length; i++) {
292
+ const segment = want[i];
293
+ const actual = have[i];
294
+ if (segment.startsWith(":"))
295
+ params[segment.slice(1)] = decodeURIComponent(actual);
296
+ else if (segment !== actual)
297
+ return void 0;
298
+ }
299
+ return params;
300
+ };
301
+ var readJson = async (request) => {
302
+ const text = await request.text();
303
+ if (text.trim() === "")
304
+ return void 0;
305
+ return JSON.parse(text);
306
+ };
307
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
308
+ var createControlPlane = (context) => {
309
+ const snapshots = /* @__PURE__ */ new Map();
310
+ let snapshotCounter = 0;
311
+ const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
312
+ const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
313
+ const builtin = {
314
+ "GET /": () => json(200, {
315
+ service: context.name,
316
+ routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
317
+ }),
318
+ "POST /reset": async ({ url, namespace }) => {
319
+ const target = url.searchParams.get("all") === "1" ? "*" : namespace;
320
+ await context.reset(target);
321
+ return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
322
+ },
323
+ "GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
324
+ "GET /clock": () => json(200, context.clock.state()),
325
+ "POST /clock": ({ body }) => {
326
+ if (!isRecord(body))
327
+ return adminError(400, "expected a JSON object");
328
+ if (body.reset === true)
329
+ context.clock.reset();
330
+ if (body.set !== void 0) {
331
+ const instant = parseInstant(body.set);
332
+ if (instant === void 0)
333
+ return adminError(400, "set: expected epoch ms or ISO-8601");
334
+ context.clock.set(instant);
335
+ }
336
+ if (body.advance !== void 0) {
337
+ const delta = parseDuration(body.advance);
338
+ if (delta === void 0)
339
+ return adminError(400, 'advance: expected ms or "15m"-style');
340
+ context.clock.advance(delta);
341
+ }
342
+ if (body.freeze === true)
343
+ context.clock.freeze();
344
+ if (body.freeze === false)
345
+ context.clock.unfreeze();
346
+ return json(200, context.clock.state());
347
+ },
348
+ "GET /faults": () => json(200, { faults: context.faults.list() }),
349
+ "POST /faults": ({ body, namespace }) => {
350
+ if (isRecord(body) && typeof body.preset === "string") {
351
+ if (!context.applyPreset)
352
+ return adminError(400, `${context.name} has no fault presets`);
353
+ const { preset, ...overrides } = body;
354
+ try {
355
+ return json(201, {
356
+ preset,
357
+ rules: context.applyPreset(preset, namespace, overrides)
358
+ });
359
+ } catch (error) {
360
+ return adminError(404, error instanceof Error ? error.message : String(error));
361
+ }
362
+ }
363
+ if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
364
+ return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
365
+ }
366
+ const rule = {
367
+ // Scoped to the caller's namespace unless it asks for every one, so one worker's
368
+ // injected failure never lands on another's request.
369
+ namespace,
370
+ ...body,
371
+ id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
372
+ };
373
+ return json(201, context.faults.add(rule));
374
+ },
375
+ "DELETE /faults": ({ url }) => {
376
+ const id = url.searchParams.get("id");
377
+ if (id === null) {
378
+ context.faults.clear();
379
+ return json(200, { status: "ok" });
380
+ }
381
+ return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
382
+ },
383
+ "POST /snapshots": ({ namespace }) => {
384
+ const point = context.timeTravel.checkpoint(namespace, "main");
385
+ context.timeTravel.retain(namespace, point.id);
386
+ snapshotCounter++;
387
+ const id = `snap_${snapshotCounter}`;
388
+ snapshots.set(id, { namespace, checkpoint: point.id });
389
+ return json(201, { id, namespace, records: point.records ?? 0 });
390
+ },
391
+ "POST /snapshots/:id/restore": ({ params, namespace }) => {
392
+ const alias = snapshots.get(params.id);
393
+ if (!alias)
394
+ return adminError(404, `no snapshot ${params.id}`);
395
+ if (alias.namespace !== namespace) {
396
+ return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
397
+ }
398
+ context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
399
+ return json(200, { status: "ok", id: params.id, namespace });
400
+ },
401
+ "DELETE /snapshots/:id": ({ params }) => {
402
+ const id = params.id;
403
+ const alias = snapshots.get(id);
404
+ if (!alias)
405
+ return adminError(404, `no snapshot ${id}`);
406
+ snapshots.delete(id);
407
+ context.timeTravel.release(alias.namespace, alias.checkpoint);
408
+ return json(200, { status: "ok" });
409
+ },
410
+ "GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
411
+ "POST /checkpoints": ({ body, namespace }) => {
412
+ const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
413
+ try {
414
+ return json(201, context.timeTravel.checkpoint(namespace, branch));
415
+ } catch (error) {
416
+ return adminError(409, error instanceof Error ? error.message : String(error));
417
+ }
418
+ },
419
+ "POST /branches/:name": ({ params, body, namespace }) => {
420
+ const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
421
+ try {
422
+ return json(201, context.timeTravel.branch(params.name, {
423
+ namespace,
424
+ ...at !== void 0 ? { at } : {}
425
+ }));
426
+ } catch (error) {
427
+ return adminError(409, error instanceof Error ? error.message : String(error));
428
+ }
429
+ },
430
+ "POST /branches/:name/checkout": ({ params, body, namespace }) => {
431
+ if (!isRecord(body) || typeof body.checkpoint !== "string") {
432
+ return adminError(400, 'expected {"checkpoint":"cp_..."}');
433
+ }
434
+ try {
435
+ context.timeTravel.checkout(body.checkpoint, {
436
+ namespace,
437
+ branch: params.name
438
+ });
439
+ return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
440
+ } catch (error) {
441
+ return adminError(409, error instanceof Error ? error.message : String(error));
442
+ }
443
+ },
444
+ "GET /requests": ({ url, namespace }) => {
445
+ const status = url.searchParams.get("status");
446
+ const since = url.searchParams.get("since");
447
+ const limit = url.searchParams.get("limit");
448
+ const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
449
+ if (since !== null && sinceMs === void 0) {
450
+ return adminError(400, "since: expected epoch ms or ISO-8601");
451
+ }
452
+ if (status !== null && !/^\d{3}$/.test(status))
453
+ return adminError(400, "status: expected an HTTP status");
454
+ if (limit !== null && !/^\d+$/.test(limit))
455
+ return adminError(400, "limit: expected a count");
456
+ const operationId = url.searchParams.get("operationId");
457
+ const everyNamespace = url.searchParams.get("all") === "1";
458
+ return json(200, {
459
+ size: context.journal.size,
460
+ requests: context.journal.list({
461
+ ...everyNamespace ? {} : { namespace },
462
+ ...operationId !== null ? { operationId } : {},
463
+ ...status !== null ? { status: Number(status) } : {},
464
+ ...sinceMs !== void 0 ? { since: sinceMs } : {},
465
+ ...limit !== null ? { limit: Number(limit) } : {}
466
+ })
467
+ });
468
+ },
469
+ "DELETE /requests": ({ url, namespace }) => {
470
+ context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
471
+ return json(200, { status: "ok" });
472
+ },
473
+ "GET /metrics": () => json(200, context.metrics.report()),
474
+ "DELETE /metrics": () => {
475
+ context.metrics.reset();
476
+ return json(200, { status: "ok" });
477
+ }
478
+ };
479
+ const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
480
+ const space = key.indexOf(" ");
481
+ return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
482
+ });
483
+ return {
484
+ namespaceOf: headerNamespace,
485
+ async handle(request) {
486
+ const url = new URL(request.url);
487
+ if (url.pathname === HEALTH_PATH && request.method === "GET") {
488
+ return json(200, {
489
+ status: "ok",
490
+ service: context.name,
491
+ uptimeMs: context.wallNow() - context.startedAt,
492
+ clock: context.clock.state(),
493
+ namespaces: context.namespaces().length,
494
+ ...context.describe()
495
+ });
496
+ }
497
+ if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
498
+ return void 0;
499
+ }
500
+ if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
501
+ return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
502
+ }
503
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
504
+ for (const route of routes) {
505
+ if (route.method !== request.method)
506
+ continue;
507
+ const params = matchRoute(route.pattern, path);
508
+ if (!params)
509
+ continue;
510
+ let body;
511
+ try {
512
+ body = await readJson(request);
513
+ } catch {
514
+ return adminError(400, "request body is not valid JSON");
515
+ }
516
+ return route.handler({
517
+ request,
518
+ url,
519
+ params,
520
+ namespace: adminNamespace(request, url),
521
+ body
522
+ });
523
+ }
524
+ return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
525
+ }
526
+ };
527
+ };
528
+
529
+ // ../core/dist/credentials.js
530
+ var bearerToken = (request) => {
531
+ const header = request.headers.get("authorization");
532
+ if (!header)
533
+ return void 0;
534
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
535
+ return match?.[1]?.trim() || void 0;
536
+ };
537
+ var createCredentialRegistry = () => {
538
+ const map = /* @__PURE__ */ new Map();
539
+ return {
540
+ set: (credential, namespace) => {
541
+ map.set(credential, namespace);
542
+ },
543
+ get: (credential) => map.get(credential),
544
+ remove: (credential) => map.delete(credential),
545
+ clear: () => map.clear(),
546
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
547
+ };
548
+ };
549
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
550
+
551
+ // ../core/dist/rng.js
552
+ var seedFrom = (value) => {
553
+ let hash = 2166136261;
554
+ for (let i = 0; i < value.length; i++) {
555
+ hash ^= value.charCodeAt(i);
556
+ hash = Math.imul(hash, 16777619);
557
+ }
558
+ return hash >>> 0;
559
+ };
560
+ var createRng = (seed = 0) => {
561
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
562
+ let state = numeric;
563
+ const next = () => {
564
+ state = state + 1831565813 >>> 0;
565
+ let t = state;
566
+ t = Math.imul(t ^ t >>> 15, t | 1);
567
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
568
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
569
+ };
570
+ return {
571
+ next,
572
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
573
+ reset: () => {
574
+ state = numeric;
575
+ },
576
+ state: () => state,
577
+ setState: (next2) => {
578
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
579
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
580
+ }
581
+ state = next2 >>> 0;
582
+ },
583
+ seed: numeric
584
+ };
585
+ };
586
+
587
+ // ../core/dist/faults.js
588
+ var matches = (rule, candidate) => {
589
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
590
+ return false;
591
+ }
592
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
593
+ return false;
594
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
595
+ return false;
596
+ }
597
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
598
+ return false;
599
+ return true;
600
+ };
601
+ var faultResponse = (rule) => {
602
+ const status = rule.status ?? 500;
603
+ const headers = { "content-type": "application/json", ...rule.headers };
604
+ if (typeof rule.body === "string")
605
+ return new Response(rule.body, { status, headers });
606
+ if (rule.body === null)
607
+ return new Response(null, { status, headers: rule.headers ?? {} });
608
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
609
+ return new Response(JSON.stringify(body), { status, headers });
610
+ };
611
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
612
+ const entries = [];
613
+ return {
614
+ add(rule) {
615
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
616
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
617
+ if (existing >= 0)
618
+ entries[existing] = entry;
619
+ else
620
+ entries.push(entry);
621
+ return rule;
622
+ },
623
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
624
+ remove(id) {
625
+ const index = entries.findIndex((e) => e.rule.id === id);
626
+ if (index < 0)
627
+ return false;
628
+ entries.splice(index, 1);
629
+ return true;
630
+ },
631
+ clear() {
632
+ entries.length = 0;
633
+ },
634
+ async take(candidate) {
635
+ const hits = [];
636
+ for (const entry of entries) {
637
+ if (entry.remaining === 0)
638
+ continue;
639
+ if (!matches(entry.rule, candidate))
640
+ continue;
641
+ const rate = entry.rule.rate ?? 1;
642
+ if (rng.next() >= rate)
643
+ continue;
644
+ entry.hits++;
645
+ if (entry.remaining !== null)
646
+ entry.remaining--;
647
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
648
+ if (delay !== void 0 && delay > 0) {
649
+ await sleep(delay);
650
+ }
651
+ const hit = { id: entry.rule.id };
652
+ if (entry.rule.effect !== void 0) {
653
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
654
+ }
655
+ if (entry.rule.drop === true)
656
+ hit.drop = true;
657
+ else if (entry.rule.status !== void 0)
658
+ hit.response = faultResponse(entry.rule);
659
+ hits.push(hit);
660
+ if (hit.drop || hit.response)
661
+ break;
662
+ }
663
+ return hits;
664
+ }
665
+ };
666
+ };
667
+
668
+ // ../../openapi/core/dist/refs.js
669
+ var OpenAPIReferenceError = class extends Error {
670
+ ref;
671
+ constructor(ref) {
672
+ super(`unresolvable $ref: ${ref}`);
673
+ this.ref = ref;
674
+ this.name = "OpenAPIReferenceError";
675
+ }
676
+ };
677
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
678
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
679
+ var resolveRef = (document2, ref) => {
680
+ if (!ref.startsWith("#/"))
681
+ throw new OpenAPIReferenceError(ref);
682
+ let cursor = document2;
683
+ for (const raw of ref.slice(2).split("/")) {
684
+ const segment = unescapePointer(raw);
685
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
686
+ throw new OpenAPIReferenceError(ref);
687
+ }
688
+ cursor = cursor[segment];
689
+ }
690
+ if (cursor === void 0)
691
+ throw new OpenAPIReferenceError(ref);
692
+ return cursor;
693
+ };
694
+ var deref = (document2, value) => {
695
+ let current = value;
696
+ const seen = /* @__PURE__ */ new Set();
697
+ while (isReference(current)) {
698
+ if (seen.has(current.$ref))
699
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
700
+ seen.add(current.$ref);
701
+ current = resolveRef(document2, current.$ref);
702
+ }
703
+ return current;
704
+ };
705
+
706
+ // ../../openapi/core/dist/types.js
707
+ var HTTP_METHODS = [
708
+ "get",
709
+ "put",
710
+ "post",
711
+ "delete",
712
+ "options",
713
+ "head",
714
+ "patch",
715
+ "trace"
716
+ ];
717
+
718
+ // ../../openapi/core/dist/document.js
719
+ var mergeParameters = (document2, item, own) => {
720
+ const merged = /* @__PURE__ */ new Map();
721
+ for (const raw of item.parameters ?? []) {
722
+ const parameter = deref(document2, raw);
723
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
724
+ }
725
+ for (const raw of own ?? []) {
726
+ const parameter = deref(document2, raw);
727
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
728
+ }
729
+ return [...merged.values()];
730
+ };
731
+ var listOperations = (document2) => {
732
+ const operations = [];
733
+ for (const [path, item] of Object.entries(document2.paths)) {
734
+ for (const method of HTTP_METHODS) {
735
+ const operation = item[method];
736
+ if (operation?.operationId === void 0)
737
+ continue;
738
+ const responses = {};
739
+ for (const [status, response] of Object.entries(operation.responses)) {
740
+ responses[status] = deref(document2, response);
741
+ }
742
+ operations.push({
743
+ operationId: operation.operationId,
744
+ method,
745
+ path,
746
+ operation,
747
+ parameters: mergeParameters(document2, item, operation.parameters),
748
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
749
+ responses
750
+ });
751
+ }
752
+ }
753
+ return operations;
754
+ };
755
+
756
+ // ../core/dist/http.js
757
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
758
+ status,
759
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
760
+ });
761
+ var HttpError = class extends Error {
762
+ status;
763
+ body;
764
+ headers;
765
+ constructor(status, body, headers = {}) {
766
+ super(`HTTP ${status}`);
767
+ this.status = status;
768
+ this.body = body;
769
+ this.headers = headers;
770
+ this.name = "HttpError";
771
+ }
772
+ toResponse() {
773
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
774
+ if (contentType === "text/plain") {
775
+ return new Response(String(this.body), {
776
+ status: this.status,
777
+ headers: this.headers
778
+ });
779
+ }
780
+ return jsonRes(this.status, this.body, this.headers);
781
+ }
782
+ };
783
+ var ok = (value) => ({ ok: true, value });
784
+ var fail = (reason) => ({ ok: false, reason });
785
+ var coerce = {
786
+ string(value) {
787
+ return typeof value === "string" ? ok(value) : fail("expected a string");
788
+ },
789
+ integer(value) {
790
+ if (typeof value === "number" && Number.isInteger(value))
791
+ return ok(value);
792
+ if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
793
+ const parsed = Number(value);
794
+ return Number.isSafeInteger(parsed) ? ok(parsed) : fail("integer out of range");
795
+ }
796
+ return fail("expected an integer");
797
+ },
798
+ boolean(value) {
799
+ if (typeof value === "boolean")
800
+ return ok(value);
801
+ if (value === "true" || value === "1")
802
+ return ok(true);
803
+ if (value === "false" || value === "0")
804
+ return ok(false);
805
+ return fail("expected a boolean");
806
+ },
807
+ enumeration(value, allowed) {
808
+ const match = allowed.find((candidate) => candidate === value);
809
+ return match === void 0 ? fail(`expected one of ${allowed.join(", ")}`) : ok(match);
810
+ },
811
+ /** Flat string-to-string map, the shape of Stripe-style `metadata`. */
812
+ stringMap(value) {
813
+ if (typeof value !== "object" || value === null || Array.isArray(value))
814
+ return fail("expected an object");
815
+ const out = {};
816
+ for (const [key, item] of Object.entries(value)) {
817
+ if (typeof item !== "string")
818
+ return fail(`expected a string at ${key}`);
819
+ out[key] = item;
820
+ }
821
+ return ok(out);
822
+ }
823
+ };
824
+
825
+ // ../core/dist/journal.js
826
+ var DEFAULT_JOURNAL_SIZE = 1e3;
827
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
828
+ const capacity = Math.max(0, Math.floor(size));
829
+ const rings = /* @__PURE__ */ new Map();
830
+ let sequence = 0;
831
+ const order = /* @__PURE__ */ new WeakMap();
832
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
833
+ return {
834
+ size: capacity,
835
+ record(entry) {
836
+ if (capacity === 0)
837
+ return;
838
+ order.set(entry, sequence++);
839
+ let ring = rings.get(entry.namespace);
840
+ if (!ring) {
841
+ ring = { entries: [], next: 0 };
842
+ rings.set(entry.namespace, ring);
843
+ }
844
+ if (ring.entries.length < capacity)
845
+ ring.entries.push(entry);
846
+ else {
847
+ ring.entries[ring.next] = entry;
848
+ ring.next = (ring.next + 1) % capacity;
849
+ }
850
+ },
851
+ list(query = {}) {
852
+ 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));
853
+ 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));
854
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
855
+ },
856
+ clear(namespace) {
857
+ if (namespace === void 0)
858
+ rings.clear();
859
+ else
860
+ rings.delete(namespace);
861
+ }
862
+ };
863
+ };
864
+ var notes = /* @__PURE__ */ new WeakMap();
865
+ var annotateResponse = (response, extra) => {
866
+ const existing = notes.get(response);
867
+ notes.set(response, {
868
+ ...existing,
869
+ ...extra,
870
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
871
+ });
872
+ return response;
873
+ };
874
+ var responseNotes = (response) => notes.get(response);
875
+
876
+ // ../core/dist/metrics.js
877
+ var createMetrics = () => {
878
+ let requests = 0;
879
+ let faults = 0;
880
+ let totalDurationMs = 0;
881
+ const byOperation = /* @__PURE__ */ new Map();
882
+ const unmatched = /* @__PURE__ */ new Map();
883
+ return {
884
+ record(entry) {
885
+ requests++;
886
+ totalDurationMs += entry.durationMs;
887
+ if (entry.faultId !== void 0)
888
+ faults++;
889
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
890
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
891
+ if (entry.unmatched) {
892
+ const route = `${entry.method} ${entry.path}`;
893
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
894
+ }
895
+ },
896
+ report: () => ({
897
+ requests,
898
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
899
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
900
+ const space = route.indexOf(" ");
901
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
902
+ }),
903
+ faults,
904
+ totalDurationMs
905
+ }),
906
+ reset() {
907
+ requests = 0;
908
+ faults = 0;
909
+ totalDurationMs = 0;
910
+ byOperation.clear();
911
+ unmatched.clear();
912
+ }
913
+ };
914
+ };
915
+
916
+ // ../../core/dist/timeline.js
917
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
918
+ var Timeline = class {
919
+ maxCheckpoints;
920
+ now;
921
+ makeId;
922
+ nodes = /* @__PURE__ */ new Map();
923
+ heads = /* @__PURE__ */ new Map();
924
+ /** Unreferenced nodes in the exact order they became collectible. */
925
+ evictable = /* @__PURE__ */ new Set();
926
+ /** Branch heads plus explicit retainers. Absent means zero. */
927
+ references = /* @__PURE__ */ new Map();
928
+ explicitPins = /* @__PURE__ */ new Map();
929
+ sequence = 0;
930
+ constructor(options = {}) {
931
+ const max = options.maxCheckpoints ?? 1e3;
932
+ if (!Number.isSafeInteger(max) || max < 1)
933
+ throw new RangeError("maxCheckpoints must be a positive integer");
934
+ this.maxCheckpoints = max;
935
+ this.now = options.now ?? (() => this.sequence);
936
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
937
+ }
938
+ /** Capture a new immutable value and move `branch` to it. */
939
+ commit(value, options = {}) {
940
+ const branch = options.branch ?? "main";
941
+ this.assertBranch(branch);
942
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
943
+ if (parent !== null && !this.nodes.has(parent))
944
+ throw new RangeError(`no checkpoint ${parent}`);
945
+ const id = this.makeId(++this.sequence);
946
+ if (this.nodes.has(id))
947
+ throw new RangeError(`duplicate checkpoint id ${id}`);
948
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
949
+ this.nodes.set(id, checkpoint);
950
+ this.moveHead(branch, id);
951
+ this.collect(this.maxCheckpoints);
952
+ return checkpoint;
953
+ }
954
+ /** Create a branch pointer without copying its checkpoint value. */
955
+ fork(branch, options = {}) {
956
+ this.assertBranch(branch);
957
+ if (this.heads.has(branch))
958
+ throw new RangeError(`branch already exists: ${branch}`);
959
+ const from = options.from ?? this.heads.get("main");
960
+ if (from === void 0)
961
+ return void 0;
962
+ const checkpoint = this.get(from);
963
+ this.moveHead(branch, checkpoint.id);
964
+ return checkpoint;
965
+ }
966
+ /** Move a branch pointer to an existing checkpoint. */
967
+ checkout(branch, id) {
968
+ this.assertBranch(branch);
969
+ const checkpoint = this.get(id);
970
+ this.moveHead(branch, checkpoint.id);
971
+ return checkpoint;
972
+ }
973
+ get(id) {
974
+ const checkpoint = this.nodes.get(id);
975
+ if (!checkpoint)
976
+ throw new RangeError(`no checkpoint ${id}`);
977
+ return checkpoint;
978
+ }
979
+ head(branch = "main") {
980
+ const id = this.heads.get(branch);
981
+ return id === void 0 ? void 0 : this.get(id);
982
+ }
983
+ hasBranch(branch) {
984
+ return this.heads.has(branch);
985
+ }
986
+ branches() {
987
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
988
+ }
989
+ checkpoints() {
990
+ return [...this.nodes.values()];
991
+ }
992
+ /** Number of retained checkpoints without allocating an array. */
993
+ get size() {
994
+ return this.nodes.size;
995
+ }
996
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
997
+ retain(id) {
998
+ const checkpoint = this.get(id);
999
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1000
+ this.addReference(id);
1001
+ return checkpoint;
1002
+ }
1003
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1004
+ release(id) {
1005
+ if (!this.nodes.has(id))
1006
+ return false;
1007
+ const pins = this.explicitPins.get(id) ?? 0;
1008
+ if (pins === 0)
1009
+ return false;
1010
+ if (pins === 1)
1011
+ this.explicitPins.delete(id);
1012
+ else
1013
+ this.explicitPins.set(id, pins - 1);
1014
+ this.removeReference(id);
1015
+ this.collect(this.maxCheckpoints);
1016
+ return true;
1017
+ }
1018
+ deleteBranch(branch) {
1019
+ if (branch === "main")
1020
+ throw new RangeError("cannot delete main branch");
1021
+ const previous = this.heads.get(branch);
1022
+ const deleted = this.heads.delete(branch);
1023
+ if (previous !== void 0)
1024
+ this.removeReference(previous);
1025
+ this.collect(this.maxCheckpoints);
1026
+ return deleted;
1027
+ }
1028
+ /**
1029
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1030
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1031
+ * storage dependency, so a retained node remains usable after pruning.
1032
+ */
1033
+ gc(max = this.maxCheckpoints) {
1034
+ if (!Number.isSafeInteger(max) || max < 1)
1035
+ throw new RangeError("max must be a positive integer");
1036
+ const removed = [];
1037
+ this.collect(max, removed);
1038
+ return removed;
1039
+ }
1040
+ collect(max, removed) {
1041
+ while (this.nodes.size > max && this.evictable.size > 0) {
1042
+ const id = this.evictable.values().next().value;
1043
+ this.evictable.delete(id);
1044
+ this.nodes.delete(id);
1045
+ removed?.push(id);
1046
+ }
1047
+ }
1048
+ moveHead(branch, id) {
1049
+ const previous = this.heads.get(branch);
1050
+ if (previous === id)
1051
+ return;
1052
+ if (previous !== void 0)
1053
+ this.removeReference(previous);
1054
+ this.heads.set(branch, id);
1055
+ this.addReference(id);
1056
+ }
1057
+ addReference(id) {
1058
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1059
+ this.evictable.delete(id);
1060
+ }
1061
+ removeReference(id) {
1062
+ const next = (this.references.get(id) ?? 0) - 1;
1063
+ if (next > 0)
1064
+ this.references.set(id, next);
1065
+ else {
1066
+ this.references.delete(id);
1067
+ if (this.nodes.has(id))
1068
+ this.evictable.add(id);
1069
+ }
1070
+ }
1071
+ assertBranch(branch) {
1072
+ if (!BRANCH_PATTERN.test(branch))
1073
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1074
+ }
1075
+ };
1076
+
1077
+ // ../../sqlite/dist/default.js
1078
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1079
+ var createDefaultSqlite = () => new Database();
1080
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1081
+
1082
+ // ../../sqlite/dist/migrate.js
1083
+ var ensureMigrationsTable = (sqlite) => {
1084
+ sqlite.exec(`
1085
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1086
+ id TEXT PRIMARY KEY NOT NULL,
1087
+ applied_at INTEGER NOT NULL
1088
+ )
1089
+ `);
1090
+ };
1091
+ var migrate = (sqlite, migrations) => {
1092
+ ensureMigrationsTable(sqlite);
1093
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1094
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1095
+ if (pending.length === 0)
1096
+ return;
1097
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1098
+ const now = Math.floor(Date.now() / 1e3);
1099
+ sqlite.transaction(() => {
1100
+ for (const migration of pending) {
1101
+ sqlite.exec(migration.sql);
1102
+ insert.run(migration.id, now);
1103
+ }
1104
+ });
1105
+ };
1106
+
1107
+ // ../../sqlite/dist/schema.js
1108
+ var CORE_MIGRATIONS = [
1109
+ {
1110
+ id: "20260322_core_records_sequences",
1111
+ sql: `
1112
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1113
+ namespace TEXT NOT NULL,
1114
+ collection TEXT NOT NULL,
1115
+ id TEXT NOT NULL,
1116
+ seq INTEGER NOT NULL,
1117
+ value TEXT NOT NULL,
1118
+ PRIMARY KEY (namespace, collection, id)
1119
+ );
1120
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1121
+ ON mockingbird_records (namespace, collection, seq);
1122
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1123
+ namespace TEXT NOT NULL,
1124
+ name TEXT NOT NULL,
1125
+ kind TEXT NOT NULL,
1126
+ value INTEGER NOT NULL,
1127
+ PRIMARY KEY (namespace, name, kind)
1128
+ );
1129
+ `
1130
+ }
1131
+ ];
1132
+ var migrateCore = (sqlite) => {
1133
+ migrate(sqlite, CORE_MIGRATIONS);
1134
+ };
1135
+ var clearNamespace = (sqlite, namespace) => {
1136
+ sqlite.transaction(() => {
1137
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1138
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1139
+ });
1140
+ };
1141
+
1142
+ // ../../openapi/metadata/dist/types.js
1143
+ var EXTENSION_KEYS = {
1144
+ operation: "x-mockingbird",
1145
+ resource: "x-mockingbird-resource",
1146
+ resourceRef: "x-mockingbird-resource-ref",
1147
+ volatile: "x-mockingbird-volatile",
1148
+ scope: "x-mockingbird-scope",
1149
+ unsupported: "x-mockingbird-unsupported",
1150
+ parityHeader: "x-mockingbird-parity-header"
1151
+ };
1152
+
1153
+ // ../../openapi/metadata/dist/read.js
1154
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1155
+ var extensionOf = (holder, key) => holder[key];
1156
+ var operationMetadata = (operation) => {
1157
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1158
+ const ext = isRecord2(raw) ? raw : {};
1159
+ const supported = ext.supported ?? true;
1160
+ const parity = ext.parity ?? {};
1161
+ return {
1162
+ supported,
1163
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1164
+ parity: {
1165
+ enabled: supported && (parity.enabled ?? true),
1166
+ safe: parity.safe ?? true,
1167
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1168
+ }
1169
+ };
1170
+ };
1171
+
1172
+ // ../core/dist/service.js
1173
+ import { Hono } from "hono";
1174
+ var defineOperations = (handlers) => handlers;
1175
+ var OperationRegistryError = class extends Error {
1176
+ problems;
1177
+ constructor(problems) {
1178
+ super(`operation registry is inconsistent:
1179
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1180
+ this.problems = problems;
1181
+ this.name = "OperationRegistryError";
1182
+ }
1183
+ };
1184
+ var verifyOperations = (document2, handlers) => {
1185
+ const problems = [];
1186
+ const operations = listOperations(document2);
1187
+ const seen = /* @__PURE__ */ new Set();
1188
+ for (const operation of operations) {
1189
+ if (seen.has(operation.operationId))
1190
+ problems.push(`duplicate operationId ${operation.operationId}`);
1191
+ seen.add(operation.operationId);
1192
+ const supported = operationMetadata(operation.operation).supported;
1193
+ const handler = handlers[operation.operationId];
1194
+ if (supported && !handler)
1195
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1196
+ if (!supported && handler)
1197
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1198
+ }
1199
+ for (const id of Object.keys(handlers)) {
1200
+ if (!seen.has(id))
1201
+ problems.push(`handler ${id} has no OpenAPI operation`);
1202
+ }
1203
+ return problems;
1204
+ };
1205
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1206
+ var routeOrder = (a, b) => {
1207
+ const sa = a.path.split("/");
1208
+ const sb = b.path.split("/");
1209
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1210
+ const x = sa[i] ?? "";
1211
+ const y = sb[i] ?? "";
1212
+ const px = x.startsWith("{");
1213
+ const py = y.startsWith("{");
1214
+ if (px !== py)
1215
+ return px ? 1 : -1;
1216
+ if (x !== y)
1217
+ return x < y ? -1 : 1;
1218
+ }
1219
+ return 0;
1220
+ };
1221
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1222
+ var bootSqlite = (sqlite) => {
1223
+ const client = resolveSqlite(sqlite);
1224
+ migrateCore(client);
1225
+ return client;
1226
+ };
1227
+ var createService = (options) => {
1228
+ const problems = verifyOperations(options.document, options.handlers);
1229
+ if (problems.length > 0)
1230
+ throw new OperationRegistryError(problems);
1231
+ migrateCore(options.sqlite);
1232
+ const now = options.now ?? (() => Date.now());
1233
+ const app = new Hono();
1234
+ app.notFound((c) => options.notFound(c.req.raw));
1235
+ app.onError((error, c) => options.onError(error, c.req.raw));
1236
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1237
+ for (const operation of operations) {
1238
+ const metadata = operationMetadata(operation.operation);
1239
+ const handler = options.handlers[operation.operationId];
1240
+ const route = async (c) => {
1241
+ const request = c.req.raw;
1242
+ if (!metadata.supported || !handler) {
1243
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1244
+ }
1245
+ const url = new URL(request.url);
1246
+ const context = {
1247
+ request,
1248
+ url,
1249
+ params: c.req.param(),
1250
+ query: queryOf(url),
1251
+ body: await readBody(request),
1252
+ sqlite: options.sqlite,
1253
+ namespace: options.namespace,
1254
+ operation,
1255
+ document: options.document,
1256
+ now
1257
+ };
1258
+ const short = await options.before?.(context);
1259
+ if (short)
1260
+ return short;
1261
+ return handler(context);
1262
+ };
1263
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1264
+ }
1265
+ return {
1266
+ app,
1267
+ sqlite: options.sqlite,
1268
+ namespace: options.namespace,
1269
+ fetch: async (request) => app.fetch(request),
1270
+ reset: async () => {
1271
+ clearNamespace(options.sqlite, options.namespace);
1272
+ }
1273
+ };
1274
+ };
1275
+
1276
+ // ../core/dist/snapshot.js
1277
+ var snapshotNamespace = (sqlite, namespace) => ({
1278
+ namespace,
1279
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1280
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1281
+ });
1282
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1283
+ sqlite.transaction(() => {
1284
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1285
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1286
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1287
+ for (const row of snapshot.records) {
1288
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1289
+ }
1290
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1291
+ for (const row of snapshot.sequences) {
1292
+ sequence.run(namespace, row.name, row.kind, row.value);
1293
+ }
1294
+ });
1295
+ };
1296
+
1297
+ // ../core/dist/version.js
1298
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1299
+
1300
+ // ../core/dist/webhooks.js
1301
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1302
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1303
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1304
+ var parseEndpoint = (value) => {
1305
+ if (!isRecord3(value) || typeof value.url !== "string")
1306
+ return "each endpoint needs a url";
1307
+ try {
1308
+ new URL(value.url);
1309
+ } catch {
1310
+ return `not a URL: ${value.url}`;
1311
+ }
1312
+ const endpoint = { url: value.url };
1313
+ if (typeof value.id === "string")
1314
+ endpoint.id = value.id;
1315
+ if (typeof value.secret === "string")
1316
+ endpoint.secret = value.secret;
1317
+ if (typeof value.signUrl === "string")
1318
+ endpoint.signUrl = value.signUrl;
1319
+ const events = value.events ?? value.enabledEvents;
1320
+ if (Array.isArray(events))
1321
+ endpoint.events = events.map(String);
1322
+ if (isRecord3(value.tags)) {
1323
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1324
+ }
1325
+ if (typeof value.account === "string")
1326
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1327
+ if (isRecord3(value.headers)) {
1328
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1329
+ }
1330
+ return endpoint;
1331
+ };
1332
+ var webhookAdminRoutes = (hub) => ({
1333
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1334
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1335
+ const type = url.searchParams.get("type");
1336
+ return type === null || d.type === type;
1337
+ })
1338
+ }),
1339
+ "GET /webhooks/events": ({ url, namespace }) => {
1340
+ const type = url.searchParams.get("type");
1341
+ return json2(200, {
1342
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1343
+ });
1344
+ },
1345
+ "POST /webhooks/:id/replay": async ({ params }) => {
1346
+ const replayed = await hub.replay(params.id);
1347
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1348
+ },
1349
+ "POST /webhooks/flush": async () => {
1350
+ await hub.flush();
1351
+ return json2(200, { status: "ok" });
1352
+ },
1353
+ "POST /webhooks/faults": ({ body, namespace }) => {
1354
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1355
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1356
+ }
1357
+ const fault = { mode: body.mode };
1358
+ if (typeof body.count === "number")
1359
+ fault.count = body.count;
1360
+ hub.fault(namespace, fault);
1361
+ return json2(201, { namespace, ...fault });
1362
+ },
1363
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1364
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1365
+ ...rest,
1366
+ secret: secret ? "(set)" : null
1367
+ }))
1368
+ }),
1369
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1370
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1371
+ if (!Array.isArray(list))
1372
+ return adminError2(400, "expected [{url, secret?, events?}]");
1373
+ const parsed = [];
1374
+ for (const each of list) {
1375
+ const endpoint = parseEndpoint(each);
1376
+ if (typeof endpoint === "string")
1377
+ return adminError2(400, endpoint);
1378
+ parsed.push(endpoint);
1379
+ }
1380
+ const set = hub.setEndpoints(namespace, parsed);
1381
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1382
+ },
1383
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1384
+ hub.setEndpoints(namespace, []);
1385
+ return json2(200, { status: "ok" });
1386
+ }
1387
+ });
1388
+ var parsePayload = (message) => {
1389
+ if (message.contentType.startsWith("application/json")) {
1390
+ try {
1391
+ return JSON.parse(message.body);
1392
+ } catch {
1393
+ return message.body;
1394
+ }
1395
+ }
1396
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1397
+ return Object.fromEntries(new URLSearchParams(message.body));
1398
+ }
1399
+ return message.body;
1400
+ };
1401
+
1402
+ // ../core/dist/runtime.js
1403
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1404
+ var BRANCH_HEADER = "x-mockingbird-branch";
1405
+ var AT_HEADER = "x-mockingbird-at";
1406
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1407
+ var DEFAULT_NAMESPACE = "default";
1408
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1409
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1410
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1411
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1412
+ var effects = /* @__PURE__ */ new WeakMap();
1413
+ var reuseSorted = (fresh, previous, compare2, equal) => {
1414
+ if (!previous || previous.length === 0)
1415
+ return fresh.map((row) => Object.freeze(row));
1416
+ const result = new Array(fresh.length);
1417
+ let unchanged = fresh.length === previous.length;
1418
+ let oldIndex = 0;
1419
+ for (let index = 0; index < fresh.length; index++) {
1420
+ const row = fresh[index];
1421
+ while (oldIndex < previous.length && compare2(previous[oldIndex], row) < 0) {
1422
+ oldIndex++;
1423
+ }
1424
+ const old = previous[oldIndex];
1425
+ result[index] = old !== void 0 && compare2(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1426
+ if (result[index] !== previous[index])
1427
+ unchanged = false;
1428
+ }
1429
+ return unchanged ? previous : result;
1430
+ };
1431
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1432
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1433
+ var DroppedConnectionError = class extends TypeError {
1434
+ code = "MOCKINGBIRD_DROP";
1435
+ constructor() {
1436
+ super("fetch failed: connection dropped by Mockingbird fault");
1437
+ this.name = "TypeError";
1438
+ }
1439
+ };
1440
+ var operationMatcher = (document2) => {
1441
+ const matchers = listOperations(document2).map((operation) => ({
1442
+ operationId: operation.operationId,
1443
+ method: operation.method.toUpperCase(),
1444
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1445
+ params: (operation.path.match(/\{/g) ?? []).length
1446
+ })).sort((a, b) => a.params - b.params);
1447
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1448
+ };
1449
+ var createRuntime = (options) => {
1450
+ const sqlite = bootSqlite(options.sqlite);
1451
+ const clock = options.clock ?? createClock();
1452
+ const rng = createRng(options.seed ?? 0);
1453
+ const wallNow = options.io?.wallNow ?? Date.now;
1454
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1455
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1456
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1457
+ const metrics = createMetrics();
1458
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1459
+ const version = options.version ?? PACKAGE_VERSION;
1460
+ const instances = /* @__PURE__ */ new Map();
1461
+ const publicNamespaces = /* @__PURE__ */ new Set();
1462
+ const branchRngs = /* @__PURE__ */ new Map();
1463
+ const timelines = /* @__PURE__ */ new Map();
1464
+ const branchStorage = /* @__PURE__ */ new Map();
1465
+ const captured = /* @__PURE__ */ new Map();
1466
+ const credentials = createCredentialRegistry();
1467
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
1468
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
1469
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
1470
+ const existing = instances.get(key);
1471
+ if (existing)
1472
+ return existing;
1473
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
1474
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
1475
+ }
1476
+ const created = options.create({
1477
+ namespace: storageNamespace(key),
1478
+ publicNamespace,
1479
+ sqlite,
1480
+ clock,
1481
+ rng: isolatedRng ?? rng
1482
+ });
1483
+ instances.set(key, created);
1484
+ publicNamespaces.add(publicNamespace);
1485
+ if (isolatedRng)
1486
+ branchRngs.set(key, isolatedRng);
1487
+ return created;
1488
+ };
1489
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
1490
+ const capture = (storage) => {
1491
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
1492
+ const previous = captured.get(storage);
1493
+ const snapshot2 = {
1494
+ namespace: fresh.namespace,
1495
+ 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),
1496
+ 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)
1497
+ };
1498
+ Object.freeze(snapshot2.records);
1499
+ Object.freeze(snapshot2.sequences);
1500
+ Object.freeze(snapshot2);
1501
+ captured.set(storage, snapshot2);
1502
+ return Object.freeze({
1503
+ snapshot: snapshot2,
1504
+ clock: Object.freeze(clock.state()),
1505
+ rngState: (branchRngs.get(storage) ?? rng).state()
1506
+ });
1507
+ };
1508
+ const timeline = (name = DEFAULT_NAMESPACE) => {
1509
+ let found = timelines.get(name);
1510
+ if (found)
1511
+ return found;
1512
+ instance(name);
1513
+ found = new Timeline({
1514
+ now: clock.now,
1515
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
1516
+ });
1517
+ found.commit(capture(name));
1518
+ timelines.set(name, found);
1519
+ return found;
1520
+ };
1521
+ const physicalBranch = (namespace, branch2) => {
1522
+ if (branch2 === "main")
1523
+ return namespace;
1524
+ const mapKey = `${namespace}\0${branch2}`;
1525
+ const existing = branchStorage.get(mapKey);
1526
+ if (existing)
1527
+ return existing;
1528
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
1529
+ branchStorage.set(mapKey, key);
1530
+ return key;
1531
+ };
1532
+ const ensureBranch = (namespace, branch2, at) => {
1533
+ if (!BRANCH_PATTERN2.test(branch2))
1534
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1535
+ const history = timeline(namespace);
1536
+ if (branch2 === "main") {
1537
+ if (at !== void 0) {
1538
+ const point = history.checkout("main", at);
1539
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1540
+ captured.set(namespace, point.value.snapshot);
1541
+ rng.setState(point.value.rngState);
1542
+ clock.set(point.value.clock.now);
1543
+ if (point.value.clock.frozen)
1544
+ clock.freeze();
1545
+ else
1546
+ clock.unfreeze();
1547
+ }
1548
+ return namespace;
1549
+ }
1550
+ const storage = physicalBranch(namespace, branch2);
1551
+ if (!history.hasBranch(branch2)) {
1552
+ if (at === void 0)
1553
+ history.commit(capture(namespace));
1554
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
1555
+ const branchRng = createRng(options.seed ?? 0);
1556
+ if (point)
1557
+ branchRng.setState(point.value.rngState);
1558
+ instanceFor(storage, namespace, branchRng);
1559
+ if (point)
1560
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1561
+ if (point)
1562
+ captured.set(storage, point.value.snapshot);
1563
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1564
+ const point = history.checkout(branch2, at);
1565
+ if (!instances.has(storage)) {
1566
+ const branchRng = createRng(options.seed ?? 0);
1567
+ branchRng.setState(point.value.rngState);
1568
+ instanceFor(storage, namespace, branchRng);
1569
+ }
1570
+ branchRngs.get(storage)?.setState(point.value.rngState);
1571
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1572
+ captured.set(storage, point.value.snapshot);
1573
+ } else {
1574
+ if (!instances.has(storage)) {
1575
+ const point = history.head(branch2);
1576
+ const branchRng = createRng(options.seed ?? 0);
1577
+ if (point)
1578
+ branchRng.setState(point.value.rngState);
1579
+ instanceFor(storage, namespace, branchRng);
1580
+ }
1581
+ }
1582
+ return storage;
1583
+ };
1584
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
1585
+ const storage = ensureBranch(namespace, branch2);
1586
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
1587
+ };
1588
+ const branch = (name, branchOptions = {}) => {
1589
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
1590
+ ensureBranch(namespace, name, branchOptions.at);
1591
+ const head = timeline(namespace).head(name);
1592
+ if (!head)
1593
+ throw new RangeError(`branch ${name} has no checkpoint`);
1594
+ return head;
1595
+ };
1596
+ const checkout = (checkpointId, checkoutOptions = {}) => {
1597
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1598
+ const branchName = checkoutOptions.branch ?? "main";
1599
+ const history = timeline(namespace);
1600
+ const point = history.checkout(branchName, checkpointId);
1601
+ const storage = ensureBranch(namespace, branchName);
1602
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1603
+ captured.set(storage, point.value.snapshot);
1604
+ clock.set(point.value.clock.now);
1605
+ if (point.value.clock.frozen)
1606
+ clock.freeze();
1607
+ else
1608
+ clock.unfreeze();
1609
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
1610
+ };
1611
+ const reset = async (name = DEFAULT_NAMESPACE) => {
1612
+ if (name === "*") {
1613
+ options.webhooks?.clear();
1614
+ for (const each of instances.values())
1615
+ await each.reset();
1616
+ timelines.clear();
1617
+ branchStorage.clear();
1618
+ branchRngs.clear();
1619
+ captured.clear();
1620
+ return;
1621
+ }
1622
+ options.webhooks?.clear(name);
1623
+ const target = instances.get(name);
1624
+ if (target)
1625
+ await target.reset();
1626
+ else
1627
+ clearNamespace(sqlite, storageNamespace(name));
1628
+ for (const [mapping, storage] of branchStorage) {
1629
+ if (!mapping.startsWith(`${name}\0`))
1630
+ continue;
1631
+ const branchInstance = instances.get(storage);
1632
+ if (branchInstance)
1633
+ await branchInstance.reset();
1634
+ else
1635
+ clearNamespace(sqlite, storageNamespace(storage));
1636
+ branchStorage.delete(mapping);
1637
+ branchRngs.delete(storage);
1638
+ captured.delete(storage);
1639
+ }
1640
+ timelines.delete(name);
1641
+ captured.delete(name);
1642
+ };
1643
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
1644
+ return checkpoint(name, "main").value.snapshot;
1645
+ };
1646
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
1647
+ instance(name);
1648
+ restoreNamespace(sqlite, storageNamespace(name), from);
1649
+ captured.set(name, from);
1650
+ const history = timelines.get(name);
1651
+ if (history)
1652
+ history.commit(capture(name), { branch: "main" });
1653
+ else
1654
+ timeline(name);
1655
+ };
1656
+ const runtime = {
1657
+ name: options.name,
1658
+ sqlite,
1659
+ clock,
1660
+ faults,
1661
+ metrics,
1662
+ journal,
1663
+ rng,
1664
+ credentials,
1665
+ webhooks: options.webhooks,
1666
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
1667
+ const preset = options.presets?.[name];
1668
+ if (!preset)
1669
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
1670
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
1671
+ namespace,
1672
+ ...rule,
1673
+ ...overrides,
1674
+ preset: name,
1675
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
1676
+ }));
1677
+ if (preset.webhook && options.webhooks) {
1678
+ options.webhooks.fault(namespace, {
1679
+ ...preset.webhook,
1680
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
1681
+ });
1682
+ }
1683
+ return added;
1684
+ },
1685
+ instance,
1686
+ namespaces: () => [...publicNamespaces].sort(),
1687
+ reset,
1688
+ snapshot,
1689
+ restore,
1690
+ checkpoint,
1691
+ branch,
1692
+ checkout,
1693
+ timeline,
1694
+ fetch: async (incoming) => {
1695
+ let request = incoming;
1696
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
1697
+ if (prefixed) {
1698
+ const url2 = new URL(request.url);
1699
+ url2.pathname = prefixed[2] ?? "/";
1700
+ const headers = new Headers(request.headers);
1701
+ if (!headers.has(NAMESPACE_HEADER)) {
1702
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
1703
+ }
1704
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
1705
+ request = new Request(url2, {
1706
+ method: request.method,
1707
+ headers,
1708
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
1709
+ signal: request.signal
1710
+ });
1711
+ }
1712
+ let namespace = control.namespaceOf(request);
1713
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
1714
+ const credential = options.credential(request);
1715
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
1716
+ if (mapped !== void 0)
1717
+ namespace = mapped;
1718
+ }
1719
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
1720
+ const at = request.headers.get(AT_HEADER) ?? void 0;
1721
+ const stamp = (response2) => {
1722
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
1723
+ try {
1724
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
1725
+ return response2;
1726
+ } catch {
1727
+ const copy = new Response(response2.body, response2);
1728
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
1729
+ return copy;
1730
+ }
1731
+ };
1732
+ const handled = await control.handle(request);
1733
+ if (handled)
1734
+ return stamp(handled);
1735
+ const started = monotonicNow();
1736
+ const url = new URL(request.url);
1737
+ const operationId = operationIdFor(request, url.pathname);
1738
+ const log = (status, faultId, response2) => {
1739
+ const noted = response2 ? responseNotes(response2) : void 0;
1740
+ const entry = {
1741
+ service: options.name,
1742
+ namespace,
1743
+ operationId,
1744
+ method: request.method,
1745
+ path: url.pathname,
1746
+ status,
1747
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
1748
+ unmatched: options.document !== void 0 && operationId === void 0,
1749
+ ...faultId !== void 0 ? { faultId } : {},
1750
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
1751
+ ...noted?.adopted ? { adopted: true } : {}
1752
+ };
1753
+ metrics.record(entry);
1754
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
1755
+ options.onLog?.(entry);
1756
+ };
1757
+ if (!NAMESPACE_PATTERN.test(namespace)) {
1758
+ log(400);
1759
+ return stamp(new Response(JSON.stringify({
1760
+ error: {
1761
+ type: "mockingbird_admin",
1762
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
1763
+ }
1764
+ }), { status: 400, headers: { "content-type": "application/json" } }));
1765
+ }
1766
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
1767
+ log(400);
1768
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
1769
+ }
1770
+ let storage;
1771
+ try {
1772
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
1773
+ const point = timeline(namespace).get(at);
1774
+ storage = physicalBranch(namespace, `at_${at}`);
1775
+ let viewRng = branchRngs.get(storage);
1776
+ if (!viewRng) {
1777
+ viewRng = createRng(options.seed ?? 0);
1778
+ instanceFor(storage, namespace, viewRng);
1779
+ }
1780
+ viewRng.setState(point.value.rngState);
1781
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1782
+ captured.set(storage, point.value.snapshot);
1783
+ } else {
1784
+ storage = ensureBranch(namespace, selectedBranch, at);
1785
+ }
1786
+ } catch (error) {
1787
+ log(409);
1788
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
1789
+ }
1790
+ const hits = await faults.take({
1791
+ operationId,
1792
+ method: request.method,
1793
+ path: url.pathname,
1794
+ namespace
1795
+ });
1796
+ const final = hits.find((hit) => hit.drop || hit.response);
1797
+ if (final?.drop) {
1798
+ log(0, final.id);
1799
+ throw new DroppedConnectionError();
1800
+ }
1801
+ if (final?.response) {
1802
+ log(final.response.status, final.id);
1803
+ return stamp(final.response);
1804
+ }
1805
+ const fired = hits.filter((hit) => hit.effect !== void 0);
1806
+ if (fired.length > 0)
1807
+ effects.set(request, fired.map((hit) => hit.effect));
1808
+ let response = await instanceFor(storage, namespace).fetch(request);
1809
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
1810
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
1811
+ response = mutableResponse(response);
1812
+ response.headers.set(CHECKPOINT_HEADER, point.id);
1813
+ }
1814
+ if (selectedBranch !== "main") {
1815
+ response = mutableResponse(response);
1816
+ response.headers.set(BRANCH_HEADER, selectedBranch);
1817
+ }
1818
+ if (at !== void 0) {
1819
+ response = mutableResponse(response);
1820
+ response.headers.set(AT_HEADER, at);
1821
+ }
1822
+ log(response.status, fired[0]?.id, response);
1823
+ return stamp(response);
1824
+ }
1825
+ };
1826
+ const control = createControlPlane({
1827
+ name: options.name,
1828
+ startedAt: wallNow(),
1829
+ wallNow,
1830
+ clock,
1831
+ faults,
1832
+ metrics,
1833
+ journal,
1834
+ defaultNamespace: DEFAULT_NAMESPACE,
1835
+ namespaces: runtime.namespaces,
1836
+ reset,
1837
+ timeTravel: {
1838
+ checkpoint: (name, branchName) => {
1839
+ const point = checkpoint(name, branchName);
1840
+ return {
1841
+ id: point.id,
1842
+ branch: point.branch,
1843
+ parent: point.parent,
1844
+ at: point.at,
1845
+ records: point.value.snapshot.records.length
1846
+ };
1847
+ },
1848
+ branch: (branchName, branchOptions) => {
1849
+ const point = branch(branchName, branchOptions);
1850
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
1851
+ },
1852
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
1853
+ retain: (name, checkpointId) => {
1854
+ timeline(name).retain(checkpointId);
1855
+ },
1856
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
1857
+ inspect: (name) => {
1858
+ const history = timeline(name);
1859
+ return {
1860
+ branches: history.branches(),
1861
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
1862
+ id,
1863
+ branch: branchName,
1864
+ parent,
1865
+ at
1866
+ }))
1867
+ };
1868
+ }
1869
+ },
1870
+ describe: options.describe ?? (() => ({})),
1871
+ ...options.presets ? {
1872
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
1873
+ } : {},
1874
+ routes: {
1875
+ ...credentialRoutes(credentials),
1876
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
1877
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1878
+ ...options.admin?.(runtime) ?? {}
1879
+ },
1880
+ adminKey: options.adminKey
1881
+ });
1882
+ return runtime;
1883
+ };
1884
+ var mutableResponse = (response) => {
1885
+ try {
1886
+ response.headers.set("x-mockingbird-mutable-probe", "1");
1887
+ response.headers.delete("x-mockingbird-mutable-probe");
1888
+ return response;
1889
+ } catch {
1890
+ return new Response(response.body, response);
1891
+ }
1892
+ };
1893
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1894
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
1895
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1896
+ var credentialRoutes = (registry) => ({
1897
+ "GET /credentials": () => adminJson(200, {
1898
+ credentials: registry.entries().map(({ credential, namespace }) => ({
1899
+ credential: maskCredential(credential),
1900
+ namespace
1901
+ }))
1902
+ }),
1903
+ "PUT /credentials": ({ body, namespace }) => {
1904
+ const pairs = [];
1905
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
1906
+ if (Array.isArray(list)) {
1907
+ for (const each of list) {
1908
+ if (typeof each === "string")
1909
+ pairs.push([each, namespace]);
1910
+ else if (isObject(each) && typeof each.credential === "string") {
1911
+ pairs.push([
1912
+ each.credential,
1913
+ typeof each.namespace === "string" ? each.namespace : namespace
1914
+ ]);
1915
+ } else
1916
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
1917
+ }
1918
+ } else if (isObject(list)) {
1919
+ for (const [credential, target] of Object.entries(list)) {
1920
+ if (typeof target !== "string")
1921
+ return adminFail(400, `namespace for ${credential} must be a string`);
1922
+ pairs.push([credential, target]);
1923
+ }
1924
+ } else if (isObject(body) && typeof body.credential === "string") {
1925
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
1926
+ } else {
1927
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
1928
+ }
1929
+ for (const [credential, target] of pairs) {
1930
+ if (!NAMESPACE_PATTERN.test(target))
1931
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
1932
+ registry.set(credential, target);
1933
+ }
1934
+ return adminJson(200, { mapped: pairs.length });
1935
+ },
1936
+ "DELETE /credentials": ({ url }) => {
1937
+ const credential = url.searchParams.get("credential");
1938
+ if (credential === null)
1939
+ registry.clear();
1940
+ else
1941
+ registry.remove(credential);
1942
+ return adminJson(200, { status: "ok" });
1943
+ }
1944
+ });
1945
+ var presetRoutes = (presets, runtime) => ({
1946
+ "GET /faults/presets": () => adminJson(200, {
1947
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
1948
+ }),
1949
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
1950
+ const name = params.name;
1951
+ if (!presets[name])
1952
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
1953
+ const overrides = isObject(body) ? body : {};
1954
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
1955
+ }
1956
+ });
1957
+
1958
+ // src/generated/openapi.ts
1959
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Payload CMS REST API (Mockingbird subset)","description":"Stateful mock subset of Payload CMS's auto-generated collection REST API: find documents\\n(with a \`where\` query subset, \`limit\`, \`page\`, \`sort\`) and find one by id. Hand-authored\\nfrom Payload's REST API docs and the consumer's response type (payload-cms-response.type.ts).\\n","version":"2","x-mockingbird-upstream":{"note":"Shapes from https://payloadcms.com/docs/rest-api/overview and https://payloadcms.com/docs/queries/overview; the consumer is apps/backend/src/modules/cms/payload-cms/payload-cms.service.ts."}},"servers":[{"url":"https://payload.gogeviti.com"}],"paths":{"/api/{collection}":{"parameters":[{"name":"collection","in":"path","required":true,"schema":{"type":"string","enum":["marketing"]}}],"get":{"operationId":"FindDocuments","description":"Paginated find. \`where[<field>][<operator>]=<value>\` supports equals, not_equals, in, not_in, exists, greater_than(_equal), less_than(_equal), like, contains, and nested \`where[and|or][<i>]\u2026\`. Only the consumer's filters are declared here for parity walks.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"where[type][equals]","in":"query","required":false,"schema":{"type":"string","enum":["referral","banner","email"]}},{"name":"where[isActive][equals]","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":100}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":20}},{"name":"sort","in":"query","required":false,"schema":{"type":"string","enum":["createdAt","-createdAt","name","-name","id","-id"]}}],"responses":{"200":{"description":"A page of documents","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaginatedDocs"}}}},"400":{"description":"Invalid query","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Errors"}}}},"404":{"description":"Unknown collection","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Errors"}}}}}}},"/api/{collection}/{id}":{"parameters":[{"name":"collection","in":"path","required":true,"schema":{"type":"string","enum":["marketing"]}},{"name":"id","in":"path","required":true,"schema":{"type":"string","description":"The seeded documents are 1-3; anything else is a 404.","pattern":"^[1-5]$"}}],"get":{"operationId":"FindDocumentById","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The document","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketingDoc"}}}},"404":{"description":"Unknown document or collection","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Errors"}}}}}}}},"components":{"schemas":{"MarketingDoc":{"type":"object","required":["id","name","type","createdAt","updatedAt"],"properties":{"id":{"type":"integer","description":"Integer ids, as Payload's Postgres adapter issues them (the consumer types \`id\` as a number)."},"name":{"type":"string"},"type":{"type":"string","enum":["referral","banner","email"]},"isActive":{"type":"boolean"},"cardTitle":{"type":["string","null"]},"cardSubtitle":{"type":["string","null"]},"cardDescription":{"type":["string","null"]},"ctaTitle":{"type":["string","null"]},"ctaActionText":{"type":["string","null"]},"shareMessage":{"type":["string","null"]},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updatedAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"PaginatedDocs":{"type":"object","required":["docs","totalDocs","limit","totalPages","page","pagingCounter","hasPrevPage","hasNextPage","prevPage","nextPage"],"properties":{"docs":{"type":"array","items":{"$ref":"#/components/schemas/MarketingDoc"}},"totalDocs":{"type":"integer"},"limit":{"type":"integer"},"totalPages":{"type":"integer"},"page":{"type":"integer"},"pagingCounter":{"type":"integer"},"hasPrevPage":{"type":"boolean"},"hasNextPage":{"type":"boolean"},"prevPage":{"type":["integer","null"]},"nextPage":{"type":["integer","null"]}}},"Errors":{"type":"object","required":["errors"],"properties":{"errors":{"type":"array","items":{"type":"object","required":["message"],"properties":{"message":{"type":"string"}}}}}}}}}`);
1960
+ var operationIds = ["FindDocuments", "FindDocumentById"];
1961
+ var supportedOperationIds = ["FindDocuments", "FindDocumentById"];
1962
+
1963
+ // src/state.ts
1964
+ var MARKETING_FIELDS = [
1965
+ "id",
1966
+ "name",
1967
+ "type",
1968
+ "isActive",
1969
+ "cardTitle",
1970
+ "cardSubtitle",
1971
+ "cardDescription",
1972
+ "ctaTitle",
1973
+ "ctaActionText",
1974
+ "shareMessage",
1975
+ "createdAt",
1976
+ "updatedAt"
1977
+ ];
1978
+ var DEFAULT_MARKETING_DOCS = [
1979
+ {
1980
+ id: 1,
1981
+ name: "Referral card (spring)",
1982
+ type: "referral",
1983
+ isActive: false,
1984
+ cardTitle: "Spring Rewards",
1985
+ cardSubtitle: "Old campaign",
1986
+ cardDescription: "An inactive card the isActive filter must skip.",
1987
+ ctaTitle: "Old CTA",
1988
+ ctaActionText: "Old action",
1989
+ shareMessage: "Old share message",
1990
+ createdAt: "2026-03-01T00:00:00.000Z",
1991
+ updatedAt: "2026-03-01T00:00:00.000Z"
1992
+ },
1993
+ {
1994
+ id: 2,
1995
+ name: "Referral card",
1996
+ type: "referral",
1997
+ isActive: true,
1998
+ cardTitle: "Give $150, Get Rewarded",
1999
+ cardSubtitle: "Refer a friend",
2000
+ cardDescription: "Share your link. Friends get $150 off their membership.",
2001
+ ctaTitle: "Share Geviti With Someone You Love",
2002
+ ctaActionText: "Invite Friends",
2003
+ shareMessage: "Join me on Geviti and get $150 off your membership.",
2004
+ createdAt: "2026-06-01T00:00:00.000Z",
2005
+ updatedAt: "2026-06-01T00:00:00.000Z"
2006
+ },
2007
+ {
2008
+ id: 3,
2009
+ name: "Home banner",
2010
+ type: "banner",
2011
+ isActive: true,
2012
+ cardTitle: "New: at-home blood draws",
2013
+ cardSubtitle: null,
2014
+ cardDescription: null,
2015
+ ctaTitle: null,
2016
+ ctaActionText: null,
2017
+ shareMessage: null,
2018
+ createdAt: "2026-07-01T00:00:00.000Z",
2019
+ updatedAt: "2026-07-01T00:00:00.000Z"
2020
+ }
2021
+ ];
2022
+ var PayloadState = class {
2023
+ constructor(sqlite, namespace, seed) {
2024
+ this.seed = seed;
2025
+ this.collections = new Collection(sqlite, namespace, "collections");
2026
+ this.ensureSeeded();
2027
+ }
2028
+ seed;
2029
+ collections;
2030
+ ensureSeeded() {
2031
+ if (this.collections.count() > 0) return;
2032
+ const seed = Object.keys(this.seed).length > 0 ? this.seed : { marketing: DEFAULT_MARKETING_DOCS };
2033
+ for (const [slug, docs] of Object.entries(seed)) this.replace(slug, docs);
2034
+ }
2035
+ get(slug) {
2036
+ return this.collections.get(slug);
2037
+ }
2038
+ replace(slug, docs) {
2039
+ const record = {
2040
+ slug,
2041
+ docs: [...docs],
2042
+ nextId: docs.reduce((max, doc) => Math.max(max, doc.id), 0) + 1
2043
+ };
2044
+ this.collections.insert(slug, record);
2045
+ return record;
2046
+ }
2047
+ save(record) {
2048
+ this.collections.insert(record.slug, record);
2049
+ }
2050
+ };
2051
+
2052
+ // src/runtime.ts
2053
+ var PAYLOAD_CMS_PRESETS = {
2054
+ server_error: {
2055
+ description: "Collection reads answer 500 {errors: [{message}]}",
2056
+ rules: [
2057
+ {
2058
+ pathPrefix: "/api/",
2059
+ status: 500,
2060
+ body: { errors: [{ message: "Something went wrong." }] }
2061
+ }
2062
+ ]
2063
+ },
2064
+ forbidden: {
2065
+ description: "Collection reads answer 403 (read access revoked)",
2066
+ rules: [
2067
+ {
2068
+ pathPrefix: "/api/",
2069
+ status: 403,
2070
+ body: { errors: [{ message: "You are not allowed to perform this action." }] }
2071
+ }
2072
+ ]
2073
+ },
2074
+ collection_not_found: {
2075
+ description: "Collection reads answer 404 (the marketing collection is missing)",
2076
+ rules: [
2077
+ {
2078
+ pathPrefix: "/api/",
2079
+ status: 404,
2080
+ body: { errors: [{ message: "The requested resource was not found." }] }
2081
+ }
2082
+ ]
2083
+ },
2084
+ no_active_docs: {
2085
+ description: "Finds answer an empty page (no active referral content)",
2086
+ rules: [{ operationId: "FindDocuments", effect: "no_active_docs" }]
2087
+ },
2088
+ malformed_json: {
2089
+ description: "Finds answer 200 with a body that is not JSON (the JSON parse throws)",
2090
+ rules: [
2091
+ {
2092
+ operationId: "FindDocuments",
2093
+ status: 200,
2094
+ body: "<!doctype html><title>Payload</title>",
2095
+ headers: { "content-type": "text/html" }
2096
+ }
2097
+ ]
2098
+ },
2099
+ unavailable: {
2100
+ description: "Every call answers a 503 HTML page from the load balancer",
2101
+ rules: [
2102
+ {
2103
+ status: 503,
2104
+ body: "<html><body>Service Unavailable</body></html>",
2105
+ headers: { "content-type": "text/html" }
2106
+ }
2107
+ ]
2108
+ },
2109
+ connection_drop: {
2110
+ description: "The connection drops before any answer (fetch rejects)",
2111
+ rules: [{ pathPrefix: "/api/", drop: true }]
2112
+ },
2113
+ slow: {
2114
+ description: "Collection reads answer after 10 s",
2115
+ rules: [{ pathPrefix: "/api/", latencyMs: 1e4 }]
2116
+ }
2117
+ };
2118
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2119
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2120
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2121
+ var toDocs = (value, now) => {
2122
+ if (!Array.isArray(value) || !value.every(isRecord4)) return "expected {docs: [{\u2026}]}";
2123
+ return value.map((doc, index) => ({
2124
+ createdAt: now,
2125
+ updatedAt: now,
2126
+ ...doc,
2127
+ id: typeof doc.id === "number" ? doc.id : index + 1
2128
+ }));
2129
+ };
2130
+ var adminRoutes = (runtime) => ({
2131
+ "GET /collections": ({ namespace }) => json3(200, { collections: runtime.instance(namespace).collections() }),
2132
+ "GET /collections/:slug": ({ params, namespace }) => {
2133
+ const collection = runtime.instance(namespace).state.get(params.slug);
2134
+ return collection ? json3(200, collection) : adminError3(404, `no collection ${params.slug}`);
2135
+ },
2136
+ "PUT /collections/:slug": ({ params, body, namespace }) => {
2137
+ const docs = toDocs(
2138
+ isRecord4(body) ? body.docs : void 0,
2139
+ new Date(runtime.clock.now()).toISOString()
2140
+ );
2141
+ if (typeof docs === "string") return adminError3(400, docs);
2142
+ return json3(200, runtime.instance(namespace).state.replace(params.slug, docs));
2143
+ },
2144
+ "POST /collections/:slug/docs": ({ params, body, namespace }) => {
2145
+ if (!isRecord4(body)) return adminError3(400, "expected a document object");
2146
+ return json3(201, runtime.instance(namespace).addDoc(params.slug, body));
2147
+ },
2148
+ "PATCH /collections/:slug/docs/:id": ({ params, body, namespace }) => {
2149
+ if (!isRecord4(body)) return adminError3(400, "expected a partial document object");
2150
+ const doc = runtime.instance(namespace).updateDoc(params.slug, Number(params.id), body);
2151
+ return doc ? json3(200, doc) : adminError3(404, `no document ${params.slug}/${params.id}`);
2152
+ },
2153
+ "DELETE /collections/:slug/docs/:id": ({ params, namespace }) => runtime.instance(namespace).deleteDoc(params.slug, Number(params.id)) ? json3(200, { deleted: true }) : adminError3(404, `no document ${params.slug}/${params.id}`)
2154
+ });
2155
+ var createRuntime2 = (options = {}) => createRuntime({
2156
+ name: PAYLOAD_CMS_NAMESPACE,
2157
+ document,
2158
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2159
+ ...options.clock ? { clock: options.clock } : {},
2160
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2161
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2162
+ ...options.onLog ? { onLog: options.onLog } : {},
2163
+ credential: payloadCredential,
2164
+ presets: PAYLOAD_CMS_PRESETS,
2165
+ create: ({ sqlite, namespace, clock }) => new PayloadCmsAPI({
2166
+ sqlite,
2167
+ namespace,
2168
+ now: clock.now,
2169
+ ...options.collections ? { collections: options.collections } : {}
2170
+ }),
2171
+ admin: adminRoutes
2172
+ });
2173
+
2174
+ // src/index.ts
2175
+ var PAYLOAD_CMS_NAMESPACE = "payload-cms";
2176
+ var payloadError = (status, message) => jsonRes(status, { errors: [{ message }] });
2177
+ var NOT_FOUND = "The requested resource was not found.";
2178
+ var payloadCredential = (request) => {
2179
+ const header = request.headers.get("authorization") ?? "";
2180
+ const apiKey = /^\S+\s+API-Key\s+(.+)$/i.exec(header.trim())?.[1];
2181
+ return apiKey?.trim() || bearerToken(request);
2182
+ };
2183
+ var OPERATORS = [
2184
+ "equals",
2185
+ "not_equals",
2186
+ "in",
2187
+ "not_in",
2188
+ "exists",
2189
+ "greater_than",
2190
+ "greater_than_equal",
2191
+ "less_than",
2192
+ "less_than_equal",
2193
+ "like",
2194
+ "contains"
2195
+ ];
2196
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2197
+ var fieldValue = (doc, path) => path.split(".").reduce((value, key) => isRecord5(value) ? value[key] : void 0, doc);
2198
+ var cast = (raw, sample) => {
2199
+ if (typeof raw !== "string") return raw;
2200
+ if (typeof sample === "boolean") return raw === "true" ? true : raw === "false" ? false : raw;
2201
+ if (typeof sample === "number" && raw.trim() !== "" && !Number.isNaN(Number(raw)))
2202
+ return Number(raw);
2203
+ if (raw === "null") return null;
2204
+ return raw;
2205
+ };
2206
+ var listOf = (raw) => Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [raw];
2207
+ var compare = (a, b) => {
2208
+ if (typeof a === "number" && typeof b === "number") return a - b;
2209
+ if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
2210
+ return void 0;
2211
+ };
2212
+ var test = (operator, actual, raw) => {
2213
+ const expected = cast(raw, actual);
2214
+ switch (operator) {
2215
+ case "equals":
2216
+ return actual === expected || actual === void 0 && expected === null;
2217
+ case "not_equals":
2218
+ return actual !== expected;
2219
+ case "in":
2220
+ return listOf(raw).some((item) => cast(item, actual) === actual);
2221
+ case "not_in":
2222
+ return !listOf(raw).some((item) => cast(item, actual) === actual);
2223
+ case "exists": {
2224
+ const present = actual !== void 0 && actual !== null;
2225
+ return raw === "false" || raw === false ? !present : present;
2226
+ }
2227
+ case "greater_than":
2228
+ return (compare(actual, expected) ?? -1) > 0;
2229
+ case "greater_than_equal":
2230
+ return (compare(actual, expected) ?? -1) >= 0;
2231
+ case "less_than":
2232
+ return (compare(actual, expected) ?? 1) < 0;
2233
+ case "less_than_equal":
2234
+ return (compare(actual, expected) ?? 1) <= 0;
2235
+ case "contains":
2236
+ return typeof actual === "string" && typeof raw === "string" && actual.toLowerCase().includes(raw.toLowerCase());
2237
+ case "like":
2238
+ return typeof actual === "string" && typeof raw === "string" && raw.toLowerCase().split(/\s+/).filter(Boolean).every((word) => actual.toLowerCase().includes(word));
2239
+ }
2240
+ };
2241
+ var compileWhere = (where, fields) => {
2242
+ if (where === void 0) return { ok: true, match: () => true };
2243
+ if (!isRecord5(where)) return { ok: false, message: "The where query is malformed." };
2244
+ const parts = [];
2245
+ for (const [key, condition] of Object.entries(where)) {
2246
+ if (key === "and" || key === "or") {
2247
+ const nested = (Array.isArray(condition) ? condition : isRecord5(condition) ? Object.values(condition) : []).map((item) => compileWhere(item, fields));
2248
+ const failed = nested.find((c) => !c.ok);
2249
+ if (failed) return failed;
2250
+ const matchers = nested.map((c) => c.match);
2251
+ parts.push(
2252
+ key === "and" ? (doc) => matchers.every((m) => m(doc)) : (doc) => matchers.length === 0 || matchers.some((m) => m(doc))
2253
+ );
2254
+ continue;
2255
+ }
2256
+ const root = key.split(".")[0];
2257
+ if (!fields.has(root)) {
2258
+ return { ok: false, message: `The following path cannot be queried: ${key}` };
2259
+ }
2260
+ if (!isRecord5(condition))
2261
+ return { ok: false, message: `The following path cannot be queried: ${key}` };
2262
+ for (const [operator, value] of Object.entries(condition)) {
2263
+ if (!OPERATORS.includes(operator)) {
2264
+ return { ok: false, message: `The following path cannot be queried: ${key}.${operator}` };
2265
+ }
2266
+ parts.push((doc) => test(operator, fieldValue(doc, key), value));
2267
+ }
2268
+ }
2269
+ return { ok: true, match: (doc) => parts.every((part) => part(doc)) };
2270
+ };
2271
+ var fieldsOf = (collection) => {
2272
+ const fields = new Set(
2273
+ collection.slug === "marketing" ? MARKETING_FIELDS : ["id", "createdAt", "updatedAt"]
2274
+ );
2275
+ for (const doc of collection.docs) for (const key of Object.keys(doc)) fields.add(key);
2276
+ return fields;
2277
+ };
2278
+ var sortDocs = (docs, sort) => {
2279
+ const descending = sort.startsWith("-");
2280
+ const field = descending ? sort.slice(1) : sort;
2281
+ return [...docs].sort((a, b) => {
2282
+ const order = compare(fieldValue(a, field), fieldValue(b, field)) ?? 0;
2283
+ return (descending ? -order : order) || b.id - a.id;
2284
+ });
2285
+ };
2286
+ var PayloadCmsAPI = class {
2287
+ app;
2288
+ sqlite;
2289
+ state;
2290
+ service;
2291
+ now;
2292
+ constructor(options = {}) {
2293
+ const sqlite = bootSqlite(options.sqlite);
2294
+ const namespace = options.namespace ?? PAYLOAD_CMS_NAMESPACE;
2295
+ this.now = options.now ?? (() => Date.now());
2296
+ this.state = new PayloadState(sqlite, namespace, options.collections ?? {});
2297
+ const handlers = defineOperations({
2298
+ FindDocuments: (context) => this.find(context),
2299
+ FindDocumentById: (context) => {
2300
+ const collection = this.state.get(context.params.collection ?? "");
2301
+ const doc = collection?.docs.find((d) => String(d.id) === context.params.id);
2302
+ if (!doc) return payloadError(404, NOT_FOUND);
2303
+ return annotateResponse(jsonRes(200, doc), { ids: { docId: String(doc.id) } });
2304
+ }
2305
+ });
2306
+ this.service = createService({
2307
+ document,
2308
+ handlers,
2309
+ sqlite,
2310
+ namespace,
2311
+ now: this.now,
2312
+ notFound: () => payloadError(404, NOT_FOUND),
2313
+ onError: (error) => {
2314
+ if (error instanceof HttpError) return error.toResponse();
2315
+ throw error;
2316
+ }
2317
+ });
2318
+ this.app = this.service.app;
2319
+ this.sqlite = this.service.sqlite;
2320
+ }
2321
+ fetch(request) {
2322
+ const url = new URL(request.url);
2323
+ const match = /^\/api\/([^/]+)(?:\/([^/]+))?\/?$/.exec(url.pathname);
2324
+ if (request.method === "GET" && match && match[1] !== "marketing" && this.state.get(match[1])) {
2325
+ return Promise.resolve(this.generic(url, match[1], match[2]));
2326
+ }
2327
+ return this.service.fetch(request);
2328
+ }
2329
+ async reset() {
2330
+ await this.service.reset();
2331
+ this.state.ensureSeeded();
2332
+ }
2333
+ generic(url, slug, id) {
2334
+ const collection = this.state.get(slug);
2335
+ if (id === void 0) {
2336
+ return this.page(collection, decodeFormPairs(url.searchParams.entries()));
2337
+ }
2338
+ const doc = collection.docs.find((d) => String(d.id) === id);
2339
+ return doc ? jsonRes(200, doc) : payloadError(404, NOT_FOUND);
2340
+ }
2341
+ find(context) {
2342
+ const collection = this.state.get(context.params.collection ?? "");
2343
+ if (!collection) return payloadError(404, NOT_FOUND);
2344
+ return this.page(collection, context.query, context.request);
2345
+ }
2346
+ page(collection, query, request) {
2347
+ const limitResult = query.limit === void 0 ? void 0 : coerce.integer(query.limit);
2348
+ const pageResult = query.page === void 0 ? void 0 : coerce.integer(query.page);
2349
+ const limit = limitResult?.ok ? Math.max(0, limitResult.value) : 10;
2350
+ const page = pageResult?.ok ? Math.max(1, pageResult.value) : 1;
2351
+ const compiled = compileWhere(query.where, fieldsOf(collection));
2352
+ if (!compiled.ok) return payloadError(400, compiled.message);
2353
+ const sort = typeof query.sort === "string" && query.sort.length > 0 ? query.sort : "-createdAt";
2354
+ const empty = request !== void 0 && faultEffect(request, "no_active_docs") !== void 0;
2355
+ const matching = empty ? [] : sortDocs(collection.docs.filter(compiled.match), sort);
2356
+ const totalDocs = matching.length;
2357
+ const size = limit === 0 ? Math.max(totalDocs, 1) : limit;
2358
+ const totalPages = Math.max(1, Math.ceil(totalDocs / size));
2359
+ const docs = matching.slice((page - 1) * size, page * size);
2360
+ return annotateResponse(
2361
+ jsonRes(200, {
2362
+ docs,
2363
+ totalDocs,
2364
+ limit,
2365
+ totalPages,
2366
+ page,
2367
+ pagingCounter: (page - 1) * size + 1,
2368
+ hasPrevPage: page > 1,
2369
+ hasNextPage: page < totalPages,
2370
+ prevPage: page > 1 ? page - 1 : null,
2371
+ nextPage: page < totalPages ? page + 1 : null
2372
+ }),
2373
+ { ids: Object.fromEntries(docs.slice(0, 5).map((doc, i) => [`doc${i}`, String(doc.id)])) }
2374
+ );
2375
+ }
2376
+ /** Add a document the way Payload's create would: next integer id, timestamps from the mock clock. */
2377
+ addDoc(slug, fields) {
2378
+ const collection = this.state.get(slug) ?? { slug, docs: [], nextId: 1 };
2379
+ const now = new Date(this.now()).toISOString();
2380
+ const id = typeof fields.id === "number" ? fields.id : collection.nextId;
2381
+ const doc = { createdAt: now, updatedAt: now, ...fields, id };
2382
+ collection.docs = [...collection.docs.filter((d) => d.id !== id), doc];
2383
+ collection.nextId = Math.max(collection.nextId, id + 1);
2384
+ this.state.save(collection);
2385
+ return doc;
2386
+ }
2387
+ updateDoc(slug, id, patch) {
2388
+ const collection = this.state.get(slug);
2389
+ const existing = collection?.docs.find((d) => d.id === id);
2390
+ if (!collection || !existing) return void 0;
2391
+ const doc = {
2392
+ ...existing,
2393
+ ...patch,
2394
+ id,
2395
+ updatedAt: new Date(this.now()).toISOString()
2396
+ };
2397
+ collection.docs = collection.docs.map((d) => d.id === id ? doc : d);
2398
+ this.state.save(collection);
2399
+ return doc;
2400
+ }
2401
+ deleteDoc(slug, id) {
2402
+ const collection = this.state.get(slug);
2403
+ if (!collection?.docs.some((d) => d.id === id)) return false;
2404
+ collection.docs = collection.docs.filter((d) => d.id !== id);
2405
+ this.state.save(collection);
2406
+ return true;
2407
+ }
2408
+ collections() {
2409
+ return Object.fromEntries(
2410
+ this.state.collections.list({ order: "oldest" }).map((row) => [row.value.slug, row.value.docs.length])
2411
+ );
2412
+ }
2413
+ };
2414
+
2415
+ export {
2416
+ document,
2417
+ operationIds,
2418
+ supportedOperationIds,
2419
+ MARKETING_FIELDS,
2420
+ DEFAULT_MARKETING_DOCS,
2421
+ PAYLOAD_CMS_PRESETS,
2422
+ createRuntime2 as createRuntime,
2423
+ PAYLOAD_CMS_NAMESPACE,
2424
+ payloadError,
2425
+ payloadCredential,
2426
+ compileWhere,
2427
+ PayloadCmsAPI
2428
+ };
2429
+ //# sourceMappingURL=chunk-Q2QUEFCG.js.map