@crvouga/mockingbird-service-prism 1.3.0 → 1.4.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.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
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);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
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);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
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);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
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);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
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));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
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);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
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);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
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);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
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);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -699,64 +701,64 @@ var graphemeLength = (value) => [...value].length;
699
701
  var validateValue = (document2, schema, value, path = []) => {
700
702
  const errors = [];
701
703
  const s = resolveSchema(document2, schema);
702
- const fail = (message) => errors.push({ path, message });
704
+ const fail2 = (message) => errors.push({ path, message });
703
705
  const actual = jsonTypeOf(value);
704
706
  if (actual === "undefined") {
705
- fail("value is undefined");
707
+ fail2("value is undefined");
706
708
  return errors;
707
709
  }
708
710
  const types = schemaTypes(s);
709
711
  if (types.length > 0) {
710
712
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
711
713
  if (!ok) {
712
- fail(`expected type ${types.join("|")}, got ${actual}`);
714
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
713
715
  return errors;
714
716
  }
715
717
  }
716
718
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
717
- fail("value not in enum");
719
+ fail2("value not in enum");
718
720
  }
719
721
  if (s.const !== void 0 && !deepEqual(s.const, value))
720
- fail("value does not equal const");
722
+ fail2("value does not equal const");
721
723
  if (typeof value === "string") {
722
724
  const length = graphemeLength(value);
723
725
  if (s.minLength !== void 0 && length < s.minLength)
724
- fail(`length ${length} < minLength ${s.minLength}`);
726
+ fail2(`length ${length} < minLength ${s.minLength}`);
725
727
  if (s.maxLength !== void 0 && length > s.maxLength)
726
- fail(`length ${length} > maxLength ${s.maxLength}`);
728
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
727
729
  if (s.pattern !== void 0) {
728
730
  try {
729
731
  if (!new RegExp(s.pattern, "u").test(value))
730
- fail(`does not match pattern ${s.pattern}`);
732
+ fail2(`does not match pattern ${s.pattern}`);
731
733
  } catch {
732
734
  }
733
735
  }
734
736
  if (s.format !== void 0) {
735
737
  const pattern = FORMAT_PATTERNS[s.format];
736
738
  if (pattern && !pattern.test(value))
737
- fail(`does not match format ${s.format}`);
739
+ fail2(`does not match format ${s.format}`);
738
740
  }
739
741
  }
740
742
  if (typeof value === "number") {
741
743
  if (s.minimum !== void 0 && value < s.minimum)
742
- fail(`${value} < minimum ${s.minimum}`);
744
+ fail2(`${value} < minimum ${s.minimum}`);
743
745
  if (s.maximum !== void 0 && value > s.maximum)
744
- fail(`${value} > maximum ${s.maximum}`);
746
+ fail2(`${value} > maximum ${s.maximum}`);
745
747
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
748
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
749
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
750
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
751
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
- fail(`${value} is not a multiple of ${s.multipleOf}`);
752
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
751
753
  }
752
754
  }
753
755
  if (Array.isArray(value)) {
754
756
  if (s.minItems !== void 0 && value.length < s.minItems)
755
- fail(`${value.length} items < minItems ${s.minItems}`);
757
+ fail2(`${value.length} items < minItems ${s.minItems}`);
756
758
  if (s.maxItems !== void 0 && value.length > s.maxItems)
757
- fail(`${value.length} items > maxItems ${s.maxItems}`);
759
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
758
760
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
759
- fail("items are not unique");
761
+ fail2("items are not unique");
760
762
  value.forEach((item, i) => {
761
763
  const itemSchema = s.prefixItems?.[i] ?? s.items;
762
764
  if (itemSchema)
@@ -768,11 +770,11 @@ var validateValue = (document2, schema, value, path = []) => {
768
770
  const keys = Object.keys(record);
769
771
  for (const name of s.required ?? [])
770
772
  if (!(name in record))
771
- fail(`missing required property ${name}`);
773
+ fail2(`missing required property ${name}`);
772
774
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
775
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
774
776
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
777
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
776
778
  for (const key of keys) {
777
779
  const property = s.properties?.[key];
778
780
  if (property) {
@@ -780,14 +782,14 @@ var validateValue = (document2, schema, value, path = []) => {
780
782
  continue;
781
783
  }
782
784
  if (s.additionalProperties === false)
783
- fail(`unexpected property ${key}`);
785
+ fail2(`unexpected property ${key}`);
784
786
  else if (typeof s.additionalProperties === "object") {
785
787
  errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
786
788
  }
787
789
  if (s.propertyNames) {
788
790
  const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
789
791
  if (nameErrors.length > 0)
790
- fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
792
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
791
793
  }
792
794
  }
793
795
  }
@@ -795,14 +797,14 @@ var validateValue = (document2, schema, value, path = []) => {
795
797
  for (const branch of s.allOf)
796
798
  errors.push(...validateValue(document2, branch, value, path));
797
799
  if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
798
- fail("matches no anyOf branch");
800
+ fail2("matches no anyOf branch");
799
801
  if (s.oneOf) {
800
802
  const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
803
  if (matches2 !== 1)
802
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
804
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
803
805
  }
804
806
  if (s.not && validateValue(document2, s.not, value).length === 0)
805
- fail("matches forbidden `not` schema");
807
+ fail2("matches forbidden `not` schema");
806
808
  return errors;
807
809
  };
808
810
 
@@ -1334,6 +1336,936 @@ var clearNamespace = (sqlite, namespace) => {
1334
1336
  });
1335
1337
  };
1336
1338
 
1339
+ // ../core/dist/surface.js
1340
+ var defineMock = (runtime) => runtime;
1341
+ var STANDARD_ADMIN_ROUTES = [
1342
+ "GET /",
1343
+ "POST /reset",
1344
+ "GET /namespaces",
1345
+ "GET /clock",
1346
+ "POST /clock",
1347
+ "GET /faults",
1348
+ "POST /faults",
1349
+ "DELETE /faults",
1350
+ "POST /snapshots",
1351
+ "POST /snapshots/:id/restore",
1352
+ "DELETE /snapshots/:id",
1353
+ "GET /timeline",
1354
+ "POST /checkpoints",
1355
+ "POST /branches/:name",
1356
+ "POST /branches/:name/checkout",
1357
+ "GET /requests",
1358
+ "DELETE /requests",
1359
+ "GET /metrics",
1360
+ "DELETE /metrics",
1361
+ "GET /credentials",
1362
+ "PUT /credentials",
1363
+ "DELETE /credentials",
1364
+ "GET /state",
1365
+ "GET /state/:collection",
1366
+ "GET /state/:collection/:id",
1367
+ "POST /state/:collection",
1368
+ "PUT /state/:collection/:id",
1369
+ "PATCH /state/:collection/:id",
1370
+ "DELETE /state/:collection/:id",
1371
+ "GET /ui",
1372
+ "GET /ui/",
1373
+ "GET /ui/manifest"
1374
+ ];
1375
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1376
+ var assertAdminUi = (ui) => {
1377
+ if (!ui?.panels)
1378
+ return;
1379
+ const seen = /* @__PURE__ */ new Set();
1380
+ for (const panel of ui.panels) {
1381
+ if (!PANEL_ID.test(panel.id)) {
1382
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1383
+ }
1384
+ if (seen.has(panel.id))
1385
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1386
+ seen.add(panel.id);
1387
+ if (panel.title.trim() === "")
1388
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1389
+ }
1390
+ };
1391
+
1392
+ // ../core/dist/admin-ui.js
1393
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1394
+ switch (char) {
1395
+ case "&":
1396
+ return "&amp;";
1397
+ case "<":
1398
+ return "&lt;";
1399
+ case ">":
1400
+ return "&gt;";
1401
+ case '"':
1402
+ return "&quot;";
1403
+ default:
1404
+ return "&#39;";
1405
+ }
1406
+ });
1407
+ var renderAdminDocument = (service) => {
1408
+ const name = escapeHtml(service);
1409
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1410
+ return `<!DOCTYPE html>
1411
+ <html lang="en">
1412
+ <head>
1413
+ <meta charset="utf-8">
1414
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1415
+ <meta name="color-scheme" content="light dark">
1416
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%233d4f3a'/%3E%3C/svg%3E">
1417
+ <title>${name} admin</title>
1418
+ <style>
1419
+ :root {
1420
+ color-scheme: light;
1421
+ --bg: #f6f5f2;
1422
+ --bg-elev: #ffffff;
1423
+ --bg-muted: #eeece6;
1424
+ --bg-inset: #f3f1eb;
1425
+ --line: #e2dfd6;
1426
+ --line-strong: #d0ccc1;
1427
+ --ink: #1c1915;
1428
+ --muted: #5e584f;
1429
+ --faint: #8a8378;
1430
+ --accent: #3d4f3a;
1431
+ --accent-ink: #f7f6f2;
1432
+ --accent-soft: #e5ece2;
1433
+ --ok: #1f7a45;
1434
+ --ok-soft: #e5f4eb;
1435
+ --warn: #9a6700;
1436
+ --warn-soft: #fbf3df;
1437
+ --err: #a33b32;
1438
+ --err-soft: #fdecea;
1439
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1440
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1441
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1442
+ --radius: 14px;
1443
+ --header: 60px;
1444
+ --nav: 220px;
1445
+ }
1446
+ :root[data-theme="dark"] {
1447
+ color-scheme: dark;
1448
+ --bg: #141311;
1449
+ --bg-elev: #1e1c19;
1450
+ --bg-muted: #26231f;
1451
+ --bg-inset: #181715;
1452
+ --line: #34302b;
1453
+ --line-strong: #4a453d;
1454
+ --ink: #f4f1ea;
1455
+ --muted: #c4bdb1;
1456
+ --faint: #8f877c;
1457
+ --accent: #c5d5b8;
1458
+ --accent-ink: #1a2118;
1459
+ --accent-soft: #2a3328;
1460
+ --ok: #8fd6a8;
1461
+ --ok-soft: #1a2e22;
1462
+ --warn: #f0cc78;
1463
+ --warn-soft: #332911;
1464
+ --err: #f0a8a2;
1465
+ --err-soft: #3a201e;
1466
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1467
+ }
1468
+ @media (prefers-color-scheme: dark) {
1469
+ :root:not([data-theme="light"]) {
1470
+ color-scheme: dark;
1471
+ --bg: #141311;
1472
+ --bg-elev: #1e1c19;
1473
+ --bg-muted: #26231f;
1474
+ --bg-inset: #181715;
1475
+ --line: #34302b;
1476
+ --line-strong: #4a453d;
1477
+ --ink: #f4f1ea;
1478
+ --muted: #c4bdb1;
1479
+ --faint: #8f877c;
1480
+ --accent: #c5d5b8;
1481
+ --accent-ink: #1a2118;
1482
+ --accent-soft: #2a3328;
1483
+ --ok: #8fd6a8;
1484
+ --ok-soft: #1a2e22;
1485
+ --warn: #f0cc78;
1486
+ --warn-soft: #332911;
1487
+ --err: #f0a8a2;
1488
+ --err-soft: #3a201e;
1489
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1490
+ }
1491
+ }
1492
+ * { box-sizing: border-box; }
1493
+ html, body { margin: 0; height: 100%; }
1494
+ body {
1495
+ font-family: var(--sans);
1496
+ background: var(--bg);
1497
+ color: var(--ink);
1498
+ line-height: 1.45;
1499
+ padding-left: env(safe-area-inset-left);
1500
+ padding-right: env(safe-area-inset-right);
1501
+ -webkit-text-size-adjust: 100%;
1502
+ }
1503
+ button, input, select, textarea { font: inherit; color: inherit; }
1504
+ button { cursor: pointer; }
1505
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1506
+ @media (prefers-reduced-motion: reduce) {
1507
+ * { scroll-behavior: auto !important; transition: none !important; }
1508
+ }
1509
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1510
+ header.top {
1511
+ position: sticky; top: 0; z-index: 5;
1512
+ display: flex; align-items: center; gap: 12px;
1513
+ min-height: var(--header); padding: 10px 16px;
1514
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1515
+ border-bottom: 1px solid var(--line);
1516
+ backdrop-filter: blur(10px);
1517
+ }
1518
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1519
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1520
+ .brand span { color: var(--faint); font-size: 12px; }
1521
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1522
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1523
+ label.field input, label.field select, .controls input[type="password"] {
1524
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1525
+ padding: 7px 8px; min-height: 36px;
1526
+ }
1527
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1528
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1529
+ background: var(--bg-elev);
1530
+ }
1531
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1532
+ .btn-quiet { background: transparent; }
1533
+ .btn-danger { color: var(--err); }
1534
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1535
+ record or the full nav row would widen the page past the viewport. */
1536
+ .layout {
1537
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1538
+ flex: 1; min-height: 0; min-width: 0;
1539
+ }
1540
+ nav.side {
1541
+ border-right: 1px solid var(--line); padding: 12px;
1542
+ display: flex; flex-direction: column; gap: 4px;
1543
+ background: var(--bg-elev);
1544
+ }
1545
+ nav.side button {
1546
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1547
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1548
+ }
1549
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1550
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1551
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1552
+ .lede { margin: 0 0 16px; color: var(--muted); }
1553
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1554
+ .card {
1555
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1556
+ padding: 14px 16px; box-shadow: var(--shadow);
1557
+ }
1558
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1559
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1560
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1561
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1562
+ .collection {
1563
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1564
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1565
+ }
1566
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1567
+ .collection small { display: block; color: var(--faint); }
1568
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1569
+ .chip {
1570
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1571
+ border-radius: 999px; padding: 4px 8px;
1572
+ }
1573
+ .chip i { color: var(--faint); font-style: normal; }
1574
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1575
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1576
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1577
+ tr.clickable { cursor: pointer; }
1578
+ tr.clickable:hover { background: var(--bg-muted); }
1579
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1580
+ pre {
1581
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1582
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1583
+ }
1584
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1585
+ .banner {
1586
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1587
+ background: var(--err-soft); color: var(--err);
1588
+ }
1589
+ .banner.show { display: block; }
1590
+ .empty { color: var(--muted); padding: 24px 8px; }
1591
+ dialog {
1592
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1593
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1594
+ }
1595
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1596
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1597
+ textarea {
1598
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1599
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1600
+ font-family: var(--mono); font-size: 12px;
1601
+ }
1602
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1603
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1604
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1605
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1606
+ .status-2 { color: var(--ok); }
1607
+ .status-4, .status-5, .status-0 { color: var(--err); }
1608
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1609
+ .route {
1610
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1611
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1612
+ }
1613
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1614
+ @media (max-width: 800px) {
1615
+ header.top {
1616
+ align-items: stretch; flex-direction: column;
1617
+ padding-top: max(10px, env(safe-area-inset-top));
1618
+ }
1619
+ input, select, textarea { font-size: 16px; }
1620
+ .controls { width: 100%; }
1621
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1622
+ .layout { grid-template-columns: minmax(0, 1fr); }
1623
+ nav.side {
1624
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1625
+ border-right: 0; border-bottom: 1px solid var(--line);
1626
+ padding: 8px;
1627
+ }
1628
+ nav.side button { white-space: nowrap; flex: none; }
1629
+ .split { grid-template-columns: minmax(0, 1fr); }
1630
+ main { padding: 14px; }
1631
+ table, thead, tbody, tr, th, td { display: block; }
1632
+ thead { display: none; }
1633
+ tr {
1634
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1635
+ background: var(--bg-elev); min-width: 0;
1636
+ }
1637
+ td {
1638
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1639
+ min-width: 0; overflow-wrap: anywhere;
1640
+ }
1641
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1642
+ .route { grid-template-columns: 72px 1fr; }
1643
+ .route button { grid-column: 1 / -1; }
1644
+ }
1645
+ </style>
1646
+ </head>
1647
+ <body>
1648
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1649
+ <header class="top">
1650
+ <div class="brand">
1651
+ <strong>${name}</strong>
1652
+ <span>Mockingbird admin</span>
1653
+ </div>
1654
+ <div class="controls">
1655
+ <label class="field">Namespace
1656
+ <select id="namespace" aria-label="Namespace"></select>
1657
+ </label>
1658
+ <label class="field">Admin key
1659
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1660
+ </label>
1661
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1662
+ <button class="btn" id="refresh" type="button">Refresh</button>
1663
+ </div>
1664
+ </header>
1665
+ <div class="layout">
1666
+ <nav class="side" id="nav" aria-label="Admin sections">
1667
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1668
+ <button type="button" data-view="state">State</button>
1669
+ <button type="button" data-view="clock">Clock</button>
1670
+ <button type="button" data-view="faults">Faults</button>
1671
+ <button type="button" data-view="journal">Journal</button>
1672
+ <button type="button" data-view="routes">Routes</button>
1673
+ </nav>
1674
+ <main id="views">
1675
+ <p class="banner" id="banner" role="alert"></p>
1676
+ <section class="view" id="view-overview">
1677
+ <h2>Overview</h2>
1678
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1679
+ <div class="grid" id="overview-cards"></div>
1680
+ <h3>Recent requests</h3>
1681
+ <div id="overview-requests"></div>
1682
+ </section>
1683
+ <section class="view" id="view-state" hidden>
1684
+ <h2>State</h2>
1685
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1686
+ <div class="split">
1687
+ <div id="collections"></div>
1688
+ <div>
1689
+ <div id="schema"></div>
1690
+ <div class="row-actions">
1691
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1692
+ </div>
1693
+ <div id="records"></div>
1694
+ </div>
1695
+ </div>
1696
+ </section>
1697
+ <section class="view" id="view-clock" hidden>
1698
+ <h2>Clock</h2>
1699
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1700
+ <div class="card" id="clock-readout"></div>
1701
+ <div class="row-actions">
1702
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1703
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1704
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1705
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1706
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1707
+ <button class="btn" id="freeze" type="button">Freeze</button>
1708
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1709
+ </div>
1710
+ <form id="clock-set" class="row-actions">
1711
+ <label class="field">Set instant
1712
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1713
+ </label>
1714
+ <button class="btn-primary" type="submit">Set</button>
1715
+ </form>
1716
+ </section>
1717
+ <section class="view" id="view-faults" hidden>
1718
+ <h2>Faults</h2>
1719
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1720
+ <form id="fault-form" class="card stack">
1721
+ <label class="field">Preset
1722
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1723
+ </label>
1724
+ <label class="field">Status
1725
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1726
+ </label>
1727
+ <label class="field">Path prefix
1728
+ <input id="fault-path" placeholder="/v1">
1729
+ </label>
1730
+ <label class="field">Method
1731
+ <input id="fault-method" placeholder="GET">
1732
+ </label>
1733
+ <div class="dialog-actions">
1734
+ <button class="btn-primary" type="submit">Add fault</button>
1735
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1736
+ </div>
1737
+ </form>
1738
+ <div id="fault-list"></div>
1739
+ </section>
1740
+ <section class="view" id="view-journal" hidden>
1741
+ <h2>Journal</h2>
1742
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1743
+ <div class="row-actions">
1744
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1745
+ </div>
1746
+ <div id="journal"></div>
1747
+ </section>
1748
+ <section class="view" id="view-routes" hidden>
1749
+ <h2>Routes</h2>
1750
+ <p class="lede">Shared controls, plus any routes this mock adds. Extra routes are how a bespoke workflow shows up beside the default UI.</p>
1751
+ <div id="route-list"></div>
1752
+ <form id="route-form" class="card stack">
1753
+ <strong id="route-title">Select a route</strong>
1754
+ <label class="field">JSON body
1755
+ <textarea id="route-body" placeholder="{ }"></textarea>
1756
+ </label>
1757
+ <div class="dialog-actions">
1758
+ <button class="btn-primary" type="submit">Send</button>
1759
+ </div>
1760
+ <pre id="route-result">Response will show here.</pre>
1761
+ </form>
1762
+ </section>
1763
+ </main>
1764
+ </div>
1765
+ </div>
1766
+ <dialog id="editor">
1767
+ <form method="dialog" id="editor-form">
1768
+ <strong id="editor-title">Record</strong>
1769
+ <label class="field">Id
1770
+ <input id="editor-id" required>
1771
+ </label>
1772
+ <label class="field">JSON value
1773
+ <textarea id="editor-value"></textarea>
1774
+ </label>
1775
+ <div class="dialog-actions">
1776
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1777
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1778
+ <button class="btn-primary" type="submit" value="save">Save</button>
1779
+ </div>
1780
+ </form>
1781
+ </dialog>
1782
+ <script>
1783
+ (() => {
1784
+ const STANDARD = new Set(${standard})
1785
+ const state = {
1786
+ namespace: "default",
1787
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1788
+ view: "overview",
1789
+ collection: "",
1790
+ shape: null,
1791
+ route: null,
1792
+ editing: null
1793
+ }
1794
+ const $ = (id) => document.getElementById(id)
1795
+ const banner = $("banner")
1796
+ const keyInput = $("admin-key")
1797
+ keyInput.value = state.key
1798
+ const params = new URLSearchParams(location.search)
1799
+ if (params.get("key")) {
1800
+ state.key = params.get("key")
1801
+ keyInput.value = state.key
1802
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1803
+ params.delete("key")
1804
+ const next = params.toString()
1805
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1806
+ }
1807
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1808
+
1809
+ const showError = (error) => {
1810
+ banner.textContent = error instanceof Error ? error.message : String(error)
1811
+ banner.classList.add("show")
1812
+ }
1813
+ const clearError = () => banner.classList.remove("show")
1814
+
1815
+ async function originGet(path) {
1816
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1817
+ if (!response.ok) throw new Error(response.status + " " + path)
1818
+ return response.json()
1819
+ }
1820
+ async function api(method, path, body) {
1821
+ const headers = { accept: "application/json" }
1822
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1823
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1824
+ if (body !== undefined) headers["content-type"] = "application/json"
1825
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1826
+ method,
1827
+ headers,
1828
+ body: body === undefined ? undefined : JSON.stringify(body)
1829
+ })
1830
+ const text = await response.text()
1831
+ let data = null
1832
+ if (text) {
1833
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1834
+ }
1835
+ if (response.status === 401) {
1836
+ keyInput.focus()
1837
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1838
+ }
1839
+ if (!response.ok) {
1840
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1841
+ }
1842
+ return data
1843
+ }
1844
+ const panelApi = {
1845
+ get: (path) => api("GET", path),
1846
+ send: (method, path, body) => api(method, path, body),
1847
+ namespace: () => state.namespace
1848
+ }
1849
+
1850
+ function setTheme(theme) {
1851
+ if (theme) document.documentElement.dataset.theme = theme
1852
+ else delete document.documentElement.dataset.theme
1853
+ }
1854
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1855
+ if (storedTheme) setTheme(storedTheme)
1856
+ $("theme").addEventListener("click", () => {
1857
+ const current = document.documentElement.dataset.theme
1858
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1859
+ const next = dark ? "light" : "dark"
1860
+ localStorage.setItem("mockingbird-admin-theme", next)
1861
+ setTheme(next)
1862
+ })
1863
+
1864
+ function show(view) {
1865
+ state.view = view
1866
+ for (const button of document.querySelectorAll("#nav button")) {
1867
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1868
+ }
1869
+ for (const section of document.querySelectorAll("main .view")) {
1870
+ section.hidden = section.id !== "view-" + view
1871
+ }
1872
+ }
1873
+ document.getElementById("nav").addEventListener("click", (event) => {
1874
+ const button = event.target.closest("button[data-view]")
1875
+ if (!button) return
1876
+ show(button.dataset.view)
1877
+ refresh().catch(showError)
1878
+ })
1879
+
1880
+ function cards(items) {
1881
+ return '<div class="grid">' + items.map((item) =>
1882
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1883
+ ).join("") + "</div>"
1884
+ }
1885
+ function table(columns, rows) {
1886
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1887
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1888
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1889
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1890
+ ).join("") + "</tr>").join("")
1891
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1892
+ }
1893
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1894
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1895
+ }[char]))
1896
+ const preview = (value) => {
1897
+ const text = JSON.stringify(value)
1898
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1899
+ }
1900
+ const when = (epoch) => {
1901
+ const date = new Date(epoch)
1902
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1903
+ }
1904
+ const clockCard = (epoch) => {
1905
+ const date = new Date(epoch)
1906
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1907
+ const iso = date.toISOString()
1908
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1909
+ }
1910
+
1911
+ async function loadNamespaces() {
1912
+ const data = await api("GET", "/namespaces")
1913
+ const select = $("namespace")
1914
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1915
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1916
+ select.innerHTML = names.map((name) =>
1917
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1918
+ ).join("")
1919
+ select.value = state.namespace
1920
+ }
1921
+
1922
+ async function renderOverview() {
1923
+ const [health, shape, clock, journal] = await Promise.all([
1924
+ originGet("/health"),
1925
+ api("GET", "/state"),
1926
+ api("GET", "/clock"),
1927
+ api("GET", "/requests?limit=8")
1928
+ ])
1929
+ state.shape = shape
1930
+ $("overview-cards").innerHTML = cards([
1931
+ { k: "Service", v: esc(health.service || "${name}") },
1932
+ { k: "Status", v: esc(health.status || "ok") },
1933
+ { k: "Namespace", v: esc(state.namespace) },
1934
+ { k: "Collections", v: String(shape.collections.length) },
1935
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1936
+ { k: "Clock", v: clockCard(clock.now) }
1937
+ ])
1938
+ const requests = (journal && journal.requests) || []
1939
+ $("overview-requests").innerHTML = table(
1940
+ [
1941
+ { label: "Method", cell: (row) => esc(row.method) },
1942
+ { label: "Path", cell: (row) => esc(row.path) },
1943
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1944
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1945
+ ],
1946
+ requests
1947
+ )
1948
+ }
1949
+
1950
+ function schemaChips(collection) {
1951
+ if (!collection || collection.fields.length === 0) {
1952
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1953
+ }
1954
+ return '<div class="chips">' + collection.fields.map((field) =>
1955
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1956
+ ).join("") + "</div>"
1957
+ }
1958
+
1959
+ async function renderState() {
1960
+ const shape = await api("GET", "/state")
1961
+ state.shape = shape
1962
+ const host = $("collections")
1963
+ if (shape.collections.length === 0) {
1964
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1965
+ $("schema").innerHTML = ""
1966
+ $("records").innerHTML = ""
1967
+ return
1968
+ }
1969
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1970
+ state.collection = shape.collections[0].name
1971
+ }
1972
+ host.innerHTML = shape.collections.map((item) =>
1973
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1974
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1975
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1976
+ ).join("")
1977
+ const selected = shape.collections.find((item) => item.name === state.collection)
1978
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1979
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1980
+ schemaChips(selected)
1981
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1982
+ const rows = page.records.map((record) => ({
1983
+ ...record,
1984
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1985
+ }))
1986
+ $("records").innerHTML = table(
1987
+ [
1988
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1989
+ { label: "Seq", cell: (row) => esc(row.seq) },
1990
+ { label: "Value", cell: (row) => preview(row.value) }
1991
+ ],
1992
+ rows
1993
+ )
1994
+ }
1995
+
1996
+ async function renderClock() {
1997
+ const clock = await api("GET", "/clock")
1998
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1999
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2000
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2001
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2002
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2003
+ }
2004
+
2005
+ async function renderFaults() {
2006
+ const [faults, presets] = await Promise.all([
2007
+ api("GET", "/faults"),
2008
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2009
+ ])
2010
+ const select = $("fault-preset")
2011
+ const current = select.value
2012
+ const list = presets.presets || []
2013
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2014
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2015
+ ).join("")
2016
+ select.value = current
2017
+ const rules = faults.faults || []
2018
+ $("fault-list").innerHTML = table(
2019
+ [
2020
+ { label: "Id", cell: (row) => esc(row.id) },
2021
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2022
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2023
+ ],
2024
+ rules
2025
+ )
2026
+ }
2027
+
2028
+ async function renderJournal() {
2029
+ const journal = await api("GET", "/requests?limit=100")
2030
+ $("journal").innerHTML = table(
2031
+ [
2032
+ { label: "When", cell: (row) => esc(row.at || "") },
2033
+ { label: "Method", cell: (row) => esc(row.method) },
2034
+ { label: "Path", cell: (row) => esc(row.path) },
2035
+ { label: "Status", cell: (row) => esc(row.status) },
2036
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2037
+ ],
2038
+ journal.requests || []
2039
+ )
2040
+ }
2041
+
2042
+ async function renderRoutes() {
2043
+ const data = await api("GET", "/")
2044
+ const routes = data.routes || []
2045
+ $("route-list").innerHTML = routes.map((route) => {
2046
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2047
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2048
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2049
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2050
+ }).join("")
2051
+ }
2052
+
2053
+ const renderers = {
2054
+ overview: renderOverview,
2055
+ state: renderState,
2056
+ clock: renderClock,
2057
+ faults: renderFaults,
2058
+ journal: renderJournal,
2059
+ routes: renderRoutes
2060
+ }
2061
+
2062
+ async function refresh() {
2063
+ clearError()
2064
+ if (state.view in renderers) await renderers[state.view]()
2065
+ }
2066
+
2067
+ $("namespace").addEventListener("change", () => {
2068
+ state.namespace = $("namespace").value
2069
+ refresh().catch(showError)
2070
+ })
2071
+ keyInput.addEventListener("change", () => {
2072
+ state.key = keyInput.value.trim()
2073
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2074
+ refresh().catch(showError)
2075
+ })
2076
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2077
+
2078
+ $("collections").addEventListener("click", (event) => {
2079
+ const button = event.target.closest("[data-collection]")
2080
+ if (!button) return
2081
+ state.collection = button.dataset.collection
2082
+ renderState().catch(showError)
2083
+ })
2084
+ $("records").addEventListener("click", (event) => {
2085
+ const row = event.target.closest("[data-id]")
2086
+ if (!row) return
2087
+ openEditor(row.dataset.id).catch(showError)
2088
+ })
2089
+
2090
+ const editor = $("editor")
2091
+ async function openEditor(id) {
2092
+ state.editing = id || null
2093
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2094
+ $("editor-id").value = id || ""
2095
+ $("editor-id").readOnly = Boolean(id)
2096
+ $("editor-delete").hidden = !id
2097
+ if (id) {
2098
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2099
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2100
+ } else {
2101
+ $("editor-value").value = "{\\n \\n}"
2102
+ }
2103
+ editor.showModal()
2104
+ }
2105
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2106
+ $("editor-form").addEventListener("submit", (event) => {
2107
+ const submitter = event.submitter
2108
+ if (!submitter || submitter.value !== "save") return
2109
+ event.preventDefault()
2110
+ let value
2111
+ try { value = JSON.parse($("editor-value").value) }
2112
+ catch { showError(new Error("Value is not JSON")); return }
2113
+ const id = $("editor-id").value.trim()
2114
+ const path = "/state/" + encodeURIComponent(state.collection)
2115
+ const request = state.editing
2116
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2117
+ : api("POST", path, { id: id || undefined, value })
2118
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2119
+ })
2120
+ $("editor-delete").addEventListener("click", () => {
2121
+ const id = state.editing
2122
+ if (!id) return
2123
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2124
+ .then(() => { editor.close(); return renderState() })
2125
+ .catch(showError)
2126
+ })
2127
+
2128
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2129
+ button.addEventListener("click", () => {
2130
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2131
+ })
2132
+ })
2133
+ $("freeze").addEventListener("click", () => {
2134
+ const frozen = $("freeze").dataset.frozen === "1"
2135
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2136
+ })
2137
+ $("clock-reset").addEventListener("click", () => {
2138
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2139
+ })
2140
+ $("clock-set").addEventListener("submit", (event) => {
2141
+ event.preventDefault()
2142
+ const raw = $("clock-instant").value.trim()
2143
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2144
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2145
+ })
2146
+
2147
+ $("fault-form").addEventListener("submit", (event) => {
2148
+ event.preventDefault()
2149
+ const preset = $("fault-preset").value
2150
+ const body = preset
2151
+ ? { preset }
2152
+ : {
2153
+ status: Number($("fault-status").value),
2154
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2155
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2156
+ }
2157
+ if (!preset && !Number.isFinite(body.status)) {
2158
+ showError(new Error("Status must be a number, or choose a preset"))
2159
+ return
2160
+ }
2161
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2162
+ })
2163
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2164
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2165
+
2166
+ $("route-list").addEventListener("click", (event) => {
2167
+ const button = event.target.closest("[data-route]")
2168
+ if (!button) return
2169
+ state.route = button.dataset.route
2170
+ $("route-title").textContent = state.route
2171
+ const method = state.route.split(" ")[0]
2172
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2173
+ })
2174
+ $("route-form").addEventListener("submit", async (event) => {
2175
+ event.preventDefault()
2176
+ if (!state.route) return showError(new Error("Choose a route first"))
2177
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2178
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2179
+ let body
2180
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2181
+ try { body = JSON.parse($("route-body").value) }
2182
+ catch { return showError(new Error("Body is not JSON")) }
2183
+ }
2184
+ try {
2185
+ const data = await api(method, concrete, body)
2186
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2187
+ } catch (error) {
2188
+ showError(error)
2189
+ }
2190
+ })
2191
+
2192
+ function mountPanels(panels) {
2193
+ const nav = $("nav")
2194
+ const views = $("views")
2195
+ for (const panel of panels) {
2196
+ const button = document.createElement("button")
2197
+ button.type = "button"
2198
+ button.dataset.view = panel.id
2199
+ button.textContent = panel.title
2200
+ nav.append(button)
2201
+ const section = document.createElement("section")
2202
+ section.className = "view"
2203
+ section.id = "view-" + panel.id
2204
+ section.hidden = true
2205
+ const title = document.createElement("h2")
2206
+ title.textContent = panel.title
2207
+ const lede = document.createElement("p")
2208
+ lede.className = "lede"
2209
+ lede.textContent = panel.description || ""
2210
+ const body = document.createElement("div")
2211
+ body.className = "panel-body"
2212
+ body.id = "panel-" + panel.id
2213
+ body.innerHTML = panel.html || ""
2214
+ section.append(title, lede, body)
2215
+ views.append(section)
2216
+ if (panel.script) {
2217
+ try {
2218
+ const run = new Function("root", "api", panel.script)
2219
+ run(body, panelApi)
2220
+ } catch (error) {
2221
+ const note = document.createElement("p")
2222
+ note.className = "banner show"
2223
+ note.textContent = error instanceof Error ? error.message : String(error)
2224
+ body.append(note)
2225
+ }
2226
+ }
2227
+ }
2228
+ }
2229
+
2230
+ loadNamespaces()
2231
+ .then(() => api("GET", "/ui/manifest"))
2232
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2233
+ .catch(showError)
2234
+ })()
2235
+ </script>
2236
+ </body>
2237
+ </html>`;
2238
+ };
2239
+ var htmlResponse = (body) => new Response(body, {
2240
+ status: 200,
2241
+ headers: {
2242
+ "content-type": "text/html; charset=utf-8",
2243
+ "cache-control": "no-store"
2244
+ }
2245
+ });
2246
+ var json2 = (body) => new Response(JSON.stringify(body), {
2247
+ status: 200,
2248
+ headers: { "content-type": "application/json; charset=utf-8" }
2249
+ });
2250
+ var adminUiRoutes = (service, ui) => {
2251
+ const shell = () => renderAdminDocument(service);
2252
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2253
+ return {
2254
+ "GET /ui": () => htmlResponse(document2()),
2255
+ "GET /ui/": () => htmlResponse(document2()),
2256
+ "GET /ui/manifest": () => json2({
2257
+ service,
2258
+ panels: (ui?.panels ?? []).map((panel) => ({
2259
+ id: panel.id,
2260
+ title: panel.title,
2261
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2262
+ html: panel.html,
2263
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2264
+ }))
2265
+ })
2266
+ };
2267
+ };
2268
+
1337
2269
  // ../../openapi/metadata/dist/types.js
1338
2270
  var EXTENSION_KEYS = {
1339
2271
  operation: "x-mockingbird",
@@ -1571,15 +2503,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1571
2503
  });
1572
2504
  };
1573
2505
 
2506
+ // ../core/dist/state-view.js
2507
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2508
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2509
+ var SAMPLE = 25;
2510
+ var WALK_LIMIT = 1e4;
2511
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2512
+ var fail = (status, message) => ({ ok: false, status, message });
2513
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2514
+ var kindOf = (value) => {
2515
+ if (value === null)
2516
+ return "null";
2517
+ if (Array.isArray(value))
2518
+ return "array";
2519
+ switch (typeof value) {
2520
+ case "string":
2521
+ return "string";
2522
+ case "number":
2523
+ return Number.isFinite(value) ? "number" : "unknown";
2524
+ case "boolean":
2525
+ return "boolean";
2526
+ case "object":
2527
+ return "object";
2528
+ default:
2529
+ return "unknown";
2530
+ }
2531
+ };
2532
+ var humanize = (name) => {
2533
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2534
+ if (words === "")
2535
+ return name;
2536
+ return words.charAt(0).toUpperCase() + words.slice(1);
2537
+ };
2538
+ var jsonValue = (value) => {
2539
+ if (value === void 0)
2540
+ return fail(400, "value is required");
2541
+ try {
2542
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2543
+ } catch {
2544
+ return fail(400, "value must be JSON");
2545
+ }
2546
+ };
2547
+ var ctorName = (value) => {
2548
+ const ctor = value.constructor;
2549
+ return typeof ctor?.name === "string" ? ctor.name : "";
2550
+ };
2551
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2552
+ var discoverCollections = (root) => {
2553
+ const found = [];
2554
+ const seen = /* @__PURE__ */ new Set();
2555
+ const visit = (value, depth) => {
2556
+ if (found.length + seen.size > WALK_LIMIT)
2557
+ return;
2558
+ if (value === null || typeof value !== "object")
2559
+ return;
2560
+ if (seen.has(value))
2561
+ return;
2562
+ seen.add(value);
2563
+ if (value instanceof Collection) {
2564
+ found.push(value);
2565
+ return;
2566
+ }
2567
+ if (value instanceof Map) {
2568
+ for (const child of value.values())
2569
+ visit(child, depth + 1);
2570
+ return;
2571
+ }
2572
+ if (value instanceof Set) {
2573
+ for (const child of value.values())
2574
+ visit(child, depth + 1);
2575
+ return;
2576
+ }
2577
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2578
+ return;
2579
+ if (Array.isArray(value)) {
2580
+ const cap = Math.min(value.length, 32);
2581
+ for (let i = 0; i < cap; i++)
2582
+ visit(value[i], depth + 1);
2583
+ return;
2584
+ }
2585
+ let children;
2586
+ try {
2587
+ children = Object.values(value);
2588
+ } catch {
2589
+ return;
2590
+ }
2591
+ for (const child of children)
2592
+ visit(child, depth + 1);
2593
+ };
2594
+ visit(root, 0);
2595
+ return found;
2596
+ };
2597
+ var storedNames = (sqlite, namespace) => {
2598
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2599
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2600
+ return [...records, ...sequences].map((row) => row.name);
2601
+ };
2602
+ var blankAccum = (name) => ({
2603
+ name,
2604
+ kinds: /* @__PURE__ */ new Set(),
2605
+ present: 0,
2606
+ nested: /* @__PURE__ */ new Map()
2607
+ });
2608
+ var absorb = (accum, value) => {
2609
+ const kind = kindOf(value);
2610
+ accum.kinds.add(kind);
2611
+ accum.present++;
2612
+ if (!isRecord3(value))
2613
+ return;
2614
+ for (const [key, child] of Object.entries(value)) {
2615
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2616
+ absorb(nested, child);
2617
+ accum.nested.set(key, nested);
2618
+ }
2619
+ };
2620
+ var finishField = (accum, samples) => {
2621
+ const kinds = [...accum.kinds];
2622
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2623
+ const field = {
2624
+ name: accum.name,
2625
+ kind,
2626
+ optional: accum.present < samples || kinds.includes("null")
2627
+ };
2628
+ if (accum.nested.size > 0) {
2629
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2630
+ }
2631
+ return field;
2632
+ };
2633
+ var inferFields = (records) => {
2634
+ if (records.length === 0)
2635
+ return [];
2636
+ const sample = records.slice(0, SAMPLE);
2637
+ const objects = sample.filter((record) => isRecord3(record.value));
2638
+ if (objects.length === 0) {
2639
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2640
+ const list = [...kinds];
2641
+ return [
2642
+ {
2643
+ name: "(value)",
2644
+ kind: list.length === 1 ? list[0] : "unknown",
2645
+ optional: false
2646
+ }
2647
+ ];
2648
+ }
2649
+ const root = /* @__PURE__ */ new Map();
2650
+ for (const record of objects) {
2651
+ for (const [key, value] of Object.entries(record.value)) {
2652
+ const accum = root.get(key) ?? blankAccum(key);
2653
+ absorb(accum, value);
2654
+ root.set(key, accum);
2655
+ }
2656
+ }
2657
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2658
+ };
2659
+ var mergeFields = (declared, inferred) => {
2660
+ const byName = /* @__PURE__ */ new Map();
2661
+ for (const field of inferred)
2662
+ byName.set(field.name, field);
2663
+ const ordered = [];
2664
+ const seen = /* @__PURE__ */ new Set();
2665
+ for (const field of declared ?? []) {
2666
+ const found = byName.get(field.name);
2667
+ seen.add(field.name);
2668
+ if (!found) {
2669
+ ordered.push({ ...field, optional: field.optional });
2670
+ continue;
2671
+ }
2672
+ ordered.push({
2673
+ ...found,
2674
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2675
+ optional: field.optional || found.optional,
2676
+ ...field.description !== void 0 ? { description: field.description } : {},
2677
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2678
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2679
+ });
2680
+ }
2681
+ for (const field of inferred) {
2682
+ if (!seen.has(field.name))
2683
+ ordered.push(field);
2684
+ }
2685
+ return ordered;
2686
+ };
2687
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2688
+ var readRecord = (collection, id) => {
2689
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2690
+ const row = rows.find((entry) => entry.id === id);
2691
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2692
+ };
2693
+ var inspectState = (scope) => {
2694
+ const declared = /* @__PURE__ */ new Map();
2695
+ for (const declaration of scope.declarations ?? []) {
2696
+ if (COLLECTION_NAME.test(declaration.name))
2697
+ declared.set(declaration.name, declaration);
2698
+ }
2699
+ const names = new Set(declared.keys());
2700
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2701
+ names.add(name);
2702
+ for (const collection of discoverCollections(scope.root)) {
2703
+ if (collection.namespace === scope.storageNamespace)
2704
+ names.add(collection.collectionName);
2705
+ }
2706
+ const collections = [];
2707
+ for (const name of names) {
2708
+ if (!COLLECTION_NAME.test(name))
2709
+ continue;
2710
+ const declaration = declared.get(name);
2711
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2712
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2713
+ const inferred = inferFields(records);
2714
+ const fields = mergeFields(declaration?.fields, inferred);
2715
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2716
+ collections.push({
2717
+ name,
2718
+ label: declaration?.label ?? humanize(name),
2719
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2720
+ count: collection.count(),
2721
+ source,
2722
+ fields,
2723
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2724
+ });
2725
+ }
2726
+ const order = /* @__PURE__ */ new Map();
2727
+ for (const [index, item] of (scope.declarations ?? []).entries())
2728
+ order.set(item.name, index);
2729
+ collections.sort((a, b) => {
2730
+ const left = order.get(a.name);
2731
+ const right = order.get(b.name);
2732
+ if (left !== void 0 && right !== void 0)
2733
+ return left - right;
2734
+ if (left !== void 0)
2735
+ return -1;
2736
+ if (right !== void 0)
2737
+ return 1;
2738
+ return a.name.localeCompare(b.name);
2739
+ });
2740
+ return {
2741
+ namespace: scope.namespace,
2742
+ storageNamespace: scope.storageNamespace,
2743
+ collections
2744
+ };
2745
+ };
2746
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2747
+ if (!COLLECTION_NAME.test(name))
2748
+ return fail(400, "collection name is not allowed");
2749
+ const limit = query.limit ?? 50;
2750
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2751
+ return fail(400, "limit must be an integer from 1 to 200");
2752
+ }
2753
+ const order = query.order ?? "newest";
2754
+ if (order !== "newest" && order !== "oldest")
2755
+ return fail(400, 'order must be "newest" or "oldest"');
2756
+ const collection = collectionOf(sqlite, storageNamespace, name);
2757
+ const rows = collection.list({ order }).filter((row) => {
2758
+ if (query.after === void 0)
2759
+ return true;
2760
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2761
+ });
2762
+ const slice = rows.slice(0, limit);
2763
+ const last = slice.at(-1);
2764
+ return {
2765
+ ok: true,
2766
+ value: {
2767
+ collection: name,
2768
+ count: collection.count(),
2769
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2770
+ next: rows.length > limit && last ? last.seq : null
2771
+ }
2772
+ };
2773
+ };
2774
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2775
+ var readStateRecord = (scope, name, id) => {
2776
+ if (!COLLECTION_NAME.test(name))
2777
+ return fail(400, "collection name is not allowed");
2778
+ if (!RECORD_ID.test(id))
2779
+ return fail(400, "record id is not allowed");
2780
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2781
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2782
+ };
2783
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2784
+ var createStateRecord = (scope, name, input) => {
2785
+ if (!COLLECTION_NAME.test(name))
2786
+ return fail(400, "collection name is not allowed");
2787
+ const parsed = jsonValue(input.value);
2788
+ if (!parsed.ok)
2789
+ return parsed;
2790
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2791
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2792
+ const checked = requireId(id);
2793
+ if (!checked.ok)
2794
+ return checked;
2795
+ if (collection.has(checked.value))
2796
+ return fail(409, `record ${checked.value} already exists`);
2797
+ const stored = collection.insert(checked.value, parsed.value);
2798
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2799
+ };
2800
+ var replaceStateRecord = (scope, name, id, value) => {
2801
+ if (!COLLECTION_NAME.test(name))
2802
+ return fail(400, "collection name is not allowed");
2803
+ const checked = requireId(id);
2804
+ if (!checked.ok)
2805
+ return checked;
2806
+ const parsed = jsonValue(value);
2807
+ if (!parsed.ok)
2808
+ return parsed;
2809
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2810
+ if (!collection.has(checked.value))
2811
+ return fail(404, `no record ${checked.value} in ${name}`);
2812
+ const stored = collection.update(checked.value, parsed.value);
2813
+ if (!stored)
2814
+ return fail(404, `no record ${checked.value} in ${name}`);
2815
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2816
+ };
2817
+ var patchStateRecord = (scope, name, id, value) => {
2818
+ const current = readStateRecord(scope, name, id);
2819
+ if (!current.ok)
2820
+ return current;
2821
+ const parsed = jsonValue(value);
2822
+ if (!parsed.ok)
2823
+ return parsed;
2824
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2825
+ return replaceStateRecord(scope, name, id, next);
2826
+ };
2827
+ var deleteStateRecord = (scope, name, id) => {
2828
+ if (!COLLECTION_NAME.test(name))
2829
+ return fail(400, "collection name is not allowed");
2830
+ const checked = requireId(id);
2831
+ if (!checked.ok)
2832
+ return checked;
2833
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2834
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2835
+ };
2836
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2837
+ status,
2838
+ headers: { "content-type": "application/json; charset=utf-8" }
2839
+ });
2840
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2841
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2842
+ var integerParam = (value) => {
2843
+ if (value === null)
2844
+ return void 0;
2845
+ if (!/^-?\d+$/.test(value))
2846
+ return "bad";
2847
+ return Number(value);
2848
+ };
2849
+ var stateAdminRoutes = (routes) => {
2850
+ const open = (namespace) => {
2851
+ try {
2852
+ return { ok: true, value: routes.open(namespace) };
2853
+ } catch (error) {
2854
+ return fail(400, error instanceof Error ? error.message : String(error));
2855
+ }
2856
+ };
2857
+ const wrote = (namespace) => {
2858
+ routes.afterWrite?.(namespace);
2859
+ };
2860
+ return {
2861
+ "GET /state": ({ namespace }) => {
2862
+ const scope = open(namespace);
2863
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2864
+ },
2865
+ "GET /state/:collection": ({ namespace, params, url }) => {
2866
+ const scope = open(namespace);
2867
+ if (!scope.ok)
2868
+ return fromResult(scope, 200);
2869
+ const limit = integerParam(url.searchParams.get("limit"));
2870
+ const after = integerParam(url.searchParams.get("after"));
2871
+ if (limit === "bad")
2872
+ return adminError2(400, "limit: expected an integer");
2873
+ if (after === "bad")
2874
+ return adminError2(400, "after: expected a sequence number");
2875
+ const order = url.searchParams.get("order");
2876
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2877
+ ...limit !== void 0 ? { limit } : {},
2878
+ ...after !== void 0 ? { after } : {},
2879
+ ...order === "newest" || order === "oldest" ? { order } : {}
2880
+ }), 200);
2881
+ },
2882
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2883
+ const scope = open(namespace);
2884
+ if (!scope.ok)
2885
+ return fromResult(scope, 200);
2886
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2887
+ },
2888
+ "POST /state/:collection": ({ namespace, params, body }) => {
2889
+ const scope = open(namespace);
2890
+ if (!scope.ok)
2891
+ return fromResult(scope, 201);
2892
+ if (!isRecord3(body) || !("value" in body)) {
2893
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2894
+ }
2895
+ const id = body.id;
2896
+ if (id !== void 0 && typeof id !== "string")
2897
+ return adminError2(400, "id must be a string");
2898
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2899
+ ...typeof id === "string" ? { id } : {},
2900
+ value: body.value
2901
+ });
2902
+ if (created.ok)
2903
+ wrote(namespace);
2904
+ return fromResult(created, 201);
2905
+ },
2906
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2907
+ const scope = open(namespace);
2908
+ if (!scope.ok)
2909
+ return fromResult(scope, 200);
2910
+ if (!isRecord3(body) || !("value" in body))
2911
+ return adminError2(400, 'expected {"value": <json>}');
2912
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2913
+ if (replaced.ok)
2914
+ wrote(namespace);
2915
+ return fromResult(replaced, 200);
2916
+ },
2917
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2918
+ const scope = open(namespace);
2919
+ if (!scope.ok)
2920
+ return fromResult(scope, 200);
2921
+ if (!isRecord3(body) || !("value" in body))
2922
+ return adminError2(400, 'expected {"value": <json>}');
2923
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2924
+ if (patched.ok)
2925
+ wrote(namespace);
2926
+ return fromResult(patched, 200);
2927
+ },
2928
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2929
+ const scope = open(namespace);
2930
+ if (!scope.ok)
2931
+ return fromResult(scope, 200);
2932
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2933
+ if (removed.ok)
2934
+ wrote(namespace);
2935
+ return fromResult(removed, 200);
2936
+ }
2937
+ };
2938
+ };
2939
+
1574
2940
  // ../core/dist/version.js
1575
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
2941
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1576
2942
 
1577
2943
  // ../core/dist/webhooks.js
1578
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1579
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1580
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2944
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2945
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2946
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1581
2947
  var parseEndpoint = (value) => {
1582
- if (!isRecord3(value) || typeof value.url !== "string")
2948
+ if (!isRecord4(value) || typeof value.url !== "string")
1583
2949
  return "each endpoint needs a url";
1584
2950
  try {
1585
2951
  new URL(value.url);
@@ -1596,18 +2962,18 @@ var parseEndpoint = (value) => {
1596
2962
  const events = value.events ?? value.enabledEvents;
1597
2963
  if (Array.isArray(events))
1598
2964
  endpoint.events = events.map(String);
1599
- if (isRecord3(value.tags)) {
2965
+ if (isRecord4(value.tags)) {
1600
2966
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1601
2967
  }
1602
2968
  if (typeof value.account === "string")
1603
2969
  endpoint.tags = { ...endpoint.tags, account: value.account };
1604
- if (isRecord3(value.headers)) {
2970
+ if (isRecord4(value.headers)) {
1605
2971
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1606
2972
  }
1607
2973
  return endpoint;
1608
2974
  };
1609
2975
  var webhookAdminRoutes = (hub) => ({
1610
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2976
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1611
2977
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1612
2978
  const type = url.searchParams.get("type");
1613
2979
  return type === null || d.type === type;
@@ -1615,51 +2981,51 @@ var webhookAdminRoutes = (hub) => ({
1615
2981
  }),
1616
2982
  "GET /webhooks/events": ({ url, namespace }) => {
1617
2983
  const type = url.searchParams.get("type");
1618
- return json2(200, {
2984
+ return json4(200, {
1619
2985
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1620
2986
  });
1621
2987
  },
1622
2988
  "POST /webhooks/:id/replay": async ({ params }) => {
1623
2989
  const replayed = await hub.replay(params.id);
1624
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2990
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1625
2991
  },
1626
2992
  "POST /webhooks/flush": async () => {
1627
2993
  await hub.flush();
1628
- return json2(200, { status: "ok" });
2994
+ return json4(200, { status: "ok" });
1629
2995
  },
1630
2996
  "POST /webhooks/faults": ({ body, namespace }) => {
1631
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1632
- return adminError2(400, "mode must be duplicate, reorder or drop");
2997
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2998
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1633
2999
  }
1634
3000
  const fault = { mode: body.mode };
1635
3001
  if (typeof body.count === "number")
1636
3002
  fault.count = body.count;
1637
3003
  hub.fault(namespace, fault);
1638
- return json2(201, { namespace, ...fault });
3004
+ return json4(201, { namespace, ...fault });
1639
3005
  },
1640
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3006
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1641
3007
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1642
3008
  ...rest,
1643
3009
  secret: secret ? "(set)" : null
1644
3010
  }))
1645
3011
  }),
1646
3012
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1647
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3013
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1648
3014
  if (!Array.isArray(list))
1649
- return adminError2(400, "expected [{url, secret?, events?}]");
3015
+ return adminError3(400, "expected [{url, secret?, events?}]");
1650
3016
  const parsed = [];
1651
3017
  for (const each of list) {
1652
3018
  const endpoint = parseEndpoint(each);
1653
3019
  if (typeof endpoint === "string")
1654
- return adminError2(400, endpoint);
3020
+ return adminError3(400, endpoint);
1655
3021
  parsed.push(endpoint);
1656
3022
  }
1657
3023
  const set = hub.setEndpoints(namespace, parsed);
1658
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3024
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1659
3025
  },
1660
3026
  "DELETE /webhook-endpoints": ({ namespace }) => {
1661
3027
  hub.setEndpoints(namespace, []);
1662
- return json2(200, { status: "ok" });
3028
+ return json4(200, { status: "ok" });
1663
3029
  }
1664
3030
  });
1665
3031
  var parsePayload = (message) => {
@@ -1724,6 +3090,7 @@ var operationMatcher = (document2) => {
1724
3090
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1725
3091
  };
1726
3092
  var createRuntime = (options) => {
3093
+ assertAdminUi(options.adminUi);
1727
3094
  const sqlite = bootSqlite(options.sqlite);
1728
3095
  const clock = options.clock ?? createClock();
1729
3096
  const rng = createRng(options.seed ?? 0);
@@ -1930,6 +3297,19 @@ var createRuntime = (options) => {
1930
3297
  else
1931
3298
  timeline(name);
1932
3299
  };
3300
+ const declarationsFor = (namespace) => {
3301
+ const declared = options.state;
3302
+ if (!declared)
3303
+ return [];
3304
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3305
+ };
3306
+ const stateScope = (namespace) => ({
3307
+ sqlite,
3308
+ namespace,
3309
+ storageNamespace: storageNamespace(namespace),
3310
+ root: instance(namespace),
3311
+ declarations: declarationsFor(namespace)
3312
+ });
1933
3313
  const runtime = {
1934
3314
  name: options.name,
1935
3315
  sqlite,
@@ -1968,6 +3348,7 @@ var createRuntime = (options) => {
1968
3348
  branch,
1969
3349
  checkout,
1970
3350
  timeline,
3351
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1971
3352
  fetch: async (incoming) => {
1972
3353
  let request = incoming;
1973
3354
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2161,11 +3542,20 @@ var createRuntime = (options) => {
2161
3542
  ...credentialRoutes(credentials),
2162
3543
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2163
3544
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2164
- ...options.admin?.(runtime) ?? {}
3545
+ ...options.admin?.(runtime) ?? {},
3546
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3547
+ // beside these; it does not replace `/state` or `/ui`.
3548
+ ...stateAdminRoutes({
3549
+ open: stateScope,
3550
+ afterWrite: (namespace) => {
3551
+ checkpoint(namespace, "main");
3552
+ }
3553
+ }),
3554
+ ...adminUiRoutes(options.name, options.adminUi)
2165
3555
  },
2166
3556
  adminKey: options.adminKey
2167
3557
  });
2168
- return runtime;
3558
+ return defineMock(runtime);
2169
3559
  };
2170
3560
  var mutableResponse = (response) => {
2171
3561
  try {
@@ -2337,12 +3727,12 @@ var PRISM_PRESETS = {
2337
3727
  rules: [{ pathPrefix: "/scans", drop: true }]
2338
3728
  }
2339
3729
  };
2340
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2341
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2342
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3730
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3731
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3732
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2343
3733
  var parseAutoAdvance = (value) => {
2344
3734
  if (value === null) return null;
2345
- if (!isRecord4(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
3735
+ if (!isRecord5(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
2346
3736
  return "autoAdvance must be {afterMs, failAt?} or null";
2347
3737
  }
2348
3738
  if (value.failAt !== void 0 && !STAGES.includes(value.failAt)) {
@@ -2351,42 +3741,42 @@ var parseAutoAdvance = (value) => {
2351
3741
  return { afterMs: value.afterMs, ...value.failAt ? { failAt: value.failAt } : {} };
2352
3742
  };
2353
3743
  var adminRoutes = (runtime) => ({
2354
- "GET /scans": ({ namespace }) => json3(200, { scans: runtime.instance(namespace).scans() }),
3744
+ "GET /scans": ({ namespace }) => json5(200, { scans: runtime.instance(namespace).scans() }),
2355
3745
  "POST /scans/:id/advance": ({ params, body, namespace }) => {
2356
3746
  const api = runtime.instance(namespace);
2357
- const steps = isRecord4(body) && body.to === "READY" ? STAGES.length : 1;
3747
+ const steps = isRecord5(body) && body.to === "READY" ? STAGES.length : 1;
2358
3748
  let scan = api.state.scans.get(params.id);
2359
- if (!scan) return adminError3(404, `no scan ${params.id}`);
3749
+ if (!scan) return adminError4(404, `no scan ${params.id}`);
2360
3750
  if (scan.status !== "PROCESSING") {
2361
- return adminError3(409, `scan ${params.id} is ${scan.status}; upload its capture first`);
3751
+ return adminError4(409, `scan ${params.id} is ${scan.status}; upload its capture first`);
2362
3752
  }
2363
3753
  for (let i = 0; i < steps && scan?.status === "PROCESSING"; i++) scan = api.advance(scan.id);
2364
- return json3(200, scan);
3754
+ return json5(200, scan);
2365
3755
  },
2366
3756
  "POST /scans/:id/fail": ({ params, namespace }) => {
2367
3757
  const scan = runtime.instance(namespace).advance(params.id, true);
2368
- return scan ? json3(200, scan) : adminError3(404, `no scan ${params.id}`);
3758
+ return scan ? json5(200, scan) : adminError4(404, `no scan ${params.id}`);
2369
3759
  },
2370
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
3760
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
2371
3761
  "PUT /settings": ({ body, namespace }) => {
2372
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
3762
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2373
3763
  const patch = {};
2374
3764
  if (body.apiKeys !== void 0) {
2375
- if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
3765
+ if (!Array.isArray(body.apiKeys)) return adminError4(400, "apiKeys: string[]");
2376
3766
  patch.apiKeys = body.apiKeys.map(String);
2377
3767
  }
2378
3768
  if (body.uploadUrlTtlMs !== void 0) {
2379
- if (typeof body.uploadUrlTtlMs !== "number") return adminError3(400, "uploadUrlTtlMs: number");
3769
+ if (typeof body.uploadUrlTtlMs !== "number") return adminError4(400, "uploadUrlTtlMs: number");
2380
3770
  patch.uploadUrlTtlMs = body.uploadUrlTtlMs;
2381
3771
  }
2382
3772
  if (body.autoAdvance !== void 0) {
2383
3773
  const parsed = parseAutoAdvance(body.autoAdvance);
2384
- if (typeof parsed === "string") return adminError3(400, parsed);
3774
+ if (typeof parsed === "string") return adminError4(400, parsed);
2385
3775
  patch.autoAdvance = parsed;
2386
3776
  }
2387
- return json3(200, runtime.instance(namespace).state.update(patch));
3777
+ return json5(200, runtime.instance(namespace).state.update(patch));
2388
3778
  },
2389
- "POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
3779
+ "POST /tick": ({ namespace }) => json5(200, { applied: runtime.instance(namespace).tick() })
2390
3780
  });
2391
3781
  var createRuntime2 = (options = {}) => {
2392
3782
  const runtime = createRuntime({
@@ -2777,7 +4167,7 @@ var PrismAPI = class {
2777
4167
  * Move a PROCESSING scan one stage on: the started stage succeeds (or fails, when `fail` is
2778
4168
  * set) and the next one starts; after `measurement` the scan is READY.
2779
4169
  */
2780
- advance(scanId, fail = false) {
4170
+ advance(scanId, fail2 = false) {
2781
4171
  const scan = this.state.scans.get(scanId);
2782
4172
  if (scan?.status !== "PROCESSING") return scan;
2783
4173
  const now = this.iso();
@@ -2785,14 +4175,14 @@ var PrismAPI = class {
2785
4175
  if (!current) return scan;
2786
4176
  const stages = {
2787
4177
  ...scan.stages,
2788
- [current]: { status: fail ? "failed" : "succeeded", updatedAt: now }
4178
+ [current]: { status: fail2 ? "failed" : "succeeded", updatedAt: now }
2789
4179
  };
2790
4180
  const nextStage = STAGES[STAGES.indexOf(current) + 1];
2791
- if (!fail && nextStage) stages[nextStage] = { status: "started", updatedAt: now };
4181
+ if (!fail2 && nextStage) stages[nextStage] = { status: "started", updatedAt: now };
2792
4182
  const next = {
2793
4183
  ...scan,
2794
4184
  stages,
2795
- status: fail ? "FAILED" : nextStage ? "PROCESSING" : "READY",
4185
+ status: fail2 ? "FAILED" : nextStage ? "PROCESSING" : "READY",
2796
4186
  updatedAt: now
2797
4187
  };
2798
4188
  this.state.scans.update(scanId, next);
@@ -2835,4 +4225,4 @@ export {
2835
4225
  scanResults,
2836
4226
  PrismAPI
2837
4227
  };
2838
- //# sourceMappingURL=chunk-Y7E4KKNJ.js.map
4228
+ //# sourceMappingURL=chunk-3QCJCNZT.js.map