@crvouga/mockingbird-service-plane 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,2811 @@
1
+ // ../core/dist/clock.js
2
+ var createClock = (source = Date.now) => {
3
+ let offsetMs = 0;
4
+ let frozenAt;
5
+ const now = () => frozenAt ?? source() + offsetMs;
6
+ return {
7
+ now,
8
+ set: (epochMs) => {
9
+ if (frozenAt !== void 0)
10
+ frozenAt = epochMs;
11
+ else
12
+ offsetMs = epochMs - source();
13
+ },
14
+ advance: (deltaMs) => {
15
+ if (frozenAt !== void 0)
16
+ frozenAt += deltaMs;
17
+ else
18
+ offsetMs += deltaMs;
19
+ },
20
+ freeze: () => {
21
+ frozenAt = now();
22
+ },
23
+ unfreeze: () => {
24
+ if (frozenAt === void 0)
25
+ return;
26
+ offsetMs = frozenAt - source();
27
+ frozenAt = void 0;
28
+ },
29
+ reset: () => {
30
+ offsetMs = 0;
31
+ frozenAt = void 0;
32
+ },
33
+ state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
34
+ };
35
+ };
36
+
37
+ // ../core/dist/collection.js
38
+ var Collection = class {
39
+ sqlite;
40
+ namespace;
41
+ name;
42
+ constructor(sqlite, namespace, name) {
43
+ this.sqlite = sqlite;
44
+ this.namespace = namespace;
45
+ this.name = name;
46
+ }
47
+ bumpCollectionSeq() {
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
49
+ const next = (row?.value ?? 0) + 1;
50
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
52
+ return next;
53
+ }
54
+ nextSequence() {
55
+ return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
+ }
57
+ get(id) {
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
59
+ if (!row)
60
+ return void 0;
61
+ return JSON.parse(row.value).value;
62
+ }
63
+ has(id) {
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
65
+ return row !== void 0;
66
+ }
67
+ /** Insert a new record, assigning it the next sequence number. */
68
+ insert(id, value) {
69
+ return this.sqlite.transaction(() => {
70
+ const seq = this.bumpCollectionSeq();
71
+ const stored = { seq, value };
72
+ this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
+ VALUES (?, ?, ?, ?, ?)
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
75
+ return stored;
76
+ });
77
+ }
78
+ /** Replace an existing record's value, keeping its position. */
79
+ update(id, value) {
80
+ return this.sqlite.transaction(() => {
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
82
+ if (!row)
83
+ return void 0;
84
+ const stored = { seq: row.seq, value };
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
86
+ return stored;
87
+ });
88
+ }
89
+ delete(id) {
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
91
+ return result.changes > 0;
92
+ }
93
+ /** How many records the collection holds, without reading them. */
94
+ count() {
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
96
+ return Number(row?.n ?? 0);
97
+ }
98
+ list(options = {}) {
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
100
+ const out = [];
101
+ for (const row of rows) {
102
+ const stored = JSON.parse(row.value);
103
+ if (options.where && !options.where(stored.value, stored.seq))
104
+ continue;
105
+ out.push({ id: row.id, seq: stored.seq, value: stored.value });
106
+ }
107
+ out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
108
+ return out;
109
+ }
110
+ };
111
+
112
+ // ../core/dist/control.js
113
+ var HEALTH_PATH = "/health";
114
+ var ADMIN_PREFIX = "/__admin";
115
+ var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
116
+ var NAMESPACE_HEADER = "x-mockingbird-namespace";
117
+ var json = (status, body) => new Response(JSON.stringify(body), {
118
+ status,
119
+ headers: { "content-type": "application/json" }
120
+ });
121
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
122
+ var UNITS = {
123
+ ms: 1,
124
+ s: 1e3,
125
+ m: 6e4,
126
+ h: 36e5,
127
+ d: 864e5
128
+ };
129
+ var parseDuration = (value) => {
130
+ if (typeof value === "number" && Number.isFinite(value))
131
+ return value;
132
+ if (typeof value !== "string")
133
+ return void 0;
134
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
135
+ if (!match)
136
+ return void 0;
137
+ return Number(match[1]) * UNITS[match[2]];
138
+ };
139
+ var parseInstant = (value) => {
140
+ if (typeof value === "number" && Number.isFinite(value))
141
+ return value;
142
+ if (typeof value !== "string")
143
+ return void 0;
144
+ const parsed = Date.parse(value);
145
+ return Number.isNaN(parsed) ? void 0 : parsed;
146
+ };
147
+ var matchRoute = (pattern, path) => {
148
+ const want = pattern.split("/").filter(Boolean);
149
+ const have = path.split("/").filter(Boolean);
150
+ if (want.length !== have.length)
151
+ return void 0;
152
+ const params = {};
153
+ for (let i = 0; i < want.length; i++) {
154
+ const segment = want[i];
155
+ const actual = have[i];
156
+ if (segment.startsWith(":"))
157
+ params[segment.slice(1)] = decodeURIComponent(actual);
158
+ else if (segment !== actual)
159
+ return void 0;
160
+ }
161
+ return params;
162
+ };
163
+ var readJson = async (request) => {
164
+ const text = await request.text();
165
+ if (text.trim() === "")
166
+ return void 0;
167
+ return JSON.parse(text);
168
+ };
169
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
+ var createControlPlane = (context) => {
171
+ const snapshots = /* @__PURE__ */ new Map();
172
+ let snapshotCounter = 0;
173
+ const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
174
+ const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
175
+ const builtin = {
176
+ "GET /": () => json(200, {
177
+ service: context.name,
178
+ routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
179
+ }),
180
+ "POST /reset": async ({ url, namespace }) => {
181
+ const target = url.searchParams.get("all") === "1" ? "*" : namespace;
182
+ await context.reset(target);
183
+ return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
184
+ },
185
+ "GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
186
+ "GET /clock": () => json(200, context.clock.state()),
187
+ "POST /clock": ({ body }) => {
188
+ if (!isRecord(body))
189
+ return adminError(400, "expected a JSON object");
190
+ if (body.reset === true)
191
+ context.clock.reset();
192
+ if (body.set !== void 0) {
193
+ const instant = parseInstant(body.set);
194
+ if (instant === void 0)
195
+ return adminError(400, "set: expected epoch ms or ISO-8601");
196
+ context.clock.set(instant);
197
+ }
198
+ if (body.advance !== void 0) {
199
+ const delta = parseDuration(body.advance);
200
+ if (delta === void 0)
201
+ return adminError(400, 'advance: expected ms or "15m"-style');
202
+ context.clock.advance(delta);
203
+ }
204
+ if (body.freeze === true)
205
+ context.clock.freeze();
206
+ if (body.freeze === false)
207
+ context.clock.unfreeze();
208
+ return json(200, context.clock.state());
209
+ },
210
+ "GET /faults": () => json(200, { faults: context.faults.list() }),
211
+ "POST /faults": ({ body, namespace }) => {
212
+ if (isRecord(body) && typeof body.preset === "string") {
213
+ if (!context.applyPreset)
214
+ return adminError(400, `${context.name} has no fault presets`);
215
+ const { preset, ...overrides } = body;
216
+ try {
217
+ return json(201, {
218
+ preset,
219
+ rules: context.applyPreset(preset, namespace, overrides)
220
+ });
221
+ } catch (error) {
222
+ return adminError(404, error instanceof Error ? error.message : String(error));
223
+ }
224
+ }
225
+ if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
226
+ return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
227
+ }
228
+ const rule = {
229
+ // Scoped to the caller's namespace unless it asks for every one, so one worker's
230
+ // injected failure never lands on another's request.
231
+ namespace,
232
+ ...body,
233
+ id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
234
+ };
235
+ return json(201, context.faults.add(rule));
236
+ },
237
+ "DELETE /faults": ({ url }) => {
238
+ const id = url.searchParams.get("id");
239
+ if (id === null) {
240
+ context.faults.clear();
241
+ return json(200, { status: "ok" });
242
+ }
243
+ return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
244
+ },
245
+ "POST /snapshots": ({ namespace }) => {
246
+ const point = context.timeTravel.checkpoint(namespace, "main");
247
+ context.timeTravel.retain(namespace, point.id);
248
+ snapshotCounter++;
249
+ const id = `snap_${snapshotCounter}`;
250
+ snapshots.set(id, { namespace, checkpoint: point.id });
251
+ return json(201, { id, namespace, records: point.records ?? 0 });
252
+ },
253
+ "POST /snapshots/:id/restore": ({ params, namespace }) => {
254
+ const alias = snapshots.get(params.id);
255
+ if (!alias)
256
+ return adminError(404, `no snapshot ${params.id}`);
257
+ if (alias.namespace !== namespace) {
258
+ return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
259
+ }
260
+ context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
261
+ return json(200, { status: "ok", id: params.id, namespace });
262
+ },
263
+ "DELETE /snapshots/:id": ({ params }) => {
264
+ const id = params.id;
265
+ const alias = snapshots.get(id);
266
+ if (!alias)
267
+ return adminError(404, `no snapshot ${id}`);
268
+ snapshots.delete(id);
269
+ context.timeTravel.release(alias.namespace, alias.checkpoint);
270
+ return json(200, { status: "ok" });
271
+ },
272
+ "GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
273
+ "POST /checkpoints": ({ body, namespace }) => {
274
+ const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
275
+ try {
276
+ return json(201, context.timeTravel.checkpoint(namespace, branch));
277
+ } catch (error) {
278
+ return adminError(409, error instanceof Error ? error.message : String(error));
279
+ }
280
+ },
281
+ "POST /branches/:name": ({ params, body, namespace }) => {
282
+ const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
283
+ try {
284
+ return json(201, context.timeTravel.branch(params.name, {
285
+ namespace,
286
+ ...at !== void 0 ? { at } : {}
287
+ }));
288
+ } catch (error) {
289
+ return adminError(409, error instanceof Error ? error.message : String(error));
290
+ }
291
+ },
292
+ "POST /branches/:name/checkout": ({ params, body, namespace }) => {
293
+ if (!isRecord(body) || typeof body.checkpoint !== "string") {
294
+ return adminError(400, 'expected {"checkpoint":"cp_..."}');
295
+ }
296
+ try {
297
+ context.timeTravel.checkout(body.checkpoint, {
298
+ namespace,
299
+ branch: params.name
300
+ });
301
+ return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
302
+ } catch (error) {
303
+ return adminError(409, error instanceof Error ? error.message : String(error));
304
+ }
305
+ },
306
+ "GET /requests": ({ url, namespace }) => {
307
+ const status = url.searchParams.get("status");
308
+ const since = url.searchParams.get("since");
309
+ const limit = url.searchParams.get("limit");
310
+ const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
311
+ if (since !== null && sinceMs === void 0) {
312
+ return adminError(400, "since: expected epoch ms or ISO-8601");
313
+ }
314
+ if (status !== null && !/^\d{3}$/.test(status))
315
+ return adminError(400, "status: expected an HTTP status");
316
+ if (limit !== null && !/^\d+$/.test(limit))
317
+ return adminError(400, "limit: expected a count");
318
+ const operationId = url.searchParams.get("operationId");
319
+ const everyNamespace = url.searchParams.get("all") === "1";
320
+ return json(200, {
321
+ size: context.journal.size,
322
+ requests: context.journal.list({
323
+ ...everyNamespace ? {} : { namespace },
324
+ ...operationId !== null ? { operationId } : {},
325
+ ...status !== null ? { status: Number(status) } : {},
326
+ ...sinceMs !== void 0 ? { since: sinceMs } : {},
327
+ ...limit !== null ? { limit: Number(limit) } : {}
328
+ })
329
+ });
330
+ },
331
+ "DELETE /requests": ({ url, namespace }) => {
332
+ context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
333
+ return json(200, { status: "ok" });
334
+ },
335
+ "GET /metrics": () => json(200, context.metrics.report()),
336
+ "DELETE /metrics": () => {
337
+ context.metrics.reset();
338
+ return json(200, { status: "ok" });
339
+ }
340
+ };
341
+ const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
342
+ const space = key.indexOf(" ");
343
+ return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
344
+ });
345
+ return {
346
+ namespaceOf: headerNamespace,
347
+ async handle(request) {
348
+ const url = new URL(request.url);
349
+ if (url.pathname === HEALTH_PATH && request.method === "GET") {
350
+ return json(200, {
351
+ status: "ok",
352
+ service: context.name,
353
+ uptimeMs: context.wallNow() - context.startedAt,
354
+ clock: context.clock.state(),
355
+ namespaces: context.namespaces().length,
356
+ ...context.describe()
357
+ });
358
+ }
359
+ if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
+ return void 0;
361
+ }
362
+ if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
+ }
365
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
+ for (const route of routes) {
367
+ if (route.method !== request.method)
368
+ continue;
369
+ const params = matchRoute(route.pattern, path);
370
+ if (!params)
371
+ continue;
372
+ let body;
373
+ try {
374
+ body = await readJson(request);
375
+ } catch {
376
+ return adminError(400, "request body is not valid JSON");
377
+ }
378
+ return route.handler({
379
+ request,
380
+ url,
381
+ params,
382
+ namespace: adminNamespace(request, url),
383
+ body
384
+ });
385
+ }
386
+ return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
387
+ }
388
+ };
389
+ };
390
+
391
+ // ../core/dist/credentials.js
392
+ var createCredentialRegistry = () => {
393
+ const map = /* @__PURE__ */ new Map();
394
+ return {
395
+ set: (credential, namespace) => {
396
+ map.set(credential, namespace);
397
+ },
398
+ get: (credential) => map.get(credential),
399
+ remove: (credential) => map.delete(credential),
400
+ clear: () => map.clear(),
401
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
402
+ };
403
+ };
404
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
405
+
406
+ // ../core/dist/rng.js
407
+ var seedFrom = (value) => {
408
+ let hash = 2166136261;
409
+ for (let i = 0; i < value.length; i++) {
410
+ hash ^= value.charCodeAt(i);
411
+ hash = Math.imul(hash, 16777619);
412
+ }
413
+ return hash >>> 0;
414
+ };
415
+ var createRng = (seed = 0) => {
416
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
417
+ let state = numeric;
418
+ const next = () => {
419
+ state = state + 1831565813 >>> 0;
420
+ let t = state;
421
+ t = Math.imul(t ^ t >>> 15, t | 1);
422
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
423
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
424
+ };
425
+ return {
426
+ next,
427
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
428
+ reset: () => {
429
+ state = numeric;
430
+ },
431
+ state: () => state,
432
+ setState: (next2) => {
433
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
434
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
435
+ }
436
+ state = next2 >>> 0;
437
+ },
438
+ seed: numeric
439
+ };
440
+ };
441
+
442
+ // ../core/dist/faults.js
443
+ var matches = (rule, candidate) => {
444
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
445
+ return false;
446
+ }
447
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
448
+ return false;
449
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
450
+ return false;
451
+ }
452
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
453
+ return false;
454
+ return true;
455
+ };
456
+ var faultResponse = (rule) => {
457
+ const status = rule.status ?? 500;
458
+ const headers = { "content-type": "application/json", ...rule.headers };
459
+ if (typeof rule.body === "string")
460
+ return new Response(rule.body, { status, headers });
461
+ if (rule.body === null)
462
+ return new Response(null, { status, headers: rule.headers ?? {} });
463
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
464
+ return new Response(JSON.stringify(body), { status, headers });
465
+ };
466
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
467
+ const entries = [];
468
+ return {
469
+ add(rule) {
470
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
471
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
472
+ if (existing >= 0)
473
+ entries[existing] = entry;
474
+ else
475
+ entries.push(entry);
476
+ return rule;
477
+ },
478
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
479
+ remove(id) {
480
+ const index = entries.findIndex((e) => e.rule.id === id);
481
+ if (index < 0)
482
+ return false;
483
+ entries.splice(index, 1);
484
+ return true;
485
+ },
486
+ clear() {
487
+ entries.length = 0;
488
+ },
489
+ async take(candidate) {
490
+ const hits = [];
491
+ for (const entry of entries) {
492
+ if (entry.remaining === 0)
493
+ continue;
494
+ if (!matches(entry.rule, candidate))
495
+ continue;
496
+ const rate = entry.rule.rate ?? 1;
497
+ if (rng.next() >= rate)
498
+ continue;
499
+ entry.hits++;
500
+ if (entry.remaining !== null)
501
+ entry.remaining--;
502
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
503
+ if (delay !== void 0 && delay > 0) {
504
+ await sleep(delay);
505
+ }
506
+ const hit = { id: entry.rule.id };
507
+ if (entry.rule.effect !== void 0) {
508
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
509
+ }
510
+ if (entry.rule.drop === true)
511
+ hit.drop = true;
512
+ else if (entry.rule.status !== void 0)
513
+ hit.response = faultResponse(entry.rule);
514
+ hits.push(hit);
515
+ if (hit.drop || hit.response)
516
+ break;
517
+ }
518
+ return hits;
519
+ }
520
+ };
521
+ };
522
+
523
+ // ../../openapi/core/dist/refs.js
524
+ var OpenAPIReferenceError = class extends Error {
525
+ ref;
526
+ constructor(ref) {
527
+ super(`unresolvable $ref: ${ref}`);
528
+ this.ref = ref;
529
+ this.name = "OpenAPIReferenceError";
530
+ }
531
+ };
532
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
533
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
534
+ var resolveRef = (document2, ref) => {
535
+ if (!ref.startsWith("#/"))
536
+ throw new OpenAPIReferenceError(ref);
537
+ let cursor = document2;
538
+ for (const raw of ref.slice(2).split("/")) {
539
+ const segment = unescapePointer(raw);
540
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
541
+ throw new OpenAPIReferenceError(ref);
542
+ }
543
+ cursor = cursor[segment];
544
+ }
545
+ if (cursor === void 0)
546
+ throw new OpenAPIReferenceError(ref);
547
+ return cursor;
548
+ };
549
+ var deref = (document2, value) => {
550
+ let current = value;
551
+ const seen = /* @__PURE__ */ new Set();
552
+ while (isReference(current)) {
553
+ if (seen.has(current.$ref))
554
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
555
+ seen.add(current.$ref);
556
+ current = resolveRef(document2, current.$ref);
557
+ }
558
+ return current;
559
+ };
560
+
561
+ // ../../openapi/core/dist/types.js
562
+ var HTTP_METHODS = [
563
+ "get",
564
+ "put",
565
+ "post",
566
+ "delete",
567
+ "options",
568
+ "head",
569
+ "patch",
570
+ "trace"
571
+ ];
572
+
573
+ // ../../openapi/core/dist/document.js
574
+ var mergeParameters = (document2, item, own) => {
575
+ const merged = /* @__PURE__ */ new Map();
576
+ for (const raw of item.parameters ?? []) {
577
+ const parameter = deref(document2, raw);
578
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
579
+ }
580
+ for (const raw of own ?? []) {
581
+ const parameter = deref(document2, raw);
582
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
583
+ }
584
+ return [...merged.values()];
585
+ };
586
+ var listOperations = (document2) => {
587
+ const operations = [];
588
+ for (const [path, item] of Object.entries(document2.paths)) {
589
+ for (const method of HTTP_METHODS) {
590
+ const operation = item[method];
591
+ if (operation?.operationId === void 0)
592
+ continue;
593
+ const responses = {};
594
+ for (const [status, response] of Object.entries(operation.responses)) {
595
+ responses[status] = deref(document2, response);
596
+ }
597
+ operations.push({
598
+ operationId: operation.operationId,
599
+ method,
600
+ path,
601
+ operation,
602
+ parameters: mergeParameters(document2, item, operation.parameters),
603
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
604
+ responses
605
+ });
606
+ }
607
+ }
608
+ return operations;
609
+ };
610
+
611
+ // ../../openapi/core/dist/schema.js
612
+ var resolveSchema = (document2, schema) => {
613
+ let current = schema;
614
+ const seen = /* @__PURE__ */ new Set();
615
+ while (typeof current.$ref === "string") {
616
+ const ref = current.$ref;
617
+ if (seen.has(ref))
618
+ break;
619
+ seen.add(ref);
620
+ const { $ref: _ignored, ...siblings } = current;
621
+ const target = resolveRef(document2, ref);
622
+ current = { ...target, ...siblings };
623
+ }
624
+ if (current.nullable === true) {
625
+ const { nullable: _nullable, ...rest } = current;
626
+ const types = schemaTypes(rest);
627
+ if (types.length > 0 && !types.includes("null"))
628
+ current = { ...rest, type: [...types, "null"] };
629
+ else
630
+ current = rest;
631
+ }
632
+ return current;
633
+ };
634
+ var schemaTypes = (schema) => {
635
+ if (Array.isArray(schema.type))
636
+ return schema.type;
637
+ if (schema.type !== void 0)
638
+ return [schema.type];
639
+ const inferred = [];
640
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
641
+ inferred.push("object");
642
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
643
+ inferred.push("array");
644
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
645
+ inferred.push("string");
646
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
647
+ inferred.push("number");
648
+ return inferred;
649
+ };
650
+ var jsonTypeOf = (value) => {
651
+ if (value === null)
652
+ return "null";
653
+ if (Array.isArray(value))
654
+ return "array";
655
+ switch (typeof value) {
656
+ case "string":
657
+ return "string";
658
+ case "boolean":
659
+ return "boolean";
660
+ case "number":
661
+ return Number.isInteger(value) ? "integer" : "number";
662
+ case "object":
663
+ return "object";
664
+ default:
665
+ return "undefined";
666
+ }
667
+ };
668
+ var deepEqual = (a, b) => {
669
+ if (a === b)
670
+ return true;
671
+ if (typeof a !== typeof b || a === null || b === null)
672
+ return false;
673
+ if (Array.isArray(a)) {
674
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
675
+ }
676
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
677
+ const ka = Object.keys(a);
678
+ const kb = Object.keys(b);
679
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
680
+ }
681
+ return false;
682
+ };
683
+ var FORMAT_PATTERNS = {
684
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
685
+ date: /^\d{4}-\d{2}-\d{2}$/,
686
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
687
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
688
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
689
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
690
+ };
691
+ var graphemeLength = (value) => [...value].length;
692
+ var validateValue = (document2, schema, value, path = []) => {
693
+ const errors = [];
694
+ const s = resolveSchema(document2, schema);
695
+ const fail2 = (message) => errors.push({ path, message });
696
+ const actual = jsonTypeOf(value);
697
+ if (actual === "undefined") {
698
+ fail2("value is undefined");
699
+ return errors;
700
+ }
701
+ const types = schemaTypes(s);
702
+ if (types.length > 0) {
703
+ const ok2 = types.some((t) => t === actual || t === "number" && actual === "integer");
704
+ if (!ok2) {
705
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
706
+ return errors;
707
+ }
708
+ }
709
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
710
+ fail2("value not in enum");
711
+ }
712
+ if (s.const !== void 0 && !deepEqual(s.const, value))
713
+ fail2("value does not equal const");
714
+ if (typeof value === "string") {
715
+ const length = graphemeLength(value);
716
+ if (s.minLength !== void 0 && length < s.minLength)
717
+ fail2(`length ${length} < minLength ${s.minLength}`);
718
+ if (s.maxLength !== void 0 && length > s.maxLength)
719
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
720
+ if (s.pattern !== void 0) {
721
+ try {
722
+ if (!new RegExp(s.pattern, "u").test(value))
723
+ fail2(`does not match pattern ${s.pattern}`);
724
+ } catch {
725
+ }
726
+ }
727
+ if (s.format !== void 0) {
728
+ const pattern = FORMAT_PATTERNS[s.format];
729
+ if (pattern && !pattern.test(value))
730
+ fail2(`does not match format ${s.format}`);
731
+ }
732
+ }
733
+ if (typeof value === "number") {
734
+ if (s.minimum !== void 0 && value < s.minimum)
735
+ fail2(`${value} < minimum ${s.minimum}`);
736
+ if (s.maximum !== void 0 && value > s.maximum)
737
+ fail2(`${value} > maximum ${s.maximum}`);
738
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
739
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
740
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
741
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
742
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
743
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
744
+ }
745
+ }
746
+ if (Array.isArray(value)) {
747
+ if (s.minItems !== void 0 && value.length < s.minItems)
748
+ fail2(`${value.length} items < minItems ${s.minItems}`);
749
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
750
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
751
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
752
+ fail2("items are not unique");
753
+ value.forEach((item, i) => {
754
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
755
+ if (itemSchema)
756
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
757
+ });
758
+ }
759
+ if (actual === "object") {
760
+ const record = value;
761
+ const keys = Object.keys(record);
762
+ for (const name of s.required ?? [])
763
+ if (!(name in record))
764
+ fail2(`missing required property ${name}`);
765
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
766
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
767
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
768
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
769
+ for (const key of keys) {
770
+ const property = s.properties?.[key];
771
+ if (property) {
772
+ errors.push(...validateValue(document2, property, record[key], [...path, key]));
773
+ continue;
774
+ }
775
+ if (s.additionalProperties === false)
776
+ fail2(`unexpected property ${key}`);
777
+ else if (typeof s.additionalProperties === "object") {
778
+ errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
779
+ }
780
+ if (s.propertyNames) {
781
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
782
+ if (nameErrors.length > 0)
783
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
784
+ }
785
+ }
786
+ }
787
+ if (s.allOf)
788
+ for (const branch of s.allOf)
789
+ errors.push(...validateValue(document2, branch, value, path));
790
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
791
+ fail2("matches no anyOf branch");
792
+ if (s.oneOf) {
793
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
794
+ if (matches2 !== 1)
795
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
796
+ }
797
+ if (s.not && validateValue(document2, s.not, value).length === 0)
798
+ fail2("matches forbidden `not` schema");
799
+ return errors;
800
+ };
801
+
802
+ // ../../http/codec/dist/form.js
803
+ var parsePath = (rawKey) => {
804
+ const open = rawKey.indexOf("[");
805
+ if (open === -1)
806
+ return [rawKey];
807
+ const path = [rawKey.slice(0, open)];
808
+ const rest = rawKey.slice(open);
809
+ const pattern = /\[([^\]]*)\]/g;
810
+ let match = pattern.exec(rest);
811
+ let consumed = 0;
812
+ while (match !== null) {
813
+ if (match.index !== consumed)
814
+ return [rawKey];
815
+ path.push(match[1] ?? "");
816
+ consumed = match.index + match[0].length;
817
+ match = pattern.exec(rest);
818
+ }
819
+ if (consumed !== rest.length)
820
+ return [rawKey];
821
+ return path;
822
+ };
823
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
824
+ var put = (target, key, value) => {
825
+ if (key === "__proto__") {
826
+ Object.defineProperty(target, key, {
827
+ value,
828
+ enumerable: true,
829
+ writable: true,
830
+ configurable: true
831
+ });
832
+ return;
833
+ }
834
+ ;
835
+ target[key] = value;
836
+ };
837
+ var assign = (target, path, value) => {
838
+ let cursor = target;
839
+ for (let i = 0; i < path.length; i++) {
840
+ const segment = path[i];
841
+ const last = i === path.length - 1;
842
+ if (Array.isArray(cursor)) {
843
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
844
+ if (index === void 0)
845
+ return;
846
+ if (last) {
847
+ put(cursor, index, value);
848
+ return;
849
+ }
850
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
851
+ if (next === void 0 || typeof next === "string") {
852
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
853
+ put(cursor, index, created);
854
+ cursor = created;
855
+ } else {
856
+ cursor = next;
857
+ }
858
+ continue;
859
+ }
860
+ if (typeof cursor === "string")
861
+ return;
862
+ if (last) {
863
+ put(cursor, segment, value);
864
+ return;
865
+ }
866
+ const nextSegment = path[i + 1];
867
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
868
+ if (existing === void 0 || typeof existing === "string") {
869
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
870
+ put(cursor, segment, created);
871
+ cursor = created;
872
+ } else {
873
+ cursor = existing;
874
+ }
875
+ }
876
+ };
877
+ var decodeFormPairs = (pairs) => {
878
+ const out = {};
879
+ for (const [rawKey, value] of pairs)
880
+ assign(out, parsePath(rawKey), value);
881
+ return densify(out);
882
+ };
883
+ var densify = (value) => {
884
+ if (typeof value === "string")
885
+ return value;
886
+ if (Array.isArray(value))
887
+ return value.filter((item) => item !== void 0).map(densify);
888
+ const out = {};
889
+ for (const [key, item] of Object.entries(value))
890
+ put(out, key, densify(item));
891
+ return out;
892
+ };
893
+ var decodeForm = (text) => {
894
+ const source = text.startsWith("?") ? text.slice(1) : text;
895
+ return decodeFormPairs(new URLSearchParams(source).entries());
896
+ };
897
+
898
+ // ../../http/codec/dist/content.js
899
+ var JSON_MEDIA_TYPE = "application/json";
900
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
901
+ var mediaTypeOf = (contentType) => {
902
+ if (!contentType)
903
+ return void 0;
904
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
905
+ return essence ? essence : void 0;
906
+ };
907
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
908
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
909
+ var decodeBody = (contentType, bytes) => {
910
+ if (bytes.byteLength === 0)
911
+ return { kind: "empty" };
912
+ const mediaType = mediaTypeOf(contentType);
913
+ if (mediaType === void 0)
914
+ return { kind: "bytes", value: bytes };
915
+ if (isJsonMediaType(mediaType)) {
916
+ const text = utf8.decode(bytes);
917
+ try {
918
+ return { kind: "json", value: JSON.parse(text) };
919
+ } catch (error) {
920
+ return {
921
+ kind: "invalid",
922
+ mediaType,
923
+ text,
924
+ error: error instanceof Error ? error.message : String(error)
925
+ };
926
+ }
927
+ }
928
+ if (mediaType === FORM_MEDIA_TYPE) {
929
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
930
+ }
931
+ if (mediaType.startsWith("text/"))
932
+ return { kind: "text", value: utf8.decode(bytes) };
933
+ return { kind: "bytes", value: bytes };
934
+ };
935
+ var readBody = async (message) => {
936
+ const bytes = new Uint8Array(await message.arrayBuffer());
937
+ return decodeBody(message.headers.get("content-type"), bytes);
938
+ };
939
+
940
+ // ../core/dist/http.js
941
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
942
+ status,
943
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
944
+ });
945
+ var HttpError = class extends Error {
946
+ status;
947
+ body;
948
+ headers;
949
+ constructor(status, body, headers = {}) {
950
+ super(`HTTP ${status}`);
951
+ this.status = status;
952
+ this.body = body;
953
+ this.headers = headers;
954
+ this.name = "HttpError";
955
+ }
956
+ toResponse() {
957
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
958
+ if (contentType === "text/plain") {
959
+ return new Response(String(this.body), {
960
+ status: this.status,
961
+ headers: this.headers
962
+ });
963
+ }
964
+ return jsonRes(this.status, this.body, this.headers);
965
+ }
966
+ };
967
+ var ok = (value) => ({ ok: true, value });
968
+ var fail = (reason) => ({ ok: false, reason });
969
+ var coerce = {
970
+ string(value) {
971
+ return typeof value === "string" ? ok(value) : fail("expected a string");
972
+ },
973
+ integer(value) {
974
+ if (typeof value === "number" && Number.isInteger(value))
975
+ return ok(value);
976
+ if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
977
+ const parsed = Number(value);
978
+ return Number.isSafeInteger(parsed) ? ok(parsed) : fail("integer out of range");
979
+ }
980
+ return fail("expected an integer");
981
+ },
982
+ boolean(value) {
983
+ if (typeof value === "boolean")
984
+ return ok(value);
985
+ if (value === "true" || value === "1")
986
+ return ok(true);
987
+ if (value === "false" || value === "0")
988
+ return ok(false);
989
+ return fail("expected a boolean");
990
+ },
991
+ enumeration(value, allowed) {
992
+ const match = allowed.find((candidate) => candidate === value);
993
+ return match === void 0 ? fail(`expected one of ${allowed.join(", ")}`) : ok(match);
994
+ },
995
+ /** Flat string-to-string map, the shape of Stripe-style `metadata`. */
996
+ stringMap(value) {
997
+ if (typeof value !== "object" || value === null || Array.isArray(value))
998
+ return fail("expected an object");
999
+ const out = {};
1000
+ for (const [key, item] of Object.entries(value)) {
1001
+ if (typeof item !== "string")
1002
+ return fail(`expected a string at ${key}`);
1003
+ out[key] = item;
1004
+ }
1005
+ return ok(out);
1006
+ }
1007
+ };
1008
+
1009
+ // ../core/dist/ids.js
1010
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1011
+ var mix = (input) => {
1012
+ let hash = 2166136261;
1013
+ for (let i = 0; i < input.length; i++) {
1014
+ hash ^= input.charCodeAt(i);
1015
+ hash = Math.imul(hash, 16777619) >>> 0;
1016
+ }
1017
+ hash ^= hash >>> 16;
1018
+ hash = Math.imul(hash, 2246822507) >>> 0;
1019
+ hash ^= hash >>> 13;
1020
+ return hash >>> 0;
1021
+ };
1022
+ var opaqueToken = (input, length) => {
1023
+ let out = "";
1024
+ let round = 0;
1025
+ while (out.length < length) {
1026
+ let hash = mix(`${input}:${round++}`);
1027
+ for (let i = 0; i < 5 && out.length < length; i++) {
1028
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1029
+ hash = Math.floor(hash / ALPHABET.length);
1030
+ }
1031
+ }
1032
+ return out;
1033
+ };
1034
+ var IdSequence = class {
1035
+ sqlite;
1036
+ namespace;
1037
+ salt;
1038
+ constructor(sqlite, namespace, salt = "mockingbird") {
1039
+ this.sqlite = sqlite;
1040
+ this.namespace = namespace;
1041
+ this.salt = salt;
1042
+ }
1043
+ next(prefix, length = 14) {
1044
+ return this.sqlite.transaction(() => {
1045
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
1046
+ const value = (row?.value ?? 0) + 1;
1047
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
1048
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
1049
+ return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
1050
+ });
1051
+ }
1052
+ };
1053
+
1054
+ // ../core/dist/journal.js
1055
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1056
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1057
+ const capacity = Math.max(0, Math.floor(size));
1058
+ const rings = /* @__PURE__ */ new Map();
1059
+ let sequence = 0;
1060
+ const order = /* @__PURE__ */ new WeakMap();
1061
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1062
+ return {
1063
+ size: capacity,
1064
+ record(entry) {
1065
+ if (capacity === 0)
1066
+ return;
1067
+ order.set(entry, sequence++);
1068
+ let ring = rings.get(entry.namespace);
1069
+ if (!ring) {
1070
+ ring = { entries: [], next: 0 };
1071
+ rings.set(entry.namespace, ring);
1072
+ }
1073
+ if (ring.entries.length < capacity)
1074
+ ring.entries.push(entry);
1075
+ else {
1076
+ ring.entries[ring.next] = entry;
1077
+ ring.next = (ring.next + 1) % capacity;
1078
+ }
1079
+ },
1080
+ list(query = {}) {
1081
+ 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));
1082
+ 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));
1083
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1084
+ },
1085
+ clear(namespace) {
1086
+ if (namespace === void 0)
1087
+ rings.clear();
1088
+ else
1089
+ rings.delete(namespace);
1090
+ }
1091
+ };
1092
+ };
1093
+ var notes = /* @__PURE__ */ new WeakMap();
1094
+ var annotateResponse = (response, extra) => {
1095
+ const existing = notes.get(response);
1096
+ notes.set(response, {
1097
+ ...existing,
1098
+ ...extra,
1099
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1100
+ });
1101
+ return response;
1102
+ };
1103
+ var responseNotes = (response) => notes.get(response);
1104
+
1105
+ // ../core/dist/metrics.js
1106
+ var createMetrics = () => {
1107
+ let requests = 0;
1108
+ let faults = 0;
1109
+ let totalDurationMs = 0;
1110
+ const byOperation = /* @__PURE__ */ new Map();
1111
+ const unmatched = /* @__PURE__ */ new Map();
1112
+ return {
1113
+ record(entry) {
1114
+ requests++;
1115
+ totalDurationMs += entry.durationMs;
1116
+ if (entry.faultId !== void 0)
1117
+ faults++;
1118
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1119
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1120
+ if (entry.unmatched) {
1121
+ const route = `${entry.method} ${entry.path}`;
1122
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1123
+ }
1124
+ },
1125
+ report: () => ({
1126
+ requests,
1127
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1128
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1129
+ const space = route.indexOf(" ");
1130
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1131
+ }),
1132
+ faults,
1133
+ totalDurationMs
1134
+ }),
1135
+ reset() {
1136
+ requests = 0;
1137
+ faults = 0;
1138
+ totalDurationMs = 0;
1139
+ byOperation.clear();
1140
+ unmatched.clear();
1141
+ }
1142
+ };
1143
+ };
1144
+
1145
+ // ../../core/dist/timeline.js
1146
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1147
+ var Timeline = class {
1148
+ maxCheckpoints;
1149
+ now;
1150
+ makeId;
1151
+ nodes = /* @__PURE__ */ new Map();
1152
+ heads = /* @__PURE__ */ new Map();
1153
+ /** Unreferenced nodes in the exact order they became collectible. */
1154
+ evictable = /* @__PURE__ */ new Set();
1155
+ /** Branch heads plus explicit retainers. Absent means zero. */
1156
+ references = /* @__PURE__ */ new Map();
1157
+ explicitPins = /* @__PURE__ */ new Map();
1158
+ sequence = 0;
1159
+ constructor(options = {}) {
1160
+ const max = options.maxCheckpoints ?? 1e3;
1161
+ if (!Number.isSafeInteger(max) || max < 1)
1162
+ throw new RangeError("maxCheckpoints must be a positive integer");
1163
+ this.maxCheckpoints = max;
1164
+ this.now = options.now ?? (() => this.sequence);
1165
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1166
+ }
1167
+ /** Capture a new immutable value and move `branch` to it. */
1168
+ commit(value, options = {}) {
1169
+ const branch = options.branch ?? "main";
1170
+ this.assertBranch(branch);
1171
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1172
+ if (parent !== null && !this.nodes.has(parent))
1173
+ throw new RangeError(`no checkpoint ${parent}`);
1174
+ const id = this.makeId(++this.sequence);
1175
+ if (this.nodes.has(id))
1176
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1177
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1178
+ this.nodes.set(id, checkpoint);
1179
+ this.moveHead(branch, id);
1180
+ this.collect(this.maxCheckpoints);
1181
+ return checkpoint;
1182
+ }
1183
+ /** Create a branch pointer without copying its checkpoint value. */
1184
+ fork(branch, options = {}) {
1185
+ this.assertBranch(branch);
1186
+ if (this.heads.has(branch))
1187
+ throw new RangeError(`branch already exists: ${branch}`);
1188
+ const from = options.from ?? this.heads.get("main");
1189
+ if (from === void 0)
1190
+ return void 0;
1191
+ const checkpoint = this.get(from);
1192
+ this.moveHead(branch, checkpoint.id);
1193
+ return checkpoint;
1194
+ }
1195
+ /** Move a branch pointer to an existing checkpoint. */
1196
+ checkout(branch, id) {
1197
+ this.assertBranch(branch);
1198
+ const checkpoint = this.get(id);
1199
+ this.moveHead(branch, checkpoint.id);
1200
+ return checkpoint;
1201
+ }
1202
+ get(id) {
1203
+ const checkpoint = this.nodes.get(id);
1204
+ if (!checkpoint)
1205
+ throw new RangeError(`no checkpoint ${id}`);
1206
+ return checkpoint;
1207
+ }
1208
+ head(branch = "main") {
1209
+ const id = this.heads.get(branch);
1210
+ return id === void 0 ? void 0 : this.get(id);
1211
+ }
1212
+ hasBranch(branch) {
1213
+ return this.heads.has(branch);
1214
+ }
1215
+ branches() {
1216
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1217
+ }
1218
+ checkpoints() {
1219
+ return [...this.nodes.values()];
1220
+ }
1221
+ /** Number of retained checkpoints without allocating an array. */
1222
+ get size() {
1223
+ return this.nodes.size;
1224
+ }
1225
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1226
+ retain(id) {
1227
+ const checkpoint = this.get(id);
1228
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1229
+ this.addReference(id);
1230
+ return checkpoint;
1231
+ }
1232
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1233
+ release(id) {
1234
+ if (!this.nodes.has(id))
1235
+ return false;
1236
+ const pins = this.explicitPins.get(id) ?? 0;
1237
+ if (pins === 0)
1238
+ return false;
1239
+ if (pins === 1)
1240
+ this.explicitPins.delete(id);
1241
+ else
1242
+ this.explicitPins.set(id, pins - 1);
1243
+ this.removeReference(id);
1244
+ this.collect(this.maxCheckpoints);
1245
+ return true;
1246
+ }
1247
+ deleteBranch(branch) {
1248
+ if (branch === "main")
1249
+ throw new RangeError("cannot delete main branch");
1250
+ const previous = this.heads.get(branch);
1251
+ const deleted = this.heads.delete(branch);
1252
+ if (previous !== void 0)
1253
+ this.removeReference(previous);
1254
+ this.collect(this.maxCheckpoints);
1255
+ return deleted;
1256
+ }
1257
+ /**
1258
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1259
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1260
+ * storage dependency, so a retained node remains usable after pruning.
1261
+ */
1262
+ gc(max = this.maxCheckpoints) {
1263
+ if (!Number.isSafeInteger(max) || max < 1)
1264
+ throw new RangeError("max must be a positive integer");
1265
+ const removed = [];
1266
+ this.collect(max, removed);
1267
+ return removed;
1268
+ }
1269
+ collect(max, removed) {
1270
+ while (this.nodes.size > max && this.evictable.size > 0) {
1271
+ const id = this.evictable.values().next().value;
1272
+ this.evictable.delete(id);
1273
+ this.nodes.delete(id);
1274
+ removed?.push(id);
1275
+ }
1276
+ }
1277
+ moveHead(branch, id) {
1278
+ const previous = this.heads.get(branch);
1279
+ if (previous === id)
1280
+ return;
1281
+ if (previous !== void 0)
1282
+ this.removeReference(previous);
1283
+ this.heads.set(branch, id);
1284
+ this.addReference(id);
1285
+ }
1286
+ addReference(id) {
1287
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1288
+ this.evictable.delete(id);
1289
+ }
1290
+ removeReference(id) {
1291
+ const next = (this.references.get(id) ?? 0) - 1;
1292
+ if (next > 0)
1293
+ this.references.set(id, next);
1294
+ else {
1295
+ this.references.delete(id);
1296
+ if (this.nodes.has(id))
1297
+ this.evictable.add(id);
1298
+ }
1299
+ }
1300
+ assertBranch(branch) {
1301
+ if (!BRANCH_PATTERN.test(branch))
1302
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1303
+ }
1304
+ };
1305
+
1306
+ // ../../sqlite/dist/default.js
1307
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1308
+ var createDefaultSqlite = () => new Database();
1309
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1310
+
1311
+ // ../../sqlite/dist/migrate.js
1312
+ var ensureMigrationsTable = (sqlite) => {
1313
+ sqlite.exec(`
1314
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1315
+ id TEXT PRIMARY KEY NOT NULL,
1316
+ applied_at INTEGER NOT NULL
1317
+ )
1318
+ `);
1319
+ };
1320
+ var migrate = (sqlite, migrations) => {
1321
+ ensureMigrationsTable(sqlite);
1322
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1323
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1324
+ if (pending.length === 0)
1325
+ return;
1326
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1327
+ const now = Math.floor(Date.now() / 1e3);
1328
+ sqlite.transaction(() => {
1329
+ for (const migration of pending) {
1330
+ sqlite.exec(migration.sql);
1331
+ insert.run(migration.id, now);
1332
+ }
1333
+ });
1334
+ };
1335
+
1336
+ // ../../sqlite/dist/schema.js
1337
+ var CORE_MIGRATIONS = [
1338
+ {
1339
+ id: "20260322_core_records_sequences",
1340
+ sql: `
1341
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1342
+ namespace TEXT NOT NULL,
1343
+ collection TEXT NOT NULL,
1344
+ id TEXT NOT NULL,
1345
+ seq INTEGER NOT NULL,
1346
+ value TEXT NOT NULL,
1347
+ PRIMARY KEY (namespace, collection, id)
1348
+ );
1349
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1350
+ ON mockingbird_records (namespace, collection, seq);
1351
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1352
+ namespace TEXT NOT NULL,
1353
+ name TEXT NOT NULL,
1354
+ kind TEXT NOT NULL,
1355
+ value INTEGER NOT NULL,
1356
+ PRIMARY KEY (namespace, name, kind)
1357
+ );
1358
+ `
1359
+ }
1360
+ ];
1361
+ var migrateCore = (sqlite) => {
1362
+ migrate(sqlite, CORE_MIGRATIONS);
1363
+ };
1364
+ var clearNamespace = (sqlite, namespace) => {
1365
+ sqlite.transaction(() => {
1366
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1367
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1368
+ });
1369
+ };
1370
+
1371
+ // ../../openapi/metadata/dist/types.js
1372
+ var EXTENSION_KEYS = {
1373
+ operation: "x-mockingbird",
1374
+ resource: "x-mockingbird-resource",
1375
+ resourceRef: "x-mockingbird-resource-ref",
1376
+ volatile: "x-mockingbird-volatile",
1377
+ scope: "x-mockingbird-scope",
1378
+ unsupported: "x-mockingbird-unsupported",
1379
+ parityHeader: "x-mockingbird-parity-header"
1380
+ };
1381
+
1382
+ // ../../openapi/metadata/dist/read.js
1383
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1384
+ var extensionOf = (holder, key) => holder[key];
1385
+ var operationMetadata = (operation) => {
1386
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1387
+ const ext = isRecord2(raw) ? raw : {};
1388
+ const supported = ext.supported ?? true;
1389
+ const parity = ext.parity ?? {};
1390
+ return {
1391
+ supported,
1392
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1393
+ parity: {
1394
+ enabled: supported && (parity.enabled ?? true),
1395
+ safe: parity.safe ?? true,
1396
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1397
+ }
1398
+ };
1399
+ };
1400
+
1401
+ // ../core/dist/service.js
1402
+ import { Hono } from "hono";
1403
+ var defineOperations = (handlers) => handlers;
1404
+ var OperationRegistryError = class extends Error {
1405
+ problems;
1406
+ constructor(problems) {
1407
+ super(`operation registry is inconsistent:
1408
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1409
+ this.problems = problems;
1410
+ this.name = "OperationRegistryError";
1411
+ }
1412
+ };
1413
+ var verifyOperations = (document2, handlers) => {
1414
+ const problems = [];
1415
+ const operations = listOperations(document2);
1416
+ const seen = /* @__PURE__ */ new Set();
1417
+ for (const operation of operations) {
1418
+ if (seen.has(operation.operationId))
1419
+ problems.push(`duplicate operationId ${operation.operationId}`);
1420
+ seen.add(operation.operationId);
1421
+ const supported = operationMetadata(operation.operation).supported;
1422
+ const handler = handlers[operation.operationId];
1423
+ if (supported && !handler)
1424
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1425
+ if (!supported && handler)
1426
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1427
+ }
1428
+ for (const id of Object.keys(handlers)) {
1429
+ if (!seen.has(id))
1430
+ problems.push(`handler ${id} has no OpenAPI operation`);
1431
+ }
1432
+ return problems;
1433
+ };
1434
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1435
+ var routeOrder = (a, b) => {
1436
+ const sa = a.path.split("/");
1437
+ const sb = b.path.split("/");
1438
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1439
+ const x = sa[i] ?? "";
1440
+ const y = sb[i] ?? "";
1441
+ const px = x.startsWith("{");
1442
+ const py = y.startsWith("{");
1443
+ if (px !== py)
1444
+ return px ? 1 : -1;
1445
+ if (x !== y)
1446
+ return x < y ? -1 : 1;
1447
+ }
1448
+ return 0;
1449
+ };
1450
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1451
+ var bootSqlite = (sqlite) => {
1452
+ const client = resolveSqlite(sqlite);
1453
+ migrateCore(client);
1454
+ return client;
1455
+ };
1456
+ var createService = (options) => {
1457
+ const problems = verifyOperations(options.document, options.handlers);
1458
+ if (problems.length > 0)
1459
+ throw new OperationRegistryError(problems);
1460
+ migrateCore(options.sqlite);
1461
+ const now = options.now ?? (() => Date.now());
1462
+ const app = new Hono();
1463
+ app.notFound((c) => options.notFound(c.req.raw));
1464
+ app.onError((error, c) => options.onError(error, c.req.raw));
1465
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1466
+ for (const operation of operations) {
1467
+ const metadata = operationMetadata(operation.operation);
1468
+ const handler = options.handlers[operation.operationId];
1469
+ const route = async (c) => {
1470
+ const request = c.req.raw;
1471
+ if (!metadata.supported || !handler) {
1472
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1473
+ }
1474
+ const url = new URL(request.url);
1475
+ const context = {
1476
+ request,
1477
+ url,
1478
+ params: c.req.param(),
1479
+ query: queryOf(url),
1480
+ body: await readBody(request),
1481
+ sqlite: options.sqlite,
1482
+ namespace: options.namespace,
1483
+ operation,
1484
+ document: options.document,
1485
+ now
1486
+ };
1487
+ const short = await options.before?.(context);
1488
+ if (short)
1489
+ return short;
1490
+ return handler(context);
1491
+ };
1492
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1493
+ }
1494
+ return {
1495
+ app,
1496
+ sqlite: options.sqlite,
1497
+ namespace: options.namespace,
1498
+ fetch: async (request) => app.fetch(request),
1499
+ reset: async () => {
1500
+ clearNamespace(options.sqlite, options.namespace);
1501
+ }
1502
+ };
1503
+ };
1504
+
1505
+ // ../core/dist/snapshot.js
1506
+ var snapshotNamespace = (sqlite, namespace) => ({
1507
+ namespace,
1508
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1509
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1510
+ });
1511
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1512
+ sqlite.transaction(() => {
1513
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1514
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1515
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1516
+ for (const row of snapshot.records) {
1517
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1518
+ }
1519
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1520
+ for (const row of snapshot.sequences) {
1521
+ sequence.run(namespace, row.name, row.kind, row.value);
1522
+ }
1523
+ });
1524
+ };
1525
+
1526
+ // ../core/dist/version.js
1527
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1528
+
1529
+ // ../core/dist/webhooks.js
1530
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1531
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1532
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1533
+ var parseEndpoint = (value) => {
1534
+ if (!isRecord3(value) || typeof value.url !== "string")
1535
+ return "each endpoint needs a url";
1536
+ try {
1537
+ new URL(value.url);
1538
+ } catch {
1539
+ return `not a URL: ${value.url}`;
1540
+ }
1541
+ const endpoint = { url: value.url };
1542
+ if (typeof value.id === "string")
1543
+ endpoint.id = value.id;
1544
+ if (typeof value.secret === "string")
1545
+ endpoint.secret = value.secret;
1546
+ if (typeof value.signUrl === "string")
1547
+ endpoint.signUrl = value.signUrl;
1548
+ const events = value.events ?? value.enabledEvents;
1549
+ if (Array.isArray(events))
1550
+ endpoint.events = events.map(String);
1551
+ if (isRecord3(value.tags)) {
1552
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1553
+ }
1554
+ if (typeof value.account === "string")
1555
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1556
+ if (isRecord3(value.headers)) {
1557
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1558
+ }
1559
+ return endpoint;
1560
+ };
1561
+ var webhookAdminRoutes = (hub) => ({
1562
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1563
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1564
+ const type = url.searchParams.get("type");
1565
+ return type === null || d.type === type;
1566
+ })
1567
+ }),
1568
+ "GET /webhooks/events": ({ url, namespace }) => {
1569
+ const type = url.searchParams.get("type");
1570
+ return json2(200, {
1571
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1572
+ });
1573
+ },
1574
+ "POST /webhooks/:id/replay": async ({ params }) => {
1575
+ const replayed = await hub.replay(params.id);
1576
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1577
+ },
1578
+ "POST /webhooks/flush": async () => {
1579
+ await hub.flush();
1580
+ return json2(200, { status: "ok" });
1581
+ },
1582
+ "POST /webhooks/faults": ({ body, namespace }) => {
1583
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1584
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1585
+ }
1586
+ const fault = { mode: body.mode };
1587
+ if (typeof body.count === "number")
1588
+ fault.count = body.count;
1589
+ hub.fault(namespace, fault);
1590
+ return json2(201, { namespace, ...fault });
1591
+ },
1592
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1593
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1594
+ ...rest,
1595
+ secret: secret ? "(set)" : null
1596
+ }))
1597
+ }),
1598
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1599
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1600
+ if (!Array.isArray(list))
1601
+ return adminError2(400, "expected [{url, secret?, events?}]");
1602
+ const parsed = [];
1603
+ for (const each of list) {
1604
+ const endpoint = parseEndpoint(each);
1605
+ if (typeof endpoint === "string")
1606
+ return adminError2(400, endpoint);
1607
+ parsed.push(endpoint);
1608
+ }
1609
+ const set = hub.setEndpoints(namespace, parsed);
1610
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1611
+ },
1612
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1613
+ hub.setEndpoints(namespace, []);
1614
+ return json2(200, { status: "ok" });
1615
+ }
1616
+ });
1617
+ var parsePayload = (message) => {
1618
+ if (message.contentType.startsWith("application/json")) {
1619
+ try {
1620
+ return JSON.parse(message.body);
1621
+ } catch {
1622
+ return message.body;
1623
+ }
1624
+ }
1625
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1626
+ return Object.fromEntries(new URLSearchParams(message.body));
1627
+ }
1628
+ return message.body;
1629
+ };
1630
+
1631
+ // ../core/dist/runtime.js
1632
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1633
+ var BRANCH_HEADER = "x-mockingbird-branch";
1634
+ var AT_HEADER = "x-mockingbird-at";
1635
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1636
+ var DEFAULT_NAMESPACE = "default";
1637
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1638
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1639
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1640
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1641
+ var effects = /* @__PURE__ */ new WeakMap();
1642
+ var reuseSorted = (fresh, previous, compare, equal) => {
1643
+ if (!previous || previous.length === 0)
1644
+ return fresh.map((row) => Object.freeze(row));
1645
+ const result = new Array(fresh.length);
1646
+ let unchanged = fresh.length === previous.length;
1647
+ let oldIndex = 0;
1648
+ for (let index = 0; index < fresh.length; index++) {
1649
+ const row = fresh[index];
1650
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1651
+ oldIndex++;
1652
+ }
1653
+ const old = previous[oldIndex];
1654
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1655
+ if (result[index] !== previous[index])
1656
+ unchanged = false;
1657
+ }
1658
+ return unchanged ? previous : result;
1659
+ };
1660
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1661
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1662
+ var DroppedConnectionError = class extends TypeError {
1663
+ code = "MOCKINGBIRD_DROP";
1664
+ constructor() {
1665
+ super("fetch failed: connection dropped by Mockingbird fault");
1666
+ this.name = "TypeError";
1667
+ }
1668
+ };
1669
+ var operationMatcher = (document2) => {
1670
+ const matchers = listOperations(document2).map((operation) => ({
1671
+ operationId: operation.operationId,
1672
+ method: operation.method.toUpperCase(),
1673
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1674
+ params: (operation.path.match(/\{/g) ?? []).length
1675
+ })).sort((a, b) => a.params - b.params);
1676
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1677
+ };
1678
+ var createRuntime = (options) => {
1679
+ const sqlite = bootSqlite(options.sqlite);
1680
+ const clock = options.clock ?? createClock();
1681
+ const rng = createRng(options.seed ?? 0);
1682
+ const wallNow = options.io?.wallNow ?? Date.now;
1683
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1684
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1685
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1686
+ const metrics = createMetrics();
1687
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1688
+ const version = options.version ?? PACKAGE_VERSION;
1689
+ const instances = /* @__PURE__ */ new Map();
1690
+ const publicNamespaces = /* @__PURE__ */ new Set();
1691
+ const branchRngs = /* @__PURE__ */ new Map();
1692
+ const timelines = /* @__PURE__ */ new Map();
1693
+ const branchStorage = /* @__PURE__ */ new Map();
1694
+ const captured = /* @__PURE__ */ new Map();
1695
+ const credentials = createCredentialRegistry();
1696
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
1697
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
1698
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
1699
+ const existing = instances.get(key);
1700
+ if (existing)
1701
+ return existing;
1702
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
1703
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
1704
+ }
1705
+ const created = options.create({
1706
+ namespace: storageNamespace(key),
1707
+ publicNamespace,
1708
+ sqlite,
1709
+ clock,
1710
+ rng: isolatedRng ?? rng
1711
+ });
1712
+ instances.set(key, created);
1713
+ publicNamespaces.add(publicNamespace);
1714
+ if (isolatedRng)
1715
+ branchRngs.set(key, isolatedRng);
1716
+ return created;
1717
+ };
1718
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
1719
+ const capture = (storage) => {
1720
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
1721
+ const previous = captured.get(storage);
1722
+ const snapshot2 = {
1723
+ namespace: fresh.namespace,
1724
+ 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),
1725
+ 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)
1726
+ };
1727
+ Object.freeze(snapshot2.records);
1728
+ Object.freeze(snapshot2.sequences);
1729
+ Object.freeze(snapshot2);
1730
+ captured.set(storage, snapshot2);
1731
+ return Object.freeze({
1732
+ snapshot: snapshot2,
1733
+ clock: Object.freeze(clock.state()),
1734
+ rngState: (branchRngs.get(storage) ?? rng).state()
1735
+ });
1736
+ };
1737
+ const timeline = (name = DEFAULT_NAMESPACE) => {
1738
+ let found = timelines.get(name);
1739
+ if (found)
1740
+ return found;
1741
+ instance(name);
1742
+ found = new Timeline({
1743
+ now: clock.now,
1744
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
1745
+ });
1746
+ found.commit(capture(name));
1747
+ timelines.set(name, found);
1748
+ return found;
1749
+ };
1750
+ const physicalBranch = (namespace, branch2) => {
1751
+ if (branch2 === "main")
1752
+ return namespace;
1753
+ const mapKey = `${namespace}\0${branch2}`;
1754
+ const existing = branchStorage.get(mapKey);
1755
+ if (existing)
1756
+ return existing;
1757
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
1758
+ branchStorage.set(mapKey, key);
1759
+ return key;
1760
+ };
1761
+ const ensureBranch = (namespace, branch2, at) => {
1762
+ if (!BRANCH_PATTERN2.test(branch2))
1763
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1764
+ const history = timeline(namespace);
1765
+ if (branch2 === "main") {
1766
+ if (at !== void 0) {
1767
+ const point = history.checkout("main", at);
1768
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1769
+ captured.set(namespace, point.value.snapshot);
1770
+ rng.setState(point.value.rngState);
1771
+ clock.set(point.value.clock.now);
1772
+ if (point.value.clock.frozen)
1773
+ clock.freeze();
1774
+ else
1775
+ clock.unfreeze();
1776
+ }
1777
+ return namespace;
1778
+ }
1779
+ const storage = physicalBranch(namespace, branch2);
1780
+ if (!history.hasBranch(branch2)) {
1781
+ if (at === void 0)
1782
+ history.commit(capture(namespace));
1783
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
1784
+ const branchRng = createRng(options.seed ?? 0);
1785
+ if (point)
1786
+ branchRng.setState(point.value.rngState);
1787
+ instanceFor(storage, namespace, branchRng);
1788
+ if (point)
1789
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1790
+ if (point)
1791
+ captured.set(storage, point.value.snapshot);
1792
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1793
+ const point = history.checkout(branch2, at);
1794
+ if (!instances.has(storage)) {
1795
+ const branchRng = createRng(options.seed ?? 0);
1796
+ branchRng.setState(point.value.rngState);
1797
+ instanceFor(storage, namespace, branchRng);
1798
+ }
1799
+ branchRngs.get(storage)?.setState(point.value.rngState);
1800
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1801
+ captured.set(storage, point.value.snapshot);
1802
+ } else {
1803
+ if (!instances.has(storage)) {
1804
+ const point = history.head(branch2);
1805
+ const branchRng = createRng(options.seed ?? 0);
1806
+ if (point)
1807
+ branchRng.setState(point.value.rngState);
1808
+ instanceFor(storage, namespace, branchRng);
1809
+ }
1810
+ }
1811
+ return storage;
1812
+ };
1813
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
1814
+ const storage = ensureBranch(namespace, branch2);
1815
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
1816
+ };
1817
+ const branch = (name, branchOptions = {}) => {
1818
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
1819
+ ensureBranch(namespace, name, branchOptions.at);
1820
+ const head = timeline(namespace).head(name);
1821
+ if (!head)
1822
+ throw new RangeError(`branch ${name} has no checkpoint`);
1823
+ return head;
1824
+ };
1825
+ const checkout = (checkpointId, checkoutOptions = {}) => {
1826
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1827
+ const branchName = checkoutOptions.branch ?? "main";
1828
+ const history = timeline(namespace);
1829
+ const point = history.checkout(branchName, checkpointId);
1830
+ const storage = ensureBranch(namespace, branchName);
1831
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1832
+ captured.set(storage, point.value.snapshot);
1833
+ clock.set(point.value.clock.now);
1834
+ if (point.value.clock.frozen)
1835
+ clock.freeze();
1836
+ else
1837
+ clock.unfreeze();
1838
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
1839
+ };
1840
+ const reset = async (name = DEFAULT_NAMESPACE) => {
1841
+ if (name === "*") {
1842
+ options.webhooks?.clear();
1843
+ for (const each of instances.values())
1844
+ await each.reset();
1845
+ timelines.clear();
1846
+ branchStorage.clear();
1847
+ branchRngs.clear();
1848
+ captured.clear();
1849
+ return;
1850
+ }
1851
+ options.webhooks?.clear(name);
1852
+ const target = instances.get(name);
1853
+ if (target)
1854
+ await target.reset();
1855
+ else
1856
+ clearNamespace(sqlite, storageNamespace(name));
1857
+ for (const [mapping, storage] of branchStorage) {
1858
+ if (!mapping.startsWith(`${name}\0`))
1859
+ continue;
1860
+ const branchInstance = instances.get(storage);
1861
+ if (branchInstance)
1862
+ await branchInstance.reset();
1863
+ else
1864
+ clearNamespace(sqlite, storageNamespace(storage));
1865
+ branchStorage.delete(mapping);
1866
+ branchRngs.delete(storage);
1867
+ captured.delete(storage);
1868
+ }
1869
+ timelines.delete(name);
1870
+ captured.delete(name);
1871
+ };
1872
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
1873
+ return checkpoint(name, "main").value.snapshot;
1874
+ };
1875
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
1876
+ instance(name);
1877
+ restoreNamespace(sqlite, storageNamespace(name), from);
1878
+ captured.set(name, from);
1879
+ const history = timelines.get(name);
1880
+ if (history)
1881
+ history.commit(capture(name), { branch: "main" });
1882
+ else
1883
+ timeline(name);
1884
+ };
1885
+ const runtime = {
1886
+ name: options.name,
1887
+ sqlite,
1888
+ clock,
1889
+ faults,
1890
+ metrics,
1891
+ journal,
1892
+ rng,
1893
+ credentials,
1894
+ webhooks: options.webhooks,
1895
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
1896
+ const preset = options.presets?.[name];
1897
+ if (!preset)
1898
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
1899
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
1900
+ namespace,
1901
+ ...rule,
1902
+ ...overrides,
1903
+ preset: name,
1904
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
1905
+ }));
1906
+ if (preset.webhook && options.webhooks) {
1907
+ options.webhooks.fault(namespace, {
1908
+ ...preset.webhook,
1909
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
1910
+ });
1911
+ }
1912
+ return added;
1913
+ },
1914
+ instance,
1915
+ namespaces: () => [...publicNamespaces].sort(),
1916
+ reset,
1917
+ snapshot,
1918
+ restore,
1919
+ checkpoint,
1920
+ branch,
1921
+ checkout,
1922
+ timeline,
1923
+ fetch: async (incoming) => {
1924
+ let request = incoming;
1925
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
1926
+ if (prefixed) {
1927
+ const url2 = new URL(request.url);
1928
+ url2.pathname = prefixed[2] ?? "/";
1929
+ const headers = new Headers(request.headers);
1930
+ if (!headers.has(NAMESPACE_HEADER)) {
1931
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
1932
+ }
1933
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
1934
+ request = new Request(url2, {
1935
+ method: request.method,
1936
+ headers,
1937
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
1938
+ signal: request.signal
1939
+ });
1940
+ }
1941
+ let namespace = control.namespaceOf(request);
1942
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
1943
+ const credential = options.credential(request);
1944
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
1945
+ if (mapped !== void 0)
1946
+ namespace = mapped;
1947
+ }
1948
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
1949
+ const at = request.headers.get(AT_HEADER) ?? void 0;
1950
+ const stamp = (response2) => {
1951
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
1952
+ try {
1953
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
1954
+ return response2;
1955
+ } catch {
1956
+ const copy = new Response(response2.body, response2);
1957
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
1958
+ return copy;
1959
+ }
1960
+ };
1961
+ const handled = await control.handle(request);
1962
+ if (handled)
1963
+ return stamp(handled);
1964
+ const started = monotonicNow();
1965
+ const url = new URL(request.url);
1966
+ const operationId = operationIdFor(request, url.pathname);
1967
+ const log = (status, faultId, response2) => {
1968
+ const noted = response2 ? responseNotes(response2) : void 0;
1969
+ const entry = {
1970
+ service: options.name,
1971
+ namespace,
1972
+ operationId,
1973
+ method: request.method,
1974
+ path: url.pathname,
1975
+ status,
1976
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
1977
+ unmatched: options.document !== void 0 && operationId === void 0,
1978
+ ...faultId !== void 0 ? { faultId } : {},
1979
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
1980
+ ...noted?.adopted ? { adopted: true } : {}
1981
+ };
1982
+ metrics.record(entry);
1983
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
1984
+ options.onLog?.(entry);
1985
+ };
1986
+ if (!NAMESPACE_PATTERN.test(namespace)) {
1987
+ log(400);
1988
+ return stamp(new Response(JSON.stringify({
1989
+ error: {
1990
+ type: "mockingbird_admin",
1991
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
1992
+ }
1993
+ }), { status: 400, headers: { "content-type": "application/json" } }));
1994
+ }
1995
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
1996
+ log(400);
1997
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
1998
+ }
1999
+ let storage;
2000
+ try {
2001
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
2002
+ const point = timeline(namespace).get(at);
2003
+ storage = physicalBranch(namespace, `at_${at}`);
2004
+ let viewRng = branchRngs.get(storage);
2005
+ if (!viewRng) {
2006
+ viewRng = createRng(options.seed ?? 0);
2007
+ instanceFor(storage, namespace, viewRng);
2008
+ }
2009
+ viewRng.setState(point.value.rngState);
2010
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2011
+ captured.set(storage, point.value.snapshot);
2012
+ } else {
2013
+ storage = ensureBranch(namespace, selectedBranch, at);
2014
+ }
2015
+ } catch (error) {
2016
+ log(409);
2017
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
2018
+ }
2019
+ const hits = await faults.take({
2020
+ operationId,
2021
+ method: request.method,
2022
+ path: url.pathname,
2023
+ namespace
2024
+ });
2025
+ const final = hits.find((hit) => hit.drop || hit.response);
2026
+ if (final?.drop) {
2027
+ log(0, final.id);
2028
+ throw new DroppedConnectionError();
2029
+ }
2030
+ if (final?.response) {
2031
+ log(final.response.status, final.id);
2032
+ return stamp(final.response);
2033
+ }
2034
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2035
+ if (fired.length > 0)
2036
+ effects.set(request, fired.map((hit) => hit.effect));
2037
+ let response = await instanceFor(storage, namespace).fetch(request);
2038
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2039
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2040
+ response = mutableResponse(response);
2041
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2042
+ }
2043
+ if (selectedBranch !== "main") {
2044
+ response = mutableResponse(response);
2045
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2046
+ }
2047
+ if (at !== void 0) {
2048
+ response = mutableResponse(response);
2049
+ response.headers.set(AT_HEADER, at);
2050
+ }
2051
+ log(response.status, fired[0]?.id, response);
2052
+ return stamp(response);
2053
+ }
2054
+ };
2055
+ const control = createControlPlane({
2056
+ name: options.name,
2057
+ startedAt: wallNow(),
2058
+ wallNow,
2059
+ clock,
2060
+ faults,
2061
+ metrics,
2062
+ journal,
2063
+ defaultNamespace: DEFAULT_NAMESPACE,
2064
+ namespaces: runtime.namespaces,
2065
+ reset,
2066
+ timeTravel: {
2067
+ checkpoint: (name, branchName) => {
2068
+ const point = checkpoint(name, branchName);
2069
+ return {
2070
+ id: point.id,
2071
+ branch: point.branch,
2072
+ parent: point.parent,
2073
+ at: point.at,
2074
+ records: point.value.snapshot.records.length
2075
+ };
2076
+ },
2077
+ branch: (branchName, branchOptions) => {
2078
+ const point = branch(branchName, branchOptions);
2079
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2080
+ },
2081
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2082
+ retain: (name, checkpointId) => {
2083
+ timeline(name).retain(checkpointId);
2084
+ },
2085
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2086
+ inspect: (name) => {
2087
+ const history = timeline(name);
2088
+ return {
2089
+ branches: history.branches(),
2090
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2091
+ id,
2092
+ branch: branchName,
2093
+ parent,
2094
+ at
2095
+ }))
2096
+ };
2097
+ }
2098
+ },
2099
+ describe: options.describe ?? (() => ({})),
2100
+ ...options.presets ? {
2101
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2102
+ } : {},
2103
+ routes: {
2104
+ ...credentialRoutes(credentials),
2105
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2106
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2107
+ ...options.admin?.(runtime) ?? {}
2108
+ },
2109
+ adminKey: options.adminKey
2110
+ });
2111
+ return runtime;
2112
+ };
2113
+ var mutableResponse = (response) => {
2114
+ try {
2115
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2116
+ response.headers.delete("x-mockingbird-mutable-probe");
2117
+ return response;
2118
+ } catch {
2119
+ return new Response(response.body, response);
2120
+ }
2121
+ };
2122
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2123
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2124
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2125
+ var credentialRoutes = (registry) => ({
2126
+ "GET /credentials": () => adminJson(200, {
2127
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2128
+ credential: maskCredential(credential),
2129
+ namespace
2130
+ }))
2131
+ }),
2132
+ "PUT /credentials": ({ body, namespace }) => {
2133
+ const pairs = [];
2134
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2135
+ if (Array.isArray(list)) {
2136
+ for (const each of list) {
2137
+ if (typeof each === "string")
2138
+ pairs.push([each, namespace]);
2139
+ else if (isObject(each) && typeof each.credential === "string") {
2140
+ pairs.push([
2141
+ each.credential,
2142
+ typeof each.namespace === "string" ? each.namespace : namespace
2143
+ ]);
2144
+ } else
2145
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2146
+ }
2147
+ } else if (isObject(list)) {
2148
+ for (const [credential, target] of Object.entries(list)) {
2149
+ if (typeof target !== "string")
2150
+ return adminFail(400, `namespace for ${credential} must be a string`);
2151
+ pairs.push([credential, target]);
2152
+ }
2153
+ } else if (isObject(body) && typeof body.credential === "string") {
2154
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2155
+ } else {
2156
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2157
+ }
2158
+ for (const [credential, target] of pairs) {
2159
+ if (!NAMESPACE_PATTERN.test(target))
2160
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2161
+ registry.set(credential, target);
2162
+ }
2163
+ return adminJson(200, { mapped: pairs.length });
2164
+ },
2165
+ "DELETE /credentials": ({ url }) => {
2166
+ const credential = url.searchParams.get("credential");
2167
+ if (credential === null)
2168
+ registry.clear();
2169
+ else
2170
+ registry.remove(credential);
2171
+ return adminJson(200, { status: "ok" });
2172
+ }
2173
+ });
2174
+ var presetRoutes = (presets, runtime) => ({
2175
+ "GET /faults/presets": () => adminJson(200, {
2176
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2177
+ }),
2178
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2179
+ const name = params.name;
2180
+ if (!presets[name])
2181
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2182
+ const overrides = isObject(body) ? body : {};
2183
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2184
+ }
2185
+ });
2186
+
2187
+ // ../core/dist/validation.js
2188
+ var bodyIssues = (context, contentType = "application/json") => {
2189
+ const requestBody = context.operation.operation.requestBody;
2190
+ if (!requestBody)
2191
+ return [];
2192
+ const resolved = deref(context.document, requestBody);
2193
+ const schema = resolved.content?.[contentType]?.schema;
2194
+ if (!schema)
2195
+ return [];
2196
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2197
+ if (context.body.kind === "invalid") {
2198
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2199
+ }
2200
+ if (value === void 0) {
2201
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2202
+ }
2203
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2204
+ };
2205
+
2206
+ // src/generated/openapi.ts
2207
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Plane REST API (Mockingbird subset)","description":"Stateful mock subset of Plane's public REST API v1 for one project: work items (cursor-paginated list, get, create, patch), comments, links, states and labels. Hand-authored from Plane's API reference and the consumer's zod schemas (plane-response.ts).\\n","version":"1","x-mockingbird-upstream":{"note":"Shapes from https://developers.plane.so/api-reference; consumer: apps/backend/src/modules/bug-reports/adapters/native-fetch-plane.adapter.ts, plane-http-client.ts, plane-response.ts."}},"servers":[{"url":"https://api.plane.so"}],"security":[{"apiKey":[]}],"paths":{"/api/v1/workspaces/{slug}/projects/{project_id}/work-items/":{"get":{"operationId":"ListWorkItems","description":"Cursor-paginated work items (\`cursor=<per_page>:<page>:<is_prev>\`).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"A page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkItemPage"}}}},"400":{"description":"Invalid cursor","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"parameters":[{"$ref":"#/components/parameters/PerPage"},{"$ref":"#/components/parameters/Cursor"},{"$ref":"#/components/parameters/OrderBy"}]},"post":{"operationId":"CreateWorkItem","description":"Create a work item.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkItem"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateWorkItemBody"}}}}},"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"}]},"/api/v1/workspaces/{slug}/projects/{project_id}/work-items/{work_item_id}/":{"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"},{"$ref":"#/components/parameters/WorkItemId"}],"get":{"operationId":"GetWorkItem","description":"One work item.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The work item","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkItem"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}}},"patch":{"operationId":"UpdateWorkItem","description":"Partial update (the consumer sends \`state\` or \`labels\`).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkItem"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateWorkItemBody"}}}}}},"/api/v1/workspaces/{slug}/projects/{project_id}/work-items/{work_item_id}/comments/":{"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"},{"$ref":"#/components/parameters/WorkItemId"}],"get":{"operationId":"ListComments","description":"Comments on a work item.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"A page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommentPage"}}}},"400":{"description":"Invalid cursor","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"parameters":[{"$ref":"#/components/parameters/PerPage"},{"$ref":"#/components/parameters/Cursor"}]},"post":{"operationId":"CreateComment","description":"Add a comment.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Comment"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCommentBody"}}}}}},"/api/v1/workspaces/{slug}/projects/{project_id}/work-items/{work_item_id}/links/":{"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"},{"$ref":"#/components/parameters/WorkItemId"}],"get":{"operationId":"ListLinks","description":"Links on a work item.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"A page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LinkPage"}}}},"400":{"description":"Invalid cursor","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"parameters":[{"$ref":"#/components/parameters/PerPage"},{"$ref":"#/components/parameters/Cursor"}]},"post":{"operationId":"CreateLink","description":"Attach a link (the same URL twice is a 400).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Link"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The URL is already linked (carries the existing link id)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"$ref":"#/components/responses/Throttled"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateLinkBody"}}}}}},"/api/v1/workspaces/{slug}/projects/{project_id}/states/":{"get":{"operationId":"ListStates","description":"The project's workflow states.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"A page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StatePage"}}}},"400":{"description":"Invalid cursor","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"parameters":[{"$ref":"#/components/parameters/PerPage"},{"$ref":"#/components/parameters/Cursor"}]},"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"}]},"/api/v1/workspaces/{slug}/projects/{project_id}/labels/":{"get":{"operationId":"ListLabels","description":"The project's labels.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"A page","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LabelPage"}}}},"400":{"description":"Invalid cursor","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/Throttled"}},"parameters":[{"$ref":"#/components/parameters/PerPage"},{"$ref":"#/components/parameters/Cursor"}]},"post":{"operationId":"CreateLabel","description":"Create a label (a duplicate name is a 409 carrying the existing id).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Label"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"Duplicate name","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"$ref":"#/components/responses/Throttled"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateLabelBody"}}}}},"parameters":[{"$ref":"#/components/parameters/Slug"},{"$ref":"#/components/parameters/ProjectId"}]}},"components":{"securitySchemes":{"apiKey":{"type":"apiKey","in":"header","name":"X-API-Key"}},"parameters":{"Slug":{"name":"slug","in":"path","required":true,"schema":{"type":"string","enum":["geviti"]}},"ProjectId":{"name":"project_id","in":"path","required":true,"schema":{"type":"string","enum":["33333333-3333-4333-8333-333333333333"]}},"WorkItemId":{"name":"work_item_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","x-mockingbird-resource-ref":{"type":"work_item","missing":"00000000-0000-4000-8000-000000000000"}}},"PerPage":{"name":"per_page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}},"Cursor":{"name":"cursor","in":"query","required":false,"schema":{"type":"string","enum":["2:0:0","2:1:0","2:2:0","100:0:0"]}},"OrderBy":{"name":"order_by","in":"query","required":false,"schema":{"type":"string","enum":["-created_at","created_at","sequence_id","-sequence_id","name","-name"]}}},"responses":{"Unauthorized":{"description":"Missing or invalid X-API-Key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"NotFound":{"description":"Unknown workspace, project or item","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"Throttled":{"description":"Rate limited (60 requests per minute per key)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}},"schemas":{"WorkItem":{"type":"object","required":["id","sequence_id","name","description_html","state","labels","priority","created_at","updated_at","project","workspace"],"properties":{"id":{"type":"string","format":"uuid","x-mockingbird-resource":{"type":"work_item","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"sequence_id":{"type":"integer"},"name":{"type":"string"},"description_html":{"type":"string"},"description_stripped":{"type":["string","null"]},"priority":{"type":"string","enum":["urgent","high","medium","low","none"]},"state":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"labels":{"type":"array","items":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}},"assignees":{"type":"array","items":{"type":"string"}},"parent":{"type":["string","null"]},"start_date":{"type":["string","null"]},"target_date":{"type":["string","null"]},"completed_at":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"archived_at":{"type":["string","null"]},"is_draft":{"type":"boolean"},"sort_order":{"type":"number"},"project":{"type":"string"},"workspace":{"type":"string"},"created_by":{"type":["string","null"]},"updated_by":{"type":["string","null"]},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"State":{"type":"object","required":["id","name","group","color","sequence","default"],"properties":{"id":{"type":"string","format":"uuid","x-mockingbird-resource":{"type":"state","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"name":{"type":"string"},"group":{"type":"string","enum":["backlog","unstarted","started","completed","cancelled","triage"]},"color":{"type":"string"},"sequence":{"type":"number"},"default":{"type":"boolean"},"description":{"type":"string"},"project":{"type":"string"},"workspace":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"Label":{"type":"object","required":["id","name","color"],"properties":{"id":{"type":"string","format":"uuid","x-mockingbird-resource":{"type":"label","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"name":{"type":"string"},"color":{"type":"string"},"description":{"type":"string"},"parent":{"type":["string","null"]},"sort_order":{"type":"number"},"project":{"type":"string"},"workspace":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"Comment":{"type":"object","required":["id","comment_html","issue","created_at"],"properties":{"id":{"type":"string","format":"uuid","x-mockingbird-volatile":{"kind":"id"}},"comment_html":{"type":"string"},"comment_stripped":{"type":"string"},"access":{"type":"string"},"issue":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"actor":{"type":["string","null"]},"project":{"type":"string"},"workspace":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"Link":{"type":"object","required":["id","url","title","issue","created_at"],"properties":{"id":{"type":"string","format":"uuid","x-mockingbird-volatile":{"kind":"id"}},"url":{"type":"string"},"title":{"type":["string","null"]},"metadata":{"type":"object"},"issue":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"project":{"type":"string"},"workspace":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"WorkItemPage":{"type":"object","required":["results","next_cursor","prev_cursor","next_page_results","prev_page_results","count","total_count","total_pages","total_results"],"properties":{"grouped_by":{"type":["string","null"]},"sub_grouped_by":{"type":["string","null"]},"total_count":{"type":"integer"},"next_cursor":{"type":"string"},"prev_cursor":{"type":"string"},"next_page_results":{"type":"boolean"},"prev_page_results":{"type":"boolean"},"count":{"type":"integer"},"total_pages":{"type":"integer"},"total_results":{"type":"integer"},"extra_stats":{"type":["object","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/WorkItem"}}}},"StatePage":{"type":"object","required":["results","next_cursor","prev_cursor","next_page_results","prev_page_results","count","total_count","total_pages","total_results"],"properties":{"grouped_by":{"type":["string","null"]},"sub_grouped_by":{"type":["string","null"]},"total_count":{"type":"integer"},"next_cursor":{"type":"string"},"prev_cursor":{"type":"string"},"next_page_results":{"type":"boolean"},"prev_page_results":{"type":"boolean"},"count":{"type":"integer"},"total_pages":{"type":"integer"},"total_results":{"type":"integer"},"extra_stats":{"type":["object","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/State"}}}},"LabelPage":{"type":"object","required":["results","next_cursor","prev_cursor","next_page_results","prev_page_results","count","total_count","total_pages","total_results"],"properties":{"grouped_by":{"type":["string","null"]},"sub_grouped_by":{"type":["string","null"]},"total_count":{"type":"integer"},"next_cursor":{"type":"string"},"prev_cursor":{"type":"string"},"next_page_results":{"type":"boolean"},"prev_page_results":{"type":"boolean"},"count":{"type":"integer"},"total_pages":{"type":"integer"},"total_results":{"type":"integer"},"extra_stats":{"type":["object","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/Label"}}}},"CommentPage":{"type":"object","required":["results","next_cursor","prev_cursor","next_page_results","prev_page_results","count","total_count","total_pages","total_results"],"properties":{"grouped_by":{"type":["string","null"]},"sub_grouped_by":{"type":["string","null"]},"total_count":{"type":"integer"},"next_cursor":{"type":"string"},"prev_cursor":{"type":"string"},"next_page_results":{"type":"boolean"},"prev_page_results":{"type":"boolean"},"count":{"type":"integer"},"total_pages":{"type":"integer"},"total_results":{"type":"integer"},"extra_stats":{"type":["object","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/Comment"}}}},"LinkPage":{"type":"object","required":["results","next_cursor","prev_cursor","next_page_results","prev_page_results","count","total_count","total_pages","total_results"],"properties":{"grouped_by":{"type":["string","null"]},"sub_grouped_by":{"type":["string","null"]},"total_count":{"type":"integer"},"next_cursor":{"type":"string"},"prev_cursor":{"type":"string"},"next_page_results":{"type":"boolean"},"prev_page_results":{"type":"boolean"},"count":{"type":"integer"},"total_pages":{"type":"integer"},"total_results":{"type":"integer"},"extra_stats":{"type":["object","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/Link"}}}},"CreateWorkItemBody":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":255},"description_html":{"type":"string","maxLength":2000},"state":{"type":"string","format":"uuid","x-mockingbird-resource-ref":{"type":"state","missing":"00000000-0000-4000-8000-000000000000"}},"labels":{"type":"array","maxItems":3,"items":{"type":"string","format":"uuid","x-mockingbird-resource-ref":{"type":"label","missing":"00000000-0000-4000-8000-000000000000"}}},"priority":{"type":"string","enum":["urgent","high","medium","low","none"]}}},"UpdateWorkItemBody":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":255},"description_html":{"type":"string","maxLength":2000},"state":{"type":"string","format":"uuid","x-mockingbird-resource-ref":{"type":"state","missing":"00000000-0000-4000-8000-000000000000"}},"labels":{"type":"array","maxItems":3,"items":{"type":"string","format":"uuid","x-mockingbird-resource-ref":{"type":"label","missing":"00000000-0000-4000-8000-000000000000"}}},"priority":{"type":"string","enum":["urgent","high","medium","low","none"]}}},"CreateCommentBody":{"type":"object","required":["comment_html"],"properties":{"comment_html":{"type":"string","minLength":1,"maxLength":2000},"access":{"type":"string","enum":["INTERNAL","EXTERNAL"]}}},"CreateLinkBody":{"type":"object","required":["url"],"properties":{"url":{"type":"string","format":"uri","pattern":"^https://","maxLength":200},"title":{"type":"string","minLength":1,"maxLength":255}}},"CreateLabelBody":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":255},"color":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$"},"description":{"type":"string","maxLength":255}}},"ErrorBody":{"type":"object","properties":{"error":{"type":"string"},"detail":{"type":"string"},"id":{"type":"string"}}},"ValidationError":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}}}`);
2208
+ var operationIds = ["ListWorkItems", "CreateWorkItem", "GetWorkItem", "UpdateWorkItem", "ListComments", "CreateComment", "ListLinks", "CreateLink", "ListStates", "ListLabels", "CreateLabel"];
2209
+ var supportedOperationIds = ["ListWorkItems", "CreateWorkItem", "GetWorkItem", "UpdateWorkItem", "ListComments", "CreateComment", "ListLinks", "CreateLink", "ListStates", "ListLabels", "CreateLabel"];
2210
+
2211
+ // src/state.ts
2212
+ var DEFAULT_SETTINGS = { apiKeys: [], rateLimitPerMinute: null, projects: [] };
2213
+ var DEFAULT_STATES = [
2214
+ { name: "Backlog", group: "backlog", color: "#A3A3A3" },
2215
+ { name: "Todo", group: "unstarted", color: "#3A3A3A" },
2216
+ { name: "In Progress", group: "started", color: "#F59E0B" },
2217
+ { name: "Done", group: "completed", color: "#16A34A" },
2218
+ { name: "Cancelled", group: "cancelled", color: "#EF4444" }
2219
+ ];
2220
+ var HEX = "0123456789abcdef";
2221
+ var uuidFrom = (input) => {
2222
+ const token = opaqueToken(input, 32);
2223
+ const hex = [...token].map((c) => HEX.charAt(c.charCodeAt(0) % 16));
2224
+ hex[12] = "4";
2225
+ hex[16] = HEX.charAt(8 + token.charCodeAt(16) % 4);
2226
+ const s = hex.join("");
2227
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
2228
+ };
2229
+ var PlaneState = class {
2230
+ constructor(sqlite, namespace, seed) {
2231
+ this.seed = seed;
2232
+ this.projects = new Collection(sqlite, namespace, "projects");
2233
+ this.states = new Collection(sqlite, namespace, "states");
2234
+ this.labels = new Collection(sqlite, namespace, "labels");
2235
+ this.items = new Collection(sqlite, namespace, "work_items");
2236
+ this.comments = new Collection(sqlite, namespace, "comments");
2237
+ this.links = new Collection(sqlite, namespace, "links");
2238
+ this.settings = new Collection(sqlite, namespace, "settings");
2239
+ this.rateLimits = new Collection(sqlite, namespace, "rate_limits");
2240
+ this.ids = new IdSequence(sqlite, namespace, "plane");
2241
+ this.ensureSeeded();
2242
+ }
2243
+ seed;
2244
+ projects;
2245
+ states;
2246
+ labels;
2247
+ items;
2248
+ comments;
2249
+ links;
2250
+ settings;
2251
+ rateLimits;
2252
+ ids;
2253
+ ensureSeeded() {
2254
+ if (!this.settings.has("settings")) {
2255
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
2256
+ }
2257
+ }
2258
+ current() {
2259
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2260
+ }
2261
+ update(patch) {
2262
+ const next = { ...this.current(), ...patch };
2263
+ this.settings.insert("settings", next);
2264
+ return next;
2265
+ }
2266
+ takeRateLimit(bucket) {
2267
+ const used = (this.rateLimits.get(bucket) ?? 0) + 1;
2268
+ if (!this.rateLimits.update(bucket, used)) this.rateLimits.insert(bucket, used);
2269
+ return used;
2270
+ }
2271
+ uuid(kind) {
2272
+ return uuidFrom(this.ids.next(`${kind}:`, 32));
2273
+ }
2274
+ };
2275
+
2276
+ // src/runtime.ts
2277
+ var API = "/api/v1/workspaces/";
2278
+ var PLANE_PRESETS = {
2279
+ rate_limited: {
2280
+ description: "Every call answers 429 Request was throttled (pass count: 2 to recover on the 3rd GET)",
2281
+ rules: [
2282
+ {
2283
+ pathPrefix: API,
2284
+ status: 429,
2285
+ body: { detail: "Request was throttled. Expected available in 60 seconds." },
2286
+ headers: { "x-ratelimit-remaining": "0" }
2287
+ }
2288
+ ]
2289
+ },
2290
+ server_error: {
2291
+ description: "Every call answers 500",
2292
+ rules: [
2293
+ {
2294
+ pathPrefix: API,
2295
+ status: 500,
2296
+ body: { error: "Something went wrong please try again later" }
2297
+ }
2298
+ ]
2299
+ },
2300
+ bad_gateway: {
2301
+ description: "Every call answers a 502 HTML page",
2302
+ rules: [
2303
+ {
2304
+ pathPrefix: API,
2305
+ status: 502,
2306
+ body: "<html><body>502 Bad Gateway</body></html>",
2307
+ headers: { "content-type": "text/html" }
2308
+ }
2309
+ ]
2310
+ },
2311
+ unauthorized: {
2312
+ description: "Every call answers 401 (token revoked)",
2313
+ rules: [{ pathPrefix: API, status: 401, body: { detail: "Given API token is not valid" } }]
2314
+ },
2315
+ invalid_json: {
2316
+ description: "Reads answer 200 with a body that is not JSON",
2317
+ rules: [
2318
+ {
2319
+ pathPrefix: API,
2320
+ method: "GET",
2321
+ status: 200,
2322
+ body: "<!doctype html><title>Plane</title>",
2323
+ headers: { "content-type": "text/html" }
2324
+ }
2325
+ ]
2326
+ },
2327
+ network_drop: {
2328
+ description: "The connection drops before any answer (fetch rejects)",
2329
+ rules: [{ pathPrefix: API, drop: true }]
2330
+ },
2331
+ slow: {
2332
+ description: "Every call answers after 15 s (past our client's 10 s timeout)",
2333
+ rules: [{ pathPrefix: API, latencyMs: 15e3 }]
2334
+ },
2335
+ pagination_missing_cursor: {
2336
+ description: "Lists claim another page (next_page_results: true) with an empty next_cursor",
2337
+ rules: [{ pathPrefix: API, method: "GET", effect: "pagination_missing_cursor" }]
2338
+ },
2339
+ pagination_repeated_cursor: {
2340
+ description: "Lists always claim another page behind the same next_cursor",
2341
+ rules: [{ pathPrefix: API, method: "GET", effect: "pagination_repeated_cursor" }]
2342
+ }
2343
+ };
2344
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2345
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2346
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2347
+ var adminRoutes = (runtime) => ({
2348
+ "GET /work-items": ({ namespace }) => json3(200, { work_items: runtime.instance(namespace).workItems() }),
2349
+ "POST /work-items/:id/state": ({ params, body, namespace }) => {
2350
+ if (!isRecord4(body) || typeof body.state !== "string") {
2351
+ return adminError3(400, 'expected {"state": "<state id or name, e.g. Done>"}');
2352
+ }
2353
+ const item = runtime.instance(namespace).moveToState(params.id, body.state);
2354
+ return item ? json3(200, item) : adminError3(404, `no work item ${params.id} or state ${body.state}`);
2355
+ },
2356
+ "POST /projects": ({ body, namespace }) => {
2357
+ if (!isRecord4(body) || typeof body.workspace !== "string" || typeof body.project !== "string") {
2358
+ return adminError3(400, 'expected {"workspace": "<slug>", "project": "<uuid>"}');
2359
+ }
2360
+ const api = runtime.instance(namespace);
2361
+ const project = api.ensureProject(body.workspace, body.project);
2362
+ return project ? json3(200, { project, states: api.statesOf(project.id), labels: api.labelsOf(project.id) }) : adminError3(409, "project is not in settings.projects");
2363
+ },
2364
+ "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
2365
+ "PUT /settings": ({ body, namespace }) => {
2366
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2367
+ const patch = {};
2368
+ if (body.apiKeys !== void 0) {
2369
+ if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
2370
+ patch.apiKeys = body.apiKeys.map(String);
2371
+ }
2372
+ if (body.rateLimitPerMinute !== void 0) {
2373
+ if (body.rateLimitPerMinute !== null && typeof body.rateLimitPerMinute !== "number") {
2374
+ return adminError3(400, "rateLimitPerMinute: number | null");
2375
+ }
2376
+ patch.rateLimitPerMinute = body.rateLimitPerMinute;
2377
+ }
2378
+ if (body.projects !== void 0) {
2379
+ if (!Array.isArray(body.projects)) return adminError3(400, 'projects: ["<slug>/<uuid>"]');
2380
+ patch.projects = body.projects.map(String);
2381
+ }
2382
+ return json3(200, runtime.instance(namespace).state.update(patch));
2383
+ }
2384
+ });
2385
+ var createRuntime2 = (options = {}) => createRuntime({
2386
+ name: PLANE_NAMESPACE,
2387
+ document,
2388
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2389
+ ...options.clock ? { clock: options.clock } : {},
2390
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2391
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2392
+ ...options.onLog ? { onLog: options.onLog } : {},
2393
+ credential: apiKeyCredential,
2394
+ presets: PLANE_PRESETS,
2395
+ create: ({ sqlite, namespace, clock }) => new PlaneAPI({
2396
+ sqlite,
2397
+ namespace,
2398
+ now: clock.now,
2399
+ ...options.settings ? { settings: options.settings } : {}
2400
+ }),
2401
+ admin: adminRoutes
2402
+ });
2403
+
2404
+ // src/index.ts
2405
+ var PLANE_NAMESPACE = "plane";
2406
+ var apiKeyCredential = (request) => request.headers.get("x-api-key")?.trim() || void 0;
2407
+ var NOT_FOUND = { error: "The requested resource does not exist." };
2408
+ var PAGE_SIZE = 100;
2409
+ var stripTags = (html) => html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
2410
+ var drfErrors = (issues) => {
2411
+ const out = {};
2412
+ for (const issue of issues) {
2413
+ const missing = /^missing required property (.+)$/.exec(issue.message);
2414
+ const field = missing ? missing[1] : issue.path.split(".")[0] || "non_field_errors";
2415
+ const message = missing ? "This field is required." : `Invalid value: ${issue.message}.`;
2416
+ out[field] = [...out[field] ?? [], message];
2417
+ }
2418
+ return out;
2419
+ };
2420
+ var PlaneAPI = class {
2421
+ app;
2422
+ sqlite;
2423
+ state;
2424
+ service;
2425
+ now;
2426
+ constructor(options = {}) {
2427
+ const sqlite = bootSqlite(options.sqlite);
2428
+ const namespace = options.namespace ?? PLANE_NAMESPACE;
2429
+ this.now = options.now ?? (() => Date.now());
2430
+ this.state = new PlaneState(sqlite, namespace, options.settings ?? {});
2431
+ const handlers = defineOperations({
2432
+ ListWorkItems: (context) => this.listWorkItems(context),
2433
+ CreateWorkItem: (context) => this.createWorkItem(context),
2434
+ GetWorkItem: (context) => {
2435
+ const item = this.item(context);
2436
+ return annotateResponse(jsonRes(200, item), { ids: { workItemId: item.id } });
2437
+ },
2438
+ UpdateWorkItem: (context) => this.updateWorkItem(context),
2439
+ ListComments: (context) => {
2440
+ const item = this.item(context);
2441
+ return this.paginate(
2442
+ context,
2443
+ this.state.comments.list({ order: "oldest", where: (c) => c.issue === item.id }).map((r) => r.value)
2444
+ );
2445
+ },
2446
+ CreateComment: (context) => this.createComment(context),
2447
+ ListLinks: (context) => {
2448
+ const item = this.item(context);
2449
+ return this.paginate(
2450
+ context,
2451
+ this.state.links.list({ where: (l) => l.issue === item.id }).map((r) => r.value)
2452
+ );
2453
+ },
2454
+ CreateLink: (context) => this.createLink(context),
2455
+ ListStates: (context) => {
2456
+ const project = this.project(context);
2457
+ return this.paginate(context, this.statesOf(project.id));
2458
+ },
2459
+ ListLabels: (context) => {
2460
+ const project = this.project(context);
2461
+ return this.paginate(context, this.labelsOf(project.id));
2462
+ },
2463
+ CreateLabel: (context) => this.createLabel(context)
2464
+ });
2465
+ this.service = createService({
2466
+ document,
2467
+ handlers,
2468
+ sqlite,
2469
+ namespace,
2470
+ now: this.now,
2471
+ notFound: () => jsonRes(404, { detail: "Not found." }),
2472
+ onError: (error) => {
2473
+ if (error instanceof HttpError) return error.toResponse();
2474
+ throw error;
2475
+ },
2476
+ before: (context) => {
2477
+ const key = apiKeyCredential(context.request);
2478
+ if (!key) return jsonRes(401, { detail: "Authentication credentials were not provided." });
2479
+ const settings = this.state.current();
2480
+ if (settings.apiKeys.length > 0 && !settings.apiKeys.includes(key)) {
2481
+ return jsonRes(401, { detail: "Given API token is not valid" });
2482
+ }
2483
+ if (settings.rateLimitPerMinute !== null) {
2484
+ const minute = Math.floor(this.now() / 6e4);
2485
+ const bucket = `${key}:${minute}`;
2486
+ const used = this.state.takeRateLimit(bucket);
2487
+ if (used > settings.rateLimitPerMinute) {
2488
+ const reset = (minute + 1) * 60;
2489
+ return jsonRes(
2490
+ 429,
2491
+ {
2492
+ detail: `Request was throttled. Expected available in ${reset - Math.floor(this.now() / 1e3)} seconds.`
2493
+ },
2494
+ { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) }
2495
+ );
2496
+ }
2497
+ }
2498
+ return void 0;
2499
+ }
2500
+ });
2501
+ this.app = this.service.app;
2502
+ this.sqlite = this.service.sqlite;
2503
+ }
2504
+ fetch(request) {
2505
+ return this.service.fetch(request);
2506
+ }
2507
+ async reset() {
2508
+ await this.service.reset();
2509
+ this.state.ensureSeeded();
2510
+ }
2511
+ iso() {
2512
+ return new Date(this.now()).toISOString();
2513
+ }
2514
+ /** The project a request addresses, provisioned with the default workflow on first use. */
2515
+ ensureProject(workspace, projectId) {
2516
+ const existing = this.state.projects.get(projectId);
2517
+ if (existing) return existing.workspace === workspace ? existing : void 0;
2518
+ const pinned = this.state.current().projects;
2519
+ if (pinned.length > 0 && !pinned.includes(`${workspace}/${projectId}`)) return void 0;
2520
+ const project = {
2521
+ id: projectId,
2522
+ workspace,
2523
+ identifier: "BUGS",
2524
+ nextSequence: 1
2525
+ };
2526
+ this.state.projects.insert(projectId, project);
2527
+ const now = this.iso();
2528
+ DEFAULT_STATES.forEach((state, index) => {
2529
+ const id = uuidFrom(`${projectId}:state:${state.name}`);
2530
+ this.state.states.insert(id, {
2531
+ id,
2532
+ name: state.name,
2533
+ group: state.group,
2534
+ color: state.color,
2535
+ sequence: (index + 1) * 15e3,
2536
+ default: index === 0,
2537
+ description: "",
2538
+ project: projectId,
2539
+ workspace,
2540
+ created_at: now,
2541
+ updated_at: now
2542
+ });
2543
+ });
2544
+ return project;
2545
+ }
2546
+ project(context) {
2547
+ const project = this.ensureProject(context.params.slug ?? "", context.params.project_id ?? "");
2548
+ if (!project) throw new HttpError(404, NOT_FOUND);
2549
+ return project;
2550
+ }
2551
+ item(context) {
2552
+ const project = this.project(context);
2553
+ const item = this.state.items.get(context.params.work_item_id ?? "");
2554
+ if (!item || item.project !== project.id) throw new HttpError(404, NOT_FOUND);
2555
+ return item;
2556
+ }
2557
+ statesOf(projectId) {
2558
+ return this.state.states.list({ order: "oldest", where: (s) => s.project === projectId }).map((r) => r.value);
2559
+ }
2560
+ labelsOf(projectId) {
2561
+ return this.state.labels.list({ order: "oldest", where: (l) => l.project === projectId }).map((r) => r.value);
2562
+ }
2563
+ /** Plane's cursor paginator: `cursor=<per_page>:<page>:<is_prev>`, offset = page × per_page. */
2564
+ paginate(context, rows) {
2565
+ const perPageResult = context.query.per_page === void 0 ? void 0 : coerce.integer(context.query.per_page);
2566
+ if (perPageResult && !perPageResult.ok) {
2567
+ return jsonRes(400, { error: "Invalid per_page parameter." });
2568
+ }
2569
+ const perPage = Math.min(PAGE_SIZE, Math.max(1, perPageResult?.value ?? PAGE_SIZE));
2570
+ let page = 0;
2571
+ let cursorSize = perPage;
2572
+ if (context.query.cursor !== void 0) {
2573
+ const match = /^(\d+):(-?\d+):([01])$/.exec(String(context.query.cursor));
2574
+ if (!match || Number(match[2]) < 0 || Number(match[1]) < 1) {
2575
+ return jsonRes(400, { error: "Invalid cursor format." });
2576
+ }
2577
+ cursorSize = Number(match[1]);
2578
+ page = Number(match[2]);
2579
+ }
2580
+ const offset = page * cursorSize;
2581
+ const results = rows.slice(offset, offset + perPage);
2582
+ const total = rows.length;
2583
+ let nextCursor = `${perPage}:${page + 1}:0`;
2584
+ let nextPageResults = offset + perPage < total;
2585
+ if (faultEffect(context.request, "pagination_missing_cursor") !== void 0) {
2586
+ nextCursor = "";
2587
+ nextPageResults = true;
2588
+ }
2589
+ if (faultEffect(context.request, "pagination_repeated_cursor") !== void 0) {
2590
+ nextCursor = `${perPage}:1:0`;
2591
+ nextPageResults = true;
2592
+ }
2593
+ return jsonRes(200, {
2594
+ grouped_by: null,
2595
+ sub_grouped_by: null,
2596
+ total_count: total,
2597
+ next_cursor: nextCursor,
2598
+ prev_cursor: `${perPage}:${page - 1}:1`,
2599
+ next_page_results: nextPageResults,
2600
+ prev_page_results: page > 0,
2601
+ count: results.length,
2602
+ total_pages: Math.ceil(total / perPage),
2603
+ total_results: total,
2604
+ extra_stats: null,
2605
+ results
2606
+ });
2607
+ }
2608
+ listWorkItems(context) {
2609
+ const project = this.project(context);
2610
+ const orderBy = typeof context.query.order_by === "string" ? context.query.order_by : "-created_at";
2611
+ const descending = orderBy.startsWith("-");
2612
+ const field = descending ? orderBy.slice(1) : orderBy;
2613
+ const rows = this.state.items.list({ order: "oldest", where: (i) => i.project === project.id }).map((r) => r.value).sort((a, b) => {
2614
+ const x = a[field] ?? "";
2615
+ const y = b[field] ?? "";
2616
+ const order = x < y ? -1 : x > y ? 1 : a.sequence_id - b.sequence_id;
2617
+ return descending ? -order : order;
2618
+ });
2619
+ return this.paginate(context, rows);
2620
+ }
2621
+ body(context) {
2622
+ const issues = bodyIssues(context);
2623
+ if (issues.length > 0) throw new HttpError(400, drfErrors(issues));
2624
+ return context.body.kind === "json" ? context.body.value : {};
2625
+ }
2626
+ /** Validate `state` / `labels` references against the project, DRF-style. */
2627
+ references(project, body) {
2628
+ const out = {};
2629
+ if (typeof body.state === "string") {
2630
+ const state = this.state.states.get(body.state);
2631
+ if (!state || state.project !== project.id) {
2632
+ throw new HttpError(400, { state: [`Invalid pk "${body.state}" - object does not exist.`] });
2633
+ }
2634
+ out.state = state;
2635
+ }
2636
+ if (Array.isArray(body.labels)) {
2637
+ const labels = body.labels.map(String);
2638
+ const missing = labels.find((id) => this.state.labels.get(id)?.project !== project.id);
2639
+ if (missing) {
2640
+ throw new HttpError(400, { labels: [`Invalid pk "${missing}" - object does not exist.`] });
2641
+ }
2642
+ out.labels = [...new Set(labels)];
2643
+ }
2644
+ return out;
2645
+ }
2646
+ createWorkItem(context) {
2647
+ const project = this.project(context);
2648
+ const body = this.body(context);
2649
+ const refs = this.references(project, body);
2650
+ const state = refs.state ?? this.statesOf(project.id).find((s) => s.default) ?? this.statesOf(project.id)[0];
2651
+ const now = this.iso();
2652
+ const html = typeof body.description_html === "string" ? body.description_html : "<p></p>";
2653
+ const item = {
2654
+ id: this.state.uuid("work_item"),
2655
+ sequence_id: project.nextSequence,
2656
+ name: String(body.name).trim(),
2657
+ description_html: html,
2658
+ description_stripped: stripTags(html) || null,
2659
+ priority: body.priority ?? "none",
2660
+ state: state?.id ?? "",
2661
+ labels: refs.labels ?? [],
2662
+ assignees: [],
2663
+ parent: null,
2664
+ start_date: null,
2665
+ target_date: null,
2666
+ completed_at: state?.group === "completed" ? now : null,
2667
+ archived_at: null,
2668
+ is_draft: false,
2669
+ sort_order: 65535 * project.nextSequence,
2670
+ project: project.id,
2671
+ workspace: project.workspace,
2672
+ created_by: uuidFrom("plane-bot"),
2673
+ updated_by: uuidFrom("plane-bot"),
2674
+ created_at: now,
2675
+ updated_at: now
2676
+ };
2677
+ this.state.items.insert(item.id, item);
2678
+ this.state.projects.update(project.id, { ...project, nextSequence: project.nextSequence + 1 });
2679
+ return annotateResponse(jsonRes(201, item), { ids: { workItemId: item.id } });
2680
+ }
2681
+ updateWorkItem(context) {
2682
+ const item = this.item(context);
2683
+ const project = this.project(context);
2684
+ const body = this.body(context);
2685
+ const refs = this.references(project, body);
2686
+ const next = this.applyPatch(item, {
2687
+ ...typeof body.name === "string" ? { name: body.name.trim() } : {},
2688
+ ...typeof body.description_html === "string" ? {
2689
+ description_html: body.description_html,
2690
+ description_stripped: stripTags(body.description_html) || null
2691
+ } : {},
2692
+ ...typeof body.priority === "string" ? { priority: body.priority } : {},
2693
+ ...refs.labels ? { labels: refs.labels } : {},
2694
+ ...refs.state ? { state: refs.state.id } : {}
2695
+ });
2696
+ return annotateResponse(jsonRes(200, next), { ids: { workItemId: next.id } });
2697
+ }
2698
+ /** Merge a patch, keeping `completed_at` in step with the state's group. */
2699
+ applyPatch(item, patch) {
2700
+ const now = this.iso();
2701
+ const merged = { ...item, ...patch, updated_at: now };
2702
+ const group = this.state.states.get(merged.state)?.group;
2703
+ merged.completed_at = group === "completed" ? item.completed_at ?? now : null;
2704
+ this.state.items.update(item.id, merged);
2705
+ return merged;
2706
+ }
2707
+ createComment(context) {
2708
+ const item = this.item(context);
2709
+ const body = this.body(context);
2710
+ const now = this.iso();
2711
+ const html = String(body.comment_html);
2712
+ const comment = {
2713
+ id: this.state.uuid("comment"),
2714
+ comment_html: html,
2715
+ comment_stripped: stripTags(html),
2716
+ access: typeof body.access === "string" ? body.access : "INTERNAL",
2717
+ issue: item.id,
2718
+ actor: uuidFrom("plane-bot"),
2719
+ project: item.project,
2720
+ workspace: item.workspace,
2721
+ created_at: now,
2722
+ updated_at: now
2723
+ };
2724
+ this.state.comments.insert(comment.id, comment);
2725
+ return annotateResponse(jsonRes(201, comment), {
2726
+ ids: { workItemId: item.id, commentId: comment.id }
2727
+ });
2728
+ }
2729
+ createLink(context) {
2730
+ const item = this.item(context);
2731
+ const body = this.body(context);
2732
+ const url = String(body.url);
2733
+ const duplicate = this.state.links.list({
2734
+ where: (l) => l.issue === item.id && l.url === url
2735
+ })[0];
2736
+ if (duplicate) {
2737
+ return jsonRes(409, { error: "URL already exists for this Issue", id: duplicate.value.id });
2738
+ }
2739
+ const now = this.iso();
2740
+ const link = {
2741
+ id: this.state.uuid("link"),
2742
+ url,
2743
+ title: typeof body.title === "string" ? body.title : null,
2744
+ metadata: {},
2745
+ issue: item.id,
2746
+ project: item.project,
2747
+ workspace: item.workspace,
2748
+ created_at: now,
2749
+ updated_at: now
2750
+ };
2751
+ this.state.links.insert(link.id, link);
2752
+ return annotateResponse(jsonRes(201, link), { ids: { workItemId: item.id, linkId: link.id } });
2753
+ }
2754
+ createLabel(context) {
2755
+ const project = this.project(context);
2756
+ const body = this.body(context);
2757
+ const name = String(body.name).trim();
2758
+ const existing = this.labelsOf(project.id).find((l) => l.name === name);
2759
+ if (existing) {
2760
+ return jsonRes(409, {
2761
+ error: "Label with the same name already exists in the project",
2762
+ id: existing.id
2763
+ });
2764
+ }
2765
+ const now = this.iso();
2766
+ const label = {
2767
+ id: this.state.uuid("label"),
2768
+ name,
2769
+ color: typeof body.color === "string" ? body.color : "#6366F1",
2770
+ description: typeof body.description === "string" ? body.description : "",
2771
+ parent: null,
2772
+ sort_order: 65535 * (this.labelsOf(project.id).length + 1),
2773
+ project: project.id,
2774
+ workspace: project.workspace,
2775
+ created_at: now,
2776
+ updated_at: now
2777
+ };
2778
+ this.state.labels.insert(label.id, label);
2779
+ return annotateResponse(jsonRes(201, label), { ids: { labelId: label.id } });
2780
+ }
2781
+ /**
2782
+ * Move a work item to a state (by id or name), the way a teammate would in Plane's UI:
2783
+ * e.g. `Done` makes the resolution watcher see group `completed`.
2784
+ */
2785
+ moveToState(workItemId, stateIdOrName) {
2786
+ const item = this.state.items.get(workItemId);
2787
+ if (!item) return void 0;
2788
+ const state = this.statesOf(item.project).find(
2789
+ (s) => s.id === stateIdOrName || s.name.toLowerCase() === stateIdOrName.toLowerCase()
2790
+ );
2791
+ if (!state) return void 0;
2792
+ return this.applyPatch(item, { state: state.id });
2793
+ }
2794
+ workItems() {
2795
+ return this.state.items.list({ order: "oldest" }).map((r) => r.value);
2796
+ }
2797
+ };
2798
+
2799
+ export {
2800
+ document,
2801
+ operationIds,
2802
+ supportedOperationIds,
2803
+ DEFAULT_STATES,
2804
+ uuidFrom,
2805
+ PLANE_PRESETS,
2806
+ createRuntime2 as createRuntime,
2807
+ PLANE_NAMESPACE,
2808
+ apiKeyCredential,
2809
+ PlaneAPI
2810
+ };
2811
+ //# sourceMappingURL=chunk-NRVXEVSO.js.map