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