@crvouga/mockingbird-service-customerio 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;
@@ -717,64 +719,64 @@ var graphemeLength = (value) => [...value].length;
717
719
  var validateValue = (document2, schema, value, path = []) => {
718
720
  const errors = [];
719
721
  const s = resolveSchema(document2, schema);
720
- const fail = (message) => errors.push({ path, message });
722
+ const fail2 = (message) => errors.push({ path, message });
721
723
  const actual = jsonTypeOf(value);
722
724
  if (actual === "undefined") {
723
- fail("value is undefined");
725
+ fail2("value is undefined");
724
726
  return errors;
725
727
  }
726
728
  const types = schemaTypes(s);
727
729
  if (types.length > 0) {
728
730
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
729
731
  if (!ok) {
730
- fail(`expected type ${types.join("|")}, got ${actual}`);
732
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
731
733
  return errors;
732
734
  }
733
735
  }
734
736
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
735
- fail("value not in enum");
737
+ fail2("value not in enum");
736
738
  }
737
739
  if (s.const !== void 0 && !deepEqual(s.const, value))
738
- fail("value does not equal const");
740
+ fail2("value does not equal const");
739
741
  if (typeof value === "string") {
740
742
  const length = graphemeLength(value);
741
743
  if (s.minLength !== void 0 && length < s.minLength)
742
- fail(`length ${length} < minLength ${s.minLength}`);
744
+ fail2(`length ${length} < minLength ${s.minLength}`);
743
745
  if (s.maxLength !== void 0 && length > s.maxLength)
744
- fail(`length ${length} > maxLength ${s.maxLength}`);
746
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
745
747
  if (s.pattern !== void 0) {
746
748
  try {
747
749
  if (!new RegExp(s.pattern, "u").test(value))
748
- fail(`does not match pattern ${s.pattern}`);
750
+ fail2(`does not match pattern ${s.pattern}`);
749
751
  } catch {
750
752
  }
751
753
  }
752
754
  if (s.format !== void 0) {
753
755
  const pattern = FORMAT_PATTERNS[s.format];
754
756
  if (pattern && !pattern.test(value))
755
- fail(`does not match format ${s.format}`);
757
+ fail2(`does not match format ${s.format}`);
756
758
  }
757
759
  }
758
760
  if (typeof value === "number") {
759
761
  if (s.minimum !== void 0 && value < s.minimum)
760
- fail(`${value} < minimum ${s.minimum}`);
762
+ fail2(`${value} < minimum ${s.minimum}`);
761
763
  if (s.maximum !== void 0 && value > s.maximum)
762
- fail(`${value} > maximum ${s.maximum}`);
764
+ fail2(`${value} > maximum ${s.maximum}`);
763
765
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
764
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
766
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
765
767
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
766
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
768
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
767
769
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
768
- fail(`${value} is not a multiple of ${s.multipleOf}`);
770
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
769
771
  }
770
772
  }
771
773
  if (Array.isArray(value)) {
772
774
  if (s.minItems !== void 0 && value.length < s.minItems)
773
- fail(`${value.length} items < minItems ${s.minItems}`);
775
+ fail2(`${value.length} items < minItems ${s.minItems}`);
774
776
  if (s.maxItems !== void 0 && value.length > s.maxItems)
775
- fail(`${value.length} items > maxItems ${s.maxItems}`);
777
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
776
778
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
777
- fail("items are not unique");
779
+ fail2("items are not unique");
778
780
  value.forEach((item, i) => {
779
781
  const itemSchema = s.prefixItems?.[i] ?? s.items;
780
782
  if (itemSchema)
@@ -786,11 +788,11 @@ var validateValue = (document2, schema, value, path = []) => {
786
788
  const keys = Object.keys(record);
787
789
  for (const name of s.required ?? [])
788
790
  if (!(name in record))
789
- fail(`missing required property ${name}`);
791
+ fail2(`missing required property ${name}`);
790
792
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
791
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
793
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
792
794
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
793
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
795
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
794
796
  for (const key of keys) {
795
797
  const property = s.properties?.[key];
796
798
  if (property) {
@@ -798,14 +800,14 @@ var validateValue = (document2, schema, value, path = []) => {
798
800
  continue;
799
801
  }
800
802
  if (s.additionalProperties === false)
801
- fail(`unexpected property ${key}`);
803
+ fail2(`unexpected property ${key}`);
802
804
  else if (typeof s.additionalProperties === "object") {
803
805
  errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
804
806
  }
805
807
  if (s.propertyNames) {
806
808
  const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
807
809
  if (nameErrors.length > 0)
808
- fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
810
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
809
811
  }
810
812
  }
811
813
  }
@@ -813,14 +815,14 @@ var validateValue = (document2, schema, value, path = []) => {
813
815
  for (const branch of s.allOf)
814
816
  errors.push(...validateValue(document2, branch, value, path));
815
817
  if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
816
- fail("matches no anyOf branch");
818
+ fail2("matches no anyOf branch");
817
819
  if (s.oneOf) {
818
820
  const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
819
821
  if (matches2 !== 1)
820
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
822
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
821
823
  }
822
824
  if (s.not && validateValue(document2, s.not, value).length === 0)
823
- fail("matches forbidden `not` schema");
825
+ fail2("matches forbidden `not` schema");
824
826
  return errors;
825
827
  };
826
828
 
@@ -1429,6 +1431,936 @@ var clearNamespace = (sqlite, namespace) => {
1429
1431
  });
1430
1432
  };
1431
1433
 
1434
+ // ../core/dist/surface.js
1435
+ var defineMock = (runtime) => runtime;
1436
+ var STANDARD_ADMIN_ROUTES = [
1437
+ "GET /",
1438
+ "POST /reset",
1439
+ "GET /namespaces",
1440
+ "GET /clock",
1441
+ "POST /clock",
1442
+ "GET /faults",
1443
+ "POST /faults",
1444
+ "DELETE /faults",
1445
+ "POST /snapshots",
1446
+ "POST /snapshots/:id/restore",
1447
+ "DELETE /snapshots/:id",
1448
+ "GET /timeline",
1449
+ "POST /checkpoints",
1450
+ "POST /branches/:name",
1451
+ "POST /branches/:name/checkout",
1452
+ "GET /requests",
1453
+ "DELETE /requests",
1454
+ "GET /metrics",
1455
+ "DELETE /metrics",
1456
+ "GET /credentials",
1457
+ "PUT /credentials",
1458
+ "DELETE /credentials",
1459
+ "GET /state",
1460
+ "GET /state/:collection",
1461
+ "GET /state/:collection/:id",
1462
+ "POST /state/:collection",
1463
+ "PUT /state/:collection/:id",
1464
+ "PATCH /state/:collection/:id",
1465
+ "DELETE /state/:collection/:id",
1466
+ "GET /ui",
1467
+ "GET /ui/",
1468
+ "GET /ui/manifest"
1469
+ ];
1470
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1471
+ var assertAdminUi = (ui) => {
1472
+ if (!ui?.panels)
1473
+ return;
1474
+ const seen = /* @__PURE__ */ new Set();
1475
+ for (const panel of ui.panels) {
1476
+ if (!PANEL_ID.test(panel.id)) {
1477
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1478
+ }
1479
+ if (seen.has(panel.id))
1480
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1481
+ seen.add(panel.id);
1482
+ if (panel.title.trim() === "")
1483
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1484
+ }
1485
+ };
1486
+
1487
+ // ../core/dist/admin-ui.js
1488
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1489
+ switch (char) {
1490
+ case "&":
1491
+ return "&amp;";
1492
+ case "<":
1493
+ return "&lt;";
1494
+ case ">":
1495
+ return "&gt;";
1496
+ case '"':
1497
+ return "&quot;";
1498
+ default:
1499
+ return "&#39;";
1500
+ }
1501
+ });
1502
+ var renderAdminDocument = (service) => {
1503
+ const name = escapeHtml(service);
1504
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1505
+ return `<!DOCTYPE html>
1506
+ <html lang="en">
1507
+ <head>
1508
+ <meta charset="utf-8">
1509
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1510
+ <meta name="color-scheme" content="light dark">
1511
+ <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">
1512
+ <title>${name} admin</title>
1513
+ <style>
1514
+ :root {
1515
+ color-scheme: light;
1516
+ --bg: #f6f5f2;
1517
+ --bg-elev: #ffffff;
1518
+ --bg-muted: #eeece6;
1519
+ --bg-inset: #f3f1eb;
1520
+ --line: #e2dfd6;
1521
+ --line-strong: #d0ccc1;
1522
+ --ink: #1c1915;
1523
+ --muted: #5e584f;
1524
+ --faint: #8a8378;
1525
+ --accent: #3d4f3a;
1526
+ --accent-ink: #f7f6f2;
1527
+ --accent-soft: #e5ece2;
1528
+ --ok: #1f7a45;
1529
+ --ok-soft: #e5f4eb;
1530
+ --warn: #9a6700;
1531
+ --warn-soft: #fbf3df;
1532
+ --err: #a33b32;
1533
+ --err-soft: #fdecea;
1534
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1535
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1536
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1537
+ --radius: 14px;
1538
+ --header: 60px;
1539
+ --nav: 220px;
1540
+ }
1541
+ :root[data-theme="dark"] {
1542
+ color-scheme: dark;
1543
+ --bg: #141311;
1544
+ --bg-elev: #1e1c19;
1545
+ --bg-muted: #26231f;
1546
+ --bg-inset: #181715;
1547
+ --line: #34302b;
1548
+ --line-strong: #4a453d;
1549
+ --ink: #f4f1ea;
1550
+ --muted: #c4bdb1;
1551
+ --faint: #8f877c;
1552
+ --accent: #c5d5b8;
1553
+ --accent-ink: #1a2118;
1554
+ --accent-soft: #2a3328;
1555
+ --ok: #8fd6a8;
1556
+ --ok-soft: #1a2e22;
1557
+ --warn: #f0cc78;
1558
+ --warn-soft: #332911;
1559
+ --err: #f0a8a2;
1560
+ --err-soft: #3a201e;
1561
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1562
+ }
1563
+ @media (prefers-color-scheme: dark) {
1564
+ :root:not([data-theme="light"]) {
1565
+ color-scheme: dark;
1566
+ --bg: #141311;
1567
+ --bg-elev: #1e1c19;
1568
+ --bg-muted: #26231f;
1569
+ --bg-inset: #181715;
1570
+ --line: #34302b;
1571
+ --line-strong: #4a453d;
1572
+ --ink: #f4f1ea;
1573
+ --muted: #c4bdb1;
1574
+ --faint: #8f877c;
1575
+ --accent: #c5d5b8;
1576
+ --accent-ink: #1a2118;
1577
+ --accent-soft: #2a3328;
1578
+ --ok: #8fd6a8;
1579
+ --ok-soft: #1a2e22;
1580
+ --warn: #f0cc78;
1581
+ --warn-soft: #332911;
1582
+ --err: #f0a8a2;
1583
+ --err-soft: #3a201e;
1584
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1585
+ }
1586
+ }
1587
+ * { box-sizing: border-box; }
1588
+ html, body { margin: 0; height: 100%; }
1589
+ body {
1590
+ font-family: var(--sans);
1591
+ background: var(--bg);
1592
+ color: var(--ink);
1593
+ line-height: 1.45;
1594
+ padding-left: env(safe-area-inset-left);
1595
+ padding-right: env(safe-area-inset-right);
1596
+ -webkit-text-size-adjust: 100%;
1597
+ }
1598
+ button, input, select, textarea { font: inherit; color: inherit; }
1599
+ button { cursor: pointer; }
1600
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1601
+ @media (prefers-reduced-motion: reduce) {
1602
+ * { scroll-behavior: auto !important; transition: none !important; }
1603
+ }
1604
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1605
+ header.top {
1606
+ position: sticky; top: 0; z-index: 5;
1607
+ display: flex; align-items: center; gap: 12px;
1608
+ min-height: var(--header); padding: 10px 16px;
1609
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1610
+ border-bottom: 1px solid var(--line);
1611
+ backdrop-filter: blur(10px);
1612
+ }
1613
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1614
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1615
+ .brand span { color: var(--faint); font-size: 12px; }
1616
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1617
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1618
+ label.field input, label.field select, .controls input[type="password"] {
1619
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1620
+ padding: 7px 8px; min-height: 36px;
1621
+ }
1622
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1623
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1624
+ background: var(--bg-elev);
1625
+ }
1626
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1627
+ .btn-quiet { background: transparent; }
1628
+ .btn-danger { color: var(--err); }
1629
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1630
+ record or the full nav row would widen the page past the viewport. */
1631
+ .layout {
1632
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1633
+ flex: 1; min-height: 0; min-width: 0;
1634
+ }
1635
+ nav.side {
1636
+ border-right: 1px solid var(--line); padding: 12px;
1637
+ display: flex; flex-direction: column; gap: 4px;
1638
+ background: var(--bg-elev);
1639
+ }
1640
+ nav.side button {
1641
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1642
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1643
+ }
1644
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1645
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1646
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1647
+ .lede { margin: 0 0 16px; color: var(--muted); }
1648
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1649
+ .card {
1650
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1651
+ padding: 14px 16px; box-shadow: var(--shadow);
1652
+ }
1653
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1654
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1655
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1656
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1657
+ .collection {
1658
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1659
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1660
+ }
1661
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1662
+ .collection small { display: block; color: var(--faint); }
1663
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1664
+ .chip {
1665
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1666
+ border-radius: 999px; padding: 4px 8px;
1667
+ }
1668
+ .chip i { color: var(--faint); font-style: normal; }
1669
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1670
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1671
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1672
+ tr.clickable { cursor: pointer; }
1673
+ tr.clickable:hover { background: var(--bg-muted); }
1674
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1675
+ pre {
1676
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1677
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1678
+ }
1679
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1680
+ .banner {
1681
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1682
+ background: var(--err-soft); color: var(--err);
1683
+ }
1684
+ .banner.show { display: block; }
1685
+ .empty { color: var(--muted); padding: 24px 8px; }
1686
+ dialog {
1687
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1688
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1689
+ }
1690
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1691
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1692
+ textarea {
1693
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1694
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1695
+ font-family: var(--mono); font-size: 12px;
1696
+ }
1697
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1698
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1699
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1700
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1701
+ .status-2 { color: var(--ok); }
1702
+ .status-4, .status-5, .status-0 { color: var(--err); }
1703
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1704
+ .route {
1705
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1706
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1707
+ }
1708
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1709
+ @media (max-width: 800px) {
1710
+ header.top {
1711
+ align-items: stretch; flex-direction: column;
1712
+ padding-top: max(10px, env(safe-area-inset-top));
1713
+ }
1714
+ input, select, textarea { font-size: 16px; }
1715
+ .controls { width: 100%; }
1716
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1717
+ .layout { grid-template-columns: minmax(0, 1fr); }
1718
+ nav.side {
1719
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1720
+ border-right: 0; border-bottom: 1px solid var(--line);
1721
+ padding: 8px;
1722
+ }
1723
+ nav.side button { white-space: nowrap; flex: none; }
1724
+ .split { grid-template-columns: minmax(0, 1fr); }
1725
+ main { padding: 14px; }
1726
+ table, thead, tbody, tr, th, td { display: block; }
1727
+ thead { display: none; }
1728
+ tr {
1729
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1730
+ background: var(--bg-elev); min-width: 0;
1731
+ }
1732
+ td {
1733
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1734
+ min-width: 0; overflow-wrap: anywhere;
1735
+ }
1736
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1737
+ .route { grid-template-columns: 72px 1fr; }
1738
+ .route button { grid-column: 1 / -1; }
1739
+ }
1740
+ </style>
1741
+ </head>
1742
+ <body>
1743
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1744
+ <header class="top">
1745
+ <div class="brand">
1746
+ <strong>${name}</strong>
1747
+ <span>Mockingbird admin</span>
1748
+ </div>
1749
+ <div class="controls">
1750
+ <label class="field">Namespace
1751
+ <select id="namespace" aria-label="Namespace"></select>
1752
+ </label>
1753
+ <label class="field">Admin key
1754
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1755
+ </label>
1756
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1757
+ <button class="btn" id="refresh" type="button">Refresh</button>
1758
+ </div>
1759
+ </header>
1760
+ <div class="layout">
1761
+ <nav class="side" id="nav" aria-label="Admin sections">
1762
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1763
+ <button type="button" data-view="state">State</button>
1764
+ <button type="button" data-view="clock">Clock</button>
1765
+ <button type="button" data-view="faults">Faults</button>
1766
+ <button type="button" data-view="journal">Journal</button>
1767
+ <button type="button" data-view="routes">Routes</button>
1768
+ </nav>
1769
+ <main id="views">
1770
+ <p class="banner" id="banner" role="alert"></p>
1771
+ <section class="view" id="view-overview">
1772
+ <h2>Overview</h2>
1773
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1774
+ <div class="grid" id="overview-cards"></div>
1775
+ <h3>Recent requests</h3>
1776
+ <div id="overview-requests"></div>
1777
+ </section>
1778
+ <section class="view" id="view-state" hidden>
1779
+ <h2>State</h2>
1780
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1781
+ <div class="split">
1782
+ <div id="collections"></div>
1783
+ <div>
1784
+ <div id="schema"></div>
1785
+ <div class="row-actions">
1786
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1787
+ </div>
1788
+ <div id="records"></div>
1789
+ </div>
1790
+ </div>
1791
+ </section>
1792
+ <section class="view" id="view-clock" hidden>
1793
+ <h2>Clock</h2>
1794
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1795
+ <div class="card" id="clock-readout"></div>
1796
+ <div class="row-actions">
1797
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1798
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1799
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1800
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1801
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1802
+ <button class="btn" id="freeze" type="button">Freeze</button>
1803
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1804
+ </div>
1805
+ <form id="clock-set" class="row-actions">
1806
+ <label class="field">Set instant
1807
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1808
+ </label>
1809
+ <button class="btn-primary" type="submit">Set</button>
1810
+ </form>
1811
+ </section>
1812
+ <section class="view" id="view-faults" hidden>
1813
+ <h2>Faults</h2>
1814
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1815
+ <form id="fault-form" class="card stack">
1816
+ <label class="field">Preset
1817
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1818
+ </label>
1819
+ <label class="field">Status
1820
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1821
+ </label>
1822
+ <label class="field">Path prefix
1823
+ <input id="fault-path" placeholder="/v1">
1824
+ </label>
1825
+ <label class="field">Method
1826
+ <input id="fault-method" placeholder="GET">
1827
+ </label>
1828
+ <div class="dialog-actions">
1829
+ <button class="btn-primary" type="submit">Add fault</button>
1830
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1831
+ </div>
1832
+ </form>
1833
+ <div id="fault-list"></div>
1834
+ </section>
1835
+ <section class="view" id="view-journal" hidden>
1836
+ <h2>Journal</h2>
1837
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1838
+ <div class="row-actions">
1839
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1840
+ </div>
1841
+ <div id="journal"></div>
1842
+ </section>
1843
+ <section class="view" id="view-routes" hidden>
1844
+ <h2>Routes</h2>
1845
+ <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>
1846
+ <div id="route-list"></div>
1847
+ <form id="route-form" class="card stack">
1848
+ <strong id="route-title">Select a route</strong>
1849
+ <label class="field">JSON body
1850
+ <textarea id="route-body" placeholder="{ }"></textarea>
1851
+ </label>
1852
+ <div class="dialog-actions">
1853
+ <button class="btn-primary" type="submit">Send</button>
1854
+ </div>
1855
+ <pre id="route-result">Response will show here.</pre>
1856
+ </form>
1857
+ </section>
1858
+ </main>
1859
+ </div>
1860
+ </div>
1861
+ <dialog id="editor">
1862
+ <form method="dialog" id="editor-form">
1863
+ <strong id="editor-title">Record</strong>
1864
+ <label class="field">Id
1865
+ <input id="editor-id" required>
1866
+ </label>
1867
+ <label class="field">JSON value
1868
+ <textarea id="editor-value"></textarea>
1869
+ </label>
1870
+ <div class="dialog-actions">
1871
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1872
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1873
+ <button class="btn-primary" type="submit" value="save">Save</button>
1874
+ </div>
1875
+ </form>
1876
+ </dialog>
1877
+ <script>
1878
+ (() => {
1879
+ const STANDARD = new Set(${standard})
1880
+ const state = {
1881
+ namespace: "default",
1882
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1883
+ view: "overview",
1884
+ collection: "",
1885
+ shape: null,
1886
+ route: null,
1887
+ editing: null
1888
+ }
1889
+ const $ = (id) => document.getElementById(id)
1890
+ const banner = $("banner")
1891
+ const keyInput = $("admin-key")
1892
+ keyInput.value = state.key
1893
+ const params = new URLSearchParams(location.search)
1894
+ if (params.get("key")) {
1895
+ state.key = params.get("key")
1896
+ keyInput.value = state.key
1897
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1898
+ params.delete("key")
1899
+ const next = params.toString()
1900
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1901
+ }
1902
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1903
+
1904
+ const showError = (error) => {
1905
+ banner.textContent = error instanceof Error ? error.message : String(error)
1906
+ banner.classList.add("show")
1907
+ }
1908
+ const clearError = () => banner.classList.remove("show")
1909
+
1910
+ async function originGet(path) {
1911
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1912
+ if (!response.ok) throw new Error(response.status + " " + path)
1913
+ return response.json()
1914
+ }
1915
+ async function api(method, path, body) {
1916
+ const headers = { accept: "application/json" }
1917
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1918
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1919
+ if (body !== undefined) headers["content-type"] = "application/json"
1920
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1921
+ method,
1922
+ headers,
1923
+ body: body === undefined ? undefined : JSON.stringify(body)
1924
+ })
1925
+ const text = await response.text()
1926
+ let data = null
1927
+ if (text) {
1928
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1929
+ }
1930
+ if (response.status === 401) {
1931
+ keyInput.focus()
1932
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1933
+ }
1934
+ if (!response.ok) {
1935
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1936
+ }
1937
+ return data
1938
+ }
1939
+ const panelApi = {
1940
+ get: (path) => api("GET", path),
1941
+ send: (method, path, body) => api(method, path, body),
1942
+ namespace: () => state.namespace
1943
+ }
1944
+
1945
+ function setTheme(theme) {
1946
+ if (theme) document.documentElement.dataset.theme = theme
1947
+ else delete document.documentElement.dataset.theme
1948
+ }
1949
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1950
+ if (storedTheme) setTheme(storedTheme)
1951
+ $("theme").addEventListener("click", () => {
1952
+ const current = document.documentElement.dataset.theme
1953
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1954
+ const next = dark ? "light" : "dark"
1955
+ localStorage.setItem("mockingbird-admin-theme", next)
1956
+ setTheme(next)
1957
+ })
1958
+
1959
+ function show(view) {
1960
+ state.view = view
1961
+ for (const button of document.querySelectorAll("#nav button")) {
1962
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1963
+ }
1964
+ for (const section of document.querySelectorAll("main .view")) {
1965
+ section.hidden = section.id !== "view-" + view
1966
+ }
1967
+ }
1968
+ document.getElementById("nav").addEventListener("click", (event) => {
1969
+ const button = event.target.closest("button[data-view]")
1970
+ if (!button) return
1971
+ show(button.dataset.view)
1972
+ refresh().catch(showError)
1973
+ })
1974
+
1975
+ function cards(items) {
1976
+ return '<div class="grid">' + items.map((item) =>
1977
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1978
+ ).join("") + "</div>"
1979
+ }
1980
+ function table(columns, rows) {
1981
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1982
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1983
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1984
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1985
+ ).join("") + "</tr>").join("")
1986
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1987
+ }
1988
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1989
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1990
+ }[char]))
1991
+ const preview = (value) => {
1992
+ const text = JSON.stringify(value)
1993
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1994
+ }
1995
+ const when = (epoch) => {
1996
+ const date = new Date(epoch)
1997
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1998
+ }
1999
+ const clockCard = (epoch) => {
2000
+ const date = new Date(epoch)
2001
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
2002
+ const iso = date.toISOString()
2003
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
2004
+ }
2005
+
2006
+ async function loadNamespaces() {
2007
+ const data = await api("GET", "/namespaces")
2008
+ const select = $("namespace")
2009
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
2010
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
2011
+ select.innerHTML = names.map((name) =>
2012
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
2013
+ ).join("")
2014
+ select.value = state.namespace
2015
+ }
2016
+
2017
+ async function renderOverview() {
2018
+ const [health, shape, clock, journal] = await Promise.all([
2019
+ originGet("/health"),
2020
+ api("GET", "/state"),
2021
+ api("GET", "/clock"),
2022
+ api("GET", "/requests?limit=8")
2023
+ ])
2024
+ state.shape = shape
2025
+ $("overview-cards").innerHTML = cards([
2026
+ { k: "Service", v: esc(health.service || "${name}") },
2027
+ { k: "Status", v: esc(health.status || "ok") },
2028
+ { k: "Namespace", v: esc(state.namespace) },
2029
+ { k: "Collections", v: String(shape.collections.length) },
2030
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
2031
+ { k: "Clock", v: clockCard(clock.now) }
2032
+ ])
2033
+ const requests = (journal && journal.requests) || []
2034
+ $("overview-requests").innerHTML = table(
2035
+ [
2036
+ { label: "Method", cell: (row) => esc(row.method) },
2037
+ { label: "Path", cell: (row) => esc(row.path) },
2038
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
2039
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
2040
+ ],
2041
+ requests
2042
+ )
2043
+ }
2044
+
2045
+ function schemaChips(collection) {
2046
+ if (!collection || collection.fields.length === 0) {
2047
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2048
+ }
2049
+ return '<div class="chips">' + collection.fields.map((field) =>
2050
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2051
+ ).join("") + "</div>"
2052
+ }
2053
+
2054
+ async function renderState() {
2055
+ const shape = await api("GET", "/state")
2056
+ state.shape = shape
2057
+ const host = $("collections")
2058
+ if (shape.collections.length === 0) {
2059
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2060
+ $("schema").innerHTML = ""
2061
+ $("records").innerHTML = ""
2062
+ return
2063
+ }
2064
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2065
+ state.collection = shape.collections[0].name
2066
+ }
2067
+ host.innerHTML = shape.collections.map((item) =>
2068
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2069
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2070
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2071
+ ).join("")
2072
+ const selected = shape.collections.find((item) => item.name === state.collection)
2073
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2074
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2075
+ schemaChips(selected)
2076
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2077
+ const rows = page.records.map((record) => ({
2078
+ ...record,
2079
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2080
+ }))
2081
+ $("records").innerHTML = table(
2082
+ [
2083
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2084
+ { label: "Seq", cell: (row) => esc(row.seq) },
2085
+ { label: "Value", cell: (row) => preview(row.value) }
2086
+ ],
2087
+ rows
2088
+ )
2089
+ }
2090
+
2091
+ async function renderClock() {
2092
+ const clock = await api("GET", "/clock")
2093
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2094
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2095
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2096
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2097
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2098
+ }
2099
+
2100
+ async function renderFaults() {
2101
+ const [faults, presets] = await Promise.all([
2102
+ api("GET", "/faults"),
2103
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2104
+ ])
2105
+ const select = $("fault-preset")
2106
+ const current = select.value
2107
+ const list = presets.presets || []
2108
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2109
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2110
+ ).join("")
2111
+ select.value = current
2112
+ const rules = faults.faults || []
2113
+ $("fault-list").innerHTML = table(
2114
+ [
2115
+ { label: "Id", cell: (row) => esc(row.id) },
2116
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2117
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2118
+ ],
2119
+ rules
2120
+ )
2121
+ }
2122
+
2123
+ async function renderJournal() {
2124
+ const journal = await api("GET", "/requests?limit=100")
2125
+ $("journal").innerHTML = table(
2126
+ [
2127
+ { label: "When", cell: (row) => esc(row.at || "") },
2128
+ { label: "Method", cell: (row) => esc(row.method) },
2129
+ { label: "Path", cell: (row) => esc(row.path) },
2130
+ { label: "Status", cell: (row) => esc(row.status) },
2131
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2132
+ ],
2133
+ journal.requests || []
2134
+ )
2135
+ }
2136
+
2137
+ async function renderRoutes() {
2138
+ const data = await api("GET", "/")
2139
+ const routes = data.routes || []
2140
+ $("route-list").innerHTML = routes.map((route) => {
2141
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2142
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2143
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2144
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2145
+ }).join("")
2146
+ }
2147
+
2148
+ const renderers = {
2149
+ overview: renderOverview,
2150
+ state: renderState,
2151
+ clock: renderClock,
2152
+ faults: renderFaults,
2153
+ journal: renderJournal,
2154
+ routes: renderRoutes
2155
+ }
2156
+
2157
+ async function refresh() {
2158
+ clearError()
2159
+ if (state.view in renderers) await renderers[state.view]()
2160
+ }
2161
+
2162
+ $("namespace").addEventListener("change", () => {
2163
+ state.namespace = $("namespace").value
2164
+ refresh().catch(showError)
2165
+ })
2166
+ keyInput.addEventListener("change", () => {
2167
+ state.key = keyInput.value.trim()
2168
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2169
+ refresh().catch(showError)
2170
+ })
2171
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2172
+
2173
+ $("collections").addEventListener("click", (event) => {
2174
+ const button = event.target.closest("[data-collection]")
2175
+ if (!button) return
2176
+ state.collection = button.dataset.collection
2177
+ renderState().catch(showError)
2178
+ })
2179
+ $("records").addEventListener("click", (event) => {
2180
+ const row = event.target.closest("[data-id]")
2181
+ if (!row) return
2182
+ openEditor(row.dataset.id).catch(showError)
2183
+ })
2184
+
2185
+ const editor = $("editor")
2186
+ async function openEditor(id) {
2187
+ state.editing = id || null
2188
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2189
+ $("editor-id").value = id || ""
2190
+ $("editor-id").readOnly = Boolean(id)
2191
+ $("editor-delete").hidden = !id
2192
+ if (id) {
2193
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2194
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2195
+ } else {
2196
+ $("editor-value").value = "{\\n \\n}"
2197
+ }
2198
+ editor.showModal()
2199
+ }
2200
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2201
+ $("editor-form").addEventListener("submit", (event) => {
2202
+ const submitter = event.submitter
2203
+ if (!submitter || submitter.value !== "save") return
2204
+ event.preventDefault()
2205
+ let value
2206
+ try { value = JSON.parse($("editor-value").value) }
2207
+ catch { showError(new Error("Value is not JSON")); return }
2208
+ const id = $("editor-id").value.trim()
2209
+ const path = "/state/" + encodeURIComponent(state.collection)
2210
+ const request = state.editing
2211
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2212
+ : api("POST", path, { id: id || undefined, value })
2213
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2214
+ })
2215
+ $("editor-delete").addEventListener("click", () => {
2216
+ const id = state.editing
2217
+ if (!id) return
2218
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2219
+ .then(() => { editor.close(); return renderState() })
2220
+ .catch(showError)
2221
+ })
2222
+
2223
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2224
+ button.addEventListener("click", () => {
2225
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2226
+ })
2227
+ })
2228
+ $("freeze").addEventListener("click", () => {
2229
+ const frozen = $("freeze").dataset.frozen === "1"
2230
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2231
+ })
2232
+ $("clock-reset").addEventListener("click", () => {
2233
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2234
+ })
2235
+ $("clock-set").addEventListener("submit", (event) => {
2236
+ event.preventDefault()
2237
+ const raw = $("clock-instant").value.trim()
2238
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2239
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2240
+ })
2241
+
2242
+ $("fault-form").addEventListener("submit", (event) => {
2243
+ event.preventDefault()
2244
+ const preset = $("fault-preset").value
2245
+ const body = preset
2246
+ ? { preset }
2247
+ : {
2248
+ status: Number($("fault-status").value),
2249
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2250
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2251
+ }
2252
+ if (!preset && !Number.isFinite(body.status)) {
2253
+ showError(new Error("Status must be a number, or choose a preset"))
2254
+ return
2255
+ }
2256
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2257
+ })
2258
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2259
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2260
+
2261
+ $("route-list").addEventListener("click", (event) => {
2262
+ const button = event.target.closest("[data-route]")
2263
+ if (!button) return
2264
+ state.route = button.dataset.route
2265
+ $("route-title").textContent = state.route
2266
+ const method = state.route.split(" ")[0]
2267
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2268
+ })
2269
+ $("route-form").addEventListener("submit", async (event) => {
2270
+ event.preventDefault()
2271
+ if (!state.route) return showError(new Error("Choose a route first"))
2272
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2273
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2274
+ let body
2275
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2276
+ try { body = JSON.parse($("route-body").value) }
2277
+ catch { return showError(new Error("Body is not JSON")) }
2278
+ }
2279
+ try {
2280
+ const data = await api(method, concrete, body)
2281
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2282
+ } catch (error) {
2283
+ showError(error)
2284
+ }
2285
+ })
2286
+
2287
+ function mountPanels(panels) {
2288
+ const nav = $("nav")
2289
+ const views = $("views")
2290
+ for (const panel of panels) {
2291
+ const button = document.createElement("button")
2292
+ button.type = "button"
2293
+ button.dataset.view = panel.id
2294
+ button.textContent = panel.title
2295
+ nav.append(button)
2296
+ const section = document.createElement("section")
2297
+ section.className = "view"
2298
+ section.id = "view-" + panel.id
2299
+ section.hidden = true
2300
+ const title = document.createElement("h2")
2301
+ title.textContent = panel.title
2302
+ const lede = document.createElement("p")
2303
+ lede.className = "lede"
2304
+ lede.textContent = panel.description || ""
2305
+ const body = document.createElement("div")
2306
+ body.className = "panel-body"
2307
+ body.id = "panel-" + panel.id
2308
+ body.innerHTML = panel.html || ""
2309
+ section.append(title, lede, body)
2310
+ views.append(section)
2311
+ if (panel.script) {
2312
+ try {
2313
+ const run = new Function("root", "api", panel.script)
2314
+ run(body, panelApi)
2315
+ } catch (error) {
2316
+ const note = document.createElement("p")
2317
+ note.className = "banner show"
2318
+ note.textContent = error instanceof Error ? error.message : String(error)
2319
+ body.append(note)
2320
+ }
2321
+ }
2322
+ }
2323
+ }
2324
+
2325
+ loadNamespaces()
2326
+ .then(() => api("GET", "/ui/manifest"))
2327
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2328
+ .catch(showError)
2329
+ })()
2330
+ </script>
2331
+ </body>
2332
+ </html>`;
2333
+ };
2334
+ var htmlResponse = (body) => new Response(body, {
2335
+ status: 200,
2336
+ headers: {
2337
+ "content-type": "text/html; charset=utf-8",
2338
+ "cache-control": "no-store"
2339
+ }
2340
+ });
2341
+ var json3 = (body) => new Response(JSON.stringify(body), {
2342
+ status: 200,
2343
+ headers: { "content-type": "application/json; charset=utf-8" }
2344
+ });
2345
+ var adminUiRoutes = (service, ui) => {
2346
+ const shell = () => renderAdminDocument(service);
2347
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2348
+ return {
2349
+ "GET /ui": () => htmlResponse(document2()),
2350
+ "GET /ui/": () => htmlResponse(document2()),
2351
+ "GET /ui/manifest": () => json3({
2352
+ service,
2353
+ panels: (ui?.panels ?? []).map((panel) => ({
2354
+ id: panel.id,
2355
+ title: panel.title,
2356
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2357
+ html: panel.html,
2358
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2359
+ }))
2360
+ })
2361
+ };
2362
+ };
2363
+
1432
2364
  // ../../openapi/metadata/dist/types.js
1433
2365
  var EXTENSION_KEYS = {
1434
2366
  operation: "x-mockingbird",
@@ -1666,8 +2598,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1666
2598
  });
1667
2599
  };
1668
2600
 
2601
+ // ../core/dist/state-view.js
2602
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2603
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2604
+ var SAMPLE = 25;
2605
+ var WALK_LIMIT = 1e4;
2606
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2607
+ var fail = (status, message) => ({ ok: false, status, message });
2608
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2609
+ var kindOf = (value) => {
2610
+ if (value === null)
2611
+ return "null";
2612
+ if (Array.isArray(value))
2613
+ return "array";
2614
+ switch (typeof value) {
2615
+ case "string":
2616
+ return "string";
2617
+ case "number":
2618
+ return Number.isFinite(value) ? "number" : "unknown";
2619
+ case "boolean":
2620
+ return "boolean";
2621
+ case "object":
2622
+ return "object";
2623
+ default:
2624
+ return "unknown";
2625
+ }
2626
+ };
2627
+ var humanize = (name) => {
2628
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2629
+ if (words === "")
2630
+ return name;
2631
+ return words.charAt(0).toUpperCase() + words.slice(1);
2632
+ };
2633
+ var jsonValue = (value) => {
2634
+ if (value === void 0)
2635
+ return fail(400, "value is required");
2636
+ try {
2637
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2638
+ } catch {
2639
+ return fail(400, "value must be JSON");
2640
+ }
2641
+ };
2642
+ var ctorName = (value) => {
2643
+ const ctor = value.constructor;
2644
+ return typeof ctor?.name === "string" ? ctor.name : "";
2645
+ };
2646
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2647
+ var discoverCollections = (root) => {
2648
+ const found = [];
2649
+ const seen = /* @__PURE__ */ new Set();
2650
+ const visit = (value, depth) => {
2651
+ if (found.length + seen.size > WALK_LIMIT)
2652
+ return;
2653
+ if (value === null || typeof value !== "object")
2654
+ return;
2655
+ if (seen.has(value))
2656
+ return;
2657
+ seen.add(value);
2658
+ if (value instanceof Collection) {
2659
+ found.push(value);
2660
+ return;
2661
+ }
2662
+ if (value instanceof Map) {
2663
+ for (const child of value.values())
2664
+ visit(child, depth + 1);
2665
+ return;
2666
+ }
2667
+ if (value instanceof Set) {
2668
+ for (const child of value.values())
2669
+ visit(child, depth + 1);
2670
+ return;
2671
+ }
2672
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2673
+ return;
2674
+ if (Array.isArray(value)) {
2675
+ const cap = Math.min(value.length, 32);
2676
+ for (let i = 0; i < cap; i++)
2677
+ visit(value[i], depth + 1);
2678
+ return;
2679
+ }
2680
+ let children;
2681
+ try {
2682
+ children = Object.values(value);
2683
+ } catch {
2684
+ return;
2685
+ }
2686
+ for (const child of children)
2687
+ visit(child, depth + 1);
2688
+ };
2689
+ visit(root, 0);
2690
+ return found;
2691
+ };
2692
+ var storedNames = (sqlite, namespace) => {
2693
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2694
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2695
+ return [...records, ...sequences].map((row) => row.name);
2696
+ };
2697
+ var blankAccum = (name) => ({
2698
+ name,
2699
+ kinds: /* @__PURE__ */ new Set(),
2700
+ present: 0,
2701
+ nested: /* @__PURE__ */ new Map()
2702
+ });
2703
+ var absorb = (accum, value) => {
2704
+ const kind = kindOf(value);
2705
+ accum.kinds.add(kind);
2706
+ accum.present++;
2707
+ if (!isRecord3(value))
2708
+ return;
2709
+ for (const [key, child] of Object.entries(value)) {
2710
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2711
+ absorb(nested, child);
2712
+ accum.nested.set(key, nested);
2713
+ }
2714
+ };
2715
+ var finishField = (accum, samples) => {
2716
+ const kinds = [...accum.kinds];
2717
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2718
+ const field = {
2719
+ name: accum.name,
2720
+ kind,
2721
+ optional: accum.present < samples || kinds.includes("null")
2722
+ };
2723
+ if (accum.nested.size > 0) {
2724
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2725
+ }
2726
+ return field;
2727
+ };
2728
+ var inferFields = (records) => {
2729
+ if (records.length === 0)
2730
+ return [];
2731
+ const sample = records.slice(0, SAMPLE);
2732
+ const objects = sample.filter((record) => isRecord3(record.value));
2733
+ if (objects.length === 0) {
2734
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2735
+ const list = [...kinds];
2736
+ return [
2737
+ {
2738
+ name: "(value)",
2739
+ kind: list.length === 1 ? list[0] : "unknown",
2740
+ optional: false
2741
+ }
2742
+ ];
2743
+ }
2744
+ const root = /* @__PURE__ */ new Map();
2745
+ for (const record of objects) {
2746
+ for (const [key, value] of Object.entries(record.value)) {
2747
+ const accum = root.get(key) ?? blankAccum(key);
2748
+ absorb(accum, value);
2749
+ root.set(key, accum);
2750
+ }
2751
+ }
2752
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2753
+ };
2754
+ var mergeFields = (declared, inferred) => {
2755
+ const byName = /* @__PURE__ */ new Map();
2756
+ for (const field of inferred)
2757
+ byName.set(field.name, field);
2758
+ const ordered = [];
2759
+ const seen = /* @__PURE__ */ new Set();
2760
+ for (const field of declared ?? []) {
2761
+ const found = byName.get(field.name);
2762
+ seen.add(field.name);
2763
+ if (!found) {
2764
+ ordered.push({ ...field, optional: field.optional });
2765
+ continue;
2766
+ }
2767
+ ordered.push({
2768
+ ...found,
2769
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2770
+ optional: field.optional || found.optional,
2771
+ ...field.description !== void 0 ? { description: field.description } : {},
2772
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2773
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2774
+ });
2775
+ }
2776
+ for (const field of inferred) {
2777
+ if (!seen.has(field.name))
2778
+ ordered.push(field);
2779
+ }
2780
+ return ordered;
2781
+ };
2782
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2783
+ var readRecord = (collection, id) => {
2784
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2785
+ const row = rows.find((entry) => entry.id === id);
2786
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2787
+ };
2788
+ var inspectState = (scope) => {
2789
+ const declared = /* @__PURE__ */ new Map();
2790
+ for (const declaration of scope.declarations ?? []) {
2791
+ if (COLLECTION_NAME.test(declaration.name))
2792
+ declared.set(declaration.name, declaration);
2793
+ }
2794
+ const names = new Set(declared.keys());
2795
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2796
+ names.add(name);
2797
+ for (const collection of discoverCollections(scope.root)) {
2798
+ if (collection.namespace === scope.storageNamespace)
2799
+ names.add(collection.collectionName);
2800
+ }
2801
+ const collections = [];
2802
+ for (const name of names) {
2803
+ if (!COLLECTION_NAME.test(name))
2804
+ continue;
2805
+ const declaration = declared.get(name);
2806
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2807
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2808
+ const inferred = inferFields(records);
2809
+ const fields = mergeFields(declaration?.fields, inferred);
2810
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2811
+ collections.push({
2812
+ name,
2813
+ label: declaration?.label ?? humanize(name),
2814
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2815
+ count: collection.count(),
2816
+ source,
2817
+ fields,
2818
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2819
+ });
2820
+ }
2821
+ const order = /* @__PURE__ */ new Map();
2822
+ for (const [index, item] of (scope.declarations ?? []).entries())
2823
+ order.set(item.name, index);
2824
+ collections.sort((a, b) => {
2825
+ const left = order.get(a.name);
2826
+ const right = order.get(b.name);
2827
+ if (left !== void 0 && right !== void 0)
2828
+ return left - right;
2829
+ if (left !== void 0)
2830
+ return -1;
2831
+ if (right !== void 0)
2832
+ return 1;
2833
+ return a.name.localeCompare(b.name);
2834
+ });
2835
+ return {
2836
+ namespace: scope.namespace,
2837
+ storageNamespace: scope.storageNamespace,
2838
+ collections
2839
+ };
2840
+ };
2841
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2842
+ if (!COLLECTION_NAME.test(name))
2843
+ return fail(400, "collection name is not allowed");
2844
+ const limit = query.limit ?? 50;
2845
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2846
+ return fail(400, "limit must be an integer from 1 to 200");
2847
+ }
2848
+ const order = query.order ?? "newest";
2849
+ if (order !== "newest" && order !== "oldest")
2850
+ return fail(400, 'order must be "newest" or "oldest"');
2851
+ const collection = collectionOf(sqlite, storageNamespace, name);
2852
+ const rows = collection.list({ order }).filter((row) => {
2853
+ if (query.after === void 0)
2854
+ return true;
2855
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2856
+ });
2857
+ const slice = rows.slice(0, limit);
2858
+ const last = slice.at(-1);
2859
+ return {
2860
+ ok: true,
2861
+ value: {
2862
+ collection: name,
2863
+ count: collection.count(),
2864
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2865
+ next: rows.length > limit && last ? last.seq : null
2866
+ }
2867
+ };
2868
+ };
2869
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2870
+ var readStateRecord = (scope, name, id) => {
2871
+ if (!COLLECTION_NAME.test(name))
2872
+ return fail(400, "collection name is not allowed");
2873
+ if (!RECORD_ID.test(id))
2874
+ return fail(400, "record id is not allowed");
2875
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2876
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2877
+ };
2878
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2879
+ var createStateRecord = (scope, name, input) => {
2880
+ if (!COLLECTION_NAME.test(name))
2881
+ return fail(400, "collection name is not allowed");
2882
+ const parsed = jsonValue(input.value);
2883
+ if (!parsed.ok)
2884
+ return parsed;
2885
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2886
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2887
+ const checked = requireId(id);
2888
+ if (!checked.ok)
2889
+ return checked;
2890
+ if (collection.has(checked.value))
2891
+ return fail(409, `record ${checked.value} already exists`);
2892
+ const stored = collection.insert(checked.value, parsed.value);
2893
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2894
+ };
2895
+ var replaceStateRecord = (scope, name, id, value) => {
2896
+ if (!COLLECTION_NAME.test(name))
2897
+ return fail(400, "collection name is not allowed");
2898
+ const checked = requireId(id);
2899
+ if (!checked.ok)
2900
+ return checked;
2901
+ const parsed = jsonValue(value);
2902
+ if (!parsed.ok)
2903
+ return parsed;
2904
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2905
+ if (!collection.has(checked.value))
2906
+ return fail(404, `no record ${checked.value} in ${name}`);
2907
+ const stored = collection.update(checked.value, parsed.value);
2908
+ if (!stored)
2909
+ return fail(404, `no record ${checked.value} in ${name}`);
2910
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2911
+ };
2912
+ var patchStateRecord = (scope, name, id, value) => {
2913
+ const current = readStateRecord(scope, name, id);
2914
+ if (!current.ok)
2915
+ return current;
2916
+ const parsed = jsonValue(value);
2917
+ if (!parsed.ok)
2918
+ return parsed;
2919
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2920
+ return replaceStateRecord(scope, name, id, next);
2921
+ };
2922
+ var deleteStateRecord = (scope, name, id) => {
2923
+ if (!COLLECTION_NAME.test(name))
2924
+ return fail(400, "collection name is not allowed");
2925
+ const checked = requireId(id);
2926
+ if (!checked.ok)
2927
+ return checked;
2928
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2929
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2930
+ };
2931
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
2932
+ status,
2933
+ headers: { "content-type": "application/json; charset=utf-8" }
2934
+ });
2935
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2936
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
2937
+ var integerParam = (value) => {
2938
+ if (value === null)
2939
+ return void 0;
2940
+ if (!/^-?\d+$/.test(value))
2941
+ return "bad";
2942
+ return Number(value);
2943
+ };
2944
+ var stateAdminRoutes = (routes) => {
2945
+ const open = (namespace) => {
2946
+ try {
2947
+ return { ok: true, value: routes.open(namespace) };
2948
+ } catch (error) {
2949
+ return fail(400, error instanceof Error ? error.message : String(error));
2950
+ }
2951
+ };
2952
+ const wrote = (namespace) => {
2953
+ routes.afterWrite?.(namespace);
2954
+ };
2955
+ return {
2956
+ "GET /state": ({ namespace }) => {
2957
+ const scope = open(namespace);
2958
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2959
+ },
2960
+ "GET /state/:collection": ({ namespace, params, url }) => {
2961
+ const scope = open(namespace);
2962
+ if (!scope.ok)
2963
+ return fromResult(scope, 200);
2964
+ const limit = integerParam(url.searchParams.get("limit"));
2965
+ const after = integerParam(url.searchParams.get("after"));
2966
+ if (limit === "bad")
2967
+ return adminError2(400, "limit: expected an integer");
2968
+ if (after === "bad")
2969
+ return adminError2(400, "after: expected a sequence number");
2970
+ const order = url.searchParams.get("order");
2971
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2972
+ ...limit !== void 0 ? { limit } : {},
2973
+ ...after !== void 0 ? { after } : {},
2974
+ ...order === "newest" || order === "oldest" ? { order } : {}
2975
+ }), 200);
2976
+ },
2977
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2978
+ const scope = open(namespace);
2979
+ if (!scope.ok)
2980
+ return fromResult(scope, 200);
2981
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2982
+ },
2983
+ "POST /state/:collection": ({ namespace, params, body }) => {
2984
+ const scope = open(namespace);
2985
+ if (!scope.ok)
2986
+ return fromResult(scope, 201);
2987
+ if (!isRecord3(body) || !("value" in body)) {
2988
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2989
+ }
2990
+ const id = body.id;
2991
+ if (id !== void 0 && typeof id !== "string")
2992
+ return adminError2(400, "id must be a string");
2993
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2994
+ ...typeof id === "string" ? { id } : {},
2995
+ value: body.value
2996
+ });
2997
+ if (created.ok)
2998
+ wrote(namespace);
2999
+ return fromResult(created, 201);
3000
+ },
3001
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3002
+ const scope = open(namespace);
3003
+ if (!scope.ok)
3004
+ return fromResult(scope, 200);
3005
+ if (!isRecord3(body) || !("value" in body))
3006
+ return adminError2(400, 'expected {"value": <json>}');
3007
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3008
+ if (replaced.ok)
3009
+ wrote(namespace);
3010
+ return fromResult(replaced, 200);
3011
+ },
3012
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3013
+ const scope = open(namespace);
3014
+ if (!scope.ok)
3015
+ return fromResult(scope, 200);
3016
+ if (!isRecord3(body) || !("value" in body))
3017
+ return adminError2(400, 'expected {"value": <json>}');
3018
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3019
+ if (patched.ok)
3020
+ wrote(namespace);
3021
+ return fromResult(patched, 200);
3022
+ },
3023
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3024
+ const scope = open(namespace);
3025
+ if (!scope.ok)
3026
+ return fromResult(scope, 200);
3027
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3028
+ if (removed.ok)
3029
+ wrote(namespace);
3030
+ return fromResult(removed, 200);
3031
+ }
3032
+ };
3033
+ };
3034
+
1669
3035
  // ../core/dist/version.js
1670
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
3036
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1671
3037
 
1672
3038
  // ../core/dist/signing.js
1673
3039
  var encoder = new TextEncoder();
@@ -2002,11 +3368,11 @@ var createWebhookHub = (options) => {
2002
3368
  };
2003
3369
  return hub;
2004
3370
  };
2005
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2006
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2007
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3371
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3372
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3373
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2008
3374
  var parseEndpoint = (value) => {
2009
- if (!isRecord3(value) || typeof value.url !== "string")
3375
+ if (!isRecord4(value) || typeof value.url !== "string")
2010
3376
  return "each endpoint needs a url";
2011
3377
  try {
2012
3378
  new URL(value.url);
@@ -2023,18 +3389,18 @@ var parseEndpoint = (value) => {
2023
3389
  const events = value.events ?? value.enabledEvents;
2024
3390
  if (Array.isArray(events))
2025
3391
  endpoint.events = events.map(String);
2026
- if (isRecord3(value.tags)) {
3392
+ if (isRecord4(value.tags)) {
2027
3393
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2028
3394
  }
2029
3395
  if (typeof value.account === "string")
2030
3396
  endpoint.tags = { ...endpoint.tags, account: value.account };
2031
- if (isRecord3(value.headers)) {
3397
+ if (isRecord4(value.headers)) {
2032
3398
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2033
3399
  }
2034
3400
  return endpoint;
2035
3401
  };
2036
3402
  var webhookAdminRoutes = (hub) => ({
2037
- "GET /webhooks": ({ url, namespace }) => json3(200, {
3403
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
2038
3404
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2039
3405
  const type = url.searchParams.get("type");
2040
3406
  return type === null || d.type === type;
@@ -2042,51 +3408,51 @@ var webhookAdminRoutes = (hub) => ({
2042
3408
  }),
2043
3409
  "GET /webhooks/events": ({ url, namespace }) => {
2044
3410
  const type = url.searchParams.get("type");
2045
- return json3(200, {
3411
+ return json5(200, {
2046
3412
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2047
3413
  });
2048
3414
  },
2049
3415
  "POST /webhooks/:id/replay": async ({ params }) => {
2050
3416
  const replayed = await hub.replay(params.id);
2051
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3417
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2052
3418
  },
2053
3419
  "POST /webhooks/flush": async () => {
2054
3420
  await hub.flush();
2055
- return json3(200, { status: "ok" });
3421
+ return json5(200, { status: "ok" });
2056
3422
  },
2057
3423
  "POST /webhooks/faults": ({ body, namespace }) => {
2058
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2059
- return adminError2(400, "mode must be duplicate, reorder or drop");
3424
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3425
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2060
3426
  }
2061
3427
  const fault = { mode: body.mode };
2062
3428
  if (typeof body.count === "number")
2063
3429
  fault.count = body.count;
2064
3430
  hub.fault(namespace, fault);
2065
- return json3(201, { namespace, ...fault });
3431
+ return json5(201, { namespace, ...fault });
2066
3432
  },
2067
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
3433
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
2068
3434
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2069
3435
  ...rest,
2070
3436
  secret: secret ? "(set)" : null
2071
3437
  }))
2072
3438
  }),
2073
3439
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2074
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3440
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2075
3441
  if (!Array.isArray(list))
2076
- return adminError2(400, "expected [{url, secret?, events?}]");
3442
+ return adminError3(400, "expected [{url, secret?, events?}]");
2077
3443
  const parsed = [];
2078
3444
  for (const each of list) {
2079
3445
  const endpoint = parseEndpoint(each);
2080
3446
  if (typeof endpoint === "string")
2081
- return adminError2(400, endpoint);
3447
+ return adminError3(400, endpoint);
2082
3448
  parsed.push(endpoint);
2083
3449
  }
2084
3450
  const set = hub.setEndpoints(namespace, parsed);
2085
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3451
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2086
3452
  },
2087
3453
  "DELETE /webhook-endpoints": ({ namespace }) => {
2088
3454
  hub.setEndpoints(namespace, []);
2089
- return json3(200, { status: "ok" });
3455
+ return json5(200, { status: "ok" });
2090
3456
  }
2091
3457
  });
2092
3458
  var parsePayload = (message) => {
@@ -2151,6 +3517,7 @@ var operationMatcher = (document2) => {
2151
3517
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2152
3518
  };
2153
3519
  var createRuntime = (options) => {
3520
+ assertAdminUi(options.adminUi);
2154
3521
  const sqlite = bootSqlite(options.sqlite);
2155
3522
  const clock = options.clock ?? createClock();
2156
3523
  const rng = createRng(options.seed ?? 0);
@@ -2357,6 +3724,19 @@ var createRuntime = (options) => {
2357
3724
  else
2358
3725
  timeline(name);
2359
3726
  };
3727
+ const declarationsFor = (namespace) => {
3728
+ const declared = options.state;
3729
+ if (!declared)
3730
+ return [];
3731
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3732
+ };
3733
+ const stateScope = (namespace) => ({
3734
+ sqlite,
3735
+ namespace,
3736
+ storageNamespace: storageNamespace(namespace),
3737
+ root: instance(namespace),
3738
+ declarations: declarationsFor(namespace)
3739
+ });
2360
3740
  const runtime = {
2361
3741
  name: options.name,
2362
3742
  sqlite,
@@ -2395,6 +3775,7 @@ var createRuntime = (options) => {
2395
3775
  branch,
2396
3776
  checkout,
2397
3777
  timeline,
3778
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2398
3779
  fetch: async (incoming) => {
2399
3780
  let request = incoming;
2400
3781
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2588,11 +3969,20 @@ var createRuntime = (options) => {
2588
3969
  ...credentialRoutes(credentials),
2589
3970
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2590
3971
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2591
- ...options.admin?.(runtime) ?? {}
3972
+ ...options.admin?.(runtime) ?? {},
3973
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3974
+ // beside these; it does not replace `/state` or `/ui`.
3975
+ ...stateAdminRoutes({
3976
+ open: stateScope,
3977
+ afterWrite: (namespace) => {
3978
+ checkpoint(namespace, "main");
3979
+ }
3980
+ }),
3981
+ ...adminUiRoutes(options.name, options.adminUi)
2592
3982
  },
2593
3983
  adminKey: options.adminKey
2594
3984
  });
2595
- return runtime;
3985
+ return defineMock(runtime);
2596
3986
  };
2597
3987
  var mutableResponse = (response) => {
2598
3988
  try {
@@ -2890,9 +4280,9 @@ var CUSTOMERIO_PRESETS = {
2890
4280
  webhook: { mode: "drop" }
2891
4281
  }
2892
4282
  };
2893
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2894
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2895
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4283
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4284
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
4285
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2896
4286
  var adminRoutes = (runtime) => ({
2897
4287
  ...outboxAdminRoutes(
2898
4288
  runtime,
@@ -2909,21 +4299,21 @@ var adminRoutes = (runtime) => ({
2909
4299
  const userId = url.searchParams.get("userId");
2910
4300
  const type = url.searchParams.get("type");
2911
4301
  const event = url.searchParams.get("event");
2912
- return json4(200, {
4302
+ return json6(200, {
2913
4303
  events: runtime.instance(namespace).state.cdp.list({
2914
4304
  order: "oldest",
2915
4305
  where: (e) => (userId === null || e.userId === userId) && (type === null || e.type === type) && (event === null || e.event === event)
2916
4306
  }).map((row) => row.value)
2917
4307
  });
2918
4308
  },
2919
- "GET /profiles": ({ namespace }) => json4(200, { profiles: runtime.instance(namespace).profiles() }),
4309
+ "GET /profiles": ({ namespace }) => json6(200, { profiles: runtime.instance(namespace).profiles() }),
2920
4310
  "GET /profiles/:id": ({ params, namespace }) => {
2921
4311
  const profile = runtime.instance(namespace).state.profile(params.id);
2922
- return profile ? json4(200, profile) : adminError3(404, `no profile ${params.id}`);
4312
+ return profile ? json6(200, profile) : adminError4(404, `no profile ${params.id}`);
2923
4313
  },
2924
4314
  "POST /reporting-events": ({ body, namespace }) => {
2925
- if (!isRecord4(body) || typeof body.metric !== "string") {
2926
- return adminError3(
4315
+ if (!isRecord5(body) || typeof body.metric !== "string") {
4316
+ return adminError4(
2927
4317
  400,
2928
4318
  'expected {"metric": "unsubscribed"|"subscribed"|"spammed"|"cio_subscription_preferences_changed"|\u2026, "userId"?, "email"?, "deliveryId"?, "objectType"?, "preferences"?}'
2929
4319
  );
@@ -2934,20 +4324,20 @@ var adminRoutes = (runtime) => ({
2934
4324
  const value = text(key);
2935
4325
  if (value !== void 0) input[key] = value;
2936
4326
  }
2937
- if (isRecord4(body.preferences))
4327
+ if (isRecord5(body.preferences))
2938
4328
  input.preferences = body.preferences;
2939
4329
  const event = runtime.instance(namespace).report(input);
2940
- return typeof event === "string" ? adminError3(404, event) : json4(201, event);
4330
+ return typeof event === "string" ? adminError4(404, event) : json6(201, event);
2941
4331
  },
2942
- "GET /transactional": ({ namespace }) => json4(200, { messages: runtime.instance(namespace).state.catalog() }),
4332
+ "GET /transactional": ({ namespace }) => json6(200, { messages: runtime.instance(namespace).state.catalog() }),
2943
4333
  "PUT /transactional": ({ body, namespace }) => {
2944
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.messages : void 0;
2945
- if (!Array.isArray(list)) return adminError3(400, "expected [{id, name, trigger_name, \u2026}]");
4334
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.messages : void 0;
4335
+ if (!Array.isArray(list)) return adminError4(400, "expected [{id, name, trigger_name, \u2026}]");
2946
4336
  const state = runtime.instance(namespace).state;
2947
4337
  for (const row of state.catalog()) state.messages.delete(String(row.id));
2948
4338
  for (const [index, raw] of list.entries()) {
2949
- if (!isRecord4(raw) || typeof raw.trigger_name !== "string") {
2950
- return adminError3(400, `messages[${index}]: trigger_name is required`);
4339
+ if (!isRecord5(raw) || typeof raw.trigger_name !== "string") {
4340
+ return adminError4(400, `messages[${index}]: trigger_name is required`);
2951
4341
  }
2952
4342
  const id = typeof raw.id === "number" ? raw.id : index + 1;
2953
4343
  state.messages.insert(String(id), {
@@ -2964,16 +4354,16 @@ var adminRoutes = (runtime) => ({
2964
4354
  updated_at: 1735689600
2965
4355
  });
2966
4356
  }
2967
- return json4(200, { messages: state.catalog() });
4357
+ return json6(200, { messages: state.catalog() });
2968
4358
  },
2969
- "GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
4359
+ "GET /settings": ({ namespace }) => json6(200, runtime.instance(namespace).state.current()),
2970
4360
  "PUT /settings": ({ body, namespace }) => {
2971
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
4361
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2972
4362
  const patch = {};
2973
4363
  if (typeof body.strictMessages === "boolean") patch.strictMessages = body.strictMessages;
2974
4364
  if (typeof body.trackingBase === "string") patch.trackingBase = body.trackingBase;
2975
4365
  if (Array.isArray(body.keys)) patch.keys = body.keys.map(String);
2976
- return json4(200, runtime.instance(namespace).state.update(patch));
4366
+ return json6(200, runtime.instance(namespace).state.update(patch));
2977
4367
  }
2978
4368
  });
2979
4369
  var createRuntime2 = (options = {}) => {
@@ -3035,7 +4425,7 @@ var APP_OPERATIONS = /* @__PURE__ */ new Set([
3035
4425
  var clickNotFound = () => new Response("404 page not found", { status: 404, headers: { "content-type": "text/plain" } });
3036
4426
  var cdpError = (status, error) => jsonRes(status, { error });
3037
4427
  var appError = (status, error) => jsonRes(status, { meta: { error } });
3038
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4428
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3039
4429
  var URL_PATTERN = /https?:\/\/[^\s"'<>]+/g;
3040
4430
  var urlsIn = (value, out = []) => {
3041
4431
  if (typeof value === "string") {
@@ -3044,7 +4434,7 @@ var urlsIn = (value, out = []) => {
3044
4434
  }
3045
4435
  } else if (Array.isArray(value)) {
3046
4436
  for (const item of value) urlsIn(item, out);
3047
- } else if (isRecord5(value)) {
4437
+ } else if (isRecord6(value)) {
3048
4438
  for (const item of Object.values(value)) urlsIn(item, out);
3049
4439
  }
3050
4440
  return out;
@@ -3130,7 +4520,7 @@ var CustomerIoAPI = class {
3130
4520
  }
3131
4521
  // ---------------------------------------------------------------- CDP
3132
4522
  cdp(context, kind) {
3133
- if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
4523
+ if (context.body.kind !== "json" || !isRecord6(context.body.value)) {
3134
4524
  return cdpError(400, "Invalid JSON body");
3135
4525
  }
3136
4526
  const issue = bodyIssues(context)[0];
@@ -3163,8 +4553,8 @@ var CustomerIoAPI = class {
3163
4553
  userId: typeof item.userId === "string" ? item.userId : null,
3164
4554
  anonymousId: typeof item.anonymousId === "string" ? item.anonymousId : null,
3165
4555
  event: typeof item.event === "string" ? item.event : null,
3166
- traits: isRecord5(item.traits) ? item.traits : {},
3167
- properties: isRecord5(item.properties) ? item.properties : {},
4556
+ traits: isRecord6(item.traits) ? item.traits : {},
4557
+ properties: isRecord6(item.properties) ? item.properties : {},
3168
4558
  timestamp: typeof item.timestamp === "string" ? item.timestamp : null,
3169
4559
  receivedAt: at,
3170
4560
  duplicate
@@ -3187,7 +4577,7 @@ var CustomerIoAPI = class {
3187
4577
  }
3188
4578
  // ---------------------------------------------------------------- App API sends
3189
4579
  send(context, channel) {
3190
- if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
4580
+ if (context.body.kind !== "json" || !isRecord6(context.body.value)) {
3191
4581
  return appError(400, "invalid JSON body");
3192
4582
  }
3193
4583
  const issue = bodyIssues(context)[0];
@@ -3224,7 +4614,7 @@ var CustomerIoAPI = class {
3224
4614
  }
3225
4615
  const tracked = body.tracked === true || body.tracked === void 0 && !!message?.link_tracking;
3226
4616
  const deliveryId = this.state.deliveryId();
3227
- const messageData = isRecord5(body.message_data) ? body.message_data : {};
4617
+ const messageData = isRecord6(body.message_data) ? body.message_data : {};
3228
4618
  const retain = body.disable_message_retention !== true;
3229
4619
  const links = urlsIn([messageData, body.body ?? ""]).map((url) => {
3230
4620
  if (!tracked) return url;
@@ -3235,7 +4625,7 @@ var CustomerIoAPI = class {
3235
4625
  const sendToUnsubscribed = body.send_to_unsubscribed === true || body.send_to_unsubscribed === void 0 && !!message?.send_to_unsubscribed;
3236
4626
  const channelOff = channel !== "inbox" && !!profile?.channelsOff.includes(channel === "sms" ? "sms" : "email");
3237
4627
  const suppressed = !sendToUnsubscribed && (!!profile?.unsubscribed || channelOff);
3238
- const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord5(body.attachments) ? Object.keys(body.attachments) : [];
4628
+ const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord6(body.attachments) ? Object.keys(body.attachments) : [];
3239
4629
  const queuedAt = Math.floor(this.now() / 1e3);
3240
4630
  const delivery = {
3241
4631
  id: deliveryId,
@@ -3252,7 +4642,7 @@ var CustomerIoAPI = class {
3252
4642
  tracked,
3253
4643
  sendToUnsubscribed,
3254
4644
  disableMessageRetention: !retain,
3255
- headers: isRecord5(body.headers) ? body.headers : {},
4645
+ headers: isRecord6(body.headers) ? body.headers : {},
3256
4646
  attachments,
3257
4647
  state: suppressed ? "suppressed" : "sent",
3258
4648
  queuedAt,
@@ -3365,4 +4755,4 @@ export {
3365
4755
  customerIoCredential,
3366
4756
  CustomerIoAPI
3367
4757
  };
3368
- //# sourceMappingURL=chunk-SULJ3UI6.js.map
4758
+ //# sourceMappingURL=chunk-F2COC6BX.js.map