@crvouga/mockingbird-service-formbricks 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;
@@ -1136,6 +1138,936 @@ var clearNamespace = (sqlite, namespace) => {
1136
1138
  });
1137
1139
  };
1138
1140
 
1141
+ // ../core/dist/surface.js
1142
+ var defineMock = (runtime) => runtime;
1143
+ var STANDARD_ADMIN_ROUTES = [
1144
+ "GET /",
1145
+ "POST /reset",
1146
+ "GET /namespaces",
1147
+ "GET /clock",
1148
+ "POST /clock",
1149
+ "GET /faults",
1150
+ "POST /faults",
1151
+ "DELETE /faults",
1152
+ "POST /snapshots",
1153
+ "POST /snapshots/:id/restore",
1154
+ "DELETE /snapshots/:id",
1155
+ "GET /timeline",
1156
+ "POST /checkpoints",
1157
+ "POST /branches/:name",
1158
+ "POST /branches/:name/checkout",
1159
+ "GET /requests",
1160
+ "DELETE /requests",
1161
+ "GET /metrics",
1162
+ "DELETE /metrics",
1163
+ "GET /credentials",
1164
+ "PUT /credentials",
1165
+ "DELETE /credentials",
1166
+ "GET /state",
1167
+ "GET /state/:collection",
1168
+ "GET /state/:collection/:id",
1169
+ "POST /state/:collection",
1170
+ "PUT /state/:collection/:id",
1171
+ "PATCH /state/:collection/:id",
1172
+ "DELETE /state/:collection/:id",
1173
+ "GET /ui",
1174
+ "GET /ui/",
1175
+ "GET /ui/manifest"
1176
+ ];
1177
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1178
+ var assertAdminUi = (ui) => {
1179
+ if (!ui?.panels)
1180
+ return;
1181
+ const seen = /* @__PURE__ */ new Set();
1182
+ for (const panel of ui.panels) {
1183
+ if (!PANEL_ID.test(panel.id)) {
1184
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1185
+ }
1186
+ if (seen.has(panel.id))
1187
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1188
+ seen.add(panel.id);
1189
+ if (panel.title.trim() === "")
1190
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1191
+ }
1192
+ };
1193
+
1194
+ // ../core/dist/admin-ui.js
1195
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1196
+ switch (char) {
1197
+ case "&":
1198
+ return "&amp;";
1199
+ case "<":
1200
+ return "&lt;";
1201
+ case ">":
1202
+ return "&gt;";
1203
+ case '"':
1204
+ return "&quot;";
1205
+ default:
1206
+ return "&#39;";
1207
+ }
1208
+ });
1209
+ var renderAdminDocument = (service) => {
1210
+ const name = escapeHtml(service);
1211
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1212
+ return `<!DOCTYPE html>
1213
+ <html lang="en">
1214
+ <head>
1215
+ <meta charset="utf-8">
1216
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1217
+ <meta name="color-scheme" content="light dark">
1218
+ <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">
1219
+ <title>${name} admin</title>
1220
+ <style>
1221
+ :root {
1222
+ color-scheme: light;
1223
+ --bg: #f6f5f2;
1224
+ --bg-elev: #ffffff;
1225
+ --bg-muted: #eeece6;
1226
+ --bg-inset: #f3f1eb;
1227
+ --line: #e2dfd6;
1228
+ --line-strong: #d0ccc1;
1229
+ --ink: #1c1915;
1230
+ --muted: #5e584f;
1231
+ --faint: #8a8378;
1232
+ --accent: #3d4f3a;
1233
+ --accent-ink: #f7f6f2;
1234
+ --accent-soft: #e5ece2;
1235
+ --ok: #1f7a45;
1236
+ --ok-soft: #e5f4eb;
1237
+ --warn: #9a6700;
1238
+ --warn-soft: #fbf3df;
1239
+ --err: #a33b32;
1240
+ --err-soft: #fdecea;
1241
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1242
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1243
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1244
+ --radius: 14px;
1245
+ --header: 60px;
1246
+ --nav: 220px;
1247
+ }
1248
+ :root[data-theme="dark"] {
1249
+ color-scheme: dark;
1250
+ --bg: #141311;
1251
+ --bg-elev: #1e1c19;
1252
+ --bg-muted: #26231f;
1253
+ --bg-inset: #181715;
1254
+ --line: #34302b;
1255
+ --line-strong: #4a453d;
1256
+ --ink: #f4f1ea;
1257
+ --muted: #c4bdb1;
1258
+ --faint: #8f877c;
1259
+ --accent: #c5d5b8;
1260
+ --accent-ink: #1a2118;
1261
+ --accent-soft: #2a3328;
1262
+ --ok: #8fd6a8;
1263
+ --ok-soft: #1a2e22;
1264
+ --warn: #f0cc78;
1265
+ --warn-soft: #332911;
1266
+ --err: #f0a8a2;
1267
+ --err-soft: #3a201e;
1268
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1269
+ }
1270
+ @media (prefers-color-scheme: dark) {
1271
+ :root:not([data-theme="light"]) {
1272
+ color-scheme: dark;
1273
+ --bg: #141311;
1274
+ --bg-elev: #1e1c19;
1275
+ --bg-muted: #26231f;
1276
+ --bg-inset: #181715;
1277
+ --line: #34302b;
1278
+ --line-strong: #4a453d;
1279
+ --ink: #f4f1ea;
1280
+ --muted: #c4bdb1;
1281
+ --faint: #8f877c;
1282
+ --accent: #c5d5b8;
1283
+ --accent-ink: #1a2118;
1284
+ --accent-soft: #2a3328;
1285
+ --ok: #8fd6a8;
1286
+ --ok-soft: #1a2e22;
1287
+ --warn: #f0cc78;
1288
+ --warn-soft: #332911;
1289
+ --err: #f0a8a2;
1290
+ --err-soft: #3a201e;
1291
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1292
+ }
1293
+ }
1294
+ * { box-sizing: border-box; }
1295
+ html, body { margin: 0; height: 100%; }
1296
+ body {
1297
+ font-family: var(--sans);
1298
+ background: var(--bg);
1299
+ color: var(--ink);
1300
+ line-height: 1.45;
1301
+ padding-left: env(safe-area-inset-left);
1302
+ padding-right: env(safe-area-inset-right);
1303
+ -webkit-text-size-adjust: 100%;
1304
+ }
1305
+ button, input, select, textarea { font: inherit; color: inherit; }
1306
+ button { cursor: pointer; }
1307
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1308
+ @media (prefers-reduced-motion: reduce) {
1309
+ * { scroll-behavior: auto !important; transition: none !important; }
1310
+ }
1311
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1312
+ header.top {
1313
+ position: sticky; top: 0; z-index: 5;
1314
+ display: flex; align-items: center; gap: 12px;
1315
+ min-height: var(--header); padding: 10px 16px;
1316
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1317
+ border-bottom: 1px solid var(--line);
1318
+ backdrop-filter: blur(10px);
1319
+ }
1320
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1321
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1322
+ .brand span { color: var(--faint); font-size: 12px; }
1323
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1324
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1325
+ label.field input, label.field select, .controls input[type="password"] {
1326
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1327
+ padding: 7px 8px; min-height: 36px;
1328
+ }
1329
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1330
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1331
+ background: var(--bg-elev);
1332
+ }
1333
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1334
+ .btn-quiet { background: transparent; }
1335
+ .btn-danger { color: var(--err); }
1336
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1337
+ record or the full nav row would widen the page past the viewport. */
1338
+ .layout {
1339
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1340
+ flex: 1; min-height: 0; min-width: 0;
1341
+ }
1342
+ nav.side {
1343
+ border-right: 1px solid var(--line); padding: 12px;
1344
+ display: flex; flex-direction: column; gap: 4px;
1345
+ background: var(--bg-elev);
1346
+ }
1347
+ nav.side button {
1348
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1349
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1350
+ }
1351
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1352
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1353
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1354
+ .lede { margin: 0 0 16px; color: var(--muted); }
1355
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1356
+ .card {
1357
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1358
+ padding: 14px 16px; box-shadow: var(--shadow);
1359
+ }
1360
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1361
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1362
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1363
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1364
+ .collection {
1365
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1366
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1367
+ }
1368
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1369
+ .collection small { display: block; color: var(--faint); }
1370
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1371
+ .chip {
1372
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1373
+ border-radius: 999px; padding: 4px 8px;
1374
+ }
1375
+ .chip i { color: var(--faint); font-style: normal; }
1376
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1377
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1378
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1379
+ tr.clickable { cursor: pointer; }
1380
+ tr.clickable:hover { background: var(--bg-muted); }
1381
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1382
+ pre {
1383
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1384
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1385
+ }
1386
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1387
+ .banner {
1388
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1389
+ background: var(--err-soft); color: var(--err);
1390
+ }
1391
+ .banner.show { display: block; }
1392
+ .empty { color: var(--muted); padding: 24px 8px; }
1393
+ dialog {
1394
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1395
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1396
+ }
1397
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1398
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1399
+ textarea {
1400
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1401
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1402
+ font-family: var(--mono); font-size: 12px;
1403
+ }
1404
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1405
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1406
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1407
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1408
+ .status-2 { color: var(--ok); }
1409
+ .status-4, .status-5, .status-0 { color: var(--err); }
1410
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1411
+ .route {
1412
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1413
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1414
+ }
1415
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1416
+ @media (max-width: 800px) {
1417
+ header.top {
1418
+ align-items: stretch; flex-direction: column;
1419
+ padding-top: max(10px, env(safe-area-inset-top));
1420
+ }
1421
+ input, select, textarea { font-size: 16px; }
1422
+ .controls { width: 100%; }
1423
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1424
+ .layout { grid-template-columns: minmax(0, 1fr); }
1425
+ nav.side {
1426
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1427
+ border-right: 0; border-bottom: 1px solid var(--line);
1428
+ padding: 8px;
1429
+ }
1430
+ nav.side button { white-space: nowrap; flex: none; }
1431
+ .split { grid-template-columns: minmax(0, 1fr); }
1432
+ main { padding: 14px; }
1433
+ table, thead, tbody, tr, th, td { display: block; }
1434
+ thead { display: none; }
1435
+ tr {
1436
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1437
+ background: var(--bg-elev); min-width: 0;
1438
+ }
1439
+ td {
1440
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1441
+ min-width: 0; overflow-wrap: anywhere;
1442
+ }
1443
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1444
+ .route { grid-template-columns: 72px 1fr; }
1445
+ .route button { grid-column: 1 / -1; }
1446
+ }
1447
+ </style>
1448
+ </head>
1449
+ <body>
1450
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1451
+ <header class="top">
1452
+ <div class="brand">
1453
+ <strong>${name}</strong>
1454
+ <span>Mockingbird admin</span>
1455
+ </div>
1456
+ <div class="controls">
1457
+ <label class="field">Namespace
1458
+ <select id="namespace" aria-label="Namespace"></select>
1459
+ </label>
1460
+ <label class="field">Admin key
1461
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1462
+ </label>
1463
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1464
+ <button class="btn" id="refresh" type="button">Refresh</button>
1465
+ </div>
1466
+ </header>
1467
+ <div class="layout">
1468
+ <nav class="side" id="nav" aria-label="Admin sections">
1469
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1470
+ <button type="button" data-view="state">State</button>
1471
+ <button type="button" data-view="clock">Clock</button>
1472
+ <button type="button" data-view="faults">Faults</button>
1473
+ <button type="button" data-view="journal">Journal</button>
1474
+ <button type="button" data-view="routes">Routes</button>
1475
+ </nav>
1476
+ <main id="views">
1477
+ <p class="banner" id="banner" role="alert"></p>
1478
+ <section class="view" id="view-overview">
1479
+ <h2>Overview</h2>
1480
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1481
+ <div class="grid" id="overview-cards"></div>
1482
+ <h3>Recent requests</h3>
1483
+ <div id="overview-requests"></div>
1484
+ </section>
1485
+ <section class="view" id="view-state" hidden>
1486
+ <h2>State</h2>
1487
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1488
+ <div class="split">
1489
+ <div id="collections"></div>
1490
+ <div>
1491
+ <div id="schema"></div>
1492
+ <div class="row-actions">
1493
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1494
+ </div>
1495
+ <div id="records"></div>
1496
+ </div>
1497
+ </div>
1498
+ </section>
1499
+ <section class="view" id="view-clock" hidden>
1500
+ <h2>Clock</h2>
1501
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1502
+ <div class="card" id="clock-readout"></div>
1503
+ <div class="row-actions">
1504
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1505
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1506
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1507
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1508
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1509
+ <button class="btn" id="freeze" type="button">Freeze</button>
1510
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1511
+ </div>
1512
+ <form id="clock-set" class="row-actions">
1513
+ <label class="field">Set instant
1514
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1515
+ </label>
1516
+ <button class="btn-primary" type="submit">Set</button>
1517
+ </form>
1518
+ </section>
1519
+ <section class="view" id="view-faults" hidden>
1520
+ <h2>Faults</h2>
1521
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1522
+ <form id="fault-form" class="card stack">
1523
+ <label class="field">Preset
1524
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1525
+ </label>
1526
+ <label class="field">Status
1527
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1528
+ </label>
1529
+ <label class="field">Path prefix
1530
+ <input id="fault-path" placeholder="/v1">
1531
+ </label>
1532
+ <label class="field">Method
1533
+ <input id="fault-method" placeholder="GET">
1534
+ </label>
1535
+ <div class="dialog-actions">
1536
+ <button class="btn-primary" type="submit">Add fault</button>
1537
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1538
+ </div>
1539
+ </form>
1540
+ <div id="fault-list"></div>
1541
+ </section>
1542
+ <section class="view" id="view-journal" hidden>
1543
+ <h2>Journal</h2>
1544
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1545
+ <div class="row-actions">
1546
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1547
+ </div>
1548
+ <div id="journal"></div>
1549
+ </section>
1550
+ <section class="view" id="view-routes" hidden>
1551
+ <h2>Routes</h2>
1552
+ <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>
1553
+ <div id="route-list"></div>
1554
+ <form id="route-form" class="card stack">
1555
+ <strong id="route-title">Select a route</strong>
1556
+ <label class="field">JSON body
1557
+ <textarea id="route-body" placeholder="{ }"></textarea>
1558
+ </label>
1559
+ <div class="dialog-actions">
1560
+ <button class="btn-primary" type="submit">Send</button>
1561
+ </div>
1562
+ <pre id="route-result">Response will show here.</pre>
1563
+ </form>
1564
+ </section>
1565
+ </main>
1566
+ </div>
1567
+ </div>
1568
+ <dialog id="editor">
1569
+ <form method="dialog" id="editor-form">
1570
+ <strong id="editor-title">Record</strong>
1571
+ <label class="field">Id
1572
+ <input id="editor-id" required>
1573
+ </label>
1574
+ <label class="field">JSON value
1575
+ <textarea id="editor-value"></textarea>
1576
+ </label>
1577
+ <div class="dialog-actions">
1578
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1579
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1580
+ <button class="btn-primary" type="submit" value="save">Save</button>
1581
+ </div>
1582
+ </form>
1583
+ </dialog>
1584
+ <script>
1585
+ (() => {
1586
+ const STANDARD = new Set(${standard})
1587
+ const state = {
1588
+ namespace: "default",
1589
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1590
+ view: "overview",
1591
+ collection: "",
1592
+ shape: null,
1593
+ route: null,
1594
+ editing: null
1595
+ }
1596
+ const $ = (id) => document.getElementById(id)
1597
+ const banner = $("banner")
1598
+ const keyInput = $("admin-key")
1599
+ keyInput.value = state.key
1600
+ const params = new URLSearchParams(location.search)
1601
+ if (params.get("key")) {
1602
+ state.key = params.get("key")
1603
+ keyInput.value = state.key
1604
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1605
+ params.delete("key")
1606
+ const next = params.toString()
1607
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1608
+ }
1609
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1610
+
1611
+ const showError = (error) => {
1612
+ banner.textContent = error instanceof Error ? error.message : String(error)
1613
+ banner.classList.add("show")
1614
+ }
1615
+ const clearError = () => banner.classList.remove("show")
1616
+
1617
+ async function originGet(path) {
1618
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1619
+ if (!response.ok) throw new Error(response.status + " " + path)
1620
+ return response.json()
1621
+ }
1622
+ async function api(method, path, body) {
1623
+ const headers = { accept: "application/json" }
1624
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1625
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1626
+ if (body !== undefined) headers["content-type"] = "application/json"
1627
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1628
+ method,
1629
+ headers,
1630
+ body: body === undefined ? undefined : JSON.stringify(body)
1631
+ })
1632
+ const text = await response.text()
1633
+ let data = null
1634
+ if (text) {
1635
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1636
+ }
1637
+ if (response.status === 401) {
1638
+ keyInput.focus()
1639
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1640
+ }
1641
+ if (!response.ok) {
1642
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1643
+ }
1644
+ return data
1645
+ }
1646
+ const panelApi = {
1647
+ get: (path) => api("GET", path),
1648
+ send: (method, path, body) => api(method, path, body),
1649
+ namespace: () => state.namespace
1650
+ }
1651
+
1652
+ function setTheme(theme) {
1653
+ if (theme) document.documentElement.dataset.theme = theme
1654
+ else delete document.documentElement.dataset.theme
1655
+ }
1656
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1657
+ if (storedTheme) setTheme(storedTheme)
1658
+ $("theme").addEventListener("click", () => {
1659
+ const current = document.documentElement.dataset.theme
1660
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1661
+ const next = dark ? "light" : "dark"
1662
+ localStorage.setItem("mockingbird-admin-theme", next)
1663
+ setTheme(next)
1664
+ })
1665
+
1666
+ function show(view) {
1667
+ state.view = view
1668
+ for (const button of document.querySelectorAll("#nav button")) {
1669
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1670
+ }
1671
+ for (const section of document.querySelectorAll("main .view")) {
1672
+ section.hidden = section.id !== "view-" + view
1673
+ }
1674
+ }
1675
+ document.getElementById("nav").addEventListener("click", (event) => {
1676
+ const button = event.target.closest("button[data-view]")
1677
+ if (!button) return
1678
+ show(button.dataset.view)
1679
+ refresh().catch(showError)
1680
+ })
1681
+
1682
+ function cards(items) {
1683
+ return '<div class="grid">' + items.map((item) =>
1684
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1685
+ ).join("") + "</div>"
1686
+ }
1687
+ function table(columns, rows) {
1688
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1689
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1690
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1691
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1692
+ ).join("") + "</tr>").join("")
1693
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1694
+ }
1695
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1696
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1697
+ }[char]))
1698
+ const preview = (value) => {
1699
+ const text = JSON.stringify(value)
1700
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1701
+ }
1702
+ const when = (epoch) => {
1703
+ const date = new Date(epoch)
1704
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1705
+ }
1706
+ const clockCard = (epoch) => {
1707
+ const date = new Date(epoch)
1708
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1709
+ const iso = date.toISOString()
1710
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1711
+ }
1712
+
1713
+ async function loadNamespaces() {
1714
+ const data = await api("GET", "/namespaces")
1715
+ const select = $("namespace")
1716
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1717
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1718
+ select.innerHTML = names.map((name) =>
1719
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1720
+ ).join("")
1721
+ select.value = state.namespace
1722
+ }
1723
+
1724
+ async function renderOverview() {
1725
+ const [health, shape, clock, journal] = await Promise.all([
1726
+ originGet("/health"),
1727
+ api("GET", "/state"),
1728
+ api("GET", "/clock"),
1729
+ api("GET", "/requests?limit=8")
1730
+ ])
1731
+ state.shape = shape
1732
+ $("overview-cards").innerHTML = cards([
1733
+ { k: "Service", v: esc(health.service || "${name}") },
1734
+ { k: "Status", v: esc(health.status || "ok") },
1735
+ { k: "Namespace", v: esc(state.namespace) },
1736
+ { k: "Collections", v: String(shape.collections.length) },
1737
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1738
+ { k: "Clock", v: clockCard(clock.now) }
1739
+ ])
1740
+ const requests = (journal && journal.requests) || []
1741
+ $("overview-requests").innerHTML = table(
1742
+ [
1743
+ { label: "Method", cell: (row) => esc(row.method) },
1744
+ { label: "Path", cell: (row) => esc(row.path) },
1745
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1746
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1747
+ ],
1748
+ requests
1749
+ )
1750
+ }
1751
+
1752
+ function schemaChips(collection) {
1753
+ if (!collection || collection.fields.length === 0) {
1754
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1755
+ }
1756
+ return '<div class="chips">' + collection.fields.map((field) =>
1757
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1758
+ ).join("") + "</div>"
1759
+ }
1760
+
1761
+ async function renderState() {
1762
+ const shape = await api("GET", "/state")
1763
+ state.shape = shape
1764
+ const host = $("collections")
1765
+ if (shape.collections.length === 0) {
1766
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1767
+ $("schema").innerHTML = ""
1768
+ $("records").innerHTML = ""
1769
+ return
1770
+ }
1771
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1772
+ state.collection = shape.collections[0].name
1773
+ }
1774
+ host.innerHTML = shape.collections.map((item) =>
1775
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1776
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1777
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1778
+ ).join("")
1779
+ const selected = shape.collections.find((item) => item.name === state.collection)
1780
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1781
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1782
+ schemaChips(selected)
1783
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1784
+ const rows = page.records.map((record) => ({
1785
+ ...record,
1786
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1787
+ }))
1788
+ $("records").innerHTML = table(
1789
+ [
1790
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1791
+ { label: "Seq", cell: (row) => esc(row.seq) },
1792
+ { label: "Value", cell: (row) => preview(row.value) }
1793
+ ],
1794
+ rows
1795
+ )
1796
+ }
1797
+
1798
+ async function renderClock() {
1799
+ const clock = await api("GET", "/clock")
1800
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1801
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1802
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1803
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1804
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1805
+ }
1806
+
1807
+ async function renderFaults() {
1808
+ const [faults, presets] = await Promise.all([
1809
+ api("GET", "/faults"),
1810
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1811
+ ])
1812
+ const select = $("fault-preset")
1813
+ const current = select.value
1814
+ const list = presets.presets || []
1815
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1816
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1817
+ ).join("")
1818
+ select.value = current
1819
+ const rules = faults.faults || []
1820
+ $("fault-list").innerHTML = table(
1821
+ [
1822
+ { label: "Id", cell: (row) => esc(row.id) },
1823
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1824
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1825
+ ],
1826
+ rules
1827
+ )
1828
+ }
1829
+
1830
+ async function renderJournal() {
1831
+ const journal = await api("GET", "/requests?limit=100")
1832
+ $("journal").innerHTML = table(
1833
+ [
1834
+ { label: "When", cell: (row) => esc(row.at || "") },
1835
+ { label: "Method", cell: (row) => esc(row.method) },
1836
+ { label: "Path", cell: (row) => esc(row.path) },
1837
+ { label: "Status", cell: (row) => esc(row.status) },
1838
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1839
+ ],
1840
+ journal.requests || []
1841
+ )
1842
+ }
1843
+
1844
+ async function renderRoutes() {
1845
+ const data = await api("GET", "/")
1846
+ const routes = data.routes || []
1847
+ $("route-list").innerHTML = routes.map((route) => {
1848
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1849
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1850
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1851
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1852
+ }).join("")
1853
+ }
1854
+
1855
+ const renderers = {
1856
+ overview: renderOverview,
1857
+ state: renderState,
1858
+ clock: renderClock,
1859
+ faults: renderFaults,
1860
+ journal: renderJournal,
1861
+ routes: renderRoutes
1862
+ }
1863
+
1864
+ async function refresh() {
1865
+ clearError()
1866
+ if (state.view in renderers) await renderers[state.view]()
1867
+ }
1868
+
1869
+ $("namespace").addEventListener("change", () => {
1870
+ state.namespace = $("namespace").value
1871
+ refresh().catch(showError)
1872
+ })
1873
+ keyInput.addEventListener("change", () => {
1874
+ state.key = keyInput.value.trim()
1875
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1876
+ refresh().catch(showError)
1877
+ })
1878
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1879
+
1880
+ $("collections").addEventListener("click", (event) => {
1881
+ const button = event.target.closest("[data-collection]")
1882
+ if (!button) return
1883
+ state.collection = button.dataset.collection
1884
+ renderState().catch(showError)
1885
+ })
1886
+ $("records").addEventListener("click", (event) => {
1887
+ const row = event.target.closest("[data-id]")
1888
+ if (!row) return
1889
+ openEditor(row.dataset.id).catch(showError)
1890
+ })
1891
+
1892
+ const editor = $("editor")
1893
+ async function openEditor(id) {
1894
+ state.editing = id || null
1895
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1896
+ $("editor-id").value = id || ""
1897
+ $("editor-id").readOnly = Boolean(id)
1898
+ $("editor-delete").hidden = !id
1899
+ if (id) {
1900
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1901
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1902
+ } else {
1903
+ $("editor-value").value = "{\\n \\n}"
1904
+ }
1905
+ editor.showModal()
1906
+ }
1907
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1908
+ $("editor-form").addEventListener("submit", (event) => {
1909
+ const submitter = event.submitter
1910
+ if (!submitter || submitter.value !== "save") return
1911
+ event.preventDefault()
1912
+ let value
1913
+ try { value = JSON.parse($("editor-value").value) }
1914
+ catch { showError(new Error("Value is not JSON")); return }
1915
+ const id = $("editor-id").value.trim()
1916
+ const path = "/state/" + encodeURIComponent(state.collection)
1917
+ const request = state.editing
1918
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1919
+ : api("POST", path, { id: id || undefined, value })
1920
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1921
+ })
1922
+ $("editor-delete").addEventListener("click", () => {
1923
+ const id = state.editing
1924
+ if (!id) return
1925
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1926
+ .then(() => { editor.close(); return renderState() })
1927
+ .catch(showError)
1928
+ })
1929
+
1930
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1931
+ button.addEventListener("click", () => {
1932
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1933
+ })
1934
+ })
1935
+ $("freeze").addEventListener("click", () => {
1936
+ const frozen = $("freeze").dataset.frozen === "1"
1937
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1938
+ })
1939
+ $("clock-reset").addEventListener("click", () => {
1940
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1941
+ })
1942
+ $("clock-set").addEventListener("submit", (event) => {
1943
+ event.preventDefault()
1944
+ const raw = $("clock-instant").value.trim()
1945
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1946
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1947
+ })
1948
+
1949
+ $("fault-form").addEventListener("submit", (event) => {
1950
+ event.preventDefault()
1951
+ const preset = $("fault-preset").value
1952
+ const body = preset
1953
+ ? { preset }
1954
+ : {
1955
+ status: Number($("fault-status").value),
1956
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1957
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1958
+ }
1959
+ if (!preset && !Number.isFinite(body.status)) {
1960
+ showError(new Error("Status must be a number, or choose a preset"))
1961
+ return
1962
+ }
1963
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1964
+ })
1965
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1966
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1967
+
1968
+ $("route-list").addEventListener("click", (event) => {
1969
+ const button = event.target.closest("[data-route]")
1970
+ if (!button) return
1971
+ state.route = button.dataset.route
1972
+ $("route-title").textContent = state.route
1973
+ const method = state.route.split(" ")[0]
1974
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1975
+ })
1976
+ $("route-form").addEventListener("submit", async (event) => {
1977
+ event.preventDefault()
1978
+ if (!state.route) return showError(new Error("Choose a route first"))
1979
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1980
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1981
+ let body
1982
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1983
+ try { body = JSON.parse($("route-body").value) }
1984
+ catch { return showError(new Error("Body is not JSON")) }
1985
+ }
1986
+ try {
1987
+ const data = await api(method, concrete, body)
1988
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1989
+ } catch (error) {
1990
+ showError(error)
1991
+ }
1992
+ })
1993
+
1994
+ function mountPanels(panels) {
1995
+ const nav = $("nav")
1996
+ const views = $("views")
1997
+ for (const panel of panels) {
1998
+ const button = document.createElement("button")
1999
+ button.type = "button"
2000
+ button.dataset.view = panel.id
2001
+ button.textContent = panel.title
2002
+ nav.append(button)
2003
+ const section = document.createElement("section")
2004
+ section.className = "view"
2005
+ section.id = "view-" + panel.id
2006
+ section.hidden = true
2007
+ const title = document.createElement("h2")
2008
+ title.textContent = panel.title
2009
+ const lede = document.createElement("p")
2010
+ lede.className = "lede"
2011
+ lede.textContent = panel.description || ""
2012
+ const body = document.createElement("div")
2013
+ body.className = "panel-body"
2014
+ body.id = "panel-" + panel.id
2015
+ body.innerHTML = panel.html || ""
2016
+ section.append(title, lede, body)
2017
+ views.append(section)
2018
+ if (panel.script) {
2019
+ try {
2020
+ const run = new Function("root", "api", panel.script)
2021
+ run(body, panelApi)
2022
+ } catch (error) {
2023
+ const note = document.createElement("p")
2024
+ note.className = "banner show"
2025
+ note.textContent = error instanceof Error ? error.message : String(error)
2026
+ body.append(note)
2027
+ }
2028
+ }
2029
+ }
2030
+ }
2031
+
2032
+ loadNamespaces()
2033
+ .then(() => api("GET", "/ui/manifest"))
2034
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2035
+ .catch(showError)
2036
+ })()
2037
+ </script>
2038
+ </body>
2039
+ </html>`;
2040
+ };
2041
+ var htmlResponse = (body) => new Response(body, {
2042
+ status: 200,
2043
+ headers: {
2044
+ "content-type": "text/html; charset=utf-8",
2045
+ "cache-control": "no-store"
2046
+ }
2047
+ });
2048
+ var json2 = (body) => new Response(JSON.stringify(body), {
2049
+ status: 200,
2050
+ headers: { "content-type": "application/json; charset=utf-8" }
2051
+ });
2052
+ var adminUiRoutes = (service, ui) => {
2053
+ const shell = () => renderAdminDocument(service);
2054
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2055
+ return {
2056
+ "GET /ui": () => htmlResponse(document2()),
2057
+ "GET /ui/": () => htmlResponse(document2()),
2058
+ "GET /ui/manifest": () => json2({
2059
+ service,
2060
+ panels: (ui?.panels ?? []).map((panel) => ({
2061
+ id: panel.id,
2062
+ title: panel.title,
2063
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2064
+ html: panel.html,
2065
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2066
+ }))
2067
+ })
2068
+ };
2069
+ };
2070
+
1139
2071
  // ../../openapi/metadata/dist/types.js
1140
2072
  var EXTENSION_KEYS = {
1141
2073
  operation: "x-mockingbird",
@@ -1299,8 +2231,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1299
2231
  });
1300
2232
  };
1301
2233
 
2234
+ // ../core/dist/state-view.js
2235
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2236
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2237
+ var SAMPLE = 25;
2238
+ var WALK_LIMIT = 1e4;
2239
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2240
+ var fail = (status, message) => ({ ok: false, status, message });
2241
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2242
+ var kindOf = (value) => {
2243
+ if (value === null)
2244
+ return "null";
2245
+ if (Array.isArray(value))
2246
+ return "array";
2247
+ switch (typeof value) {
2248
+ case "string":
2249
+ return "string";
2250
+ case "number":
2251
+ return Number.isFinite(value) ? "number" : "unknown";
2252
+ case "boolean":
2253
+ return "boolean";
2254
+ case "object":
2255
+ return "object";
2256
+ default:
2257
+ return "unknown";
2258
+ }
2259
+ };
2260
+ var humanize = (name) => {
2261
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2262
+ if (words === "")
2263
+ return name;
2264
+ return words.charAt(0).toUpperCase() + words.slice(1);
2265
+ };
2266
+ var jsonValue = (value) => {
2267
+ if (value === void 0)
2268
+ return fail(400, "value is required");
2269
+ try {
2270
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2271
+ } catch {
2272
+ return fail(400, "value must be JSON");
2273
+ }
2274
+ };
2275
+ var ctorName = (value) => {
2276
+ const ctor = value.constructor;
2277
+ return typeof ctor?.name === "string" ? ctor.name : "";
2278
+ };
2279
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2280
+ var discoverCollections = (root) => {
2281
+ const found = [];
2282
+ const seen = /* @__PURE__ */ new Set();
2283
+ const visit = (value, depth) => {
2284
+ if (found.length + seen.size > WALK_LIMIT)
2285
+ return;
2286
+ if (value === null || typeof value !== "object")
2287
+ return;
2288
+ if (seen.has(value))
2289
+ return;
2290
+ seen.add(value);
2291
+ if (value instanceof Collection) {
2292
+ found.push(value);
2293
+ return;
2294
+ }
2295
+ if (value instanceof Map) {
2296
+ for (const child of value.values())
2297
+ visit(child, depth + 1);
2298
+ return;
2299
+ }
2300
+ if (value instanceof Set) {
2301
+ for (const child of value.values())
2302
+ visit(child, depth + 1);
2303
+ return;
2304
+ }
2305
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2306
+ return;
2307
+ if (Array.isArray(value)) {
2308
+ const cap = Math.min(value.length, 32);
2309
+ for (let i = 0; i < cap; i++)
2310
+ visit(value[i], depth + 1);
2311
+ return;
2312
+ }
2313
+ let children;
2314
+ try {
2315
+ children = Object.values(value);
2316
+ } catch {
2317
+ return;
2318
+ }
2319
+ for (const child of children)
2320
+ visit(child, depth + 1);
2321
+ };
2322
+ visit(root, 0);
2323
+ return found;
2324
+ };
2325
+ var storedNames = (sqlite, namespace) => {
2326
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2327
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2328
+ return [...records, ...sequences].map((row) => row.name);
2329
+ };
2330
+ var blankAccum = (name) => ({
2331
+ name,
2332
+ kinds: /* @__PURE__ */ new Set(),
2333
+ present: 0,
2334
+ nested: /* @__PURE__ */ new Map()
2335
+ });
2336
+ var absorb = (accum, value) => {
2337
+ const kind = kindOf(value);
2338
+ accum.kinds.add(kind);
2339
+ accum.present++;
2340
+ if (!isRecord3(value))
2341
+ return;
2342
+ for (const [key, child] of Object.entries(value)) {
2343
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2344
+ absorb(nested, child);
2345
+ accum.nested.set(key, nested);
2346
+ }
2347
+ };
2348
+ var finishField = (accum, samples) => {
2349
+ const kinds = [...accum.kinds];
2350
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2351
+ const field = {
2352
+ name: accum.name,
2353
+ kind,
2354
+ optional: accum.present < samples || kinds.includes("null")
2355
+ };
2356
+ if (accum.nested.size > 0) {
2357
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2358
+ }
2359
+ return field;
2360
+ };
2361
+ var inferFields = (records) => {
2362
+ if (records.length === 0)
2363
+ return [];
2364
+ const sample = records.slice(0, SAMPLE);
2365
+ const objects = sample.filter((record) => isRecord3(record.value));
2366
+ if (objects.length === 0) {
2367
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2368
+ const list = [...kinds];
2369
+ return [
2370
+ {
2371
+ name: "(value)",
2372
+ kind: list.length === 1 ? list[0] : "unknown",
2373
+ optional: false
2374
+ }
2375
+ ];
2376
+ }
2377
+ const root = /* @__PURE__ */ new Map();
2378
+ for (const record of objects) {
2379
+ for (const [key, value] of Object.entries(record.value)) {
2380
+ const accum = root.get(key) ?? blankAccum(key);
2381
+ absorb(accum, value);
2382
+ root.set(key, accum);
2383
+ }
2384
+ }
2385
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2386
+ };
2387
+ var mergeFields = (declared, inferred) => {
2388
+ const byName = /* @__PURE__ */ new Map();
2389
+ for (const field of inferred)
2390
+ byName.set(field.name, field);
2391
+ const ordered = [];
2392
+ const seen = /* @__PURE__ */ new Set();
2393
+ for (const field of declared ?? []) {
2394
+ const found = byName.get(field.name);
2395
+ seen.add(field.name);
2396
+ if (!found) {
2397
+ ordered.push({ ...field, optional: field.optional });
2398
+ continue;
2399
+ }
2400
+ ordered.push({
2401
+ ...found,
2402
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2403
+ optional: field.optional || found.optional,
2404
+ ...field.description !== void 0 ? { description: field.description } : {},
2405
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2406
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2407
+ });
2408
+ }
2409
+ for (const field of inferred) {
2410
+ if (!seen.has(field.name))
2411
+ ordered.push(field);
2412
+ }
2413
+ return ordered;
2414
+ };
2415
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2416
+ var readRecord = (collection, id) => {
2417
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2418
+ const row = rows.find((entry) => entry.id === id);
2419
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2420
+ };
2421
+ var inspectState = (scope) => {
2422
+ const declared = /* @__PURE__ */ new Map();
2423
+ for (const declaration of scope.declarations ?? []) {
2424
+ if (COLLECTION_NAME.test(declaration.name))
2425
+ declared.set(declaration.name, declaration);
2426
+ }
2427
+ const names = new Set(declared.keys());
2428
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2429
+ names.add(name);
2430
+ for (const collection of discoverCollections(scope.root)) {
2431
+ if (collection.namespace === scope.storageNamespace)
2432
+ names.add(collection.collectionName);
2433
+ }
2434
+ const collections = [];
2435
+ for (const name of names) {
2436
+ if (!COLLECTION_NAME.test(name))
2437
+ continue;
2438
+ const declaration = declared.get(name);
2439
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2440
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2441
+ const inferred = inferFields(records);
2442
+ const fields = mergeFields(declaration?.fields, inferred);
2443
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2444
+ collections.push({
2445
+ name,
2446
+ label: declaration?.label ?? humanize(name),
2447
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2448
+ count: collection.count(),
2449
+ source,
2450
+ fields,
2451
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2452
+ });
2453
+ }
2454
+ const order = /* @__PURE__ */ new Map();
2455
+ for (const [index, item] of (scope.declarations ?? []).entries())
2456
+ order.set(item.name, index);
2457
+ collections.sort((a, b) => {
2458
+ const left = order.get(a.name);
2459
+ const right = order.get(b.name);
2460
+ if (left !== void 0 && right !== void 0)
2461
+ return left - right;
2462
+ if (left !== void 0)
2463
+ return -1;
2464
+ if (right !== void 0)
2465
+ return 1;
2466
+ return a.name.localeCompare(b.name);
2467
+ });
2468
+ return {
2469
+ namespace: scope.namespace,
2470
+ storageNamespace: scope.storageNamespace,
2471
+ collections
2472
+ };
2473
+ };
2474
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2475
+ if (!COLLECTION_NAME.test(name))
2476
+ return fail(400, "collection name is not allowed");
2477
+ const limit = query.limit ?? 50;
2478
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2479
+ return fail(400, "limit must be an integer from 1 to 200");
2480
+ }
2481
+ const order = query.order ?? "newest";
2482
+ if (order !== "newest" && order !== "oldest")
2483
+ return fail(400, 'order must be "newest" or "oldest"');
2484
+ const collection = collectionOf(sqlite, storageNamespace, name);
2485
+ const rows = collection.list({ order }).filter((row) => {
2486
+ if (query.after === void 0)
2487
+ return true;
2488
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2489
+ });
2490
+ const slice = rows.slice(0, limit);
2491
+ const last = slice.at(-1);
2492
+ return {
2493
+ ok: true,
2494
+ value: {
2495
+ collection: name,
2496
+ count: collection.count(),
2497
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2498
+ next: rows.length > limit && last ? last.seq : null
2499
+ }
2500
+ };
2501
+ };
2502
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2503
+ var readStateRecord = (scope, name, id) => {
2504
+ if (!COLLECTION_NAME.test(name))
2505
+ return fail(400, "collection name is not allowed");
2506
+ if (!RECORD_ID.test(id))
2507
+ return fail(400, "record id is not allowed");
2508
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2509
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2510
+ };
2511
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2512
+ var createStateRecord = (scope, name, input) => {
2513
+ if (!COLLECTION_NAME.test(name))
2514
+ return fail(400, "collection name is not allowed");
2515
+ const parsed = jsonValue(input.value);
2516
+ if (!parsed.ok)
2517
+ return parsed;
2518
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2519
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2520
+ const checked = requireId(id);
2521
+ if (!checked.ok)
2522
+ return checked;
2523
+ if (collection.has(checked.value))
2524
+ return fail(409, `record ${checked.value} already exists`);
2525
+ const stored = collection.insert(checked.value, parsed.value);
2526
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2527
+ };
2528
+ var replaceStateRecord = (scope, name, id, value) => {
2529
+ if (!COLLECTION_NAME.test(name))
2530
+ return fail(400, "collection name is not allowed");
2531
+ const checked = requireId(id);
2532
+ if (!checked.ok)
2533
+ return checked;
2534
+ const parsed = jsonValue(value);
2535
+ if (!parsed.ok)
2536
+ return parsed;
2537
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2538
+ if (!collection.has(checked.value))
2539
+ return fail(404, `no record ${checked.value} in ${name}`);
2540
+ const stored = collection.update(checked.value, parsed.value);
2541
+ if (!stored)
2542
+ return fail(404, `no record ${checked.value} in ${name}`);
2543
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2544
+ };
2545
+ var patchStateRecord = (scope, name, id, value) => {
2546
+ const current = readStateRecord(scope, name, id);
2547
+ if (!current.ok)
2548
+ return current;
2549
+ const parsed = jsonValue(value);
2550
+ if (!parsed.ok)
2551
+ return parsed;
2552
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2553
+ return replaceStateRecord(scope, name, id, next);
2554
+ };
2555
+ var deleteStateRecord = (scope, name, id) => {
2556
+ if (!COLLECTION_NAME.test(name))
2557
+ return fail(400, "collection name is not allowed");
2558
+ const checked = requireId(id);
2559
+ if (!checked.ok)
2560
+ return checked;
2561
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2562
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2563
+ };
2564
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2565
+ status,
2566
+ headers: { "content-type": "application/json; charset=utf-8" }
2567
+ });
2568
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2569
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2570
+ var integerParam = (value) => {
2571
+ if (value === null)
2572
+ return void 0;
2573
+ if (!/^-?\d+$/.test(value))
2574
+ return "bad";
2575
+ return Number(value);
2576
+ };
2577
+ var stateAdminRoutes = (routes) => {
2578
+ const open = (namespace) => {
2579
+ try {
2580
+ return { ok: true, value: routes.open(namespace) };
2581
+ } catch (error2) {
2582
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2583
+ }
2584
+ };
2585
+ const wrote = (namespace) => {
2586
+ routes.afterWrite?.(namespace);
2587
+ };
2588
+ return {
2589
+ "GET /state": ({ namespace }) => {
2590
+ const scope = open(namespace);
2591
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2592
+ },
2593
+ "GET /state/:collection": ({ namespace, params, url }) => {
2594
+ const scope = open(namespace);
2595
+ if (!scope.ok)
2596
+ return fromResult(scope, 200);
2597
+ const limit = integerParam(url.searchParams.get("limit"));
2598
+ const after = integerParam(url.searchParams.get("after"));
2599
+ if (limit === "bad")
2600
+ return adminError2(400, "limit: expected an integer");
2601
+ if (after === "bad")
2602
+ return adminError2(400, "after: expected a sequence number");
2603
+ const order = url.searchParams.get("order");
2604
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2605
+ ...limit !== void 0 ? { limit } : {},
2606
+ ...after !== void 0 ? { after } : {},
2607
+ ...order === "newest" || order === "oldest" ? { order } : {}
2608
+ }), 200);
2609
+ },
2610
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2611
+ const scope = open(namespace);
2612
+ if (!scope.ok)
2613
+ return fromResult(scope, 200);
2614
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2615
+ },
2616
+ "POST /state/:collection": ({ namespace, params, body }) => {
2617
+ const scope = open(namespace);
2618
+ if (!scope.ok)
2619
+ return fromResult(scope, 201);
2620
+ if (!isRecord3(body) || !("value" in body)) {
2621
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2622
+ }
2623
+ const id = body.id;
2624
+ if (id !== void 0 && typeof id !== "string")
2625
+ return adminError2(400, "id must be a string");
2626
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2627
+ ...typeof id === "string" ? { id } : {},
2628
+ value: body.value
2629
+ });
2630
+ if (created.ok)
2631
+ wrote(namespace);
2632
+ return fromResult(created, 201);
2633
+ },
2634
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2635
+ const scope = open(namespace);
2636
+ if (!scope.ok)
2637
+ return fromResult(scope, 200);
2638
+ if (!isRecord3(body) || !("value" in body))
2639
+ return adminError2(400, 'expected {"value": <json>}');
2640
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2641
+ if (replaced.ok)
2642
+ wrote(namespace);
2643
+ return fromResult(replaced, 200);
2644
+ },
2645
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2646
+ const scope = open(namespace);
2647
+ if (!scope.ok)
2648
+ return fromResult(scope, 200);
2649
+ if (!isRecord3(body) || !("value" in body))
2650
+ return adminError2(400, 'expected {"value": <json>}');
2651
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2652
+ if (patched.ok)
2653
+ wrote(namespace);
2654
+ return fromResult(patched, 200);
2655
+ },
2656
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2657
+ const scope = open(namespace);
2658
+ if (!scope.ok)
2659
+ return fromResult(scope, 200);
2660
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2661
+ if (removed.ok)
2662
+ wrote(namespace);
2663
+ return fromResult(removed, 200);
2664
+ }
2665
+ };
2666
+ };
2667
+
1302
2668
  // ../core/dist/version.js
1303
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2669
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1304
2670
 
1305
2671
  // ../core/dist/signing.js
1306
2672
  var encoder = new TextEncoder();
@@ -1635,11 +3001,11 @@ var createWebhookHub = (options) => {
1635
3001
  };
1636
3002
  return hub;
1637
3003
  };
1638
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1639
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1640
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3004
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3005
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3006
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1641
3007
  var parseEndpoint = (value) => {
1642
- if (!isRecord3(value) || typeof value.url !== "string")
3008
+ if (!isRecord4(value) || typeof value.url !== "string")
1643
3009
  return "each endpoint needs a url";
1644
3010
  try {
1645
3011
  new URL(value.url);
@@ -1656,18 +3022,18 @@ var parseEndpoint = (value) => {
1656
3022
  const events = value.events ?? value.enabledEvents;
1657
3023
  if (Array.isArray(events))
1658
3024
  endpoint.events = events.map(String);
1659
- if (isRecord3(value.tags)) {
3025
+ if (isRecord4(value.tags)) {
1660
3026
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1661
3027
  }
1662
3028
  if (typeof value.account === "string")
1663
3029
  endpoint.tags = { ...endpoint.tags, account: value.account };
1664
- if (isRecord3(value.headers)) {
3030
+ if (isRecord4(value.headers)) {
1665
3031
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1666
3032
  }
1667
3033
  return endpoint;
1668
3034
  };
1669
3035
  var webhookAdminRoutes = (hub) => ({
1670
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3036
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1671
3037
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1672
3038
  const type = url.searchParams.get("type");
1673
3039
  return type === null || d.type === type;
@@ -1675,51 +3041,51 @@ var webhookAdminRoutes = (hub) => ({
1675
3041
  }),
1676
3042
  "GET /webhooks/events": ({ url, namespace }) => {
1677
3043
  const type = url.searchParams.get("type");
1678
- return json2(200, {
3044
+ return json4(200, {
1679
3045
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1680
3046
  });
1681
3047
  },
1682
3048
  "POST /webhooks/:id/replay": async ({ params }) => {
1683
3049
  const replayed = await hub.replay(params.id);
1684
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3050
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1685
3051
  },
1686
3052
  "POST /webhooks/flush": async () => {
1687
3053
  await hub.flush();
1688
- return json2(200, { status: "ok" });
3054
+ return json4(200, { status: "ok" });
1689
3055
  },
1690
3056
  "POST /webhooks/faults": ({ body, namespace }) => {
1691
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1692
- return adminError2(400, "mode must be duplicate, reorder or drop");
3057
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3058
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1693
3059
  }
1694
3060
  const fault = { mode: body.mode };
1695
3061
  if (typeof body.count === "number")
1696
3062
  fault.count = body.count;
1697
3063
  hub.fault(namespace, fault);
1698
- return json2(201, { namespace, ...fault });
3064
+ return json4(201, { namespace, ...fault });
1699
3065
  },
1700
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3066
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1701
3067
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1702
3068
  ...rest,
1703
3069
  secret: secret ? "(set)" : null
1704
3070
  }))
1705
3071
  }),
1706
3072
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1707
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3073
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1708
3074
  if (!Array.isArray(list))
1709
- return adminError2(400, "expected [{url, secret?, events?}]");
3075
+ return adminError3(400, "expected [{url, secret?, events?}]");
1710
3076
  const parsed = [];
1711
3077
  for (const each of list) {
1712
3078
  const endpoint = parseEndpoint(each);
1713
3079
  if (typeof endpoint === "string")
1714
- return adminError2(400, endpoint);
3080
+ return adminError3(400, endpoint);
1715
3081
  parsed.push(endpoint);
1716
3082
  }
1717
3083
  const set = hub.setEndpoints(namespace, parsed);
1718
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3084
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1719
3085
  },
1720
3086
  "DELETE /webhook-endpoints": ({ namespace }) => {
1721
3087
  hub.setEndpoints(namespace, []);
1722
- return json2(200, { status: "ok" });
3088
+ return json4(200, { status: "ok" });
1723
3089
  }
1724
3090
  });
1725
3091
  var parsePayload = (message) => {
@@ -1784,6 +3150,7 @@ var operationMatcher = (document2) => {
1784
3150
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1785
3151
  };
1786
3152
  var createRuntime = (options) => {
3153
+ assertAdminUi(options.adminUi);
1787
3154
  const sqlite = bootSqlite(options.sqlite);
1788
3155
  const clock = options.clock ?? createClock();
1789
3156
  const rng = createRng(options.seed ?? 0);
@@ -1990,6 +3357,19 @@ var createRuntime = (options) => {
1990
3357
  else
1991
3358
  timeline(name);
1992
3359
  };
3360
+ const declarationsFor = (namespace) => {
3361
+ const declared = options.state;
3362
+ if (!declared)
3363
+ return [];
3364
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3365
+ };
3366
+ const stateScope = (namespace) => ({
3367
+ sqlite,
3368
+ namespace,
3369
+ storageNamespace: storageNamespace(namespace),
3370
+ root: instance(namespace),
3371
+ declarations: declarationsFor(namespace)
3372
+ });
1993
3373
  const runtime = {
1994
3374
  name: options.name,
1995
3375
  sqlite,
@@ -2028,6 +3408,7 @@ var createRuntime = (options) => {
2028
3408
  branch,
2029
3409
  checkout,
2030
3410
  timeline,
3411
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2031
3412
  fetch: async (incoming) => {
2032
3413
  let request = incoming;
2033
3414
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2221,11 +3602,20 @@ var createRuntime = (options) => {
2221
3602
  ...credentialRoutes(credentials),
2222
3603
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2223
3604
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2224
- ...options.admin?.(runtime) ?? {}
3605
+ ...options.admin?.(runtime) ?? {},
3606
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3607
+ // beside these; it does not replace `/state` or `/ui`.
3608
+ ...stateAdminRoutes({
3609
+ open: stateScope,
3610
+ afterWrite: (namespace) => {
3611
+ checkpoint(namespace, "main");
3612
+ }
3613
+ }),
3614
+ ...adminUiRoutes(options.name, options.adminUi)
2225
3615
  },
2226
3616
  adminKey: options.adminKey
2227
3617
  });
2228
- return runtime;
3618
+ return defineMock(runtime);
2229
3619
  };
2230
3620
  var mutableResponse = (response) => {
2231
3621
  try {
@@ -3271,24 +4661,24 @@ var FORMBRICKS_PRESETS = {
3271
4661
  webhook: { mode: "reorder" }
3272
4662
  }
3273
4663
  };
3274
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3275
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
3276
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4664
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4665
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4666
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3277
4667
  var adminRoutes = (runtime) => ({
3278
4668
  "GET /responses": ({ url, namespace }) => {
3279
4669
  const surveyId = url.searchParams.get("surveyId");
3280
- return json3(200, {
4670
+ return json5(200, {
3281
4671
  responses: runtime.instance(namespace).responses().filter((r) => surveyId === null || r.surveyId === surveyId)
3282
4672
  });
3283
4673
  },
3284
- "GET /surveys": ({ namespace }) => json3(200, { surveys: runtime.instance(namespace).state.allSurveys() }),
4674
+ "GET /surveys": ({ namespace }) => json5(200, { surveys: runtime.instance(namespace).state.allSurveys() }),
3285
4675
  "PUT /surveys": ({ body, namespace }) => {
3286
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.surveys : void 0;
3287
- if (!Array.isArray(list)) return adminError3(400, "expected [survey] or {surveys: [survey]}");
4676
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.surveys : void 0;
4677
+ if (!Array.isArray(list)) return adminError4(400, "expected [survey] or {surveys: [survey]}");
3288
4678
  const state = runtime.instance(namespace).state;
3289
4679
  for (const [index, survey] of list.entries()) {
3290
- if (!isRecord4(survey) || typeof survey.id !== "string" || typeof survey.name !== "string") {
3291
- return adminError3(400, `surveys[${index}]: id and name are required`);
4680
+ if (!isRecord5(survey) || typeof survey.id !== "string" || typeof survey.name !== "string") {
4681
+ return adminError4(400, `surveys[${index}]: id and name are required`);
3292
4682
  }
3293
4683
  }
3294
4684
  for (const survey of list) {
@@ -3301,22 +4691,22 @@ var adminRoutes = (runtime) => ({
3301
4691
  workspaceId: owner ? state.resolveWorkspace(owner) ?? owner : null
3302
4692
  });
3303
4693
  }
3304
- return json3(200, { surveys: state.allSurveys().map((s) => s.id) });
4694
+ return json5(200, { surveys: state.allSurveys().map((s) => s.id) });
3305
4695
  },
3306
- "GET /contacts": ({ namespace }) => json3(200, {
4696
+ "GET /contacts": ({ namespace }) => json5(200, {
3307
4697
  contacts: runtime.instance(namespace).state.contacts.list({ order: "oldest" }).map((row) => row.value)
3308
4698
  }),
3309
4699
  "PUT /contacts": ({ body, namespace }) => {
3310
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.contacts : void 0;
3311
- if (!Array.isArray(list)) return adminError3(400, "expected [contact] or {contacts: [contact]}");
4700
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.contacts : void 0;
4701
+ if (!Array.isArray(list)) return adminError4(400, "expected [contact] or {contacts: [contact]}");
3312
4702
  const state = runtime.instance(namespace).state;
3313
4703
  for (const [index, contact] of list.entries()) {
3314
- if (!isRecord4(contact) || typeof contact.id !== "string") {
3315
- return adminError3(400, `contacts[${index}]: id is required`);
4704
+ if (!isRecord5(contact) || typeof contact.id !== "string") {
4705
+ return adminError4(400, `contacts[${index}]: id is required`);
3316
4706
  }
3317
4707
  }
3318
4708
  for (const contact of list) {
3319
- const attributes = isRecord4(contact.attributes) ? Object.fromEntries(Object.entries(contact.attributes).map(([k, v]) => [k, String(v)])) : {};
4709
+ const attributes = isRecord5(contact.attributes) ? Object.fromEntries(Object.entries(contact.attributes).map(([k, v]) => [k, String(v)])) : {};
3320
4710
  if (typeof contact.userId === "string") attributes.userId = contact.userId;
3321
4711
  state.contacts.insert(contact.id, {
3322
4712
  id: contact.id,
@@ -3324,14 +4714,14 @@ var adminRoutes = (runtime) => ({
3324
4714
  attributes
3325
4715
  });
3326
4716
  }
3327
- return json3(200, { contacts: state.contacts.list({ order: "oldest" }).map((r) => r.value.id) });
4717
+ return json5(200, { contacts: state.contacts.list({ order: "oldest" }).map((r) => r.value.id) });
3328
4718
  },
3329
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
4719
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
3330
4720
  "PUT /settings": ({ body, namespace }) => {
3331
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
4721
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
3332
4722
  const patch = {};
3333
4723
  if (Array.isArray(body.workspaces)) patch.workspaces = body.workspaces.map(String);
3334
- if (isRecord4(body.legacyEnvironmentIds)) {
4724
+ if (isRecord5(body.legacyEnvironmentIds)) {
3335
4725
  patch.legacyEnvironmentIds = Object.fromEntries(
3336
4726
  Object.entries(body.legacyEnvironmentIds).map(([k, v]) => [k, String(v)])
3337
4727
  );
@@ -3339,7 +4729,7 @@ var adminRoutes = (runtime) => ({
3339
4729
  if (Array.isArray(body.apiKeys)) patch.apiKeys = body.apiKeys.map(String);
3340
4730
  if (typeof body.webhookId === "string") patch.webhookId = body.webhookId;
3341
4731
  if (typeof body.contactsEnabled === "boolean") patch.contactsEnabled = body.contactsEnabled;
3342
- return json3(200, runtime.instance(namespace).state.update(patch));
4732
+ return json5(200, runtime.instance(namespace).state.update(patch));
3343
4733
  }
3344
4734
  });
3345
4735
  var formbricksCredential = (request) => {
@@ -4006,4 +5396,4 @@ export {
4006
5396
  formbricksError,
4007
5397
  FormbricksAPI
4008
5398
  };
4009
- //# sourceMappingURL=chunk-JEJVVA5B.js.map
5399
+ //# sourceMappingURL=chunk-GPMHAIYZ.js.map