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