@crvouga/mockingbird-service-intercom 1.4.0 → 1.6.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
  }
@@ -616,7 +618,7 @@ var listOperations = (document2) => {
616
618
  };
617
619
 
618
620
  // ../../openapi/core/dist/schema.js
619
- var resolveSchema = (document2, schema) => {
621
+ var resolveSchema = (document3, schema) => {
620
622
  let current = schema;
621
623
  const seen = /* @__PURE__ */ new Set();
622
624
  while (typeof current.$ref === "string") {
@@ -625,7 +627,7 @@ var resolveSchema = (document2, schema) => {
625
627
  break;
626
628
  seen.add(ref);
627
629
  const { $ref: _ignored, ...siblings } = current;
628
- const target = resolveRef(document2, ref);
630
+ const target = resolveRef(document3, ref);
629
631
  current = { ...target, ...siblings };
630
632
  }
631
633
  if (current.nullable === true) {
@@ -696,71 +698,71 @@ var FORMAT_PATTERNS = {
696
698
  ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
697
699
  };
698
700
  var graphemeLength = (value) => [...value].length;
699
- var validateValue = (document2, schema, value, path = []) => {
701
+ var validateValue = (document3, schema, value, path = []) => {
700
702
  const errors = [];
701
- const s = resolveSchema(document2, schema);
702
- const fail = (message) => errors.push({ path, message });
703
+ const s = resolveSchema(document3, schema);
704
+ const fail2 = (message) => errors.push({ path, message });
703
705
  const actual = jsonTypeOf(value);
704
706
  if (actual === "undefined") {
705
- fail("value is undefined");
707
+ fail2("value is undefined");
706
708
  return errors;
707
709
  }
708
710
  const types = schemaTypes(s);
709
711
  if (types.length > 0) {
710
712
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
711
713
  if (!ok) {
712
- fail(`expected type ${types.join("|")}, got ${actual}`);
714
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
713
715
  return errors;
714
716
  }
715
717
  }
716
718
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
717
- fail("value not in enum");
719
+ fail2("value not in enum");
718
720
  }
719
721
  if (s.const !== void 0 && !deepEqual(s.const, value))
720
- fail("value does not equal const");
722
+ fail2("value does not equal const");
721
723
  if (typeof value === "string") {
722
724
  const length = graphemeLength(value);
723
725
  if (s.minLength !== void 0 && length < s.minLength)
724
- fail(`length ${length} < minLength ${s.minLength}`);
726
+ fail2(`length ${length} < minLength ${s.minLength}`);
725
727
  if (s.maxLength !== void 0 && length > s.maxLength)
726
- fail(`length ${length} > maxLength ${s.maxLength}`);
728
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
727
729
  if (s.pattern !== void 0) {
728
730
  try {
729
731
  if (!new RegExp(s.pattern, "u").test(value))
730
- fail(`does not match pattern ${s.pattern}`);
732
+ fail2(`does not match pattern ${s.pattern}`);
731
733
  } catch {
732
734
  }
733
735
  }
734
736
  if (s.format !== void 0) {
735
737
  const pattern = FORMAT_PATTERNS[s.format];
736
738
  if (pattern && !pattern.test(value))
737
- fail(`does not match format ${s.format}`);
739
+ fail2(`does not match format ${s.format}`);
738
740
  }
739
741
  }
740
742
  if (typeof value === "number") {
741
743
  if (s.minimum !== void 0 && value < s.minimum)
742
- fail(`${value} < minimum ${s.minimum}`);
744
+ fail2(`${value} < minimum ${s.minimum}`);
743
745
  if (s.maximum !== void 0 && value > s.maximum)
744
- fail(`${value} > maximum ${s.maximum}`);
746
+ fail2(`${value} > maximum ${s.maximum}`);
745
747
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
748
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
749
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
750
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
751
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
- fail(`${value} is not a multiple of ${s.multipleOf}`);
752
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
751
753
  }
752
754
  }
753
755
  if (Array.isArray(value)) {
754
756
  if (s.minItems !== void 0 && value.length < s.minItems)
755
- fail(`${value.length} items < minItems ${s.minItems}`);
757
+ fail2(`${value.length} items < minItems ${s.minItems}`);
756
758
  if (s.maxItems !== void 0 && value.length > s.maxItems)
757
- fail(`${value.length} items > maxItems ${s.maxItems}`);
759
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
758
760
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
759
- fail("items are not unique");
761
+ fail2("items are not unique");
760
762
  value.forEach((item, i) => {
761
763
  const itemSchema = s.prefixItems?.[i] ?? s.items;
762
764
  if (itemSchema)
763
- errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
765
+ errors.push(...validateValue(document3, itemSchema, item, [...path, i]));
764
766
  });
765
767
  }
766
768
  if (actual === "object") {
@@ -768,41 +770,41 @@ var validateValue = (document2, schema, value, path = []) => {
768
770
  const keys = Object.keys(record);
769
771
  for (const name of s.required ?? [])
770
772
  if (!(name in record))
771
- fail(`missing required property ${name}`);
773
+ fail2(`missing required property ${name}`);
772
774
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
775
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
774
776
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
777
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
776
778
  for (const key of keys) {
777
779
  const property = s.properties?.[key];
778
780
  if (property) {
779
- errors.push(...validateValue(document2, property, record[key], [...path, key]));
781
+ errors.push(...validateValue(document3, property, record[key], [...path, key]));
780
782
  continue;
781
783
  }
782
784
  if (s.additionalProperties === false)
783
- fail(`unexpected property ${key}`);
785
+ fail2(`unexpected property ${key}`);
784
786
  else if (typeof s.additionalProperties === "object") {
785
- errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
787
+ errors.push(...validateValue(document3, s.additionalProperties, record[key], [...path, key]));
786
788
  }
787
789
  if (s.propertyNames) {
788
- const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
790
+ const nameErrors = validateValue(document3, s.propertyNames, key, [...path, key]);
789
791
  if (nameErrors.length > 0)
790
- fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
792
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
791
793
  }
792
794
  }
793
795
  }
794
796
  if (s.allOf)
795
797
  for (const branch of s.allOf)
796
- errors.push(...validateValue(document2, branch, value, path));
797
- if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
798
- fail("matches no anyOf branch");
798
+ errors.push(...validateValue(document3, branch, value, path));
799
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document3, branch, value).length === 0))
800
+ fail2("matches no anyOf branch");
799
801
  if (s.oneOf) {
800
- const matches3 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
802
+ const matches3 = s.oneOf.filter((branch) => validateValue(document3, branch, value).length === 0).length;
801
803
  if (matches3 !== 1)
802
- fail(`matches ${matches3} oneOf branches, expected exactly 1`);
804
+ fail2(`matches ${matches3} oneOf branches, expected exactly 1`);
803
805
  }
804
- if (s.not && validateValue(document2, s.not, value).length === 0)
805
- fail("matches forbidden `not` schema");
806
+ if (s.not && validateValue(document3, s.not, value).length === 0)
807
+ fail2("matches forbidden `not` schema");
806
808
  return errors;
807
809
  };
808
810
 
@@ -1442,6 +1444,1737 @@ var clearNamespace = (sqlite, namespace) => {
1442
1444
  });
1443
1445
  };
1444
1446
 
1447
+ // ../../ui/dist/reset.js
1448
+ var CSS_RESET = `*,
1449
+ *::before,
1450
+ *::after {
1451
+ box-sizing: border-box;
1452
+ margin: 0;
1453
+ padding: 0;
1454
+ }
1455
+
1456
+ * {
1457
+ scrollbar-width: thin;
1458
+ scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;
1459
+ }
1460
+
1461
+ *::-webkit-scrollbar {
1462
+ width: 12px;
1463
+ height: 12px;
1464
+ }
1465
+
1466
+ *::-webkit-scrollbar-track,
1467
+ *::-webkit-scrollbar-corner {
1468
+ background: Canvas;
1469
+ }
1470
+
1471
+ *::-webkit-scrollbar-thumb {
1472
+ background: color-mix(in srgb, CanvasText 35%, Canvas);
1473
+ border: 3px solid Canvas;
1474
+ border-radius: 999px;
1475
+ }
1476
+
1477
+ html {
1478
+ hanging-punctuation: first allow-end last;
1479
+ -webkit-text-size-adjust: none;
1480
+ text-size-adjust: none;
1481
+ tab-size: 4;
1482
+ font-family:
1483
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI",
1484
+ "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
1485
+ font-size: 16px;
1486
+ line-height: 1.5;
1487
+ -webkit-font-smoothing: antialiased;
1488
+ -moz-osx-font-smoothing: grayscale;
1489
+ text-rendering: optimizeLegibility;
1490
+ -webkit-tap-highlight-color: transparent;
1491
+ scroll-behavior: smooth;
1492
+ background: Canvas;
1493
+ color: CanvasText;
1494
+ }
1495
+
1496
+ body {
1497
+ min-height: 100svh;
1498
+ line-height: 1.5;
1499
+ background: Canvas;
1500
+ color: CanvasText;
1501
+ }
1502
+
1503
+ h1 {
1504
+ font-size: 2em;
1505
+ }
1506
+
1507
+ h2 {
1508
+ font-size: 1.5em;
1509
+ }
1510
+
1511
+ h3 {
1512
+ font-size: 1.17em;
1513
+ }
1514
+
1515
+ h4 {
1516
+ font-size: 1em;
1517
+ }
1518
+
1519
+ h5 {
1520
+ font-size: 0.83em;
1521
+ }
1522
+
1523
+ h6 {
1524
+ font-size: 0.67em;
1525
+ }
1526
+
1527
+ h1,
1528
+ h2,
1529
+ h3,
1530
+ h4,
1531
+ h5,
1532
+ h6 {
1533
+ font-weight: 700;
1534
+ line-height: 1.2;
1535
+ text-wrap: balance;
1536
+ overflow-wrap: break-word;
1537
+ }
1538
+
1539
+ p,
1540
+ li,
1541
+ figcaption,
1542
+ dd,
1543
+ dt,
1544
+ blockquote {
1545
+ overflow-wrap: break-word;
1546
+ }
1547
+
1548
+ p,
1549
+ li,
1550
+ figcaption,
1551
+ blockquote {
1552
+ text-wrap: pretty;
1553
+ }
1554
+
1555
+ ul,
1556
+ ol,
1557
+ menu {
1558
+ list-style: none;
1559
+ }
1560
+
1561
+ a {
1562
+ color: inherit;
1563
+ text-decoration: underline;
1564
+ text-decoration-thickness: 1px;
1565
+ text-underline-offset: 0.15em;
1566
+ text-decoration-skip-ink: auto;
1567
+ }
1568
+
1569
+ b,
1570
+ strong {
1571
+ font-weight: 700;
1572
+ }
1573
+
1574
+ small {
1575
+ font-size: 0.875em;
1576
+ }
1577
+
1578
+ code,
1579
+ kbd,
1580
+ samp,
1581
+ pre {
1582
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1583
+ font-size: 1em;
1584
+ }
1585
+
1586
+ sub,
1587
+ sup {
1588
+ font-size: 75%;
1589
+ line-height: 0;
1590
+ position: relative;
1591
+ vertical-align: baseline;
1592
+ }
1593
+
1594
+ sub {
1595
+ bottom: -0.25em;
1596
+ }
1597
+
1598
+ sup {
1599
+ top: -0.5em;
1600
+ }
1601
+
1602
+ abbr[title] {
1603
+ text-decoration: underline dotted;
1604
+ text-underline-offset: 0.15em;
1605
+ }
1606
+
1607
+ mark {
1608
+ background: Mark;
1609
+ color: MarkText;
1610
+ }
1611
+
1612
+ hr {
1613
+ height: 0;
1614
+ border: 0;
1615
+ border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1616
+ color: inherit;
1617
+ }
1618
+
1619
+ img,
1620
+ picture,
1621
+ video,
1622
+ canvas {
1623
+ display: block;
1624
+ max-width: 100%;
1625
+ }
1626
+
1627
+ img,
1628
+ video {
1629
+ height: auto;
1630
+ }
1631
+
1632
+ svg {
1633
+ overflow: hidden;
1634
+ }
1635
+
1636
+ iframe {
1637
+ border: 0;
1638
+ max-width: 100%;
1639
+ }
1640
+
1641
+ table {
1642
+ border-collapse: collapse;
1643
+ border-spacing: 0;
1644
+ }
1645
+
1646
+ fieldset {
1647
+ border: 0;
1648
+ min-inline-size: 0;
1649
+ }
1650
+
1651
+ legend {
1652
+ padding: 0;
1653
+ }
1654
+
1655
+ button,
1656
+ input,
1657
+ select,
1658
+ textarea,
1659
+ optgroup {
1660
+ font: inherit;
1661
+ letter-spacing: inherit;
1662
+ color: inherit;
1663
+ margin: 0;
1664
+ vertical-align: middle;
1665
+ }
1666
+
1667
+ button,
1668
+ input[type="button"],
1669
+ input[type="submit"],
1670
+ input[type="reset"] {
1671
+ appearance: none;
1672
+ background: none;
1673
+ border: 0;
1674
+ padding: 0;
1675
+ cursor: pointer;
1676
+ text-align: center;
1677
+ }
1678
+
1679
+ input,
1680
+ textarea,
1681
+ select {
1682
+ background-color: Canvas;
1683
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1684
+ border-radius: 0;
1685
+ padding: 0.5em 0.65em;
1686
+ }
1687
+
1688
+ input[type="checkbox"],
1689
+ input[type="radio"],
1690
+ input[type="range"],
1691
+ input[type="file"],
1692
+ input[type="color"],
1693
+ input[type="button"],
1694
+ input[type="submit"],
1695
+ input[type="reset"],
1696
+ input[type="image"],
1697
+ input[type="hidden"] {
1698
+ background: none;
1699
+ border: 0;
1700
+ padding: 0;
1701
+ border-radius: 0;
1702
+ }
1703
+
1704
+ input[type="checkbox"],
1705
+ input[type="radio"] {
1706
+ accent-color: CanvasText;
1707
+ }
1708
+
1709
+ input[type="search"] {
1710
+ appearance: none;
1711
+ background-color: Canvas;
1712
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1713
+ }
1714
+
1715
+ input[type="search"]::-webkit-search-decoration,
1716
+ input[type="search"]::-webkit-search-cancel-button,
1717
+ input[type="search"]::-webkit-search-results-button,
1718
+ input[type="search"]::-webkit-search-results-decoration {
1719
+ -webkit-appearance: none;
1720
+ display: none;
1721
+ }
1722
+
1723
+ input[type="number"] {
1724
+ appearance: textfield;
1725
+ background-color: Canvas;
1726
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1727
+ }
1728
+
1729
+ input[type="number"]::-webkit-inner-spin-button,
1730
+ input[type="number"]::-webkit-outer-spin-button {
1731
+ -webkit-appearance: none;
1732
+ margin: 0;
1733
+ }
1734
+
1735
+ textarea {
1736
+ resize: vertical;
1737
+ }
1738
+
1739
+ ::placeholder {
1740
+ opacity: 1;
1741
+ color: color-mix(in srgb, CanvasText 45%, transparent);
1742
+ }
1743
+
1744
+ :focus-visible {
1745
+ outline: 2px solid CanvasText;
1746
+ outline-offset: 2px;
1747
+ }
1748
+
1749
+ :focus:not(:focus-visible) {
1750
+ outline: none;
1751
+ }
1752
+
1753
+ :disabled,
1754
+ [disabled] {
1755
+ cursor: default;
1756
+ opacity: 0.6;
1757
+ }
1758
+
1759
+ label,
1760
+ summary,
1761
+ select,
1762
+ [role="button"] {
1763
+ cursor: pointer;
1764
+ }
1765
+
1766
+ summary {
1767
+ display: list-item;
1768
+ }
1769
+
1770
+ details {
1771
+ display: block;
1772
+ }
1773
+
1774
+ dialog {
1775
+ margin: auto;
1776
+ padding: 1rem;
1777
+ border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1778
+ background: Canvas;
1779
+ color: CanvasText;
1780
+ max-width: calc(100vw - 2rem);
1781
+ max-height: calc(100svh - 2rem);
1782
+ }
1783
+
1784
+ dialog:not([open]) {
1785
+ display: none;
1786
+ }
1787
+
1788
+ ::backdrop {
1789
+ background: color-mix(in srgb, CanvasText 40%, transparent);
1790
+ }
1791
+
1792
+ [hidden] {
1793
+ display: none !important;
1794
+ }
1795
+
1796
+ ::selection {
1797
+ background: Highlight;
1798
+ color: HighlightText;
1799
+ }
1800
+
1801
+ @media (prefers-reduced-motion: reduce) {
1802
+ *,
1803
+ *::before,
1804
+ *::after {
1805
+ animation-duration: 0.01ms !important;
1806
+ animation-iteration-count: 1 !important;
1807
+ transition-duration: 0.01ms !important;
1808
+ scroll-behavior: auto !important;
1809
+ }
1810
+ }
1811
+
1812
+ @media (pointer: coarse) {
1813
+ input,
1814
+ select,
1815
+ textarea {
1816
+ font-size: max(16px, 1em);
1817
+ }
1818
+ }`;
1819
+
1820
+ // ../core/dist/admin-client.js
1821
+ function isRecord2(value) {
1822
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1823
+ }
1824
+ function mountAdminBrand(doc, host, service, catalog) {
1825
+ const clip = (value, max) => {
1826
+ if (typeof value !== "string")
1827
+ return null;
1828
+ const trimmed = value.trim();
1829
+ if (trimmed === "")
1830
+ return null;
1831
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
1832
+ };
1833
+ const httpUrl = (value) => {
1834
+ if (typeof value !== "string" || value.length > 2e3)
1835
+ return null;
1836
+ try {
1837
+ const url = new URL(value);
1838
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1839
+ return null;
1840
+ return url.href;
1841
+ } catch {
1842
+ return null;
1843
+ }
1844
+ };
1845
+ const hexColor = (value) => {
1846
+ if (typeof value !== "string")
1847
+ return null;
1848
+ const raw = value.trim();
1849
+ return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null;
1850
+ };
1851
+ const hostname = (value) => {
1852
+ try {
1853
+ return new URL(value).hostname.replace(/^www\./, "");
1854
+ } catch {
1855
+ return value;
1856
+ }
1857
+ };
1858
+ host.replaceChildren();
1859
+ host.hidden = true;
1860
+ if (!isRecord2(catalog) || !Object.hasOwn(catalog, service))
1861
+ return;
1862
+ const row = catalog[service];
1863
+ if (!isRecord2(row))
1864
+ return;
1865
+ const vendor = clip(row.vendor, 80);
1866
+ const website = httpUrl(row.website);
1867
+ const guide = httpUrl(row.guide);
1868
+ const docs = httpUrl(row.docs);
1869
+ const logo = httpUrl(row.logo);
1870
+ const color = hexColor(row.color);
1871
+ const description = clip(row.description, 280);
1872
+ if (vendor === null || website === null && guide === null && docs === null)
1873
+ return;
1874
+ const add = (node) => {
1875
+ host.append(node);
1876
+ return node;
1877
+ };
1878
+ if (logo !== null) {
1879
+ const img = doc.createElement("img");
1880
+ img.alt = "";
1881
+ img.src = logo;
1882
+ img.width = 16;
1883
+ img.height = 16;
1884
+ img.decoding = "async";
1885
+ img.referrerPolicy = "no-referrer";
1886
+ if (color !== null)
1887
+ img.style.borderColor = color;
1888
+ add(img);
1889
+ }
1890
+ const name = doc.createElement("span");
1891
+ name.className = "vendor-name";
1892
+ name.textContent = vendor;
1893
+ if (description !== null)
1894
+ name.title = description;
1895
+ add(name);
1896
+ const sep = () => {
1897
+ const node = doc.createElement("span");
1898
+ node.className = "vendor-sep";
1899
+ node.setAttribute("aria-hidden", "true");
1900
+ node.textContent = "\xB7";
1901
+ return node;
1902
+ };
1903
+ const link = (href, label, title) => {
1904
+ const node = doc.createElement("a");
1905
+ node.className = "vendor-link";
1906
+ node.href = href;
1907
+ node.target = "_blank";
1908
+ node.rel = "noopener noreferrer";
1909
+ node.referrerPolicy = "no-referrer";
1910
+ node.textContent = label;
1911
+ node.title = title;
1912
+ return node;
1913
+ };
1914
+ if (website !== null) {
1915
+ add(sep());
1916
+ add(link(website, hostname(website), `${vendor} website`));
1917
+ }
1918
+ if (guide !== null) {
1919
+ add(sep());
1920
+ add(link(guide, "Docs", `Docs for ${vendor}`));
1921
+ }
1922
+ if (docs !== null) {
1923
+ add(sep());
1924
+ add(link(docs, "API", `${vendor} API reference`));
1925
+ }
1926
+ host.removeAttribute("hidden");
1927
+ host.hidden = false;
1928
+ }
1929
+ function startAdminBrand(env) {
1930
+ const requested = env.params.get("brands");
1931
+ let brandsUrl = env.brandsUrl;
1932
+ if (requested) {
1933
+ try {
1934
+ const url = new URL(requested, env.location.href);
1935
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]" || url.origin === env.location.origin;
1936
+ if ((url.protocol === "https:" || url.protocol === "http:") && local)
1937
+ brandsUrl = url.href;
1938
+ } catch {
1939
+ brandsUrl = env.brandsUrl;
1940
+ }
1941
+ }
1942
+ const vendorHost = env.$("vendor");
1943
+ const brandRoot = env.document.querySelector("[data-mockingbird-admin]");
1944
+ const brandService = brandRoot?.getAttribute("data-service") || "";
1945
+ if (vendorHost === null)
1946
+ return;
1947
+ env.fetch(brandsUrl, {
1948
+ headers: { accept: "application/json" },
1949
+ signal: AbortSignal.timeout(5e3)
1950
+ }).then(async (response) => {
1951
+ if (!response.ok)
1952
+ return null;
1953
+ const catalog = await response.json();
1954
+ return catalog;
1955
+ }).then((catalog) => {
1956
+ mountAdminBrand(env.document, vendorHost, brandService, catalog);
1957
+ }).catch(() => {
1958
+ });
1959
+ }
1960
+ function faultPresetList(value) {
1961
+ if (!isRecord2(value))
1962
+ throw new Error("Fault presets response was not an object");
1963
+ if (!Object.hasOwn(value, "presets") || value.presets === void 0 || value.presets === null) {
1964
+ return { presets: [] };
1965
+ }
1966
+ if (!Array.isArray(value.presets))
1967
+ throw new Error("Fault presets response was not a list");
1968
+ return {
1969
+ presets: value.presets.flatMap((item) => {
1970
+ if (!isRecord2(item) || typeof item.name !== "string")
1971
+ return [];
1972
+ return [{ name: item.name }];
1973
+ })
1974
+ };
1975
+ }
1976
+ function bootAdmin(config) {
1977
+ const fieldKinds = ["string", "number", "boolean", "null", "object", "array", "unknown"];
1978
+ const sources = ["declared", "inferred", "mixed"];
1979
+ const isFieldKind = (value) => typeof value === "string" && fieldKinds.some((kind) => kind === value);
1980
+ const isSource = (value) => typeof value === "string" && sources.some((source) => source === value);
1981
+ const readJson2 = (text2) => {
1982
+ const value = JSON.parse(text2);
1983
+ return value;
1984
+ };
1985
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => {
1986
+ switch (char) {
1987
+ case "&":
1988
+ return "&amp;";
1989
+ case "<":
1990
+ return "&lt;";
1991
+ case ">":
1992
+ return "&gt;";
1993
+ case '"':
1994
+ return "&quot;";
1995
+ default:
1996
+ return "&#39;";
1997
+ }
1998
+ });
1999
+ const el = (id, kind) => {
2000
+ const node = document.getElementById(id);
2001
+ if (!(node instanceof kind))
2002
+ throw new Error(`admin shell is missing #${id}`);
2003
+ return node;
2004
+ };
2005
+ const errorMessage = (data, fallback) => {
2006
+ if (!isRecord2(data))
2007
+ return fallback;
2008
+ const error = data.error;
2009
+ if (!isRecord2(error) || typeof error.message !== "string" || error.message === "") {
2010
+ return fallback;
2011
+ }
2012
+ return error.message;
2013
+ };
2014
+ const requireList = (value, label) => {
2015
+ if (value === void 0 || value === null)
2016
+ return [];
2017
+ if (!Array.isArray(value))
2018
+ throw new Error(`${label} was not a list`);
2019
+ return value;
2020
+ };
2021
+ const state = {
2022
+ namespace: "default",
2023
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
2024
+ view: "overview",
2025
+ collection: "",
2026
+ shape: null,
2027
+ route: null,
2028
+ editing: null
2029
+ };
2030
+ const standard = new Set(config.standardRoutes);
2031
+ const banner = el("banner", HTMLElement);
2032
+ const keyInput = el("admin-key", HTMLInputElement);
2033
+ keyInput.value = state.key;
2034
+ const params = new URLSearchParams(location.search);
2035
+ const queryKey = params.get("key");
2036
+ if (queryKey) {
2037
+ state.key = queryKey;
2038
+ keyInput.value = state.key;
2039
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2040
+ params.delete("key");
2041
+ const next = params.toString();
2042
+ history.replaceState(null, "", location.pathname + (next ? `?${next}` : ""));
2043
+ }
2044
+ const queryNamespace = params.get("namespace");
2045
+ if (queryNamespace)
2046
+ state.namespace = queryNamespace;
2047
+ const showError = (error) => {
2048
+ banner.textContent = error instanceof Error ? error.message : String(error);
2049
+ banner.classList.add("show");
2050
+ };
2051
+ const clearError = () => {
2052
+ banner.classList.remove("show");
2053
+ };
2054
+ const api = async (method, path, body) => {
2055
+ const headers = { accept: "application/json" };
2056
+ if (state.key !== "")
2057
+ headers[config.adminKeyHeader] = state.key;
2058
+ if (state.namespace !== "")
2059
+ headers["x-mockingbird-namespace"] = state.namespace;
2060
+ if (body !== void 0)
2061
+ headers["content-type"] = "application/json";
2062
+ const init = { method, headers };
2063
+ if (body !== void 0)
2064
+ init.body = JSON.stringify(body);
2065
+ const response = await fetch(config.adminPrefix + path, init);
2066
+ const text2 = await response.text();
2067
+ let data = null;
2068
+ if (text2 !== "") {
2069
+ try {
2070
+ data = readJson2(text2);
2071
+ } catch {
2072
+ data = { raw: text2 };
2073
+ }
2074
+ }
2075
+ if (response.status === 401) {
2076
+ keyInput.focus();
2077
+ throw new Error(errorMessage(data, "Admin key required"));
2078
+ }
2079
+ if (!response.ok) {
2080
+ throw new Error(errorMessage(data, `${response.status} ${method} ${path}`));
2081
+ }
2082
+ return data;
2083
+ };
2084
+ const originGet = async (path) => {
2085
+ const response = await fetch(path, { headers: { accept: "application/json" } });
2086
+ if (!response.ok)
2087
+ throw new Error(`${response.status} ${path}`);
2088
+ const value = await response.json();
2089
+ return value;
2090
+ };
2091
+ const panelApi = {
2092
+ get: (path) => api("GET", path),
2093
+ send: (method, path, body) => api(method, path, body),
2094
+ namespace: () => state.namespace
2095
+ };
2096
+ const isPanelScript = (value) => typeof value === "function";
2097
+ const setTheme = (theme) => {
2098
+ if (theme)
2099
+ document.documentElement.dataset.theme = theme;
2100
+ else
2101
+ delete document.documentElement.dataset.theme;
2102
+ };
2103
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme");
2104
+ if (storedTheme)
2105
+ setTheme(storedTheme);
2106
+ el("theme", HTMLButtonElement).addEventListener("click", () => {
2107
+ const current = document.documentElement.dataset.theme;
2108
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
2109
+ const next = dark ? "light" : "dark";
2110
+ localStorage.setItem("mockingbird-admin-theme", next);
2111
+ setTheme(next);
2112
+ });
2113
+ const show = (view) => {
2114
+ state.view = view;
2115
+ for (const button of document.querySelectorAll("#nav button")) {
2116
+ if (!(button instanceof HTMLButtonElement))
2117
+ continue;
2118
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false");
2119
+ }
2120
+ for (const section of document.querySelectorAll("main .view")) {
2121
+ if (!(section instanceof HTMLElement))
2122
+ continue;
2123
+ section.hidden = section.id !== `view-${view}`;
2124
+ }
2125
+ };
2126
+ el("nav", HTMLElement).addEventListener("click", (event) => {
2127
+ const target = event.target;
2128
+ if (!(target instanceof Element))
2129
+ return;
2130
+ const button = target.closest("button[data-view]");
2131
+ if (!(button instanceof HTMLButtonElement))
2132
+ return;
2133
+ const view = button.dataset.view;
2134
+ if (view === void 0)
2135
+ return;
2136
+ show(view);
2137
+ refresh().catch(showError);
2138
+ });
2139
+ 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>`;
2140
+ const table = (columns, rows) => {
2141
+ if (rows.length === 0)
2142
+ return '<p class="empty">Nothing here yet.</p>';
2143
+ const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join("")}</tr>`;
2144
+ const body = rows.map((row) => {
2145
+ const cells = columns.map((column) => `<td data-label="${column.label}">${column.cell(row)}</td>`).join("");
2146
+ const attrs = "attrs" in row && typeof row.attrs === "string" ? row.attrs : "";
2147
+ return `<tr${attrs}>${cells}</tr>`;
2148
+ }).join("");
2149
+ return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`;
2150
+ };
2151
+ const preview = (value) => {
2152
+ const text2 = JSON.stringify(value) ?? "null";
2153
+ return esc(text2.length > 180 ? `${text2.slice(0, 180)}\u2026` : text2);
2154
+ };
2155
+ const when = (epoch) => {
2156
+ const date = new Date(epoch);
2157
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString();
2158
+ };
2159
+ const clockCard = (epoch) => {
2160
+ const date = new Date(epoch);
2161
+ if (Number.isNaN(date.getTime()))
2162
+ return esc(String(epoch));
2163
+ const iso = date.toISOString();
2164
+ return `${esc(iso.slice(0, 10))}<span class="clock-time">${esc(iso.slice(11, 19))} UTC</span>`;
2165
+ };
2166
+ const decodeClock = (value) => {
2167
+ if (!isRecord2(value) || typeof value.now !== "number" || typeof value.offsetMs !== "number" || typeof value.frozen !== "boolean") {
2168
+ throw new Error("Clock response was not a clock");
2169
+ }
2170
+ return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen };
2171
+ };
2172
+ const decodeField = (value) => {
2173
+ if (!isRecord2(value) || typeof value.name !== "string" || !isFieldKind(value.kind)) {
2174
+ return void 0;
2175
+ }
2176
+ const field = {
2177
+ name: value.name,
2178
+ kind: value.kind,
2179
+ optional: value.optional === true
2180
+ };
2181
+ if (typeof value.description === "string")
2182
+ field.description = value.description;
2183
+ if (Array.isArray(value.fields)) {
2184
+ field.fields = value.fields.flatMap((item) => {
2185
+ const child = decodeField(item);
2186
+ return child === void 0 ? [] : [child];
2187
+ });
2188
+ }
2189
+ return field;
2190
+ };
2191
+ const decodeCollection = (value) => {
2192
+ if (!isRecord2(value) || typeof value.name !== "string")
2193
+ return void 0;
2194
+ const fields = Array.isArray(value.fields) ? value.fields.flatMap((item) => {
2195
+ const field = decodeField(item);
2196
+ return field === void 0 ? [] : [field];
2197
+ }) : [];
2198
+ const collection = {
2199
+ name: value.name,
2200
+ label: typeof value.label === "string" ? value.label : value.name,
2201
+ count: typeof value.count === "number" ? value.count : 0,
2202
+ source: isSource(value.source) ? value.source : "inferred",
2203
+ fields
2204
+ };
2205
+ if (typeof value.description === "string")
2206
+ collection.description = value.description;
2207
+ return collection;
2208
+ };
2209
+ const decodeState = (value) => {
2210
+ if (!isRecord2(value) || !Array.isArray(value.collections)) {
2211
+ throw new Error("State response has no collection list");
2212
+ }
2213
+ return {
2214
+ namespace: typeof value.namespace === "string" ? value.namespace : state.namespace,
2215
+ storageNamespace: typeof value.storageNamespace === "string" ? value.storageNamespace : "",
2216
+ collections: value.collections.flatMap((item) => {
2217
+ const collection = decodeCollection(item);
2218
+ return collection === void 0 ? [] : [collection];
2219
+ })
2220
+ };
2221
+ };
2222
+ const decodeRecords = (value) => requireList(isRecord2(value) ? value.records : void 0, "Records").flatMap((item) => {
2223
+ if (!isRecord2(item) || typeof item.id !== "string")
2224
+ return [];
2225
+ return [
2226
+ {
2227
+ id: item.id,
2228
+ seq: typeof item.seq === "number" ? item.seq : 0,
2229
+ value: item.value,
2230
+ attrs: ` class="clickable" data-id="${esc(item.id)}"`
2231
+ }
2232
+ ];
2233
+ });
2234
+ const textOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : "";
2235
+ const decodeJournal = (value) => requireList(isRecord2(value) ? value.requests : void 0, "Journal").flatMap((item) => {
2236
+ if (!isRecord2(item))
2237
+ return [];
2238
+ return [
2239
+ {
2240
+ at: textOf(item.at),
2241
+ method: textOf(item.method),
2242
+ path: textOf(item.path),
2243
+ status: textOf(item.status),
2244
+ durationMs: textOf(item.durationMs),
2245
+ operationId: textOf(item.operationId)
2246
+ }
2247
+ ];
2248
+ });
2249
+ const decodeFaults = (value) => requireList(isRecord2(value) ? value.faults : void 0, "Faults").flatMap((item) => {
2250
+ if (!isRecord2(item))
2251
+ return [];
2252
+ return [
2253
+ {
2254
+ id: textOf(item.id),
2255
+ method: typeof item.method === "string" ? item.method : void 0,
2256
+ pathPrefix: typeof item.pathPrefix === "string" ? item.pathPrefix : void 0,
2257
+ operationId: typeof item.operationId === "string" ? item.operationId : void 0,
2258
+ status: typeof item.status === "number" ? item.status : void 0,
2259
+ effect: typeof item.effect === "string" ? item.effect : void 0,
2260
+ drop: typeof item.drop === "boolean" ? item.drop : void 0,
2261
+ latencyMs: typeof item.latencyMs === "number" ? item.latencyMs : void 0
2262
+ }
2263
+ ];
2264
+ });
2265
+ const loadNamespaces = async () => {
2266
+ const data = await api("GET", "/namespaces");
2267
+ const select = el("namespace", HTMLSelectElement);
2268
+ const listed = requireList(isRecord2(data) ? data.namespaces : void 0, "Namespaces");
2269
+ const fallback = isRecord2(data) && typeof data.default === "string" && data.default !== "" ? data.default : "default";
2270
+ const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice();
2271
+ if (!names.includes(state.namespace))
2272
+ names.unshift(state.namespace);
2273
+ select.innerHTML = names.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join("");
2274
+ select.value = state.namespace;
2275
+ };
2276
+ const renderOverview = async () => {
2277
+ const [health, shape, clock, journal] = await Promise.all([
2278
+ originGet("/health"),
2279
+ api("GET", "/state"),
2280
+ api("GET", "/clock"),
2281
+ api("GET", "/requests?limit=8")
2282
+ ]);
2283
+ if (!isRecord2(health))
2284
+ throw new Error("Health response was not an object");
2285
+ const decoded = decodeState(shape);
2286
+ state.shape = decoded;
2287
+ const time = decodeClock(clock);
2288
+ el("overview-cards", HTMLElement).innerHTML = cards([
2289
+ {
2290
+ k: "Service",
2291
+ v: esc(typeof health.service === "string" && health.service !== "" ? health.service : config.service)
2292
+ },
2293
+ {
2294
+ k: "Status",
2295
+ v: esc(typeof health.status === "string" && health.status !== "" ? health.status : "ok")
2296
+ },
2297
+ { k: "Namespace", v: esc(state.namespace) },
2298
+ { k: "Collections", v: String(decoded.collections.length) },
2299
+ {
2300
+ k: "Records",
2301
+ v: String(decoded.collections.reduce((sum, item) => sum + item.count, 0))
2302
+ },
2303
+ { k: "Clock", v: clockCard(time.now) }
2304
+ ]);
2305
+ el("overview-requests", HTMLElement).innerHTML = table([
2306
+ { label: "Method", cell: (row) => esc(row.method) },
2307
+ { label: "Path", cell: (row) => esc(row.path) },
2308
+ {
2309
+ label: "Status",
2310
+ cell: (row) => `<span class="status-${row.status.charAt(0)}">${esc(row.status)}</span>`
2311
+ },
2312
+ { label: "Operation", cell: (row) => esc(row.operationId) }
2313
+ ], decodeJournal(journal));
2314
+ };
2315
+ const schemaChips = (collection) => {
2316
+ if (collection.fields.length === 0) {
2317
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>';
2318
+ }
2319
+ return `<div class="chips">${collection.fields.map((field) => `<span class="chip">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? "?" : ""}</i></span>`).join("")}</div>`;
2320
+ };
2321
+ const renderState = async () => {
2322
+ const shape = decodeState(await api("GET", "/state"));
2323
+ state.shape = shape;
2324
+ const host = el("collections", HTMLElement);
2325
+ if (shape.collections.length === 0) {
2326
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>';
2327
+ el("schema", HTMLElement).innerHTML = "";
2328
+ el("records", HTMLElement).innerHTML = "";
2329
+ return;
2330
+ }
2331
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2332
+ const first = shape.collections[0];
2333
+ if (first === void 0)
2334
+ return;
2335
+ state.collection = first.name;
2336
+ }
2337
+ 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("");
2338
+ const selected = shape.collections.find((item) => item.name === state.collection);
2339
+ if (selected === void 0)
2340
+ return;
2341
+ const description = selected.description ? `<p class="lede">${esc(selected.description)}</p>` : "";
2342
+ el("schema", HTMLElement).innerHTML = `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`;
2343
+ const page = await api("GET", `/state/${encodeURIComponent(state.collection)}?limit=50`);
2344
+ el("records", HTMLElement).innerHTML = table([
2345
+ { label: "Id", cell: (row) => `<code>${esc(row.id)}</code>` },
2346
+ { label: "Seq", cell: (row) => esc(row.seq) },
2347
+ { label: "Value", cell: (row) => preview(row.value) }
2348
+ ], decodeRecords(page));
2349
+ };
2350
+ const renderClock = async () => {
2351
+ const clock = decodeClock(await api("GET", "/clock"));
2352
+ 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>`;
2353
+ const freeze = el("freeze", HTMLButtonElement);
2354
+ freeze.textContent = clock.frozen ? "Unfreeze" : "Freeze";
2355
+ freeze.dataset.frozen = clock.frozen ? "1" : "0";
2356
+ };
2357
+ const renderFaults = async () => {
2358
+ const [faults, presets] = await Promise.all([
2359
+ api("GET", "/faults"),
2360
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2361
+ ]);
2362
+ const select = el("fault-preset", HTMLSelectElement);
2363
+ const current = select.value;
2364
+ const list = faultPresetList(presets).presets;
2365
+ select.innerHTML = `<option value="">Custom rule</option>${list.map((preset) => `<option value="${esc(preset.name)}">${esc(preset.name)}</option>`).join("")}`;
2366
+ select.value = current;
2367
+ el("fault-list", HTMLElement).innerHTML = table([
2368
+ { label: "Id", cell: (row) => esc(row.id) },
2369
+ {
2370
+ label: "Match",
2371
+ cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter((part) => Boolean(part)).join(" ") || "all")
2372
+ },
2373
+ {
2374
+ label: "Effect",
2375
+ cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || ""))
2376
+ }
2377
+ ], decodeFaults(faults));
2378
+ };
2379
+ const renderJournal = async () => {
2380
+ const journal = await api("GET", "/requests?limit=100");
2381
+ el("journal", HTMLElement).innerHTML = table([
2382
+ { label: "When", cell: (row) => esc(row.at) },
2383
+ { label: "Method", cell: (row) => esc(row.method) },
2384
+ { label: "Path", cell: (row) => esc(row.path) },
2385
+ { label: "Status", cell: (row) => esc(row.status) },
2386
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2387
+ ], decodeJournal(journal));
2388
+ };
2389
+ const renderRoutes = async () => {
2390
+ const data = await api("GET", "/");
2391
+ if (!isRecord2(data))
2392
+ throw new Error("Route list was not an object");
2393
+ const routes = requireList(data.routes, "Routes").map((route) => String(route));
2394
+ el("route-list", HTMLElement).innerHTML = routes.map((route) => {
2395
+ const extra = standard.has(route) ? "" : " <span class='badge'>extension</span>";
2396
+ const parts = route.split(" ");
2397
+ const method = parts[0] ?? "";
2398
+ const path = parts.slice(1).join(" ");
2399
+ 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>`;
2400
+ }).join("");
2401
+ };
2402
+ const renderers = {
2403
+ overview: renderOverview,
2404
+ state: renderState,
2405
+ clock: renderClock,
2406
+ faults: renderFaults,
2407
+ journal: renderJournal,
2408
+ routes: renderRoutes
2409
+ };
2410
+ async function refresh() {
2411
+ clearError();
2412
+ const render = renderers[state.view];
2413
+ if (render)
2414
+ await render();
2415
+ }
2416
+ el("namespace", HTMLSelectElement).addEventListener("change", () => {
2417
+ state.namespace = el("namespace", HTMLSelectElement).value;
2418
+ refresh().catch(showError);
2419
+ });
2420
+ keyInput.addEventListener("change", () => {
2421
+ state.key = keyInput.value.trim();
2422
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2423
+ refresh().catch(showError);
2424
+ });
2425
+ el("refresh", HTMLButtonElement).addEventListener("click", () => {
2426
+ refresh().catch(showError);
2427
+ });
2428
+ el("collections", HTMLElement).addEventListener("click", (event) => {
2429
+ const target = event.target;
2430
+ if (!(target instanceof Element))
2431
+ return;
2432
+ const button = target.closest("[data-collection]");
2433
+ if (!(button instanceof HTMLElement))
2434
+ return;
2435
+ const collection = button.dataset.collection;
2436
+ if (collection === void 0)
2437
+ return;
2438
+ state.collection = collection;
2439
+ renderState().catch(showError);
2440
+ });
2441
+ el("records", HTMLElement).addEventListener("click", (event) => {
2442
+ const target = event.target;
2443
+ if (!(target instanceof Element))
2444
+ return;
2445
+ const row = target.closest("[data-id]");
2446
+ if (!(row instanceof HTMLElement))
2447
+ return;
2448
+ const id = row.dataset.id;
2449
+ if (id === void 0)
2450
+ return;
2451
+ openEditor(id).catch(showError);
2452
+ });
2453
+ const editor = el("editor", HTMLDialogElement);
2454
+ const editorId = el("editor-id", HTMLInputElement);
2455
+ const editorValue = el("editor-value", HTMLTextAreaElement);
2456
+ const editorDelete = el("editor-delete", HTMLButtonElement);
2457
+ async function openEditor(id) {
2458
+ state.editing = id;
2459
+ el("editor-title", HTMLElement).textContent = id ? "Edit record" : "New record";
2460
+ editorId.value = id ?? "";
2461
+ editorId.readOnly = id !== null;
2462
+ editorDelete.hidden = id === null;
2463
+ if (id) {
2464
+ const record = await api("GET", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`);
2465
+ if (!isRecord2(record))
2466
+ throw new Error("Record response was not an object");
2467
+ editorValue.value = JSON.stringify(record.value, null, 2) ?? "";
2468
+ } else {
2469
+ editorValue.value = "{\n \n}";
2470
+ }
2471
+ editor.showModal();
2472
+ }
2473
+ el("new-record", HTMLButtonElement).addEventListener("click", () => {
2474
+ openEditor(null).catch(showError);
2475
+ });
2476
+ el("editor-form", HTMLFormElement).addEventListener("submit", (event) => {
2477
+ const submitter = event.submitter;
2478
+ if (!(submitter instanceof HTMLButtonElement) || submitter.value !== "save")
2479
+ return;
2480
+ event.preventDefault();
2481
+ let value;
2482
+ try {
2483
+ value = readJson2(editorValue.value);
2484
+ } catch {
2485
+ showError(new Error("Value is not JSON"));
2486
+ return;
2487
+ }
2488
+ const id = editorId.value.trim();
2489
+ const path = `/state/${encodeURIComponent(state.collection)}`;
2490
+ const request = state.editing ? api("PUT", `${path}/${encodeURIComponent(id)}`, { value }) : api("POST", path, { id: id || void 0, value });
2491
+ request.then(() => {
2492
+ editor.close();
2493
+ return renderState();
2494
+ }).catch(showError);
2495
+ });
2496
+ editorDelete.addEventListener("click", () => {
2497
+ const id = state.editing;
2498
+ if (!id)
2499
+ return;
2500
+ api("DELETE", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`).then(() => {
2501
+ editor.close();
2502
+ return renderState();
2503
+ }).catch(showError);
2504
+ });
2505
+ for (const button of document.querySelectorAll("[data-advance]")) {
2506
+ if (!(button instanceof HTMLButtonElement))
2507
+ continue;
2508
+ button.addEventListener("click", () => {
2509
+ const raw = button.dataset.advance;
2510
+ if (raw === void 0)
2511
+ return;
2512
+ api("POST", "/clock", { advance: Number(raw) }).then(() => renderClock()).catch(showError);
2513
+ });
2514
+ }
2515
+ el("freeze", HTMLButtonElement).addEventListener("click", () => {
2516
+ const frozen = el("freeze", HTMLButtonElement).dataset.frozen === "1";
2517
+ api("POST", "/clock", { freeze: !frozen }).then(() => renderClock()).catch(showError);
2518
+ });
2519
+ el("clock-reset", HTMLButtonElement).addEventListener("click", () => {
2520
+ api("POST", "/clock", { reset: true }).then(() => renderClock()).catch(showError);
2521
+ });
2522
+ el("clock-set", HTMLFormElement).addEventListener("submit", (event) => {
2523
+ event.preventDefault();
2524
+ const raw = el("clock-instant", HTMLInputElement).value.trim();
2525
+ const set = /^-?\d+$/.test(raw) ? Number(raw) : raw;
2526
+ api("POST", "/clock", { set }).then(() => renderClock()).catch(showError);
2527
+ });
2528
+ el("fault-form", HTMLFormElement).addEventListener("submit", (event) => {
2529
+ event.preventDefault();
2530
+ const preset = el("fault-preset", HTMLSelectElement).value;
2531
+ if (preset !== "") {
2532
+ api("POST", "/faults", { preset }).then(() => renderFaults()).catch(showError);
2533
+ return;
2534
+ }
2535
+ const status = Number(el("fault-status", HTMLInputElement).value);
2536
+ if (!Number.isFinite(status)) {
2537
+ showError(new Error("Status must be a number, or choose a preset"));
2538
+ return;
2539
+ }
2540
+ const path = el("fault-path", HTMLInputElement).value;
2541
+ const method = el("fault-method", HTMLInputElement).value;
2542
+ api("POST", "/faults", {
2543
+ status,
2544
+ ...path !== "" ? { pathPrefix: path } : {},
2545
+ ...method !== "" ? { method } : {}
2546
+ }).then(() => renderFaults()).catch(showError);
2547
+ });
2548
+ el("fault-clear", HTMLButtonElement).addEventListener("click", () => {
2549
+ api("DELETE", "/faults").then(() => renderFaults()).catch(showError);
2550
+ });
2551
+ el("journal-clear", HTMLButtonElement).addEventListener("click", () => {
2552
+ api("DELETE", "/requests").then(() => renderJournal()).catch(showError);
2553
+ });
2554
+ el("route-list", HTMLElement).addEventListener("click", (event) => {
2555
+ const target = event.target;
2556
+ if (!(target instanceof Element))
2557
+ return;
2558
+ const button = target.closest("[data-route]");
2559
+ if (!(button instanceof HTMLElement))
2560
+ return;
2561
+ const route = button.dataset.route;
2562
+ if (route === void 0)
2563
+ return;
2564
+ state.route = route;
2565
+ el("route-title", HTMLElement).textContent = route;
2566
+ const method = route.split(" ")[0] ?? "";
2567
+ el("route-body", HTMLTextAreaElement).disabled = method === "GET" || method === "DELETE";
2568
+ });
2569
+ el("route-form", HTMLFormElement).addEventListener("submit", (event) => {
2570
+ event.preventDefault();
2571
+ const send = async () => {
2572
+ if (state.route === null)
2573
+ throw new Error("Choose a route first");
2574
+ const parts = state.route.split(" ");
2575
+ const method = parts[0];
2576
+ const path = parts.slice(1).join(" ");
2577
+ if (method === void 0)
2578
+ throw new Error("Choose a route first");
2579
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_match, key) => prompt(`Value for ${key}`) || "");
2580
+ let body;
2581
+ const routeBody = el("route-body", HTMLTextAreaElement);
2582
+ if (method !== "GET" && method !== "DELETE" && routeBody.value.trim() !== "") {
2583
+ try {
2584
+ body = readJson2(routeBody.value);
2585
+ } catch {
2586
+ throw new Error("Body is not JSON");
2587
+ }
2588
+ }
2589
+ const data = await api(method, concrete, body);
2590
+ el("route-result", HTMLElement).textContent = JSON.stringify(data, null, 2);
2591
+ };
2592
+ send().catch(showError);
2593
+ });
2594
+ const decodePanel = (value) => {
2595
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2596
+ return void 0;
2597
+ }
2598
+ const panel = {
2599
+ id: value.id,
2600
+ title: value.title,
2601
+ description: typeof value.description === "string" ? value.description : "",
2602
+ html: typeof value.html === "string" ? value.html : ""
2603
+ };
2604
+ if (typeof value.script === "string")
2605
+ panel.script = value.script;
2606
+ return panel;
2607
+ };
2608
+ const mountPanels = (panels) => {
2609
+ const nav = el("nav", HTMLElement);
2610
+ const views = el("views", HTMLElement);
2611
+ for (const panel of panels) {
2612
+ const button = document.createElement("button");
2613
+ button.type = "button";
2614
+ button.dataset.view = panel.id;
2615
+ button.textContent = panel.title;
2616
+ nav.append(button);
2617
+ const section = document.createElement("section");
2618
+ section.className = "view";
2619
+ section.id = `view-${panel.id}`;
2620
+ section.hidden = true;
2621
+ const title = document.createElement("h2");
2622
+ title.textContent = panel.title;
2623
+ const lede = document.createElement("p");
2624
+ lede.className = "lede";
2625
+ lede.textContent = panel.description;
2626
+ const body = document.createElement("div");
2627
+ body.className = "panel-body";
2628
+ body.id = `panel-${panel.id}`;
2629
+ body.innerHTML = panel.html;
2630
+ section.append(title, lede, body);
2631
+ views.append(section);
2632
+ if (panel.script === void 0)
2633
+ continue;
2634
+ try {
2635
+ const compiled = new Function("root", "api", panel.script);
2636
+ if (!isPanelScript(compiled))
2637
+ throw new Error("panel script did not compile");
2638
+ compiled(body, panelApi);
2639
+ } catch (error) {
2640
+ const note = document.createElement("p");
2641
+ note.className = "banner show";
2642
+ note.textContent = error instanceof Error ? error.message : String(error);
2643
+ body.append(note);
2644
+ }
2645
+ }
2646
+ };
2647
+ startAdminBrand({
2648
+ document,
2649
+ $: (id) => document.getElementById(id),
2650
+ params,
2651
+ location: { href: location.href, origin: location.origin },
2652
+ fetch,
2653
+ brandsUrl: config.brandsUrl
2654
+ });
2655
+ loadNamespaces().then(() => api("GET", "/ui/manifest")).then((manifest) => {
2656
+ const panels = requireList(isRecord2(manifest) ? manifest.panels : void 0, "Panels").flatMap((panel) => {
2657
+ const decoded = decodePanel(panel);
2658
+ return decoded === void 0 ? [] : [decoded];
2659
+ });
2660
+ mountPanels(panels);
2661
+ return refresh();
2662
+ }).catch(showError);
2663
+ }
2664
+ var clientPrelude = [isRecord2, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin].map((fn) => fn.toString()).join("\n");
2665
+ var adminClientSource = (config) => {
2666
+ const payload = JSON.stringify(config).replace(/</g, "\\u003c");
2667
+ return `<script>
2668
+ ${clientPrelude}
2669
+ bootAdmin(${payload});
2670
+ </script>`;
2671
+ };
2672
+
2673
+ // ../core/dist/surface.js
2674
+ var defineMock = (runtime) => runtime;
2675
+ var STANDARD_ADMIN_ROUTES = [
2676
+ "GET /",
2677
+ "POST /reset",
2678
+ "GET /namespaces",
2679
+ "GET /clock",
2680
+ "POST /clock",
2681
+ "GET /faults",
2682
+ "POST /faults",
2683
+ "DELETE /faults",
2684
+ "POST /snapshots",
2685
+ "POST /snapshots/:id/restore",
2686
+ "DELETE /snapshots/:id",
2687
+ "GET /timeline",
2688
+ "POST /checkpoints",
2689
+ "POST /branches/:name",
2690
+ "POST /branches/:name/checkout",
2691
+ "GET /requests",
2692
+ "DELETE /requests",
2693
+ "GET /metrics",
2694
+ "DELETE /metrics",
2695
+ "GET /credentials",
2696
+ "PUT /credentials",
2697
+ "DELETE /credentials",
2698
+ "GET /state",
2699
+ "GET /state/:collection",
2700
+ "GET /state/:collection/:id",
2701
+ "POST /state/:collection",
2702
+ "PUT /state/:collection/:id",
2703
+ "PATCH /state/:collection/:id",
2704
+ "DELETE /state/:collection/:id",
2705
+ "GET /ui",
2706
+ "GET /ui/",
2707
+ "GET /ui/manifest"
2708
+ ];
2709
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
2710
+ var assertAdminUi = (ui) => {
2711
+ if (!ui?.panels)
2712
+ return;
2713
+ const seen = /* @__PURE__ */ new Set();
2714
+ for (const panel of ui.panels) {
2715
+ if (!PANEL_ID.test(panel.id)) {
2716
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
2717
+ }
2718
+ if (seen.has(panel.id))
2719
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
2720
+ seen.add(panel.id);
2721
+ if (panel.title.trim() === "")
2722
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
2723
+ }
2724
+ };
2725
+
2726
+ // ../core/dist/admin-ui.js
2727
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
2728
+ switch (char) {
2729
+ case "&":
2730
+ return "&amp;";
2731
+ case "<":
2732
+ return "&lt;";
2733
+ case ">":
2734
+ return "&gt;";
2735
+ case '"':
2736
+ return "&quot;";
2737
+ default:
2738
+ return "&#39;";
2739
+ }
2740
+ });
2741
+ var ADMIN_BRANDS_URL = "https://mockingbird.chrisvouga.dev/brands.json";
2742
+ var renderAdminDocument = (service) => {
2743
+ const name = escapeHtml(service);
2744
+ const script = adminClientSource({
2745
+ standardRoutes: STANDARD_ADMIN_ROUTES,
2746
+ adminPrefix: ADMIN_PREFIX,
2747
+ adminKeyHeader: ADMIN_KEY_HEADER,
2748
+ brandsUrl: ADMIN_BRANDS_URL,
2749
+ service
2750
+ });
2751
+ return `<!DOCTYPE html>
2752
+ <html lang="en">
2753
+ <head>
2754
+ <meta charset="utf-8">
2755
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2756
+ <meta name="color-scheme" content="light dark">
2757
+ <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">
2758
+ <title>${name} admin</title>
2759
+ <style>
2760
+ ${CSS_RESET}
2761
+ :root {
2762
+ color-scheme: light;
2763
+ --bg: #fafafa;
2764
+ --bg-elev: #ffffff;
2765
+ --bg-muted: #f4f4f5;
2766
+ --bg-inset: #f4f4f5;
2767
+ --line: #dedee3;
2768
+ --line-strong: #c4c4cc;
2769
+ --ink: #18181b;
2770
+ --muted: #62626b;
2771
+ --faint: #71717a;
2772
+ --accent: #27272a;
2773
+ --accent-ink: #ffffff;
2774
+ --accent-soft: #f4f4f5;
2775
+ --ok: #166534;
2776
+ --ok-soft: #f0fdf4;
2777
+ --warn: #a16207;
2778
+ --warn-soft: #fefce8;
2779
+ --err: #a82d32;
2780
+ --err-soft: #fef2f2;
2781
+ --shadow: none;
2782
+ --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2783
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
2784
+ --radius: 10px;
2785
+ --header: 56px;
2786
+ --nav: 200px;
2787
+ }
2788
+ :root[data-theme="dark"] {
2789
+ color-scheme: dark;
2790
+ --bg: #111113;
2791
+ --bg-elev: #19191c;
2792
+ --bg-muted: #242428;
2793
+ --bg-inset: #111113;
2794
+ --line: #36363c;
2795
+ --line-strong: #52525b;
2796
+ --ink: #f4f4f5;
2797
+ --muted: #a9a9b2;
2798
+ --faint: #71717a;
2799
+ --accent: #e4e4e7;
2800
+ --accent-ink: #18181b;
2801
+ --accent-soft: #242428;
2802
+ --ok: #86efac;
2803
+ --ok-soft: #14241b;
2804
+ --warn: #fde68a;
2805
+ --warn-soft: #2a2410;
2806
+ --err: #ffaaaa;
2807
+ --err-soft: #2c1516;
2808
+ --shadow: none;
2809
+ }
2810
+ @media (prefers-color-scheme: dark) {
2811
+ :root:not([data-theme="light"]) {
2812
+ color-scheme: dark;
2813
+ --bg: #111113;
2814
+ --bg-elev: #19191c;
2815
+ --bg-muted: #242428;
2816
+ --bg-inset: #111113;
2817
+ --line: #36363c;
2818
+ --line-strong: #52525b;
2819
+ --ink: #f4f4f5;
2820
+ --muted: #a9a9b2;
2821
+ --faint: #71717a;
2822
+ --accent: #e4e4e7;
2823
+ --accent-ink: #18181b;
2824
+ --accent-soft: #242428;
2825
+ --ok: #86efac;
2826
+ --ok-soft: #14241b;
2827
+ --warn: #fde68a;
2828
+ --warn-soft: #2a2410;
2829
+ --err: #ffaaaa;
2830
+ --err-soft: #2c1516;
2831
+ --shadow: none;
2832
+ }
2833
+ }
2834
+ /* Fill the viewport, then grow with the content so the background covers the scroll. */
2835
+ html { height: 100%; }
2836
+ body {
2837
+ margin: 0;
2838
+ min-height: 100%;
2839
+ display: flex;
2840
+ flex-direction: column;
2841
+ font-family: var(--sans);
2842
+ background: var(--bg);
2843
+ color: var(--ink);
2844
+ line-height: 1.45;
2845
+ padding-left: env(safe-area-inset-left);
2846
+ padding-right: env(safe-area-inset-right);
2847
+ -webkit-text-size-adjust: 100%;
2848
+ }
2849
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
2850
+ .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }
2851
+ header.top {
2852
+ position: sticky; top: 0; z-index: 5;
2853
+ display: flex; align-items: center; gap: 12px;
2854
+ min-height: var(--header); padding: 10px 16px;
2855
+ background: var(--bg-elev);
2856
+ border-bottom: 1px solid var(--line);
2857
+ min-width: 0; max-width: 100%;
2858
+ }
2859
+ .brand {
2860
+ display: flex; flex-flow: row wrap; align-items: center; gap: 14px;
2861
+ min-width: 0; max-width: 100%; margin-right: auto;
2862
+ }
2863
+ .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }
2864
+ .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }
2865
+ .brand-id span { color: var(--faint); font-size: 12px; }
2866
+ .vendor {
2867
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2868
+ min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);
2869
+ }
2870
+ .vendor[hidden] { display: none; }
2871
+ /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */
2872
+ .vendor img {
2873
+ width: 16px; height: 16px; padding: 2px; box-sizing: content-box;
2874
+ border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;
2875
+ }
2876
+ .vendor-name { color: var(--ink); font-weight: 600; }
2877
+ .vendor-sep { color: var(--faint); }
2878
+ .vendor-link { color: inherit; text-decoration: none; }
2879
+ .vendor-link:hover { color: var(--ink); text-decoration: underline; }
2880
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
2881
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
2882
+ label.field input, label.field select, .controls input[type="password"] {
2883
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
2884
+ padding: 7px 8px; min-height: 36px;
2885
+ }
2886
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
2887
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
2888
+ background: var(--bg-elev);
2889
+ }
2890
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
2891
+ .btn-quiet { background: transparent; }
2892
+ .btn-danger { color: var(--err); }
2893
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
2894
+ record or the full nav row would widen the page past the viewport. */
2895
+ .layout {
2896
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
2897
+ flex: 1 0 auto; min-width: 0;
2898
+ }
2899
+ nav.side {
2900
+ border-right: 1px solid var(--line); padding: 12px;
2901
+ display: flex; flex-direction: column; gap: 4px;
2902
+ background: var(--bg-elev);
2903
+ }
2904
+ nav.side button {
2905
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
2906
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
2907
+ }
2908
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
2909
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
2910
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
2911
+ .lede { margin: 0 0 16px; color: var(--muted); }
2912
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
2913
+ .card {
2914
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
2915
+ padding: 14px 16px; box-shadow: var(--shadow);
2916
+ }
2917
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
2918
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
2919
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
2920
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
2921
+ .collection {
2922
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
2923
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
2924
+ }
2925
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
2926
+ .collection small { display: block; color: var(--faint); }
2927
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
2928
+ .chip {
2929
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
2930
+ border-radius: 999px; padding: 4px 8px;
2931
+ }
2932
+ .chip i { color: var(--faint); font-style: normal; }
2933
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
2934
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
2935
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
2936
+ tr.clickable { cursor: pointer; }
2937
+ tr.clickable:hover { background: var(--bg-muted); }
2938
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
2939
+ pre {
2940
+ margin: 0; white-space: pre-wrap; word-break: break-word;
2941
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
2942
+ }
2943
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
2944
+ .banner {
2945
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
2946
+ background: var(--err-soft); color: var(--err);
2947
+ }
2948
+ .banner.show { display: block; }
2949
+ .empty { color: var(--muted); padding: 24px 8px; }
2950
+ dialog {
2951
+ border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);
2952
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: none;
2953
+ }
2954
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
2955
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
2956
+ textarea {
2957
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
2958
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
2959
+ font-family: var(--mono); font-size: 12px;
2960
+ }
2961
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
2962
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
2963
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
2964
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
2965
+ .status-2 { color: var(--ok); }
2966
+ .status-4, .status-5, .status-0 { color: var(--err); }
2967
+ .stack { display: flex; flex-direction: column; gap: 12px; }
2968
+ .route {
2969
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
2970
+ padding: 8px 0; border-bottom: 1px solid var(--line);
2971
+ }
2972
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
2973
+ @media (max-width: 800px) {
2974
+ header.top {
2975
+ align-items: stretch; flex-direction: column;
2976
+ padding-top: max(10px, env(safe-area-inset-top));
2977
+ }
2978
+ input, select, textarea { font-size: 16px; }
2979
+ .brand, .vendor, .controls { width: 100%; }
2980
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
2981
+ .layout { grid-template-columns: minmax(0, 1fr); }
2982
+ nav.side {
2983
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
2984
+ border-right: 0; border-bottom: 1px solid var(--line);
2985
+ padding: 8px;
2986
+ }
2987
+ nav.side button { white-space: nowrap; flex: none; }
2988
+ .split { grid-template-columns: minmax(0, 1fr); }
2989
+ main { padding: 14px; }
2990
+ table, thead, tbody, tr, th, td { display: block; }
2991
+ thead { display: none; }
2992
+ tr {
2993
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
2994
+ background: var(--bg-elev); min-width: 0;
2995
+ }
2996
+ td {
2997
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
2998
+ min-width: 0; overflow-wrap: anywhere;
2999
+ }
3000
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
3001
+ .route { grid-template-columns: 72px 1fr; }
3002
+ .route button { grid-column: 1 / -1; }
3003
+ }
3004
+ </style>
3005
+ </head>
3006
+ <body>
3007
+ <div class="app" data-service="${name}" data-mockingbird-admin>
3008
+ <header class="top">
3009
+ <div class="brand">
3010
+ <div class="brand-id">
3011
+ <strong>${name}</strong>
3012
+ <span>Admin</span>
3013
+ </div>
3014
+ <div class="vendor" id="vendor" hidden></div>
3015
+ </div>
3016
+ <div class="controls">
3017
+ <label class="field">Namespace
3018
+ <select id="namespace" aria-label="Namespace"></select>
3019
+ </label>
3020
+ <label class="field">Admin key
3021
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
3022
+ </label>
3023
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
3024
+ <button class="btn" id="refresh" type="button">Refresh</button>
3025
+ </div>
3026
+ </header>
3027
+ <div class="layout">
3028
+ <nav class="side" id="nav" aria-label="Admin sections">
3029
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
3030
+ <button type="button" data-view="state">State</button>
3031
+ <button type="button" data-view="clock">Clock</button>
3032
+ <button type="button" data-view="faults">Faults</button>
3033
+ <button type="button" data-view="journal">Journal</button>
3034
+ <button type="button" data-view="routes">Routes</button>
3035
+ </nav>
3036
+ <main id="views">
3037
+ <p class="banner" id="banner" role="alert"></p>
3038
+ <section class="view" id="view-overview">
3039
+ <h2>Overview</h2>
3040
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
3041
+ <div class="grid" id="overview-cards"></div>
3042
+ <h3>Recent requests</h3>
3043
+ <div id="overview-requests"></div>
3044
+ </section>
3045
+ <section class="view" id="view-state" hidden>
3046
+ <h2>State</h2>
3047
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
3048
+ <div class="split">
3049
+ <div id="collections"></div>
3050
+ <div>
3051
+ <div id="schema"></div>
3052
+ <div class="row-actions">
3053
+ <button class="btn-primary" id="new-record" type="button">New record</button>
3054
+ </div>
3055
+ <div id="records"></div>
3056
+ </div>
3057
+ </div>
3058
+ </section>
3059
+ <section class="view" id="view-clock" hidden>
3060
+ <h2>Clock</h2>
3061
+ <p class="lede">The clock every timestamp in this mock reads.</p>
3062
+ <div class="card" id="clock-readout"></div>
3063
+ <div class="row-actions">
3064
+ <button class="btn" type="button" data-advance="60000">+1m</button>
3065
+ <button class="btn" type="button" data-advance="900000">+15m</button>
3066
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
3067
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
3068
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
3069
+ <button class="btn" id="freeze" type="button">Freeze</button>
3070
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
3071
+ </div>
3072
+ <form id="clock-set" class="row-actions">
3073
+ <label class="field">Set instant
3074
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
3075
+ </label>
3076
+ <button class="btn-primary" type="submit">Set</button>
3077
+ </form>
3078
+ </section>
3079
+ <section class="view" id="view-faults" hidden>
3080
+ <h2>Faults</h2>
3081
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
3082
+ <form id="fault-form" class="card stack">
3083
+ <label class="field">Preset
3084
+ <select id="fault-preset"><option value="">Custom rule</option></select>
3085
+ </label>
3086
+ <label class="field">Status
3087
+ <input id="fault-status" inputmode="numeric" placeholder="503">
3088
+ </label>
3089
+ <label class="field">Path prefix
3090
+ <input id="fault-path" placeholder="/v1">
3091
+ </label>
3092
+ <label class="field">Method
3093
+ <input id="fault-method" placeholder="GET">
3094
+ </label>
3095
+ <div class="dialog-actions">
3096
+ <button class="btn-primary" type="submit">Add fault</button>
3097
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
3098
+ </div>
3099
+ </form>
3100
+ <div id="fault-list"></div>
3101
+ </section>
3102
+ <section class="view" id="view-journal" hidden>
3103
+ <h2>Journal</h2>
3104
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
3105
+ <div class="row-actions">
3106
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
3107
+ </div>
3108
+ <div id="journal"></div>
3109
+ </section>
3110
+ <section class="view" id="view-routes" hidden>
3111
+ <h2>Routes</h2>
3112
+ <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>
3113
+ <div id="route-list"></div>
3114
+ <form id="route-form" class="card stack">
3115
+ <strong id="route-title">Select a route</strong>
3116
+ <label class="field">JSON body
3117
+ <textarea id="route-body" placeholder="{ }"></textarea>
3118
+ </label>
3119
+ <div class="dialog-actions">
3120
+ <button class="btn-primary" type="submit">Send</button>
3121
+ </div>
3122
+ <pre id="route-result">Response will show here.</pre>
3123
+ </form>
3124
+ </section>
3125
+ </main>
3126
+ </div>
3127
+ </div>
3128
+ <dialog id="editor">
3129
+ <form method="dialog" id="editor-form">
3130
+ <strong id="editor-title">Record</strong>
3131
+ <label class="field">Id
3132
+ <input id="editor-id" required>
3133
+ </label>
3134
+ <label class="field">JSON value
3135
+ <textarea id="editor-value"></textarea>
3136
+ </label>
3137
+ <div class="dialog-actions">
3138
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
3139
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
3140
+ <button class="btn-primary" type="submit" value="save">Save</button>
3141
+ </div>
3142
+ </form>
3143
+ </dialog>
3144
+ ${script}
3145
+ </body>
3146
+ </html>`;
3147
+ };
3148
+ var htmlResponse = (body) => new Response(body, {
3149
+ status: 200,
3150
+ headers: {
3151
+ "content-type": "text/html; charset=utf-8",
3152
+ "cache-control": "no-store"
3153
+ }
3154
+ });
3155
+ var json3 = (body) => new Response(JSON.stringify(body), {
3156
+ status: 200,
3157
+ headers: { "content-type": "application/json; charset=utf-8" }
3158
+ });
3159
+ var adminUiRoutes = (service, ui) => {
3160
+ const shell = () => renderAdminDocument(service);
3161
+ const document3 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
3162
+ return {
3163
+ "GET /ui": () => htmlResponse(document3()),
3164
+ "GET /ui/": () => htmlResponse(document3()),
3165
+ "GET /ui/manifest": () => json3({
3166
+ service,
3167
+ panels: (ui?.panels ?? []).map((panel) => ({
3168
+ id: panel.id,
3169
+ title: panel.title,
3170
+ ...panel.description !== void 0 ? { description: panel.description } : {},
3171
+ html: panel.html,
3172
+ ...panel.script !== void 0 ? { script: panel.script } : {}
3173
+ }))
3174
+ })
3175
+ };
3176
+ };
3177
+
1445
3178
  // ../../openapi/metadata/dist/types.js
1446
3179
  var EXTENSION_KEYS = {
1447
3180
  operation: "x-mockingbird",
@@ -1454,11 +3187,11 @@ var EXTENSION_KEYS = {
1454
3187
  };
1455
3188
 
1456
3189
  // ../../openapi/metadata/dist/read.js
1457
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3190
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1458
3191
  var extensionOf = (holder, key) => holder[key];
1459
3192
  var operationMetadata = (operation) => {
1460
3193
  const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1461
- const ext = isRecord2(raw) ? raw : {};
3194
+ const ext = isRecord3(raw) ? raw : {};
1462
3195
  const supported = ext.supported ?? true;
1463
3196
  const parity = ext.parity ?? {};
1464
3197
  return {
@@ -1568,9 +3301,9 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1568
3301
  this.name = "OperationRegistryError";
1569
3302
  }
1570
3303
  };
1571
- var verifyOperations = (document2, handlers) => {
3304
+ var verifyOperations = (document3, handlers) => {
1572
3305
  const problems = [];
1573
- const operations = listOperations(document2);
3306
+ const operations = listOperations(document3);
1574
3307
  const seen = /* @__PURE__ */ new Set();
1575
3308
  for (const operation of operations) {
1576
3309
  if (seen.has(operation.operationId))
@@ -1679,8 +3412,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1679
3412
  });
1680
3413
  };
1681
3414
 
3415
+ // ../core/dist/state-view.js
3416
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
3417
+ var RECORD_ID = /^[^\s/]{1,256}$/;
3418
+ var SAMPLE = 25;
3419
+ var WALK_LIMIT = 1e4;
3420
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
3421
+ var fail = (status, message) => ({ ok: false, status, message });
3422
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3423
+ var kindOf = (value) => {
3424
+ if (value === null)
3425
+ return "null";
3426
+ if (Array.isArray(value))
3427
+ return "array";
3428
+ switch (typeof value) {
3429
+ case "string":
3430
+ return "string";
3431
+ case "number":
3432
+ return Number.isFinite(value) ? "number" : "unknown";
3433
+ case "boolean":
3434
+ return "boolean";
3435
+ case "object":
3436
+ return "object";
3437
+ default:
3438
+ return "unknown";
3439
+ }
3440
+ };
3441
+ var humanize = (name) => {
3442
+ const words = name.replace(/[@:_-]+/g, " ").trim();
3443
+ if (words === "")
3444
+ return name;
3445
+ return words.charAt(0).toUpperCase() + words.slice(1);
3446
+ };
3447
+ var jsonValue = (value) => {
3448
+ if (value === void 0)
3449
+ return fail(400, "value is required");
3450
+ try {
3451
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
3452
+ } catch {
3453
+ return fail(400, "value must be JSON");
3454
+ }
3455
+ };
3456
+ var ctorName = (value) => {
3457
+ const ctor = value.constructor;
3458
+ return typeof ctor?.name === "string" ? ctor.name : "";
3459
+ };
3460
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
3461
+ var discoverCollections = (root) => {
3462
+ const found = [];
3463
+ const seen = /* @__PURE__ */ new Set();
3464
+ const visit = (value, depth) => {
3465
+ if (found.length + seen.size > WALK_LIMIT)
3466
+ return;
3467
+ if (value === null || typeof value !== "object")
3468
+ return;
3469
+ if (seen.has(value))
3470
+ return;
3471
+ seen.add(value);
3472
+ if (value instanceof Collection) {
3473
+ found.push(value);
3474
+ return;
3475
+ }
3476
+ if (value instanceof Map) {
3477
+ for (const child of value.values())
3478
+ visit(child, depth + 1);
3479
+ return;
3480
+ }
3481
+ if (value instanceof Set) {
3482
+ for (const child of value.values())
3483
+ visit(child, depth + 1);
3484
+ return;
3485
+ }
3486
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
3487
+ return;
3488
+ if (Array.isArray(value)) {
3489
+ const cap = Math.min(value.length, 32);
3490
+ for (let i = 0; i < cap; i++)
3491
+ visit(value[i], depth + 1);
3492
+ return;
3493
+ }
3494
+ let children;
3495
+ try {
3496
+ children = Object.values(value);
3497
+ } catch {
3498
+ return;
3499
+ }
3500
+ for (const child of children)
3501
+ visit(child, depth + 1);
3502
+ };
3503
+ visit(root, 0);
3504
+ return found;
3505
+ };
3506
+ var storedNames = (sqlite, namespace) => {
3507
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
3508
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
3509
+ return [...records, ...sequences].map((row) => row.name);
3510
+ };
3511
+ var blankAccum = (name) => ({
3512
+ name,
3513
+ kinds: /* @__PURE__ */ new Set(),
3514
+ present: 0,
3515
+ nested: /* @__PURE__ */ new Map()
3516
+ });
3517
+ var absorb = (accum, value) => {
3518
+ const kind = kindOf(value);
3519
+ accum.kinds.add(kind);
3520
+ accum.present++;
3521
+ if (!isRecord4(value))
3522
+ return;
3523
+ for (const [key, child] of Object.entries(value)) {
3524
+ const nested = accum.nested.get(key) ?? blankAccum(key);
3525
+ absorb(nested, child);
3526
+ accum.nested.set(key, nested);
3527
+ }
3528
+ };
3529
+ var finishField = (accum, samples) => {
3530
+ const kinds = [...accum.kinds];
3531
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
3532
+ const field = {
3533
+ name: accum.name,
3534
+ kind,
3535
+ optional: accum.present < samples || kinds.includes("null")
3536
+ };
3537
+ if (accum.nested.size > 0) {
3538
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
3539
+ }
3540
+ return field;
3541
+ };
3542
+ var inferFields = (records) => {
3543
+ if (records.length === 0)
3544
+ return [];
3545
+ const sample = records.slice(0, SAMPLE);
3546
+ const objects = sample.filter((record) => isRecord4(record.value));
3547
+ if (objects.length === 0) {
3548
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
3549
+ const list = [...kinds];
3550
+ return [
3551
+ {
3552
+ name: "(value)",
3553
+ kind: list.length === 1 ? list[0] : "unknown",
3554
+ optional: false
3555
+ }
3556
+ ];
3557
+ }
3558
+ const root = /* @__PURE__ */ new Map();
3559
+ for (const record of objects) {
3560
+ for (const [key, value] of Object.entries(record.value)) {
3561
+ const accum = root.get(key) ?? blankAccum(key);
3562
+ absorb(accum, value);
3563
+ root.set(key, accum);
3564
+ }
3565
+ }
3566
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
3567
+ };
3568
+ var mergeFields = (declared, inferred) => {
3569
+ const byName = /* @__PURE__ */ new Map();
3570
+ for (const field of inferred)
3571
+ byName.set(field.name, field);
3572
+ const ordered = [];
3573
+ const seen = /* @__PURE__ */ new Set();
3574
+ for (const field of declared ?? []) {
3575
+ const found = byName.get(field.name);
3576
+ seen.add(field.name);
3577
+ if (!found) {
3578
+ ordered.push({ ...field, optional: field.optional });
3579
+ continue;
3580
+ }
3581
+ ordered.push({
3582
+ ...found,
3583
+ kind: field.kind === "unknown" ? found.kind : field.kind,
3584
+ optional: field.optional || found.optional,
3585
+ ...field.description !== void 0 ? { description: field.description } : {},
3586
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
3587
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
3588
+ });
3589
+ }
3590
+ for (const field of inferred) {
3591
+ if (!seen.has(field.name))
3592
+ ordered.push(field);
3593
+ }
3594
+ return ordered;
3595
+ };
3596
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
3597
+ var readRecord = (collection, id) => {
3598
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
3599
+ const row = rows.find((entry) => entry.id === id);
3600
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
3601
+ };
3602
+ var inspectState = (scope) => {
3603
+ const declared = /* @__PURE__ */ new Map();
3604
+ for (const declaration of scope.declarations ?? []) {
3605
+ if (COLLECTION_NAME.test(declaration.name))
3606
+ declared.set(declaration.name, declaration);
3607
+ }
3608
+ const names = new Set(declared.keys());
3609
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
3610
+ names.add(name);
3611
+ for (const collection of discoverCollections(scope.root)) {
3612
+ if (collection.namespace === scope.storageNamespace)
3613
+ names.add(collection.collectionName);
3614
+ }
3615
+ const collections = [];
3616
+ for (const name of names) {
3617
+ if (!COLLECTION_NAME.test(name))
3618
+ continue;
3619
+ const declaration = declared.get(name);
3620
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3621
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
3622
+ const inferred = inferFields(records);
3623
+ const fields = mergeFields(declaration?.fields, inferred);
3624
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
3625
+ collections.push({
3626
+ name,
3627
+ label: declaration?.label ?? humanize(name),
3628
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
3629
+ count: collection.count(),
3630
+ source,
3631
+ fields,
3632
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
3633
+ });
3634
+ }
3635
+ const order = /* @__PURE__ */ new Map();
3636
+ for (const [index, item] of (scope.declarations ?? []).entries())
3637
+ order.set(item.name, index);
3638
+ collections.sort((a, b) => {
3639
+ const left = order.get(a.name);
3640
+ const right = order.get(b.name);
3641
+ if (left !== void 0 && right !== void 0)
3642
+ return left - right;
3643
+ if (left !== void 0)
3644
+ return -1;
3645
+ if (right !== void 0)
3646
+ return 1;
3647
+ return a.name.localeCompare(b.name);
3648
+ });
3649
+ return {
3650
+ namespace: scope.namespace,
3651
+ storageNamespace: scope.storageNamespace,
3652
+ collections
3653
+ };
3654
+ };
3655
+ var pageOf = (sqlite, storageNamespace, name, query) => {
3656
+ if (!COLLECTION_NAME.test(name))
3657
+ return fail(400, "collection name is not allowed");
3658
+ const limit = query.limit ?? 50;
3659
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
3660
+ return fail(400, "limit must be an integer from 1 to 200");
3661
+ }
3662
+ const order = query.order ?? "newest";
3663
+ if (order !== "newest" && order !== "oldest")
3664
+ return fail(400, 'order must be "newest" or "oldest"');
3665
+ const collection = collectionOf(sqlite, storageNamespace, name);
3666
+ const rows = collection.list({ order }).filter((row) => {
3667
+ if (query.after === void 0)
3668
+ return true;
3669
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
3670
+ });
3671
+ const slice = rows.slice(0, limit);
3672
+ const last = slice.at(-1);
3673
+ return {
3674
+ ok: true,
3675
+ value: {
3676
+ collection: name,
3677
+ count: collection.count(),
3678
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
3679
+ next: rows.length > limit && last ? last.seq : null
3680
+ }
3681
+ };
3682
+ };
3683
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
3684
+ var readStateRecord = (scope, name, id) => {
3685
+ if (!COLLECTION_NAME.test(name))
3686
+ return fail(400, "collection name is not allowed");
3687
+ if (!RECORD_ID.test(id))
3688
+ return fail(400, "record id is not allowed");
3689
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
3690
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
3691
+ };
3692
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
3693
+ var createStateRecord = (scope, name, input) => {
3694
+ if (!COLLECTION_NAME.test(name))
3695
+ return fail(400, "collection name is not allowed");
3696
+ const parsed = jsonValue(input.value);
3697
+ if (!parsed.ok)
3698
+ return parsed;
3699
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3700
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
3701
+ const checked = requireId(id);
3702
+ if (!checked.ok)
3703
+ return checked;
3704
+ if (collection.has(checked.value))
3705
+ return fail(409, `record ${checked.value} already exists`);
3706
+ const stored = collection.insert(checked.value, parsed.value);
3707
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3708
+ };
3709
+ var replaceStateRecord = (scope, name, id, value) => {
3710
+ if (!COLLECTION_NAME.test(name))
3711
+ return fail(400, "collection name is not allowed");
3712
+ const checked = requireId(id);
3713
+ if (!checked.ok)
3714
+ return checked;
3715
+ const parsed = jsonValue(value);
3716
+ if (!parsed.ok)
3717
+ return parsed;
3718
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3719
+ if (!collection.has(checked.value))
3720
+ return fail(404, `no record ${checked.value} in ${name}`);
3721
+ const stored = collection.update(checked.value, parsed.value);
3722
+ if (!stored)
3723
+ return fail(404, `no record ${checked.value} in ${name}`);
3724
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3725
+ };
3726
+ var patchStateRecord = (scope, name, id, value) => {
3727
+ const current = readStateRecord(scope, name, id);
3728
+ if (!current.ok)
3729
+ return current;
3730
+ const parsed = jsonValue(value);
3731
+ if (!parsed.ok)
3732
+ return parsed;
3733
+ const next = isRecord4(current.value.value) && isRecord4(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
3734
+ return replaceStateRecord(scope, name, id, next);
3735
+ };
3736
+ var deleteStateRecord = (scope, name, id) => {
3737
+ if (!COLLECTION_NAME.test(name))
3738
+ return fail(400, "collection name is not allowed");
3739
+ const checked = requireId(id);
3740
+ if (!checked.ok)
3741
+ return checked;
3742
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3743
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
3744
+ };
3745
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
3746
+ status,
3747
+ headers: { "content-type": "application/json; charset=utf-8" }
3748
+ });
3749
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3750
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
3751
+ var integerParam = (value) => {
3752
+ if (value === null)
3753
+ return void 0;
3754
+ if (!/^-?\d+$/.test(value))
3755
+ return "bad";
3756
+ return Number(value);
3757
+ };
3758
+ var stateAdminRoutes = (routes) => {
3759
+ const open = (namespace) => {
3760
+ try {
3761
+ return { ok: true, value: routes.open(namespace) };
3762
+ } catch (error) {
3763
+ return fail(400, error instanceof Error ? error.message : String(error));
3764
+ }
3765
+ };
3766
+ const wrote = (namespace) => {
3767
+ routes.afterWrite?.(namespace);
3768
+ };
3769
+ return {
3770
+ "GET /state": ({ namespace }) => {
3771
+ const scope = open(namespace);
3772
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
3773
+ },
3774
+ "GET /state/:collection": ({ namespace, params, url }) => {
3775
+ const scope = open(namespace);
3776
+ if (!scope.ok)
3777
+ return fromResult(scope, 200);
3778
+ const limit = integerParam(url.searchParams.get("limit"));
3779
+ const after = integerParam(url.searchParams.get("after"));
3780
+ if (limit === "bad")
3781
+ return adminError2(400, "limit: expected an integer");
3782
+ if (after === "bad")
3783
+ return adminError2(400, "after: expected a sequence number");
3784
+ const order = url.searchParams.get("order");
3785
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
3786
+ ...limit !== void 0 ? { limit } : {},
3787
+ ...after !== void 0 ? { after } : {},
3788
+ ...order === "newest" || order === "oldest" ? { order } : {}
3789
+ }), 200);
3790
+ },
3791
+ "GET /state/:collection/:id": ({ namespace, params }) => {
3792
+ const scope = open(namespace);
3793
+ if (!scope.ok)
3794
+ return fromResult(scope, 200);
3795
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
3796
+ },
3797
+ "POST /state/:collection": ({ namespace, params, body }) => {
3798
+ const scope = open(namespace);
3799
+ if (!scope.ok)
3800
+ return fromResult(scope, 201);
3801
+ if (!isRecord4(body) || !("value" in body)) {
3802
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3803
+ }
3804
+ const id = body.id;
3805
+ if (id !== void 0 && typeof id !== "string")
3806
+ return adminError2(400, "id must be a string");
3807
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3808
+ ...typeof id === "string" ? { id } : {},
3809
+ value: body.value
3810
+ });
3811
+ if (created.ok)
3812
+ wrote(namespace);
3813
+ return fromResult(created, 201);
3814
+ },
3815
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3816
+ const scope = open(namespace);
3817
+ if (!scope.ok)
3818
+ return fromResult(scope, 200);
3819
+ if (!isRecord4(body) || !("value" in body))
3820
+ return adminError2(400, 'expected {"value": <json>}');
3821
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3822
+ if (replaced.ok)
3823
+ wrote(namespace);
3824
+ return fromResult(replaced, 200);
3825
+ },
3826
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3827
+ const scope = open(namespace);
3828
+ if (!scope.ok)
3829
+ return fromResult(scope, 200);
3830
+ if (!isRecord4(body) || !("value" in body))
3831
+ return adminError2(400, 'expected {"value": <json>}');
3832
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3833
+ if (patched.ok)
3834
+ wrote(namespace);
3835
+ return fromResult(patched, 200);
3836
+ },
3837
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3838
+ const scope = open(namespace);
3839
+ if (!scope.ok)
3840
+ return fromResult(scope, 200);
3841
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3842
+ if (removed.ok)
3843
+ wrote(namespace);
3844
+ return fromResult(removed, 200);
3845
+ }
3846
+ };
3847
+ };
3848
+
1682
3849
  // ../core/dist/version.js
1683
- var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
3850
+ var PACKAGE_VERSION = true ? "1.6.0" : UNRELEASED_VERSION;
1684
3851
 
1685
3852
  // ../core/dist/signing.js
1686
3853
  var encoder = new TextEncoder();
@@ -2015,11 +4182,11 @@ var createWebhookHub = (options) => {
2015
4182
  };
2016
4183
  return hub;
2017
4184
  };
2018
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2019
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2020
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4185
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4186
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4187
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2021
4188
  var parseEndpoint = (value) => {
2022
- if (!isRecord3(value) || typeof value.url !== "string")
4189
+ if (!isRecord5(value) || typeof value.url !== "string")
2023
4190
  return "each endpoint needs a url";
2024
4191
  try {
2025
4192
  new URL(value.url);
@@ -2036,18 +4203,18 @@ var parseEndpoint = (value) => {
2036
4203
  const events = value.events ?? value.enabledEvents;
2037
4204
  if (Array.isArray(events))
2038
4205
  endpoint.events = events.map(String);
2039
- if (isRecord3(value.tags)) {
4206
+ if (isRecord5(value.tags)) {
2040
4207
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2041
4208
  }
2042
4209
  if (typeof value.account === "string")
2043
4210
  endpoint.tags = { ...endpoint.tags, account: value.account };
2044
- if (isRecord3(value.headers)) {
4211
+ if (isRecord5(value.headers)) {
2045
4212
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2046
4213
  }
2047
4214
  return endpoint;
2048
4215
  };
2049
4216
  var webhookAdminRoutes = (hub) => ({
2050
- "GET /webhooks": ({ url, namespace }) => json3(200, {
4217
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
2051
4218
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2052
4219
  const type = url.searchParams.get("type");
2053
4220
  return type === null || d.type === type;
@@ -2055,51 +4222,51 @@ var webhookAdminRoutes = (hub) => ({
2055
4222
  }),
2056
4223
  "GET /webhooks/events": ({ url, namespace }) => {
2057
4224
  const type = url.searchParams.get("type");
2058
- return json3(200, {
4225
+ return json5(200, {
2059
4226
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2060
4227
  });
2061
4228
  },
2062
4229
  "POST /webhooks/:id/replay": async ({ params }) => {
2063
4230
  const replayed = await hub.replay(params.id);
2064
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
4231
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2065
4232
  },
2066
4233
  "POST /webhooks/flush": async () => {
2067
4234
  await hub.flush();
2068
- return json3(200, { status: "ok" });
4235
+ return json5(200, { status: "ok" });
2069
4236
  },
2070
4237
  "POST /webhooks/faults": ({ body, namespace }) => {
2071
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2072
- return adminError2(400, "mode must be duplicate, reorder or drop");
4238
+ if (!isRecord5(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
4239
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2073
4240
  }
2074
4241
  const fault = { mode: body.mode };
2075
4242
  if (typeof body.count === "number")
2076
4243
  fault.count = body.count;
2077
4244
  hub.fault(namespace, fault);
2078
- return json3(201, { namespace, ...fault });
4245
+ return json5(201, { namespace, ...fault });
2079
4246
  },
2080
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
4247
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
2081
4248
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2082
4249
  ...rest,
2083
4250
  secret: secret ? "(set)" : null
2084
4251
  }))
2085
4252
  }),
2086
4253
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2087
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
4254
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.endpoints : void 0;
2088
4255
  if (!Array.isArray(list))
2089
- return adminError2(400, "expected [{url, secret?, events?}]");
4256
+ return adminError3(400, "expected [{url, secret?, events?}]");
2090
4257
  const parsed = [];
2091
4258
  for (const each of list) {
2092
4259
  const endpoint = parseEndpoint(each);
2093
4260
  if (typeof endpoint === "string")
2094
- return adminError2(400, endpoint);
4261
+ return adminError3(400, endpoint);
2095
4262
  parsed.push(endpoint);
2096
4263
  }
2097
4264
  const set = hub.setEndpoints(namespace, parsed);
2098
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
4265
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2099
4266
  },
2100
4267
  "DELETE /webhook-endpoints": ({ namespace }) => {
2101
4268
  hub.setEndpoints(namespace, []);
2102
- return json3(200, { status: "ok" });
4269
+ return json5(200, { status: "ok" });
2103
4270
  }
2104
4271
  });
2105
4272
  var parsePayload = (message) => {
@@ -2154,8 +4321,8 @@ var DroppedConnectionError = class extends TypeError {
2154
4321
  this.name = "TypeError";
2155
4322
  }
2156
4323
  };
2157
- var operationMatcher = (document2) => {
2158
- const matchers = listOperations(document2).map((operation) => ({
4324
+ var operationMatcher = (document3) => {
4325
+ const matchers = listOperations(document3).map((operation) => ({
2159
4326
  operationId: operation.operationId,
2160
4327
  method: operation.method.toUpperCase(),
2161
4328
  pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
@@ -2164,6 +4331,7 @@ var operationMatcher = (document2) => {
2164
4331
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2165
4332
  };
2166
4333
  var createRuntime = (options) => {
4334
+ assertAdminUi(options.adminUi);
2167
4335
  const sqlite = bootSqlite(options.sqlite);
2168
4336
  const clock = options.clock ?? createClock();
2169
4337
  const rng = createRng(options.seed ?? 0);
@@ -2249,10 +4417,10 @@ var createRuntime = (options) => {
2249
4417
  const ensureBranch = (namespace, branch2, at) => {
2250
4418
  if (!BRANCH_PATTERN2.test(branch2))
2251
4419
  throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2252
- const history = timeline(namespace);
4420
+ const history2 = timeline(namespace);
2253
4421
  if (branch2 === "main") {
2254
4422
  if (at !== void 0) {
2255
- const point = history.checkout("main", at);
4423
+ const point = history2.checkout("main", at);
2256
4424
  restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2257
4425
  captured.set(namespace, point.value.snapshot);
2258
4426
  rng.setState(point.value.rngState);
@@ -2265,10 +4433,10 @@ var createRuntime = (options) => {
2265
4433
  return namespace;
2266
4434
  }
2267
4435
  const storage = physicalBranch(namespace, branch2);
2268
- if (!history.hasBranch(branch2)) {
4436
+ if (!history2.hasBranch(branch2)) {
2269
4437
  if (at === void 0)
2270
- history.commit(capture(namespace));
2271
- const point = history.fork(branch2, at === void 0 ? {} : { from: at });
4438
+ history2.commit(capture(namespace));
4439
+ const point = history2.fork(branch2, at === void 0 ? {} : { from: at });
2272
4440
  const branchRng = createRng(options.seed ?? 0);
2273
4441
  if (point)
2274
4442
  branchRng.setState(point.value.rngState);
@@ -2277,8 +4445,8 @@ var createRuntime = (options) => {
2277
4445
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2278
4446
  if (point)
2279
4447
  captured.set(storage, point.value.snapshot);
2280
- } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2281
- const point = history.checkout(branch2, at);
4448
+ } else if (at !== void 0 && history2.head(branch2)?.id !== at) {
4449
+ const point = history2.checkout(branch2, at);
2282
4450
  if (!instances.has(storage)) {
2283
4451
  const branchRng = createRng(options.seed ?? 0);
2284
4452
  branchRng.setState(point.value.rngState);
@@ -2289,7 +4457,7 @@ var createRuntime = (options) => {
2289
4457
  captured.set(storage, point.value.snapshot);
2290
4458
  } else {
2291
4459
  if (!instances.has(storage)) {
2292
- const point = history.head(branch2);
4460
+ const point = history2.head(branch2);
2293
4461
  const branchRng = createRng(options.seed ?? 0);
2294
4462
  if (point)
2295
4463
  branchRng.setState(point.value.rngState);
@@ -2313,8 +4481,8 @@ var createRuntime = (options) => {
2313
4481
  const checkout = (checkpointId, checkoutOptions = {}) => {
2314
4482
  const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2315
4483
  const branchName = checkoutOptions.branch ?? "main";
2316
- const history = timeline(namespace);
2317
- const point = history.checkout(branchName, checkpointId);
4484
+ const history2 = timeline(namespace);
4485
+ const point = history2.checkout(branchName, checkpointId);
2318
4486
  const storage = ensureBranch(namespace, branchName);
2319
4487
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2320
4488
  captured.set(storage, point.value.snapshot);
@@ -2364,12 +4532,25 @@ var createRuntime = (options) => {
2364
4532
  instance(name);
2365
4533
  restoreNamespace(sqlite, storageNamespace(name), from);
2366
4534
  captured.set(name, from);
2367
- const history = timelines.get(name);
2368
- if (history)
2369
- history.commit(capture(name), { branch: "main" });
4535
+ const history2 = timelines.get(name);
4536
+ if (history2)
4537
+ history2.commit(capture(name), { branch: "main" });
2370
4538
  else
2371
4539
  timeline(name);
2372
4540
  };
4541
+ const declarationsFor = (namespace) => {
4542
+ const declared = options.state;
4543
+ if (!declared)
4544
+ return [];
4545
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
4546
+ };
4547
+ const stateScope = (namespace) => ({
4548
+ sqlite,
4549
+ namespace,
4550
+ storageNamespace: storageNamespace(namespace),
4551
+ root: instance(namespace),
4552
+ declarations: declarationsFor(namespace)
4553
+ });
2373
4554
  const runtime = {
2374
4555
  name: options.name,
2375
4556
  sqlite,
@@ -2408,6 +4589,7 @@ var createRuntime = (options) => {
2408
4589
  branch,
2409
4590
  checkout,
2410
4591
  timeline,
4592
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2411
4593
  fetch: async (incoming) => {
2412
4594
  let request = incoming;
2413
4595
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2581,10 +4763,10 @@ var createRuntime = (options) => {
2581
4763
  },
2582
4764
  release: (name, checkpointId) => timeline(name).release(checkpointId),
2583
4765
  inspect: (name) => {
2584
- const history = timeline(name);
4766
+ const history2 = timeline(name);
2585
4767
  return {
2586
- branches: history.branches(),
2587
- checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
4768
+ branches: history2.branches(),
4769
+ checkpoints: history2.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2588
4770
  id,
2589
4771
  branch: branchName,
2590
4772
  parent,
@@ -2599,13 +4781,22 @@ var createRuntime = (options) => {
2599
4781
  } : {},
2600
4782
  routes: {
2601
4783
  ...credentialRoutes(credentials),
2602
- ...options.presets ? presetRoutes(options.presets, runtime) : {},
2603
4784
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2604
- ...options.admin?.(runtime) ?? {}
4785
+ ...options.admin?.(runtime) ?? {},
4786
+ // Shell routes win a colliding key. Fault presets are one of them: the admin page
4787
+ // maps `presets`, and a service route must not replace that list with a record.
4788
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
4789
+ ...stateAdminRoutes({
4790
+ open: stateScope,
4791
+ afterWrite: (namespace) => {
4792
+ checkpoint(namespace, "main");
4793
+ }
4794
+ }),
4795
+ ...adminUiRoutes(options.name, options.adminUi)
2605
4796
  },
2606
4797
  adminKey: options.adminKey
2607
4798
  });
2608
- return runtime;
4799
+ return defineMock(runtime);
2609
4800
  };
2610
4801
  var mutableResponse = (response) => {
2611
4802
  try {
@@ -2669,9 +4860,12 @@ var credentialRoutes = (registry) => ({
2669
4860
  }
2670
4861
  });
2671
4862
  var presetRoutes = (presets, runtime) => ({
2672
- "GET /faults/presets": () => adminJson(200, {
2673
- presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2674
- }),
4863
+ "GET /faults/presets": () => {
4864
+ const body = {
4865
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4866
+ };
4867
+ return adminJson(200, body);
4868
+ },
2675
4869
  "POST /faults/presets/:name": ({ params, body, namespace }) => {
2676
4870
  const name = params.name;
2677
4871
  if (!presets[name])
@@ -2682,7 +4876,7 @@ var presetRoutes = (presets, runtime) => ({
2682
4876
  });
2683
4877
 
2684
4878
  // src/generated/openapi.ts
2685
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Intercom REST API 2.11 (Mockingbird subset)","description":"Stateful mock subset of the Intercom REST API (version 2.11): contacts (search, create,\\nupdate, get), conversations (create, update, reply as user or admin with attachments,\\nclose/open/snooze/assign, get, search) and the admin identity endpoints. Covers the backend's\\nmember messaging adapter and the Intercom sync adapter.\\n","version":"2.11","x-mockingbird-upstream":{"note":"Trimmed from Intercom's published 2.11 API reference to the operations and fields our consumers use (intercom-messaging.adapter.ts, intercom-api.adapter.ts) and the webhook receivers (messaging.controller.ts, the EMR IntercomWebhookService)."}},"servers":[{"url":"https://api.intercom.io"}],"security":[{"bearerAuth":[]}],"paths":{"/contacts/search":{"post":{"operationId":"SearchContacts","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["query"],"properties":{"query":{"$ref":"#/components/schemas/ContactQuery"},"pagination":{"$ref":"#/components/schemas/Pagination"}}}}}},"responses":{"200":{"description":"Matching contacts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/contacts":{"post":{"operationId":"CreateContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactCreate"}}}},"responses":{"200":{"description":"The created contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/contacts/{contact_id}":{"parameters":[{"name":"contact_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}}}],"get":{"operationId":"GetContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"operationId":"UpdateContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactUpdate"}}}},"responses":{"200":{"description":"The updated contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/conversations":{"post":{"operationId":"CreateConversation","description":"A contact-initiated conversation. An optional \`Idempotency-Key\` header replays.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,40}$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["from","body"],"properties":{"from":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string","enum":["user","lead","contact"]},"id":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}}}},"body":{"type":"string","minLength":1,"maxLength":400},"created_at":{"type":"integer","minimum":1600000000,"maximum":1900000000}}}}}},"responses":{"200":{"description":"The first message of the new conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/conversations/search":{"post":{"operationId":"SearchConversations","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["query"],"properties":{"query":{"$ref":"#/components/schemas/ConversationQuery"},"pagination":{"$ref":"#/components/schemas/Pagination"},"sort_field":{"type":"string","enum":["updated_at","created_at","id","waiting_since"]},"sort_order":{"type":"string","enum":["ascending","descending"]}}}}}},"responses":{"200":{"description":"A page of matching conversations (without conversation parts)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/conversations/{conversation_id}":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"get":{"operationId":"GetConversation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"responses":{"200":{"description":"The conversation with its parts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"operationId":"UpdateConversation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"read":{"type":"boolean"},"title":{"type":"string","maxLength":120},"custom_attributes":{"type":"object","maxProperties":4,"additionalProperties":{"type":["string","number","boolean","null"]}}}}}}},"responses":{"200":{"description":"The updated conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/conversations/{conversation_id}/reply":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"post":{"operationId":"ReplyConversation","description":"Reply as the contact (\`type: user\` + \`intercom_user_id\`) or as an admin (\`type: admin\` + \`admin_id\`), as JSON (attachments as base64 \`attachment_files\`) or multipart (\`attachment_files[]\` file parts). Admin comments fire \`conversation.admin.replied\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReplyBody"}},"multipart/form-data":{"schema":{"type":"object","required":["message_type","type"],"properties":{"message_type":{"type":"string"},"type":{"type":"string"},"intercom_user_id":{"type":"string"},"admin_id":{"type":"string"},"body":{"type":"string"},"attachment_files[]":{"type":"array","items":{"type":"string","format":"binary"}}}}}}},"responses":{"200":{"description":"The conversation, with the new part","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/conversations/{conversation_id}/parts":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"post":{"operationId":"ManageConversation","description":"Close, open, snooze or assign; close and open fire \`conversation.admin.closed\` / \`opened\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["message_type","type","admin_id"],"properties":{"message_type":{"type":"string","enum":["close","open","snoozed","assignment"]},"type":{"type":"string","enum":["admin"]},"admin_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}},"body":{"type":"string","maxLength":400},"snoozed_until":{"type":"integer","minimum":1600000000,"maximum":1900000000},"assignee_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}}}}}}},"responses":{"200":{"description":"The conversation, with the new part","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/admins":{"get":{"operationId":"ListAdmins","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The workspace's admins","content":{"application/json":{"schema":{"type":"object","required":["type","admins"],"properties":{"type":{"type":"string","enum":["admin.list"]},"admins":{"type":"array","items":{"$ref":"#/components/schemas/Admin"}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/me":{"get":{"operationId":"GetMe","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The admin that owns the access token","content":{"application/json":{"schema":{"type":"object","required":["type","id","email","app"],"properties":{"type":{"type":"string","enum":["admin"]},"id":{"type":"string"},"name":{"type":"string"},"email":{"type":"string"},"email_verified":{"type":"boolean"},"has_inbox_seat":{"type":"boolean"},"avatar":{"type":"object"},"app":{"type":"object","required":["type","id_code"],"properties":{"type":{"type":"string"},"id_code":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"integer"},"secure":{"type":"boolean"},"identity_verification":{"type":"boolean"},"timezone":{"type":"string"},"region":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"parameters":{"ConversationId":{"name":"conversation_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"conversation","missing":"999999999999999"}}},"DisplayAs":{"name":"display_as","in":"query","schema":{"type":"string","enum":["plaintext"]}}},"responses":{"BadRequest":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"Unauthorized":{"description":"Missing or invalid access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"NotFound":{"description":"Unknown resource","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"Conflict":{"description":"A contact with that external_id or email already exists (or an idempotency conflict)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}}},"schemas":{"ErrorList":{"type":"object","required":["type","errors"],"properties":{"type":{"type":"string","enum":["error.list"]},"request_id":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"errors":{"type":"array","minItems":1,"items":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string"},"message":{"type":"string"}}}}}},"Pagination":{"type":"object","properties":{"per_page":{"type":"integer","minimum":1,"maximum":150},"starting_after":{"type":"string","maxLength":80}}},"ContactFilter":{"type":"object","required":["field","operator","value"],"properties":{"field":{"type":"string","enum":["external_id","email","id","name","role","phone"]},"operator":{"type":"string","enum":["=","!=","~","!~","^","$","IN","NIN"]},"value":{"oneOf":[{"type":"string","maxLength":80},{"type":"array","maxItems":3,"items":{"type":"string","maxLength":80}}]}}},"ContactQuery":{"oneOf":[{"$ref":"#/components/schemas/ContactFilter"},{"type":"object","required":["operator","value"],"properties":{"operator":{"type":"string","enum":["AND","OR"]},"value":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/ContactFilter"}}}}]},"ConversationFilter":{"type":"object","required":["field","operator","value"],"properties":{"field":{"type":"string","enum":["id","contact_ids","admin_assignee_id","team_assignee_id","state","open","read","created_at","updated_at","source.author.email","source.delivered_as"]},"operator":{"type":"string","enum":["=","!=","<",">","~","IN","NIN"]},"value":{"oneOf":[{"type":"string","maxLength":80},{"type":"integer"},{"type":"boolean"},{"type":"array","maxItems":3,"items":{"type":"string","maxLength":80}}]}}},"ConversationQuery":{"oneOf":[{"$ref":"#/components/schemas/ConversationFilter"},{"type":"object","required":["operator","value"],"properties":{"operator":{"type":"string","enum":["AND","OR"]},"value":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/ConversationFilter"}}}}]},"CustomAttributes":{"type":"object","maxProperties":30,"additionalProperties":{"type":["string","number","boolean","null"]}},"ContactCreate":{"type":"object","properties":{"role":{"type":"string","enum":["user","lead"]},"external_id":{"description":"Any string. The first branch steers the walk generator toward a few values, so random walks reach the duplicate (409) path.","anyOf":[{"type":"string","pattern":"^[1-4]$"},{"type":"string","minLength":1,"maxLength":64}]},"email":{"type":"string","format":"email","maxLength":120},"name":{"type":["string","null"],"maxLength":80},"phone":{"type":["string","null"],"maxLength":40},"signed_up_at":{"type":["integer","null"],"minimum":1000000000,"maximum":1900000000},"last_seen_at":{"type":["integer","null"],"minimum":1000000000,"maximum":1900000000},"custom_attributes":{"$ref":"#/components/schemas/CustomAttributes"}}},"ContactUpdate":{"allOf":[{"$ref":"#/components/schemas/ContactCreate"}]},"ReplyBody":{"type":"object","required":["message_type","type"],"properties":{"message_type":{"type":"string","enum":["comment","note","quick_reply"]},"type":{"type":"string","enum":["user","admin"]},"body":{"type":"string","maxLength":400},"intercom_user_id":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}},"user_id":{"type":"string","maxLength":64},"email":{"type":"string","maxLength":120},"admin_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}},"created_at":{"type":"integer","minimum":1600000000,"maximum":1900000000},"attachment_urls":{"type":"array","maxItems":3,"items":{"type":"string","maxLength":200}},"attachment_files":{"type":"array","maxItems":3,"items":{"type":"object","required":["content_type","data","name"],"properties":{"content_type":{"type":"string","maxLength":80},"data":{"type":"string","maxLength":400},"name":{"type":"string","minLength":1,"maxLength":80}}}}}},"Contact":{"type":"object","required":["type","id","role","created_at","updated_at","custom_attributes"],"properties":{"type":{"type":"string","enum":["contact"]},"id":{"type":"string","x-mockingbird-resource":{"type":"contact","identity":true}},"workspace_id":{"type":"string"},"external_id":{"type":["string","null"]},"role":{"type":"string"},"email":{"type":["string","null"]},"phone":{"type":["string","null"]},"name":{"type":["string","null"]},"avatar":{"type":["string","null"]},"owner_id":{"type":["integer","null"]},"has_hard_bounced":{"type":"boolean"},"marked_email_as_spam":{"type":"boolean"},"unsubscribed_from_emails":{"type":"boolean"},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"signed_up_at":{"type":["integer","null"]},"last_seen_at":{"type":["integer","null"]},"custom_attributes":{"type":"object"},"tags":{"type":"object"},"notes":{"type":"object"},"companies":{"type":"object"},"location":{"type":"object"},"social_profiles":{"type":"object"}}},"Pages":{"type":"object","required":["type","page","per_page","total_pages"],"properties":{"type":{"type":"string","enum":["pages"]},"page":{"type":"integer"},"per_page":{"type":"integer"},"total_pages":{"type":"integer"},"next":{"type":"object","required":["page","starting_after"],"properties":{"page":{"type":"integer"},"starting_after":{"type":"string"}}}}},"ContactList":{"type":"object","required":["type","data","total_count","pages"],"properties":{"type":{"type":"string","enum":["list"]},"data":{"type":"array","items":{"$ref":"#/components/schemas/Contact"}},"total_count":{"type":"integer"},"pages":{"$ref":"#/components/schemas/Pages"}}},"Author":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"name":{"type":["string","null"]},"email":{"type":["string","null"]}}},"Attachment":{"type":"object","required":["type","name","url","content_type"],"properties":{"type":{"type":"string"},"name":{"type":"string"},"url":{"type":"string"},"content_type":{"type":"string"},"filesize":{"type":"integer"},"width":{"type":["integer","null"]},"height":{"type":["integer","null"]}}},"ConversationPart":{"type":"object","required":["type","id","part_type","created_at","author"],"properties":{"type":{"type":"string","enum":["conversation_part"]},"id":{"type":"string"},"part_type":{"type":"string"},"body":{"type":["string","null"]},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"notified_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"assigned_to":{"type":["object","null"]},"author":{"$ref":"#/components/schemas/Author"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/Attachment"}},"external_id":{"type":["string","null"]},"redacted":{"type":"boolean"}}},"Conversation":{"type":"object","required":["type","id","created_at","updated_at","open","state","read","source","contacts"],"properties":{"type":{"type":"string","enum":["conversation"]},"id":{"type":"string","x-mockingbird-resource":{"type":"conversation","identity":true}},"title":{"type":["string","null"]},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"waiting_since":{"type":["integer","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"snoozed_until":{"type":["integer","null"]},"open":{"type":"boolean"},"state":{"type":"string","enum":["open","closed","snoozed"]},"read":{"type":"boolean"},"priority":{"type":"string"},"admin_assignee_id":{"type":["integer","null"]},"team_assignee_id":{"type":["string","null"]},"tags":{"type":"object"},"conversation_rating":{"type":["object","null"]},"source":{"type":"object","required":["type","id","delivered_as","body","author"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"delivered_as":{"type":"string"},"subject":{"type":"string"},"body":{"type":["string","null"]},"author":{"$ref":"#/components/schemas/Author"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/Attachment"}},"url":{"type":["string","null"]},"redacted":{"type":"boolean"}}},"contacts":{"type":"object","required":["type","contacts"],"properties":{"type":{"type":"string"},"contacts":{"type":"array","items":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"external_id":{"type":["string","null"]}}}}}},"teammates":{"type":"object"},"custom_attributes":{"type":"object"},"first_contact_reply":{"type":["object","null"]},"sla_applied":{"type":["object","null"]},"statistics":{"type":["object","null"]},"ai_agent_participated":{"type":"boolean"},"conversation_parts":{"type":"object","required":["type","conversation_parts","total_count"],"properties":{"type":{"type":"string"},"conversation_parts":{"type":"array","items":{"$ref":"#/components/schemas/ConversationPart"}},"total_count":{"type":"integer"}}}}},"ConversationList":{"type":"object","required":["type","pages","total_count","conversations"],"properties":{"type":{"type":"string","enum":["conversation.list"]},"pages":{"$ref":"#/components/schemas/Pages"},"total_count":{"type":"integer"},"conversations":{"type":"array","items":{"$ref":"#/components/schemas/Conversation"}}}},"Message":{"type":"object","required":["type","id","created_at","body","message_type","conversation_id"],"properties":{"type":{"type":"string","enum":["user_message"]},"id":{"type":"string"},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"body":{"type":"string"},"message_type":{"type":"string","enum":["inapp"]},"conversation_id":{"type":"string","x-mockingbird-resource":{"type":"conversation","identity":true}}}},"Admin":{"type":"object","required":["type","id","name","email"],"properties":{"type":{"type":"string","enum":["admin"]},"id":{"type":"string","x-mockingbird-resource":{"type":"admin","identity":true}},"name":{"type":"string"},"email":{"type":"string"},"job_title":{"type":["string","null"]},"away_mode_enabled":{"type":"boolean"},"away_mode_reassign":{"type":"boolean"},"has_inbox_seat":{"type":"boolean"},"team_ids":{"type":"array","items":{"type":"integer"}}}}}}}`);
4879
+ var document2 = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Intercom REST API 2.11 (Mockingbird subset)","description":"Stateful mock subset of the Intercom REST API (version 2.11): contacts (search, create,\\nupdate, get), conversations (create, update, reply as user or admin with attachments,\\nclose/open/snooze/assign, get, search) and the admin identity endpoints. Covers the backend's\\nmember messaging adapter and the Intercom sync adapter.\\n","version":"2.11","x-mockingbird-upstream":{"note":"Trimmed from Intercom's published 2.11 API reference to the operations and fields our consumers use (intercom-messaging.adapter.ts, intercom-api.adapter.ts) and the webhook receivers (messaging.controller.ts, the EMR IntercomWebhookService)."}},"servers":[{"url":"https://api.intercom.io"}],"security":[{"bearerAuth":[]}],"paths":{"/contacts/search":{"post":{"operationId":"SearchContacts","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["query"],"properties":{"query":{"$ref":"#/components/schemas/ContactQuery"},"pagination":{"$ref":"#/components/schemas/Pagination"}}}}}},"responses":{"200":{"description":"Matching contacts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/contacts":{"post":{"operationId":"CreateContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactCreate"}}}},"responses":{"200":{"description":"The created contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/contacts/{contact_id}":{"parameters":[{"name":"contact_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}}}],"get":{"operationId":"GetContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"operationId":"UpdateContact","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactUpdate"}}}},"responses":{"200":{"description":"The updated contact","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Contact"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/conversations":{"post":{"operationId":"CreateConversation","description":"A contact-initiated conversation. An optional \`Idempotency-Key\` header replays.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,40}$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["from","body"],"properties":{"from":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string","enum":["user","lead","contact"]},"id":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}}}},"body":{"type":"string","minLength":1,"maxLength":400},"created_at":{"type":"integer","minimum":1600000000,"maximum":1900000000}}}}}},"responses":{"200":{"description":"The first message of the new conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/conversations/search":{"post":{"operationId":"SearchConversations","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["query"],"properties":{"query":{"$ref":"#/components/schemas/ConversationQuery"},"pagination":{"$ref":"#/components/schemas/Pagination"},"sort_field":{"type":"string","enum":["updated_at","created_at","id","waiting_since"]},"sort_order":{"type":"string","enum":["ascending","descending"]}}}}}},"responses":{"200":{"description":"A page of matching conversations (without conversation parts)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/conversations/{conversation_id}":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"get":{"operationId":"GetConversation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"responses":{"200":{"description":"The conversation with its parts","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"operationId":"UpdateConversation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/DisplayAs"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"read":{"type":"boolean"},"title":{"type":"string","maxLength":120},"custom_attributes":{"type":"object","maxProperties":4,"additionalProperties":{"type":["string","number","boolean","null"]}}}}}}},"responses":{"200":{"description":"The updated conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/conversations/{conversation_id}/reply":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"post":{"operationId":"ReplyConversation","description":"Reply as the contact (\`type: user\` + \`intercom_user_id\`) or as an admin (\`type: admin\` + \`admin_id\`), as JSON (attachments as base64 \`attachment_files\`) or multipart (\`attachment_files[]\` file parts). Admin comments fire \`conversation.admin.replied\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReplyBody"}},"multipart/form-data":{"schema":{"type":"object","required":["message_type","type"],"properties":{"message_type":{"type":"string"},"type":{"type":"string"},"intercom_user_id":{"type":"string"},"admin_id":{"type":"string"},"body":{"type":"string"},"attachment_files[]":{"type":"array","items":{"type":"string","format":"binary"}}}}}}},"responses":{"200":{"description":"The conversation, with the new part","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/conversations/{conversation_id}/parts":{"parameters":[{"$ref":"#/components/parameters/ConversationId"}],"post":{"operationId":"ManageConversation","description":"Close, open, snooze or assign; close and open fire \`conversation.admin.closed\` / \`opened\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["message_type","type","admin_id"],"properties":{"message_type":{"type":"string","enum":["close","open","snoozed","assignment"]},"type":{"type":"string","enum":["admin"]},"admin_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}},"body":{"type":"string","maxLength":400},"snoozed_until":{"type":"integer","minimum":1600000000,"maximum":1900000000},"assignee_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}}}}}}},"responses":{"200":{"description":"The conversation, with the new part","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Conversation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/admins":{"get":{"operationId":"ListAdmins","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The workspace's admins","content":{"application/json":{"schema":{"type":"object","required":["type","admins"],"properties":{"type":{"type":"string","enum":["admin.list"]},"admins":{"type":"array","items":{"$ref":"#/components/schemas/Admin"}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/me":{"get":{"operationId":"GetMe","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The admin that owns the access token","content":{"application/json":{"schema":{"type":"object","required":["type","id","email","app"],"properties":{"type":{"type":"string","enum":["admin"]},"id":{"type":"string"},"name":{"type":"string"},"email":{"type":"string"},"email_verified":{"type":"boolean"},"has_inbox_seat":{"type":"boolean"},"avatar":{"type":"object"},"app":{"type":"object","required":["type","id_code"],"properties":{"type":{"type":"string"},"id_code":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"integer"},"secure":{"type":"boolean"},"identity_verification":{"type":"boolean"},"timezone":{"type":"string"},"region":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"parameters":{"ConversationId":{"name":"conversation_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"conversation","missing":"999999999999999"}}},"DisplayAs":{"name":"display_as","in":"query","schema":{"type":"string","enum":["plaintext"]}}},"responses":{"BadRequest":{"description":"Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"Unauthorized":{"description":"Missing or invalid access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"NotFound":{"description":"Unknown resource","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}},"Conflict":{"description":"A contact with that external_id or email already exists (or an idempotency conflict)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorList"}}}}},"schemas":{"ErrorList":{"type":"object","required":["type","errors"],"properties":{"type":{"type":"string","enum":["error.list"]},"request_id":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"errors":{"type":"array","minItems":1,"items":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string"},"message":{"type":"string"}}}}}},"Pagination":{"type":"object","properties":{"per_page":{"type":"integer","minimum":1,"maximum":150},"starting_after":{"type":"string","maxLength":80}}},"ContactFilter":{"type":"object","required":["field","operator","value"],"properties":{"field":{"type":"string","enum":["external_id","email","id","name","role","phone"]},"operator":{"type":"string","enum":["=","!=","~","!~","^","$","IN","NIN"]},"value":{"oneOf":[{"type":"string","maxLength":80},{"type":"array","maxItems":3,"items":{"type":"string","maxLength":80}}]}}},"ContactQuery":{"oneOf":[{"$ref":"#/components/schemas/ContactFilter"},{"type":"object","required":["operator","value"],"properties":{"operator":{"type":"string","enum":["AND","OR"]},"value":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/ContactFilter"}}}}]},"ConversationFilter":{"type":"object","required":["field","operator","value"],"properties":{"field":{"type":"string","enum":["id","contact_ids","admin_assignee_id","team_assignee_id","state","open","read","created_at","updated_at","source.author.email","source.delivered_as"]},"operator":{"type":"string","enum":["=","!=","<",">","~","IN","NIN"]},"value":{"oneOf":[{"type":"string","maxLength":80},{"type":"integer"},{"type":"boolean"},{"type":"array","maxItems":3,"items":{"type":"string","maxLength":80}}]}}},"ConversationQuery":{"oneOf":[{"$ref":"#/components/schemas/ConversationFilter"},{"type":"object","required":["operator","value"],"properties":{"operator":{"type":"string","enum":["AND","OR"]},"value":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/ConversationFilter"}}}}]},"CustomAttributes":{"type":"object","maxProperties":30,"additionalProperties":{"type":["string","number","boolean","null"]}},"ContactCreate":{"type":"object","properties":{"role":{"type":"string","enum":["user","lead"]},"external_id":{"description":"Any string. The first branch steers the walk generator toward a few values, so random walks reach the duplicate (409) path.","anyOf":[{"type":"string","pattern":"^[1-4]$"},{"type":"string","minLength":1,"maxLength":64}]},"email":{"type":"string","format":"email","maxLength":120},"name":{"type":["string","null"],"maxLength":80},"phone":{"type":["string","null"],"maxLength":40},"signed_up_at":{"type":["integer","null"],"minimum":1000000000,"maximum":1900000000},"last_seen_at":{"type":["integer","null"],"minimum":1000000000,"maximum":1900000000},"custom_attributes":{"$ref":"#/components/schemas/CustomAttributes"}}},"ContactUpdate":{"allOf":[{"$ref":"#/components/schemas/ContactCreate"}]},"ReplyBody":{"type":"object","required":["message_type","type"],"properties":{"message_type":{"type":"string","enum":["comment","note","quick_reply"]},"type":{"type":"string","enum":["user","admin"]},"body":{"type":"string","maxLength":400},"intercom_user_id":{"type":"string","x-mockingbird-resource-ref":{"type":"contact","missing":0}},"user_id":{"type":"string","maxLength":64},"email":{"type":"string","maxLength":120},"admin_id":{"type":"string","x-mockingbird-resource-ref":{"type":"admin","missing":"9999999"}},"created_at":{"type":"integer","minimum":1600000000,"maximum":1900000000},"attachment_urls":{"type":"array","maxItems":3,"items":{"type":"string","maxLength":200}},"attachment_files":{"type":"array","maxItems":3,"items":{"type":"object","required":["content_type","data","name"],"properties":{"content_type":{"type":"string","maxLength":80},"data":{"type":"string","maxLength":400},"name":{"type":"string","minLength":1,"maxLength":80}}}}}},"Contact":{"type":"object","required":["type","id","role","created_at","updated_at","custom_attributes"],"properties":{"type":{"type":"string","enum":["contact"]},"id":{"type":"string","x-mockingbird-resource":{"type":"contact","identity":true}},"workspace_id":{"type":"string"},"external_id":{"type":["string","null"]},"role":{"type":"string"},"email":{"type":["string","null"]},"phone":{"type":["string","null"]},"name":{"type":["string","null"]},"avatar":{"type":["string","null"]},"owner_id":{"type":["integer","null"]},"has_hard_bounced":{"type":"boolean"},"marked_email_as_spam":{"type":"boolean"},"unsubscribed_from_emails":{"type":"boolean"},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"signed_up_at":{"type":["integer","null"]},"last_seen_at":{"type":["integer","null"]},"custom_attributes":{"type":"object"},"tags":{"type":"object"},"notes":{"type":"object"},"companies":{"type":"object"},"location":{"type":"object"},"social_profiles":{"type":"object"}}},"Pages":{"type":"object","required":["type","page","per_page","total_pages"],"properties":{"type":{"type":"string","enum":["pages"]},"page":{"type":"integer"},"per_page":{"type":"integer"},"total_pages":{"type":"integer"},"next":{"type":"object","required":["page","starting_after"],"properties":{"page":{"type":"integer"},"starting_after":{"type":"string"}}}}},"ContactList":{"type":"object","required":["type","data","total_count","pages"],"properties":{"type":{"type":"string","enum":["list"]},"data":{"type":"array","items":{"$ref":"#/components/schemas/Contact"}},"total_count":{"type":"integer"},"pages":{"$ref":"#/components/schemas/Pages"}}},"Author":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"name":{"type":["string","null"]},"email":{"type":["string","null"]}}},"Attachment":{"type":"object","required":["type","name","url","content_type"],"properties":{"type":{"type":"string"},"name":{"type":"string"},"url":{"type":"string"},"content_type":{"type":"string"},"filesize":{"type":"integer"},"width":{"type":["integer","null"]},"height":{"type":["integer","null"]}}},"ConversationPart":{"type":"object","required":["type","id","part_type","created_at","author"],"properties":{"type":{"type":"string","enum":["conversation_part"]},"id":{"type":"string"},"part_type":{"type":"string"},"body":{"type":["string","null"]},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"notified_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"assigned_to":{"type":["object","null"]},"author":{"$ref":"#/components/schemas/Author"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/Attachment"}},"external_id":{"type":["string","null"]},"redacted":{"type":"boolean"}}},"Conversation":{"type":"object","required":["type","id","created_at","updated_at","open","state","read","source","contacts"],"properties":{"type":{"type":"string","enum":["conversation"]},"id":{"type":"string","x-mockingbird-resource":{"type":"conversation","identity":true}},"title":{"type":["string","null"]},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"waiting_since":{"type":["integer","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"snoozed_until":{"type":["integer","null"]},"open":{"type":"boolean"},"state":{"type":"string","enum":["open","closed","snoozed"]},"read":{"type":"boolean"},"priority":{"type":"string"},"admin_assignee_id":{"type":["integer","null"]},"team_assignee_id":{"type":["string","null"]},"tags":{"type":"object"},"conversation_rating":{"type":["object","null"]},"source":{"type":"object","required":["type","id","delivered_as","body","author"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"delivered_as":{"type":"string"},"subject":{"type":"string"},"body":{"type":["string","null"]},"author":{"$ref":"#/components/schemas/Author"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/Attachment"}},"url":{"type":["string","null"]},"redacted":{"type":"boolean"}}},"contacts":{"type":"object","required":["type","contacts"],"properties":{"type":{"type":"string"},"contacts":{"type":"array","items":{"type":"object","required":["type","id"],"properties":{"type":{"type":"string"},"id":{"type":"string"},"external_id":{"type":["string","null"]}}}}}},"teammates":{"type":"object"},"custom_attributes":{"type":"object"},"first_contact_reply":{"type":["object","null"]},"sla_applied":{"type":["object","null"]},"statistics":{"type":["object","null"]},"ai_agent_participated":{"type":"boolean"},"conversation_parts":{"type":"object","required":["type","conversation_parts","total_count"],"properties":{"type":{"type":"string"},"conversation_parts":{"type":"array","items":{"$ref":"#/components/schemas/ConversationPart"}},"total_count":{"type":"integer"}}}}},"ConversationList":{"type":"object","required":["type","pages","total_count","conversations"],"properties":{"type":{"type":"string","enum":["conversation.list"]},"pages":{"$ref":"#/components/schemas/Pages"},"total_count":{"type":"integer"},"conversations":{"type":"array","items":{"$ref":"#/components/schemas/Conversation"}}}},"Message":{"type":"object","required":["type","id","created_at","body","message_type","conversation_id"],"properties":{"type":{"type":"string","enum":["user_message"]},"id":{"type":"string"},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"body":{"type":"string"},"message_type":{"type":"string","enum":["inapp"]},"conversation_id":{"type":"string","x-mockingbird-resource":{"type":"conversation","identity":true}}}},"Admin":{"type":"object","required":["type","id","name","email"],"properties":{"type":{"type":"string","enum":["admin"]},"id":{"type":"string","x-mockingbird-resource":{"type":"admin","identity":true}},"name":{"type":"string"},"email":{"type":"string"},"job_title":{"type":["string","null"]},"away_mode_enabled":{"type":"boolean"},"away_mode_reassign":{"type":"boolean"},"has_inbox_seat":{"type":"boolean"},"team_ids":{"type":"array","items":{"type":"integer"}}}}}}}`);
2686
4880
  var operationIds = ["SearchContacts", "CreateContact", "GetContact", "UpdateContact", "CreateConversation", "SearchConversations", "GetConversation", "UpdateConversation", "ReplyConversation", "ManageConversation", "ListAdmins", "GetMe"];
2687
4881
  var supportedOperationIds = ["SearchContacts", "CreateContact", "GetContact", "UpdateContact", "CreateConversation", "SearchConversations", "GetConversation", "UpdateConversation", "ReplyConversation", "ManageConversation", "ListAdmins", "GetMe"];
2688
4882
 
@@ -2690,9 +4884,9 @@ var supportedOperationIds = ["SearchContacts", "CreateContact", "GetContact", "U
2690
4884
  var QueryError = class extends Error {
2691
4885
  };
2692
4886
  var FILTER_OPERATORS = ["=", "!=", "IN", "NIN", "<", ">", "~", "!~", "^", "$"];
2693
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4887
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2694
4888
  var parseQuery = (value, fields, depth = 0) => {
2695
- if (!isRecord4(value)) throw new QueryError("query must be an object");
4889
+ if (!isRecord6(value)) throw new QueryError("query must be an object");
2696
4890
  const operator = value.operator;
2697
4891
  if (operator === "AND" || operator === "OR") {
2698
4892
  if (depth >= 2) throw new QueryError("queries can be nested at most two levels deep");
@@ -2767,7 +4961,7 @@ var decodeCursor = (cursor) => {
2767
4961
  throw new QueryError("starting_after is not a valid cursor");
2768
4962
  };
2769
4963
  var paginate = (items, pagination, defaultPerPage) => {
2770
- const options = isRecord4(pagination) ? pagination : {};
4964
+ const options = isRecord6(pagination) ? pagination : {};
2771
4965
  const perPage = options.per_page === void 0 ? defaultPerPage : Number(options.per_page);
2772
4966
  if (!Number.isInteger(perPage) || perPage < 1 || perPage > 150) {
2773
4967
  throw new QueryError("per_page must be between 1 and 150");
@@ -2788,10 +4982,10 @@ var paginate = (items, pagination, defaultPerPage) => {
2788
4982
  }
2789
4983
  };
2790
4984
  };
2791
- var escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
4985
+ var escapeHtml2 = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2792
4986
  var toHtml = (body) => {
2793
4987
  if (/<[a-z][\s\S]*>/i.test(body)) return body;
2794
- return body.split(/\r?\n/).map((line) => `<p>${escapeHtml(line)}</p>`).join("");
4988
+ return body.split(/\r?\n/).map((line) => `<p>${escapeHtml2(line)}</p>`).join("");
2795
4989
  };
2796
4990
  var toPlaintext = (html) => {
2797
4991
  if (html === null) return null;
@@ -2963,14 +5157,14 @@ var INTERCOM_PRESETS = {
2963
5157
  webhook: { mode: "drop" }
2964
5158
  }
2965
5159
  };
2966
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2967
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2968
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5160
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5161
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
5162
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2969
5163
  var guard = (run) => {
2970
5164
  try {
2971
5165
  return run();
2972
5166
  } catch (error) {
2973
- if (error instanceof IntercomError) return adminError3(error.status, error.message);
5167
+ if (error instanceof IntercomError) return adminError4(error.status, error.message);
2974
5168
  throw error;
2975
5169
  }
2976
5170
  };
@@ -2980,27 +5174,27 @@ var adminRoutes = (runtime) => {
2980
5174
  const defaultAdmin = (namespace) => api(namespace).state.admins.list({ order: "oldest" }).at(0)?.value.id ?? "";
2981
5175
  return {
2982
5176
  ...outboxAdminRoutes(runtime, (instance) => instance.state.outbox),
2983
- "GET /contacts": ({ namespace }) => json4(200, { contacts: api(namespace).contacts() }),
2984
- "GET /conversations": ({ namespace }) => json4(200, { conversations: api(namespace).conversations() }),
5177
+ "GET /contacts": ({ namespace }) => json6(200, { contacts: api(namespace).contacts() }),
5178
+ "GET /conversations": ({ namespace }) => json6(200, { conversations: api(namespace).conversations() }),
2985
5179
  "POST /conversations": ({ body, namespace }) => guard(() => {
2986
- if (!isRecord5(body) || typeof body.body !== "string") {
2987
- return adminError3(400, 'expected {"contactId" | "externalId", "adminId"?, "body"}');
5180
+ if (!isRecord7(body) || typeof body.body !== "string") {
5181
+ return adminError4(400, 'expected {"contactId" | "externalId", "adminId"?, "body"}');
2988
5182
  }
2989
5183
  const state = api(namespace).state;
2990
5184
  const contactId = typeof body.contactId === "string" ? body.contactId : typeof body.externalId === "string" ? state.findContact((c) => c.external_id === body.externalId)?.id : void 0;
2991
- if (!contactId) return adminError3(404, "no such contact");
5185
+ if (!contactId) return adminError4(404, "no such contact");
2992
5186
  const created = api(namespace).startAdminConversation({
2993
5187
  contactId,
2994
5188
  adminId: typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace),
2995
5189
  body: body.body
2996
5190
  });
2997
- return json4(201, created);
5191
+ return json6(201, created);
2998
5192
  }),
2999
5193
  "POST /conversations/:id/admin-reply": ({ params, body, namespace }) => guard(() => {
3000
5194
  const found = conversation(namespace, params.id);
3001
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3002
- if (!isRecord5(body) || typeof body.body !== "string") {
3003
- return adminError3(
5195
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
5196
+ if (!isRecord7(body) || typeof body.body !== "string") {
5197
+ return adminError4(
3004
5198
  400,
3005
5199
  'expected {"adminId" | "admin_id"?, "body", "messageType"?: "comment" | "note"}'
3006
5200
  );
@@ -3010,30 +5204,30 @@ var adminRoutes = (runtime) => {
3010
5204
  const author = instance.state.admins.get(
3011
5205
  typeof requested === "string" ? requested : defaultAdmin(namespace)
3012
5206
  );
3013
- if (!author) return adminError3(404, `no admin ${String(requested)}`);
5207
+ if (!author) return adminError4(404, `no admin ${String(requested)}`);
3014
5208
  const next = instance.appendPart(found, {
3015
5209
  partType: body.messageType === "note" ? "note" : "comment",
3016
5210
  author: { type: "admin", id: author.id, name: author.name, email: author.email },
3017
5211
  body: toHtml(body.body)
3018
5212
  });
3019
- return json4(200, next);
5213
+ return json6(200, next);
3020
5214
  }),
3021
5215
  "POST /conversations/:id/close": ({ params, body, namespace }) => guard(() => {
3022
5216
  const found = conversation(namespace, params.id);
3023
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3024
- const adminId = isRecord5(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
3025
- return json4(200, api(namespace).manage(found, { action: "close", adminId }));
5217
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
5218
+ const adminId = isRecord7(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
5219
+ return json6(200, api(namespace).manage(found, { action: "close", adminId }));
3026
5220
  }),
3027
5221
  "POST /conversations/:id/open": ({ params, body, namespace }) => guard(() => {
3028
5222
  const found = conversation(namespace, params.id);
3029
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3030
- const adminId = isRecord5(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
3031
- return json4(200, api(namespace).manage(found, { action: "open", adminId }));
5223
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
5224
+ const adminId = isRecord7(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
5225
+ return json6(200, api(namespace).manage(found, { action: "open", adminId }));
3032
5226
  }),
3033
5227
  "PUT /admins": ({ body, namespace }) => {
3034
- const list = Array.isArray(body) ? body : isRecord5(body) ? body.admins : void 0;
3035
- if (!Array.isArray(list) || !list.every((a) => isRecord5(a) && typeof a.id === "string")) {
3036
- return adminError3(400, "expected [{id, name, email}, \u2026]");
5228
+ const list = Array.isArray(body) ? body : isRecord7(body) ? body.admins : void 0;
5229
+ if (!Array.isArray(list) || !list.every((a) => isRecord7(a) && typeof a.id === "string")) {
5230
+ return adminError4(400, "expected [{id, name, email}, \u2026]");
3037
5231
  }
3038
5232
  const state = api(namespace).state;
3039
5233
  for (const row of state.admins.list()) state.admins.delete(row.id);
@@ -3050,23 +5244,23 @@ var adminRoutes = (runtime) => {
3050
5244
  team_ids: []
3051
5245
  });
3052
5246
  }
3053
- return json4(200, { admins: state.admins.list({ order: "oldest" }).map((row) => row.value) });
5247
+ return json6(200, { admins: state.admins.list({ order: "oldest" }).map((row) => row.value) });
3054
5248
  },
3055
- "GET /settings": ({ namespace }) => json4(200, api(namespace).state.current()),
5249
+ "GET /settings": ({ namespace }) => json6(200, api(namespace).state.current()),
3056
5250
  "PUT /settings": ({ body, namespace }) => {
3057
- if (!isRecord5(body)) return adminError3(400, "expected a JSON object");
5251
+ if (!isRecord7(body)) return adminError4(400, "expected a JSON object");
3058
5252
  const patch = {};
3059
5253
  if (body.tokens !== void 0) {
3060
- if (!Array.isArray(body.tokens)) return adminError3(400, "tokens: string[]");
5254
+ if (!Array.isArray(body.tokens)) return adminError4(400, "tokens: string[]");
3061
5255
  patch.tokens = body.tokens.map(String);
3062
5256
  }
3063
5257
  if (body.customAttributes !== void 0) {
3064
5258
  if (body.customAttributes !== null && !Array.isArray(body.customAttributes)) {
3065
- return adminError3(400, "customAttributes: string[] | null");
5259
+ return adminError4(400, "customAttributes: string[] | null");
3066
5260
  }
3067
5261
  patch.customAttributes = body.customAttributes === null ? null : body.customAttributes.map(String);
3068
5262
  }
3069
- return json4(200, api(namespace).state.update(patch));
5263
+ return json6(200, api(namespace).state.update(patch));
3070
5264
  }
3071
5265
  };
3072
5266
  };
@@ -3091,7 +5285,7 @@ var createRuntime2 = (options = {}) => {
3091
5285
  });
3092
5286
  const runtime = createRuntime({
3093
5287
  name: INTERCOM_NAMESPACE,
3094
- document,
5288
+ document: document2,
3095
5289
  ...options.sqlite ? { sqlite: options.sqlite } : {},
3096
5290
  ...options.clock ? { clock: options.clock } : {},
3097
5291
  ...options.seed !== void 0 ? { seed: options.seed } : {},
@@ -3169,7 +5363,7 @@ var CONVERSATION_FIELDS = [
3169
5363
  "source.author.name",
3170
5364
  "source.author.email"
3171
5365
  ];
3172
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5366
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3173
5367
  var str = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
3174
5368
  var IntercomError = class extends Error {
3175
5369
  constructor(status, code, message) {
@@ -3250,7 +5444,7 @@ var IntercomAPI = class {
3250
5444
  })
3251
5445
  });
3252
5446
  this.service = createService({
3253
- document,
5447
+ document: document2,
3254
5448
  handlers,
3255
5449
  sqlite,
3256
5450
  namespace,
@@ -3314,7 +5508,7 @@ var IntercomAPI = class {
3314
5508
  `${[first.path, missing[1]].filter(Boolean).join(".")} is required`
3315
5509
  ) : new IntercomError(400, "parameter_invalid", `${first.path || "body"} ${first.message}`);
3316
5510
  }
3317
- return context.body.kind === "json" && isRecord6(context.body.value) ? context.body.value : {};
5511
+ return context.body.kind === "json" && isRecord8(context.body.value) ? context.body.value : {};
3318
5512
  }
3319
5513
  // ─── Contacts ───────────────────────────────────────────────────────────────────────────
3320
5514
  contactBody(contact) {
@@ -3375,7 +5569,7 @@ var IntercomAPI = class {
3375
5569
  checkCustomAttributes(attributes) {
3376
5570
  if (attributes === void 0) return {};
3377
5571
  const defined = this.state.current().customAttributes;
3378
- const given = isRecord6(attributes) ? attributes : {};
5572
+ const given = isRecord8(attributes) ? attributes : {};
3379
5573
  if (defined !== null) {
3380
5574
  const unknown = Object.keys(given).find((key) => !defined.includes(key));
3381
5575
  if (unknown !== void 0) {
@@ -3609,7 +5803,7 @@ var IntercomAPI = class {
3609
5803
  ...typeof body.title === "string" ? { title: body.title } : {},
3610
5804
  custom_attributes: {
3611
5805
  ...conversation.custom_attributes,
3612
- ...isRecord6(body.custom_attributes) ? body.custom_attributes : {}
5806
+ ...isRecord8(body.custom_attributes) ? body.custom_attributes : {}
3613
5807
  },
3614
5808
  updated_at: this.seconds()
3615
5809
  };
@@ -3929,7 +6123,7 @@ var IntercomAPI = class {
3929
6123
  if (field.startsWith("source.")) {
3930
6124
  let value = conversation.source;
3931
6125
  for (const key of field.slice("source.".length).split(".")) {
3932
- value = isRecord6(value) ? value[key] : void 0;
6126
+ value = isRecord8(value) ? value[key] : void 0;
3933
6127
  }
3934
6128
  return value;
3935
6129
  }
@@ -4013,7 +6207,7 @@ var IntercomAPI = class {
4013
6207
  };
4014
6208
 
4015
6209
  export {
4016
- document,
6210
+ document2 as document,
4017
6211
  operationIds,
4018
6212
  supportedOperationIds,
4019
6213
  encodeCursor,
@@ -4031,4 +6225,4 @@ export {
4031
6225
  IntercomError,
4032
6226
  IntercomAPI
4033
6227
  };
4034
- //# sourceMappingURL=chunk-4XH3F7DQ.js.map
6228
+ //# sourceMappingURL=chunk-ZKUDPTGZ.js.map