@crvouga/mockingbird-service-flex 1.2.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
 
@@ -1394,6 +1396,936 @@ var clearNamespace = (sqlite, namespace) => {
1394
1396
  });
1395
1397
  };
1396
1398
 
1399
+ // ../core/dist/surface.js
1400
+ var defineMock = (runtime) => runtime;
1401
+ var STANDARD_ADMIN_ROUTES = [
1402
+ "GET /",
1403
+ "POST /reset",
1404
+ "GET /namespaces",
1405
+ "GET /clock",
1406
+ "POST /clock",
1407
+ "GET /faults",
1408
+ "POST /faults",
1409
+ "DELETE /faults",
1410
+ "POST /snapshots",
1411
+ "POST /snapshots/:id/restore",
1412
+ "DELETE /snapshots/:id",
1413
+ "GET /timeline",
1414
+ "POST /checkpoints",
1415
+ "POST /branches/:name",
1416
+ "POST /branches/:name/checkout",
1417
+ "GET /requests",
1418
+ "DELETE /requests",
1419
+ "GET /metrics",
1420
+ "DELETE /metrics",
1421
+ "GET /credentials",
1422
+ "PUT /credentials",
1423
+ "DELETE /credentials",
1424
+ "GET /state",
1425
+ "GET /state/:collection",
1426
+ "GET /state/:collection/:id",
1427
+ "POST /state/:collection",
1428
+ "PUT /state/:collection/:id",
1429
+ "PATCH /state/:collection/:id",
1430
+ "DELETE /state/:collection/:id",
1431
+ "GET /ui",
1432
+ "GET /ui/",
1433
+ "GET /ui/manifest"
1434
+ ];
1435
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1436
+ var assertAdminUi = (ui) => {
1437
+ if (!ui?.panels)
1438
+ return;
1439
+ const seen = /* @__PURE__ */ new Set();
1440
+ for (const panel of ui.panels) {
1441
+ if (!PANEL_ID.test(panel.id)) {
1442
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1443
+ }
1444
+ if (seen.has(panel.id))
1445
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1446
+ seen.add(panel.id);
1447
+ if (panel.title.trim() === "")
1448
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1449
+ }
1450
+ };
1451
+
1452
+ // ../core/dist/admin-ui.js
1453
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1454
+ switch (char) {
1455
+ case "&":
1456
+ return "&amp;";
1457
+ case "<":
1458
+ return "&lt;";
1459
+ case ">":
1460
+ return "&gt;";
1461
+ case '"':
1462
+ return "&quot;";
1463
+ default:
1464
+ return "&#39;";
1465
+ }
1466
+ });
1467
+ var renderAdminDocument = (service) => {
1468
+ const name = escapeHtml(service);
1469
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1470
+ return `<!DOCTYPE html>
1471
+ <html lang="en">
1472
+ <head>
1473
+ <meta charset="utf-8">
1474
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1475
+ <meta name="color-scheme" content="light dark">
1476
+ <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">
1477
+ <title>${name} admin</title>
1478
+ <style>
1479
+ :root {
1480
+ color-scheme: light;
1481
+ --bg: #f6f5f2;
1482
+ --bg-elev: #ffffff;
1483
+ --bg-muted: #eeece6;
1484
+ --bg-inset: #f3f1eb;
1485
+ --line: #e2dfd6;
1486
+ --line-strong: #d0ccc1;
1487
+ --ink: #1c1915;
1488
+ --muted: #5e584f;
1489
+ --faint: #8a8378;
1490
+ --accent: #3d4f3a;
1491
+ --accent-ink: #f7f6f2;
1492
+ --accent-soft: #e5ece2;
1493
+ --ok: #1f7a45;
1494
+ --ok-soft: #e5f4eb;
1495
+ --warn: #9a6700;
1496
+ --warn-soft: #fbf3df;
1497
+ --err: #a33b32;
1498
+ --err-soft: #fdecea;
1499
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1500
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1501
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1502
+ --radius: 14px;
1503
+ --header: 60px;
1504
+ --nav: 220px;
1505
+ }
1506
+ :root[data-theme="dark"] {
1507
+ color-scheme: dark;
1508
+ --bg: #141311;
1509
+ --bg-elev: #1e1c19;
1510
+ --bg-muted: #26231f;
1511
+ --bg-inset: #181715;
1512
+ --line: #34302b;
1513
+ --line-strong: #4a453d;
1514
+ --ink: #f4f1ea;
1515
+ --muted: #c4bdb1;
1516
+ --faint: #8f877c;
1517
+ --accent: #c5d5b8;
1518
+ --accent-ink: #1a2118;
1519
+ --accent-soft: #2a3328;
1520
+ --ok: #8fd6a8;
1521
+ --ok-soft: #1a2e22;
1522
+ --warn: #f0cc78;
1523
+ --warn-soft: #332911;
1524
+ --err: #f0a8a2;
1525
+ --err-soft: #3a201e;
1526
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1527
+ }
1528
+ @media (prefers-color-scheme: dark) {
1529
+ :root:not([data-theme="light"]) {
1530
+ color-scheme: dark;
1531
+ --bg: #141311;
1532
+ --bg-elev: #1e1c19;
1533
+ --bg-muted: #26231f;
1534
+ --bg-inset: #181715;
1535
+ --line: #34302b;
1536
+ --line-strong: #4a453d;
1537
+ --ink: #f4f1ea;
1538
+ --muted: #c4bdb1;
1539
+ --faint: #8f877c;
1540
+ --accent: #c5d5b8;
1541
+ --accent-ink: #1a2118;
1542
+ --accent-soft: #2a3328;
1543
+ --ok: #8fd6a8;
1544
+ --ok-soft: #1a2e22;
1545
+ --warn: #f0cc78;
1546
+ --warn-soft: #332911;
1547
+ --err: #f0a8a2;
1548
+ --err-soft: #3a201e;
1549
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1550
+ }
1551
+ }
1552
+ * { box-sizing: border-box; }
1553
+ html, body { margin: 0; height: 100%; }
1554
+ body {
1555
+ font-family: var(--sans);
1556
+ background: var(--bg);
1557
+ color: var(--ink);
1558
+ line-height: 1.45;
1559
+ padding-left: env(safe-area-inset-left);
1560
+ padding-right: env(safe-area-inset-right);
1561
+ -webkit-text-size-adjust: 100%;
1562
+ }
1563
+ button, input, select, textarea { font: inherit; color: inherit; }
1564
+ button { cursor: pointer; }
1565
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1566
+ @media (prefers-reduced-motion: reduce) {
1567
+ * { scroll-behavior: auto !important; transition: none !important; }
1568
+ }
1569
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1570
+ header.top {
1571
+ position: sticky; top: 0; z-index: 5;
1572
+ display: flex; align-items: center; gap: 12px;
1573
+ min-height: var(--header); padding: 10px 16px;
1574
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1575
+ border-bottom: 1px solid var(--line);
1576
+ backdrop-filter: blur(10px);
1577
+ }
1578
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1579
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1580
+ .brand span { color: var(--faint); font-size: 12px; }
1581
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1582
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1583
+ label.field input, label.field select, .controls input[type="password"] {
1584
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1585
+ padding: 7px 8px; min-height: 36px;
1586
+ }
1587
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1588
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1589
+ background: var(--bg-elev);
1590
+ }
1591
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1592
+ .btn-quiet { background: transparent; }
1593
+ .btn-danger { color: var(--err); }
1594
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1595
+ record or the full nav row would widen the page past the viewport. */
1596
+ .layout {
1597
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1598
+ flex: 1; min-height: 0; min-width: 0;
1599
+ }
1600
+ nav.side {
1601
+ border-right: 1px solid var(--line); padding: 12px;
1602
+ display: flex; flex-direction: column; gap: 4px;
1603
+ background: var(--bg-elev);
1604
+ }
1605
+ nav.side button {
1606
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1607
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1608
+ }
1609
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1610
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1611
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1612
+ .lede { margin: 0 0 16px; color: var(--muted); }
1613
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1614
+ .card {
1615
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1616
+ padding: 14px 16px; box-shadow: var(--shadow);
1617
+ }
1618
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1619
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1620
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1621
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1622
+ .collection {
1623
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1624
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1625
+ }
1626
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1627
+ .collection small { display: block; color: var(--faint); }
1628
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1629
+ .chip {
1630
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1631
+ border-radius: 999px; padding: 4px 8px;
1632
+ }
1633
+ .chip i { color: var(--faint); font-style: normal; }
1634
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1635
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1636
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1637
+ tr.clickable { cursor: pointer; }
1638
+ tr.clickable:hover { background: var(--bg-muted); }
1639
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1640
+ pre {
1641
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1642
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1643
+ }
1644
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1645
+ .banner {
1646
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1647
+ background: var(--err-soft); color: var(--err);
1648
+ }
1649
+ .banner.show { display: block; }
1650
+ .empty { color: var(--muted); padding: 24px 8px; }
1651
+ dialog {
1652
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1653
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1654
+ }
1655
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1656
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1657
+ textarea {
1658
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1659
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1660
+ font-family: var(--mono); font-size: 12px;
1661
+ }
1662
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1663
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1664
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1665
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1666
+ .status-2 { color: var(--ok); }
1667
+ .status-4, .status-5, .status-0 { color: var(--err); }
1668
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1669
+ .route {
1670
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1671
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1672
+ }
1673
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1674
+ @media (max-width: 800px) {
1675
+ header.top {
1676
+ align-items: stretch; flex-direction: column;
1677
+ padding-top: max(10px, env(safe-area-inset-top));
1678
+ }
1679
+ input, select, textarea { font-size: 16px; }
1680
+ .controls { width: 100%; }
1681
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1682
+ .layout { grid-template-columns: minmax(0, 1fr); }
1683
+ nav.side {
1684
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1685
+ border-right: 0; border-bottom: 1px solid var(--line);
1686
+ padding: 8px;
1687
+ }
1688
+ nav.side button { white-space: nowrap; flex: none; }
1689
+ .split { grid-template-columns: minmax(0, 1fr); }
1690
+ main { padding: 14px; }
1691
+ table, thead, tbody, tr, th, td { display: block; }
1692
+ thead { display: none; }
1693
+ tr {
1694
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1695
+ background: var(--bg-elev); min-width: 0;
1696
+ }
1697
+ td {
1698
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1699
+ min-width: 0; overflow-wrap: anywhere;
1700
+ }
1701
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1702
+ .route { grid-template-columns: 72px 1fr; }
1703
+ .route button { grid-column: 1 / -1; }
1704
+ }
1705
+ </style>
1706
+ </head>
1707
+ <body>
1708
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1709
+ <header class="top">
1710
+ <div class="brand">
1711
+ <strong>${name}</strong>
1712
+ <span>Mockingbird admin</span>
1713
+ </div>
1714
+ <div class="controls">
1715
+ <label class="field">Namespace
1716
+ <select id="namespace" aria-label="Namespace"></select>
1717
+ </label>
1718
+ <label class="field">Admin key
1719
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1720
+ </label>
1721
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1722
+ <button class="btn" id="refresh" type="button">Refresh</button>
1723
+ </div>
1724
+ </header>
1725
+ <div class="layout">
1726
+ <nav class="side" id="nav" aria-label="Admin sections">
1727
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1728
+ <button type="button" data-view="state">State</button>
1729
+ <button type="button" data-view="clock">Clock</button>
1730
+ <button type="button" data-view="faults">Faults</button>
1731
+ <button type="button" data-view="journal">Journal</button>
1732
+ <button type="button" data-view="routes">Routes</button>
1733
+ </nav>
1734
+ <main id="views">
1735
+ <p class="banner" id="banner" role="alert"></p>
1736
+ <section class="view" id="view-overview">
1737
+ <h2>Overview</h2>
1738
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1739
+ <div class="grid" id="overview-cards"></div>
1740
+ <h3>Recent requests</h3>
1741
+ <div id="overview-requests"></div>
1742
+ </section>
1743
+ <section class="view" id="view-state" hidden>
1744
+ <h2>State</h2>
1745
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1746
+ <div class="split">
1747
+ <div id="collections"></div>
1748
+ <div>
1749
+ <div id="schema"></div>
1750
+ <div class="row-actions">
1751
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1752
+ </div>
1753
+ <div id="records"></div>
1754
+ </div>
1755
+ </div>
1756
+ </section>
1757
+ <section class="view" id="view-clock" hidden>
1758
+ <h2>Clock</h2>
1759
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1760
+ <div class="card" id="clock-readout"></div>
1761
+ <div class="row-actions">
1762
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1763
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1764
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1765
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1766
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1767
+ <button class="btn" id="freeze" type="button">Freeze</button>
1768
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1769
+ </div>
1770
+ <form id="clock-set" class="row-actions">
1771
+ <label class="field">Set instant
1772
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1773
+ </label>
1774
+ <button class="btn-primary" type="submit">Set</button>
1775
+ </form>
1776
+ </section>
1777
+ <section class="view" id="view-faults" hidden>
1778
+ <h2>Faults</h2>
1779
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1780
+ <form id="fault-form" class="card stack">
1781
+ <label class="field">Preset
1782
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1783
+ </label>
1784
+ <label class="field">Status
1785
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1786
+ </label>
1787
+ <label class="field">Path prefix
1788
+ <input id="fault-path" placeholder="/v1">
1789
+ </label>
1790
+ <label class="field">Method
1791
+ <input id="fault-method" placeholder="GET">
1792
+ </label>
1793
+ <div class="dialog-actions">
1794
+ <button class="btn-primary" type="submit">Add fault</button>
1795
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1796
+ </div>
1797
+ </form>
1798
+ <div id="fault-list"></div>
1799
+ </section>
1800
+ <section class="view" id="view-journal" hidden>
1801
+ <h2>Journal</h2>
1802
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1803
+ <div class="row-actions">
1804
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1805
+ </div>
1806
+ <div id="journal"></div>
1807
+ </section>
1808
+ <section class="view" id="view-routes" hidden>
1809
+ <h2>Routes</h2>
1810
+ <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>
1811
+ <div id="route-list"></div>
1812
+ <form id="route-form" class="card stack">
1813
+ <strong id="route-title">Select a route</strong>
1814
+ <label class="field">JSON body
1815
+ <textarea id="route-body" placeholder="{ }"></textarea>
1816
+ </label>
1817
+ <div class="dialog-actions">
1818
+ <button class="btn-primary" type="submit">Send</button>
1819
+ </div>
1820
+ <pre id="route-result">Response will show here.</pre>
1821
+ </form>
1822
+ </section>
1823
+ </main>
1824
+ </div>
1825
+ </div>
1826
+ <dialog id="editor">
1827
+ <form method="dialog" id="editor-form">
1828
+ <strong id="editor-title">Record</strong>
1829
+ <label class="field">Id
1830
+ <input id="editor-id" required>
1831
+ </label>
1832
+ <label class="field">JSON value
1833
+ <textarea id="editor-value"></textarea>
1834
+ </label>
1835
+ <div class="dialog-actions">
1836
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1837
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1838
+ <button class="btn-primary" type="submit" value="save">Save</button>
1839
+ </div>
1840
+ </form>
1841
+ </dialog>
1842
+ <script>
1843
+ (() => {
1844
+ const STANDARD = new Set(${standard})
1845
+ const state = {
1846
+ namespace: "default",
1847
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1848
+ view: "overview",
1849
+ collection: "",
1850
+ shape: null,
1851
+ route: null,
1852
+ editing: null
1853
+ }
1854
+ const $ = (id) => document.getElementById(id)
1855
+ const banner = $("banner")
1856
+ const keyInput = $("admin-key")
1857
+ keyInput.value = state.key
1858
+ const params = new URLSearchParams(location.search)
1859
+ if (params.get("key")) {
1860
+ state.key = params.get("key")
1861
+ keyInput.value = state.key
1862
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1863
+ params.delete("key")
1864
+ const next = params.toString()
1865
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1866
+ }
1867
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1868
+
1869
+ const showError = (error) => {
1870
+ banner.textContent = error instanceof Error ? error.message : String(error)
1871
+ banner.classList.add("show")
1872
+ }
1873
+ const clearError = () => banner.classList.remove("show")
1874
+
1875
+ async function originGet(path) {
1876
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1877
+ if (!response.ok) throw new Error(response.status + " " + path)
1878
+ return response.json()
1879
+ }
1880
+ async function api(method, path, body) {
1881
+ const headers = { accept: "application/json" }
1882
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1883
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1884
+ if (body !== undefined) headers["content-type"] = "application/json"
1885
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1886
+ method,
1887
+ headers,
1888
+ body: body === undefined ? undefined : JSON.stringify(body)
1889
+ })
1890
+ const text = await response.text()
1891
+ let data = null
1892
+ if (text) {
1893
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1894
+ }
1895
+ if (response.status === 401) {
1896
+ keyInput.focus()
1897
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1898
+ }
1899
+ if (!response.ok) {
1900
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1901
+ }
1902
+ return data
1903
+ }
1904
+ const panelApi = {
1905
+ get: (path) => api("GET", path),
1906
+ send: (method, path, body) => api(method, path, body),
1907
+ namespace: () => state.namespace
1908
+ }
1909
+
1910
+ function setTheme(theme) {
1911
+ if (theme) document.documentElement.dataset.theme = theme
1912
+ else delete document.documentElement.dataset.theme
1913
+ }
1914
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1915
+ if (storedTheme) setTheme(storedTheme)
1916
+ $("theme").addEventListener("click", () => {
1917
+ const current = document.documentElement.dataset.theme
1918
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1919
+ const next = dark ? "light" : "dark"
1920
+ localStorage.setItem("mockingbird-admin-theme", next)
1921
+ setTheme(next)
1922
+ })
1923
+
1924
+ function show(view) {
1925
+ state.view = view
1926
+ for (const button of document.querySelectorAll("#nav button")) {
1927
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1928
+ }
1929
+ for (const section of document.querySelectorAll("main .view")) {
1930
+ section.hidden = section.id !== "view-" + view
1931
+ }
1932
+ }
1933
+ document.getElementById("nav").addEventListener("click", (event) => {
1934
+ const button = event.target.closest("button[data-view]")
1935
+ if (!button) return
1936
+ show(button.dataset.view)
1937
+ refresh().catch(showError)
1938
+ })
1939
+
1940
+ function cards(items) {
1941
+ return '<div class="grid">' + items.map((item) =>
1942
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1943
+ ).join("") + "</div>"
1944
+ }
1945
+ function table(columns, rows) {
1946
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1947
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1948
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1949
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1950
+ ).join("") + "</tr>").join("")
1951
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1952
+ }
1953
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1954
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1955
+ }[char]))
1956
+ const preview = (value) => {
1957
+ const text = JSON.stringify(value)
1958
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1959
+ }
1960
+ const when = (epoch) => {
1961
+ const date = new Date(epoch)
1962
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1963
+ }
1964
+ const clockCard = (epoch) => {
1965
+ const date = new Date(epoch)
1966
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1967
+ const iso = date.toISOString()
1968
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1969
+ }
1970
+
1971
+ async function loadNamespaces() {
1972
+ const data = await api("GET", "/namespaces")
1973
+ const select = $("namespace")
1974
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1975
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1976
+ select.innerHTML = names.map((name) =>
1977
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1978
+ ).join("")
1979
+ select.value = state.namespace
1980
+ }
1981
+
1982
+ async function renderOverview() {
1983
+ const [health, shape, clock, journal] = await Promise.all([
1984
+ originGet("/health"),
1985
+ api("GET", "/state"),
1986
+ api("GET", "/clock"),
1987
+ api("GET", "/requests?limit=8")
1988
+ ])
1989
+ state.shape = shape
1990
+ $("overview-cards").innerHTML = cards([
1991
+ { k: "Service", v: esc(health.service || "${name}") },
1992
+ { k: "Status", v: esc(health.status || "ok") },
1993
+ { k: "Namespace", v: esc(state.namespace) },
1994
+ { k: "Collections", v: String(shape.collections.length) },
1995
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1996
+ { k: "Clock", v: clockCard(clock.now) }
1997
+ ])
1998
+ const requests = (journal && journal.requests) || []
1999
+ $("overview-requests").innerHTML = table(
2000
+ [
2001
+ { label: "Method", cell: (row) => esc(row.method) },
2002
+ { label: "Path", cell: (row) => esc(row.path) },
2003
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
2004
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
2005
+ ],
2006
+ requests
2007
+ )
2008
+ }
2009
+
2010
+ function schemaChips(collection) {
2011
+ if (!collection || collection.fields.length === 0) {
2012
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2013
+ }
2014
+ return '<div class="chips">' + collection.fields.map((field) =>
2015
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2016
+ ).join("") + "</div>"
2017
+ }
2018
+
2019
+ async function renderState() {
2020
+ const shape = await api("GET", "/state")
2021
+ state.shape = shape
2022
+ const host = $("collections")
2023
+ if (shape.collections.length === 0) {
2024
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2025
+ $("schema").innerHTML = ""
2026
+ $("records").innerHTML = ""
2027
+ return
2028
+ }
2029
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2030
+ state.collection = shape.collections[0].name
2031
+ }
2032
+ host.innerHTML = shape.collections.map((item) =>
2033
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2034
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2035
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2036
+ ).join("")
2037
+ const selected = shape.collections.find((item) => item.name === state.collection)
2038
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2039
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2040
+ schemaChips(selected)
2041
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2042
+ const rows = page.records.map((record) => ({
2043
+ ...record,
2044
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2045
+ }))
2046
+ $("records").innerHTML = table(
2047
+ [
2048
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2049
+ { label: "Seq", cell: (row) => esc(row.seq) },
2050
+ { label: "Value", cell: (row) => preview(row.value) }
2051
+ ],
2052
+ rows
2053
+ )
2054
+ }
2055
+
2056
+ async function renderClock() {
2057
+ const clock = await api("GET", "/clock")
2058
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2059
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2060
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2061
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2062
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2063
+ }
2064
+
2065
+ async function renderFaults() {
2066
+ const [faults, presets] = await Promise.all([
2067
+ api("GET", "/faults"),
2068
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2069
+ ])
2070
+ const select = $("fault-preset")
2071
+ const current = select.value
2072
+ const list = presets.presets || []
2073
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2074
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2075
+ ).join("")
2076
+ select.value = current
2077
+ const rules = faults.faults || []
2078
+ $("fault-list").innerHTML = table(
2079
+ [
2080
+ { label: "Id", cell: (row) => esc(row.id) },
2081
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2082
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2083
+ ],
2084
+ rules
2085
+ )
2086
+ }
2087
+
2088
+ async function renderJournal() {
2089
+ const journal = await api("GET", "/requests?limit=100")
2090
+ $("journal").innerHTML = table(
2091
+ [
2092
+ { label: "When", cell: (row) => esc(row.at || "") },
2093
+ { label: "Method", cell: (row) => esc(row.method) },
2094
+ { label: "Path", cell: (row) => esc(row.path) },
2095
+ { label: "Status", cell: (row) => esc(row.status) },
2096
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2097
+ ],
2098
+ journal.requests || []
2099
+ )
2100
+ }
2101
+
2102
+ async function renderRoutes() {
2103
+ const data = await api("GET", "/")
2104
+ const routes = data.routes || []
2105
+ $("route-list").innerHTML = routes.map((route) => {
2106
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2107
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2108
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2109
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2110
+ }).join("")
2111
+ }
2112
+
2113
+ const renderers = {
2114
+ overview: renderOverview,
2115
+ state: renderState,
2116
+ clock: renderClock,
2117
+ faults: renderFaults,
2118
+ journal: renderJournal,
2119
+ routes: renderRoutes
2120
+ }
2121
+
2122
+ async function refresh() {
2123
+ clearError()
2124
+ if (state.view in renderers) await renderers[state.view]()
2125
+ }
2126
+
2127
+ $("namespace").addEventListener("change", () => {
2128
+ state.namespace = $("namespace").value
2129
+ refresh().catch(showError)
2130
+ })
2131
+ keyInput.addEventListener("change", () => {
2132
+ state.key = keyInput.value.trim()
2133
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2134
+ refresh().catch(showError)
2135
+ })
2136
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2137
+
2138
+ $("collections").addEventListener("click", (event) => {
2139
+ const button = event.target.closest("[data-collection]")
2140
+ if (!button) return
2141
+ state.collection = button.dataset.collection
2142
+ renderState().catch(showError)
2143
+ })
2144
+ $("records").addEventListener("click", (event) => {
2145
+ const row = event.target.closest("[data-id]")
2146
+ if (!row) return
2147
+ openEditor(row.dataset.id).catch(showError)
2148
+ })
2149
+
2150
+ const editor = $("editor")
2151
+ async function openEditor(id) {
2152
+ state.editing = id || null
2153
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2154
+ $("editor-id").value = id || ""
2155
+ $("editor-id").readOnly = Boolean(id)
2156
+ $("editor-delete").hidden = !id
2157
+ if (id) {
2158
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2159
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2160
+ } else {
2161
+ $("editor-value").value = "{\\n \\n}"
2162
+ }
2163
+ editor.showModal()
2164
+ }
2165
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2166
+ $("editor-form").addEventListener("submit", (event) => {
2167
+ const submitter = event.submitter
2168
+ if (!submitter || submitter.value !== "save") return
2169
+ event.preventDefault()
2170
+ let value
2171
+ try { value = JSON.parse($("editor-value").value) }
2172
+ catch { showError(new Error("Value is not JSON")); return }
2173
+ const id = $("editor-id").value.trim()
2174
+ const path = "/state/" + encodeURIComponent(state.collection)
2175
+ const request = state.editing
2176
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2177
+ : api("POST", path, { id: id || undefined, value })
2178
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2179
+ })
2180
+ $("editor-delete").addEventListener("click", () => {
2181
+ const id = state.editing
2182
+ if (!id) return
2183
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2184
+ .then(() => { editor.close(); return renderState() })
2185
+ .catch(showError)
2186
+ })
2187
+
2188
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2189
+ button.addEventListener("click", () => {
2190
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2191
+ })
2192
+ })
2193
+ $("freeze").addEventListener("click", () => {
2194
+ const frozen = $("freeze").dataset.frozen === "1"
2195
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2196
+ })
2197
+ $("clock-reset").addEventListener("click", () => {
2198
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2199
+ })
2200
+ $("clock-set").addEventListener("submit", (event) => {
2201
+ event.preventDefault()
2202
+ const raw = $("clock-instant").value.trim()
2203
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2204
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2205
+ })
2206
+
2207
+ $("fault-form").addEventListener("submit", (event) => {
2208
+ event.preventDefault()
2209
+ const preset = $("fault-preset").value
2210
+ const body = preset
2211
+ ? { preset }
2212
+ : {
2213
+ status: Number($("fault-status").value),
2214
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2215
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2216
+ }
2217
+ if (!preset && !Number.isFinite(body.status)) {
2218
+ showError(new Error("Status must be a number, or choose a preset"))
2219
+ return
2220
+ }
2221
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2222
+ })
2223
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2224
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2225
+
2226
+ $("route-list").addEventListener("click", (event) => {
2227
+ const button = event.target.closest("[data-route]")
2228
+ if (!button) return
2229
+ state.route = button.dataset.route
2230
+ $("route-title").textContent = state.route
2231
+ const method = state.route.split(" ")[0]
2232
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2233
+ })
2234
+ $("route-form").addEventListener("submit", async (event) => {
2235
+ event.preventDefault()
2236
+ if (!state.route) return showError(new Error("Choose a route first"))
2237
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2238
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2239
+ let body
2240
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2241
+ try { body = JSON.parse($("route-body").value) }
2242
+ catch { return showError(new Error("Body is not JSON")) }
2243
+ }
2244
+ try {
2245
+ const data = await api(method, concrete, body)
2246
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2247
+ } catch (error) {
2248
+ showError(error)
2249
+ }
2250
+ })
2251
+
2252
+ function mountPanels(panels) {
2253
+ const nav = $("nav")
2254
+ const views = $("views")
2255
+ for (const panel of panels) {
2256
+ const button = document.createElement("button")
2257
+ button.type = "button"
2258
+ button.dataset.view = panel.id
2259
+ button.textContent = panel.title
2260
+ nav.append(button)
2261
+ const section = document.createElement("section")
2262
+ section.className = "view"
2263
+ section.id = "view-" + panel.id
2264
+ section.hidden = true
2265
+ const title = document.createElement("h2")
2266
+ title.textContent = panel.title
2267
+ const lede = document.createElement("p")
2268
+ lede.className = "lede"
2269
+ lede.textContent = panel.description || ""
2270
+ const body = document.createElement("div")
2271
+ body.className = "panel-body"
2272
+ body.id = "panel-" + panel.id
2273
+ body.innerHTML = panel.html || ""
2274
+ section.append(title, lede, body)
2275
+ views.append(section)
2276
+ if (panel.script) {
2277
+ try {
2278
+ const run = new Function("root", "api", panel.script)
2279
+ run(body, panelApi)
2280
+ } catch (error) {
2281
+ const note = document.createElement("p")
2282
+ note.className = "banner show"
2283
+ note.textContent = error instanceof Error ? error.message : String(error)
2284
+ body.append(note)
2285
+ }
2286
+ }
2287
+ }
2288
+ }
2289
+
2290
+ loadNamespaces()
2291
+ .then(() => api("GET", "/ui/manifest"))
2292
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2293
+ .catch(showError)
2294
+ })()
2295
+ </script>
2296
+ </body>
2297
+ </html>`;
2298
+ };
2299
+ var htmlResponse = (body) => new Response(body, {
2300
+ status: 200,
2301
+ headers: {
2302
+ "content-type": "text/html; charset=utf-8",
2303
+ "cache-control": "no-store"
2304
+ }
2305
+ });
2306
+ var json2 = (body) => new Response(JSON.stringify(body), {
2307
+ status: 200,
2308
+ headers: { "content-type": "application/json; charset=utf-8" }
2309
+ });
2310
+ var adminUiRoutes = (service, ui) => {
2311
+ const shell = () => renderAdminDocument(service);
2312
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2313
+ return {
2314
+ "GET /ui": () => htmlResponse(document2()),
2315
+ "GET /ui/": () => htmlResponse(document2()),
2316
+ "GET /ui/manifest": () => json2({
2317
+ service,
2318
+ panels: (ui?.panels ?? []).map((panel) => ({
2319
+ id: panel.id,
2320
+ title: panel.title,
2321
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2322
+ html: panel.html,
2323
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2324
+ }))
2325
+ })
2326
+ };
2327
+ };
2328
+
1397
2329
  // ../../openapi/metadata/dist/types.js
1398
2330
  var EXTENSION_KEYS = {
1399
2331
  operation: "x-mockingbird",
@@ -1631,8 +2563,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1631
2563
  });
1632
2564
  };
1633
2565
 
2566
+ // ../core/dist/state-view.js
2567
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2568
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2569
+ var SAMPLE = 25;
2570
+ var WALK_LIMIT = 1e4;
2571
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2572
+ var fail = (status, message) => ({ ok: false, status, message });
2573
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2574
+ var kindOf = (value) => {
2575
+ if (value === null)
2576
+ return "null";
2577
+ if (Array.isArray(value))
2578
+ return "array";
2579
+ switch (typeof value) {
2580
+ case "string":
2581
+ return "string";
2582
+ case "number":
2583
+ return Number.isFinite(value) ? "number" : "unknown";
2584
+ case "boolean":
2585
+ return "boolean";
2586
+ case "object":
2587
+ return "object";
2588
+ default:
2589
+ return "unknown";
2590
+ }
2591
+ };
2592
+ var humanize = (name) => {
2593
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2594
+ if (words === "")
2595
+ return name;
2596
+ return words.charAt(0).toUpperCase() + words.slice(1);
2597
+ };
2598
+ var jsonValue = (value) => {
2599
+ if (value === void 0)
2600
+ return fail(400, "value is required");
2601
+ try {
2602
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2603
+ } catch {
2604
+ return fail(400, "value must be JSON");
2605
+ }
2606
+ };
2607
+ var ctorName = (value) => {
2608
+ const ctor = value.constructor;
2609
+ return typeof ctor?.name === "string" ? ctor.name : "";
2610
+ };
2611
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2612
+ var discoverCollections = (root) => {
2613
+ const found = [];
2614
+ const seen = /* @__PURE__ */ new Set();
2615
+ const visit = (value, depth) => {
2616
+ if (found.length + seen.size > WALK_LIMIT)
2617
+ return;
2618
+ if (value === null || typeof value !== "object")
2619
+ return;
2620
+ if (seen.has(value))
2621
+ return;
2622
+ seen.add(value);
2623
+ if (value instanceof Collection) {
2624
+ found.push(value);
2625
+ return;
2626
+ }
2627
+ if (value instanceof Map) {
2628
+ for (const child of value.values())
2629
+ visit(child, depth + 1);
2630
+ return;
2631
+ }
2632
+ if (value instanceof Set) {
2633
+ for (const child of value.values())
2634
+ visit(child, depth + 1);
2635
+ return;
2636
+ }
2637
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2638
+ return;
2639
+ if (Array.isArray(value)) {
2640
+ const cap = Math.min(value.length, 32);
2641
+ for (let i = 0; i < cap; i++)
2642
+ visit(value[i], depth + 1);
2643
+ return;
2644
+ }
2645
+ let children;
2646
+ try {
2647
+ children = Object.values(value);
2648
+ } catch {
2649
+ return;
2650
+ }
2651
+ for (const child of children)
2652
+ visit(child, depth + 1);
2653
+ };
2654
+ visit(root, 0);
2655
+ return found;
2656
+ };
2657
+ var storedNames = (sqlite, namespace) => {
2658
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2659
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2660
+ return [...records, ...sequences].map((row) => row.name);
2661
+ };
2662
+ var blankAccum = (name) => ({
2663
+ name,
2664
+ kinds: /* @__PURE__ */ new Set(),
2665
+ present: 0,
2666
+ nested: /* @__PURE__ */ new Map()
2667
+ });
2668
+ var absorb = (accum, value) => {
2669
+ const kind = kindOf(value);
2670
+ accum.kinds.add(kind);
2671
+ accum.present++;
2672
+ if (!isRecord3(value))
2673
+ return;
2674
+ for (const [key, child] of Object.entries(value)) {
2675
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2676
+ absorb(nested, child);
2677
+ accum.nested.set(key, nested);
2678
+ }
2679
+ };
2680
+ var finishField = (accum, samples) => {
2681
+ const kinds = [...accum.kinds];
2682
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2683
+ const field = {
2684
+ name: accum.name,
2685
+ kind,
2686
+ optional: accum.present < samples || kinds.includes("null")
2687
+ };
2688
+ if (accum.nested.size > 0) {
2689
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2690
+ }
2691
+ return field;
2692
+ };
2693
+ var inferFields = (records) => {
2694
+ if (records.length === 0)
2695
+ return [];
2696
+ const sample = records.slice(0, SAMPLE);
2697
+ const objects = sample.filter((record) => isRecord3(record.value));
2698
+ if (objects.length === 0) {
2699
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2700
+ const list = [...kinds];
2701
+ return [
2702
+ {
2703
+ name: "(value)",
2704
+ kind: list.length === 1 ? list[0] : "unknown",
2705
+ optional: false
2706
+ }
2707
+ ];
2708
+ }
2709
+ const root = /* @__PURE__ */ new Map();
2710
+ for (const record of objects) {
2711
+ for (const [key, value] of Object.entries(record.value)) {
2712
+ const accum = root.get(key) ?? blankAccum(key);
2713
+ absorb(accum, value);
2714
+ root.set(key, accum);
2715
+ }
2716
+ }
2717
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2718
+ };
2719
+ var mergeFields = (declared, inferred) => {
2720
+ const byName = /* @__PURE__ */ new Map();
2721
+ for (const field of inferred)
2722
+ byName.set(field.name, field);
2723
+ const ordered = [];
2724
+ const seen = /* @__PURE__ */ new Set();
2725
+ for (const field of declared ?? []) {
2726
+ const found = byName.get(field.name);
2727
+ seen.add(field.name);
2728
+ if (!found) {
2729
+ ordered.push({ ...field, optional: field.optional });
2730
+ continue;
2731
+ }
2732
+ ordered.push({
2733
+ ...found,
2734
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2735
+ optional: field.optional || found.optional,
2736
+ ...field.description !== void 0 ? { description: field.description } : {},
2737
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2738
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2739
+ });
2740
+ }
2741
+ for (const field of inferred) {
2742
+ if (!seen.has(field.name))
2743
+ ordered.push(field);
2744
+ }
2745
+ return ordered;
2746
+ };
2747
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2748
+ var readRecord = (collection, id) => {
2749
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2750
+ const row = rows.find((entry) => entry.id === id);
2751
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2752
+ };
2753
+ var inspectState = (scope) => {
2754
+ const declared = /* @__PURE__ */ new Map();
2755
+ for (const declaration of scope.declarations ?? []) {
2756
+ if (COLLECTION_NAME.test(declaration.name))
2757
+ declared.set(declaration.name, declaration);
2758
+ }
2759
+ const names = new Set(declared.keys());
2760
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2761
+ names.add(name);
2762
+ for (const collection of discoverCollections(scope.root)) {
2763
+ if (collection.namespace === scope.storageNamespace)
2764
+ names.add(collection.collectionName);
2765
+ }
2766
+ const collections = [];
2767
+ for (const name of names) {
2768
+ if (!COLLECTION_NAME.test(name))
2769
+ continue;
2770
+ const declaration = declared.get(name);
2771
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2772
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2773
+ const inferred = inferFields(records);
2774
+ const fields = mergeFields(declaration?.fields, inferred);
2775
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2776
+ collections.push({
2777
+ name,
2778
+ label: declaration?.label ?? humanize(name),
2779
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2780
+ count: collection.count(),
2781
+ source,
2782
+ fields,
2783
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2784
+ });
2785
+ }
2786
+ const order = /* @__PURE__ */ new Map();
2787
+ for (const [index, item] of (scope.declarations ?? []).entries())
2788
+ order.set(item.name, index);
2789
+ collections.sort((a, b) => {
2790
+ const left = order.get(a.name);
2791
+ const right = order.get(b.name);
2792
+ if (left !== void 0 && right !== void 0)
2793
+ return left - right;
2794
+ if (left !== void 0)
2795
+ return -1;
2796
+ if (right !== void 0)
2797
+ return 1;
2798
+ return a.name.localeCompare(b.name);
2799
+ });
2800
+ return {
2801
+ namespace: scope.namespace,
2802
+ storageNamespace: scope.storageNamespace,
2803
+ collections
2804
+ };
2805
+ };
2806
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2807
+ if (!COLLECTION_NAME.test(name))
2808
+ return fail(400, "collection name is not allowed");
2809
+ const limit = query.limit ?? 50;
2810
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2811
+ return fail(400, "limit must be an integer from 1 to 200");
2812
+ }
2813
+ const order = query.order ?? "newest";
2814
+ if (order !== "newest" && order !== "oldest")
2815
+ return fail(400, 'order must be "newest" or "oldest"');
2816
+ const collection = collectionOf(sqlite, storageNamespace, name);
2817
+ const rows = collection.list({ order }).filter((row) => {
2818
+ if (query.after === void 0)
2819
+ return true;
2820
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2821
+ });
2822
+ const slice = rows.slice(0, limit);
2823
+ const last = slice.at(-1);
2824
+ return {
2825
+ ok: true,
2826
+ value: {
2827
+ collection: name,
2828
+ count: collection.count(),
2829
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2830
+ next: rows.length > limit && last ? last.seq : null
2831
+ }
2832
+ };
2833
+ };
2834
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2835
+ var readStateRecord = (scope, name, id) => {
2836
+ if (!COLLECTION_NAME.test(name))
2837
+ return fail(400, "collection name is not allowed");
2838
+ if (!RECORD_ID.test(id))
2839
+ return fail(400, "record id is not allowed");
2840
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2841
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2842
+ };
2843
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2844
+ var createStateRecord = (scope, name, input) => {
2845
+ if (!COLLECTION_NAME.test(name))
2846
+ return fail(400, "collection name is not allowed");
2847
+ const parsed = jsonValue(input.value);
2848
+ if (!parsed.ok)
2849
+ return parsed;
2850
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2851
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2852
+ const checked = requireId(id);
2853
+ if (!checked.ok)
2854
+ return checked;
2855
+ if (collection.has(checked.value))
2856
+ return fail(409, `record ${checked.value} already exists`);
2857
+ const stored = collection.insert(checked.value, parsed.value);
2858
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2859
+ };
2860
+ var replaceStateRecord = (scope, name, id, value) => {
2861
+ if (!COLLECTION_NAME.test(name))
2862
+ return fail(400, "collection name is not allowed");
2863
+ const checked = requireId(id);
2864
+ if (!checked.ok)
2865
+ return checked;
2866
+ const parsed = jsonValue(value);
2867
+ if (!parsed.ok)
2868
+ return parsed;
2869
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2870
+ if (!collection.has(checked.value))
2871
+ return fail(404, `no record ${checked.value} in ${name}`);
2872
+ const stored = collection.update(checked.value, parsed.value);
2873
+ if (!stored)
2874
+ return fail(404, `no record ${checked.value} in ${name}`);
2875
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2876
+ };
2877
+ var patchStateRecord = (scope, name, id, value) => {
2878
+ const current = readStateRecord(scope, name, id);
2879
+ if (!current.ok)
2880
+ return current;
2881
+ const parsed = jsonValue(value);
2882
+ if (!parsed.ok)
2883
+ return parsed;
2884
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2885
+ return replaceStateRecord(scope, name, id, next);
2886
+ };
2887
+ var deleteStateRecord = (scope, name, id) => {
2888
+ if (!COLLECTION_NAME.test(name))
2889
+ return fail(400, "collection name is not allowed");
2890
+ const checked = requireId(id);
2891
+ if (!checked.ok)
2892
+ return checked;
2893
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2894
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2895
+ };
2896
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2897
+ status,
2898
+ headers: { "content-type": "application/json; charset=utf-8" }
2899
+ });
2900
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2901
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2902
+ var integerParam = (value) => {
2903
+ if (value === null)
2904
+ return void 0;
2905
+ if (!/^-?\d+$/.test(value))
2906
+ return "bad";
2907
+ return Number(value);
2908
+ };
2909
+ var stateAdminRoutes = (routes) => {
2910
+ const open = (namespace) => {
2911
+ try {
2912
+ return { ok: true, value: routes.open(namespace) };
2913
+ } catch (error2) {
2914
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2915
+ }
2916
+ };
2917
+ const wrote = (namespace) => {
2918
+ routes.afterWrite?.(namespace);
2919
+ };
2920
+ return {
2921
+ "GET /state": ({ namespace }) => {
2922
+ const scope = open(namespace);
2923
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2924
+ },
2925
+ "GET /state/:collection": ({ namespace, params, url }) => {
2926
+ const scope = open(namespace);
2927
+ if (!scope.ok)
2928
+ return fromResult(scope, 200);
2929
+ const limit = integerParam(url.searchParams.get("limit"));
2930
+ const after = integerParam(url.searchParams.get("after"));
2931
+ if (limit === "bad")
2932
+ return adminError2(400, "limit: expected an integer");
2933
+ if (after === "bad")
2934
+ return adminError2(400, "after: expected a sequence number");
2935
+ const order = url.searchParams.get("order");
2936
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2937
+ ...limit !== void 0 ? { limit } : {},
2938
+ ...after !== void 0 ? { after } : {},
2939
+ ...order === "newest" || order === "oldest" ? { order } : {}
2940
+ }), 200);
2941
+ },
2942
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2943
+ const scope = open(namespace);
2944
+ if (!scope.ok)
2945
+ return fromResult(scope, 200);
2946
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2947
+ },
2948
+ "POST /state/:collection": ({ namespace, params, body }) => {
2949
+ const scope = open(namespace);
2950
+ if (!scope.ok)
2951
+ return fromResult(scope, 201);
2952
+ if (!isRecord3(body) || !("value" in body)) {
2953
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2954
+ }
2955
+ const id = body.id;
2956
+ if (id !== void 0 && typeof id !== "string")
2957
+ return adminError2(400, "id must be a string");
2958
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2959
+ ...typeof id === "string" ? { id } : {},
2960
+ value: body.value
2961
+ });
2962
+ if (created.ok)
2963
+ wrote(namespace);
2964
+ return fromResult(created, 201);
2965
+ },
2966
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2967
+ const scope = open(namespace);
2968
+ if (!scope.ok)
2969
+ return fromResult(scope, 200);
2970
+ if (!isRecord3(body) || !("value" in body))
2971
+ return adminError2(400, 'expected {"value": <json>}');
2972
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2973
+ if (replaced.ok)
2974
+ wrote(namespace);
2975
+ return fromResult(replaced, 200);
2976
+ },
2977
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2978
+ const scope = open(namespace);
2979
+ if (!scope.ok)
2980
+ return fromResult(scope, 200);
2981
+ if (!isRecord3(body) || !("value" in body))
2982
+ return adminError2(400, 'expected {"value": <json>}');
2983
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2984
+ if (patched.ok)
2985
+ wrote(namespace);
2986
+ return fromResult(patched, 200);
2987
+ },
2988
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2989
+ const scope = open(namespace);
2990
+ if (!scope.ok)
2991
+ return fromResult(scope, 200);
2992
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2993
+ if (removed.ok)
2994
+ wrote(namespace);
2995
+ return fromResult(removed, 200);
2996
+ }
2997
+ };
2998
+ };
2999
+
1634
3000
  // ../core/dist/version.js
1635
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
3001
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1636
3002
 
1637
3003
  // ../core/dist/signing.js
1638
3004
  var encoder = new TextEncoder();
@@ -1967,11 +3333,11 @@ var createWebhookHub = (options) => {
1967
3333
  };
1968
3334
  return hub;
1969
3335
  };
1970
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1971
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1972
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3336
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3337
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3338
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1973
3339
  var parseEndpoint = (value) => {
1974
- if (!isRecord3(value) || typeof value.url !== "string")
3340
+ if (!isRecord4(value) || typeof value.url !== "string")
1975
3341
  return "each endpoint needs a url";
1976
3342
  try {
1977
3343
  new URL(value.url);
@@ -1988,18 +3354,18 @@ var parseEndpoint = (value) => {
1988
3354
  const events = value.events ?? value.enabledEvents;
1989
3355
  if (Array.isArray(events))
1990
3356
  endpoint.events = events.map(String);
1991
- if (isRecord3(value.tags)) {
3357
+ if (isRecord4(value.tags)) {
1992
3358
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1993
3359
  }
1994
3360
  if (typeof value.account === "string")
1995
3361
  endpoint.tags = { ...endpoint.tags, account: value.account };
1996
- if (isRecord3(value.headers)) {
3362
+ if (isRecord4(value.headers)) {
1997
3363
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1998
3364
  }
1999
3365
  return endpoint;
2000
3366
  };
2001
3367
  var webhookAdminRoutes = (hub) => ({
2002
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3368
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
2003
3369
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2004
3370
  const type = url.searchParams.get("type");
2005
3371
  return type === null || d.type === type;
@@ -2007,51 +3373,51 @@ var webhookAdminRoutes = (hub) => ({
2007
3373
  }),
2008
3374
  "GET /webhooks/events": ({ url, namespace }) => {
2009
3375
  const type = url.searchParams.get("type");
2010
- return json2(200, {
3376
+ return json4(200, {
2011
3377
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2012
3378
  });
2013
3379
  },
2014
3380
  "POST /webhooks/:id/replay": async ({ params }) => {
2015
3381
  const replayed = await hub.replay(params.id);
2016
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3382
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2017
3383
  },
2018
3384
  "POST /webhooks/flush": async () => {
2019
3385
  await hub.flush();
2020
- return json2(200, { status: "ok" });
3386
+ return json4(200, { status: "ok" });
2021
3387
  },
2022
3388
  "POST /webhooks/faults": ({ body, namespace }) => {
2023
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2024
- return adminError2(400, "mode must be duplicate, reorder or drop");
3389
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3390
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2025
3391
  }
2026
3392
  const fault = { mode: body.mode };
2027
3393
  if (typeof body.count === "number")
2028
3394
  fault.count = body.count;
2029
3395
  hub.fault(namespace, fault);
2030
- return json2(201, { namespace, ...fault });
3396
+ return json4(201, { namespace, ...fault });
2031
3397
  },
2032
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3398
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
2033
3399
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2034
3400
  ...rest,
2035
3401
  secret: secret ? "(set)" : null
2036
3402
  }))
2037
3403
  }),
2038
3404
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2039
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3405
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2040
3406
  if (!Array.isArray(list))
2041
- return adminError2(400, "expected [{url, secret?, events?}]");
3407
+ return adminError3(400, "expected [{url, secret?, events?}]");
2042
3408
  const parsed = [];
2043
3409
  for (const each of list) {
2044
3410
  const endpoint = parseEndpoint(each);
2045
3411
  if (typeof endpoint === "string")
2046
- return adminError2(400, endpoint);
3412
+ return adminError3(400, endpoint);
2047
3413
  parsed.push(endpoint);
2048
3414
  }
2049
3415
  const set = hub.setEndpoints(namespace, parsed);
2050
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3416
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2051
3417
  },
2052
3418
  "DELETE /webhook-endpoints": ({ namespace }) => {
2053
3419
  hub.setEndpoints(namespace, []);
2054
- return json2(200, { status: "ok" });
3420
+ return json4(200, { status: "ok" });
2055
3421
  }
2056
3422
  });
2057
3423
  var parsePayload = (message) => {
@@ -2116,6 +3482,7 @@ var operationMatcher = (document2) => {
2116
3482
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2117
3483
  };
2118
3484
  var createRuntime = (options) => {
3485
+ assertAdminUi(options.adminUi);
2119
3486
  const sqlite = bootSqlite(options.sqlite);
2120
3487
  const clock = options.clock ?? createClock();
2121
3488
  const rng = createRng(options.seed ?? 0);
@@ -2322,6 +3689,19 @@ var createRuntime = (options) => {
2322
3689
  else
2323
3690
  timeline(name);
2324
3691
  };
3692
+ const declarationsFor = (namespace) => {
3693
+ const declared = options.state;
3694
+ if (!declared)
3695
+ return [];
3696
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3697
+ };
3698
+ const stateScope = (namespace) => ({
3699
+ sqlite,
3700
+ namespace,
3701
+ storageNamespace: storageNamespace(namespace),
3702
+ root: instance(namespace),
3703
+ declarations: declarationsFor(namespace)
3704
+ });
2325
3705
  const runtime = {
2326
3706
  name: options.name,
2327
3707
  sqlite,
@@ -2360,6 +3740,7 @@ var createRuntime = (options) => {
2360
3740
  branch,
2361
3741
  checkout,
2362
3742
  timeline,
3743
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2363
3744
  fetch: async (incoming) => {
2364
3745
  let request = incoming;
2365
3746
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2553,11 +3934,20 @@ var createRuntime = (options) => {
2553
3934
  ...credentialRoutes(credentials),
2554
3935
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2555
3936
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2556
- ...options.admin?.(runtime) ?? {}
3937
+ ...options.admin?.(runtime) ?? {},
3938
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3939
+ // beside these; it does not replace `/state` or `/ui`.
3940
+ ...stateAdminRoutes({
3941
+ open: stateScope,
3942
+ afterWrite: (namespace) => {
3943
+ checkpoint(namespace, "main");
3944
+ }
3945
+ }),
3946
+ ...adminUiRoutes(options.name, options.adminUi)
2557
3947
  },
2558
3948
  adminKey: options.adminKey
2559
3949
  });
2560
- return runtime;
3950
+ return defineMock(runtime);
2561
3951
  };
2562
3952
  var mutableResponse = (response) => {
2563
3953
  try {
@@ -2675,14 +4065,14 @@ var classifyCard = (form) => {
2675
4065
  return { kind: "approve", hsa: number === CARDS.hsa };
2676
4066
  };
2677
4067
  var substituteSessionId = (url, sessionId) => url.replaceAll("{CHECKOUT_SESSION_ID}", sessionId).replace(/%7BCHECKOUT_SESSION_ID%7D/gi, sessionId);
2678
- var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4068
+ var escapeHtml2 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2679
4069
  var dollars = (cents) => `$${(cents / 100).toFixed(2)}`;
2680
4070
  var layout = (title, body) => `<!doctype html>
2681
4071
  <html lang="en">
2682
4072
  <head>
2683
4073
  <meta charset="utf-8">
2684
4074
  <meta name="viewport" content="width=device-width, initial-scale=1">
2685
- <title>${escapeHtml(title)}</title>
4075
+ <title>${escapeHtml2(title)}</title>
2686
4076
  <style>
2687
4077
  body{font-family:system-ui,sans-serif;max-width:28rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a}
2688
4078
  label{display:block;margin:.75rem 0 .25rem;font-size:.9rem}
@@ -2697,20 +4087,20 @@ ${body}
2697
4087
  </body>
2698
4088
  </html>
2699
4089
  `;
2700
- var alert = (error2) => error2 ? `<div role="alert" data-testid="flex-mock-error">${escapeHtml(error2)}</div>` : "";
4090
+ var alert = (error2) => error2 ? `<div role="alert" data-testid="flex-mock-error">${escapeHtml2(error2)}</div>` : "";
2701
4091
  var cancelLink = (session) => session.cancel_url ? `<p><a data-testid="flex-mock-cancel" href="./${encodeURIComponent(session.checkout_session_id)}/cancel">Cancel and return</a></p>` : "";
2702
4092
  var cadence = (session) => {
2703
4093
  const recurring = session.line_items.find((item) => item.price_data.recurring)?.price_data.recurring;
2704
4094
  if (!recurring) return "";
2705
4095
  const count = recurring.interval_count ?? 1;
2706
4096
  const every = count === 1 ? recurring.interval : `${count} ${recurring.interval}s`;
2707
- return ` <span data-testid="flex-mock-interval">per ${escapeHtml(every)}</span>`;
4097
+ return ` <span data-testid="flex-mock-interval">per ${escapeHtml2(every)}</span>`;
2708
4098
  };
2709
4099
  var summary = (input) => {
2710
4100
  const { session } = input;
2711
- const items = input.productNames.map((name) => `<li data-testid="flex-mock-line-item">${escapeHtml(name)}</li>`).join("");
4101
+ const items = input.productNames.map((name) => `<li data-testid="flex-mock-line-item">${escapeHtml2(name)}</li>`).join("");
2712
4102
  return `<h1>${session.mode === "subscription" ? "Subscribe with HSA/FSA" : "Pay with HSA/FSA"}</h1>
2713
- <p data-testid="flex-mock-session" data-session-id="${escapeHtml(session.checkout_session_id)}" data-mode="${escapeHtml(session.mode)}">
4103
+ <p data-testid="flex-mock-session" data-session-id="${escapeHtml2(session.checkout_session_id)}" data-mode="${escapeHtml2(session.mode)}">
2714
4104
  ${session.mode === "setup" ? "Save a card for future payments" : `Total <strong data-testid="flex-mock-amount">${dollars(session.amount_total)}</strong>${session.mode === "subscription" ? cadence(session) : ""}`}
2715
4105
  </p>
2716
4106
  ${items ? `<ul>${items}</ul>` : ""}`;
@@ -2766,8 +4156,8 @@ ${cancelLink(input.session)}`
2766
4156
  };
2767
4157
  var closedPage = (session) => layout(
2768
4158
  "Flex checkout (Mockingbird)",
2769
- `<h1>This checkout is ${escapeHtml(session.status)}</h1>
2770
- <p data-testid="flex-mock-closed" data-status="${escapeHtml(session.status)}">Nothing more to pay here.</p>`
4159
+ `<h1>This checkout is ${escapeHtml2(session.status)}</h1>
4160
+ <p data-testid="flex-mock-closed" data-status="${escapeHtml2(session.status)}">Nothing more to pay here.</p>`
2771
4161
  );
2772
4162
  var notFoundPage = () => layout(
2773
4163
  "Flex checkout (Mockingbird)",
@@ -3652,11 +5042,11 @@ var FLEX_PRESETS = {
3652
5042
  webhook: { mode: "drop" }
3653
5043
  }
3654
5044
  };
3655
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3656
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
3657
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5045
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5046
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
5047
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3658
5048
  var parseSettings = (body) => {
3659
- if (!isRecord4(body)) return "expected a JSON object";
5049
+ if (!isRecord5(body)) return "expected a JSON object";
3660
5050
  const patch = {};
3661
5051
  if (body.eventNaming !== void 0) {
3662
5052
  if (body.eventNaming !== "dotted" && body.eventNaming !== "underscored") {
@@ -3689,19 +5079,19 @@ var parseSettings = (body) => {
3689
5079
  };
3690
5080
  var adminRoutes = (runtime) => {
3691
5081
  const session = (namespace, id) => runtime.instance(namespace).state.sessions.get(id);
3692
- const found = (value, what) => value ? json3(200, value) : adminError3(404, `no ${what}`);
5082
+ const found = (value, what) => value ? json5(200, value) : adminError4(404, `no ${what}`);
3693
5083
  const notOpen = (namespace, id) => {
3694
5084
  const current = session(namespace, id);
3695
- if (!current) return adminError3(404, `no session ${id}`);
3696
- return current.status === "open" ? void 0 : adminError3(409, `session ${id} is ${current.status}, not open`);
5085
+ if (!current) return adminError4(404, `no session ${id}`);
5086
+ return current.status === "open" ? void 0 : adminError4(409, `session ${id} is ${current.status}, not open`);
3697
5087
  };
3698
5088
  return {
3699
- "GET /sessions": ({ namespace }) => json3(200, { sessions: runtime.instance(namespace).sessions() }),
5089
+ "GET /sessions": ({ namespace }) => json5(200, { sessions: runtime.instance(namespace).sessions() }),
3700
5090
  "GET /sessions/:id": ({ namespace, params }) => found(session(namespace, params.id), `session ${params.id}`),
3701
5091
  "POST /sessions/:id/complete": ({ namespace, params, body }) => {
3702
5092
  const closed = notOpen(namespace, params.id);
3703
5093
  if (closed) return closed;
3704
- const hsa = !(isRecord4(body) && body.card === "4242424242424242");
5094
+ const hsa = !(isRecord5(body) && body.card === "4242424242424242");
3705
5095
  return found(
3706
5096
  runtime.instance(namespace).settle(params.id, { hsa }),
3707
5097
  `session ${params.id}`
@@ -3712,9 +5102,9 @@ var adminRoutes = (runtime) => {
3712
5102
  "POST /sessions/:id/require_action": ({ namespace, params, body }) => {
3713
5103
  const closed = notOpen(namespace, params.id);
3714
5104
  if (closed) return closed;
3715
- const type = isRecord4(body) ? body.next_action_type : void 0;
5105
+ const type = isRecord5(body) ? body.next_action_type : void 0;
3716
5106
  if (type !== void 0 && !isNextActionType(type)) {
3717
- return adminError3(
5107
+ return adminError4(
3718
5108
  400,
3719
5109
  "next_action_type: collect_letter_of_medical_necessity | provide_second_payment_method | provide_alternative_payment_method | payment_failed"
3720
5110
  );
@@ -3725,8 +5115,8 @@ var adminRoutes = (runtime) => {
3725
5115
  );
3726
5116
  },
3727
5117
  "PUT /sessions/:id/payment-intent": ({ namespace, params, body }) => {
3728
- if (!isRecord4(body) || !PAYMENT_INTENT_STATUSES.includes(String(body.status))) {
3729
- return adminError3(400, `status: ${PAYMENT_INTENT_STATUSES.join(" | ")}`);
5118
+ if (!isRecord5(body) || !PAYMENT_INTENT_STATUSES.includes(String(body.status))) {
5119
+ return adminError4(400, `status: ${PAYMENT_INTENT_STATUSES.join(" | ")}`);
3730
5120
  }
3731
5121
  const api = runtime.instance(namespace);
3732
5122
  const intent = api.setPaymentIntent(params.id, {
@@ -3736,52 +5126,52 @@ var adminRoutes = (runtime) => {
3736
5126
  return found(intent, `session ${params.id}`);
3737
5127
  },
3738
5128
  "PUT /products/:id": ({ namespace, params, body }) => {
3739
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
5129
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
3740
5130
  const api = runtime.instance(namespace);
3741
5131
  const product = api.state.products.get(params.id);
3742
- if (!product) return adminError3(404, `no product ${params.id}`);
5132
+ if (!product) return adminError4(404, `no product ${params.id}`);
3743
5133
  const next = { ...product };
3744
5134
  for (const key of ["hsa_fsa_eligibility", "visit_type", "client_reference_id"]) {
3745
5135
  const value = body[key];
3746
5136
  if (value === void 0) continue;
3747
5137
  if (value !== null && typeof value !== "string")
3748
- return adminError3(400, `${key}: string | null`);
5138
+ return adminError4(400, `${key}: string | null`);
3749
5139
  next[key] = value;
3750
5140
  }
3751
5141
  for (const key of ["active", "test_mode"]) {
3752
5142
  const value = body[key];
3753
5143
  if (value === void 0) continue;
3754
- if (typeof value !== "boolean") return adminError3(400, `${key}: boolean`);
5144
+ if (typeof value !== "boolean") return adminError4(400, `${key}: boolean`);
3755
5145
  next[key] = value;
3756
5146
  }
3757
5147
  if (body.name !== void 0) {
3758
- if (typeof body.name !== "string") return adminError3(400, "name: string");
5148
+ if (typeof body.name !== "string") return adminError4(400, "name: string");
3759
5149
  next.name = body.name;
3760
5150
  }
3761
5151
  if (body.metadata !== void 0) {
3762
- if (body.metadata !== null && !isRecord4(body.metadata))
3763
- return adminError3(400, "metadata: object | null");
5152
+ if (body.metadata !== null && !isRecord5(body.metadata))
5153
+ return adminError4(400, "metadata: object | null");
3764
5154
  next.metadata = body.metadata;
3765
5155
  }
3766
- return json3(200, api.putProduct(next));
5156
+ return json5(200, api.putProduct(next));
3767
5157
  },
3768
5158
  "POST /events": ({ namespace, body }) => {
3769
- if (!isRecord4(body) || typeof body.type !== "string") {
3770
- return adminError3(400, 'expected {"type": "<event type>", "session"?: id, "product"?: id}');
5159
+ if (!isRecord5(body) || typeof body.type !== "string") {
5160
+ return adminError4(400, 'expected {"type": "<event type>", "session"?: id, "product"?: id}');
3771
5161
  }
3772
5162
  const event = runtime.instance(namespace).emitFor(body.type, {
3773
5163
  ...typeof body.session === "string" ? { sessionId: body.session } : {},
3774
5164
  ...typeof body.product === "string" ? { productId: body.product } : {}
3775
5165
  });
3776
- return event ? json3(201, event) : adminError3(404, "no such session or product");
5166
+ return event ? json5(201, event) : adminError4(404, "no such session or product");
3777
5167
  },
3778
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
5168
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
3779
5169
  "PUT /settings": ({ body, namespace }) => {
3780
5170
  const patch = parseSettings(body);
3781
- if (typeof patch === "string") return adminError3(400, patch);
3782
- return json3(200, runtime.instance(namespace).state.update(patch));
5171
+ if (typeof patch === "string") return adminError4(400, patch);
5172
+ return json5(200, runtime.instance(namespace).state.update(patch));
3783
5173
  },
3784
- "POST /tick": ({ namespace }) => json3(200, { expired: runtime.instance(namespace).tick() })
5174
+ "POST /tick": ({ namespace }) => json5(200, { expired: runtime.instance(namespace).tick() })
3785
5175
  };
3786
5176
  };
3787
5177
  var createRuntime2 = (options = {}) => {
@@ -3870,11 +5260,11 @@ var keyMode = (key) => {
3870
5260
  var HOSTED = /* @__PURE__ */ new Set(["HostedCheckoutPage", "SubmitHostedCheckout", "CancelHostedCheckout"]);
3871
5261
  var error = (status, type, message, extra = {}) => jsonRes(status, { error: { type, message, ...extra } });
3872
5262
  var invalid = (message, param) => error(400, "invalid_request_error", message, param ? { param } : {});
3873
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5263
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3874
5264
  var envelope = (context, name) => {
3875
5265
  const body = context.body.kind === "json" ? context.body.value : void 0;
3876
- const inner = isRecord5(body) ? body[name] : void 0;
3877
- return isRecord5(inner) ? inner : {};
5266
+ const inner = isRecord6(body) ? body[name] : void 0;
5267
+ return isRecord6(inner) ? inner : {};
3878
5268
  };
3879
5269
  var flag = (value) => value === "true";
3880
5270
  var sleep = (ms, signal) => new Promise((resolve) => {
@@ -4044,7 +5434,7 @@ var FlexAPI = class {
4044
5434
  visit_type: null,
4045
5435
  active: true,
4046
5436
  test_mode: this.testMode(context),
4047
- metadata: isRecord5(input.metadata) ? input.metadata : null,
5437
+ metadata: isRecord6(input.metadata) ? input.metadata : null,
4048
5438
  created_at: this.iso()
4049
5439
  };
4050
5440
  this.state.products.put(product);
@@ -4069,7 +5459,7 @@ var FlexAPI = class {
4069
5459
  ...typeof input.name === "string" ? { name: input.name } : {},
4070
5460
  ...typeof input.description === "string" ? { description: input.description } : {},
4071
5461
  ...typeof input.url === "string" ? { url: input.url } : {},
4072
- ...isRecord5(input.metadata) ? { metadata: input.metadata } : {}
5462
+ ...isRecord6(input.metadata) ? { metadata: input.metadata } : {}
4073
5463
  };
4074
5464
  this.putProduct(next);
4075
5465
  return annotateResponse(jsonRes(200, { product: next }), {
@@ -4201,7 +5591,7 @@ var FlexAPI = class {
4201
5591
  payment_intent: null,
4202
5592
  setup_intent: setupIntent,
4203
5593
  subscription: null,
4204
- subscription_data: mode === "subscription" ? isRecord5(input.subscription_data) ? input.subscription_data : {} : null,
5594
+ subscription_data: mode === "subscription" ? isRecord6(input.subscription_data) ? input.subscription_data : {} : null,
4205
5595
  mode,
4206
5596
  status: "open",
4207
5597
  url: `${this.pageBase(context)}/pay/${encodeURIComponent(id)}`,
@@ -4209,7 +5599,7 @@ var FlexAPI = class {
4209
5599
  cancel_url: typeof input.cancel_url === "string" ? input.cancel_url : null,
4210
5600
  next_action: null,
4211
5601
  visit_type: products.map((p) => p.visit_type).find((v) => v && v !== "notApplicable") ?? products[0]?.visit_type ?? null,
4212
- metadata: isRecord5(input.metadata) ? input.metadata : null,
5602
+ metadata: isRecord6(input.metadata) ? input.metadata : null,
4213
5603
  line_items: items,
4214
5604
  allow_promotion_codes: input.allow_promotion_codes === true,
4215
5605
  capture_method: typeof input.capture_method === "string" ? input.capture_method : "automatic",
@@ -4733,4 +6123,4 @@ export {
4733
6123
  FlexAPI,
4734
6124
  isNextActionType
4735
6125
  };
4736
- //# sourceMappingURL=chunk-UQWTCFIV.js.map
6126
+ //# sourceMappingURL=chunk-UKBUYHZN.js.map