@crvouga/mockingbird-service-posthog 1.3.0 → 1.5.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;
@@ -538,10 +540,10 @@ var OpenAPIReferenceError = class extends Error {
538
540
  };
539
541
  var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
540
542
  var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
541
- var resolveRef = (document2, ref) => {
543
+ var resolveRef = (document3, ref) => {
542
544
  if (!ref.startsWith("#/"))
543
545
  throw new OpenAPIReferenceError(ref);
544
- let cursor = document2;
546
+ let cursor = document3;
545
547
  for (const raw of ref.slice(2).split("/")) {
546
548
  const segment = unescapePointer(raw);
547
549
  if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
@@ -553,14 +555,14 @@ var resolveRef = (document2, ref) => {
553
555
  throw new OpenAPIReferenceError(ref);
554
556
  return cursor;
555
557
  };
556
- var deref = (document2, value) => {
558
+ var deref = (document3, value) => {
557
559
  let current = value;
558
560
  const seen = /* @__PURE__ */ new Set();
559
561
  while (isReference(current)) {
560
562
  if (seen.has(current.$ref))
561
563
  throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
562
564
  seen.add(current.$ref);
563
- current = resolveRef(document2, current.$ref);
565
+ current = resolveRef(document3, current.$ref);
564
566
  }
565
567
  return current;
566
568
  };
@@ -578,36 +580,36 @@ var HTTP_METHODS = [
578
580
  ];
579
581
 
580
582
  // ../../openapi/core/dist/document.js
581
- var mergeParameters = (document2, item, own) => {
583
+ var mergeParameters = (document3, item, own) => {
582
584
  const merged = /* @__PURE__ */ new Map();
583
585
  for (const raw of item.parameters ?? []) {
584
- const parameter = deref(document2, raw);
586
+ const parameter = deref(document3, raw);
585
587
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
586
588
  }
587
589
  for (const raw of own ?? []) {
588
- const parameter = deref(document2, raw);
590
+ const parameter = deref(document3, raw);
589
591
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
590
592
  }
591
593
  return [...merged.values()];
592
594
  };
593
- var listOperations = (document2) => {
595
+ var listOperations = (document3) => {
594
596
  const operations = [];
595
- for (const [path, item] of Object.entries(document2.paths)) {
597
+ for (const [path, item] of Object.entries(document3.paths)) {
596
598
  for (const method of HTTP_METHODS) {
597
599
  const operation = item[method];
598
600
  if (operation?.operationId === void 0)
599
601
  continue;
600
602
  const responses = {};
601
603
  for (const [status, response] of Object.entries(operation.responses)) {
602
- responses[status] = deref(document2, response);
604
+ responses[status] = deref(document3, response);
603
605
  }
604
606
  operations.push({
605
607
  operationId: operation.operationId,
606
608
  method,
607
609
  path,
608
610
  operation,
609
- parameters: mergeParameters(document2, item, operation.parameters),
610
- requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
611
+ parameters: mergeParameters(document3, item, operation.parameters),
612
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document3, operation.requestBody),
611
613
  responses
612
614
  });
613
615
  }
@@ -1151,6 +1153,1737 @@ var clearNamespace = (sqlite, namespace) => {
1151
1153
  });
1152
1154
  };
1153
1155
 
1156
+ // ../../ui/dist/reset.js
1157
+ var CSS_RESET = `*,
1158
+ *::before,
1159
+ *::after {
1160
+ box-sizing: border-box;
1161
+ margin: 0;
1162
+ padding: 0;
1163
+ }
1164
+
1165
+ * {
1166
+ scrollbar-width: thin;
1167
+ scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;
1168
+ }
1169
+
1170
+ *::-webkit-scrollbar {
1171
+ width: 12px;
1172
+ height: 12px;
1173
+ }
1174
+
1175
+ *::-webkit-scrollbar-track,
1176
+ *::-webkit-scrollbar-corner {
1177
+ background: Canvas;
1178
+ }
1179
+
1180
+ *::-webkit-scrollbar-thumb {
1181
+ background: color-mix(in srgb, CanvasText 35%, Canvas);
1182
+ border: 3px solid Canvas;
1183
+ border-radius: 999px;
1184
+ }
1185
+
1186
+ html {
1187
+ hanging-punctuation: first allow-end last;
1188
+ -webkit-text-size-adjust: none;
1189
+ text-size-adjust: none;
1190
+ tab-size: 4;
1191
+ font-family:
1192
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI",
1193
+ "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
1194
+ font-size: 16px;
1195
+ line-height: 1.5;
1196
+ -webkit-font-smoothing: antialiased;
1197
+ -moz-osx-font-smoothing: grayscale;
1198
+ text-rendering: optimizeLegibility;
1199
+ -webkit-tap-highlight-color: transparent;
1200
+ scroll-behavior: smooth;
1201
+ background: Canvas;
1202
+ color: CanvasText;
1203
+ }
1204
+
1205
+ body {
1206
+ min-height: 100svh;
1207
+ line-height: 1.5;
1208
+ background: Canvas;
1209
+ color: CanvasText;
1210
+ }
1211
+
1212
+ h1 {
1213
+ font-size: 2em;
1214
+ }
1215
+
1216
+ h2 {
1217
+ font-size: 1.5em;
1218
+ }
1219
+
1220
+ h3 {
1221
+ font-size: 1.17em;
1222
+ }
1223
+
1224
+ h4 {
1225
+ font-size: 1em;
1226
+ }
1227
+
1228
+ h5 {
1229
+ font-size: 0.83em;
1230
+ }
1231
+
1232
+ h6 {
1233
+ font-size: 0.67em;
1234
+ }
1235
+
1236
+ h1,
1237
+ h2,
1238
+ h3,
1239
+ h4,
1240
+ h5,
1241
+ h6 {
1242
+ font-weight: 700;
1243
+ line-height: 1.2;
1244
+ text-wrap: balance;
1245
+ overflow-wrap: break-word;
1246
+ }
1247
+
1248
+ p,
1249
+ li,
1250
+ figcaption,
1251
+ dd,
1252
+ dt,
1253
+ blockquote {
1254
+ overflow-wrap: break-word;
1255
+ }
1256
+
1257
+ p,
1258
+ li,
1259
+ figcaption,
1260
+ blockquote {
1261
+ text-wrap: pretty;
1262
+ }
1263
+
1264
+ ul,
1265
+ ol,
1266
+ menu {
1267
+ list-style: none;
1268
+ }
1269
+
1270
+ a {
1271
+ color: inherit;
1272
+ text-decoration: underline;
1273
+ text-decoration-thickness: 1px;
1274
+ text-underline-offset: 0.15em;
1275
+ text-decoration-skip-ink: auto;
1276
+ }
1277
+
1278
+ b,
1279
+ strong {
1280
+ font-weight: 700;
1281
+ }
1282
+
1283
+ small {
1284
+ font-size: 0.875em;
1285
+ }
1286
+
1287
+ code,
1288
+ kbd,
1289
+ samp,
1290
+ pre {
1291
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1292
+ font-size: 1em;
1293
+ }
1294
+
1295
+ sub,
1296
+ sup {
1297
+ font-size: 75%;
1298
+ line-height: 0;
1299
+ position: relative;
1300
+ vertical-align: baseline;
1301
+ }
1302
+
1303
+ sub {
1304
+ bottom: -0.25em;
1305
+ }
1306
+
1307
+ sup {
1308
+ top: -0.5em;
1309
+ }
1310
+
1311
+ abbr[title] {
1312
+ text-decoration: underline dotted;
1313
+ text-underline-offset: 0.15em;
1314
+ }
1315
+
1316
+ mark {
1317
+ background: Mark;
1318
+ color: MarkText;
1319
+ }
1320
+
1321
+ hr {
1322
+ height: 0;
1323
+ border: 0;
1324
+ border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1325
+ color: inherit;
1326
+ }
1327
+
1328
+ img,
1329
+ picture,
1330
+ video,
1331
+ canvas {
1332
+ display: block;
1333
+ max-width: 100%;
1334
+ }
1335
+
1336
+ img,
1337
+ video {
1338
+ height: auto;
1339
+ }
1340
+
1341
+ svg {
1342
+ overflow: hidden;
1343
+ }
1344
+
1345
+ iframe {
1346
+ border: 0;
1347
+ max-width: 100%;
1348
+ }
1349
+
1350
+ table {
1351
+ border-collapse: collapse;
1352
+ border-spacing: 0;
1353
+ }
1354
+
1355
+ fieldset {
1356
+ border: 0;
1357
+ min-inline-size: 0;
1358
+ }
1359
+
1360
+ legend {
1361
+ padding: 0;
1362
+ }
1363
+
1364
+ button,
1365
+ input,
1366
+ select,
1367
+ textarea,
1368
+ optgroup {
1369
+ font: inherit;
1370
+ letter-spacing: inherit;
1371
+ color: inherit;
1372
+ margin: 0;
1373
+ vertical-align: middle;
1374
+ }
1375
+
1376
+ button,
1377
+ input[type="button"],
1378
+ input[type="submit"],
1379
+ input[type="reset"] {
1380
+ appearance: none;
1381
+ background: none;
1382
+ border: 0;
1383
+ padding: 0;
1384
+ cursor: pointer;
1385
+ text-align: center;
1386
+ }
1387
+
1388
+ input,
1389
+ textarea,
1390
+ select {
1391
+ background-color: Canvas;
1392
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1393
+ border-radius: 0;
1394
+ padding: 0.5em 0.65em;
1395
+ }
1396
+
1397
+ input[type="checkbox"],
1398
+ input[type="radio"],
1399
+ input[type="range"],
1400
+ input[type="file"],
1401
+ input[type="color"],
1402
+ input[type="button"],
1403
+ input[type="submit"],
1404
+ input[type="reset"],
1405
+ input[type="image"],
1406
+ input[type="hidden"] {
1407
+ background: none;
1408
+ border: 0;
1409
+ padding: 0;
1410
+ border-radius: 0;
1411
+ }
1412
+
1413
+ input[type="checkbox"],
1414
+ input[type="radio"] {
1415
+ accent-color: CanvasText;
1416
+ }
1417
+
1418
+ input[type="search"] {
1419
+ appearance: none;
1420
+ background-color: Canvas;
1421
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1422
+ }
1423
+
1424
+ input[type="search"]::-webkit-search-decoration,
1425
+ input[type="search"]::-webkit-search-cancel-button,
1426
+ input[type="search"]::-webkit-search-results-button,
1427
+ input[type="search"]::-webkit-search-results-decoration {
1428
+ -webkit-appearance: none;
1429
+ display: none;
1430
+ }
1431
+
1432
+ input[type="number"] {
1433
+ appearance: textfield;
1434
+ background-color: Canvas;
1435
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1436
+ }
1437
+
1438
+ input[type="number"]::-webkit-inner-spin-button,
1439
+ input[type="number"]::-webkit-outer-spin-button {
1440
+ -webkit-appearance: none;
1441
+ margin: 0;
1442
+ }
1443
+
1444
+ textarea {
1445
+ resize: vertical;
1446
+ }
1447
+
1448
+ ::placeholder {
1449
+ opacity: 1;
1450
+ color: color-mix(in srgb, CanvasText 45%, transparent);
1451
+ }
1452
+
1453
+ :focus-visible {
1454
+ outline: 2px solid CanvasText;
1455
+ outline-offset: 2px;
1456
+ }
1457
+
1458
+ :focus:not(:focus-visible) {
1459
+ outline: none;
1460
+ }
1461
+
1462
+ :disabled,
1463
+ [disabled] {
1464
+ cursor: default;
1465
+ opacity: 0.6;
1466
+ }
1467
+
1468
+ label,
1469
+ summary,
1470
+ select,
1471
+ [role="button"] {
1472
+ cursor: pointer;
1473
+ }
1474
+
1475
+ summary {
1476
+ display: list-item;
1477
+ }
1478
+
1479
+ details {
1480
+ display: block;
1481
+ }
1482
+
1483
+ dialog {
1484
+ margin: auto;
1485
+ padding: 1rem;
1486
+ border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1487
+ background: Canvas;
1488
+ color: CanvasText;
1489
+ max-width: calc(100vw - 2rem);
1490
+ max-height: calc(100svh - 2rem);
1491
+ }
1492
+
1493
+ dialog:not([open]) {
1494
+ display: none;
1495
+ }
1496
+
1497
+ ::backdrop {
1498
+ background: color-mix(in srgb, CanvasText 40%, transparent);
1499
+ }
1500
+
1501
+ [hidden] {
1502
+ display: none !important;
1503
+ }
1504
+
1505
+ ::selection {
1506
+ background: Highlight;
1507
+ color: HighlightText;
1508
+ }
1509
+
1510
+ @media (prefers-reduced-motion: reduce) {
1511
+ *,
1512
+ *::before,
1513
+ *::after {
1514
+ animation-duration: 0.01ms !important;
1515
+ animation-iteration-count: 1 !important;
1516
+ transition-duration: 0.01ms !important;
1517
+ scroll-behavior: auto !important;
1518
+ }
1519
+ }
1520
+
1521
+ @media (pointer: coarse) {
1522
+ input,
1523
+ select,
1524
+ textarea {
1525
+ font-size: max(16px, 1em);
1526
+ }
1527
+ }`;
1528
+
1529
+ // ../core/dist/admin-client.js
1530
+ function isRecord2(value) {
1531
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1532
+ }
1533
+ function mountAdminBrand(doc, host, service, catalog) {
1534
+ const clip = (value, max) => {
1535
+ if (typeof value !== "string")
1536
+ return null;
1537
+ const trimmed = value.trim();
1538
+ if (trimmed === "")
1539
+ return null;
1540
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
1541
+ };
1542
+ const httpUrl = (value) => {
1543
+ if (typeof value !== "string" || value.length > 2e3)
1544
+ return null;
1545
+ try {
1546
+ const url = new URL(value);
1547
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1548
+ return null;
1549
+ return url.href;
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ };
1554
+ const hexColor = (value) => {
1555
+ if (typeof value !== "string")
1556
+ return null;
1557
+ const raw = value.trim();
1558
+ return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null;
1559
+ };
1560
+ const hostname = (value) => {
1561
+ try {
1562
+ return new URL(value).hostname.replace(/^www\./, "");
1563
+ } catch {
1564
+ return value;
1565
+ }
1566
+ };
1567
+ host.replaceChildren();
1568
+ host.hidden = true;
1569
+ if (!isRecord2(catalog) || !Object.hasOwn(catalog, service))
1570
+ return;
1571
+ const row = catalog[service];
1572
+ if (!isRecord2(row))
1573
+ return;
1574
+ const vendor = clip(row.vendor, 80);
1575
+ const website = httpUrl(row.website);
1576
+ const guide = httpUrl(row.guide);
1577
+ const docs = httpUrl(row.docs);
1578
+ const logo = httpUrl(row.logo);
1579
+ const color = hexColor(row.color);
1580
+ const description = clip(row.description, 280);
1581
+ if (vendor === null || website === null && guide === null && docs === null)
1582
+ return;
1583
+ const add = (node) => {
1584
+ host.append(node);
1585
+ return node;
1586
+ };
1587
+ if (logo !== null) {
1588
+ const img = doc.createElement("img");
1589
+ img.alt = "";
1590
+ img.src = logo;
1591
+ img.width = 16;
1592
+ img.height = 16;
1593
+ img.decoding = "async";
1594
+ img.referrerPolicy = "no-referrer";
1595
+ if (color !== null)
1596
+ img.style.borderColor = color;
1597
+ add(img);
1598
+ }
1599
+ const name = doc.createElement("span");
1600
+ name.className = "vendor-name";
1601
+ name.textContent = vendor;
1602
+ if (description !== null)
1603
+ name.title = description;
1604
+ add(name);
1605
+ const sep = () => {
1606
+ const node = doc.createElement("span");
1607
+ node.className = "vendor-sep";
1608
+ node.setAttribute("aria-hidden", "true");
1609
+ node.textContent = "\xB7";
1610
+ return node;
1611
+ };
1612
+ const link = (href, label, title) => {
1613
+ const node = doc.createElement("a");
1614
+ node.className = "vendor-link";
1615
+ node.href = href;
1616
+ node.target = "_blank";
1617
+ node.rel = "noopener noreferrer";
1618
+ node.referrerPolicy = "no-referrer";
1619
+ node.textContent = label;
1620
+ node.title = title;
1621
+ return node;
1622
+ };
1623
+ if (website !== null) {
1624
+ add(sep());
1625
+ add(link(website, hostname(website), `${vendor} website`));
1626
+ }
1627
+ if (guide !== null) {
1628
+ add(sep());
1629
+ add(link(guide, "Docs", `Docs for ${vendor}`));
1630
+ }
1631
+ if (docs !== null) {
1632
+ add(sep());
1633
+ add(link(docs, "API", `${vendor} API reference`));
1634
+ }
1635
+ host.removeAttribute("hidden");
1636
+ host.hidden = false;
1637
+ }
1638
+ function startAdminBrand(env) {
1639
+ const requested = env.params.get("brands");
1640
+ let brandsUrl = env.brandsUrl;
1641
+ if (requested) {
1642
+ try {
1643
+ const url = new URL(requested, env.location.href);
1644
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]" || url.origin === env.location.origin;
1645
+ if ((url.protocol === "https:" || url.protocol === "http:") && local)
1646
+ brandsUrl = url.href;
1647
+ } catch {
1648
+ brandsUrl = env.brandsUrl;
1649
+ }
1650
+ }
1651
+ const vendorHost = env.$("vendor");
1652
+ const brandRoot = env.document.querySelector("[data-mockingbird-admin]");
1653
+ const brandService = brandRoot?.getAttribute("data-service") || "";
1654
+ if (vendorHost === null)
1655
+ return;
1656
+ env.fetch(brandsUrl, {
1657
+ headers: { accept: "application/json" },
1658
+ signal: AbortSignal.timeout(5e3)
1659
+ }).then(async (response) => {
1660
+ if (!response.ok)
1661
+ return null;
1662
+ const catalog = await response.json();
1663
+ return catalog;
1664
+ }).then((catalog) => {
1665
+ mountAdminBrand(env.document, vendorHost, brandService, catalog);
1666
+ }).catch(() => {
1667
+ });
1668
+ }
1669
+ function faultPresetList(value) {
1670
+ if (!isRecord2(value))
1671
+ throw new Error("Fault presets response was not an object");
1672
+ if (!Object.hasOwn(value, "presets") || value.presets === void 0 || value.presets === null) {
1673
+ return { presets: [] };
1674
+ }
1675
+ if (!Array.isArray(value.presets))
1676
+ throw new Error("Fault presets response was not a list");
1677
+ return {
1678
+ presets: value.presets.flatMap((item) => {
1679
+ if (!isRecord2(item) || typeof item.name !== "string")
1680
+ return [];
1681
+ return [{ name: item.name }];
1682
+ })
1683
+ };
1684
+ }
1685
+ function bootAdmin(config) {
1686
+ const fieldKinds = ["string", "number", "boolean", "null", "object", "array", "unknown"];
1687
+ const sources = ["declared", "inferred", "mixed"];
1688
+ const isFieldKind = (value) => typeof value === "string" && fieldKinds.some((kind) => kind === value);
1689
+ const isSource = (value) => typeof value === "string" && sources.some((source) => source === value);
1690
+ const readJson2 = (text) => {
1691
+ const value = JSON.parse(text);
1692
+ return value;
1693
+ };
1694
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => {
1695
+ switch (char) {
1696
+ case "&":
1697
+ return "&amp;";
1698
+ case "<":
1699
+ return "&lt;";
1700
+ case ">":
1701
+ return "&gt;";
1702
+ case '"':
1703
+ return "&quot;";
1704
+ default:
1705
+ return "&#39;";
1706
+ }
1707
+ });
1708
+ const el = (id, kind) => {
1709
+ const node = document.getElementById(id);
1710
+ if (!(node instanceof kind))
1711
+ throw new Error(`admin shell is missing #${id}`);
1712
+ return node;
1713
+ };
1714
+ const errorMessage = (data, fallback) => {
1715
+ if (!isRecord2(data))
1716
+ return fallback;
1717
+ const error2 = data.error;
1718
+ if (!isRecord2(error2) || typeof error2.message !== "string" || error2.message === "") {
1719
+ return fallback;
1720
+ }
1721
+ return error2.message;
1722
+ };
1723
+ const requireList = (value, label) => {
1724
+ if (value === void 0 || value === null)
1725
+ return [];
1726
+ if (!Array.isArray(value))
1727
+ throw new Error(`${label} was not a list`);
1728
+ return value;
1729
+ };
1730
+ const state = {
1731
+ namespace: "default",
1732
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1733
+ view: "overview",
1734
+ collection: "",
1735
+ shape: null,
1736
+ route: null,
1737
+ editing: null
1738
+ };
1739
+ const standard = new Set(config.standardRoutes);
1740
+ const banner = el("banner", HTMLElement);
1741
+ const keyInput = el("admin-key", HTMLInputElement);
1742
+ keyInput.value = state.key;
1743
+ const params = new URLSearchParams(location.search);
1744
+ const queryKey = params.get("key");
1745
+ if (queryKey) {
1746
+ state.key = queryKey;
1747
+ keyInput.value = state.key;
1748
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
1749
+ params.delete("key");
1750
+ const next = params.toString();
1751
+ history.replaceState(null, "", location.pathname + (next ? `?${next}` : ""));
1752
+ }
1753
+ const queryNamespace = params.get("namespace");
1754
+ if (queryNamespace)
1755
+ state.namespace = queryNamespace;
1756
+ const showError = (error2) => {
1757
+ banner.textContent = error2 instanceof Error ? error2.message : String(error2);
1758
+ banner.classList.add("show");
1759
+ };
1760
+ const clearError = () => {
1761
+ banner.classList.remove("show");
1762
+ };
1763
+ const api = async (method, path, body) => {
1764
+ const headers = { accept: "application/json" };
1765
+ if (state.key !== "")
1766
+ headers[config.adminKeyHeader] = state.key;
1767
+ if (state.namespace !== "")
1768
+ headers["x-mockingbird-namespace"] = state.namespace;
1769
+ if (body !== void 0)
1770
+ headers["content-type"] = "application/json";
1771
+ const init = { method, headers };
1772
+ if (body !== void 0)
1773
+ init.body = JSON.stringify(body);
1774
+ const response = await fetch(config.adminPrefix + path, init);
1775
+ const text = await response.text();
1776
+ let data = null;
1777
+ if (text !== "") {
1778
+ try {
1779
+ data = readJson2(text);
1780
+ } catch {
1781
+ data = { raw: text };
1782
+ }
1783
+ }
1784
+ if (response.status === 401) {
1785
+ keyInput.focus();
1786
+ throw new Error(errorMessage(data, "Admin key required"));
1787
+ }
1788
+ if (!response.ok) {
1789
+ throw new Error(errorMessage(data, `${response.status} ${method} ${path}`));
1790
+ }
1791
+ return data;
1792
+ };
1793
+ const originGet = async (path) => {
1794
+ const response = await fetch(path, { headers: { accept: "application/json" } });
1795
+ if (!response.ok)
1796
+ throw new Error(`${response.status} ${path}`);
1797
+ const value = await response.json();
1798
+ return value;
1799
+ };
1800
+ const panelApi = {
1801
+ get: (path) => api("GET", path),
1802
+ send: (method, path, body) => api(method, path, body),
1803
+ namespace: () => state.namespace
1804
+ };
1805
+ const isPanelScript = (value) => typeof value === "function";
1806
+ const setTheme = (theme) => {
1807
+ if (theme)
1808
+ document.documentElement.dataset.theme = theme;
1809
+ else
1810
+ delete document.documentElement.dataset.theme;
1811
+ };
1812
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme");
1813
+ if (storedTheme)
1814
+ setTheme(storedTheme);
1815
+ el("theme", HTMLButtonElement).addEventListener("click", () => {
1816
+ const current = document.documentElement.dataset.theme;
1817
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
1818
+ const next = dark ? "light" : "dark";
1819
+ localStorage.setItem("mockingbird-admin-theme", next);
1820
+ setTheme(next);
1821
+ });
1822
+ const show = (view) => {
1823
+ state.view = view;
1824
+ for (const button of document.querySelectorAll("#nav button")) {
1825
+ if (!(button instanceof HTMLButtonElement))
1826
+ continue;
1827
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false");
1828
+ }
1829
+ for (const section of document.querySelectorAll("main .view")) {
1830
+ if (!(section instanceof HTMLElement))
1831
+ continue;
1832
+ section.hidden = section.id !== `view-${view}`;
1833
+ }
1834
+ };
1835
+ el("nav", HTMLElement).addEventListener("click", (event) => {
1836
+ const target = event.target;
1837
+ if (!(target instanceof Element))
1838
+ return;
1839
+ const button = target.closest("button[data-view]");
1840
+ if (!(button instanceof HTMLButtonElement))
1841
+ return;
1842
+ const view = button.dataset.view;
1843
+ if (view === void 0)
1844
+ return;
1845
+ show(view);
1846
+ refresh().catch(showError);
1847
+ });
1848
+ const cards = (items) => `<div class="grid">${items.map((item) => `<article class="card"><div class="k">${item.k}</div><div class="v">${item.v}</div></article>`).join("")}</div>`;
1849
+ const table = (columns, rows) => {
1850
+ if (rows.length === 0)
1851
+ return '<p class="empty">Nothing here yet.</p>';
1852
+ const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join("")}</tr>`;
1853
+ const body = rows.map((row) => {
1854
+ const cells = columns.map((column) => `<td data-label="${column.label}">${column.cell(row)}</td>`).join("");
1855
+ const attrs = "attrs" in row && typeof row.attrs === "string" ? row.attrs : "";
1856
+ return `<tr${attrs}>${cells}</tr>`;
1857
+ }).join("");
1858
+ return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`;
1859
+ };
1860
+ const preview = (value) => {
1861
+ const text = JSON.stringify(value) ?? "null";
1862
+ return esc(text.length > 180 ? `${text.slice(0, 180)}\u2026` : text);
1863
+ };
1864
+ const when = (epoch) => {
1865
+ const date = new Date(epoch);
1866
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString();
1867
+ };
1868
+ const clockCard = (epoch) => {
1869
+ const date = new Date(epoch);
1870
+ if (Number.isNaN(date.getTime()))
1871
+ return esc(String(epoch));
1872
+ const iso = date.toISOString();
1873
+ return `${esc(iso.slice(0, 10))}<span class="clock-time">${esc(iso.slice(11, 19))} UTC</span>`;
1874
+ };
1875
+ const decodeClock = (value) => {
1876
+ if (!isRecord2(value) || typeof value.now !== "number" || typeof value.offsetMs !== "number" || typeof value.frozen !== "boolean") {
1877
+ throw new Error("Clock response was not a clock");
1878
+ }
1879
+ return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen };
1880
+ };
1881
+ const decodeField = (value) => {
1882
+ if (!isRecord2(value) || typeof value.name !== "string" || !isFieldKind(value.kind)) {
1883
+ return void 0;
1884
+ }
1885
+ const field = {
1886
+ name: value.name,
1887
+ kind: value.kind,
1888
+ optional: value.optional === true
1889
+ };
1890
+ if (typeof value.description === "string")
1891
+ field.description = value.description;
1892
+ if (Array.isArray(value.fields)) {
1893
+ field.fields = value.fields.flatMap((item) => {
1894
+ const child = decodeField(item);
1895
+ return child === void 0 ? [] : [child];
1896
+ });
1897
+ }
1898
+ return field;
1899
+ };
1900
+ const decodeCollection = (value) => {
1901
+ if (!isRecord2(value) || typeof value.name !== "string")
1902
+ return void 0;
1903
+ const fields = Array.isArray(value.fields) ? value.fields.flatMap((item) => {
1904
+ const field = decodeField(item);
1905
+ return field === void 0 ? [] : [field];
1906
+ }) : [];
1907
+ const collection = {
1908
+ name: value.name,
1909
+ label: typeof value.label === "string" ? value.label : value.name,
1910
+ count: typeof value.count === "number" ? value.count : 0,
1911
+ source: isSource(value.source) ? value.source : "inferred",
1912
+ fields
1913
+ };
1914
+ if (typeof value.description === "string")
1915
+ collection.description = value.description;
1916
+ return collection;
1917
+ };
1918
+ const decodeState = (value) => {
1919
+ if (!isRecord2(value) || !Array.isArray(value.collections)) {
1920
+ throw new Error("State response has no collection list");
1921
+ }
1922
+ return {
1923
+ namespace: typeof value.namespace === "string" ? value.namespace : state.namespace,
1924
+ storageNamespace: typeof value.storageNamespace === "string" ? value.storageNamespace : "",
1925
+ collections: value.collections.flatMap((item) => {
1926
+ const collection = decodeCollection(item);
1927
+ return collection === void 0 ? [] : [collection];
1928
+ })
1929
+ };
1930
+ };
1931
+ const decodeRecords = (value) => requireList(isRecord2(value) ? value.records : void 0, "Records").flatMap((item) => {
1932
+ if (!isRecord2(item) || typeof item.id !== "string")
1933
+ return [];
1934
+ return [
1935
+ {
1936
+ id: item.id,
1937
+ seq: typeof item.seq === "number" ? item.seq : 0,
1938
+ value: item.value,
1939
+ attrs: ` class="clickable" data-id="${esc(item.id)}"`
1940
+ }
1941
+ ];
1942
+ });
1943
+ const textOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : "";
1944
+ const decodeJournal = (value) => requireList(isRecord2(value) ? value.requests : void 0, "Journal").flatMap((item) => {
1945
+ if (!isRecord2(item))
1946
+ return [];
1947
+ return [
1948
+ {
1949
+ at: textOf(item.at),
1950
+ method: textOf(item.method),
1951
+ path: textOf(item.path),
1952
+ status: textOf(item.status),
1953
+ durationMs: textOf(item.durationMs),
1954
+ operationId: textOf(item.operationId)
1955
+ }
1956
+ ];
1957
+ });
1958
+ const decodeFaults = (value) => requireList(isRecord2(value) ? value.faults : void 0, "Faults").flatMap((item) => {
1959
+ if (!isRecord2(item))
1960
+ return [];
1961
+ return [
1962
+ {
1963
+ id: textOf(item.id),
1964
+ method: typeof item.method === "string" ? item.method : void 0,
1965
+ pathPrefix: typeof item.pathPrefix === "string" ? item.pathPrefix : void 0,
1966
+ operationId: typeof item.operationId === "string" ? item.operationId : void 0,
1967
+ status: typeof item.status === "number" ? item.status : void 0,
1968
+ effect: typeof item.effect === "string" ? item.effect : void 0,
1969
+ drop: typeof item.drop === "boolean" ? item.drop : void 0,
1970
+ latencyMs: typeof item.latencyMs === "number" ? item.latencyMs : void 0
1971
+ }
1972
+ ];
1973
+ });
1974
+ const loadNamespaces = async () => {
1975
+ const data = await api("GET", "/namespaces");
1976
+ const select = el("namespace", HTMLSelectElement);
1977
+ const listed = requireList(isRecord2(data) ? data.namespaces : void 0, "Namespaces");
1978
+ const fallback = isRecord2(data) && typeof data.default === "string" && data.default !== "" ? data.default : "default";
1979
+ const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice();
1980
+ if (!names.includes(state.namespace))
1981
+ names.unshift(state.namespace);
1982
+ select.innerHTML = names.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join("");
1983
+ select.value = state.namespace;
1984
+ };
1985
+ const renderOverview = async () => {
1986
+ const [health, shape, clock, journal] = await Promise.all([
1987
+ originGet("/health"),
1988
+ api("GET", "/state"),
1989
+ api("GET", "/clock"),
1990
+ api("GET", "/requests?limit=8")
1991
+ ]);
1992
+ if (!isRecord2(health))
1993
+ throw new Error("Health response was not an object");
1994
+ const decoded2 = decodeState(shape);
1995
+ state.shape = decoded2;
1996
+ const time = decodeClock(clock);
1997
+ el("overview-cards", HTMLElement).innerHTML = cards([
1998
+ {
1999
+ k: "Service",
2000
+ v: esc(typeof health.service === "string" && health.service !== "" ? health.service : config.service)
2001
+ },
2002
+ {
2003
+ k: "Status",
2004
+ v: esc(typeof health.status === "string" && health.status !== "" ? health.status : "ok")
2005
+ },
2006
+ { k: "Namespace", v: esc(state.namespace) },
2007
+ { k: "Collections", v: String(decoded2.collections.length) },
2008
+ {
2009
+ k: "Records",
2010
+ v: String(decoded2.collections.reduce((sum, item) => sum + item.count, 0))
2011
+ },
2012
+ { k: "Clock", v: clockCard(time.now) }
2013
+ ]);
2014
+ el("overview-requests", HTMLElement).innerHTML = table([
2015
+ { label: "Method", cell: (row) => esc(row.method) },
2016
+ { label: "Path", cell: (row) => esc(row.path) },
2017
+ {
2018
+ label: "Status",
2019
+ cell: (row) => `<span class="status-${row.status.charAt(0)}">${esc(row.status)}</span>`
2020
+ },
2021
+ { label: "Operation", cell: (row) => esc(row.operationId) }
2022
+ ], decodeJournal(journal));
2023
+ };
2024
+ const schemaChips = (collection) => {
2025
+ if (collection.fields.length === 0) {
2026
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>';
2027
+ }
2028
+ return `<div class="chips">${collection.fields.map((field) => `<span class="chip">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? "?" : ""}</i></span>`).join("")}</div>`;
2029
+ };
2030
+ const renderState = async () => {
2031
+ const shape = decodeState(await api("GET", "/state"));
2032
+ state.shape = shape;
2033
+ const host = el("collections", HTMLElement);
2034
+ if (shape.collections.length === 0) {
2035
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>';
2036
+ el("schema", HTMLElement).innerHTML = "";
2037
+ el("records", HTMLElement).innerHTML = "";
2038
+ return;
2039
+ }
2040
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2041
+ const first = shape.collections[0];
2042
+ if (first === void 0)
2043
+ return;
2044
+ state.collection = first.name;
2045
+ }
2046
+ host.innerHTML = shape.collections.map((item) => `<button type="button" class="collection" data-collection="${esc(item.name)}" aria-current="${item.name === state.collection ? "true" : "false"}"><strong>${esc(item.label)}</strong><small>${esc(item.count)} \xB7 ${esc(item.source)}</small></button>`).join("");
2047
+ const selected = shape.collections.find((item) => item.name === state.collection);
2048
+ if (selected === void 0)
2049
+ return;
2050
+ const description = selected.description ? `<p class="lede">${esc(selected.description)}</p>` : "";
2051
+ el("schema", HTMLElement).innerHTML = `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`;
2052
+ const page = await api("GET", `/state/${encodeURIComponent(state.collection)}?limit=50`);
2053
+ el("records", HTMLElement).innerHTML = table([
2054
+ { label: "Id", cell: (row) => `<code>${esc(row.id)}</code>` },
2055
+ { label: "Seq", cell: (row) => esc(row.seq) },
2056
+ { label: "Value", cell: (row) => preview(row.value) }
2057
+ ], decodeRecords(page));
2058
+ };
2059
+ const renderClock = async () => {
2060
+ const clock = decodeClock(await api("GET", "/clock"));
2061
+ el("clock-readout", HTMLElement).innerHTML = `<div class="k">Now</div><div class="v">${esc(when(clock.now))}</div><p>${esc(clock.now)} ms \xB7 offset ${esc(clock.offsetMs)} ms ${clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>"}</p>`;
2062
+ const freeze = el("freeze", HTMLButtonElement);
2063
+ freeze.textContent = clock.frozen ? "Unfreeze" : "Freeze";
2064
+ freeze.dataset.frozen = clock.frozen ? "1" : "0";
2065
+ };
2066
+ const renderFaults = async () => {
2067
+ const [faults, presets] = await Promise.all([
2068
+ api("GET", "/faults"),
2069
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2070
+ ]);
2071
+ const select = el("fault-preset", HTMLSelectElement);
2072
+ const current = select.value;
2073
+ const list = faultPresetList(presets).presets;
2074
+ select.innerHTML = `<option value="">Custom rule</option>${list.map((preset) => `<option value="${esc(preset.name)}">${esc(preset.name)}</option>`).join("")}`;
2075
+ select.value = current;
2076
+ el("fault-list", HTMLElement).innerHTML = table([
2077
+ { label: "Id", cell: (row) => esc(row.id) },
2078
+ {
2079
+ label: "Match",
2080
+ cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter((part) => Boolean(part)).join(" ") || "all")
2081
+ },
2082
+ {
2083
+ label: "Effect",
2084
+ cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || ""))
2085
+ }
2086
+ ], decodeFaults(faults));
2087
+ };
2088
+ const renderJournal = async () => {
2089
+ const journal = await api("GET", "/requests?limit=100");
2090
+ el("journal", HTMLElement).innerHTML = table([
2091
+ { label: "When", cell: (row) => esc(row.at) },
2092
+ { label: "Method", cell: (row) => esc(row.method) },
2093
+ { label: "Path", cell: (row) => esc(row.path) },
2094
+ { label: "Status", cell: (row) => esc(row.status) },
2095
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2096
+ ], decodeJournal(journal));
2097
+ };
2098
+ const renderRoutes = async () => {
2099
+ const data = await api("GET", "/");
2100
+ if (!isRecord2(data))
2101
+ throw new Error("Route list was not an object");
2102
+ const routes = requireList(data.routes, "Routes").map((route) => String(route));
2103
+ el("route-list", HTMLElement).innerHTML = routes.map((route) => {
2104
+ const extra = standard.has(route) ? "" : " <span class='badge'>extension</span>";
2105
+ const parts = route.split(" ");
2106
+ const method = parts[0] ?? "";
2107
+ const path = parts.slice(1).join(" ");
2108
+ return `<div class="route"><span class="method">${esc(method)}</span><span>${esc(path)}${extra}</span><button class="btn" type="button" data-route="${esc(route)}">Use</button></div>`;
2109
+ }).join("");
2110
+ };
2111
+ const renderers = {
2112
+ overview: renderOverview,
2113
+ state: renderState,
2114
+ clock: renderClock,
2115
+ faults: renderFaults,
2116
+ journal: renderJournal,
2117
+ routes: renderRoutes
2118
+ };
2119
+ async function refresh() {
2120
+ clearError();
2121
+ const render = renderers[state.view];
2122
+ if (render)
2123
+ await render();
2124
+ }
2125
+ el("namespace", HTMLSelectElement).addEventListener("change", () => {
2126
+ state.namespace = el("namespace", HTMLSelectElement).value;
2127
+ refresh().catch(showError);
2128
+ });
2129
+ keyInput.addEventListener("change", () => {
2130
+ state.key = keyInput.value.trim();
2131
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2132
+ refresh().catch(showError);
2133
+ });
2134
+ el("refresh", HTMLButtonElement).addEventListener("click", () => {
2135
+ refresh().catch(showError);
2136
+ });
2137
+ el("collections", HTMLElement).addEventListener("click", (event) => {
2138
+ const target = event.target;
2139
+ if (!(target instanceof Element))
2140
+ return;
2141
+ const button = target.closest("[data-collection]");
2142
+ if (!(button instanceof HTMLElement))
2143
+ return;
2144
+ const collection = button.dataset.collection;
2145
+ if (collection === void 0)
2146
+ return;
2147
+ state.collection = collection;
2148
+ renderState().catch(showError);
2149
+ });
2150
+ el("records", HTMLElement).addEventListener("click", (event) => {
2151
+ const target = event.target;
2152
+ if (!(target instanceof Element))
2153
+ return;
2154
+ const row = target.closest("[data-id]");
2155
+ if (!(row instanceof HTMLElement))
2156
+ return;
2157
+ const id = row.dataset.id;
2158
+ if (id === void 0)
2159
+ return;
2160
+ openEditor(id).catch(showError);
2161
+ });
2162
+ const editor = el("editor", HTMLDialogElement);
2163
+ const editorId = el("editor-id", HTMLInputElement);
2164
+ const editorValue = el("editor-value", HTMLTextAreaElement);
2165
+ const editorDelete = el("editor-delete", HTMLButtonElement);
2166
+ async function openEditor(id) {
2167
+ state.editing = id;
2168
+ el("editor-title", HTMLElement).textContent = id ? "Edit record" : "New record";
2169
+ editorId.value = id ?? "";
2170
+ editorId.readOnly = id !== null;
2171
+ editorDelete.hidden = id === null;
2172
+ if (id) {
2173
+ const record = await api("GET", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`);
2174
+ if (!isRecord2(record))
2175
+ throw new Error("Record response was not an object");
2176
+ editorValue.value = JSON.stringify(record.value, null, 2) ?? "";
2177
+ } else {
2178
+ editorValue.value = "{\n \n}";
2179
+ }
2180
+ editor.showModal();
2181
+ }
2182
+ el("new-record", HTMLButtonElement).addEventListener("click", () => {
2183
+ openEditor(null).catch(showError);
2184
+ });
2185
+ el("editor-form", HTMLFormElement).addEventListener("submit", (event) => {
2186
+ const submitter = event.submitter;
2187
+ if (!(submitter instanceof HTMLButtonElement) || submitter.value !== "save")
2188
+ return;
2189
+ event.preventDefault();
2190
+ let value;
2191
+ try {
2192
+ value = readJson2(editorValue.value);
2193
+ } catch {
2194
+ showError(new Error("Value is not JSON"));
2195
+ return;
2196
+ }
2197
+ const id = editorId.value.trim();
2198
+ const path = `/state/${encodeURIComponent(state.collection)}`;
2199
+ const request = state.editing ? api("PUT", `${path}/${encodeURIComponent(id)}`, { value }) : api("POST", path, { id: id || void 0, value });
2200
+ request.then(() => {
2201
+ editor.close();
2202
+ return renderState();
2203
+ }).catch(showError);
2204
+ });
2205
+ editorDelete.addEventListener("click", () => {
2206
+ const id = state.editing;
2207
+ if (!id)
2208
+ return;
2209
+ api("DELETE", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`).then(() => {
2210
+ editor.close();
2211
+ return renderState();
2212
+ }).catch(showError);
2213
+ });
2214
+ for (const button of document.querySelectorAll("[data-advance]")) {
2215
+ if (!(button instanceof HTMLButtonElement))
2216
+ continue;
2217
+ button.addEventListener("click", () => {
2218
+ const raw = button.dataset.advance;
2219
+ if (raw === void 0)
2220
+ return;
2221
+ api("POST", "/clock", { advance: Number(raw) }).then(() => renderClock()).catch(showError);
2222
+ });
2223
+ }
2224
+ el("freeze", HTMLButtonElement).addEventListener("click", () => {
2225
+ const frozen = el("freeze", HTMLButtonElement).dataset.frozen === "1";
2226
+ api("POST", "/clock", { freeze: !frozen }).then(() => renderClock()).catch(showError);
2227
+ });
2228
+ el("clock-reset", HTMLButtonElement).addEventListener("click", () => {
2229
+ api("POST", "/clock", { reset: true }).then(() => renderClock()).catch(showError);
2230
+ });
2231
+ el("clock-set", HTMLFormElement).addEventListener("submit", (event) => {
2232
+ event.preventDefault();
2233
+ const raw = el("clock-instant", HTMLInputElement).value.trim();
2234
+ const set = /^-?\d+$/.test(raw) ? Number(raw) : raw;
2235
+ api("POST", "/clock", { set }).then(() => renderClock()).catch(showError);
2236
+ });
2237
+ el("fault-form", HTMLFormElement).addEventListener("submit", (event) => {
2238
+ event.preventDefault();
2239
+ const preset = el("fault-preset", HTMLSelectElement).value;
2240
+ if (preset !== "") {
2241
+ api("POST", "/faults", { preset }).then(() => renderFaults()).catch(showError);
2242
+ return;
2243
+ }
2244
+ const status = Number(el("fault-status", HTMLInputElement).value);
2245
+ if (!Number.isFinite(status)) {
2246
+ showError(new Error("Status must be a number, or choose a preset"));
2247
+ return;
2248
+ }
2249
+ const path = el("fault-path", HTMLInputElement).value;
2250
+ const method = el("fault-method", HTMLInputElement).value;
2251
+ api("POST", "/faults", {
2252
+ status,
2253
+ ...path !== "" ? { pathPrefix: path } : {},
2254
+ ...method !== "" ? { method } : {}
2255
+ }).then(() => renderFaults()).catch(showError);
2256
+ });
2257
+ el("fault-clear", HTMLButtonElement).addEventListener("click", () => {
2258
+ api("DELETE", "/faults").then(() => renderFaults()).catch(showError);
2259
+ });
2260
+ el("journal-clear", HTMLButtonElement).addEventListener("click", () => {
2261
+ api("DELETE", "/requests").then(() => renderJournal()).catch(showError);
2262
+ });
2263
+ el("route-list", HTMLElement).addEventListener("click", (event) => {
2264
+ const target = event.target;
2265
+ if (!(target instanceof Element))
2266
+ return;
2267
+ const button = target.closest("[data-route]");
2268
+ if (!(button instanceof HTMLElement))
2269
+ return;
2270
+ const route = button.dataset.route;
2271
+ if (route === void 0)
2272
+ return;
2273
+ state.route = route;
2274
+ el("route-title", HTMLElement).textContent = route;
2275
+ const method = route.split(" ")[0] ?? "";
2276
+ el("route-body", HTMLTextAreaElement).disabled = method === "GET" || method === "DELETE";
2277
+ });
2278
+ el("route-form", HTMLFormElement).addEventListener("submit", (event) => {
2279
+ event.preventDefault();
2280
+ const send = async () => {
2281
+ if (state.route === null)
2282
+ throw new Error("Choose a route first");
2283
+ const parts = state.route.split(" ");
2284
+ const method = parts[0];
2285
+ const path = parts.slice(1).join(" ");
2286
+ if (method === void 0)
2287
+ throw new Error("Choose a route first");
2288
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_match, key) => prompt(`Value for ${key}`) || "");
2289
+ let body;
2290
+ const routeBody = el("route-body", HTMLTextAreaElement);
2291
+ if (method !== "GET" && method !== "DELETE" && routeBody.value.trim() !== "") {
2292
+ try {
2293
+ body = readJson2(routeBody.value);
2294
+ } catch {
2295
+ throw new Error("Body is not JSON");
2296
+ }
2297
+ }
2298
+ const data = await api(method, concrete, body);
2299
+ el("route-result", HTMLElement).textContent = JSON.stringify(data, null, 2);
2300
+ };
2301
+ send().catch(showError);
2302
+ });
2303
+ const decodePanel = (value) => {
2304
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2305
+ return void 0;
2306
+ }
2307
+ const panel = {
2308
+ id: value.id,
2309
+ title: value.title,
2310
+ description: typeof value.description === "string" ? value.description : "",
2311
+ html: typeof value.html === "string" ? value.html : ""
2312
+ };
2313
+ if (typeof value.script === "string")
2314
+ panel.script = value.script;
2315
+ return panel;
2316
+ };
2317
+ const mountPanels = (panels) => {
2318
+ const nav = el("nav", HTMLElement);
2319
+ const views = el("views", HTMLElement);
2320
+ for (const panel of panels) {
2321
+ const button = document.createElement("button");
2322
+ button.type = "button";
2323
+ button.dataset.view = panel.id;
2324
+ button.textContent = panel.title;
2325
+ nav.append(button);
2326
+ const section = document.createElement("section");
2327
+ section.className = "view";
2328
+ section.id = `view-${panel.id}`;
2329
+ section.hidden = true;
2330
+ const title = document.createElement("h2");
2331
+ title.textContent = panel.title;
2332
+ const lede = document.createElement("p");
2333
+ lede.className = "lede";
2334
+ lede.textContent = panel.description;
2335
+ const body = document.createElement("div");
2336
+ body.className = "panel-body";
2337
+ body.id = `panel-${panel.id}`;
2338
+ body.innerHTML = panel.html;
2339
+ section.append(title, lede, body);
2340
+ views.append(section);
2341
+ if (panel.script === void 0)
2342
+ continue;
2343
+ try {
2344
+ const compiled = new Function("root", "api", panel.script);
2345
+ if (!isPanelScript(compiled))
2346
+ throw new Error("panel script did not compile");
2347
+ compiled(body, panelApi);
2348
+ } catch (error2) {
2349
+ const note = document.createElement("p");
2350
+ note.className = "banner show";
2351
+ note.textContent = error2 instanceof Error ? error2.message : String(error2);
2352
+ body.append(note);
2353
+ }
2354
+ }
2355
+ };
2356
+ startAdminBrand({
2357
+ document,
2358
+ $: (id) => document.getElementById(id),
2359
+ params,
2360
+ location: { href: location.href, origin: location.origin },
2361
+ fetch,
2362
+ brandsUrl: config.brandsUrl
2363
+ });
2364
+ loadNamespaces().then(() => api("GET", "/ui/manifest")).then((manifest) => {
2365
+ const panels = requireList(isRecord2(manifest) ? manifest.panels : void 0, "Panels").flatMap((panel) => {
2366
+ const decoded2 = decodePanel(panel);
2367
+ return decoded2 === void 0 ? [] : [decoded2];
2368
+ });
2369
+ mountPanels(panels);
2370
+ return refresh();
2371
+ }).catch(showError);
2372
+ }
2373
+ var clientPrelude = [isRecord2, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin].map((fn) => fn.toString()).join("\n");
2374
+ var adminClientSource = (config) => {
2375
+ const payload = JSON.stringify(config).replace(/</g, "\\u003c");
2376
+ return `<script>
2377
+ ${clientPrelude}
2378
+ bootAdmin(${payload});
2379
+ </script>`;
2380
+ };
2381
+
2382
+ // ../core/dist/surface.js
2383
+ var defineMock = (runtime) => runtime;
2384
+ var STANDARD_ADMIN_ROUTES = [
2385
+ "GET /",
2386
+ "POST /reset",
2387
+ "GET /namespaces",
2388
+ "GET /clock",
2389
+ "POST /clock",
2390
+ "GET /faults",
2391
+ "POST /faults",
2392
+ "DELETE /faults",
2393
+ "POST /snapshots",
2394
+ "POST /snapshots/:id/restore",
2395
+ "DELETE /snapshots/:id",
2396
+ "GET /timeline",
2397
+ "POST /checkpoints",
2398
+ "POST /branches/:name",
2399
+ "POST /branches/:name/checkout",
2400
+ "GET /requests",
2401
+ "DELETE /requests",
2402
+ "GET /metrics",
2403
+ "DELETE /metrics",
2404
+ "GET /credentials",
2405
+ "PUT /credentials",
2406
+ "DELETE /credentials",
2407
+ "GET /state",
2408
+ "GET /state/:collection",
2409
+ "GET /state/:collection/:id",
2410
+ "POST /state/:collection",
2411
+ "PUT /state/:collection/:id",
2412
+ "PATCH /state/:collection/:id",
2413
+ "DELETE /state/:collection/:id",
2414
+ "GET /ui",
2415
+ "GET /ui/",
2416
+ "GET /ui/manifest"
2417
+ ];
2418
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
2419
+ var assertAdminUi = (ui) => {
2420
+ if (!ui?.panels)
2421
+ return;
2422
+ const seen = /* @__PURE__ */ new Set();
2423
+ for (const panel of ui.panels) {
2424
+ if (!PANEL_ID.test(panel.id)) {
2425
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
2426
+ }
2427
+ if (seen.has(panel.id))
2428
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
2429
+ seen.add(panel.id);
2430
+ if (panel.title.trim() === "")
2431
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
2432
+ }
2433
+ };
2434
+
2435
+ // ../core/dist/admin-ui.js
2436
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
2437
+ switch (char) {
2438
+ case "&":
2439
+ return "&amp;";
2440
+ case "<":
2441
+ return "&lt;";
2442
+ case ">":
2443
+ return "&gt;";
2444
+ case '"':
2445
+ return "&quot;";
2446
+ default:
2447
+ return "&#39;";
2448
+ }
2449
+ });
2450
+ var ADMIN_BRANDS_URL = "https://mockingbird.chrisvouga.dev/brands.json";
2451
+ var renderAdminDocument = (service) => {
2452
+ const name = escapeHtml(service);
2453
+ const script = adminClientSource({
2454
+ standardRoutes: STANDARD_ADMIN_ROUTES,
2455
+ adminPrefix: ADMIN_PREFIX,
2456
+ adminKeyHeader: ADMIN_KEY_HEADER,
2457
+ brandsUrl: ADMIN_BRANDS_URL,
2458
+ service
2459
+ });
2460
+ return `<!DOCTYPE html>
2461
+ <html lang="en">
2462
+ <head>
2463
+ <meta charset="utf-8">
2464
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2465
+ <meta name="color-scheme" content="light dark">
2466
+ <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='2' fill='%2327272a'/%3E%3C/svg%3E">
2467
+ <title>${name} admin</title>
2468
+ <style>
2469
+ ${CSS_RESET}
2470
+ :root {
2471
+ color-scheme: light;
2472
+ --bg: #fafafa;
2473
+ --bg-elev: #ffffff;
2474
+ --bg-muted: #f4f4f5;
2475
+ --bg-inset: #f4f4f5;
2476
+ --line: #dedee3;
2477
+ --line-strong: #c4c4cc;
2478
+ --ink: #18181b;
2479
+ --muted: #62626b;
2480
+ --faint: #71717a;
2481
+ --accent: #27272a;
2482
+ --accent-ink: #ffffff;
2483
+ --accent-soft: #f4f4f5;
2484
+ --ok: #166534;
2485
+ --ok-soft: #f0fdf4;
2486
+ --warn: #a16207;
2487
+ --warn-soft: #fefce8;
2488
+ --err: #a82d32;
2489
+ --err-soft: #fef2f2;
2490
+ --shadow: none;
2491
+ --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2492
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
2493
+ --radius: 10px;
2494
+ --header: 56px;
2495
+ --nav: 200px;
2496
+ }
2497
+ :root[data-theme="dark"] {
2498
+ color-scheme: dark;
2499
+ --bg: #111113;
2500
+ --bg-elev: #19191c;
2501
+ --bg-muted: #242428;
2502
+ --bg-inset: #111113;
2503
+ --line: #36363c;
2504
+ --line-strong: #52525b;
2505
+ --ink: #f4f4f5;
2506
+ --muted: #a9a9b2;
2507
+ --faint: #71717a;
2508
+ --accent: #e4e4e7;
2509
+ --accent-ink: #18181b;
2510
+ --accent-soft: #242428;
2511
+ --ok: #86efac;
2512
+ --ok-soft: #14241b;
2513
+ --warn: #fde68a;
2514
+ --warn-soft: #2a2410;
2515
+ --err: #ffaaaa;
2516
+ --err-soft: #2c1516;
2517
+ --shadow: none;
2518
+ }
2519
+ @media (prefers-color-scheme: dark) {
2520
+ :root:not([data-theme="light"]) {
2521
+ color-scheme: dark;
2522
+ --bg: #111113;
2523
+ --bg-elev: #19191c;
2524
+ --bg-muted: #242428;
2525
+ --bg-inset: #111113;
2526
+ --line: #36363c;
2527
+ --line-strong: #52525b;
2528
+ --ink: #f4f4f5;
2529
+ --muted: #a9a9b2;
2530
+ --faint: #71717a;
2531
+ --accent: #e4e4e7;
2532
+ --accent-ink: #18181b;
2533
+ --accent-soft: #242428;
2534
+ --ok: #86efac;
2535
+ --ok-soft: #14241b;
2536
+ --warn: #fde68a;
2537
+ --warn-soft: #2a2410;
2538
+ --err: #ffaaaa;
2539
+ --err-soft: #2c1516;
2540
+ --shadow: none;
2541
+ }
2542
+ }
2543
+ /* Fill the viewport, then grow with the content so the background covers the scroll. */
2544
+ html { height: 100%; }
2545
+ body {
2546
+ margin: 0;
2547
+ min-height: 100%;
2548
+ display: flex;
2549
+ flex-direction: column;
2550
+ font-family: var(--sans);
2551
+ background: var(--bg);
2552
+ color: var(--ink);
2553
+ line-height: 1.45;
2554
+ padding-left: env(safe-area-inset-left);
2555
+ padding-right: env(safe-area-inset-right);
2556
+ -webkit-text-size-adjust: 100%;
2557
+ }
2558
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
2559
+ .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }
2560
+ header.top {
2561
+ position: sticky; top: 0; z-index: 5;
2562
+ display: flex; align-items: center; gap: 12px;
2563
+ min-height: var(--header); padding: 10px 16px;
2564
+ background: var(--bg-elev);
2565
+ border-bottom: 1px solid var(--line);
2566
+ min-width: 0; max-width: 100%;
2567
+ }
2568
+ .brand {
2569
+ display: flex; flex-flow: row wrap; align-items: center; gap: 14px;
2570
+ min-width: 0; max-width: 100%; margin-right: auto;
2571
+ }
2572
+ .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }
2573
+ .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }
2574
+ .brand-id span { color: var(--faint); font-size: 12px; }
2575
+ .vendor {
2576
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2577
+ min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);
2578
+ }
2579
+ .vendor[hidden] { display: none; }
2580
+ /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */
2581
+ .vendor img {
2582
+ width: 16px; height: 16px; padding: 2px; box-sizing: content-box;
2583
+ border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;
2584
+ }
2585
+ .vendor-name { color: var(--ink); font-weight: 600; }
2586
+ .vendor-sep { color: var(--faint); }
2587
+ .vendor-link { color: inherit; text-decoration: none; }
2588
+ .vendor-link:hover { color: var(--ink); text-decoration: underline; }
2589
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
2590
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
2591
+ label.field input, label.field select, .controls input[type="password"] {
2592
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
2593
+ padding: 7px 8px; min-height: 36px;
2594
+ }
2595
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
2596
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
2597
+ background: var(--bg-elev);
2598
+ }
2599
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
2600
+ .btn-quiet { background: transparent; }
2601
+ .btn-danger { color: var(--err); }
2602
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
2603
+ record or the full nav row would widen the page past the viewport. */
2604
+ .layout {
2605
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
2606
+ flex: 1 0 auto; min-width: 0;
2607
+ }
2608
+ nav.side {
2609
+ border-right: 1px solid var(--line); padding: 12px;
2610
+ display: flex; flex-direction: column; gap: 4px;
2611
+ background: var(--bg-elev);
2612
+ }
2613
+ nav.side button {
2614
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
2615
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
2616
+ }
2617
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
2618
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
2619
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
2620
+ .lede { margin: 0 0 16px; color: var(--muted); }
2621
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
2622
+ .card {
2623
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
2624
+ padding: 14px 16px; box-shadow: var(--shadow);
2625
+ }
2626
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
2627
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
2628
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
2629
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
2630
+ .collection {
2631
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
2632
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
2633
+ }
2634
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
2635
+ .collection small { display: block; color: var(--faint); }
2636
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
2637
+ .chip {
2638
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
2639
+ border-radius: 999px; padding: 4px 8px;
2640
+ }
2641
+ .chip i { color: var(--faint); font-style: normal; }
2642
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
2643
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
2644
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
2645
+ tr.clickable { cursor: pointer; }
2646
+ tr.clickable:hover { background: var(--bg-muted); }
2647
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
2648
+ pre {
2649
+ margin: 0; white-space: pre-wrap; word-break: break-word;
2650
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
2651
+ }
2652
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
2653
+ .banner {
2654
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
2655
+ background: var(--err-soft); color: var(--err);
2656
+ }
2657
+ .banner.show { display: block; }
2658
+ .empty { color: var(--muted); padding: 24px 8px; }
2659
+ dialog {
2660
+ border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);
2661
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: none;
2662
+ }
2663
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
2664
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
2665
+ textarea {
2666
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
2667
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
2668
+ font-family: var(--mono); font-size: 12px;
2669
+ }
2670
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
2671
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
2672
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
2673
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
2674
+ .status-2 { color: var(--ok); }
2675
+ .status-4, .status-5, .status-0 { color: var(--err); }
2676
+ .stack { display: flex; flex-direction: column; gap: 12px; }
2677
+ .route {
2678
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
2679
+ padding: 8px 0; border-bottom: 1px solid var(--line);
2680
+ }
2681
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
2682
+ @media (max-width: 800px) {
2683
+ header.top {
2684
+ align-items: stretch; flex-direction: column;
2685
+ padding-top: max(10px, env(safe-area-inset-top));
2686
+ }
2687
+ input, select, textarea { font-size: 16px; }
2688
+ .brand, .vendor, .controls { width: 100%; }
2689
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
2690
+ .layout { grid-template-columns: minmax(0, 1fr); }
2691
+ nav.side {
2692
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
2693
+ border-right: 0; border-bottom: 1px solid var(--line);
2694
+ padding: 8px;
2695
+ }
2696
+ nav.side button { white-space: nowrap; flex: none; }
2697
+ .split { grid-template-columns: minmax(0, 1fr); }
2698
+ main { padding: 14px; }
2699
+ table, thead, tbody, tr, th, td { display: block; }
2700
+ thead { display: none; }
2701
+ tr {
2702
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
2703
+ background: var(--bg-elev); min-width: 0;
2704
+ }
2705
+ td {
2706
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
2707
+ min-width: 0; overflow-wrap: anywhere;
2708
+ }
2709
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
2710
+ .route { grid-template-columns: 72px 1fr; }
2711
+ .route button { grid-column: 1 / -1; }
2712
+ }
2713
+ </style>
2714
+ </head>
2715
+ <body>
2716
+ <div class="app" data-service="${name}" data-mockingbird-admin>
2717
+ <header class="top">
2718
+ <div class="brand">
2719
+ <div class="brand-id">
2720
+ <strong>${name}</strong>
2721
+ <span>Admin</span>
2722
+ </div>
2723
+ <div class="vendor" id="vendor" hidden></div>
2724
+ </div>
2725
+ <div class="controls">
2726
+ <label class="field">Namespace
2727
+ <select id="namespace" aria-label="Namespace"></select>
2728
+ </label>
2729
+ <label class="field">Admin key
2730
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
2731
+ </label>
2732
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
2733
+ <button class="btn" id="refresh" type="button">Refresh</button>
2734
+ </div>
2735
+ </header>
2736
+ <div class="layout">
2737
+ <nav class="side" id="nav" aria-label="Admin sections">
2738
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
2739
+ <button type="button" data-view="state">State</button>
2740
+ <button type="button" data-view="clock">Clock</button>
2741
+ <button type="button" data-view="faults">Faults</button>
2742
+ <button type="button" data-view="journal">Journal</button>
2743
+ <button type="button" data-view="routes">Routes</button>
2744
+ </nav>
2745
+ <main id="views">
2746
+ <p class="banner" id="banner" role="alert"></p>
2747
+ <section class="view" id="view-overview">
2748
+ <h2>Overview</h2>
2749
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
2750
+ <div class="grid" id="overview-cards"></div>
2751
+ <h3>Recent requests</h3>
2752
+ <div id="overview-requests"></div>
2753
+ </section>
2754
+ <section class="view" id="view-state" hidden>
2755
+ <h2>State</h2>
2756
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
2757
+ <div class="split">
2758
+ <div id="collections"></div>
2759
+ <div>
2760
+ <div id="schema"></div>
2761
+ <div class="row-actions">
2762
+ <button class="btn-primary" id="new-record" type="button">New record</button>
2763
+ </div>
2764
+ <div id="records"></div>
2765
+ </div>
2766
+ </div>
2767
+ </section>
2768
+ <section class="view" id="view-clock" hidden>
2769
+ <h2>Clock</h2>
2770
+ <p class="lede">The clock every timestamp in this mock reads.</p>
2771
+ <div class="card" id="clock-readout"></div>
2772
+ <div class="row-actions">
2773
+ <button class="btn" type="button" data-advance="60000">+1m</button>
2774
+ <button class="btn" type="button" data-advance="900000">+15m</button>
2775
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
2776
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
2777
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
2778
+ <button class="btn" id="freeze" type="button">Freeze</button>
2779
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
2780
+ </div>
2781
+ <form id="clock-set" class="row-actions">
2782
+ <label class="field">Set instant
2783
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
2784
+ </label>
2785
+ <button class="btn-primary" type="submit">Set</button>
2786
+ </form>
2787
+ </section>
2788
+ <section class="view" id="view-faults" hidden>
2789
+ <h2>Faults</h2>
2790
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
2791
+ <form id="fault-form" class="card stack">
2792
+ <label class="field">Preset
2793
+ <select id="fault-preset"><option value="">Custom rule</option></select>
2794
+ </label>
2795
+ <label class="field">Status
2796
+ <input id="fault-status" inputmode="numeric" placeholder="503">
2797
+ </label>
2798
+ <label class="field">Path prefix
2799
+ <input id="fault-path" placeholder="/v1">
2800
+ </label>
2801
+ <label class="field">Method
2802
+ <input id="fault-method" placeholder="GET">
2803
+ </label>
2804
+ <div class="dialog-actions">
2805
+ <button class="btn-primary" type="submit">Add fault</button>
2806
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
2807
+ </div>
2808
+ </form>
2809
+ <div id="fault-list"></div>
2810
+ </section>
2811
+ <section class="view" id="view-journal" hidden>
2812
+ <h2>Journal</h2>
2813
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
2814
+ <div class="row-actions">
2815
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
2816
+ </div>
2817
+ <div id="journal"></div>
2818
+ </section>
2819
+ <section class="view" id="view-routes" hidden>
2820
+ <h2>Routes</h2>
2821
+ <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>
2822
+ <div id="route-list"></div>
2823
+ <form id="route-form" class="card stack">
2824
+ <strong id="route-title">Select a route</strong>
2825
+ <label class="field">JSON body
2826
+ <textarea id="route-body" placeholder="{ }"></textarea>
2827
+ </label>
2828
+ <div class="dialog-actions">
2829
+ <button class="btn-primary" type="submit">Send</button>
2830
+ </div>
2831
+ <pre id="route-result">Response will show here.</pre>
2832
+ </form>
2833
+ </section>
2834
+ </main>
2835
+ </div>
2836
+ </div>
2837
+ <dialog id="editor">
2838
+ <form method="dialog" id="editor-form">
2839
+ <strong id="editor-title">Record</strong>
2840
+ <label class="field">Id
2841
+ <input id="editor-id" required>
2842
+ </label>
2843
+ <label class="field">JSON value
2844
+ <textarea id="editor-value"></textarea>
2845
+ </label>
2846
+ <div class="dialog-actions">
2847
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
2848
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
2849
+ <button class="btn-primary" type="submit" value="save">Save</button>
2850
+ </div>
2851
+ </form>
2852
+ </dialog>
2853
+ ${script}
2854
+ </body>
2855
+ </html>`;
2856
+ };
2857
+ var htmlResponse = (body) => new Response(body, {
2858
+ status: 200,
2859
+ headers: {
2860
+ "content-type": "text/html; charset=utf-8",
2861
+ "cache-control": "no-store"
2862
+ }
2863
+ });
2864
+ var json2 = (body) => new Response(JSON.stringify(body), {
2865
+ status: 200,
2866
+ headers: { "content-type": "application/json; charset=utf-8" }
2867
+ });
2868
+ var adminUiRoutes = (service, ui) => {
2869
+ const shell = () => renderAdminDocument(service);
2870
+ const document3 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2871
+ return {
2872
+ "GET /ui": () => htmlResponse(document3()),
2873
+ "GET /ui/": () => htmlResponse(document3()),
2874
+ "GET /ui/manifest": () => json2({
2875
+ service,
2876
+ panels: (ui?.panels ?? []).map((panel) => ({
2877
+ id: panel.id,
2878
+ title: panel.title,
2879
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2880
+ html: panel.html,
2881
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2882
+ }))
2883
+ })
2884
+ };
2885
+ };
2886
+
1154
2887
  // ../../openapi/metadata/dist/types.js
1155
2888
  var EXTENSION_KEYS = {
1156
2889
  operation: "x-mockingbird",
@@ -1163,11 +2896,11 @@ var EXTENSION_KEYS = {
1163
2896
  };
1164
2897
 
1165
2898
  // ../../openapi/metadata/dist/read.js
1166
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2899
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1167
2900
  var extensionOf = (holder, key) => holder[key];
1168
2901
  var operationMetadata = (operation) => {
1169
2902
  const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1170
- const ext = isRecord2(raw) ? raw : {};
2903
+ const ext = isRecord3(raw) ? raw : {};
1171
2904
  const supported = ext.supported ?? true;
1172
2905
  const parity = ext.parity ?? {};
1173
2906
  return {
@@ -1203,9 +2936,9 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1203
2936
  this.name = "OperationRegistryError";
1204
2937
  }
1205
2938
  };
1206
- var verifyOperations = (document2, handlers) => {
2939
+ var verifyOperations = (document3, handlers) => {
1207
2940
  const problems = [];
1208
- const operations = listOperations(document2);
2941
+ const operations = listOperations(document3);
1209
2942
  const seen = /* @__PURE__ */ new Set();
1210
2943
  for (const operation of operations) {
1211
2944
  if (seen.has(operation.operationId))
@@ -1314,19 +3047,453 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1314
3047
  });
1315
3048
  };
1316
3049
 
3050
+ // ../core/dist/state-view.js
3051
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
3052
+ var RECORD_ID = /^[^\s/]{1,256}$/;
3053
+ var SAMPLE = 25;
3054
+ var WALK_LIMIT = 1e4;
3055
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
3056
+ var fail = (status, message) => ({ ok: false, status, message });
3057
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3058
+ var kindOf = (value) => {
3059
+ if (value === null)
3060
+ return "null";
3061
+ if (Array.isArray(value))
3062
+ return "array";
3063
+ switch (typeof value) {
3064
+ case "string":
3065
+ return "string";
3066
+ case "number":
3067
+ return Number.isFinite(value) ? "number" : "unknown";
3068
+ case "boolean":
3069
+ return "boolean";
3070
+ case "object":
3071
+ return "object";
3072
+ default:
3073
+ return "unknown";
3074
+ }
3075
+ };
3076
+ var humanize = (name) => {
3077
+ const words = name.replace(/[@:_-]+/g, " ").trim();
3078
+ if (words === "")
3079
+ return name;
3080
+ return words.charAt(0).toUpperCase() + words.slice(1);
3081
+ };
3082
+ var jsonValue = (value) => {
3083
+ if (value === void 0)
3084
+ return fail(400, "value is required");
3085
+ try {
3086
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
3087
+ } catch {
3088
+ return fail(400, "value must be JSON");
3089
+ }
3090
+ };
3091
+ var ctorName = (value) => {
3092
+ const ctor = value.constructor;
3093
+ return typeof ctor?.name === "string" ? ctor.name : "";
3094
+ };
3095
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
3096
+ var discoverCollections = (root) => {
3097
+ const found = [];
3098
+ const seen = /* @__PURE__ */ new Set();
3099
+ const visit = (value, depth) => {
3100
+ if (found.length + seen.size > WALK_LIMIT)
3101
+ return;
3102
+ if (value === null || typeof value !== "object")
3103
+ return;
3104
+ if (seen.has(value))
3105
+ return;
3106
+ seen.add(value);
3107
+ if (value instanceof Collection) {
3108
+ found.push(value);
3109
+ return;
3110
+ }
3111
+ if (value instanceof Map) {
3112
+ for (const child of value.values())
3113
+ visit(child, depth + 1);
3114
+ return;
3115
+ }
3116
+ if (value instanceof Set) {
3117
+ for (const child of value.values())
3118
+ visit(child, depth + 1);
3119
+ return;
3120
+ }
3121
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
3122
+ return;
3123
+ if (Array.isArray(value)) {
3124
+ const cap = Math.min(value.length, 32);
3125
+ for (let i = 0; i < cap; i++)
3126
+ visit(value[i], depth + 1);
3127
+ return;
3128
+ }
3129
+ let children;
3130
+ try {
3131
+ children = Object.values(value);
3132
+ } catch {
3133
+ return;
3134
+ }
3135
+ for (const child of children)
3136
+ visit(child, depth + 1);
3137
+ };
3138
+ visit(root, 0);
3139
+ return found;
3140
+ };
3141
+ var storedNames = (sqlite, namespace) => {
3142
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
3143
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
3144
+ return [...records, ...sequences].map((row) => row.name);
3145
+ };
3146
+ var blankAccum = (name) => ({
3147
+ name,
3148
+ kinds: /* @__PURE__ */ new Set(),
3149
+ present: 0,
3150
+ nested: /* @__PURE__ */ new Map()
3151
+ });
3152
+ var absorb = (accum, value) => {
3153
+ const kind = kindOf(value);
3154
+ accum.kinds.add(kind);
3155
+ accum.present++;
3156
+ if (!isRecord4(value))
3157
+ return;
3158
+ for (const [key, child] of Object.entries(value)) {
3159
+ const nested = accum.nested.get(key) ?? blankAccum(key);
3160
+ absorb(nested, child);
3161
+ accum.nested.set(key, nested);
3162
+ }
3163
+ };
3164
+ var finishField = (accum, samples) => {
3165
+ const kinds = [...accum.kinds];
3166
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
3167
+ const field = {
3168
+ name: accum.name,
3169
+ kind,
3170
+ optional: accum.present < samples || kinds.includes("null")
3171
+ };
3172
+ if (accum.nested.size > 0) {
3173
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
3174
+ }
3175
+ return field;
3176
+ };
3177
+ var inferFields = (records) => {
3178
+ if (records.length === 0)
3179
+ return [];
3180
+ const sample = records.slice(0, SAMPLE);
3181
+ const objects = sample.filter((record) => isRecord4(record.value));
3182
+ if (objects.length === 0) {
3183
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
3184
+ const list = [...kinds];
3185
+ return [
3186
+ {
3187
+ name: "(value)",
3188
+ kind: list.length === 1 ? list[0] : "unknown",
3189
+ optional: false
3190
+ }
3191
+ ];
3192
+ }
3193
+ const root = /* @__PURE__ */ new Map();
3194
+ for (const record of objects) {
3195
+ for (const [key, value] of Object.entries(record.value)) {
3196
+ const accum = root.get(key) ?? blankAccum(key);
3197
+ absorb(accum, value);
3198
+ root.set(key, accum);
3199
+ }
3200
+ }
3201
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
3202
+ };
3203
+ var mergeFields = (declared, inferred) => {
3204
+ const byName = /* @__PURE__ */ new Map();
3205
+ for (const field of inferred)
3206
+ byName.set(field.name, field);
3207
+ const ordered = [];
3208
+ const seen = /* @__PURE__ */ new Set();
3209
+ for (const field of declared ?? []) {
3210
+ const found = byName.get(field.name);
3211
+ seen.add(field.name);
3212
+ if (!found) {
3213
+ ordered.push({ ...field, optional: field.optional });
3214
+ continue;
3215
+ }
3216
+ ordered.push({
3217
+ ...found,
3218
+ kind: field.kind === "unknown" ? found.kind : field.kind,
3219
+ optional: field.optional || found.optional,
3220
+ ...field.description !== void 0 ? { description: field.description } : {},
3221
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
3222
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
3223
+ });
3224
+ }
3225
+ for (const field of inferred) {
3226
+ if (!seen.has(field.name))
3227
+ ordered.push(field);
3228
+ }
3229
+ return ordered;
3230
+ };
3231
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
3232
+ var readRecord = (collection, id) => {
3233
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
3234
+ const row = rows.find((entry) => entry.id === id);
3235
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
3236
+ };
3237
+ var inspectState = (scope) => {
3238
+ const declared = /* @__PURE__ */ new Map();
3239
+ for (const declaration of scope.declarations ?? []) {
3240
+ if (COLLECTION_NAME.test(declaration.name))
3241
+ declared.set(declaration.name, declaration);
3242
+ }
3243
+ const names = new Set(declared.keys());
3244
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
3245
+ names.add(name);
3246
+ for (const collection of discoverCollections(scope.root)) {
3247
+ if (collection.namespace === scope.storageNamespace)
3248
+ names.add(collection.collectionName);
3249
+ }
3250
+ const collections = [];
3251
+ for (const name of names) {
3252
+ if (!COLLECTION_NAME.test(name))
3253
+ continue;
3254
+ const declaration = declared.get(name);
3255
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3256
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
3257
+ const inferred = inferFields(records);
3258
+ const fields = mergeFields(declaration?.fields, inferred);
3259
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
3260
+ collections.push({
3261
+ name,
3262
+ label: declaration?.label ?? humanize(name),
3263
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
3264
+ count: collection.count(),
3265
+ source,
3266
+ fields,
3267
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
3268
+ });
3269
+ }
3270
+ const order = /* @__PURE__ */ new Map();
3271
+ for (const [index, item] of (scope.declarations ?? []).entries())
3272
+ order.set(item.name, index);
3273
+ collections.sort((a, b) => {
3274
+ const left = order.get(a.name);
3275
+ const right = order.get(b.name);
3276
+ if (left !== void 0 && right !== void 0)
3277
+ return left - right;
3278
+ if (left !== void 0)
3279
+ return -1;
3280
+ if (right !== void 0)
3281
+ return 1;
3282
+ return a.name.localeCompare(b.name);
3283
+ });
3284
+ return {
3285
+ namespace: scope.namespace,
3286
+ storageNamespace: scope.storageNamespace,
3287
+ collections
3288
+ };
3289
+ };
3290
+ var pageOf = (sqlite, storageNamespace, name, query) => {
3291
+ if (!COLLECTION_NAME.test(name))
3292
+ return fail(400, "collection name is not allowed");
3293
+ const limit = query.limit ?? 50;
3294
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
3295
+ return fail(400, "limit must be an integer from 1 to 200");
3296
+ }
3297
+ const order = query.order ?? "newest";
3298
+ if (order !== "newest" && order !== "oldest")
3299
+ return fail(400, 'order must be "newest" or "oldest"');
3300
+ const collection = collectionOf(sqlite, storageNamespace, name);
3301
+ const rows = collection.list({ order }).filter((row) => {
3302
+ if (query.after === void 0)
3303
+ return true;
3304
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
3305
+ });
3306
+ const slice = rows.slice(0, limit);
3307
+ const last = slice.at(-1);
3308
+ return {
3309
+ ok: true,
3310
+ value: {
3311
+ collection: name,
3312
+ count: collection.count(),
3313
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
3314
+ next: rows.length > limit && last ? last.seq : null
3315
+ }
3316
+ };
3317
+ };
3318
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
3319
+ var readStateRecord = (scope, name, id) => {
3320
+ if (!COLLECTION_NAME.test(name))
3321
+ return fail(400, "collection name is not allowed");
3322
+ if (!RECORD_ID.test(id))
3323
+ return fail(400, "record id is not allowed");
3324
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
3325
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
3326
+ };
3327
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
3328
+ var createStateRecord = (scope, name, input) => {
3329
+ if (!COLLECTION_NAME.test(name))
3330
+ return fail(400, "collection name is not allowed");
3331
+ const parsed = jsonValue(input.value);
3332
+ if (!parsed.ok)
3333
+ return parsed;
3334
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3335
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
3336
+ const checked = requireId(id);
3337
+ if (!checked.ok)
3338
+ return checked;
3339
+ if (collection.has(checked.value))
3340
+ return fail(409, `record ${checked.value} already exists`);
3341
+ const stored = collection.insert(checked.value, parsed.value);
3342
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3343
+ };
3344
+ var replaceStateRecord = (scope, name, id, value) => {
3345
+ if (!COLLECTION_NAME.test(name))
3346
+ return fail(400, "collection name is not allowed");
3347
+ const checked = requireId(id);
3348
+ if (!checked.ok)
3349
+ return checked;
3350
+ const parsed = jsonValue(value);
3351
+ if (!parsed.ok)
3352
+ return parsed;
3353
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3354
+ if (!collection.has(checked.value))
3355
+ return fail(404, `no record ${checked.value} in ${name}`);
3356
+ const stored = collection.update(checked.value, parsed.value);
3357
+ if (!stored)
3358
+ return fail(404, `no record ${checked.value} in ${name}`);
3359
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3360
+ };
3361
+ var patchStateRecord = (scope, name, id, value) => {
3362
+ const current = readStateRecord(scope, name, id);
3363
+ if (!current.ok)
3364
+ return current;
3365
+ const parsed = jsonValue(value);
3366
+ if (!parsed.ok)
3367
+ return parsed;
3368
+ const next = isRecord4(current.value.value) && isRecord4(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
3369
+ return replaceStateRecord(scope, name, id, next);
3370
+ };
3371
+ var deleteStateRecord = (scope, name, id) => {
3372
+ if (!COLLECTION_NAME.test(name))
3373
+ return fail(400, "collection name is not allowed");
3374
+ const checked = requireId(id);
3375
+ if (!checked.ok)
3376
+ return checked;
3377
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3378
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
3379
+ };
3380
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
3381
+ status,
3382
+ headers: { "content-type": "application/json; charset=utf-8" }
3383
+ });
3384
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
3385
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
3386
+ var integerParam = (value) => {
3387
+ if (value === null)
3388
+ return void 0;
3389
+ if (!/^-?\d+$/.test(value))
3390
+ return "bad";
3391
+ return Number(value);
3392
+ };
3393
+ var stateAdminRoutes = (routes) => {
3394
+ const open = (namespace) => {
3395
+ try {
3396
+ return { ok: true, value: routes.open(namespace) };
3397
+ } catch (error2) {
3398
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
3399
+ }
3400
+ };
3401
+ const wrote = (namespace) => {
3402
+ routes.afterWrite?.(namespace);
3403
+ };
3404
+ return {
3405
+ "GET /state": ({ namespace }) => {
3406
+ const scope = open(namespace);
3407
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
3408
+ },
3409
+ "GET /state/:collection": ({ namespace, params, url }) => {
3410
+ const scope = open(namespace);
3411
+ if (!scope.ok)
3412
+ return fromResult(scope, 200);
3413
+ const limit = integerParam(url.searchParams.get("limit"));
3414
+ const after = integerParam(url.searchParams.get("after"));
3415
+ if (limit === "bad")
3416
+ return adminError2(400, "limit: expected an integer");
3417
+ if (after === "bad")
3418
+ return adminError2(400, "after: expected a sequence number");
3419
+ const order = url.searchParams.get("order");
3420
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
3421
+ ...limit !== void 0 ? { limit } : {},
3422
+ ...after !== void 0 ? { after } : {},
3423
+ ...order === "newest" || order === "oldest" ? { order } : {}
3424
+ }), 200);
3425
+ },
3426
+ "GET /state/:collection/:id": ({ namespace, params }) => {
3427
+ const scope = open(namespace);
3428
+ if (!scope.ok)
3429
+ return fromResult(scope, 200);
3430
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
3431
+ },
3432
+ "POST /state/:collection": ({ namespace, params, body }) => {
3433
+ const scope = open(namespace);
3434
+ if (!scope.ok)
3435
+ return fromResult(scope, 201);
3436
+ if (!isRecord4(body) || !("value" in body)) {
3437
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3438
+ }
3439
+ const id = body.id;
3440
+ if (id !== void 0 && typeof id !== "string")
3441
+ return adminError2(400, "id must be a string");
3442
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3443
+ ...typeof id === "string" ? { id } : {},
3444
+ value: body.value
3445
+ });
3446
+ if (created.ok)
3447
+ wrote(namespace);
3448
+ return fromResult(created, 201);
3449
+ },
3450
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3451
+ const scope = open(namespace);
3452
+ if (!scope.ok)
3453
+ return fromResult(scope, 200);
3454
+ if (!isRecord4(body) || !("value" in body))
3455
+ return adminError2(400, 'expected {"value": <json>}');
3456
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3457
+ if (replaced.ok)
3458
+ wrote(namespace);
3459
+ return fromResult(replaced, 200);
3460
+ },
3461
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3462
+ const scope = open(namespace);
3463
+ if (!scope.ok)
3464
+ return fromResult(scope, 200);
3465
+ if (!isRecord4(body) || !("value" in body))
3466
+ return adminError2(400, 'expected {"value": <json>}');
3467
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3468
+ if (patched.ok)
3469
+ wrote(namespace);
3470
+ return fromResult(patched, 200);
3471
+ },
3472
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3473
+ const scope = open(namespace);
3474
+ if (!scope.ok)
3475
+ return fromResult(scope, 200);
3476
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3477
+ if (removed.ok)
3478
+ wrote(namespace);
3479
+ return fromResult(removed, 200);
3480
+ }
3481
+ };
3482
+ };
3483
+
1317
3484
  // ../core/dist/version.js
1318
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
3485
+ var PACKAGE_VERSION = true ? "1.5.0" : UNRELEASED_VERSION;
1319
3486
 
1320
3487
  // ../core/dist/signing.js
1321
3488
  var encoder = new TextEncoder();
1322
3489
  var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1323
3490
 
1324
3491
  // ../core/dist/webhooks.js
1325
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1326
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1327
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3492
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3493
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3494
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1328
3495
  var parseEndpoint = (value) => {
1329
- if (!isRecord3(value) || typeof value.url !== "string")
3496
+ if (!isRecord5(value) || typeof value.url !== "string")
1330
3497
  return "each endpoint needs a url";
1331
3498
  try {
1332
3499
  new URL(value.url);
@@ -1343,18 +3510,18 @@ var parseEndpoint = (value) => {
1343
3510
  const events = value.events ?? value.enabledEvents;
1344
3511
  if (Array.isArray(events))
1345
3512
  endpoint.events = events.map(String);
1346
- if (isRecord3(value.tags)) {
3513
+ if (isRecord5(value.tags)) {
1347
3514
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1348
3515
  }
1349
3516
  if (typeof value.account === "string")
1350
3517
  endpoint.tags = { ...endpoint.tags, account: value.account };
1351
- if (isRecord3(value.headers)) {
3518
+ if (isRecord5(value.headers)) {
1352
3519
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1353
3520
  }
1354
3521
  return endpoint;
1355
3522
  };
1356
3523
  var webhookAdminRoutes = (hub) => ({
1357
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3524
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1358
3525
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1359
3526
  const type = url.searchParams.get("type");
1360
3527
  return type === null || d.type === type;
@@ -1362,51 +3529,51 @@ var webhookAdminRoutes = (hub) => ({
1362
3529
  }),
1363
3530
  "GET /webhooks/events": ({ url, namespace }) => {
1364
3531
  const type = url.searchParams.get("type");
1365
- return json2(200, {
3532
+ return json4(200, {
1366
3533
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1367
3534
  });
1368
3535
  },
1369
3536
  "POST /webhooks/:id/replay": async ({ params }) => {
1370
3537
  const replayed = await hub.replay(params.id);
1371
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3538
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1372
3539
  },
1373
3540
  "POST /webhooks/flush": async () => {
1374
3541
  await hub.flush();
1375
- return json2(200, { status: "ok" });
3542
+ return json4(200, { status: "ok" });
1376
3543
  },
1377
3544
  "POST /webhooks/faults": ({ body, namespace }) => {
1378
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1379
- return adminError2(400, "mode must be duplicate, reorder or drop");
3545
+ if (!isRecord5(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3546
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1380
3547
  }
1381
3548
  const fault = { mode: body.mode };
1382
3549
  if (typeof body.count === "number")
1383
3550
  fault.count = body.count;
1384
3551
  hub.fault(namespace, fault);
1385
- return json2(201, { namespace, ...fault });
3552
+ return json4(201, { namespace, ...fault });
1386
3553
  },
1387
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3554
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1388
3555
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1389
3556
  ...rest,
1390
3557
  secret: secret ? "(set)" : null
1391
3558
  }))
1392
3559
  }),
1393
3560
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1394
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3561
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.endpoints : void 0;
1395
3562
  if (!Array.isArray(list))
1396
- return adminError2(400, "expected [{url, secret?, events?}]");
3563
+ return adminError3(400, "expected [{url, secret?, events?}]");
1397
3564
  const parsed = [];
1398
3565
  for (const each of list) {
1399
3566
  const endpoint = parseEndpoint(each);
1400
3567
  if (typeof endpoint === "string")
1401
- return adminError2(400, endpoint);
3568
+ return adminError3(400, endpoint);
1402
3569
  parsed.push(endpoint);
1403
3570
  }
1404
3571
  const set = hub.setEndpoints(namespace, parsed);
1405
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3572
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1406
3573
  },
1407
3574
  "DELETE /webhook-endpoints": ({ namespace }) => {
1408
3575
  hub.setEndpoints(namespace, []);
1409
- return json2(200, { status: "ok" });
3576
+ return json4(200, { status: "ok" });
1410
3577
  }
1411
3578
  });
1412
3579
  var parsePayload = (message) => {
@@ -1460,8 +3627,8 @@ var DroppedConnectionError = class extends TypeError {
1460
3627
  this.name = "TypeError";
1461
3628
  }
1462
3629
  };
1463
- var operationMatcher = (document2) => {
1464
- const matchers = listOperations(document2).map((operation) => ({
3630
+ var operationMatcher = (document3) => {
3631
+ const matchers = listOperations(document3).map((operation) => ({
1465
3632
  operationId: operation.operationId,
1466
3633
  method: operation.method.toUpperCase(),
1467
3634
  pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
@@ -1470,6 +3637,7 @@ var operationMatcher = (document2) => {
1470
3637
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1471
3638
  };
1472
3639
  var createRuntime = (options) => {
3640
+ assertAdminUi(options.adminUi);
1473
3641
  const sqlite = bootSqlite(options.sqlite);
1474
3642
  const clock = options.clock ?? createClock();
1475
3643
  const rng = createRng(options.seed ?? 0);
@@ -1555,10 +3723,10 @@ var createRuntime = (options) => {
1555
3723
  const ensureBranch = (namespace, branch2, at) => {
1556
3724
  if (!BRANCH_PATTERN2.test(branch2))
1557
3725
  throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1558
- const history = timeline(namespace);
3726
+ const history2 = timeline(namespace);
1559
3727
  if (branch2 === "main") {
1560
3728
  if (at !== void 0) {
1561
- const point = history.checkout("main", at);
3729
+ const point = history2.checkout("main", at);
1562
3730
  restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1563
3731
  captured.set(namespace, point.value.snapshot);
1564
3732
  rng.setState(point.value.rngState);
@@ -1571,10 +3739,10 @@ var createRuntime = (options) => {
1571
3739
  return namespace;
1572
3740
  }
1573
3741
  const storage = physicalBranch(namespace, branch2);
1574
- if (!history.hasBranch(branch2)) {
3742
+ if (!history2.hasBranch(branch2)) {
1575
3743
  if (at === void 0)
1576
- history.commit(capture(namespace));
1577
- const point = history.fork(branch2, at === void 0 ? {} : { from: at });
3744
+ history2.commit(capture(namespace));
3745
+ const point = history2.fork(branch2, at === void 0 ? {} : { from: at });
1578
3746
  const branchRng = createRng(options.seed ?? 0);
1579
3747
  if (point)
1580
3748
  branchRng.setState(point.value.rngState);
@@ -1583,8 +3751,8 @@ var createRuntime = (options) => {
1583
3751
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1584
3752
  if (point)
1585
3753
  captured.set(storage, point.value.snapshot);
1586
- } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1587
- const point = history.checkout(branch2, at);
3754
+ } else if (at !== void 0 && history2.head(branch2)?.id !== at) {
3755
+ const point = history2.checkout(branch2, at);
1588
3756
  if (!instances.has(storage)) {
1589
3757
  const branchRng = createRng(options.seed ?? 0);
1590
3758
  branchRng.setState(point.value.rngState);
@@ -1595,7 +3763,7 @@ var createRuntime = (options) => {
1595
3763
  captured.set(storage, point.value.snapshot);
1596
3764
  } else {
1597
3765
  if (!instances.has(storage)) {
1598
- const point = history.head(branch2);
3766
+ const point = history2.head(branch2);
1599
3767
  const branchRng = createRng(options.seed ?? 0);
1600
3768
  if (point)
1601
3769
  branchRng.setState(point.value.rngState);
@@ -1619,8 +3787,8 @@ var createRuntime = (options) => {
1619
3787
  const checkout = (checkpointId, checkoutOptions = {}) => {
1620
3788
  const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1621
3789
  const branchName = checkoutOptions.branch ?? "main";
1622
- const history = timeline(namespace);
1623
- const point = history.checkout(branchName, checkpointId);
3790
+ const history2 = timeline(namespace);
3791
+ const point = history2.checkout(branchName, checkpointId);
1624
3792
  const storage = ensureBranch(namespace, branchName);
1625
3793
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1626
3794
  captured.set(storage, point.value.snapshot);
@@ -1670,12 +3838,25 @@ var createRuntime = (options) => {
1670
3838
  instance(name);
1671
3839
  restoreNamespace(sqlite, storageNamespace(name), from);
1672
3840
  captured.set(name, from);
1673
- const history = timelines.get(name);
1674
- if (history)
1675
- history.commit(capture(name), { branch: "main" });
3841
+ const history2 = timelines.get(name);
3842
+ if (history2)
3843
+ history2.commit(capture(name), { branch: "main" });
1676
3844
  else
1677
3845
  timeline(name);
1678
3846
  };
3847
+ const declarationsFor = (namespace) => {
3848
+ const declared = options.state;
3849
+ if (!declared)
3850
+ return [];
3851
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3852
+ };
3853
+ const stateScope = (namespace) => ({
3854
+ sqlite,
3855
+ namespace,
3856
+ storageNamespace: storageNamespace(namespace),
3857
+ root: instance(namespace),
3858
+ declarations: declarationsFor(namespace)
3859
+ });
1679
3860
  const runtime = {
1680
3861
  name: options.name,
1681
3862
  sqlite,
@@ -1714,6 +3895,7 @@ var createRuntime = (options) => {
1714
3895
  branch,
1715
3896
  checkout,
1716
3897
  timeline,
3898
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1717
3899
  fetch: async (incoming) => {
1718
3900
  let request = incoming;
1719
3901
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -1887,10 +4069,10 @@ var createRuntime = (options) => {
1887
4069
  },
1888
4070
  release: (name, checkpointId) => timeline(name).release(checkpointId),
1889
4071
  inspect: (name) => {
1890
- const history = timeline(name);
4072
+ const history2 = timeline(name);
1891
4073
  return {
1892
- branches: history.branches(),
1893
- checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
4074
+ branches: history2.branches(),
4075
+ checkpoints: history2.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
1894
4076
  id,
1895
4077
  branch: branchName,
1896
4078
  parent,
@@ -1905,13 +4087,22 @@ var createRuntime = (options) => {
1905
4087
  } : {},
1906
4088
  routes: {
1907
4089
  ...credentialRoutes(credentials),
1908
- ...options.presets ? presetRoutes(options.presets, runtime) : {},
1909
4090
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1910
- ...options.admin?.(runtime) ?? {}
4091
+ ...options.admin?.(runtime) ?? {},
4092
+ // Shell routes win a colliding key. Fault presets are one of them: the admin page
4093
+ // maps `presets`, and a service route must not replace that list with a record.
4094
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
4095
+ ...stateAdminRoutes({
4096
+ open: stateScope,
4097
+ afterWrite: (namespace) => {
4098
+ checkpoint(namespace, "main");
4099
+ }
4100
+ }),
4101
+ ...adminUiRoutes(options.name, options.adminUi)
1911
4102
  },
1912
4103
  adminKey: options.adminKey
1913
4104
  });
1914
- return runtime;
4105
+ return defineMock(runtime);
1915
4106
  };
1916
4107
  var mutableResponse = (response) => {
1917
4108
  try {
@@ -1975,9 +4166,12 @@ var credentialRoutes = (registry) => ({
1975
4166
  }
1976
4167
  });
1977
4168
  var presetRoutes = (presets, runtime) => ({
1978
- "GET /faults/presets": () => adminJson(200, {
1979
- presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
1980
- }),
4169
+ "GET /faults/presets": () => {
4170
+ const body = {
4171
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4172
+ };
4173
+ return adminJson(200, body);
4174
+ },
1981
4175
  "POST /faults/presets/:name": ({ params, body, namespace }) => {
1982
4176
  const name = params.name;
1983
4177
  if (!presets[name])
@@ -2048,15 +4242,15 @@ var decodePostHogBody = (request) => {
2048
4242
  decoded.set(request, pending);
2049
4243
  return pending;
2050
4244
  };
2051
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4245
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2052
4246
  var nonEmpty = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2053
4247
  var tokenFromBody = (body) => {
2054
4248
  if (Array.isArray(body)) return tokenFromBody(body[0]);
2055
- if (!isRecord4(body)) return void 0;
4249
+ if (!isRecord6(body)) return void 0;
2056
4250
  const direct = nonEmpty(body.token) ?? nonEmpty(body.api_key);
2057
4251
  if (direct) return direct;
2058
4252
  if (Array.isArray(body.batch)) return tokenFromBody(body.batch[0]);
2059
- if (isRecord4(body.properties)) return nonEmpty(body.properties.token);
4253
+ if (isRecord6(body.properties)) return nonEmpty(body.properties.token);
2060
4254
  return void 0;
2061
4255
  };
2062
4256
  var ARRAY_PATH = /^\/array\/([^/]+)\/config(\.js)?\/?$/;
@@ -2130,7 +4324,7 @@ var legacyMaps = (evaluations) => {
2130
4324
  }
2131
4325
  return { featureFlags, featureFlagPayloads };
2132
4326
  };
2133
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4327
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2134
4328
  var payloadString = (payload) => payload === void 0 || payload === null ? null : JSON.stringify(payload);
2135
4329
  var parsePayload2 = (payload) => {
2136
4330
  if (payload === null) return null;
@@ -2159,7 +4353,7 @@ var adminView = (flag) => ({
2159
4353
  var isValue = (value) => typeof value === "boolean" || typeof value === "string" && value.length > 0;
2160
4354
  var parseFlagSpec = (body) => {
2161
4355
  if (body === void 0) return { default: null, payload: null, overrides: [] };
2162
- if (!isRecord5(body)) return "expected a JSON object";
4356
+ if (!isRecord7(body)) return "expected a JSON object";
2163
4357
  const value = body.default ?? body.value;
2164
4358
  if (value !== void 0 && value !== null && !isValue(value)) {
2165
4359
  return "default must be true, false, a variant string, or null (absent)";
@@ -2168,7 +4362,7 @@ var parseFlagSpec = (body) => {
2168
4362
  if (body.overrides !== void 0) {
2169
4363
  if (!Array.isArray(body.overrides)) return "overrides must be a list";
2170
4364
  for (const each of body.overrides) {
2171
- if (!isRecord5(each)) return "each override is {distinct_id?|email?, value, payload?}";
4365
+ if (!isRecord7(each)) return "each override is {distinct_id?|email?, value, payload?}";
2172
4366
  const id = each.distinct_id ?? each.distinctId;
2173
4367
  const email = each.email;
2174
4368
  if (id === void 0 && email === void 0) return "each override needs distinct_id or email";
@@ -2249,10 +4443,10 @@ var restView = (flag) => {
2249
4443
  };
2250
4444
  var propertyValues = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" || typeof v === "number").map(String) : typeof value === "string" || typeof value === "number" ? [String(value)] : [];
2251
4445
  var fromFilters = (filters) => {
2252
- const record = isRecord5(filters) ? filters : {};
2253
- const groups = Array.isArray(record.groups) ? record.groups.filter(isRecord5) : [];
2254
- const multivariate = isRecord5(record.multivariate) ? record.multivariate : void 0;
2255
- const variants = Array.isArray(multivariate?.variants) ? multivariate.variants.filter(isRecord5) : [];
4446
+ const record = isRecord7(filters) ? filters : {};
4447
+ const groups = Array.isArray(record.groups) ? record.groups.filter(isRecord7) : [];
4448
+ const multivariate = isRecord7(record.multivariate) ? record.multivariate : void 0;
4449
+ const variants = Array.isArray(multivariate?.variants) ? multivariate.variants.filter(isRecord7) : [];
2256
4450
  const topVariant = [...variants].sort((a, b) => Number(b.rollout_percentage ?? 0) - Number(a.rollout_percentage ?? 0)).map((v) => v.key).find((key) => typeof key === "string" && key.length > 0);
2257
4451
  const on = (group) => {
2258
4452
  const rollout = group.rollout_percentage ?? 100;
@@ -2263,7 +4457,7 @@ var fromFilters = (filters) => {
2263
4457
  const overrides = [];
2264
4458
  let fallback = groups.length === 0 ? false : null;
2265
4459
  for (const group of groups) {
2266
- const properties = Array.isArray(group.properties) ? group.properties.filter(isRecord5) : [];
4460
+ const properties = Array.isArray(group.properties) ? group.properties.filter(isRecord7) : [];
2267
4461
  if (properties.length === 0) {
2268
4462
  const rollout = group.rollout_percentage ?? 100;
2269
4463
  const value = typeof rollout === "number" && rollout < 100 ? false : on(group);
@@ -2280,14 +4474,14 @@ var fromFilters = (filters) => {
2280
4474
  }
2281
4475
  }
2282
4476
  if (fallback === null) fallback = false;
2283
- const payloads = isRecord5(record.payloads) ? record.payloads : {};
4477
+ const payloads = isRecord7(record.payloads) ? record.payloads : {};
2284
4478
  const rawPayload = typeof fallback === "string" && fallback in payloads ? payloads[fallback] : payloads.true;
2285
4479
  const payload = rawPayload === void 0 || rawPayload === null ? null : typeof rawPayload === "string" ? rawPayload : JSON.stringify(rawPayload);
2286
4480
  return { default: fallback, payload, overrides };
2287
4481
  };
2288
4482
 
2289
4483
  // src/generated/openapi.ts
2290
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"PostHog feature flags, capture and management API (Mockingbird subset)","description":"Stateful mock subset of PostHog: remote flag evaluation (\`/flags\` v2 and the legacy\\n\`/decide\` shape), remote config, event capture (\`/batch/\`, \`/e/\`, \`/i/v0/e/\`), session\\nrecording intake, the posthog-js asset and survey endpoints, and the slice of the\\nmanagement API our tooling and crons call (feature-flag list/create/patch, HogQL query).\\nHand-authored from the wire shapes of posthog-node 5.52.2 / @posthog/core 1.54.0,\\nposthog-js 1.433.2 and our own raw fetches.\\n\\nPaths are written without the trailing slash PostHog uses; the mock answers both\\n(\`/flags/?v=2\` from the SDKs and \`/flags?v=2\` from the EMR frontend's raw fetch).\\nCapture and flag bodies may arrive gzip-compressed (\`Content-Encoding: gzip\`, or raw gzip\\nbytes from posthog-js), base64 (\`data=\` form bodies), or as plain JSON; the contract\\ndeclares the decoded JSON.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from @posthog/core posthog-core-stateless (getFlags, sendBatch, getRemoteConfig, getSurveysStateless), posthog-js request.ts / posthog-featureflags.ts, and the consumer's posthog-server.adapter.ts, posthog-server.ts (EMR frontend), website-posthog-purchase.sink.ts, posthog-hogql.client.ts and feature-flags-cli."}},"servers":[{"url":"https://us.i.posthog.com"}],"paths":{"/flags":{"post":{"operationId":"EvaluateFlags","description":"Remote flag evaluation. \`v=2\` (what every current SDK sends) answers the \`flags\` detail\\nmap; no \`v\` or \`v=1\` answers the legacy \`featureFlags\`/\`featureFlagPayloads\` maps.\\n\`config=true\` adds the remote-config fields. The project key is \`token\` (SDKs) or\\n\`api_key\` (the EMR frontend's raw fetch).\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Version"},{"$ref":"#/components/parameters/Config"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsRequest"}}}},"responses":{"200":{"description":"Evaluated flags","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsResponse"}}}},"400":{"description":"Malformed body or missing distinct_id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited (fault preset flags_429)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault preset flags_5xx)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/decide":{"post":{"operationId":"Decide","description":"The legacy endpoint (the Python client sends \`POST /decide/?v=3\` with\\n\`{api_key, distinct_id}\`). \`v\` < 4 answers the legacy maps; \`v=4\` the \`flags\` map.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Version"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsRequest"}}}},"responses":{"200":{"description":"Evaluated flags (legacy shape)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsResponse"}}}},"400":{"description":"Malformed body or missing distinct_id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited (fault preset flags_429)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault preset flags_5xx)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/array/{token}/config":{"parameters":[{"$ref":"#/components/parameters/TokenPath"}],"get":{"operationId":"GetRemoteConfig","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Remote config (posthog-react-native, @posthog/core)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RemoteConfig"}}}}}}},"/array/{token}/config.js":{"parameters":[{"$ref":"#/components/parameters/TokenPath"}],"get":{"operationId":"GetRemoteConfigScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Remote config as a script that sets \`window._POSTHOG_REMOTE_CONFIG[token]\` (posthog-js)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/batch":{"post":{"operationId":"CaptureBatch","description":"posthog-node and posthog-react-native flushes (Content-Encoding: gzip).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/e":{"post":{"operationId":"CaptureEvent","description":"One event, an array of events, or \`{api_key, batch}\` (posthog-js).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/i/v0/e":{"post":{"operationId":"CaptureEventV0","description":"The capture endpoint remote config advertises (\`analytics.endpoint\`); also our backend's website purchase sink (\`{api_key, event, distinct_id, timestamp, uuid, properties}\`).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/s":{"post":{"operationId":"CaptureRecording","description":"Session-recording snapshots; counted, never stored.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}}}}},"/static/recorder.js":{"get":{"operationId":"GetRecorderScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The session recorder bundle (an inert script here)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/static/{version}/recorder.js":{"parameters":[{"name":"version","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]+\\\\.[0-9]+\\\\.[0-9]+$"}}],"get":{"operationId":"GetVersionedRecorderScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The versioned session recorder bundle (an inert script here)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/api/surveys":{"get":{"operationId":"ListSurveys","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/TokenQuery"}],"responses":{"200":{"description":"No surveys","content":{"application/json":{"schema":{"type":"object","required":["surveys"],"properties":{"surveys":{"type":"array","maxItems":0}}}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/web_experiments":{"get":{"operationId":"ListWebExperiments","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/TokenQuery"}],"responses":{"200":{"description":"No web experiments","content":{"application/json":{"schema":{"type":"object","required":["experiments"],"properties":{"experiments":{"type":"array","maxItems":0}}}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/feature_flags":{"parameters":[{"$ref":"#/components/parameters/ProjectId"}],"get":{"operationId":"ListFeatureFlags","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"maximum":1000}}],"responses":{"200":{"description":"One page of flags (feature-flags-cli follows \`next\`)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlagPage"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"post":{"operationId":"CreateFeatureFlag","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFeatureFlagBody"}}}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlag"}}}},"400":{"description":"Invalid, or the key already exists","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/feature_flags/{flagId}":{"parameters":[{"$ref":"#/components/parameters/ProjectId"},{"name":"flagId","in":"path","required":true,"description":"The flag's numeric id. The mock also accepts the flag key (how self-parity walks reference flags they created, since resource identities are strings).","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"feature_flag","missing":"999999"}}}],"patch":{"operationId":"UpdateFeatureFlag","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateFeatureFlagBody"}}}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlag"}}}},"400":{"description":"Invalid","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"No such flag","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/query":{"parameters":[{"$ref":"#/components/parameters/ProjectId"}],"post":{"operationId":"RunQuery","description":"HogQL (the marketing-metrics crons). Answers canned results set with \`PUT /__admin/settings {\\"queryResults\\": [...]}\`; \`{results: []}\` otherwise.","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryRequest"}}}},"responses":{"200":{"description":"Query results","content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryResponse"}}}},"400":{"description":"Not a HogQL query","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"parameters":{"Version":{"name":"v","in":"query","schema":{"type":"integer","minimum":1,"maximum":4}},"Config":{"name":"config","in":"query","schema":{"type":"string","enum":["true","false"]}},"TokenPath":{"name":"token","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"}},"TokenQuery":{"name":"token","in":"query","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"}},"ProjectId":{"name":"projectId","in":"path","required":true,"schema":{"type":"integer","minimum":1,"maximum":999999999}}},"schemas":{"ErrorBody":{"type":"object","required":["type","code","detail"],"properties":{"type":{"type":"string"},"code":{"type":"string"},"detail":{"type":"string"},"attr":{"type":["string","null"]}}},"FlagsRequest":{"type":"object","required":["distinct_id"],"properties":{"token":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"groups":{"type":"object"},"person_properties":{"type":"object","properties":{"email":{"type":"string","maxLength":120}}},"group_properties":{"type":"object"},"$device_id":{"type":"string","maxLength":64},"$anon_distinct_id":{"type":"string","maxLength":64},"evaluation_contexts":{"type":"array","maxItems":5,"items":{"type":"string","maxLength":40}},"evaluation_runtime":{"type":"string","enum":["server","client","all"]},"flag_keys_to_evaluate":{"type":"array","maxItems":10,"items":{"type":"string","maxLength":64}},"geoip_disable":{"type":"boolean"},"disable_flags":{"type":"boolean"}}},"FlagDetail":{"type":"object","required":["key","enabled","variant","reason","metadata"],"properties":{"key":{"type":"string"},"enabled":{"type":"boolean"},"variant":{"type":["string","null"]},"failed":{"type":"boolean"},"reason":{"type":"object","required":["code","description"],"properties":{"code":{"type":"string"},"condition_index":{"type":["integer","null"]},"description":{"type":"string"}}},"metadata":{"type":"object","required":["id","version"],"properties":{"id":{"type":"integer"},"version":{"type":"integer"},"description":{"type":["string","null"]},"payload":{"type":"string","description":"The payload as a JSON string."}}}}},"FlagsResponse":{"type":"object","required":["errorsWhileComputingFlags"],"properties":{"flags":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/FlagDetail"}},"featureFlags":{"type":"object","additionalProperties":{"type":["boolean","string"]}},"featureFlagPayloads":{"type":"object","additionalProperties":{"type":"string"}},"errorsWhileComputingFlags":{"type":"boolean"},"quotaLimited":{"type":"array","items":{"type":"string"}},"requestId":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"evaluatedAt":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"config":{"type":"object"},"supportedCompression":{"type":"array","items":{"type":"string"}},"sessionRecording":{"oneOf":[{"type":"boolean"},{"type":"object"}]}}},"RemoteConfig":{"type":"object","required":["token","supportedCompression","hasFeatureFlags","analytics","sessionRecording"],"properties":{"token":{"type":"string"},"supportedCompression":{"type":"array","items":{"type":"string"}},"hasFeatureFlags":{"type":"boolean"},"analytics":{"type":"object","required":["endpoint"],"properties":{"endpoint":{"type":"string"}}},"sessionRecording":{"oneOf":[{"type":"boolean"},{"type":"object","required":["endpoint"],"properties":{"endpoint":{"type":"string"}}}]},"surveys":{"type":"boolean"},"heatmaps":{"type":"boolean"},"siteApps":{"type":"array"}}},"CapturedEventBody":{"type":"object","required":["event"],"properties":{"event":{"type":"string","minLength":1,"maxLength":64},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"properties":{"type":"object"},"timestamp":{"type":"string","format":"date-time"},"uuid":{"type":"string","format":"uuid"}}},"BatchRequest":{"type":"object","required":["api_key","batch"],"properties":{"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"batch":{"type":"array","maxItems":5,"items":{"$ref":"#/components/schemas/CapturedEventBody"}},"sent_at":{"type":"string","format":"date-time"}}},"CaptureRequest":{"type":"object","required":["api_key","event"],"properties":{"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"event":{"type":"string","minLength":1,"maxLength":64},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"properties":{"type":"object"},"timestamp":{"type":"string","format":"date-time"},"uuid":{"type":"string","format":"uuid"}}},"CaptureResponse":{"type":"object","required":["status"],"properties":{"status":{"oneOf":[{"type":"string"},{"type":"integer"}]}}},"FeatureFlag":{"type":"object","required":["id","key","name","active","filters"],"properties":{"id":{"type":"integer"},"key":{"type":"string","x-mockingbird-resource":{"type":"feature_flag","identity":true}},"name":{"type":"string"},"active":{"type":"boolean"},"deleted":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"version":{"type":"integer"},"filters":{"type":"object","required":["groups"],"properties":{"groups":{"type":"array","items":{"type":"object"}},"multivariate":{"oneOf":[{"type":"null"},{"type":"object"}]},"payloads":{"type":"object"}}}}},"FeatureFlagPage":{"type":"object","required":["count","next","previous","results"],"properties":{"count":{"type":"integer"},"next":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"url"}},"previous":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"url"}},"results":{"type":"array","items":{"$ref":"#/components/schemas/FeatureFlag"}}}},"FlagGroup":{"type":"object","properties":{"properties":{"type":"array","maxItems":2,"items":{"type":"object","required":["key","value"],"properties":{"key":{"type":"string","enum":["distinct_id","email"]},"type":{"type":"string","enum":["person"]},"operator":{"type":"string","enum":["exact"]},"value":{"type":"array","maxItems":3,"items":{"type":"string","minLength":1,"maxLength":40}}}}},"rollout_percentage":{"type":"integer","minimum":0,"maximum":100},"variant":{"type":["string","null"],"maxLength":20}}},"FlagFilters":{"type":"object","properties":{"groups":{"type":"array","maxItems":3,"items":{"$ref":"#/components/schemas/FlagGroup"}},"payloads":{"type":"object","properties":{"true":{"type":"string","maxLength":200}}}}},"CreateFeatureFlagBody":{"type":"object","required":["key"],"properties":{"key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"name":{"type":"string","maxLength":120},"active":{"type":"boolean"},"filters":{"$ref":"#/components/schemas/FlagFilters"}}},"UpdateFeatureFlagBody":{"type":"object","properties":{"name":{"type":"string","maxLength":120},"active":{"type":"boolean"},"deleted":{"type":"boolean"},"filters":{"$ref":"#/components/schemas/FlagFilters"}}},"QueryRequest":{"type":"object","required":["query"],"properties":{"query":{"type":"object","required":["kind","query"],"properties":{"kind":{"type":"string","enum":["HogQLQuery"]},"query":{"type":"string","minLength":1,"maxLength":500}}}}},"QueryResponse":{"type":"object","required":["results"],"properties":{"results":{"type":"array","items":{"type":"array"}},"columns":{"type":"array","items":{"type":"string"}},"is_cached":{"type":"boolean"}}}}}}`);
4484
+ var document2 = JSON.parse(`{"openapi":"3.1.0","info":{"title":"PostHog feature flags, capture and management API (Mockingbird subset)","description":"Stateful mock subset of PostHog: remote flag evaluation (\`/flags\` v2 and the legacy\\n\`/decide\` shape), remote config, event capture (\`/batch/\`, \`/e/\`, \`/i/v0/e/\`), session\\nrecording intake, the posthog-js asset and survey endpoints, and the slice of the\\nmanagement API our tooling and crons call (feature-flag list/create/patch, HogQL query).\\nHand-authored from the wire shapes of posthog-node 5.52.2 / @posthog/core 1.54.0,\\nposthog-js 1.433.2 and our own raw fetches.\\n\\nPaths are written without the trailing slash PostHog uses; the mock answers both\\n(\`/flags/?v=2\` from the SDKs and \`/flags?v=2\` from the EMR frontend's raw fetch).\\nCapture and flag bodies may arrive gzip-compressed (\`Content-Encoding: gzip\`, or raw gzip\\nbytes from posthog-js), base64 (\`data=\` form bodies), or as plain JSON; the contract\\ndeclares the decoded JSON.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from @posthog/core posthog-core-stateless (getFlags, sendBatch, getRemoteConfig, getSurveysStateless), posthog-js request.ts / posthog-featureflags.ts, and the consumer's posthog-server.adapter.ts, posthog-server.ts (EMR frontend), website-posthog-purchase.sink.ts, posthog-hogql.client.ts and feature-flags-cli."}},"servers":[{"url":"https://us.i.posthog.com"}],"paths":{"/flags":{"post":{"operationId":"EvaluateFlags","description":"Remote flag evaluation. \`v=2\` (what every current SDK sends) answers the \`flags\` detail\\nmap; no \`v\` or \`v=1\` answers the legacy \`featureFlags\`/\`featureFlagPayloads\` maps.\\n\`config=true\` adds the remote-config fields. The project key is \`token\` (SDKs) or\\n\`api_key\` (the EMR frontend's raw fetch).\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Version"},{"$ref":"#/components/parameters/Config"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsRequest"}}}},"responses":{"200":{"description":"Evaluated flags","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsResponse"}}}},"400":{"description":"Malformed body or missing distinct_id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited (fault preset flags_429)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault preset flags_5xx)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/decide":{"post":{"operationId":"Decide","description":"The legacy endpoint (the Python client sends \`POST /decide/?v=3\` with\\n\`{api_key, distinct_id}\`). \`v\` < 4 answers the legacy maps; \`v=4\` the \`flags\` map.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/Version"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsRequest"}}}},"responses":{"200":{"description":"Evaluated flags (legacy shape)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlagsResponse"}}}},"400":{"description":"Malformed body or missing distinct_id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited (fault preset flags_429)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault preset flags_5xx)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/array/{token}/config":{"parameters":[{"$ref":"#/components/parameters/TokenPath"}],"get":{"operationId":"GetRemoteConfig","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Remote config (posthog-react-native, @posthog/core)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RemoteConfig"}}}}}}},"/array/{token}/config.js":{"parameters":[{"$ref":"#/components/parameters/TokenPath"}],"get":{"operationId":"GetRemoteConfigScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Remote config as a script that sets \`window._POSTHOG_REMOTE_CONFIG[token]\` (posthog-js)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/batch":{"post":{"operationId":"CaptureBatch","description":"posthog-node and posthog-react-native flushes (Content-Encoding: gzip).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/e":{"post":{"operationId":"CaptureEvent","description":"One event, an array of events, or \`{api_key, batch}\` (posthog-js).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/i/v0/e":{"post":{"operationId":"CaptureEventV0","description":"The capture endpoint remote config advertises (\`analytics.endpoint\`); also our backend's website purchase sink (\`{api_key, event, distinct_id, timestamp, uuid, properties}\`).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}},"400":{"description":"Malformed body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error (fault)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/s":{"post":{"operationId":"CaptureRecording","description":"Session-recording snapshots; counted, never stored.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureRequest"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CaptureResponse"}}}}}}},"/static/recorder.js":{"get":{"operationId":"GetRecorderScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The session recorder bundle (an inert script here)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/static/{version}/recorder.js":{"parameters":[{"name":"version","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]+\\\\.[0-9]+\\\\.[0-9]+$"}}],"get":{"operationId":"GetVersionedRecorderScript","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The versioned session recorder bundle (an inert script here)","content":{"application/javascript":{"schema":{"type":"string"}}}}}}},"/api/surveys":{"get":{"operationId":"ListSurveys","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/TokenQuery"}],"responses":{"200":{"description":"No surveys","content":{"application/json":{"schema":{"type":"object","required":["surveys"],"properties":{"surveys":{"type":"array","maxItems":0}}}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/web_experiments":{"get":{"operationId":"ListWebExperiments","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/TokenQuery"}],"responses":{"200":{"description":"No web experiments","content":{"application/json":{"schema":{"type":"object","required":["experiments"],"properties":{"experiments":{"type":"array","maxItems":0}}}}}},"401":{"description":"No project API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/feature_flags":{"parameters":[{"$ref":"#/components/parameters/ProjectId"}],"get":{"operationId":"ListFeatureFlags","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"maximum":1000}}],"responses":{"200":{"description":"One page of flags (feature-flags-cli follows \`next\`)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlagPage"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"post":{"operationId":"CreateFeatureFlag","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFeatureFlagBody"}}}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlag"}}}},"400":{"description":"Invalid, or the key already exists","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/feature_flags/{flagId}":{"parameters":[{"$ref":"#/components/parameters/ProjectId"},{"name":"flagId","in":"path","required":true,"description":"The flag's numeric id. The mock also accepts the flag key (how self-parity walks reference flags they created, since resource identities are strings).","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"feature_flag","missing":"999999"}}}],"patch":{"operationId":"UpdateFeatureFlag","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateFeatureFlagBody"}}}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlag"}}}},"400":{"description":"Invalid","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"No such flag","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/projects/{projectId}/query":{"parameters":[{"$ref":"#/components/parameters/ProjectId"}],"post":{"operationId":"RunQuery","description":"HogQL (the marketing-metrics crons). Answers canned results set with \`PUT /__admin/settings {\\"queryResults\\": [...]}\`; \`{results: []}\` otherwise.","security":[{"bearerAuth":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryRequest"}}}},"responses":{"200":{"description":"Query results","content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryResponse"}}}},"400":{"description":"Not a HogQL query","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"No personal API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"parameters":{"Version":{"name":"v","in":"query","schema":{"type":"integer","minimum":1,"maximum":4}},"Config":{"name":"config","in":"query","schema":{"type":"string","enum":["true","false"]}},"TokenPath":{"name":"token","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"}},"TokenQuery":{"name":"token","in":"query","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"}},"ProjectId":{"name":"projectId","in":"path","required":true,"schema":{"type":"integer","minimum":1,"maximum":999999999}}},"schemas":{"ErrorBody":{"type":"object","required":["type","code","detail"],"properties":{"type":{"type":"string"},"code":{"type":"string"},"detail":{"type":"string"},"attr":{"type":["string","null"]}}},"FlagsRequest":{"type":"object","required":["distinct_id"],"properties":{"token":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"groups":{"type":"object"},"person_properties":{"type":"object","properties":{"email":{"type":"string","maxLength":120}}},"group_properties":{"type":"object"},"$device_id":{"type":"string","maxLength":64},"$anon_distinct_id":{"type":"string","maxLength":64},"evaluation_contexts":{"type":"array","maxItems":5,"items":{"type":"string","maxLength":40}},"evaluation_runtime":{"type":"string","enum":["server","client","all"]},"flag_keys_to_evaluate":{"type":"array","maxItems":10,"items":{"type":"string","maxLength":64}},"geoip_disable":{"type":"boolean"},"disable_flags":{"type":"boolean"}}},"FlagDetail":{"type":"object","required":["key","enabled","variant","reason","metadata"],"properties":{"key":{"type":"string"},"enabled":{"type":"boolean"},"variant":{"type":["string","null"]},"failed":{"type":"boolean"},"reason":{"type":"object","required":["code","description"],"properties":{"code":{"type":"string"},"condition_index":{"type":["integer","null"]},"description":{"type":"string"}}},"metadata":{"type":"object","required":["id","version"],"properties":{"id":{"type":"integer"},"version":{"type":"integer"},"description":{"type":["string","null"]},"payload":{"type":"string","description":"The payload as a JSON string."}}}}},"FlagsResponse":{"type":"object","required":["errorsWhileComputingFlags"],"properties":{"flags":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/FlagDetail"}},"featureFlags":{"type":"object","additionalProperties":{"type":["boolean","string"]}},"featureFlagPayloads":{"type":"object","additionalProperties":{"type":"string"}},"errorsWhileComputingFlags":{"type":"boolean"},"quotaLimited":{"type":"array","items":{"type":"string"}},"requestId":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"evaluatedAt":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"config":{"type":"object"},"supportedCompression":{"type":"array","items":{"type":"string"}},"sessionRecording":{"oneOf":[{"type":"boolean"},{"type":"object"}]}}},"RemoteConfig":{"type":"object","required":["token","supportedCompression","hasFeatureFlags","analytics","sessionRecording"],"properties":{"token":{"type":"string"},"supportedCompression":{"type":"array","items":{"type":"string"}},"hasFeatureFlags":{"type":"boolean"},"analytics":{"type":"object","required":["endpoint"],"properties":{"endpoint":{"type":"string"}}},"sessionRecording":{"oneOf":[{"type":"boolean"},{"type":"object","required":["endpoint"],"properties":{"endpoint":{"type":"string"}}}]},"surveys":{"type":"boolean"},"heatmaps":{"type":"boolean"},"siteApps":{"type":"array"}}},"CapturedEventBody":{"type":"object","required":["event"],"properties":{"event":{"type":"string","minLength":1,"maxLength":64},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"properties":{"type":"object"},"timestamp":{"type":"string","format":"date-time"},"uuid":{"type":"string","format":"uuid"}}},"BatchRequest":{"type":"object","required":["api_key","batch"],"properties":{"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"batch":{"type":"array","maxItems":5,"items":{"$ref":"#/components/schemas/CapturedEventBody"}},"sent_at":{"type":"string","format":"date-time"}}},"CaptureRequest":{"type":"object","required":["api_key","event"],"properties":{"api_key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"event":{"type":"string","minLength":1,"maxLength":64},"distinct_id":{"type":"string","minLength":1,"maxLength":64},"properties":{"type":"object"},"timestamp":{"type":"string","format":"date-time"},"uuid":{"type":"string","format":"uuid"}}},"CaptureResponse":{"type":"object","required":["status"],"properties":{"status":{"oneOf":[{"type":"string"},{"type":"integer"}]}}},"FeatureFlag":{"type":"object","required":["id","key","name","active","filters"],"properties":{"id":{"type":"integer"},"key":{"type":"string","x-mockingbird-resource":{"type":"feature_flag","identity":true}},"name":{"type":"string"},"active":{"type":"boolean"},"deleted":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"version":{"type":"integer"},"filters":{"type":"object","required":["groups"],"properties":{"groups":{"type":"array","items":{"type":"object"}},"multivariate":{"oneOf":[{"type":"null"},{"type":"object"}]},"payloads":{"type":"object"}}}}},"FeatureFlagPage":{"type":"object","required":["count","next","previous","results"],"properties":{"count":{"type":"integer"},"next":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"url"}},"previous":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"url"}},"results":{"type":"array","items":{"$ref":"#/components/schemas/FeatureFlag"}}}},"FlagGroup":{"type":"object","properties":{"properties":{"type":"array","maxItems":2,"items":{"type":"object","required":["key","value"],"properties":{"key":{"type":"string","enum":["distinct_id","email"]},"type":{"type":"string","enum":["person"]},"operator":{"type":"string","enum":["exact"]},"value":{"type":"array","maxItems":3,"items":{"type":"string","minLength":1,"maxLength":40}}}}},"rollout_percentage":{"type":"integer","minimum":0,"maximum":100},"variant":{"type":["string","null"],"maxLength":20}}},"FlagFilters":{"type":"object","properties":{"groups":{"type":"array","maxItems":3,"items":{"$ref":"#/components/schemas/FlagGroup"}},"payloads":{"type":"object","properties":{"true":{"type":"string","maxLength":200}}}}},"CreateFeatureFlagBody":{"type":"object","required":["key"],"properties":{"key":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$"},"name":{"type":"string","maxLength":120},"active":{"type":"boolean"},"filters":{"$ref":"#/components/schemas/FlagFilters"}}},"UpdateFeatureFlagBody":{"type":"object","properties":{"name":{"type":"string","maxLength":120},"active":{"type":"boolean"},"deleted":{"type":"boolean"},"filters":{"$ref":"#/components/schemas/FlagFilters"}}},"QueryRequest":{"type":"object","required":["query"],"properties":{"query":{"type":"object","required":["kind","query"],"properties":{"kind":{"type":"string","enum":["HogQLQuery"]},"query":{"type":"string","minLength":1,"maxLength":500}}}}},"QueryResponse":{"type":"object","required":["results"],"properties":{"results":{"type":"array","items":{"type":"array"}},"columns":{"type":"array","items":{"type":"string"}},"is_cached":{"type":"boolean"}}}}}}`);
2291
4485
  var operationIds = ["EvaluateFlags", "Decide", "GetRemoteConfig", "GetRemoteConfigScript", "CaptureBatch", "CaptureEvent", "CaptureEventV0", "CaptureRecording", "GetRecorderScript", "GetVersionedRecorderScript", "ListSurveys", "ListWebExperiments", "ListFeatureFlags", "CreateFeatureFlag", "UpdateFeatureFlag", "RunQuery"];
2292
4486
  var supportedOperationIds = ["EvaluateFlags", "Decide", "GetRemoteConfig", "GetRemoteConfigScript", "CaptureBatch", "CaptureEvent", "CaptureEventV0", "CaptureRecording", "GetRecorderScript", "GetVersionedRecorderScript", "ListSurveys", "ListWebExperiments", "ListFeatureFlags", "CreateFeatureFlag", "UpdateFeatureFlag", "RunQuery"];
2293
4487
 
@@ -2453,13 +4647,13 @@ var POSTHOG_PRESETS = {
2453
4647
  }))
2454
4648
  }
2455
4649
  };
2456
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2457
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2458
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4650
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4651
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4652
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2459
4653
  var parseBulk = (body) => {
2460
- const source = isRecord6(body) && isRecord6(body.flags) ? body.flags : body;
2461
- const entries = Array.isArray(source) ? source.map((each) => [isRecord6(each) ? String(each.key ?? "") : "", each]) : isRecord6(source) ? Object.entries(source).filter(([key]) => key !== "replace") : [];
2462
- if (!Array.isArray(source) && !isRecord6(source)) return "expected {flags: {<key>: spec}}";
4654
+ const source = isRecord8(body) && isRecord8(body.flags) ? body.flags : body;
4655
+ const entries = Array.isArray(source) ? source.map((each) => [isRecord8(each) ? String(each.key ?? "") : "", each]) : isRecord8(source) ? Object.entries(source).filter(([key]) => key !== "replace") : [];
4656
+ if (!Array.isArray(source) && !isRecord8(source)) return "expected {flags: {<key>: spec}}";
2463
4657
  const specs = {};
2464
4658
  for (const [key, value] of entries) {
2465
4659
  if (!key) return "every flag needs a key";
@@ -2473,7 +4667,7 @@ var parseQueryResults = (value) => {
2473
4667
  if (!Array.isArray(value)) return "queryResults: [{match?, columns?, results: [[\u2026]]}]";
2474
4668
  const out = [];
2475
4669
  for (const each of value) {
2476
- if (!isRecord6(each) || !Array.isArray(each.results) || !each.results.every(Array.isArray)) {
4670
+ if (!isRecord8(each) || !Array.isArray(each.results) || !each.results.every(Array.isArray)) {
2477
4671
  return "each queryResults entry needs results: unknown[][]";
2478
4672
  }
2479
4673
  out.push({
@@ -2487,51 +4681,51 @@ var parseQueryResults = (value) => {
2487
4681
  var adminRoutes = (runtime) => {
2488
4682
  const api = (namespace) => runtime.instance(namespace);
2489
4683
  return {
2490
- "GET /flags": ({ namespace }) => json3(200, { flags: api(namespace).flagList() }),
4684
+ "GET /flags": ({ namespace }) => json5(200, { flags: api(namespace).flagList() }),
2491
4685
  "GET /flags/evaluate": ({ url, namespace }) => {
2492
4686
  const distinctId = url.searchParams.get("distinct_id");
2493
- if (!distinctId) return adminError3(400, "distinct_id is required");
4687
+ if (!distinctId) return adminError4(400, "distinct_id is required");
2494
4688
  const email = url.searchParams.get("email");
2495
4689
  const evaluations = api(namespace).evaluate({
2496
4690
  distinct_id: distinctId,
2497
4691
  ...email ? { person_properties: { email } } : {}
2498
4692
  });
2499
- return json3(200, {
4693
+ return json5(200, {
2500
4694
  flags: Object.fromEntries(evaluations.map((e) => [e.key, e.value]))
2501
4695
  });
2502
4696
  },
2503
4697
  "GET /flags/:key": ({ params, namespace }) => {
2504
4698
  const flag = api(namespace).state.flags.get(params.key);
2505
- return flag ? json3(200, adminView(flag)) : adminError3(404, `no flag ${params.key}`);
4699
+ return flag ? json5(200, adminView(flag)) : adminError4(404, `no flag ${params.key}`);
2506
4700
  },
2507
4701
  "PUT /flags/:key": ({ params, body, namespace }) => {
2508
4702
  const spec = parseFlagSpec(body);
2509
- if (typeof spec === "string") return adminError3(400, spec);
2510
- return json3(200, adminView(api(namespace).state.putFlag(params.key, spec)));
4703
+ if (typeof spec === "string") return adminError4(400, spec);
4704
+ return json5(200, adminView(api(namespace).state.putFlag(params.key, spec)));
2511
4705
  },
2512
- "DELETE /flags/:key": ({ params, namespace }) => api(namespace).state.flags.delete(params.key) ? json3(200, { deleted: params.key }) : adminError3(404, `no flag ${params.key}`),
4706
+ "DELETE /flags/:key": ({ params, namespace }) => api(namespace).state.flags.delete(params.key) ? json5(200, { deleted: params.key }) : adminError4(404, `no flag ${params.key}`),
2513
4707
  "PUT /flags": ({ body, namespace }) => {
2514
4708
  const specs = parseBulk(body);
2515
- if (typeof specs === "string") return adminError3(400, specs);
4709
+ if (typeof specs === "string") return adminError4(400, specs);
2516
4710
  const state = api(namespace).state;
2517
- if (isRecord6(body) && body.replace === true) {
4711
+ if (isRecord8(body) && body.replace === true) {
2518
4712
  for (const flag of state.listFlags()) state.flags.delete(flag.key);
2519
4713
  }
2520
4714
  for (const [key, spec] of Object.entries(specs)) state.putFlag(key, spec);
2521
- return json3(200, { flags: api(namespace).flagList() });
4715
+ return json5(200, { flags: api(namespace).flagList() });
2522
4716
  },
2523
4717
  "POST /flags/import": ({ body, namespace }) => {
2524
- const input = isRecord6(body) ? body : {};
4718
+ const input = isRecord8(body) ? body : {};
2525
4719
  const env = input.env ?? "dev";
2526
- if (env !== "dev" && env !== "prod") return adminError3(400, 'env must be "dev" or "prod"');
4720
+ if (env !== "dev" && env !== "prod") return adminError4(400, 'env must be "dev" or "prod"');
2527
4721
  const from = input.from ?? "state.json";
2528
4722
  let file;
2529
- if (isRecord6(input.state) && Array.isArray(input.state.flags)) {
4723
+ if (isRecord8(input.state) && Array.isArray(input.state.flags)) {
2530
4724
  file = input.state;
2531
4725
  } else if (from === "state.json") {
2532
4726
  file = ACME_FLAG_STATE;
2533
4727
  } else {
2534
- return adminError3(400, 'from must be "state.json" (the bundled copy) or pass "state"');
4728
+ return adminError4(400, 'from must be "state.json" (the bundled copy) or pass "state"');
2535
4729
  }
2536
4730
  const project = typeof input.project === "string" ? input.project : void 0;
2537
4731
  const specs = specsFromState(file, { env, ...project ? { project } : {} });
@@ -2540,7 +4734,7 @@ var adminRoutes = (runtime) => {
2540
4734
  for (const flag of state.listFlags()) state.flags.delete(flag.key);
2541
4735
  }
2542
4736
  for (const [key, spec] of Object.entries(specs)) state.putFlag(key, spec);
2543
- return json3(200, {
4737
+ return json5(200, {
2544
4738
  imported: Object.keys(specs).length,
2545
4739
  env,
2546
4740
  project: project ?? "member-app"
@@ -2549,17 +4743,17 @@ var adminRoutes = (runtime) => {
2549
4743
  "POST /flags/bump": ({ namespace }) => {
2550
4744
  const state = api(namespace).state;
2551
4745
  const next = state.update({ generation: state.current().generation + 1 });
2552
- return json3(200, {
4746
+ return json5(200, {
2553
4747
  generation: next.generation,
2554
4748
  note: "Nothing changed server-side. Clear the app's flag caches now (backend 60 s per user, EMR frontend 60 s / 10 s)."
2555
4749
  });
2556
4750
  },
2557
4751
  "GET /events": ({ url, namespace }) => {
2558
4752
  const since = parseSince(url.searchParams.get("since"));
2559
- if (since === null) return adminError3(400, "since must be epoch ms or ISO-8601");
4753
+ if (since === null) return adminError4(400, "since must be epoch ms or ISO-8601");
2560
4754
  const distinct = url.searchParams.get("distinct_id");
2561
4755
  const event = url.searchParams.get("event");
2562
- return json3(200, {
4756
+ return json5(200, {
2563
4757
  events: api(namespace).events({
2564
4758
  ...distinct !== null ? { distinct_id: distinct } : {},
2565
4759
  ...event !== null ? { event } : {},
@@ -2567,22 +4761,22 @@ var adminRoutes = (runtime) => {
2567
4761
  })
2568
4762
  });
2569
4763
  },
2570
- "GET /recordings": ({ namespace }) => json3(200, { count: api(namespace).state.current().recordings }),
2571
- "GET /settings": ({ namespace }) => json3(200, api(namespace).state.current()),
4764
+ "GET /recordings": ({ namespace }) => json5(200, { count: api(namespace).state.current().recordings }),
4765
+ "GET /settings": ({ namespace }) => json5(200, api(namespace).state.current()),
2572
4766
  "PUT /settings": ({ body, namespace }) => {
2573
- if (!isRecord6(body)) return adminError3(400, "expected a JSON object");
4767
+ if (!isRecord8(body)) return adminError4(400, "expected a JSON object");
2574
4768
  const patch = {};
2575
4769
  if (body.sessionRecording !== void 0) {
2576
4770
  if (typeof body.sessionRecording !== "boolean")
2577
- return adminError3(400, "sessionRecording: boolean");
4771
+ return adminError4(400, "sessionRecording: boolean");
2578
4772
  patch.sessionRecording = body.sessionRecording;
2579
4773
  }
2580
4774
  if (body.queryResults !== void 0) {
2581
4775
  const parsed = parseQueryResults(body.queryResults);
2582
- if (typeof parsed === "string") return adminError3(400, parsed);
4776
+ if (typeof parsed === "string") return adminError4(400, parsed);
2583
4777
  patch.queryResults = parsed;
2584
4778
  }
2585
- return json3(200, api(namespace).state.update(patch));
4779
+ return json5(200, api(namespace).state.update(patch));
2586
4780
  }
2587
4781
  };
2588
4782
  };
@@ -2590,7 +4784,7 @@ var createRuntime2 = (options = {}) => {
2590
4784
  const tokens = /* @__PURE__ */ new WeakMap();
2591
4785
  const runtime = createRuntime({
2592
4786
  name: POSTHOG_NAMESPACE,
2593
- document,
4787
+ document: document2,
2594
4788
  ...options.sqlite ? { sqlite: options.sqlite } : {},
2595
4789
  ...options.clock ? { clock: options.clock } : {},
2596
4790
  ...options.seed !== void 0 ? { seed: options.seed } : {},
@@ -2622,7 +4816,7 @@ var createRuntime2 = (options = {}) => {
2622
4816
 
2623
4817
  // src/index.ts
2624
4818
  var POSTHOG_NAMESPACE = "posthog";
2625
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4819
+ var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2626
4820
  var error = (status, type, code, detail, attr) => jsonRes(status, { type, code, detail, attr: attr ?? null });
2627
4821
  var invalidApiKey = () => error(
2628
4822
  401,
@@ -2660,7 +4854,7 @@ var scrubProperties = (event, properties) => {
2660
4854
  }
2661
4855
  const kept = scrubRecord(properties);
2662
4856
  for (const nested of ["$set", "$set_once"]) {
2663
- if (isRecord7(kept[nested])) kept[nested] = scrubRecord(kept[nested]);
4857
+ if (isRecord9(kept[nested])) kept[nested] = scrubRecord(kept[nested]);
2664
4858
  }
2665
4859
  return kept;
2666
4860
  };
@@ -2716,7 +4910,7 @@ var PostHogAPI = class {
2716
4910
  RunQuery: (context) => this.query(context)
2717
4911
  });
2718
4912
  this.service = createService({
2719
- document,
4913
+ document: document2,
2720
4914
  handlers,
2721
4915
  sqlite,
2722
4916
  namespace,
@@ -2781,7 +4975,7 @@ var PostHogAPI = class {
2781
4975
  }
2782
4976
  flags(context, route) {
2783
4977
  const body = this.body(context);
2784
- if (!isRecord7(body)) return malformed();
4978
+ if (!isRecord9(body)) return malformed();
2785
4979
  if (!tokenFromBody(body)) return invalidApiKey();
2786
4980
  const distinctId = body.distinct_id;
2787
4981
  if (typeof distinctId !== "string" && typeof distinctId !== "number") {
@@ -2791,7 +4985,7 @@ var PostHogAPI = class {
2791
4985
  const detailed = route === "decide" ? version >= 4 : version >= 2;
2792
4986
  const subject = {
2793
4987
  distinct_id: String(distinctId),
2794
- ...isRecord7(body.person_properties) ? { person_properties: body.person_properties } : {}
4988
+ ...isRecord9(body.person_properties) ? { person_properties: body.person_properties } : {}
2795
4989
  };
2796
4990
  const keys = [body.flag_keys_to_evaluate, body.flag_keys].find(Array.isArray);
2797
4991
  const quotaLimited = this.effect(context, "quota_limited");
@@ -2824,15 +5018,15 @@ var PostHogAPI = class {
2824
5018
  }
2825
5019
  const token = tokenFromBody(body);
2826
5020
  if (!token) return invalidApiKey();
2827
- const items = Array.isArray(body) ? body : isRecord7(body) && Array.isArray(body.batch) ? body.batch : [body];
5021
+ const items = Array.isArray(body) ? body : isRecord9(body) && Array.isArray(body.batch) ? body.batch : [body];
2828
5022
  const events = items.filter(
2829
- (item) => isRecord7(item) && typeof item.event === "string" && item.event.length > 0
5023
+ (item) => isRecord9(item) && typeof item.event === "string" && item.event.length > 0
2830
5024
  );
2831
5025
  if (events.length === 0 && items.length > 0) return malformed("Invalid payload: no event name");
2832
5026
  const stored = [];
2833
5027
  for (const raw of events) {
2834
5028
  const event = raw.event;
2835
- const properties = isRecord7(raw.properties) ? raw.properties : {};
5029
+ const properties = isRecord9(raw.properties) ? raw.properties : {};
2836
5030
  const distinct = raw.distinct_id ?? properties.distinct_id ?? raw.$distinct_id ?? properties.$distinct_id;
2837
5031
  const uuid = typeof raw.uuid === "string" && raw.uuid ? raw.uuid : this.state.nextEventId();
2838
5032
  if (this.state.events.has(uuid)) continue;
@@ -2874,7 +5068,7 @@ var PostHogAPI = class {
2874
5068
  }
2875
5069
  createFlag(context) {
2876
5070
  const body = this.body(context);
2877
- if (!isRecord7(body)) return malformed();
5071
+ if (!isRecord9(body)) return malformed();
2878
5072
  const key = body.key;
2879
5073
  if (typeof key !== "string" || !/^[A-Za-z0-9_-]+$/.test(key)) {
2880
5074
  return error(
@@ -2906,7 +5100,7 @@ var PostHogAPI = class {
2906
5100
  const flag = this.state.findFlag(context.params.flagId ?? "");
2907
5101
  if (!flag) return error(404, "invalid_request", "not_found", "Not found.");
2908
5102
  const body = this.body(context);
2909
- if (!isRecord7(body)) return malformed();
5103
+ if (!isRecord9(body)) return malformed();
2910
5104
  const patch = {};
2911
5105
  if (typeof body.name === "string") patch.name = body.name;
2912
5106
  if (typeof body.active === "boolean") patch.active = body.active;
@@ -2917,7 +5111,7 @@ var PostHogAPI = class {
2917
5111
  }
2918
5112
  query(context) {
2919
5113
  const body = this.body(context);
2920
- const query = isRecord7(body) && isRecord7(body.query) ? body.query : void 0;
5114
+ const query = isRecord9(body) && isRecord9(body.query) ? body.query : void 0;
2921
5115
  if (query?.kind !== "HogQLQuery" || typeof query.query !== "string") {
2922
5116
  return error(400, "validation_error", "invalid_input", "Expected a HogQLQuery.", "query");
2923
5117
  }
@@ -2947,7 +5141,7 @@ export {
2947
5141
  evaluateFlag,
2948
5142
  payloadString,
2949
5143
  parseFlagSpec,
2950
- document,
5144
+ document2 as document,
2951
5145
  operationIds,
2952
5146
  supportedOperationIds,
2953
5147
  ACME_FLAG_STATE,
@@ -2959,4 +5153,4 @@ export {
2959
5153
  scrubProperties,
2960
5154
  PostHogAPI
2961
5155
  };
2962
- //# sourceMappingURL=chunk-2FGITTBR.js.map
5156
+ //# sourceMappingURL=chunk-A7ITZA26.js.map