@crvouga/mockingbird-service-livekit 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -961,6 +963,936 @@ var clearNamespace = (sqlite, namespace) => {
961
963
  });
962
964
  };
963
965
 
966
+ // ../core/dist/surface.js
967
+ var defineMock = (runtime) => runtime;
968
+ var STANDARD_ADMIN_ROUTES = [
969
+ "GET /",
970
+ "POST /reset",
971
+ "GET /namespaces",
972
+ "GET /clock",
973
+ "POST /clock",
974
+ "GET /faults",
975
+ "POST /faults",
976
+ "DELETE /faults",
977
+ "POST /snapshots",
978
+ "POST /snapshots/:id/restore",
979
+ "DELETE /snapshots/:id",
980
+ "GET /timeline",
981
+ "POST /checkpoints",
982
+ "POST /branches/:name",
983
+ "POST /branches/:name/checkout",
984
+ "GET /requests",
985
+ "DELETE /requests",
986
+ "GET /metrics",
987
+ "DELETE /metrics",
988
+ "GET /credentials",
989
+ "PUT /credentials",
990
+ "DELETE /credentials",
991
+ "GET /state",
992
+ "GET /state/:collection",
993
+ "GET /state/:collection/:id",
994
+ "POST /state/:collection",
995
+ "PUT /state/:collection/:id",
996
+ "PATCH /state/:collection/:id",
997
+ "DELETE /state/:collection/:id",
998
+ "GET /ui",
999
+ "GET /ui/",
1000
+ "GET /ui/manifest"
1001
+ ];
1002
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1003
+ var assertAdminUi = (ui) => {
1004
+ if (!ui?.panels)
1005
+ return;
1006
+ const seen = /* @__PURE__ */ new Set();
1007
+ for (const panel of ui.panels) {
1008
+ if (!PANEL_ID.test(panel.id)) {
1009
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1010
+ }
1011
+ if (seen.has(panel.id))
1012
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1013
+ seen.add(panel.id);
1014
+ if (panel.title.trim() === "")
1015
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1016
+ }
1017
+ };
1018
+
1019
+ // ../core/dist/admin-ui.js
1020
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1021
+ switch (char) {
1022
+ case "&":
1023
+ return "&amp;";
1024
+ case "<":
1025
+ return "&lt;";
1026
+ case ">":
1027
+ return "&gt;";
1028
+ case '"':
1029
+ return "&quot;";
1030
+ default:
1031
+ return "&#39;";
1032
+ }
1033
+ });
1034
+ var renderAdminDocument = (service) => {
1035
+ const name = escapeHtml(service);
1036
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1037
+ return `<!DOCTYPE html>
1038
+ <html lang="en">
1039
+ <head>
1040
+ <meta charset="utf-8">
1041
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1042
+ <meta name="color-scheme" content="light dark">
1043
+ <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">
1044
+ <title>${name} admin</title>
1045
+ <style>
1046
+ :root {
1047
+ color-scheme: light;
1048
+ --bg: #f6f5f2;
1049
+ --bg-elev: #ffffff;
1050
+ --bg-muted: #eeece6;
1051
+ --bg-inset: #f3f1eb;
1052
+ --line: #e2dfd6;
1053
+ --line-strong: #d0ccc1;
1054
+ --ink: #1c1915;
1055
+ --muted: #5e584f;
1056
+ --faint: #8a8378;
1057
+ --accent: #3d4f3a;
1058
+ --accent-ink: #f7f6f2;
1059
+ --accent-soft: #e5ece2;
1060
+ --ok: #1f7a45;
1061
+ --ok-soft: #e5f4eb;
1062
+ --warn: #9a6700;
1063
+ --warn-soft: #fbf3df;
1064
+ --err: #a33b32;
1065
+ --err-soft: #fdecea;
1066
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1067
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1068
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1069
+ --radius: 14px;
1070
+ --header: 60px;
1071
+ --nav: 220px;
1072
+ }
1073
+ :root[data-theme="dark"] {
1074
+ color-scheme: dark;
1075
+ --bg: #141311;
1076
+ --bg-elev: #1e1c19;
1077
+ --bg-muted: #26231f;
1078
+ --bg-inset: #181715;
1079
+ --line: #34302b;
1080
+ --line-strong: #4a453d;
1081
+ --ink: #f4f1ea;
1082
+ --muted: #c4bdb1;
1083
+ --faint: #8f877c;
1084
+ --accent: #c5d5b8;
1085
+ --accent-ink: #1a2118;
1086
+ --accent-soft: #2a3328;
1087
+ --ok: #8fd6a8;
1088
+ --ok-soft: #1a2e22;
1089
+ --warn: #f0cc78;
1090
+ --warn-soft: #332911;
1091
+ --err: #f0a8a2;
1092
+ --err-soft: #3a201e;
1093
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1094
+ }
1095
+ @media (prefers-color-scheme: dark) {
1096
+ :root:not([data-theme="light"]) {
1097
+ color-scheme: dark;
1098
+ --bg: #141311;
1099
+ --bg-elev: #1e1c19;
1100
+ --bg-muted: #26231f;
1101
+ --bg-inset: #181715;
1102
+ --line: #34302b;
1103
+ --line-strong: #4a453d;
1104
+ --ink: #f4f1ea;
1105
+ --muted: #c4bdb1;
1106
+ --faint: #8f877c;
1107
+ --accent: #c5d5b8;
1108
+ --accent-ink: #1a2118;
1109
+ --accent-soft: #2a3328;
1110
+ --ok: #8fd6a8;
1111
+ --ok-soft: #1a2e22;
1112
+ --warn: #f0cc78;
1113
+ --warn-soft: #332911;
1114
+ --err: #f0a8a2;
1115
+ --err-soft: #3a201e;
1116
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1117
+ }
1118
+ }
1119
+ * { box-sizing: border-box; }
1120
+ html, body { margin: 0; height: 100%; }
1121
+ body {
1122
+ font-family: var(--sans);
1123
+ background: var(--bg);
1124
+ color: var(--ink);
1125
+ line-height: 1.45;
1126
+ padding-left: env(safe-area-inset-left);
1127
+ padding-right: env(safe-area-inset-right);
1128
+ -webkit-text-size-adjust: 100%;
1129
+ }
1130
+ button, input, select, textarea { font: inherit; color: inherit; }
1131
+ button { cursor: pointer; }
1132
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1133
+ @media (prefers-reduced-motion: reduce) {
1134
+ * { scroll-behavior: auto !important; transition: none !important; }
1135
+ }
1136
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1137
+ header.top {
1138
+ position: sticky; top: 0; z-index: 5;
1139
+ display: flex; align-items: center; gap: 12px;
1140
+ min-height: var(--header); padding: 10px 16px;
1141
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1142
+ border-bottom: 1px solid var(--line);
1143
+ backdrop-filter: blur(10px);
1144
+ }
1145
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1146
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1147
+ .brand span { color: var(--faint); font-size: 12px; }
1148
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1149
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1150
+ label.field input, label.field select, .controls input[type="password"] {
1151
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1152
+ padding: 7px 8px; min-height: 36px;
1153
+ }
1154
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1155
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1156
+ background: var(--bg-elev);
1157
+ }
1158
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1159
+ .btn-quiet { background: transparent; }
1160
+ .btn-danger { color: var(--err); }
1161
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1162
+ record or the full nav row would widen the page past the viewport. */
1163
+ .layout {
1164
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1165
+ flex: 1; min-height: 0; min-width: 0;
1166
+ }
1167
+ nav.side {
1168
+ border-right: 1px solid var(--line); padding: 12px;
1169
+ display: flex; flex-direction: column; gap: 4px;
1170
+ background: var(--bg-elev);
1171
+ }
1172
+ nav.side button {
1173
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1174
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1175
+ }
1176
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1177
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1178
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1179
+ .lede { margin: 0 0 16px; color: var(--muted); }
1180
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1181
+ .card {
1182
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1183
+ padding: 14px 16px; box-shadow: var(--shadow);
1184
+ }
1185
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1186
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1187
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1188
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1189
+ .collection {
1190
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1191
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1192
+ }
1193
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1194
+ .collection small { display: block; color: var(--faint); }
1195
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1196
+ .chip {
1197
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1198
+ border-radius: 999px; padding: 4px 8px;
1199
+ }
1200
+ .chip i { color: var(--faint); font-style: normal; }
1201
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1202
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1203
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1204
+ tr.clickable { cursor: pointer; }
1205
+ tr.clickable:hover { background: var(--bg-muted); }
1206
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1207
+ pre {
1208
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1209
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1210
+ }
1211
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1212
+ .banner {
1213
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1214
+ background: var(--err-soft); color: var(--err);
1215
+ }
1216
+ .banner.show { display: block; }
1217
+ .empty { color: var(--muted); padding: 24px 8px; }
1218
+ dialog {
1219
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1220
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1221
+ }
1222
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1223
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1224
+ textarea {
1225
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1226
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1227
+ font-family: var(--mono); font-size: 12px;
1228
+ }
1229
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1230
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1231
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1232
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1233
+ .status-2 { color: var(--ok); }
1234
+ .status-4, .status-5, .status-0 { color: var(--err); }
1235
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1236
+ .route {
1237
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1238
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1239
+ }
1240
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1241
+ @media (max-width: 800px) {
1242
+ header.top {
1243
+ align-items: stretch; flex-direction: column;
1244
+ padding-top: max(10px, env(safe-area-inset-top));
1245
+ }
1246
+ input, select, textarea { font-size: 16px; }
1247
+ .controls { width: 100%; }
1248
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1249
+ .layout { grid-template-columns: minmax(0, 1fr); }
1250
+ nav.side {
1251
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1252
+ border-right: 0; border-bottom: 1px solid var(--line);
1253
+ padding: 8px;
1254
+ }
1255
+ nav.side button { white-space: nowrap; flex: none; }
1256
+ .split { grid-template-columns: minmax(0, 1fr); }
1257
+ main { padding: 14px; }
1258
+ table, thead, tbody, tr, th, td { display: block; }
1259
+ thead { display: none; }
1260
+ tr {
1261
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1262
+ background: var(--bg-elev); min-width: 0;
1263
+ }
1264
+ td {
1265
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1266
+ min-width: 0; overflow-wrap: anywhere;
1267
+ }
1268
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1269
+ .route { grid-template-columns: 72px 1fr; }
1270
+ .route button { grid-column: 1 / -1; }
1271
+ }
1272
+ </style>
1273
+ </head>
1274
+ <body>
1275
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1276
+ <header class="top">
1277
+ <div class="brand">
1278
+ <strong>${name}</strong>
1279
+ <span>Mockingbird admin</span>
1280
+ </div>
1281
+ <div class="controls">
1282
+ <label class="field">Namespace
1283
+ <select id="namespace" aria-label="Namespace"></select>
1284
+ </label>
1285
+ <label class="field">Admin key
1286
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1287
+ </label>
1288
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1289
+ <button class="btn" id="refresh" type="button">Refresh</button>
1290
+ </div>
1291
+ </header>
1292
+ <div class="layout">
1293
+ <nav class="side" id="nav" aria-label="Admin sections">
1294
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1295
+ <button type="button" data-view="state">State</button>
1296
+ <button type="button" data-view="clock">Clock</button>
1297
+ <button type="button" data-view="faults">Faults</button>
1298
+ <button type="button" data-view="journal">Journal</button>
1299
+ <button type="button" data-view="routes">Routes</button>
1300
+ </nav>
1301
+ <main id="views">
1302
+ <p class="banner" id="banner" role="alert"></p>
1303
+ <section class="view" id="view-overview">
1304
+ <h2>Overview</h2>
1305
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1306
+ <div class="grid" id="overview-cards"></div>
1307
+ <h3>Recent requests</h3>
1308
+ <div id="overview-requests"></div>
1309
+ </section>
1310
+ <section class="view" id="view-state" hidden>
1311
+ <h2>State</h2>
1312
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1313
+ <div class="split">
1314
+ <div id="collections"></div>
1315
+ <div>
1316
+ <div id="schema"></div>
1317
+ <div class="row-actions">
1318
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1319
+ </div>
1320
+ <div id="records"></div>
1321
+ </div>
1322
+ </div>
1323
+ </section>
1324
+ <section class="view" id="view-clock" hidden>
1325
+ <h2>Clock</h2>
1326
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1327
+ <div class="card" id="clock-readout"></div>
1328
+ <div class="row-actions">
1329
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1330
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1331
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1332
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1333
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1334
+ <button class="btn" id="freeze" type="button">Freeze</button>
1335
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1336
+ </div>
1337
+ <form id="clock-set" class="row-actions">
1338
+ <label class="field">Set instant
1339
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1340
+ </label>
1341
+ <button class="btn-primary" type="submit">Set</button>
1342
+ </form>
1343
+ </section>
1344
+ <section class="view" id="view-faults" hidden>
1345
+ <h2>Faults</h2>
1346
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1347
+ <form id="fault-form" class="card stack">
1348
+ <label class="field">Preset
1349
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1350
+ </label>
1351
+ <label class="field">Status
1352
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1353
+ </label>
1354
+ <label class="field">Path prefix
1355
+ <input id="fault-path" placeholder="/v1">
1356
+ </label>
1357
+ <label class="field">Method
1358
+ <input id="fault-method" placeholder="GET">
1359
+ </label>
1360
+ <div class="dialog-actions">
1361
+ <button class="btn-primary" type="submit">Add fault</button>
1362
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1363
+ </div>
1364
+ </form>
1365
+ <div id="fault-list"></div>
1366
+ </section>
1367
+ <section class="view" id="view-journal" hidden>
1368
+ <h2>Journal</h2>
1369
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1370
+ <div class="row-actions">
1371
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1372
+ </div>
1373
+ <div id="journal"></div>
1374
+ </section>
1375
+ <section class="view" id="view-routes" hidden>
1376
+ <h2>Routes</h2>
1377
+ <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>
1378
+ <div id="route-list"></div>
1379
+ <form id="route-form" class="card stack">
1380
+ <strong id="route-title">Select a route</strong>
1381
+ <label class="field">JSON body
1382
+ <textarea id="route-body" placeholder="{ }"></textarea>
1383
+ </label>
1384
+ <div class="dialog-actions">
1385
+ <button class="btn-primary" type="submit">Send</button>
1386
+ </div>
1387
+ <pre id="route-result">Response will show here.</pre>
1388
+ </form>
1389
+ </section>
1390
+ </main>
1391
+ </div>
1392
+ </div>
1393
+ <dialog id="editor">
1394
+ <form method="dialog" id="editor-form">
1395
+ <strong id="editor-title">Record</strong>
1396
+ <label class="field">Id
1397
+ <input id="editor-id" required>
1398
+ </label>
1399
+ <label class="field">JSON value
1400
+ <textarea id="editor-value"></textarea>
1401
+ </label>
1402
+ <div class="dialog-actions">
1403
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1404
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1405
+ <button class="btn-primary" type="submit" value="save">Save</button>
1406
+ </div>
1407
+ </form>
1408
+ </dialog>
1409
+ <script>
1410
+ (() => {
1411
+ const STANDARD = new Set(${standard})
1412
+ const state = {
1413
+ namespace: "default",
1414
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1415
+ view: "overview",
1416
+ collection: "",
1417
+ shape: null,
1418
+ route: null,
1419
+ editing: null
1420
+ }
1421
+ const $ = (id) => document.getElementById(id)
1422
+ const banner = $("banner")
1423
+ const keyInput = $("admin-key")
1424
+ keyInput.value = state.key
1425
+ const params = new URLSearchParams(location.search)
1426
+ if (params.get("key")) {
1427
+ state.key = params.get("key")
1428
+ keyInput.value = state.key
1429
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1430
+ params.delete("key")
1431
+ const next = params.toString()
1432
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1433
+ }
1434
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1435
+
1436
+ const showError = (error) => {
1437
+ banner.textContent = error instanceof Error ? error.message : String(error)
1438
+ banner.classList.add("show")
1439
+ }
1440
+ const clearError = () => banner.classList.remove("show")
1441
+
1442
+ async function originGet(path) {
1443
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1444
+ if (!response.ok) throw new Error(response.status + " " + path)
1445
+ return response.json()
1446
+ }
1447
+ async function api(method, path, body) {
1448
+ const headers = { accept: "application/json" }
1449
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1450
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1451
+ if (body !== undefined) headers["content-type"] = "application/json"
1452
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1453
+ method,
1454
+ headers,
1455
+ body: body === undefined ? undefined : JSON.stringify(body)
1456
+ })
1457
+ const text = await response.text()
1458
+ let data = null
1459
+ if (text) {
1460
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1461
+ }
1462
+ if (response.status === 401) {
1463
+ keyInput.focus()
1464
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1465
+ }
1466
+ if (!response.ok) {
1467
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1468
+ }
1469
+ return data
1470
+ }
1471
+ const panelApi = {
1472
+ get: (path) => api("GET", path),
1473
+ send: (method, path, body) => api(method, path, body),
1474
+ namespace: () => state.namespace
1475
+ }
1476
+
1477
+ function setTheme(theme) {
1478
+ if (theme) document.documentElement.dataset.theme = theme
1479
+ else delete document.documentElement.dataset.theme
1480
+ }
1481
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1482
+ if (storedTheme) setTheme(storedTheme)
1483
+ $("theme").addEventListener("click", () => {
1484
+ const current = document.documentElement.dataset.theme
1485
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1486
+ const next = dark ? "light" : "dark"
1487
+ localStorage.setItem("mockingbird-admin-theme", next)
1488
+ setTheme(next)
1489
+ })
1490
+
1491
+ function show(view) {
1492
+ state.view = view
1493
+ for (const button of document.querySelectorAll("#nav button")) {
1494
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1495
+ }
1496
+ for (const section of document.querySelectorAll("main .view")) {
1497
+ section.hidden = section.id !== "view-" + view
1498
+ }
1499
+ }
1500
+ document.getElementById("nav").addEventListener("click", (event) => {
1501
+ const button = event.target.closest("button[data-view]")
1502
+ if (!button) return
1503
+ show(button.dataset.view)
1504
+ refresh().catch(showError)
1505
+ })
1506
+
1507
+ function cards(items) {
1508
+ return '<div class="grid">' + items.map((item) =>
1509
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1510
+ ).join("") + "</div>"
1511
+ }
1512
+ function table(columns, rows) {
1513
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1514
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1515
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1516
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1517
+ ).join("") + "</tr>").join("")
1518
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1519
+ }
1520
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1521
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1522
+ }[char]))
1523
+ const preview = (value) => {
1524
+ const text = JSON.stringify(value)
1525
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1526
+ }
1527
+ const when = (epoch) => {
1528
+ const date = new Date(epoch)
1529
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1530
+ }
1531
+ const clockCard = (epoch) => {
1532
+ const date = new Date(epoch)
1533
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1534
+ const iso = date.toISOString()
1535
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1536
+ }
1537
+
1538
+ async function loadNamespaces() {
1539
+ const data = await api("GET", "/namespaces")
1540
+ const select = $("namespace")
1541
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1542
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1543
+ select.innerHTML = names.map((name) =>
1544
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1545
+ ).join("")
1546
+ select.value = state.namespace
1547
+ }
1548
+
1549
+ async function renderOverview() {
1550
+ const [health, shape, clock, journal] = await Promise.all([
1551
+ originGet("/health"),
1552
+ api("GET", "/state"),
1553
+ api("GET", "/clock"),
1554
+ api("GET", "/requests?limit=8")
1555
+ ])
1556
+ state.shape = shape
1557
+ $("overview-cards").innerHTML = cards([
1558
+ { k: "Service", v: esc(health.service || "${name}") },
1559
+ { k: "Status", v: esc(health.status || "ok") },
1560
+ { k: "Namespace", v: esc(state.namespace) },
1561
+ { k: "Collections", v: String(shape.collections.length) },
1562
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1563
+ { k: "Clock", v: clockCard(clock.now) }
1564
+ ])
1565
+ const requests = (journal && journal.requests) || []
1566
+ $("overview-requests").innerHTML = table(
1567
+ [
1568
+ { label: "Method", cell: (row) => esc(row.method) },
1569
+ { label: "Path", cell: (row) => esc(row.path) },
1570
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1571
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1572
+ ],
1573
+ requests
1574
+ )
1575
+ }
1576
+
1577
+ function schemaChips(collection) {
1578
+ if (!collection || collection.fields.length === 0) {
1579
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1580
+ }
1581
+ return '<div class="chips">' + collection.fields.map((field) =>
1582
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1583
+ ).join("") + "</div>"
1584
+ }
1585
+
1586
+ async function renderState() {
1587
+ const shape = await api("GET", "/state")
1588
+ state.shape = shape
1589
+ const host = $("collections")
1590
+ if (shape.collections.length === 0) {
1591
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1592
+ $("schema").innerHTML = ""
1593
+ $("records").innerHTML = ""
1594
+ return
1595
+ }
1596
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1597
+ state.collection = shape.collections[0].name
1598
+ }
1599
+ host.innerHTML = shape.collections.map((item) =>
1600
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1601
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1602
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1603
+ ).join("")
1604
+ const selected = shape.collections.find((item) => item.name === state.collection)
1605
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1606
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1607
+ schemaChips(selected)
1608
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1609
+ const rows = page.records.map((record) => ({
1610
+ ...record,
1611
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1612
+ }))
1613
+ $("records").innerHTML = table(
1614
+ [
1615
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1616
+ { label: "Seq", cell: (row) => esc(row.seq) },
1617
+ { label: "Value", cell: (row) => preview(row.value) }
1618
+ ],
1619
+ rows
1620
+ )
1621
+ }
1622
+
1623
+ async function renderClock() {
1624
+ const clock = await api("GET", "/clock")
1625
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1626
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1627
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1628
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1629
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1630
+ }
1631
+
1632
+ async function renderFaults() {
1633
+ const [faults, presets] = await Promise.all([
1634
+ api("GET", "/faults"),
1635
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1636
+ ])
1637
+ const select = $("fault-preset")
1638
+ const current = select.value
1639
+ const list = presets.presets || []
1640
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1641
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1642
+ ).join("")
1643
+ select.value = current
1644
+ const rules = faults.faults || []
1645
+ $("fault-list").innerHTML = table(
1646
+ [
1647
+ { label: "Id", cell: (row) => esc(row.id) },
1648
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1649
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1650
+ ],
1651
+ rules
1652
+ )
1653
+ }
1654
+
1655
+ async function renderJournal() {
1656
+ const journal = await api("GET", "/requests?limit=100")
1657
+ $("journal").innerHTML = table(
1658
+ [
1659
+ { label: "When", cell: (row) => esc(row.at || "") },
1660
+ { label: "Method", cell: (row) => esc(row.method) },
1661
+ { label: "Path", cell: (row) => esc(row.path) },
1662
+ { label: "Status", cell: (row) => esc(row.status) },
1663
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1664
+ ],
1665
+ journal.requests || []
1666
+ )
1667
+ }
1668
+
1669
+ async function renderRoutes() {
1670
+ const data = await api("GET", "/")
1671
+ const routes = data.routes || []
1672
+ $("route-list").innerHTML = routes.map((route) => {
1673
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1674
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1675
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1676
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1677
+ }).join("")
1678
+ }
1679
+
1680
+ const renderers = {
1681
+ overview: renderOverview,
1682
+ state: renderState,
1683
+ clock: renderClock,
1684
+ faults: renderFaults,
1685
+ journal: renderJournal,
1686
+ routes: renderRoutes
1687
+ }
1688
+
1689
+ async function refresh() {
1690
+ clearError()
1691
+ if (state.view in renderers) await renderers[state.view]()
1692
+ }
1693
+
1694
+ $("namespace").addEventListener("change", () => {
1695
+ state.namespace = $("namespace").value
1696
+ refresh().catch(showError)
1697
+ })
1698
+ keyInput.addEventListener("change", () => {
1699
+ state.key = keyInput.value.trim()
1700
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1701
+ refresh().catch(showError)
1702
+ })
1703
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1704
+
1705
+ $("collections").addEventListener("click", (event) => {
1706
+ const button = event.target.closest("[data-collection]")
1707
+ if (!button) return
1708
+ state.collection = button.dataset.collection
1709
+ renderState().catch(showError)
1710
+ })
1711
+ $("records").addEventListener("click", (event) => {
1712
+ const row = event.target.closest("[data-id]")
1713
+ if (!row) return
1714
+ openEditor(row.dataset.id).catch(showError)
1715
+ })
1716
+
1717
+ const editor = $("editor")
1718
+ async function openEditor(id) {
1719
+ state.editing = id || null
1720
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1721
+ $("editor-id").value = id || ""
1722
+ $("editor-id").readOnly = Boolean(id)
1723
+ $("editor-delete").hidden = !id
1724
+ if (id) {
1725
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1726
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1727
+ } else {
1728
+ $("editor-value").value = "{\\n \\n}"
1729
+ }
1730
+ editor.showModal()
1731
+ }
1732
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1733
+ $("editor-form").addEventListener("submit", (event) => {
1734
+ const submitter = event.submitter
1735
+ if (!submitter || submitter.value !== "save") return
1736
+ event.preventDefault()
1737
+ let value
1738
+ try { value = JSON.parse($("editor-value").value) }
1739
+ catch { showError(new Error("Value is not JSON")); return }
1740
+ const id = $("editor-id").value.trim()
1741
+ const path = "/state/" + encodeURIComponent(state.collection)
1742
+ const request = state.editing
1743
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1744
+ : api("POST", path, { id: id || undefined, value })
1745
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1746
+ })
1747
+ $("editor-delete").addEventListener("click", () => {
1748
+ const id = state.editing
1749
+ if (!id) return
1750
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1751
+ .then(() => { editor.close(); return renderState() })
1752
+ .catch(showError)
1753
+ })
1754
+
1755
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1756
+ button.addEventListener("click", () => {
1757
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1758
+ })
1759
+ })
1760
+ $("freeze").addEventListener("click", () => {
1761
+ const frozen = $("freeze").dataset.frozen === "1"
1762
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1763
+ })
1764
+ $("clock-reset").addEventListener("click", () => {
1765
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1766
+ })
1767
+ $("clock-set").addEventListener("submit", (event) => {
1768
+ event.preventDefault()
1769
+ const raw = $("clock-instant").value.trim()
1770
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1771
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1772
+ })
1773
+
1774
+ $("fault-form").addEventListener("submit", (event) => {
1775
+ event.preventDefault()
1776
+ const preset = $("fault-preset").value
1777
+ const body = preset
1778
+ ? { preset }
1779
+ : {
1780
+ status: Number($("fault-status").value),
1781
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1782
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1783
+ }
1784
+ if (!preset && !Number.isFinite(body.status)) {
1785
+ showError(new Error("Status must be a number, or choose a preset"))
1786
+ return
1787
+ }
1788
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1789
+ })
1790
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1791
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1792
+
1793
+ $("route-list").addEventListener("click", (event) => {
1794
+ const button = event.target.closest("[data-route]")
1795
+ if (!button) return
1796
+ state.route = button.dataset.route
1797
+ $("route-title").textContent = state.route
1798
+ const method = state.route.split(" ")[0]
1799
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1800
+ })
1801
+ $("route-form").addEventListener("submit", async (event) => {
1802
+ event.preventDefault()
1803
+ if (!state.route) return showError(new Error("Choose a route first"))
1804
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1805
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1806
+ let body
1807
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1808
+ try { body = JSON.parse($("route-body").value) }
1809
+ catch { return showError(new Error("Body is not JSON")) }
1810
+ }
1811
+ try {
1812
+ const data = await api(method, concrete, body)
1813
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1814
+ } catch (error) {
1815
+ showError(error)
1816
+ }
1817
+ })
1818
+
1819
+ function mountPanels(panels) {
1820
+ const nav = $("nav")
1821
+ const views = $("views")
1822
+ for (const panel of panels) {
1823
+ const button = document.createElement("button")
1824
+ button.type = "button"
1825
+ button.dataset.view = panel.id
1826
+ button.textContent = panel.title
1827
+ nav.append(button)
1828
+ const section = document.createElement("section")
1829
+ section.className = "view"
1830
+ section.id = "view-" + panel.id
1831
+ section.hidden = true
1832
+ const title = document.createElement("h2")
1833
+ title.textContent = panel.title
1834
+ const lede = document.createElement("p")
1835
+ lede.className = "lede"
1836
+ lede.textContent = panel.description || ""
1837
+ const body = document.createElement("div")
1838
+ body.className = "panel-body"
1839
+ body.id = "panel-" + panel.id
1840
+ body.innerHTML = panel.html || ""
1841
+ section.append(title, lede, body)
1842
+ views.append(section)
1843
+ if (panel.script) {
1844
+ try {
1845
+ const run = new Function("root", "api", panel.script)
1846
+ run(body, panelApi)
1847
+ } catch (error) {
1848
+ const note = document.createElement("p")
1849
+ note.className = "banner show"
1850
+ note.textContent = error instanceof Error ? error.message : String(error)
1851
+ body.append(note)
1852
+ }
1853
+ }
1854
+ }
1855
+ }
1856
+
1857
+ loadNamespaces()
1858
+ .then(() => api("GET", "/ui/manifest"))
1859
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
1860
+ .catch(showError)
1861
+ })()
1862
+ </script>
1863
+ </body>
1864
+ </html>`;
1865
+ };
1866
+ var htmlResponse = (body) => new Response(body, {
1867
+ status: 200,
1868
+ headers: {
1869
+ "content-type": "text/html; charset=utf-8",
1870
+ "cache-control": "no-store"
1871
+ }
1872
+ });
1873
+ var json2 = (body) => new Response(JSON.stringify(body), {
1874
+ status: 200,
1875
+ headers: { "content-type": "application/json; charset=utf-8" }
1876
+ });
1877
+ var adminUiRoutes = (service, ui) => {
1878
+ const shell = () => renderAdminDocument(service);
1879
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
1880
+ return {
1881
+ "GET /ui": () => htmlResponse(document2()),
1882
+ "GET /ui/": () => htmlResponse(document2()),
1883
+ "GET /ui/manifest": () => json2({
1884
+ service,
1885
+ panels: (ui?.panels ?? []).map((panel) => ({
1886
+ id: panel.id,
1887
+ title: panel.title,
1888
+ ...panel.description !== void 0 ? { description: panel.description } : {},
1889
+ html: panel.html,
1890
+ ...panel.script !== void 0 ? { script: panel.script } : {}
1891
+ }))
1892
+ })
1893
+ };
1894
+ };
1895
+
964
1896
  // ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request/constants.js
965
1897
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
966
1898
 
@@ -1428,8 +2360,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1428
2360
  });
1429
2361
  };
1430
2362
 
2363
+ // ../core/dist/state-view.js
2364
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2365
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2366
+ var SAMPLE = 25;
2367
+ var WALK_LIMIT = 1e4;
2368
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2369
+ var fail = (status, message) => ({ ok: false, status, message });
2370
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2371
+ var kindOf = (value) => {
2372
+ if (value === null)
2373
+ return "null";
2374
+ if (Array.isArray(value))
2375
+ return "array";
2376
+ switch (typeof value) {
2377
+ case "string":
2378
+ return "string";
2379
+ case "number":
2380
+ return Number.isFinite(value) ? "number" : "unknown";
2381
+ case "boolean":
2382
+ return "boolean";
2383
+ case "object":
2384
+ return "object";
2385
+ default:
2386
+ return "unknown";
2387
+ }
2388
+ };
2389
+ var humanize = (name) => {
2390
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2391
+ if (words === "")
2392
+ return name;
2393
+ return words.charAt(0).toUpperCase() + words.slice(1);
2394
+ };
2395
+ var jsonValue = (value) => {
2396
+ if (value === void 0)
2397
+ return fail(400, "value is required");
2398
+ try {
2399
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2400
+ } catch {
2401
+ return fail(400, "value must be JSON");
2402
+ }
2403
+ };
2404
+ var ctorName = (value) => {
2405
+ const ctor = value.constructor;
2406
+ return typeof ctor?.name === "string" ? ctor.name : "";
2407
+ };
2408
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2409
+ var discoverCollections = (root) => {
2410
+ const found = [];
2411
+ const seen = /* @__PURE__ */ new Set();
2412
+ const visit = (value, depth) => {
2413
+ if (found.length + seen.size > WALK_LIMIT)
2414
+ return;
2415
+ if (value === null || typeof value !== "object")
2416
+ return;
2417
+ if (seen.has(value))
2418
+ return;
2419
+ seen.add(value);
2420
+ if (value instanceof Collection) {
2421
+ found.push(value);
2422
+ return;
2423
+ }
2424
+ if (value instanceof Map) {
2425
+ for (const child of value.values())
2426
+ visit(child, depth + 1);
2427
+ return;
2428
+ }
2429
+ if (value instanceof Set) {
2430
+ for (const child of value.values())
2431
+ visit(child, depth + 1);
2432
+ return;
2433
+ }
2434
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2435
+ return;
2436
+ if (Array.isArray(value)) {
2437
+ const cap = Math.min(value.length, 32);
2438
+ for (let i = 0; i < cap; i++)
2439
+ visit(value[i], depth + 1);
2440
+ return;
2441
+ }
2442
+ let children;
2443
+ try {
2444
+ children = Object.values(value);
2445
+ } catch {
2446
+ return;
2447
+ }
2448
+ for (const child of children)
2449
+ visit(child, depth + 1);
2450
+ };
2451
+ visit(root, 0);
2452
+ return found;
2453
+ };
2454
+ var storedNames = (sqlite, namespace) => {
2455
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2456
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2457
+ return [...records, ...sequences].map((row) => row.name);
2458
+ };
2459
+ var blankAccum = (name) => ({
2460
+ name,
2461
+ kinds: /* @__PURE__ */ new Set(),
2462
+ present: 0,
2463
+ nested: /* @__PURE__ */ new Map()
2464
+ });
2465
+ var absorb = (accum, value) => {
2466
+ const kind = kindOf(value);
2467
+ accum.kinds.add(kind);
2468
+ accum.present++;
2469
+ if (!isRecord2(value))
2470
+ return;
2471
+ for (const [key, child] of Object.entries(value)) {
2472
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2473
+ absorb(nested, child);
2474
+ accum.nested.set(key, nested);
2475
+ }
2476
+ };
2477
+ var finishField = (accum, samples) => {
2478
+ const kinds = [...accum.kinds];
2479
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2480
+ const field = {
2481
+ name: accum.name,
2482
+ kind,
2483
+ optional: accum.present < samples || kinds.includes("null")
2484
+ };
2485
+ if (accum.nested.size > 0) {
2486
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2487
+ }
2488
+ return field;
2489
+ };
2490
+ var inferFields = (records) => {
2491
+ if (records.length === 0)
2492
+ return [];
2493
+ const sample = records.slice(0, SAMPLE);
2494
+ const objects = sample.filter((record2) => isRecord2(record2.value));
2495
+ if (objects.length === 0) {
2496
+ const kinds = new Set(sample.map((record2) => kindOf(record2.value)));
2497
+ const list = [...kinds];
2498
+ return [
2499
+ {
2500
+ name: "(value)",
2501
+ kind: list.length === 1 ? list[0] : "unknown",
2502
+ optional: false
2503
+ }
2504
+ ];
2505
+ }
2506
+ const root = /* @__PURE__ */ new Map();
2507
+ for (const record2 of objects) {
2508
+ for (const [key, value] of Object.entries(record2.value)) {
2509
+ const accum = root.get(key) ?? blankAccum(key);
2510
+ absorb(accum, value);
2511
+ root.set(key, accum);
2512
+ }
2513
+ }
2514
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2515
+ };
2516
+ var mergeFields = (declared, inferred) => {
2517
+ const byName = /* @__PURE__ */ new Map();
2518
+ for (const field of inferred)
2519
+ byName.set(field.name, field);
2520
+ const ordered = [];
2521
+ const seen = /* @__PURE__ */ new Set();
2522
+ for (const field of declared ?? []) {
2523
+ const found = byName.get(field.name);
2524
+ seen.add(field.name);
2525
+ if (!found) {
2526
+ ordered.push({ ...field, optional: field.optional });
2527
+ continue;
2528
+ }
2529
+ ordered.push({
2530
+ ...found,
2531
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2532
+ optional: field.optional || found.optional,
2533
+ ...field.description !== void 0 ? { description: field.description } : {},
2534
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2535
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2536
+ });
2537
+ }
2538
+ for (const field of inferred) {
2539
+ if (!seen.has(field.name))
2540
+ ordered.push(field);
2541
+ }
2542
+ return ordered;
2543
+ };
2544
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2545
+ var readRecord = (collection, id) => {
2546
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2547
+ const row = rows.find((entry) => entry.id === id);
2548
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2549
+ };
2550
+ var inspectState = (scope) => {
2551
+ const declared = /* @__PURE__ */ new Map();
2552
+ for (const declaration of scope.declarations ?? []) {
2553
+ if (COLLECTION_NAME.test(declaration.name))
2554
+ declared.set(declaration.name, declaration);
2555
+ }
2556
+ const names = new Set(declared.keys());
2557
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2558
+ names.add(name);
2559
+ for (const collection of discoverCollections(scope.root)) {
2560
+ if (collection.namespace === scope.storageNamespace)
2561
+ names.add(collection.collectionName);
2562
+ }
2563
+ const collections = [];
2564
+ for (const name of names) {
2565
+ if (!COLLECTION_NAME.test(name))
2566
+ continue;
2567
+ const declaration = declared.get(name);
2568
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2569
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2570
+ const inferred = inferFields(records);
2571
+ const fields = mergeFields(declaration?.fields, inferred);
2572
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2573
+ collections.push({
2574
+ name,
2575
+ label: declaration?.label ?? humanize(name),
2576
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2577
+ count: collection.count(),
2578
+ source,
2579
+ fields,
2580
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2581
+ });
2582
+ }
2583
+ const order = /* @__PURE__ */ new Map();
2584
+ for (const [index, item] of (scope.declarations ?? []).entries())
2585
+ order.set(item.name, index);
2586
+ collections.sort((a, b) => {
2587
+ const left = order.get(a.name);
2588
+ const right = order.get(b.name);
2589
+ if (left !== void 0 && right !== void 0)
2590
+ return left - right;
2591
+ if (left !== void 0)
2592
+ return -1;
2593
+ if (right !== void 0)
2594
+ return 1;
2595
+ return a.name.localeCompare(b.name);
2596
+ });
2597
+ return {
2598
+ namespace: scope.namespace,
2599
+ storageNamespace: scope.storageNamespace,
2600
+ collections
2601
+ };
2602
+ };
2603
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2604
+ if (!COLLECTION_NAME.test(name))
2605
+ return fail(400, "collection name is not allowed");
2606
+ const limit = query.limit ?? 50;
2607
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2608
+ return fail(400, "limit must be an integer from 1 to 200");
2609
+ }
2610
+ const order = query.order ?? "newest";
2611
+ if (order !== "newest" && order !== "oldest")
2612
+ return fail(400, 'order must be "newest" or "oldest"');
2613
+ const collection = collectionOf(sqlite, storageNamespace, name);
2614
+ const rows = collection.list({ order }).filter((row) => {
2615
+ if (query.after === void 0)
2616
+ return true;
2617
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2618
+ });
2619
+ const slice = rows.slice(0, limit);
2620
+ const last = slice.at(-1);
2621
+ return {
2622
+ ok: true,
2623
+ value: {
2624
+ collection: name,
2625
+ count: collection.count(),
2626
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2627
+ next: rows.length > limit && last ? last.seq : null
2628
+ }
2629
+ };
2630
+ };
2631
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2632
+ var readStateRecord = (scope, name, id) => {
2633
+ if (!COLLECTION_NAME.test(name))
2634
+ return fail(400, "collection name is not allowed");
2635
+ if (!RECORD_ID.test(id))
2636
+ return fail(400, "record id is not allowed");
2637
+ const record2 = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2638
+ return record2 ? { ok: true, value: record2 } : fail(404, `no record ${id} in ${name}`);
2639
+ };
2640
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2641
+ var createStateRecord = (scope, name, input) => {
2642
+ if (!COLLECTION_NAME.test(name))
2643
+ return fail(400, "collection name is not allowed");
2644
+ const parsed = jsonValue(input.value);
2645
+ if (!parsed.ok)
2646
+ return parsed;
2647
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2648
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2649
+ const checked = requireId(id);
2650
+ if (!checked.ok)
2651
+ return checked;
2652
+ if (collection.has(checked.value))
2653
+ return fail(409, `record ${checked.value} already exists`);
2654
+ const stored = collection.insert(checked.value, parsed.value);
2655
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2656
+ };
2657
+ var replaceStateRecord = (scope, name, id, value) => {
2658
+ if (!COLLECTION_NAME.test(name))
2659
+ return fail(400, "collection name is not allowed");
2660
+ const checked = requireId(id);
2661
+ if (!checked.ok)
2662
+ return checked;
2663
+ const parsed = jsonValue(value);
2664
+ if (!parsed.ok)
2665
+ return parsed;
2666
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2667
+ if (!collection.has(checked.value))
2668
+ return fail(404, `no record ${checked.value} in ${name}`);
2669
+ const stored = collection.update(checked.value, parsed.value);
2670
+ if (!stored)
2671
+ return fail(404, `no record ${checked.value} in ${name}`);
2672
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2673
+ };
2674
+ var patchStateRecord = (scope, name, id, value) => {
2675
+ const current = readStateRecord(scope, name, id);
2676
+ if (!current.ok)
2677
+ return current;
2678
+ const parsed = jsonValue(value);
2679
+ if (!parsed.ok)
2680
+ return parsed;
2681
+ const next = isRecord2(current.value.value) && isRecord2(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2682
+ return replaceStateRecord(scope, name, id, next);
2683
+ };
2684
+ var deleteStateRecord = (scope, name, id) => {
2685
+ if (!COLLECTION_NAME.test(name))
2686
+ return fail(400, "collection name is not allowed");
2687
+ const checked = requireId(id);
2688
+ if (!checked.ok)
2689
+ return checked;
2690
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2691
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2692
+ };
2693
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2694
+ status,
2695
+ headers: { "content-type": "application/json; charset=utf-8" }
2696
+ });
2697
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2698
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2699
+ var integerParam = (value) => {
2700
+ if (value === null)
2701
+ return void 0;
2702
+ if (!/^-?\d+$/.test(value))
2703
+ return "bad";
2704
+ return Number(value);
2705
+ };
2706
+ var stateAdminRoutes = (routes) => {
2707
+ const open = (namespace) => {
2708
+ try {
2709
+ return { ok: true, value: routes.open(namespace) };
2710
+ } catch (error2) {
2711
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2712
+ }
2713
+ };
2714
+ const wrote = (namespace) => {
2715
+ routes.afterWrite?.(namespace);
2716
+ };
2717
+ return {
2718
+ "GET /state": ({ namespace }) => {
2719
+ const scope = open(namespace);
2720
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2721
+ },
2722
+ "GET /state/:collection": ({ namespace, params, url }) => {
2723
+ const scope = open(namespace);
2724
+ if (!scope.ok)
2725
+ return fromResult(scope, 200);
2726
+ const limit = integerParam(url.searchParams.get("limit"));
2727
+ const after = integerParam(url.searchParams.get("after"));
2728
+ if (limit === "bad")
2729
+ return adminError2(400, "limit: expected an integer");
2730
+ if (after === "bad")
2731
+ return adminError2(400, "after: expected a sequence number");
2732
+ const order = url.searchParams.get("order");
2733
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2734
+ ...limit !== void 0 ? { limit } : {},
2735
+ ...after !== void 0 ? { after } : {},
2736
+ ...order === "newest" || order === "oldest" ? { order } : {}
2737
+ }), 200);
2738
+ },
2739
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2740
+ const scope = open(namespace);
2741
+ if (!scope.ok)
2742
+ return fromResult(scope, 200);
2743
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2744
+ },
2745
+ "POST /state/:collection": ({ namespace, params, body }) => {
2746
+ const scope = open(namespace);
2747
+ if (!scope.ok)
2748
+ return fromResult(scope, 201);
2749
+ if (!isRecord2(body) || !("value" in body)) {
2750
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2751
+ }
2752
+ const id = body.id;
2753
+ if (id !== void 0 && typeof id !== "string")
2754
+ return adminError2(400, "id must be a string");
2755
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2756
+ ...typeof id === "string" ? { id } : {},
2757
+ value: body.value
2758
+ });
2759
+ if (created.ok)
2760
+ wrote(namespace);
2761
+ return fromResult(created, 201);
2762
+ },
2763
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2764
+ const scope = open(namespace);
2765
+ if (!scope.ok)
2766
+ return fromResult(scope, 200);
2767
+ if (!isRecord2(body) || !("value" in body))
2768
+ return adminError2(400, 'expected {"value": <json>}');
2769
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2770
+ if (replaced.ok)
2771
+ wrote(namespace);
2772
+ return fromResult(replaced, 200);
2773
+ },
2774
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2775
+ const scope = open(namespace);
2776
+ if (!scope.ok)
2777
+ return fromResult(scope, 200);
2778
+ if (!isRecord2(body) || !("value" in body))
2779
+ return adminError2(400, 'expected {"value": <json>}');
2780
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2781
+ if (patched.ok)
2782
+ wrote(namespace);
2783
+ return fromResult(patched, 200);
2784
+ },
2785
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2786
+ const scope = open(namespace);
2787
+ if (!scope.ok)
2788
+ return fromResult(scope, 200);
2789
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2790
+ if (removed.ok)
2791
+ wrote(namespace);
2792
+ return fromResult(removed, 200);
2793
+ }
2794
+ };
2795
+ };
2796
+
1431
2797
  // ../core/dist/version.js
1432
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
2798
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1433
2799
 
1434
2800
  // ../core/dist/signing.js
1435
2801
  var encoder = new TextEncoder();
@@ -1764,11 +3130,11 @@ var createWebhookHub = (options) => {
1764
3130
  };
1765
3131
  return hub;
1766
3132
  };
1767
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1768
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1769
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3133
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3134
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3135
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1770
3136
  var parseEndpoint = (value) => {
1771
- if (!isRecord2(value) || typeof value.url !== "string")
3137
+ if (!isRecord3(value) || typeof value.url !== "string")
1772
3138
  return "each endpoint needs a url";
1773
3139
  try {
1774
3140
  new URL(value.url);
@@ -1785,18 +3151,18 @@ var parseEndpoint = (value) => {
1785
3151
  const events = value.events ?? value.enabledEvents;
1786
3152
  if (Array.isArray(events))
1787
3153
  endpoint.events = events.map(String);
1788
- if (isRecord2(value.tags)) {
3154
+ if (isRecord3(value.tags)) {
1789
3155
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1790
3156
  }
1791
3157
  if (typeof value.account === "string")
1792
3158
  endpoint.tags = { ...endpoint.tags, account: value.account };
1793
- if (isRecord2(value.headers)) {
3159
+ if (isRecord3(value.headers)) {
1794
3160
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1795
3161
  }
1796
3162
  return endpoint;
1797
3163
  };
1798
3164
  var webhookAdminRoutes = (hub) => ({
1799
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3165
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1800
3166
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1801
3167
  const type = url.searchParams.get("type");
1802
3168
  return type === null || d.type === type;
@@ -1804,51 +3170,51 @@ var webhookAdminRoutes = (hub) => ({
1804
3170
  }),
1805
3171
  "GET /webhooks/events": ({ url, namespace }) => {
1806
3172
  const type = url.searchParams.get("type");
1807
- return json2(200, {
3173
+ return json4(200, {
1808
3174
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1809
3175
  });
1810
3176
  },
1811
3177
  "POST /webhooks/:id/replay": async ({ params }) => {
1812
3178
  const replayed = await hub.replay(params.id);
1813
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3179
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1814
3180
  },
1815
3181
  "POST /webhooks/flush": async () => {
1816
3182
  await hub.flush();
1817
- return json2(200, { status: "ok" });
3183
+ return json4(200, { status: "ok" });
1818
3184
  },
1819
3185
  "POST /webhooks/faults": ({ body, namespace }) => {
1820
- if (!isRecord2(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1821
- return adminError2(400, "mode must be duplicate, reorder or drop");
3186
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3187
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1822
3188
  }
1823
3189
  const fault = { mode: body.mode };
1824
3190
  if (typeof body.count === "number")
1825
3191
  fault.count = body.count;
1826
3192
  hub.fault(namespace, fault);
1827
- return json2(201, { namespace, ...fault });
3193
+ return json4(201, { namespace, ...fault });
1828
3194
  },
1829
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3195
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1830
3196
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1831
3197
  ...rest,
1832
3198
  secret: secret ? "(set)" : null
1833
3199
  }))
1834
3200
  }),
1835
3201
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1836
- const list = Array.isArray(body) ? body : isRecord2(body) ? body.endpoints : void 0;
3202
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1837
3203
  if (!Array.isArray(list))
1838
- return adminError2(400, "expected [{url, secret?, events?}]");
3204
+ return adminError3(400, "expected [{url, secret?, events?}]");
1839
3205
  const parsed = [];
1840
3206
  for (const each of list) {
1841
3207
  const endpoint = parseEndpoint(each);
1842
3208
  if (typeof endpoint === "string")
1843
- return adminError2(400, endpoint);
3209
+ return adminError3(400, endpoint);
1844
3210
  parsed.push(endpoint);
1845
3211
  }
1846
3212
  const set = hub.setEndpoints(namespace, parsed);
1847
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3213
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1848
3214
  },
1849
3215
  "DELETE /webhook-endpoints": ({ namespace }) => {
1850
3216
  hub.setEndpoints(namespace, []);
1851
- return json2(200, { status: "ok" });
3217
+ return json4(200, { status: "ok" });
1852
3218
  }
1853
3219
  });
1854
3220
  var parsePayload = (message) => {
@@ -1911,6 +3277,7 @@ var operationMatcher = (document2) => {
1911
3277
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1912
3278
  };
1913
3279
  var createRuntime = (options) => {
3280
+ assertAdminUi(options.adminUi);
1914
3281
  const sqlite = bootSqlite(options.sqlite);
1915
3282
  const clock = options.clock ?? createClock();
1916
3283
  const rng = createRng(options.seed ?? 0);
@@ -2117,6 +3484,19 @@ var createRuntime = (options) => {
2117
3484
  else
2118
3485
  timeline(name);
2119
3486
  };
3487
+ const declarationsFor = (namespace) => {
3488
+ const declared = options.state;
3489
+ if (!declared)
3490
+ return [];
3491
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3492
+ };
3493
+ const stateScope = (namespace) => ({
3494
+ sqlite,
3495
+ namespace,
3496
+ storageNamespace: storageNamespace(namespace),
3497
+ root: instance(namespace),
3498
+ declarations: declarationsFor(namespace)
3499
+ });
2120
3500
  const runtime = {
2121
3501
  name: options.name,
2122
3502
  sqlite,
@@ -2155,6 +3535,7 @@ var createRuntime = (options) => {
2155
3535
  branch,
2156
3536
  checkout,
2157
3537
  timeline,
3538
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2158
3539
  fetch: async (incoming) => {
2159
3540
  let request = incoming;
2160
3541
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2348,11 +3729,20 @@ var createRuntime = (options) => {
2348
3729
  ...credentialRoutes(credentials),
2349
3730
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2350
3731
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2351
- ...options.admin?.(runtime) ?? {}
3732
+ ...options.admin?.(runtime) ?? {},
3733
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3734
+ // beside these; it does not replace `/state` or `/ui`.
3735
+ ...stateAdminRoutes({
3736
+ open: stateScope,
3737
+ afterWrite: (namespace) => {
3738
+ checkpoint(namespace, "main");
3739
+ }
3740
+ }),
3741
+ ...adminUiRoutes(options.name, options.adminUi)
2352
3742
  },
2353
3743
  adminKey: options.adminKey
2354
3744
  });
2355
- return runtime;
3745
+ return defineMock(runtime);
2356
3746
  };
2357
3747
  var mutableResponse = (response) => {
2358
3748
  try {
@@ -2981,4 +4371,4 @@ export {
2981
4371
  LIVEKIT_NAMESPACE,
2982
4372
  LiveKitAPI
2983
4373
  };
2984
- //# sourceMappingURL=chunk-TV3OEFVK.js.map
4374
+ //# sourceMappingURL=chunk-EZZFTKWG.js.map