@crvouga/mockingbird-service-odx 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;
@@ -1095,6 +1097,936 @@ var clearNamespace = (sqlite, namespace) => {
1095
1097
  });
1096
1098
  };
1097
1099
 
1100
+ // ../core/dist/surface.js
1101
+ var defineMock = (runtime) => runtime;
1102
+ var STANDARD_ADMIN_ROUTES = [
1103
+ "GET /",
1104
+ "POST /reset",
1105
+ "GET /namespaces",
1106
+ "GET /clock",
1107
+ "POST /clock",
1108
+ "GET /faults",
1109
+ "POST /faults",
1110
+ "DELETE /faults",
1111
+ "POST /snapshots",
1112
+ "POST /snapshots/:id/restore",
1113
+ "DELETE /snapshots/:id",
1114
+ "GET /timeline",
1115
+ "POST /checkpoints",
1116
+ "POST /branches/:name",
1117
+ "POST /branches/:name/checkout",
1118
+ "GET /requests",
1119
+ "DELETE /requests",
1120
+ "GET /metrics",
1121
+ "DELETE /metrics",
1122
+ "GET /credentials",
1123
+ "PUT /credentials",
1124
+ "DELETE /credentials",
1125
+ "GET /state",
1126
+ "GET /state/:collection",
1127
+ "GET /state/:collection/:id",
1128
+ "POST /state/:collection",
1129
+ "PUT /state/:collection/:id",
1130
+ "PATCH /state/:collection/:id",
1131
+ "DELETE /state/:collection/:id",
1132
+ "GET /ui",
1133
+ "GET /ui/",
1134
+ "GET /ui/manifest"
1135
+ ];
1136
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1137
+ var assertAdminUi = (ui) => {
1138
+ if (!ui?.panels)
1139
+ return;
1140
+ const seen = /* @__PURE__ */ new Set();
1141
+ for (const panel of ui.panels) {
1142
+ if (!PANEL_ID.test(panel.id)) {
1143
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1144
+ }
1145
+ if (seen.has(panel.id))
1146
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1147
+ seen.add(panel.id);
1148
+ if (panel.title.trim() === "")
1149
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1150
+ }
1151
+ };
1152
+
1153
+ // ../core/dist/admin-ui.js
1154
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1155
+ switch (char) {
1156
+ case "&":
1157
+ return "&amp;";
1158
+ case "<":
1159
+ return "&lt;";
1160
+ case ">":
1161
+ return "&gt;";
1162
+ case '"':
1163
+ return "&quot;";
1164
+ default:
1165
+ return "&#39;";
1166
+ }
1167
+ });
1168
+ var renderAdminDocument = (service) => {
1169
+ const name = escapeHtml(service);
1170
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1171
+ return `<!DOCTYPE html>
1172
+ <html lang="en">
1173
+ <head>
1174
+ <meta charset="utf-8">
1175
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1176
+ <meta name="color-scheme" content="light dark">
1177
+ <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">
1178
+ <title>${name} admin</title>
1179
+ <style>
1180
+ :root {
1181
+ color-scheme: light;
1182
+ --bg: #f6f5f2;
1183
+ --bg-elev: #ffffff;
1184
+ --bg-muted: #eeece6;
1185
+ --bg-inset: #f3f1eb;
1186
+ --line: #e2dfd6;
1187
+ --line-strong: #d0ccc1;
1188
+ --ink: #1c1915;
1189
+ --muted: #5e584f;
1190
+ --faint: #8a8378;
1191
+ --accent: #3d4f3a;
1192
+ --accent-ink: #f7f6f2;
1193
+ --accent-soft: #e5ece2;
1194
+ --ok: #1f7a45;
1195
+ --ok-soft: #e5f4eb;
1196
+ --warn: #9a6700;
1197
+ --warn-soft: #fbf3df;
1198
+ --err: #a33b32;
1199
+ --err-soft: #fdecea;
1200
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1201
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1202
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1203
+ --radius: 14px;
1204
+ --header: 60px;
1205
+ --nav: 220px;
1206
+ }
1207
+ :root[data-theme="dark"] {
1208
+ color-scheme: dark;
1209
+ --bg: #141311;
1210
+ --bg-elev: #1e1c19;
1211
+ --bg-muted: #26231f;
1212
+ --bg-inset: #181715;
1213
+ --line: #34302b;
1214
+ --line-strong: #4a453d;
1215
+ --ink: #f4f1ea;
1216
+ --muted: #c4bdb1;
1217
+ --faint: #8f877c;
1218
+ --accent: #c5d5b8;
1219
+ --accent-ink: #1a2118;
1220
+ --accent-soft: #2a3328;
1221
+ --ok: #8fd6a8;
1222
+ --ok-soft: #1a2e22;
1223
+ --warn: #f0cc78;
1224
+ --warn-soft: #332911;
1225
+ --err: #f0a8a2;
1226
+ --err-soft: #3a201e;
1227
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1228
+ }
1229
+ @media (prefers-color-scheme: dark) {
1230
+ :root:not([data-theme="light"]) {
1231
+ color-scheme: dark;
1232
+ --bg: #141311;
1233
+ --bg-elev: #1e1c19;
1234
+ --bg-muted: #26231f;
1235
+ --bg-inset: #181715;
1236
+ --line: #34302b;
1237
+ --line-strong: #4a453d;
1238
+ --ink: #f4f1ea;
1239
+ --muted: #c4bdb1;
1240
+ --faint: #8f877c;
1241
+ --accent: #c5d5b8;
1242
+ --accent-ink: #1a2118;
1243
+ --accent-soft: #2a3328;
1244
+ --ok: #8fd6a8;
1245
+ --ok-soft: #1a2e22;
1246
+ --warn: #f0cc78;
1247
+ --warn-soft: #332911;
1248
+ --err: #f0a8a2;
1249
+ --err-soft: #3a201e;
1250
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1251
+ }
1252
+ }
1253
+ * { box-sizing: border-box; }
1254
+ html, body { margin: 0; height: 100%; }
1255
+ body {
1256
+ font-family: var(--sans);
1257
+ background: var(--bg);
1258
+ color: var(--ink);
1259
+ line-height: 1.45;
1260
+ padding-left: env(safe-area-inset-left);
1261
+ padding-right: env(safe-area-inset-right);
1262
+ -webkit-text-size-adjust: 100%;
1263
+ }
1264
+ button, input, select, textarea { font: inherit; color: inherit; }
1265
+ button { cursor: pointer; }
1266
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1267
+ @media (prefers-reduced-motion: reduce) {
1268
+ * { scroll-behavior: auto !important; transition: none !important; }
1269
+ }
1270
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1271
+ header.top {
1272
+ position: sticky; top: 0; z-index: 5;
1273
+ display: flex; align-items: center; gap: 12px;
1274
+ min-height: var(--header); padding: 10px 16px;
1275
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1276
+ border-bottom: 1px solid var(--line);
1277
+ backdrop-filter: blur(10px);
1278
+ }
1279
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1280
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1281
+ .brand span { color: var(--faint); font-size: 12px; }
1282
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1283
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1284
+ label.field input, label.field select, .controls input[type="password"] {
1285
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1286
+ padding: 7px 8px; min-height: 36px;
1287
+ }
1288
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1289
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1290
+ background: var(--bg-elev);
1291
+ }
1292
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1293
+ .btn-quiet { background: transparent; }
1294
+ .btn-danger { color: var(--err); }
1295
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1296
+ record or the full nav row would widen the page past the viewport. */
1297
+ .layout {
1298
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1299
+ flex: 1; min-height: 0; min-width: 0;
1300
+ }
1301
+ nav.side {
1302
+ border-right: 1px solid var(--line); padding: 12px;
1303
+ display: flex; flex-direction: column; gap: 4px;
1304
+ background: var(--bg-elev);
1305
+ }
1306
+ nav.side button {
1307
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1308
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1309
+ }
1310
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1311
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1312
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1313
+ .lede { margin: 0 0 16px; color: var(--muted); }
1314
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1315
+ .card {
1316
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1317
+ padding: 14px 16px; box-shadow: var(--shadow);
1318
+ }
1319
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1320
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1321
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1322
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1323
+ .collection {
1324
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1325
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1326
+ }
1327
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1328
+ .collection small { display: block; color: var(--faint); }
1329
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1330
+ .chip {
1331
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1332
+ border-radius: 999px; padding: 4px 8px;
1333
+ }
1334
+ .chip i { color: var(--faint); font-style: normal; }
1335
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1336
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1337
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1338
+ tr.clickable { cursor: pointer; }
1339
+ tr.clickable:hover { background: var(--bg-muted); }
1340
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1341
+ pre {
1342
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1343
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1344
+ }
1345
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1346
+ .banner {
1347
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1348
+ background: var(--err-soft); color: var(--err);
1349
+ }
1350
+ .banner.show { display: block; }
1351
+ .empty { color: var(--muted); padding: 24px 8px; }
1352
+ dialog {
1353
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1354
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1355
+ }
1356
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1357
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1358
+ textarea {
1359
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1360
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1361
+ font-family: var(--mono); font-size: 12px;
1362
+ }
1363
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1364
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1365
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1366
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1367
+ .status-2 { color: var(--ok); }
1368
+ .status-4, .status-5, .status-0 { color: var(--err); }
1369
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1370
+ .route {
1371
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1372
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1373
+ }
1374
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1375
+ @media (max-width: 800px) {
1376
+ header.top {
1377
+ align-items: stretch; flex-direction: column;
1378
+ padding-top: max(10px, env(safe-area-inset-top));
1379
+ }
1380
+ input, select, textarea { font-size: 16px; }
1381
+ .controls { width: 100%; }
1382
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1383
+ .layout { grid-template-columns: minmax(0, 1fr); }
1384
+ nav.side {
1385
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1386
+ border-right: 0; border-bottom: 1px solid var(--line);
1387
+ padding: 8px;
1388
+ }
1389
+ nav.side button { white-space: nowrap; flex: none; }
1390
+ .split { grid-template-columns: minmax(0, 1fr); }
1391
+ main { padding: 14px; }
1392
+ table, thead, tbody, tr, th, td { display: block; }
1393
+ thead { display: none; }
1394
+ tr {
1395
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1396
+ background: var(--bg-elev); min-width: 0;
1397
+ }
1398
+ td {
1399
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1400
+ min-width: 0; overflow-wrap: anywhere;
1401
+ }
1402
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1403
+ .route { grid-template-columns: 72px 1fr; }
1404
+ .route button { grid-column: 1 / -1; }
1405
+ }
1406
+ </style>
1407
+ </head>
1408
+ <body>
1409
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1410
+ <header class="top">
1411
+ <div class="brand">
1412
+ <strong>${name}</strong>
1413
+ <span>Mockingbird admin</span>
1414
+ </div>
1415
+ <div class="controls">
1416
+ <label class="field">Namespace
1417
+ <select id="namespace" aria-label="Namespace"></select>
1418
+ </label>
1419
+ <label class="field">Admin key
1420
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1421
+ </label>
1422
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1423
+ <button class="btn" id="refresh" type="button">Refresh</button>
1424
+ </div>
1425
+ </header>
1426
+ <div class="layout">
1427
+ <nav class="side" id="nav" aria-label="Admin sections">
1428
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1429
+ <button type="button" data-view="state">State</button>
1430
+ <button type="button" data-view="clock">Clock</button>
1431
+ <button type="button" data-view="faults">Faults</button>
1432
+ <button type="button" data-view="journal">Journal</button>
1433
+ <button type="button" data-view="routes">Routes</button>
1434
+ </nav>
1435
+ <main id="views">
1436
+ <p class="banner" id="banner" role="alert"></p>
1437
+ <section class="view" id="view-overview">
1438
+ <h2>Overview</h2>
1439
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1440
+ <div class="grid" id="overview-cards"></div>
1441
+ <h3>Recent requests</h3>
1442
+ <div id="overview-requests"></div>
1443
+ </section>
1444
+ <section class="view" id="view-state" hidden>
1445
+ <h2>State</h2>
1446
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1447
+ <div class="split">
1448
+ <div id="collections"></div>
1449
+ <div>
1450
+ <div id="schema"></div>
1451
+ <div class="row-actions">
1452
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1453
+ </div>
1454
+ <div id="records"></div>
1455
+ </div>
1456
+ </div>
1457
+ </section>
1458
+ <section class="view" id="view-clock" hidden>
1459
+ <h2>Clock</h2>
1460
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1461
+ <div class="card" id="clock-readout"></div>
1462
+ <div class="row-actions">
1463
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1464
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1465
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1466
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1467
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1468
+ <button class="btn" id="freeze" type="button">Freeze</button>
1469
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1470
+ </div>
1471
+ <form id="clock-set" class="row-actions">
1472
+ <label class="field">Set instant
1473
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1474
+ </label>
1475
+ <button class="btn-primary" type="submit">Set</button>
1476
+ </form>
1477
+ </section>
1478
+ <section class="view" id="view-faults" hidden>
1479
+ <h2>Faults</h2>
1480
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1481
+ <form id="fault-form" class="card stack">
1482
+ <label class="field">Preset
1483
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1484
+ </label>
1485
+ <label class="field">Status
1486
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1487
+ </label>
1488
+ <label class="field">Path prefix
1489
+ <input id="fault-path" placeholder="/v1">
1490
+ </label>
1491
+ <label class="field">Method
1492
+ <input id="fault-method" placeholder="GET">
1493
+ </label>
1494
+ <div class="dialog-actions">
1495
+ <button class="btn-primary" type="submit">Add fault</button>
1496
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1497
+ </div>
1498
+ </form>
1499
+ <div id="fault-list"></div>
1500
+ </section>
1501
+ <section class="view" id="view-journal" hidden>
1502
+ <h2>Journal</h2>
1503
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1504
+ <div class="row-actions">
1505
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1506
+ </div>
1507
+ <div id="journal"></div>
1508
+ </section>
1509
+ <section class="view" id="view-routes" hidden>
1510
+ <h2>Routes</h2>
1511
+ <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>
1512
+ <div id="route-list"></div>
1513
+ <form id="route-form" class="card stack">
1514
+ <strong id="route-title">Select a route</strong>
1515
+ <label class="field">JSON body
1516
+ <textarea id="route-body" placeholder="{ }"></textarea>
1517
+ </label>
1518
+ <div class="dialog-actions">
1519
+ <button class="btn-primary" type="submit">Send</button>
1520
+ </div>
1521
+ <pre id="route-result">Response will show here.</pre>
1522
+ </form>
1523
+ </section>
1524
+ </main>
1525
+ </div>
1526
+ </div>
1527
+ <dialog id="editor">
1528
+ <form method="dialog" id="editor-form">
1529
+ <strong id="editor-title">Record</strong>
1530
+ <label class="field">Id
1531
+ <input id="editor-id" required>
1532
+ </label>
1533
+ <label class="field">JSON value
1534
+ <textarea id="editor-value"></textarea>
1535
+ </label>
1536
+ <div class="dialog-actions">
1537
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1538
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1539
+ <button class="btn-primary" type="submit" value="save">Save</button>
1540
+ </div>
1541
+ </form>
1542
+ </dialog>
1543
+ <script>
1544
+ (() => {
1545
+ const STANDARD = new Set(${standard})
1546
+ const state = {
1547
+ namespace: "default",
1548
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1549
+ view: "overview",
1550
+ collection: "",
1551
+ shape: null,
1552
+ route: null,
1553
+ editing: null
1554
+ }
1555
+ const $ = (id) => document.getElementById(id)
1556
+ const banner = $("banner")
1557
+ const keyInput = $("admin-key")
1558
+ keyInput.value = state.key
1559
+ const params = new URLSearchParams(location.search)
1560
+ if (params.get("key")) {
1561
+ state.key = params.get("key")
1562
+ keyInput.value = state.key
1563
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1564
+ params.delete("key")
1565
+ const next = params.toString()
1566
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1567
+ }
1568
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1569
+
1570
+ const showError = (error) => {
1571
+ banner.textContent = error instanceof Error ? error.message : String(error)
1572
+ banner.classList.add("show")
1573
+ }
1574
+ const clearError = () => banner.classList.remove("show")
1575
+
1576
+ async function originGet(path) {
1577
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1578
+ if (!response.ok) throw new Error(response.status + " " + path)
1579
+ return response.json()
1580
+ }
1581
+ async function api(method, path, body) {
1582
+ const headers = { accept: "application/json" }
1583
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1584
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1585
+ if (body !== undefined) headers["content-type"] = "application/json"
1586
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1587
+ method,
1588
+ headers,
1589
+ body: body === undefined ? undefined : JSON.stringify(body)
1590
+ })
1591
+ const text = await response.text()
1592
+ let data = null
1593
+ if (text) {
1594
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1595
+ }
1596
+ if (response.status === 401) {
1597
+ keyInput.focus()
1598
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1599
+ }
1600
+ if (!response.ok) {
1601
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1602
+ }
1603
+ return data
1604
+ }
1605
+ const panelApi = {
1606
+ get: (path) => api("GET", path),
1607
+ send: (method, path, body) => api(method, path, body),
1608
+ namespace: () => state.namespace
1609
+ }
1610
+
1611
+ function setTheme(theme) {
1612
+ if (theme) document.documentElement.dataset.theme = theme
1613
+ else delete document.documentElement.dataset.theme
1614
+ }
1615
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1616
+ if (storedTheme) setTheme(storedTheme)
1617
+ $("theme").addEventListener("click", () => {
1618
+ const current = document.documentElement.dataset.theme
1619
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1620
+ const next = dark ? "light" : "dark"
1621
+ localStorage.setItem("mockingbird-admin-theme", next)
1622
+ setTheme(next)
1623
+ })
1624
+
1625
+ function show(view) {
1626
+ state.view = view
1627
+ for (const button of document.querySelectorAll("#nav button")) {
1628
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1629
+ }
1630
+ for (const section of document.querySelectorAll("main .view")) {
1631
+ section.hidden = section.id !== "view-" + view
1632
+ }
1633
+ }
1634
+ document.getElementById("nav").addEventListener("click", (event) => {
1635
+ const button = event.target.closest("button[data-view]")
1636
+ if (!button) return
1637
+ show(button.dataset.view)
1638
+ refresh().catch(showError)
1639
+ })
1640
+
1641
+ function cards(items) {
1642
+ return '<div class="grid">' + items.map((item) =>
1643
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1644
+ ).join("") + "</div>"
1645
+ }
1646
+ function table(columns, rows) {
1647
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1648
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1649
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1650
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1651
+ ).join("") + "</tr>").join("")
1652
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1653
+ }
1654
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1655
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1656
+ }[char]))
1657
+ const preview = (value) => {
1658
+ const text = JSON.stringify(value)
1659
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1660
+ }
1661
+ const when = (epoch) => {
1662
+ const date = new Date(epoch)
1663
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1664
+ }
1665
+ const clockCard = (epoch) => {
1666
+ const date = new Date(epoch)
1667
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1668
+ const iso = date.toISOString()
1669
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1670
+ }
1671
+
1672
+ async function loadNamespaces() {
1673
+ const data = await api("GET", "/namespaces")
1674
+ const select = $("namespace")
1675
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1676
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1677
+ select.innerHTML = names.map((name) =>
1678
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1679
+ ).join("")
1680
+ select.value = state.namespace
1681
+ }
1682
+
1683
+ async function renderOverview() {
1684
+ const [health, shape, clock, journal] = await Promise.all([
1685
+ originGet("/health"),
1686
+ api("GET", "/state"),
1687
+ api("GET", "/clock"),
1688
+ api("GET", "/requests?limit=8")
1689
+ ])
1690
+ state.shape = shape
1691
+ $("overview-cards").innerHTML = cards([
1692
+ { k: "Service", v: esc(health.service || "${name}") },
1693
+ { k: "Status", v: esc(health.status || "ok") },
1694
+ { k: "Namespace", v: esc(state.namespace) },
1695
+ { k: "Collections", v: String(shape.collections.length) },
1696
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1697
+ { k: "Clock", v: clockCard(clock.now) }
1698
+ ])
1699
+ const requests = (journal && journal.requests) || []
1700
+ $("overview-requests").innerHTML = table(
1701
+ [
1702
+ { label: "Method", cell: (row) => esc(row.method) },
1703
+ { label: "Path", cell: (row) => esc(row.path) },
1704
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1705
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1706
+ ],
1707
+ requests
1708
+ )
1709
+ }
1710
+
1711
+ function schemaChips(collection) {
1712
+ if (!collection || collection.fields.length === 0) {
1713
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1714
+ }
1715
+ return '<div class="chips">' + collection.fields.map((field) =>
1716
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1717
+ ).join("") + "</div>"
1718
+ }
1719
+
1720
+ async function renderState() {
1721
+ const shape = await api("GET", "/state")
1722
+ state.shape = shape
1723
+ const host = $("collections")
1724
+ if (shape.collections.length === 0) {
1725
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1726
+ $("schema").innerHTML = ""
1727
+ $("records").innerHTML = ""
1728
+ return
1729
+ }
1730
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1731
+ state.collection = shape.collections[0].name
1732
+ }
1733
+ host.innerHTML = shape.collections.map((item) =>
1734
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1735
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1736
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1737
+ ).join("")
1738
+ const selected = shape.collections.find((item) => item.name === state.collection)
1739
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1740
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1741
+ schemaChips(selected)
1742
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1743
+ const rows = page.records.map((record) => ({
1744
+ ...record,
1745
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1746
+ }))
1747
+ $("records").innerHTML = table(
1748
+ [
1749
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1750
+ { label: "Seq", cell: (row) => esc(row.seq) },
1751
+ { label: "Value", cell: (row) => preview(row.value) }
1752
+ ],
1753
+ rows
1754
+ )
1755
+ }
1756
+
1757
+ async function renderClock() {
1758
+ const clock = await api("GET", "/clock")
1759
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1760
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1761
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1762
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1763
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1764
+ }
1765
+
1766
+ async function renderFaults() {
1767
+ const [faults, presets] = await Promise.all([
1768
+ api("GET", "/faults"),
1769
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1770
+ ])
1771
+ const select = $("fault-preset")
1772
+ const current = select.value
1773
+ const list = presets.presets || []
1774
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1775
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1776
+ ).join("")
1777
+ select.value = current
1778
+ const rules = faults.faults || []
1779
+ $("fault-list").innerHTML = table(
1780
+ [
1781
+ { label: "Id", cell: (row) => esc(row.id) },
1782
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1783
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1784
+ ],
1785
+ rules
1786
+ )
1787
+ }
1788
+
1789
+ async function renderJournal() {
1790
+ const journal = await api("GET", "/requests?limit=100")
1791
+ $("journal").innerHTML = table(
1792
+ [
1793
+ { label: "When", cell: (row) => esc(row.at || "") },
1794
+ { label: "Method", cell: (row) => esc(row.method) },
1795
+ { label: "Path", cell: (row) => esc(row.path) },
1796
+ { label: "Status", cell: (row) => esc(row.status) },
1797
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1798
+ ],
1799
+ journal.requests || []
1800
+ )
1801
+ }
1802
+
1803
+ async function renderRoutes() {
1804
+ const data = await api("GET", "/")
1805
+ const routes = data.routes || []
1806
+ $("route-list").innerHTML = routes.map((route) => {
1807
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1808
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1809
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1810
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1811
+ }).join("")
1812
+ }
1813
+
1814
+ const renderers = {
1815
+ overview: renderOverview,
1816
+ state: renderState,
1817
+ clock: renderClock,
1818
+ faults: renderFaults,
1819
+ journal: renderJournal,
1820
+ routes: renderRoutes
1821
+ }
1822
+
1823
+ async function refresh() {
1824
+ clearError()
1825
+ if (state.view in renderers) await renderers[state.view]()
1826
+ }
1827
+
1828
+ $("namespace").addEventListener("change", () => {
1829
+ state.namespace = $("namespace").value
1830
+ refresh().catch(showError)
1831
+ })
1832
+ keyInput.addEventListener("change", () => {
1833
+ state.key = keyInput.value.trim()
1834
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1835
+ refresh().catch(showError)
1836
+ })
1837
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1838
+
1839
+ $("collections").addEventListener("click", (event) => {
1840
+ const button = event.target.closest("[data-collection]")
1841
+ if (!button) return
1842
+ state.collection = button.dataset.collection
1843
+ renderState().catch(showError)
1844
+ })
1845
+ $("records").addEventListener("click", (event) => {
1846
+ const row = event.target.closest("[data-id]")
1847
+ if (!row) return
1848
+ openEditor(row.dataset.id).catch(showError)
1849
+ })
1850
+
1851
+ const editor = $("editor")
1852
+ async function openEditor(id) {
1853
+ state.editing = id || null
1854
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1855
+ $("editor-id").value = id || ""
1856
+ $("editor-id").readOnly = Boolean(id)
1857
+ $("editor-delete").hidden = !id
1858
+ if (id) {
1859
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1860
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1861
+ } else {
1862
+ $("editor-value").value = "{\\n \\n}"
1863
+ }
1864
+ editor.showModal()
1865
+ }
1866
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1867
+ $("editor-form").addEventListener("submit", (event) => {
1868
+ const submitter = event.submitter
1869
+ if (!submitter || submitter.value !== "save") return
1870
+ event.preventDefault()
1871
+ let value
1872
+ try { value = JSON.parse($("editor-value").value) }
1873
+ catch { showError(new Error("Value is not JSON")); return }
1874
+ const id = $("editor-id").value.trim()
1875
+ const path = "/state/" + encodeURIComponent(state.collection)
1876
+ const request = state.editing
1877
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1878
+ : api("POST", path, { id: id || undefined, value })
1879
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1880
+ })
1881
+ $("editor-delete").addEventListener("click", () => {
1882
+ const id = state.editing
1883
+ if (!id) return
1884
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1885
+ .then(() => { editor.close(); return renderState() })
1886
+ .catch(showError)
1887
+ })
1888
+
1889
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1890
+ button.addEventListener("click", () => {
1891
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1892
+ })
1893
+ })
1894
+ $("freeze").addEventListener("click", () => {
1895
+ const frozen = $("freeze").dataset.frozen === "1"
1896
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1897
+ })
1898
+ $("clock-reset").addEventListener("click", () => {
1899
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1900
+ })
1901
+ $("clock-set").addEventListener("submit", (event) => {
1902
+ event.preventDefault()
1903
+ const raw = $("clock-instant").value.trim()
1904
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1905
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1906
+ })
1907
+
1908
+ $("fault-form").addEventListener("submit", (event) => {
1909
+ event.preventDefault()
1910
+ const preset = $("fault-preset").value
1911
+ const body = preset
1912
+ ? { preset }
1913
+ : {
1914
+ status: Number($("fault-status").value),
1915
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1916
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1917
+ }
1918
+ if (!preset && !Number.isFinite(body.status)) {
1919
+ showError(new Error("Status must be a number, or choose a preset"))
1920
+ return
1921
+ }
1922
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1923
+ })
1924
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1925
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1926
+
1927
+ $("route-list").addEventListener("click", (event) => {
1928
+ const button = event.target.closest("[data-route]")
1929
+ if (!button) return
1930
+ state.route = button.dataset.route
1931
+ $("route-title").textContent = state.route
1932
+ const method = state.route.split(" ")[0]
1933
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1934
+ })
1935
+ $("route-form").addEventListener("submit", async (event) => {
1936
+ event.preventDefault()
1937
+ if (!state.route) return showError(new Error("Choose a route first"))
1938
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1939
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1940
+ let body
1941
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1942
+ try { body = JSON.parse($("route-body").value) }
1943
+ catch { return showError(new Error("Body is not JSON")) }
1944
+ }
1945
+ try {
1946
+ const data = await api(method, concrete, body)
1947
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1948
+ } catch (error) {
1949
+ showError(error)
1950
+ }
1951
+ })
1952
+
1953
+ function mountPanels(panels) {
1954
+ const nav = $("nav")
1955
+ const views = $("views")
1956
+ for (const panel of panels) {
1957
+ const button = document.createElement("button")
1958
+ button.type = "button"
1959
+ button.dataset.view = panel.id
1960
+ button.textContent = panel.title
1961
+ nav.append(button)
1962
+ const section = document.createElement("section")
1963
+ section.className = "view"
1964
+ section.id = "view-" + panel.id
1965
+ section.hidden = true
1966
+ const title = document.createElement("h2")
1967
+ title.textContent = panel.title
1968
+ const lede = document.createElement("p")
1969
+ lede.className = "lede"
1970
+ lede.textContent = panel.description || ""
1971
+ const body = document.createElement("div")
1972
+ body.className = "panel-body"
1973
+ body.id = "panel-" + panel.id
1974
+ body.innerHTML = panel.html || ""
1975
+ section.append(title, lede, body)
1976
+ views.append(section)
1977
+ if (panel.script) {
1978
+ try {
1979
+ const run = new Function("root", "api", panel.script)
1980
+ run(body, panelApi)
1981
+ } catch (error) {
1982
+ const note = document.createElement("p")
1983
+ note.className = "banner show"
1984
+ note.textContent = error instanceof Error ? error.message : String(error)
1985
+ body.append(note)
1986
+ }
1987
+ }
1988
+ }
1989
+ }
1990
+
1991
+ loadNamespaces()
1992
+ .then(() => api("GET", "/ui/manifest"))
1993
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
1994
+ .catch(showError)
1995
+ })()
1996
+ </script>
1997
+ </body>
1998
+ </html>`;
1999
+ };
2000
+ var htmlResponse = (body) => new Response(body, {
2001
+ status: 200,
2002
+ headers: {
2003
+ "content-type": "text/html; charset=utf-8",
2004
+ "cache-control": "no-store"
2005
+ }
2006
+ });
2007
+ var json2 = (body) => new Response(JSON.stringify(body), {
2008
+ status: 200,
2009
+ headers: { "content-type": "application/json; charset=utf-8" }
2010
+ });
2011
+ var adminUiRoutes = (service, ui) => {
2012
+ const shell = () => renderAdminDocument(service);
2013
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2014
+ return {
2015
+ "GET /ui": () => htmlResponse(document2()),
2016
+ "GET /ui/": () => htmlResponse(document2()),
2017
+ "GET /ui/manifest": () => json2({
2018
+ service,
2019
+ panels: (ui?.panels ?? []).map((panel) => ({
2020
+ id: panel.id,
2021
+ title: panel.title,
2022
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2023
+ html: panel.html,
2024
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2025
+ }))
2026
+ })
2027
+ };
2028
+ };
2029
+
1098
2030
  // ../../openapi/metadata/dist/types.js
1099
2031
  var EXTENSION_KEYS = {
1100
2032
  operation: "x-mockingbird",
@@ -1258,8 +2190,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1258
2190
  });
1259
2191
  };
1260
2192
 
2193
+ // ../core/dist/state-view.js
2194
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2195
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2196
+ var SAMPLE = 25;
2197
+ var WALK_LIMIT = 1e4;
2198
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2199
+ var fail = (status, message2) => ({ ok: false, status, message: message2 });
2200
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2201
+ var kindOf = (value) => {
2202
+ if (value === null)
2203
+ return "null";
2204
+ if (Array.isArray(value))
2205
+ return "array";
2206
+ switch (typeof value) {
2207
+ case "string":
2208
+ return "string";
2209
+ case "number":
2210
+ return Number.isFinite(value) ? "number" : "unknown";
2211
+ case "boolean":
2212
+ return "boolean";
2213
+ case "object":
2214
+ return "object";
2215
+ default:
2216
+ return "unknown";
2217
+ }
2218
+ };
2219
+ var humanize = (name) => {
2220
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2221
+ if (words === "")
2222
+ return name;
2223
+ return words.charAt(0).toUpperCase() + words.slice(1);
2224
+ };
2225
+ var jsonValue = (value) => {
2226
+ if (value === void 0)
2227
+ return fail(400, "value is required");
2228
+ try {
2229
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2230
+ } catch {
2231
+ return fail(400, "value must be JSON");
2232
+ }
2233
+ };
2234
+ var ctorName = (value) => {
2235
+ const ctor = value.constructor;
2236
+ return typeof ctor?.name === "string" ? ctor.name : "";
2237
+ };
2238
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2239
+ var discoverCollections = (root) => {
2240
+ const found = [];
2241
+ const seen = /* @__PURE__ */ new Set();
2242
+ const visit = (value, depth) => {
2243
+ if (found.length + seen.size > WALK_LIMIT)
2244
+ return;
2245
+ if (value === null || typeof value !== "object")
2246
+ return;
2247
+ if (seen.has(value))
2248
+ return;
2249
+ seen.add(value);
2250
+ if (value instanceof Collection) {
2251
+ found.push(value);
2252
+ return;
2253
+ }
2254
+ if (value instanceof Map) {
2255
+ for (const child of value.values())
2256
+ visit(child, depth + 1);
2257
+ return;
2258
+ }
2259
+ if (value instanceof Set) {
2260
+ for (const child of value.values())
2261
+ visit(child, depth + 1);
2262
+ return;
2263
+ }
2264
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2265
+ return;
2266
+ if (Array.isArray(value)) {
2267
+ const cap = Math.min(value.length, 32);
2268
+ for (let i = 0; i < cap; i++)
2269
+ visit(value[i], depth + 1);
2270
+ return;
2271
+ }
2272
+ let children;
2273
+ try {
2274
+ children = Object.values(value);
2275
+ } catch {
2276
+ return;
2277
+ }
2278
+ for (const child of children)
2279
+ visit(child, depth + 1);
2280
+ };
2281
+ visit(root, 0);
2282
+ return found;
2283
+ };
2284
+ var storedNames = (sqlite, namespace) => {
2285
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2286
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2287
+ return [...records, ...sequences].map((row) => row.name);
2288
+ };
2289
+ var blankAccum = (name) => ({
2290
+ name,
2291
+ kinds: /* @__PURE__ */ new Set(),
2292
+ present: 0,
2293
+ nested: /* @__PURE__ */ new Map()
2294
+ });
2295
+ var absorb = (accum, value) => {
2296
+ const kind = kindOf(value);
2297
+ accum.kinds.add(kind);
2298
+ accum.present++;
2299
+ if (!isRecord3(value))
2300
+ return;
2301
+ for (const [key, child] of Object.entries(value)) {
2302
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2303
+ absorb(nested, child);
2304
+ accum.nested.set(key, nested);
2305
+ }
2306
+ };
2307
+ var finishField = (accum, samples) => {
2308
+ const kinds = [...accum.kinds];
2309
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2310
+ const field = {
2311
+ name: accum.name,
2312
+ kind,
2313
+ optional: accum.present < samples || kinds.includes("null")
2314
+ };
2315
+ if (accum.nested.size > 0) {
2316
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2317
+ }
2318
+ return field;
2319
+ };
2320
+ var inferFields = (records) => {
2321
+ if (records.length === 0)
2322
+ return [];
2323
+ const sample = records.slice(0, SAMPLE);
2324
+ const objects = sample.filter((record) => isRecord3(record.value));
2325
+ if (objects.length === 0) {
2326
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2327
+ const list = [...kinds];
2328
+ return [
2329
+ {
2330
+ name: "(value)",
2331
+ kind: list.length === 1 ? list[0] : "unknown",
2332
+ optional: false
2333
+ }
2334
+ ];
2335
+ }
2336
+ const root = /* @__PURE__ */ new Map();
2337
+ for (const record of objects) {
2338
+ for (const [key, value] of Object.entries(record.value)) {
2339
+ const accum = root.get(key) ?? blankAccum(key);
2340
+ absorb(accum, value);
2341
+ root.set(key, accum);
2342
+ }
2343
+ }
2344
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2345
+ };
2346
+ var mergeFields = (declared, inferred) => {
2347
+ const byName = /* @__PURE__ */ new Map();
2348
+ for (const field of inferred)
2349
+ byName.set(field.name, field);
2350
+ const ordered = [];
2351
+ const seen = /* @__PURE__ */ new Set();
2352
+ for (const field of declared ?? []) {
2353
+ const found = byName.get(field.name);
2354
+ seen.add(field.name);
2355
+ if (!found) {
2356
+ ordered.push({ ...field, optional: field.optional });
2357
+ continue;
2358
+ }
2359
+ ordered.push({
2360
+ ...found,
2361
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2362
+ optional: field.optional || found.optional,
2363
+ ...field.description !== void 0 ? { description: field.description } : {},
2364
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2365
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2366
+ });
2367
+ }
2368
+ for (const field of inferred) {
2369
+ if (!seen.has(field.name))
2370
+ ordered.push(field);
2371
+ }
2372
+ return ordered;
2373
+ };
2374
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2375
+ var readRecord = (collection, id) => {
2376
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2377
+ const row = rows.find((entry) => entry.id === id);
2378
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2379
+ };
2380
+ var inspectState = (scope) => {
2381
+ const declared = /* @__PURE__ */ new Map();
2382
+ for (const declaration of scope.declarations ?? []) {
2383
+ if (COLLECTION_NAME.test(declaration.name))
2384
+ declared.set(declaration.name, declaration);
2385
+ }
2386
+ const names = new Set(declared.keys());
2387
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2388
+ names.add(name);
2389
+ for (const collection of discoverCollections(scope.root)) {
2390
+ if (collection.namespace === scope.storageNamespace)
2391
+ names.add(collection.collectionName);
2392
+ }
2393
+ const collections = [];
2394
+ for (const name of names) {
2395
+ if (!COLLECTION_NAME.test(name))
2396
+ continue;
2397
+ const declaration = declared.get(name);
2398
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2399
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2400
+ const inferred = inferFields(records);
2401
+ const fields = mergeFields(declaration?.fields, inferred);
2402
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2403
+ collections.push({
2404
+ name,
2405
+ label: declaration?.label ?? humanize(name),
2406
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2407
+ count: collection.count(),
2408
+ source,
2409
+ fields,
2410
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2411
+ });
2412
+ }
2413
+ const order = /* @__PURE__ */ new Map();
2414
+ for (const [index, item] of (scope.declarations ?? []).entries())
2415
+ order.set(item.name, index);
2416
+ collections.sort((a, b) => {
2417
+ const left = order.get(a.name);
2418
+ const right = order.get(b.name);
2419
+ if (left !== void 0 && right !== void 0)
2420
+ return left - right;
2421
+ if (left !== void 0)
2422
+ return -1;
2423
+ if (right !== void 0)
2424
+ return 1;
2425
+ return a.name.localeCompare(b.name);
2426
+ });
2427
+ return {
2428
+ namespace: scope.namespace,
2429
+ storageNamespace: scope.storageNamespace,
2430
+ collections
2431
+ };
2432
+ };
2433
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2434
+ if (!COLLECTION_NAME.test(name))
2435
+ return fail(400, "collection name is not allowed");
2436
+ const limit = query.limit ?? 50;
2437
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2438
+ return fail(400, "limit must be an integer from 1 to 200");
2439
+ }
2440
+ const order = query.order ?? "newest";
2441
+ if (order !== "newest" && order !== "oldest")
2442
+ return fail(400, 'order must be "newest" or "oldest"');
2443
+ const collection = collectionOf(sqlite, storageNamespace, name);
2444
+ const rows = collection.list({ order }).filter((row) => {
2445
+ if (query.after === void 0)
2446
+ return true;
2447
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2448
+ });
2449
+ const slice = rows.slice(0, limit);
2450
+ const last = slice.at(-1);
2451
+ return {
2452
+ ok: true,
2453
+ value: {
2454
+ collection: name,
2455
+ count: collection.count(),
2456
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2457
+ next: rows.length > limit && last ? last.seq : null
2458
+ }
2459
+ };
2460
+ };
2461
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2462
+ var readStateRecord = (scope, name, id) => {
2463
+ if (!COLLECTION_NAME.test(name))
2464
+ return fail(400, "collection name is not allowed");
2465
+ if (!RECORD_ID.test(id))
2466
+ return fail(400, "record id is not allowed");
2467
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2468
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2469
+ };
2470
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2471
+ var createStateRecord = (scope, name, input) => {
2472
+ if (!COLLECTION_NAME.test(name))
2473
+ return fail(400, "collection name is not allowed");
2474
+ const parsed = jsonValue(input.value);
2475
+ if (!parsed.ok)
2476
+ return parsed;
2477
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2478
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2479
+ const checked = requireId(id);
2480
+ if (!checked.ok)
2481
+ return checked;
2482
+ if (collection.has(checked.value))
2483
+ return fail(409, `record ${checked.value} already exists`);
2484
+ const stored = collection.insert(checked.value, parsed.value);
2485
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2486
+ };
2487
+ var replaceStateRecord = (scope, name, id, value) => {
2488
+ if (!COLLECTION_NAME.test(name))
2489
+ return fail(400, "collection name is not allowed");
2490
+ const checked = requireId(id);
2491
+ if (!checked.ok)
2492
+ return checked;
2493
+ const parsed = jsonValue(value);
2494
+ if (!parsed.ok)
2495
+ return parsed;
2496
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2497
+ if (!collection.has(checked.value))
2498
+ return fail(404, `no record ${checked.value} in ${name}`);
2499
+ const stored = collection.update(checked.value, parsed.value);
2500
+ if (!stored)
2501
+ return fail(404, `no record ${checked.value} in ${name}`);
2502
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2503
+ };
2504
+ var patchStateRecord = (scope, name, id, value) => {
2505
+ const current = readStateRecord(scope, name, id);
2506
+ if (!current.ok)
2507
+ return current;
2508
+ const parsed = jsonValue(value);
2509
+ if (!parsed.ok)
2510
+ return parsed;
2511
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2512
+ return replaceStateRecord(scope, name, id, next);
2513
+ };
2514
+ var deleteStateRecord = (scope, name, id) => {
2515
+ if (!COLLECTION_NAME.test(name))
2516
+ return fail(400, "collection name is not allowed");
2517
+ const checked = requireId(id);
2518
+ if (!checked.ok)
2519
+ return checked;
2520
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2521
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2522
+ };
2523
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2524
+ status,
2525
+ headers: { "content-type": "application/json; charset=utf-8" }
2526
+ });
2527
+ var adminError2 = (status, message2) => json3(status, { error: { type: "mockingbird_admin", message: message2 } });
2528
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2529
+ var integerParam = (value) => {
2530
+ if (value === null)
2531
+ return void 0;
2532
+ if (!/^-?\d+$/.test(value))
2533
+ return "bad";
2534
+ return Number(value);
2535
+ };
2536
+ var stateAdminRoutes = (routes) => {
2537
+ const open = (namespace) => {
2538
+ try {
2539
+ return { ok: true, value: routes.open(namespace) };
2540
+ } catch (error) {
2541
+ return fail(400, error instanceof Error ? error.message : String(error));
2542
+ }
2543
+ };
2544
+ const wrote = (namespace) => {
2545
+ routes.afterWrite?.(namespace);
2546
+ };
2547
+ return {
2548
+ "GET /state": ({ namespace }) => {
2549
+ const scope = open(namespace);
2550
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2551
+ },
2552
+ "GET /state/:collection": ({ namespace, params, url }) => {
2553
+ const scope = open(namespace);
2554
+ if (!scope.ok)
2555
+ return fromResult(scope, 200);
2556
+ const limit = integerParam(url.searchParams.get("limit"));
2557
+ const after = integerParam(url.searchParams.get("after"));
2558
+ if (limit === "bad")
2559
+ return adminError2(400, "limit: expected an integer");
2560
+ if (after === "bad")
2561
+ return adminError2(400, "after: expected a sequence number");
2562
+ const order = url.searchParams.get("order");
2563
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2564
+ ...limit !== void 0 ? { limit } : {},
2565
+ ...after !== void 0 ? { after } : {},
2566
+ ...order === "newest" || order === "oldest" ? { order } : {}
2567
+ }), 200);
2568
+ },
2569
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2570
+ const scope = open(namespace);
2571
+ if (!scope.ok)
2572
+ return fromResult(scope, 200);
2573
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2574
+ },
2575
+ "POST /state/:collection": ({ namespace, params, body }) => {
2576
+ const scope = open(namespace);
2577
+ if (!scope.ok)
2578
+ return fromResult(scope, 201);
2579
+ if (!isRecord3(body) || !("value" in body)) {
2580
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2581
+ }
2582
+ const id = body.id;
2583
+ if (id !== void 0 && typeof id !== "string")
2584
+ return adminError2(400, "id must be a string");
2585
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2586
+ ...typeof id === "string" ? { id } : {},
2587
+ value: body.value
2588
+ });
2589
+ if (created.ok)
2590
+ wrote(namespace);
2591
+ return fromResult(created, 201);
2592
+ },
2593
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2594
+ const scope = open(namespace);
2595
+ if (!scope.ok)
2596
+ return fromResult(scope, 200);
2597
+ if (!isRecord3(body) || !("value" in body))
2598
+ return adminError2(400, 'expected {"value": <json>}');
2599
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2600
+ if (replaced.ok)
2601
+ wrote(namespace);
2602
+ return fromResult(replaced, 200);
2603
+ },
2604
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2605
+ const scope = open(namespace);
2606
+ if (!scope.ok)
2607
+ return fromResult(scope, 200);
2608
+ if (!isRecord3(body) || !("value" in body))
2609
+ return adminError2(400, 'expected {"value": <json>}');
2610
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2611
+ if (patched.ok)
2612
+ wrote(namespace);
2613
+ return fromResult(patched, 200);
2614
+ },
2615
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2616
+ const scope = open(namespace);
2617
+ if (!scope.ok)
2618
+ return fromResult(scope, 200);
2619
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2620
+ if (removed.ok)
2621
+ wrote(namespace);
2622
+ return fromResult(removed, 200);
2623
+ }
2624
+ };
2625
+ };
2626
+
1261
2627
  // ../core/dist/version.js
1262
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2628
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1263
2629
 
1264
2630
  // ../core/dist/signing.js
1265
2631
  var encoder = new TextEncoder();
@@ -1594,11 +2960,11 @@ var createWebhookHub = (options) => {
1594
2960
  };
1595
2961
  return hub;
1596
2962
  };
1597
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1598
- var adminError2 = (status, message2) => json2(status, { error: { type: "mockingbird_admin", message: message2 } });
1599
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2963
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2964
+ var adminError3 = (status, message2) => json4(status, { error: { type: "mockingbird_admin", message: message2 } });
2965
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1600
2966
  var parseEndpoint = (value) => {
1601
- if (!isRecord3(value) || typeof value.url !== "string")
2967
+ if (!isRecord4(value) || typeof value.url !== "string")
1602
2968
  return "each endpoint needs a url";
1603
2969
  try {
1604
2970
  new URL(value.url);
@@ -1615,18 +2981,18 @@ var parseEndpoint = (value) => {
1615
2981
  const events = value.events ?? value.enabledEvents;
1616
2982
  if (Array.isArray(events))
1617
2983
  endpoint.events = events.map(String);
1618
- if (isRecord3(value.tags)) {
2984
+ if (isRecord4(value.tags)) {
1619
2985
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1620
2986
  }
1621
2987
  if (typeof value.account === "string")
1622
2988
  endpoint.tags = { ...endpoint.tags, account: value.account };
1623
- if (isRecord3(value.headers)) {
2989
+ if (isRecord4(value.headers)) {
1624
2990
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1625
2991
  }
1626
2992
  return endpoint;
1627
2993
  };
1628
2994
  var webhookAdminRoutes = (hub) => ({
1629
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2995
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1630
2996
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1631
2997
  const type = url.searchParams.get("type");
1632
2998
  return type === null || d.type === type;
@@ -1634,51 +3000,51 @@ var webhookAdminRoutes = (hub) => ({
1634
3000
  }),
1635
3001
  "GET /webhooks/events": ({ url, namespace }) => {
1636
3002
  const type = url.searchParams.get("type");
1637
- return json2(200, {
3003
+ return json4(200, {
1638
3004
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1639
3005
  });
1640
3006
  },
1641
3007
  "POST /webhooks/:id/replay": async ({ params }) => {
1642
3008
  const replayed = await hub.replay(params.id);
1643
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3009
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1644
3010
  },
1645
3011
  "POST /webhooks/flush": async () => {
1646
3012
  await hub.flush();
1647
- return json2(200, { status: "ok" });
3013
+ return json4(200, { status: "ok" });
1648
3014
  },
1649
3015
  "POST /webhooks/faults": ({ body, namespace }) => {
1650
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1651
- return adminError2(400, "mode must be duplicate, reorder or drop");
3016
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3017
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1652
3018
  }
1653
3019
  const fault = { mode: body.mode };
1654
3020
  if (typeof body.count === "number")
1655
3021
  fault.count = body.count;
1656
3022
  hub.fault(namespace, fault);
1657
- return json2(201, { namespace, ...fault });
3023
+ return json4(201, { namespace, ...fault });
1658
3024
  },
1659
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3025
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1660
3026
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1661
3027
  ...rest,
1662
3028
  secret: secret ? "(set)" : null
1663
3029
  }))
1664
3030
  }),
1665
3031
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1666
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3032
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1667
3033
  if (!Array.isArray(list))
1668
- return adminError2(400, "expected [{url, secret?, events?}]");
3034
+ return adminError3(400, "expected [{url, secret?, events?}]");
1669
3035
  const parsed = [];
1670
3036
  for (const each of list) {
1671
3037
  const endpoint = parseEndpoint(each);
1672
3038
  if (typeof endpoint === "string")
1673
- return adminError2(400, endpoint);
3039
+ return adminError3(400, endpoint);
1674
3040
  parsed.push(endpoint);
1675
3041
  }
1676
3042
  const set = hub.setEndpoints(namespace, parsed);
1677
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3043
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1678
3044
  },
1679
3045
  "DELETE /webhook-endpoints": ({ namespace }) => {
1680
3046
  hub.setEndpoints(namespace, []);
1681
- return json2(200, { status: "ok" });
3047
+ return json4(200, { status: "ok" });
1682
3048
  }
1683
3049
  });
1684
3050
  var parsePayload = (message2) => {
@@ -1743,6 +3109,7 @@ var operationMatcher = (document2) => {
1743
3109
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1744
3110
  };
1745
3111
  var createRuntime = (options) => {
3112
+ assertAdminUi(options.adminUi);
1746
3113
  const sqlite = bootSqlite(options.sqlite);
1747
3114
  const clock = options.clock ?? createClock();
1748
3115
  const rng = createRng(options.seed ?? 0);
@@ -1949,6 +3316,19 @@ var createRuntime = (options) => {
1949
3316
  else
1950
3317
  timeline(name);
1951
3318
  };
3319
+ const declarationsFor = (namespace) => {
3320
+ const declared = options.state;
3321
+ if (!declared)
3322
+ return [];
3323
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3324
+ };
3325
+ const stateScope = (namespace) => ({
3326
+ sqlite,
3327
+ namespace,
3328
+ storageNamespace: storageNamespace(namespace),
3329
+ root: instance(namespace),
3330
+ declarations: declarationsFor(namespace)
3331
+ });
1952
3332
  const runtime = {
1953
3333
  name: options.name,
1954
3334
  sqlite,
@@ -1987,6 +3367,7 @@ var createRuntime = (options) => {
1987
3367
  branch,
1988
3368
  checkout,
1989
3369
  timeline,
3370
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1990
3371
  fetch: async (incoming) => {
1991
3372
  let request = incoming;
1992
3373
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2180,11 +3561,20 @@ var createRuntime = (options) => {
2180
3561
  ...credentialRoutes(credentials),
2181
3562
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2182
3563
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2183
- ...options.admin?.(runtime) ?? {}
3564
+ ...options.admin?.(runtime) ?? {},
3565
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3566
+ // beside these; it does not replace `/state` or `/ui`.
3567
+ ...stateAdminRoutes({
3568
+ open: stateScope,
3569
+ afterWrite: (namespace) => {
3570
+ checkpoint(namespace, "main");
3571
+ }
3572
+ }),
3573
+ ...adminUiRoutes(options.name, options.adminUi)
2184
3574
  },
2185
3575
  adminKey: options.adminKey
2186
3576
  });
2187
- return runtime;
3577
+ return defineMock(runtime);
2188
3578
  };
2189
3579
  var mutableResponse = (response) => {
2190
3580
  try {
@@ -2762,41 +4152,41 @@ var ODX_PRESETS = {
2762
4152
  webhook: { mode: "drop" }
2763
4153
  }
2764
4154
  };
2765
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2766
- var adminError3 = (status, message2) => json3(status, { error: { type: "mockingbird_admin", message: message2 } });
2767
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4155
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4156
+ var adminError4 = (status, message2) => json5(status, { error: { type: "mockingbird_admin", message: message2 } });
4157
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2768
4158
  var EVENTS = ["Created", "Updated", "Deleted"];
2769
4159
  var SIGNATURES = ["valid", "short", "bad"];
2770
4160
  var adminRoutes = (runtime) => ({
2771
- "GET /patients": ({ namespace }) => json3(200, { patients: runtime.instance(namespace).patients() }),
2772
- "GET /tests": ({ namespace }) => json3(200, {
4161
+ "GET /patients": ({ namespace }) => json5(200, { patients: runtime.instance(namespace).patients() }),
4162
+ "GET /tests": ({ namespace }) => json5(200, {
2773
4163
  // Results are the mock's own output; no HL7 (PHI) is ever stored.
2774
4164
  tests: runtime.instance(namespace).tests()
2775
4165
  }),
2776
4166
  "POST /tests/:id/webhook": ({ params, body, namespace }) => {
2777
- const input = isRecord4(body) ? body : {};
4167
+ const input = isRecord5(body) ? body : {};
2778
4168
  const eventType = String(input.eventType ?? "Updated");
2779
4169
  const signature = String(input.signature ?? "valid");
2780
4170
  if (!EVENTS.includes(eventType))
2781
- return adminError3(400, "eventType must be Created, Updated or Deleted");
4171
+ return adminError4(400, "eventType must be Created, Updated or Deleted");
2782
4172
  if (!SIGNATURES.includes(signature))
2783
- return adminError3(400, "signature must be valid, short or bad");
4173
+ return adminError4(400, "signature must be valid, short or bad");
2784
4174
  const event = runtime.instance(namespace).emit(params.id, eventType, signature);
2785
- return event ? json3(202, event) : adminError3(404, `no patient test ${params.id}`);
4175
+ return event ? json5(202, event) : adminError4(404, `no patient test ${params.id}`);
2786
4176
  },
2787
4177
  "DELETE /tests/:id": ({ params, namespace }) => {
2788
4178
  const event = runtime.instance(namespace).emit(params.id, "Deleted");
2789
- return event ? json3(200, event) : adminError3(404, `no patient test ${params.id}`);
4179
+ return event ? json5(200, event) : adminError4(404, `no patient test ${params.id}`);
2790
4180
  },
2791
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
4181
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
2792
4182
  "PUT /settings": ({ body, namespace }) => {
2793
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
4183
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2794
4184
  const patch = {};
2795
4185
  if (body.apiKeys !== void 0) {
2796
- if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
4186
+ if (!Array.isArray(body.apiKeys)) return adminError4(400, "apiKeys: string[]");
2797
4187
  patch.apiKeys = body.apiKeys.map(String);
2798
4188
  }
2799
- return json3(200, runtime.instance(namespace).state.update(patch));
4189
+ return json5(200, runtime.instance(namespace).state.update(patch));
2800
4190
  }
2801
4191
  });
2802
4192
  var createRuntime2 = (options = {}) => {
@@ -2875,9 +4265,9 @@ var problem = (errors) => jsonRes(400, {
2875
4265
  status: 400,
2876
4266
  errors
2877
4267
  });
2878
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4268
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2879
4269
  var text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : null;
2880
- var jsonBody = (context) => context.body.kind === "json" && isRecord5(context.body.value) ? context.body.value : void 0;
4270
+ var jsonBody = (context) => context.body.kind === "json" && isRecord6(context.body.value) ? context.body.value : void 0;
2881
4271
  var dotnetDate = (value) => {
2882
4272
  const raw = text(value);
2883
4273
  if (!raw) return null;
@@ -3106,7 +4496,7 @@ var OdxAPI = class {
3106
4496
  const results = [];
3107
4497
  const importLogs = [];
3108
4498
  for (const raw of body.results) {
3109
- const item = isRecord5(raw) ? raw : {};
4499
+ const item = isRecord6(raw) ? raw : {};
3110
4500
  const element = ELEMENTS.find((e) => e.elementId === item.elementId);
3111
4501
  if (!element || typeof item.value !== "number") {
3112
4502
  importLogs.push({
@@ -3217,7 +4607,7 @@ var OdxAPI = class {
3217
4607
  if (id !== void 0 && !existing) return message(404, "Webhook not found.");
3218
4608
  const body = jsonBody(context);
3219
4609
  const url = text(body?.webhookUrl);
3220
- const events = isRecord5(body?.entityEvents) ? body.entityEvents.PatientTest : void 0;
4610
+ const events = isRecord6(body?.entityEvents) ? body.entityEvents.PatientTest : void 0;
3221
4611
  const errors = {};
3222
4612
  let valid = false;
3223
4613
  try {
@@ -3268,4 +4658,4 @@ export {
3268
4658
  apiKeyCredential,
3269
4659
  OdxAPI
3270
4660
  };
3271
- //# sourceMappingURL=chunk-ALB2VJMU.js.map
4661
+ //# sourceMappingURL=chunk-RVGTBCUV.js.map