@crvouga/mockingbird-service-flex 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -538,10 +540,10 @@ var OpenAPIReferenceError = class extends Error {
538
540
  };
539
541
  var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
540
542
  var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
541
- var resolveRef = (document2, ref) => {
543
+ var resolveRef = (document3, ref) => {
542
544
  if (!ref.startsWith("#/"))
543
545
  throw new OpenAPIReferenceError(ref);
544
- let cursor = document2;
546
+ let cursor = document3;
545
547
  for (const raw of ref.slice(2).split("/")) {
546
548
  const segment = unescapePointer(raw);
547
549
  if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
@@ -553,14 +555,14 @@ var resolveRef = (document2, ref) => {
553
555
  throw new OpenAPIReferenceError(ref);
554
556
  return cursor;
555
557
  };
556
- var deref = (document2, value) => {
558
+ var deref = (document3, value) => {
557
559
  let current = value;
558
560
  const seen = /* @__PURE__ */ new Set();
559
561
  while (isReference(current)) {
560
562
  if (seen.has(current.$ref))
561
563
  throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
562
564
  seen.add(current.$ref);
563
- current = resolveRef(document2, current.$ref);
565
+ current = resolveRef(document3, current.$ref);
564
566
  }
565
567
  return current;
566
568
  };
@@ -578,36 +580,36 @@ var HTTP_METHODS = [
578
580
  ];
579
581
 
580
582
  // ../../openapi/core/dist/document.js
581
- var mergeParameters = (document2, item, own) => {
583
+ var mergeParameters = (document3, item, own) => {
582
584
  const merged = /* @__PURE__ */ new Map();
583
585
  for (const raw of item.parameters ?? []) {
584
- const parameter = deref(document2, raw);
586
+ const parameter = deref(document3, raw);
585
587
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
586
588
  }
587
589
  for (const raw of own ?? []) {
588
- const parameter = deref(document2, raw);
590
+ const parameter = deref(document3, raw);
589
591
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
590
592
  }
591
593
  return [...merged.values()];
592
594
  };
593
- var listOperations = (document2) => {
595
+ var listOperations = (document3) => {
594
596
  const operations = [];
595
- for (const [path, item] of Object.entries(document2.paths)) {
597
+ for (const [path, item] of Object.entries(document3.paths)) {
596
598
  for (const method of HTTP_METHODS) {
597
599
  const operation = item[method];
598
600
  if (operation?.operationId === void 0)
599
601
  continue;
600
602
  const responses = {};
601
603
  for (const [status, response] of Object.entries(operation.responses)) {
602
- responses[status] = deref(document2, response);
604
+ responses[status] = deref(document3, response);
603
605
  }
604
606
  operations.push({
605
607
  operationId: operation.operationId,
606
608
  method,
607
609
  path,
608
610
  operation,
609
- parameters: mergeParameters(document2, item, operation.parameters),
610
- requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
611
+ parameters: mergeParameters(document3, item, operation.parameters),
612
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document3, operation.requestBody),
611
613
  responses
612
614
  });
613
615
  }
@@ -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 matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
802
+ const matches2 = s.oneOf.filter((branch) => validateValue(document3, branch, value).length === 0).length;
801
803
  if (matches2 !== 1)
802
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
804
+ fail2(`matches ${matches2} 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
 
@@ -1394,6 +1396,1737 @@ var clearNamespace = (sqlite, namespace) => {
1394
1396
  });
1395
1397
  };
1396
1398
 
1399
+ // ../../ui/dist/reset.js
1400
+ var CSS_RESET = `*,
1401
+ *::before,
1402
+ *::after {
1403
+ box-sizing: border-box;
1404
+ margin: 0;
1405
+ padding: 0;
1406
+ }
1407
+
1408
+ * {
1409
+ scrollbar-width: thin;
1410
+ scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;
1411
+ }
1412
+
1413
+ *::-webkit-scrollbar {
1414
+ width: 12px;
1415
+ height: 12px;
1416
+ }
1417
+
1418
+ *::-webkit-scrollbar-track,
1419
+ *::-webkit-scrollbar-corner {
1420
+ background: Canvas;
1421
+ }
1422
+
1423
+ *::-webkit-scrollbar-thumb {
1424
+ background: color-mix(in srgb, CanvasText 35%, Canvas);
1425
+ border: 3px solid Canvas;
1426
+ border-radius: 999px;
1427
+ }
1428
+
1429
+ html {
1430
+ hanging-punctuation: first allow-end last;
1431
+ -webkit-text-size-adjust: none;
1432
+ text-size-adjust: none;
1433
+ tab-size: 4;
1434
+ font-family:
1435
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI",
1436
+ "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
1437
+ font-size: 16px;
1438
+ line-height: 1.5;
1439
+ -webkit-font-smoothing: antialiased;
1440
+ -moz-osx-font-smoothing: grayscale;
1441
+ text-rendering: optimizeLegibility;
1442
+ -webkit-tap-highlight-color: transparent;
1443
+ scroll-behavior: smooth;
1444
+ background: Canvas;
1445
+ color: CanvasText;
1446
+ }
1447
+
1448
+ body {
1449
+ min-height: 100svh;
1450
+ line-height: 1.5;
1451
+ background: Canvas;
1452
+ color: CanvasText;
1453
+ }
1454
+
1455
+ h1 {
1456
+ font-size: 2em;
1457
+ }
1458
+
1459
+ h2 {
1460
+ font-size: 1.5em;
1461
+ }
1462
+
1463
+ h3 {
1464
+ font-size: 1.17em;
1465
+ }
1466
+
1467
+ h4 {
1468
+ font-size: 1em;
1469
+ }
1470
+
1471
+ h5 {
1472
+ font-size: 0.83em;
1473
+ }
1474
+
1475
+ h6 {
1476
+ font-size: 0.67em;
1477
+ }
1478
+
1479
+ h1,
1480
+ h2,
1481
+ h3,
1482
+ h4,
1483
+ h5,
1484
+ h6 {
1485
+ font-weight: 700;
1486
+ line-height: 1.2;
1487
+ text-wrap: balance;
1488
+ overflow-wrap: break-word;
1489
+ }
1490
+
1491
+ p,
1492
+ li,
1493
+ figcaption,
1494
+ dd,
1495
+ dt,
1496
+ blockquote {
1497
+ overflow-wrap: break-word;
1498
+ }
1499
+
1500
+ p,
1501
+ li,
1502
+ figcaption,
1503
+ blockquote {
1504
+ text-wrap: pretty;
1505
+ }
1506
+
1507
+ ul,
1508
+ ol,
1509
+ menu {
1510
+ list-style: none;
1511
+ }
1512
+
1513
+ a {
1514
+ color: inherit;
1515
+ text-decoration: underline;
1516
+ text-decoration-thickness: 1px;
1517
+ text-underline-offset: 0.15em;
1518
+ text-decoration-skip-ink: auto;
1519
+ }
1520
+
1521
+ b,
1522
+ strong {
1523
+ font-weight: 700;
1524
+ }
1525
+
1526
+ small {
1527
+ font-size: 0.875em;
1528
+ }
1529
+
1530
+ code,
1531
+ kbd,
1532
+ samp,
1533
+ pre {
1534
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1535
+ font-size: 1em;
1536
+ }
1537
+
1538
+ sub,
1539
+ sup {
1540
+ font-size: 75%;
1541
+ line-height: 0;
1542
+ position: relative;
1543
+ vertical-align: baseline;
1544
+ }
1545
+
1546
+ sub {
1547
+ bottom: -0.25em;
1548
+ }
1549
+
1550
+ sup {
1551
+ top: -0.5em;
1552
+ }
1553
+
1554
+ abbr[title] {
1555
+ text-decoration: underline dotted;
1556
+ text-underline-offset: 0.15em;
1557
+ }
1558
+
1559
+ mark {
1560
+ background: Mark;
1561
+ color: MarkText;
1562
+ }
1563
+
1564
+ hr {
1565
+ height: 0;
1566
+ border: 0;
1567
+ border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1568
+ color: inherit;
1569
+ }
1570
+
1571
+ img,
1572
+ picture,
1573
+ video,
1574
+ canvas {
1575
+ display: block;
1576
+ max-width: 100%;
1577
+ }
1578
+
1579
+ img,
1580
+ video {
1581
+ height: auto;
1582
+ }
1583
+
1584
+ svg {
1585
+ overflow: hidden;
1586
+ }
1587
+
1588
+ iframe {
1589
+ border: 0;
1590
+ max-width: 100%;
1591
+ }
1592
+
1593
+ table {
1594
+ border-collapse: collapse;
1595
+ border-spacing: 0;
1596
+ }
1597
+
1598
+ fieldset {
1599
+ border: 0;
1600
+ min-inline-size: 0;
1601
+ }
1602
+
1603
+ legend {
1604
+ padding: 0;
1605
+ }
1606
+
1607
+ button,
1608
+ input,
1609
+ select,
1610
+ textarea,
1611
+ optgroup {
1612
+ font: inherit;
1613
+ letter-spacing: inherit;
1614
+ color: inherit;
1615
+ margin: 0;
1616
+ vertical-align: middle;
1617
+ }
1618
+
1619
+ button,
1620
+ input[type="button"],
1621
+ input[type="submit"],
1622
+ input[type="reset"] {
1623
+ appearance: none;
1624
+ background: none;
1625
+ border: 0;
1626
+ padding: 0;
1627
+ cursor: pointer;
1628
+ text-align: center;
1629
+ }
1630
+
1631
+ input,
1632
+ textarea,
1633
+ select {
1634
+ background-color: Canvas;
1635
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1636
+ border-radius: 0;
1637
+ padding: 0.5em 0.65em;
1638
+ }
1639
+
1640
+ input[type="checkbox"],
1641
+ input[type="radio"],
1642
+ input[type="range"],
1643
+ input[type="file"],
1644
+ input[type="color"],
1645
+ input[type="button"],
1646
+ input[type="submit"],
1647
+ input[type="reset"],
1648
+ input[type="image"],
1649
+ input[type="hidden"] {
1650
+ background: none;
1651
+ border: 0;
1652
+ padding: 0;
1653
+ border-radius: 0;
1654
+ }
1655
+
1656
+ input[type="checkbox"],
1657
+ input[type="radio"] {
1658
+ accent-color: CanvasText;
1659
+ }
1660
+
1661
+ input[type="search"] {
1662
+ appearance: none;
1663
+ background-color: Canvas;
1664
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1665
+ }
1666
+
1667
+ input[type="search"]::-webkit-search-decoration,
1668
+ input[type="search"]::-webkit-search-cancel-button,
1669
+ input[type="search"]::-webkit-search-results-button,
1670
+ input[type="search"]::-webkit-search-results-decoration {
1671
+ -webkit-appearance: none;
1672
+ display: none;
1673
+ }
1674
+
1675
+ input[type="number"] {
1676
+ appearance: textfield;
1677
+ background-color: Canvas;
1678
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1679
+ }
1680
+
1681
+ input[type="number"]::-webkit-inner-spin-button,
1682
+ input[type="number"]::-webkit-outer-spin-button {
1683
+ -webkit-appearance: none;
1684
+ margin: 0;
1685
+ }
1686
+
1687
+ textarea {
1688
+ resize: vertical;
1689
+ }
1690
+
1691
+ ::placeholder {
1692
+ opacity: 1;
1693
+ color: color-mix(in srgb, CanvasText 45%, transparent);
1694
+ }
1695
+
1696
+ :focus-visible {
1697
+ outline: 2px solid CanvasText;
1698
+ outline-offset: 2px;
1699
+ }
1700
+
1701
+ :focus:not(:focus-visible) {
1702
+ outline: none;
1703
+ }
1704
+
1705
+ :disabled,
1706
+ [disabled] {
1707
+ cursor: default;
1708
+ opacity: 0.6;
1709
+ }
1710
+
1711
+ label,
1712
+ summary,
1713
+ select,
1714
+ [role="button"] {
1715
+ cursor: pointer;
1716
+ }
1717
+
1718
+ summary {
1719
+ display: list-item;
1720
+ }
1721
+
1722
+ details {
1723
+ display: block;
1724
+ }
1725
+
1726
+ dialog {
1727
+ margin: auto;
1728
+ padding: 1rem;
1729
+ border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1730
+ background: Canvas;
1731
+ color: CanvasText;
1732
+ max-width: calc(100vw - 2rem);
1733
+ max-height: calc(100svh - 2rem);
1734
+ }
1735
+
1736
+ dialog:not([open]) {
1737
+ display: none;
1738
+ }
1739
+
1740
+ ::backdrop {
1741
+ background: color-mix(in srgb, CanvasText 40%, transparent);
1742
+ }
1743
+
1744
+ [hidden] {
1745
+ display: none !important;
1746
+ }
1747
+
1748
+ ::selection {
1749
+ background: Highlight;
1750
+ color: HighlightText;
1751
+ }
1752
+
1753
+ @media (prefers-reduced-motion: reduce) {
1754
+ *,
1755
+ *::before,
1756
+ *::after {
1757
+ animation-duration: 0.01ms !important;
1758
+ animation-iteration-count: 1 !important;
1759
+ transition-duration: 0.01ms !important;
1760
+ scroll-behavior: auto !important;
1761
+ }
1762
+ }
1763
+
1764
+ @media (pointer: coarse) {
1765
+ input,
1766
+ select,
1767
+ textarea {
1768
+ font-size: max(16px, 1em);
1769
+ }
1770
+ }`;
1771
+
1772
+ // ../core/dist/admin-client.js
1773
+ function isRecord2(value) {
1774
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1775
+ }
1776
+ function mountAdminBrand(doc, host, service, catalog) {
1777
+ const clip = (value, max) => {
1778
+ if (typeof value !== "string")
1779
+ return null;
1780
+ const trimmed = value.trim();
1781
+ if (trimmed === "")
1782
+ return null;
1783
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
1784
+ };
1785
+ const httpUrl = (value) => {
1786
+ if (typeof value !== "string" || value.length > 2e3)
1787
+ return null;
1788
+ try {
1789
+ const url = new URL(value);
1790
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1791
+ return null;
1792
+ return url.href;
1793
+ } catch {
1794
+ return null;
1795
+ }
1796
+ };
1797
+ const hexColor = (value) => {
1798
+ if (typeof value !== "string")
1799
+ return null;
1800
+ const raw = value.trim();
1801
+ return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null;
1802
+ };
1803
+ const hostname = (value) => {
1804
+ try {
1805
+ return new URL(value).hostname.replace(/^www\./, "");
1806
+ } catch {
1807
+ return value;
1808
+ }
1809
+ };
1810
+ host.replaceChildren();
1811
+ host.hidden = true;
1812
+ if (!isRecord2(catalog) || !Object.hasOwn(catalog, service))
1813
+ return;
1814
+ const row = catalog[service];
1815
+ if (!isRecord2(row))
1816
+ return;
1817
+ const vendor = clip(row.vendor, 80);
1818
+ const website = httpUrl(row.website);
1819
+ const guide = httpUrl(row.guide);
1820
+ const docs = httpUrl(row.docs);
1821
+ const logo = httpUrl(row.logo);
1822
+ const color = hexColor(row.color);
1823
+ const description = clip(row.description, 280);
1824
+ if (vendor === null || website === null && guide === null && docs === null)
1825
+ return;
1826
+ const add = (node) => {
1827
+ host.append(node);
1828
+ return node;
1829
+ };
1830
+ if (logo !== null) {
1831
+ const img = doc.createElement("img");
1832
+ img.alt = "";
1833
+ img.src = logo;
1834
+ img.width = 16;
1835
+ img.height = 16;
1836
+ img.decoding = "async";
1837
+ img.referrerPolicy = "no-referrer";
1838
+ if (color !== null)
1839
+ img.style.borderColor = color;
1840
+ add(img);
1841
+ }
1842
+ const name = doc.createElement("span");
1843
+ name.className = "vendor-name";
1844
+ name.textContent = vendor;
1845
+ if (description !== null)
1846
+ name.title = description;
1847
+ add(name);
1848
+ const sep = () => {
1849
+ const node = doc.createElement("span");
1850
+ node.className = "vendor-sep";
1851
+ node.setAttribute("aria-hidden", "true");
1852
+ node.textContent = "\xB7";
1853
+ return node;
1854
+ };
1855
+ const link = (href, label, title) => {
1856
+ const node = doc.createElement("a");
1857
+ node.className = "vendor-link";
1858
+ node.href = href;
1859
+ node.target = "_blank";
1860
+ node.rel = "noopener noreferrer";
1861
+ node.referrerPolicy = "no-referrer";
1862
+ node.textContent = label;
1863
+ node.title = title;
1864
+ return node;
1865
+ };
1866
+ if (website !== null) {
1867
+ add(sep());
1868
+ add(link(website, hostname(website), `${vendor} website`));
1869
+ }
1870
+ if (guide !== null) {
1871
+ add(sep());
1872
+ add(link(guide, "Docs", `Docs for ${vendor}`));
1873
+ }
1874
+ if (docs !== null) {
1875
+ add(sep());
1876
+ add(link(docs, "API", `${vendor} API reference`));
1877
+ }
1878
+ host.removeAttribute("hidden");
1879
+ host.hidden = false;
1880
+ }
1881
+ function startAdminBrand(env) {
1882
+ const requested = env.params.get("brands");
1883
+ let brandsUrl = env.brandsUrl;
1884
+ if (requested) {
1885
+ try {
1886
+ const url = new URL(requested, env.location.href);
1887
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]" || url.origin === env.location.origin;
1888
+ if ((url.protocol === "https:" || url.protocol === "http:") && local)
1889
+ brandsUrl = url.href;
1890
+ } catch {
1891
+ brandsUrl = env.brandsUrl;
1892
+ }
1893
+ }
1894
+ const vendorHost = env.$("vendor");
1895
+ const brandRoot = env.document.querySelector("[data-mockingbird-admin]");
1896
+ const brandService = brandRoot?.getAttribute("data-service") || "";
1897
+ if (vendorHost === null)
1898
+ return;
1899
+ env.fetch(brandsUrl, {
1900
+ headers: { accept: "application/json" },
1901
+ signal: AbortSignal.timeout(5e3)
1902
+ }).then(async (response) => {
1903
+ if (!response.ok)
1904
+ return null;
1905
+ const catalog = await response.json();
1906
+ return catalog;
1907
+ }).then((catalog) => {
1908
+ mountAdminBrand(env.document, vendorHost, brandService, catalog);
1909
+ }).catch(() => {
1910
+ });
1911
+ }
1912
+ function faultPresetList(value) {
1913
+ if (!isRecord2(value))
1914
+ throw new Error("Fault presets response was not an object");
1915
+ if (!Object.hasOwn(value, "presets") || value.presets === void 0 || value.presets === null) {
1916
+ return { presets: [] };
1917
+ }
1918
+ if (!Array.isArray(value.presets))
1919
+ throw new Error("Fault presets response was not a list");
1920
+ return {
1921
+ presets: value.presets.flatMap((item) => {
1922
+ if (!isRecord2(item) || typeof item.name !== "string")
1923
+ return [];
1924
+ return [{ name: item.name }];
1925
+ })
1926
+ };
1927
+ }
1928
+ function bootAdmin(config) {
1929
+ const fieldKinds = ["string", "number", "boolean", "null", "object", "array", "unknown"];
1930
+ const sources = ["declared", "inferred", "mixed"];
1931
+ const isFieldKind = (value) => typeof value === "string" && fieldKinds.some((kind) => kind === value);
1932
+ const isSource = (value) => typeof value === "string" && sources.some((source) => source === value);
1933
+ const readJson2 = (text) => {
1934
+ const value = JSON.parse(text);
1935
+ return value;
1936
+ };
1937
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => {
1938
+ switch (char) {
1939
+ case "&":
1940
+ return "&amp;";
1941
+ case "<":
1942
+ return "&lt;";
1943
+ case ">":
1944
+ return "&gt;";
1945
+ case '"':
1946
+ return "&quot;";
1947
+ default:
1948
+ return "&#39;";
1949
+ }
1950
+ });
1951
+ const el = (id, kind) => {
1952
+ const node = document.getElementById(id);
1953
+ if (!(node instanceof kind))
1954
+ throw new Error(`admin shell is missing #${id}`);
1955
+ return node;
1956
+ };
1957
+ const errorMessage = (data, fallback) => {
1958
+ if (!isRecord2(data))
1959
+ return fallback;
1960
+ const error2 = data.error;
1961
+ if (!isRecord2(error2) || typeof error2.message !== "string" || error2.message === "") {
1962
+ return fallback;
1963
+ }
1964
+ return error2.message;
1965
+ };
1966
+ const requireList = (value, label) => {
1967
+ if (value === void 0 || value === null)
1968
+ return [];
1969
+ if (!Array.isArray(value))
1970
+ throw new Error(`${label} was not a list`);
1971
+ return value;
1972
+ };
1973
+ const state = {
1974
+ namespace: "default",
1975
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1976
+ view: "overview",
1977
+ collection: "",
1978
+ shape: null,
1979
+ route: null,
1980
+ editing: null
1981
+ };
1982
+ const standard = new Set(config.standardRoutes);
1983
+ const banner = el("banner", HTMLElement);
1984
+ const keyInput = el("admin-key", HTMLInputElement);
1985
+ keyInput.value = state.key;
1986
+ const params = new URLSearchParams(location.search);
1987
+ const queryKey = params.get("key");
1988
+ if (queryKey) {
1989
+ state.key = queryKey;
1990
+ keyInput.value = state.key;
1991
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
1992
+ params.delete("key");
1993
+ const next = params.toString();
1994
+ history.replaceState(null, "", location.pathname + (next ? `?${next}` : ""));
1995
+ }
1996
+ const queryNamespace = params.get("namespace");
1997
+ if (queryNamespace)
1998
+ state.namespace = queryNamespace;
1999
+ const showError = (error2) => {
2000
+ banner.textContent = error2 instanceof Error ? error2.message : String(error2);
2001
+ banner.classList.add("show");
2002
+ };
2003
+ const clearError = () => {
2004
+ banner.classList.remove("show");
2005
+ };
2006
+ const api = async (method, path, body) => {
2007
+ const headers = { accept: "application/json" };
2008
+ if (state.key !== "")
2009
+ headers[config.adminKeyHeader] = state.key;
2010
+ if (state.namespace !== "")
2011
+ headers["x-mockingbird-namespace"] = state.namespace;
2012
+ if (body !== void 0)
2013
+ headers["content-type"] = "application/json";
2014
+ const init = { method, headers };
2015
+ if (body !== void 0)
2016
+ init.body = JSON.stringify(body);
2017
+ const response = await fetch(config.adminPrefix + path, init);
2018
+ const text = await response.text();
2019
+ let data = null;
2020
+ if (text !== "") {
2021
+ try {
2022
+ data = readJson2(text);
2023
+ } catch {
2024
+ data = { raw: text };
2025
+ }
2026
+ }
2027
+ if (response.status === 401) {
2028
+ keyInput.focus();
2029
+ throw new Error(errorMessage(data, "Admin key required"));
2030
+ }
2031
+ if (!response.ok) {
2032
+ throw new Error(errorMessage(data, `${response.status} ${method} ${path}`));
2033
+ }
2034
+ return data;
2035
+ };
2036
+ const originGet = async (path) => {
2037
+ const response = await fetch(path, { headers: { accept: "application/json" } });
2038
+ if (!response.ok)
2039
+ throw new Error(`${response.status} ${path}`);
2040
+ const value = await response.json();
2041
+ return value;
2042
+ };
2043
+ const panelApi = {
2044
+ get: (path) => api("GET", path),
2045
+ send: (method, path, body) => api(method, path, body),
2046
+ namespace: () => state.namespace
2047
+ };
2048
+ const isPanelScript = (value) => typeof value === "function";
2049
+ const setTheme = (theme) => {
2050
+ if (theme)
2051
+ document.documentElement.dataset.theme = theme;
2052
+ else
2053
+ delete document.documentElement.dataset.theme;
2054
+ };
2055
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme");
2056
+ if (storedTheme)
2057
+ setTheme(storedTheme);
2058
+ el("theme", HTMLButtonElement).addEventListener("click", () => {
2059
+ const current = document.documentElement.dataset.theme;
2060
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
2061
+ const next = dark ? "light" : "dark";
2062
+ localStorage.setItem("mockingbird-admin-theme", next);
2063
+ setTheme(next);
2064
+ });
2065
+ const show = (view) => {
2066
+ state.view = view;
2067
+ for (const button of document.querySelectorAll("#nav button")) {
2068
+ if (!(button instanceof HTMLButtonElement))
2069
+ continue;
2070
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false");
2071
+ }
2072
+ for (const section of document.querySelectorAll("main .view")) {
2073
+ if (!(section instanceof HTMLElement))
2074
+ continue;
2075
+ section.hidden = section.id !== `view-${view}`;
2076
+ }
2077
+ };
2078
+ el("nav", HTMLElement).addEventListener("click", (event) => {
2079
+ const target = event.target;
2080
+ if (!(target instanceof Element))
2081
+ return;
2082
+ const button = target.closest("button[data-view]");
2083
+ if (!(button instanceof HTMLButtonElement))
2084
+ return;
2085
+ const view = button.dataset.view;
2086
+ if (view === void 0)
2087
+ return;
2088
+ show(view);
2089
+ refresh().catch(showError);
2090
+ });
2091
+ 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>`;
2092
+ const table = (columns, rows) => {
2093
+ if (rows.length === 0)
2094
+ return '<p class="empty">Nothing here yet.</p>';
2095
+ const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join("")}</tr>`;
2096
+ const body = rows.map((row) => {
2097
+ const cells = columns.map((column) => `<td data-label="${column.label}">${column.cell(row)}</td>`).join("");
2098
+ const attrs = "attrs" in row && typeof row.attrs === "string" ? row.attrs : "";
2099
+ return `<tr${attrs}>${cells}</tr>`;
2100
+ }).join("");
2101
+ return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`;
2102
+ };
2103
+ const preview = (value) => {
2104
+ const text = JSON.stringify(value) ?? "null";
2105
+ return esc(text.length > 180 ? `${text.slice(0, 180)}\u2026` : text);
2106
+ };
2107
+ const when = (epoch) => {
2108
+ const date = new Date(epoch);
2109
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString();
2110
+ };
2111
+ const clockCard = (epoch) => {
2112
+ const date = new Date(epoch);
2113
+ if (Number.isNaN(date.getTime()))
2114
+ return esc(String(epoch));
2115
+ const iso = date.toISOString();
2116
+ return `${esc(iso.slice(0, 10))}<span class="clock-time">${esc(iso.slice(11, 19))} UTC</span>`;
2117
+ };
2118
+ const decodeClock = (value) => {
2119
+ if (!isRecord2(value) || typeof value.now !== "number" || typeof value.offsetMs !== "number" || typeof value.frozen !== "boolean") {
2120
+ throw new Error("Clock response was not a clock");
2121
+ }
2122
+ return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen };
2123
+ };
2124
+ const decodeField = (value) => {
2125
+ if (!isRecord2(value) || typeof value.name !== "string" || !isFieldKind(value.kind)) {
2126
+ return void 0;
2127
+ }
2128
+ const field = {
2129
+ name: value.name,
2130
+ kind: value.kind,
2131
+ optional: value.optional === true
2132
+ };
2133
+ if (typeof value.description === "string")
2134
+ field.description = value.description;
2135
+ if (Array.isArray(value.fields)) {
2136
+ field.fields = value.fields.flatMap((item) => {
2137
+ const child = decodeField(item);
2138
+ return child === void 0 ? [] : [child];
2139
+ });
2140
+ }
2141
+ return field;
2142
+ };
2143
+ const decodeCollection = (value) => {
2144
+ if (!isRecord2(value) || typeof value.name !== "string")
2145
+ return void 0;
2146
+ const fields = Array.isArray(value.fields) ? value.fields.flatMap((item) => {
2147
+ const field = decodeField(item);
2148
+ return field === void 0 ? [] : [field];
2149
+ }) : [];
2150
+ const collection = {
2151
+ name: value.name,
2152
+ label: typeof value.label === "string" ? value.label : value.name,
2153
+ count: typeof value.count === "number" ? value.count : 0,
2154
+ source: isSource(value.source) ? value.source : "inferred",
2155
+ fields
2156
+ };
2157
+ if (typeof value.description === "string")
2158
+ collection.description = value.description;
2159
+ return collection;
2160
+ };
2161
+ const decodeState = (value) => {
2162
+ if (!isRecord2(value) || !Array.isArray(value.collections)) {
2163
+ throw new Error("State response has no collection list");
2164
+ }
2165
+ return {
2166
+ namespace: typeof value.namespace === "string" ? value.namespace : state.namespace,
2167
+ storageNamespace: typeof value.storageNamespace === "string" ? value.storageNamespace : "",
2168
+ collections: value.collections.flatMap((item) => {
2169
+ const collection = decodeCollection(item);
2170
+ return collection === void 0 ? [] : [collection];
2171
+ })
2172
+ };
2173
+ };
2174
+ const decodeRecords = (value) => requireList(isRecord2(value) ? value.records : void 0, "Records").flatMap((item) => {
2175
+ if (!isRecord2(item) || typeof item.id !== "string")
2176
+ return [];
2177
+ return [
2178
+ {
2179
+ id: item.id,
2180
+ seq: typeof item.seq === "number" ? item.seq : 0,
2181
+ value: item.value,
2182
+ attrs: ` class="clickable" data-id="${esc(item.id)}"`
2183
+ }
2184
+ ];
2185
+ });
2186
+ const textOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : "";
2187
+ const decodeJournal = (value) => requireList(isRecord2(value) ? value.requests : void 0, "Journal").flatMap((item) => {
2188
+ if (!isRecord2(item))
2189
+ return [];
2190
+ return [
2191
+ {
2192
+ at: textOf(item.at),
2193
+ method: textOf(item.method),
2194
+ path: textOf(item.path),
2195
+ status: textOf(item.status),
2196
+ durationMs: textOf(item.durationMs),
2197
+ operationId: textOf(item.operationId)
2198
+ }
2199
+ ];
2200
+ });
2201
+ const decodeFaults = (value) => requireList(isRecord2(value) ? value.faults : void 0, "Faults").flatMap((item) => {
2202
+ if (!isRecord2(item))
2203
+ return [];
2204
+ return [
2205
+ {
2206
+ id: textOf(item.id),
2207
+ method: typeof item.method === "string" ? item.method : void 0,
2208
+ pathPrefix: typeof item.pathPrefix === "string" ? item.pathPrefix : void 0,
2209
+ operationId: typeof item.operationId === "string" ? item.operationId : void 0,
2210
+ status: typeof item.status === "number" ? item.status : void 0,
2211
+ effect: typeof item.effect === "string" ? item.effect : void 0,
2212
+ drop: typeof item.drop === "boolean" ? item.drop : void 0,
2213
+ latencyMs: typeof item.latencyMs === "number" ? item.latencyMs : void 0
2214
+ }
2215
+ ];
2216
+ });
2217
+ const loadNamespaces = async () => {
2218
+ const data = await api("GET", "/namespaces");
2219
+ const select = el("namespace", HTMLSelectElement);
2220
+ const listed = requireList(isRecord2(data) ? data.namespaces : void 0, "Namespaces");
2221
+ const fallback = isRecord2(data) && typeof data.default === "string" && data.default !== "" ? data.default : "default";
2222
+ const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice();
2223
+ if (!names.includes(state.namespace))
2224
+ names.unshift(state.namespace);
2225
+ select.innerHTML = names.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join("");
2226
+ select.value = state.namespace;
2227
+ };
2228
+ const renderOverview = async () => {
2229
+ const [health, shape, clock, journal] = await Promise.all([
2230
+ originGet("/health"),
2231
+ api("GET", "/state"),
2232
+ api("GET", "/clock"),
2233
+ api("GET", "/requests?limit=8")
2234
+ ]);
2235
+ if (!isRecord2(health))
2236
+ throw new Error("Health response was not an object");
2237
+ const decoded = decodeState(shape);
2238
+ state.shape = decoded;
2239
+ const time = decodeClock(clock);
2240
+ el("overview-cards", HTMLElement).innerHTML = cards([
2241
+ {
2242
+ k: "Service",
2243
+ v: esc(typeof health.service === "string" && health.service !== "" ? health.service : config.service)
2244
+ },
2245
+ {
2246
+ k: "Status",
2247
+ v: esc(typeof health.status === "string" && health.status !== "" ? health.status : "ok")
2248
+ },
2249
+ { k: "Namespace", v: esc(state.namespace) },
2250
+ { k: "Collections", v: String(decoded.collections.length) },
2251
+ {
2252
+ k: "Records",
2253
+ v: String(decoded.collections.reduce((sum, item) => sum + item.count, 0))
2254
+ },
2255
+ { k: "Clock", v: clockCard(time.now) }
2256
+ ]);
2257
+ el("overview-requests", HTMLElement).innerHTML = table([
2258
+ { label: "Method", cell: (row) => esc(row.method) },
2259
+ { label: "Path", cell: (row) => esc(row.path) },
2260
+ {
2261
+ label: "Status",
2262
+ cell: (row) => `<span class="status-${row.status.charAt(0)}">${esc(row.status)}</span>`
2263
+ },
2264
+ { label: "Operation", cell: (row) => esc(row.operationId) }
2265
+ ], decodeJournal(journal));
2266
+ };
2267
+ const schemaChips = (collection) => {
2268
+ if (collection.fields.length === 0) {
2269
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>';
2270
+ }
2271
+ return `<div class="chips">${collection.fields.map((field) => `<span class="chip">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? "?" : ""}</i></span>`).join("")}</div>`;
2272
+ };
2273
+ const renderState = async () => {
2274
+ const shape = decodeState(await api("GET", "/state"));
2275
+ state.shape = shape;
2276
+ const host = el("collections", HTMLElement);
2277
+ if (shape.collections.length === 0) {
2278
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>';
2279
+ el("schema", HTMLElement).innerHTML = "";
2280
+ el("records", HTMLElement).innerHTML = "";
2281
+ return;
2282
+ }
2283
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2284
+ const first = shape.collections[0];
2285
+ if (first === void 0)
2286
+ return;
2287
+ state.collection = first.name;
2288
+ }
2289
+ 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("");
2290
+ const selected = shape.collections.find((item) => item.name === state.collection);
2291
+ if (selected === void 0)
2292
+ return;
2293
+ const description = selected.description ? `<p class="lede">${esc(selected.description)}</p>` : "";
2294
+ el("schema", HTMLElement).innerHTML = `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`;
2295
+ const page = await api("GET", `/state/${encodeURIComponent(state.collection)}?limit=50`);
2296
+ el("records", HTMLElement).innerHTML = table([
2297
+ { label: "Id", cell: (row) => `<code>${esc(row.id)}</code>` },
2298
+ { label: "Seq", cell: (row) => esc(row.seq) },
2299
+ { label: "Value", cell: (row) => preview(row.value) }
2300
+ ], decodeRecords(page));
2301
+ };
2302
+ const renderClock = async () => {
2303
+ const clock = decodeClock(await api("GET", "/clock"));
2304
+ 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>`;
2305
+ const freeze = el("freeze", HTMLButtonElement);
2306
+ freeze.textContent = clock.frozen ? "Unfreeze" : "Freeze";
2307
+ freeze.dataset.frozen = clock.frozen ? "1" : "0";
2308
+ };
2309
+ const renderFaults = async () => {
2310
+ const [faults, presets] = await Promise.all([
2311
+ api("GET", "/faults"),
2312
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2313
+ ]);
2314
+ const select = el("fault-preset", HTMLSelectElement);
2315
+ const current = select.value;
2316
+ const list = faultPresetList(presets).presets;
2317
+ select.innerHTML = `<option value="">Custom rule</option>${list.map((preset) => `<option value="${esc(preset.name)}">${esc(preset.name)}</option>`).join("")}`;
2318
+ select.value = current;
2319
+ el("fault-list", HTMLElement).innerHTML = table([
2320
+ { label: "Id", cell: (row) => esc(row.id) },
2321
+ {
2322
+ label: "Match",
2323
+ cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter((part) => Boolean(part)).join(" ") || "all")
2324
+ },
2325
+ {
2326
+ label: "Effect",
2327
+ cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || ""))
2328
+ }
2329
+ ], decodeFaults(faults));
2330
+ };
2331
+ const renderJournal = async () => {
2332
+ const journal = await api("GET", "/requests?limit=100");
2333
+ el("journal", HTMLElement).innerHTML = table([
2334
+ { label: "When", cell: (row) => esc(row.at) },
2335
+ { label: "Method", cell: (row) => esc(row.method) },
2336
+ { label: "Path", cell: (row) => esc(row.path) },
2337
+ { label: "Status", cell: (row) => esc(row.status) },
2338
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2339
+ ], decodeJournal(journal));
2340
+ };
2341
+ const renderRoutes = async () => {
2342
+ const data = await api("GET", "/");
2343
+ if (!isRecord2(data))
2344
+ throw new Error("Route list was not an object");
2345
+ const routes = requireList(data.routes, "Routes").map((route) => String(route));
2346
+ el("route-list", HTMLElement).innerHTML = routes.map((route) => {
2347
+ const extra = standard.has(route) ? "" : " <span class='badge'>extension</span>";
2348
+ const parts = route.split(" ");
2349
+ const method = parts[0] ?? "";
2350
+ const path = parts.slice(1).join(" ");
2351
+ 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>`;
2352
+ }).join("");
2353
+ };
2354
+ const renderers = {
2355
+ overview: renderOverview,
2356
+ state: renderState,
2357
+ clock: renderClock,
2358
+ faults: renderFaults,
2359
+ journal: renderJournal,
2360
+ routes: renderRoutes
2361
+ };
2362
+ async function refresh() {
2363
+ clearError();
2364
+ const render = renderers[state.view];
2365
+ if (render)
2366
+ await render();
2367
+ }
2368
+ el("namespace", HTMLSelectElement).addEventListener("change", () => {
2369
+ state.namespace = el("namespace", HTMLSelectElement).value;
2370
+ refresh().catch(showError);
2371
+ });
2372
+ keyInput.addEventListener("change", () => {
2373
+ state.key = keyInput.value.trim();
2374
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2375
+ refresh().catch(showError);
2376
+ });
2377
+ el("refresh", HTMLButtonElement).addEventListener("click", () => {
2378
+ refresh().catch(showError);
2379
+ });
2380
+ el("collections", HTMLElement).addEventListener("click", (event) => {
2381
+ const target = event.target;
2382
+ if (!(target instanceof Element))
2383
+ return;
2384
+ const button = target.closest("[data-collection]");
2385
+ if (!(button instanceof HTMLElement))
2386
+ return;
2387
+ const collection = button.dataset.collection;
2388
+ if (collection === void 0)
2389
+ return;
2390
+ state.collection = collection;
2391
+ renderState().catch(showError);
2392
+ });
2393
+ el("records", HTMLElement).addEventListener("click", (event) => {
2394
+ const target = event.target;
2395
+ if (!(target instanceof Element))
2396
+ return;
2397
+ const row = target.closest("[data-id]");
2398
+ if (!(row instanceof HTMLElement))
2399
+ return;
2400
+ const id = row.dataset.id;
2401
+ if (id === void 0)
2402
+ return;
2403
+ openEditor(id).catch(showError);
2404
+ });
2405
+ const editor = el("editor", HTMLDialogElement);
2406
+ const editorId = el("editor-id", HTMLInputElement);
2407
+ const editorValue = el("editor-value", HTMLTextAreaElement);
2408
+ const editorDelete = el("editor-delete", HTMLButtonElement);
2409
+ async function openEditor(id) {
2410
+ state.editing = id;
2411
+ el("editor-title", HTMLElement).textContent = id ? "Edit record" : "New record";
2412
+ editorId.value = id ?? "";
2413
+ editorId.readOnly = id !== null;
2414
+ editorDelete.hidden = id === null;
2415
+ if (id) {
2416
+ const record = await api("GET", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`);
2417
+ if (!isRecord2(record))
2418
+ throw new Error("Record response was not an object");
2419
+ editorValue.value = JSON.stringify(record.value, null, 2) ?? "";
2420
+ } else {
2421
+ editorValue.value = "{\n \n}";
2422
+ }
2423
+ editor.showModal();
2424
+ }
2425
+ el("new-record", HTMLButtonElement).addEventListener("click", () => {
2426
+ openEditor(null).catch(showError);
2427
+ });
2428
+ el("editor-form", HTMLFormElement).addEventListener("submit", (event) => {
2429
+ const submitter = event.submitter;
2430
+ if (!(submitter instanceof HTMLButtonElement) || submitter.value !== "save")
2431
+ return;
2432
+ event.preventDefault();
2433
+ let value;
2434
+ try {
2435
+ value = readJson2(editorValue.value);
2436
+ } catch {
2437
+ showError(new Error("Value is not JSON"));
2438
+ return;
2439
+ }
2440
+ const id = editorId.value.trim();
2441
+ const path = `/state/${encodeURIComponent(state.collection)}`;
2442
+ const request = state.editing ? api("PUT", `${path}/${encodeURIComponent(id)}`, { value }) : api("POST", path, { id: id || void 0, value });
2443
+ request.then(() => {
2444
+ editor.close();
2445
+ return renderState();
2446
+ }).catch(showError);
2447
+ });
2448
+ editorDelete.addEventListener("click", () => {
2449
+ const id = state.editing;
2450
+ if (!id)
2451
+ return;
2452
+ api("DELETE", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`).then(() => {
2453
+ editor.close();
2454
+ return renderState();
2455
+ }).catch(showError);
2456
+ });
2457
+ for (const button of document.querySelectorAll("[data-advance]")) {
2458
+ if (!(button instanceof HTMLButtonElement))
2459
+ continue;
2460
+ button.addEventListener("click", () => {
2461
+ const raw = button.dataset.advance;
2462
+ if (raw === void 0)
2463
+ return;
2464
+ api("POST", "/clock", { advance: Number(raw) }).then(() => renderClock()).catch(showError);
2465
+ });
2466
+ }
2467
+ el("freeze", HTMLButtonElement).addEventListener("click", () => {
2468
+ const frozen = el("freeze", HTMLButtonElement).dataset.frozen === "1";
2469
+ api("POST", "/clock", { freeze: !frozen }).then(() => renderClock()).catch(showError);
2470
+ });
2471
+ el("clock-reset", HTMLButtonElement).addEventListener("click", () => {
2472
+ api("POST", "/clock", { reset: true }).then(() => renderClock()).catch(showError);
2473
+ });
2474
+ el("clock-set", HTMLFormElement).addEventListener("submit", (event) => {
2475
+ event.preventDefault();
2476
+ const raw = el("clock-instant", HTMLInputElement).value.trim();
2477
+ const set = /^-?\d+$/.test(raw) ? Number(raw) : raw;
2478
+ api("POST", "/clock", { set }).then(() => renderClock()).catch(showError);
2479
+ });
2480
+ el("fault-form", HTMLFormElement).addEventListener("submit", (event) => {
2481
+ event.preventDefault();
2482
+ const preset = el("fault-preset", HTMLSelectElement).value;
2483
+ if (preset !== "") {
2484
+ api("POST", "/faults", { preset }).then(() => renderFaults()).catch(showError);
2485
+ return;
2486
+ }
2487
+ const status = Number(el("fault-status", HTMLInputElement).value);
2488
+ if (!Number.isFinite(status)) {
2489
+ showError(new Error("Status must be a number, or choose a preset"));
2490
+ return;
2491
+ }
2492
+ const path = el("fault-path", HTMLInputElement).value;
2493
+ const method = el("fault-method", HTMLInputElement).value;
2494
+ api("POST", "/faults", {
2495
+ status,
2496
+ ...path !== "" ? { pathPrefix: path } : {},
2497
+ ...method !== "" ? { method } : {}
2498
+ }).then(() => renderFaults()).catch(showError);
2499
+ });
2500
+ el("fault-clear", HTMLButtonElement).addEventListener("click", () => {
2501
+ api("DELETE", "/faults").then(() => renderFaults()).catch(showError);
2502
+ });
2503
+ el("journal-clear", HTMLButtonElement).addEventListener("click", () => {
2504
+ api("DELETE", "/requests").then(() => renderJournal()).catch(showError);
2505
+ });
2506
+ el("route-list", HTMLElement).addEventListener("click", (event) => {
2507
+ const target = event.target;
2508
+ if (!(target instanceof Element))
2509
+ return;
2510
+ const button = target.closest("[data-route]");
2511
+ if (!(button instanceof HTMLElement))
2512
+ return;
2513
+ const route = button.dataset.route;
2514
+ if (route === void 0)
2515
+ return;
2516
+ state.route = route;
2517
+ el("route-title", HTMLElement).textContent = route;
2518
+ const method = route.split(" ")[0] ?? "";
2519
+ el("route-body", HTMLTextAreaElement).disabled = method === "GET" || method === "DELETE";
2520
+ });
2521
+ el("route-form", HTMLFormElement).addEventListener("submit", (event) => {
2522
+ event.preventDefault();
2523
+ const send = async () => {
2524
+ if (state.route === null)
2525
+ throw new Error("Choose a route first");
2526
+ const parts = state.route.split(" ");
2527
+ const method = parts[0];
2528
+ const path = parts.slice(1).join(" ");
2529
+ if (method === void 0)
2530
+ throw new Error("Choose a route first");
2531
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_match, key) => prompt(`Value for ${key}`) || "");
2532
+ let body;
2533
+ const routeBody = el("route-body", HTMLTextAreaElement);
2534
+ if (method !== "GET" && method !== "DELETE" && routeBody.value.trim() !== "") {
2535
+ try {
2536
+ body = readJson2(routeBody.value);
2537
+ } catch {
2538
+ throw new Error("Body is not JSON");
2539
+ }
2540
+ }
2541
+ const data = await api(method, concrete, body);
2542
+ el("route-result", HTMLElement).textContent = JSON.stringify(data, null, 2);
2543
+ };
2544
+ send().catch(showError);
2545
+ });
2546
+ const decodePanel = (value) => {
2547
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2548
+ return void 0;
2549
+ }
2550
+ const panel = {
2551
+ id: value.id,
2552
+ title: value.title,
2553
+ description: typeof value.description === "string" ? value.description : "",
2554
+ html: typeof value.html === "string" ? value.html : ""
2555
+ };
2556
+ if (typeof value.script === "string")
2557
+ panel.script = value.script;
2558
+ return panel;
2559
+ };
2560
+ const mountPanels = (panels) => {
2561
+ const nav = el("nav", HTMLElement);
2562
+ const views = el("views", HTMLElement);
2563
+ for (const panel of panels) {
2564
+ const button = document.createElement("button");
2565
+ button.type = "button";
2566
+ button.dataset.view = panel.id;
2567
+ button.textContent = panel.title;
2568
+ nav.append(button);
2569
+ const section = document.createElement("section");
2570
+ section.className = "view";
2571
+ section.id = `view-${panel.id}`;
2572
+ section.hidden = true;
2573
+ const title = document.createElement("h2");
2574
+ title.textContent = panel.title;
2575
+ const lede = document.createElement("p");
2576
+ lede.className = "lede";
2577
+ lede.textContent = panel.description;
2578
+ const body = document.createElement("div");
2579
+ body.className = "panel-body";
2580
+ body.id = `panel-${panel.id}`;
2581
+ body.innerHTML = panel.html;
2582
+ section.append(title, lede, body);
2583
+ views.append(section);
2584
+ if (panel.script === void 0)
2585
+ continue;
2586
+ try {
2587
+ const compiled = new Function("root", "api", panel.script);
2588
+ if (!isPanelScript(compiled))
2589
+ throw new Error("panel script did not compile");
2590
+ compiled(body, panelApi);
2591
+ } catch (error2) {
2592
+ const note = document.createElement("p");
2593
+ note.className = "banner show";
2594
+ note.textContent = error2 instanceof Error ? error2.message : String(error2);
2595
+ body.append(note);
2596
+ }
2597
+ }
2598
+ };
2599
+ startAdminBrand({
2600
+ document,
2601
+ $: (id) => document.getElementById(id),
2602
+ params,
2603
+ location: { href: location.href, origin: location.origin },
2604
+ fetch,
2605
+ brandsUrl: config.brandsUrl
2606
+ });
2607
+ loadNamespaces().then(() => api("GET", "/ui/manifest")).then((manifest) => {
2608
+ const panels = requireList(isRecord2(manifest) ? manifest.panels : void 0, "Panels").flatMap((panel) => {
2609
+ const decoded = decodePanel(panel);
2610
+ return decoded === void 0 ? [] : [decoded];
2611
+ });
2612
+ mountPanels(panels);
2613
+ return refresh();
2614
+ }).catch(showError);
2615
+ }
2616
+ var clientPrelude = [isRecord2, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin].map((fn) => fn.toString()).join("\n");
2617
+ var adminClientSource = (config) => {
2618
+ const payload = JSON.stringify(config).replace(/</g, "\\u003c");
2619
+ return `<script>
2620
+ ${clientPrelude}
2621
+ bootAdmin(${payload});
2622
+ </script>`;
2623
+ };
2624
+
2625
+ // ../core/dist/surface.js
2626
+ var defineMock = (runtime) => runtime;
2627
+ var STANDARD_ADMIN_ROUTES = [
2628
+ "GET /",
2629
+ "POST /reset",
2630
+ "GET /namespaces",
2631
+ "GET /clock",
2632
+ "POST /clock",
2633
+ "GET /faults",
2634
+ "POST /faults",
2635
+ "DELETE /faults",
2636
+ "POST /snapshots",
2637
+ "POST /snapshots/:id/restore",
2638
+ "DELETE /snapshots/:id",
2639
+ "GET /timeline",
2640
+ "POST /checkpoints",
2641
+ "POST /branches/:name",
2642
+ "POST /branches/:name/checkout",
2643
+ "GET /requests",
2644
+ "DELETE /requests",
2645
+ "GET /metrics",
2646
+ "DELETE /metrics",
2647
+ "GET /credentials",
2648
+ "PUT /credentials",
2649
+ "DELETE /credentials",
2650
+ "GET /state",
2651
+ "GET /state/:collection",
2652
+ "GET /state/:collection/:id",
2653
+ "POST /state/:collection",
2654
+ "PUT /state/:collection/:id",
2655
+ "PATCH /state/:collection/:id",
2656
+ "DELETE /state/:collection/:id",
2657
+ "GET /ui",
2658
+ "GET /ui/",
2659
+ "GET /ui/manifest"
2660
+ ];
2661
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
2662
+ var assertAdminUi = (ui) => {
2663
+ if (!ui?.panels)
2664
+ return;
2665
+ const seen = /* @__PURE__ */ new Set();
2666
+ for (const panel of ui.panels) {
2667
+ if (!PANEL_ID.test(panel.id)) {
2668
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
2669
+ }
2670
+ if (seen.has(panel.id))
2671
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
2672
+ seen.add(panel.id);
2673
+ if (panel.title.trim() === "")
2674
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
2675
+ }
2676
+ };
2677
+
2678
+ // ../core/dist/admin-ui.js
2679
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
2680
+ switch (char) {
2681
+ case "&":
2682
+ return "&amp;";
2683
+ case "<":
2684
+ return "&lt;";
2685
+ case ">":
2686
+ return "&gt;";
2687
+ case '"':
2688
+ return "&quot;";
2689
+ default:
2690
+ return "&#39;";
2691
+ }
2692
+ });
2693
+ var ADMIN_BRANDS_URL = "https://mockingbird.chrisvouga.dev/brands.json";
2694
+ var renderAdminDocument = (service) => {
2695
+ const name = escapeHtml(service);
2696
+ const script = adminClientSource({
2697
+ standardRoutes: STANDARD_ADMIN_ROUTES,
2698
+ adminPrefix: ADMIN_PREFIX,
2699
+ adminKeyHeader: ADMIN_KEY_HEADER,
2700
+ brandsUrl: ADMIN_BRANDS_URL,
2701
+ service
2702
+ });
2703
+ return `<!DOCTYPE html>
2704
+ <html lang="en">
2705
+ <head>
2706
+ <meta charset="utf-8">
2707
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2708
+ <meta name="color-scheme" content="light dark">
2709
+ <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">
2710
+ <title>${name} admin</title>
2711
+ <style>
2712
+ ${CSS_RESET}
2713
+ :root {
2714
+ color-scheme: light;
2715
+ --bg: #fafafa;
2716
+ --bg-elev: #ffffff;
2717
+ --bg-muted: #f4f4f5;
2718
+ --bg-inset: #f4f4f5;
2719
+ --line: #dedee3;
2720
+ --line-strong: #c4c4cc;
2721
+ --ink: #18181b;
2722
+ --muted: #62626b;
2723
+ --faint: #71717a;
2724
+ --accent: #27272a;
2725
+ --accent-ink: #ffffff;
2726
+ --accent-soft: #f4f4f5;
2727
+ --ok: #166534;
2728
+ --ok-soft: #f0fdf4;
2729
+ --warn: #a16207;
2730
+ --warn-soft: #fefce8;
2731
+ --err: #a82d32;
2732
+ --err-soft: #fef2f2;
2733
+ --shadow: none;
2734
+ --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2735
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
2736
+ --radius: 10px;
2737
+ --header: 56px;
2738
+ --nav: 200px;
2739
+ }
2740
+ :root[data-theme="dark"] {
2741
+ color-scheme: dark;
2742
+ --bg: #111113;
2743
+ --bg-elev: #19191c;
2744
+ --bg-muted: #242428;
2745
+ --bg-inset: #111113;
2746
+ --line: #36363c;
2747
+ --line-strong: #52525b;
2748
+ --ink: #f4f4f5;
2749
+ --muted: #a9a9b2;
2750
+ --faint: #71717a;
2751
+ --accent: #e4e4e7;
2752
+ --accent-ink: #18181b;
2753
+ --accent-soft: #242428;
2754
+ --ok: #86efac;
2755
+ --ok-soft: #14241b;
2756
+ --warn: #fde68a;
2757
+ --warn-soft: #2a2410;
2758
+ --err: #ffaaaa;
2759
+ --err-soft: #2c1516;
2760
+ --shadow: none;
2761
+ }
2762
+ @media (prefers-color-scheme: dark) {
2763
+ :root:not([data-theme="light"]) {
2764
+ color-scheme: dark;
2765
+ --bg: #111113;
2766
+ --bg-elev: #19191c;
2767
+ --bg-muted: #242428;
2768
+ --bg-inset: #111113;
2769
+ --line: #36363c;
2770
+ --line-strong: #52525b;
2771
+ --ink: #f4f4f5;
2772
+ --muted: #a9a9b2;
2773
+ --faint: #71717a;
2774
+ --accent: #e4e4e7;
2775
+ --accent-ink: #18181b;
2776
+ --accent-soft: #242428;
2777
+ --ok: #86efac;
2778
+ --ok-soft: #14241b;
2779
+ --warn: #fde68a;
2780
+ --warn-soft: #2a2410;
2781
+ --err: #ffaaaa;
2782
+ --err-soft: #2c1516;
2783
+ --shadow: none;
2784
+ }
2785
+ }
2786
+ /* Fill the viewport, then grow with the content so the background covers the scroll. */
2787
+ html { height: 100%; }
2788
+ body {
2789
+ margin: 0;
2790
+ min-height: 100%;
2791
+ display: flex;
2792
+ flex-direction: column;
2793
+ font-family: var(--sans);
2794
+ background: var(--bg);
2795
+ color: var(--ink);
2796
+ line-height: 1.45;
2797
+ padding-left: env(safe-area-inset-left);
2798
+ padding-right: env(safe-area-inset-right);
2799
+ -webkit-text-size-adjust: 100%;
2800
+ }
2801
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
2802
+ .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }
2803
+ header.top {
2804
+ position: sticky; top: 0; z-index: 5;
2805
+ display: flex; align-items: center; gap: 12px;
2806
+ min-height: var(--header); padding: 10px 16px;
2807
+ background: var(--bg-elev);
2808
+ border-bottom: 1px solid var(--line);
2809
+ min-width: 0; max-width: 100%;
2810
+ }
2811
+ .brand {
2812
+ display: flex; flex-flow: row wrap; align-items: center; gap: 14px;
2813
+ min-width: 0; max-width: 100%; margin-right: auto;
2814
+ }
2815
+ .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }
2816
+ .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }
2817
+ .brand-id span { color: var(--faint); font-size: 12px; }
2818
+ .vendor {
2819
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2820
+ min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);
2821
+ }
2822
+ .vendor[hidden] { display: none; }
2823
+ /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */
2824
+ .vendor img {
2825
+ width: 16px; height: 16px; padding: 2px; box-sizing: content-box;
2826
+ border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;
2827
+ }
2828
+ .vendor-name { color: var(--ink); font-weight: 600; }
2829
+ .vendor-sep { color: var(--faint); }
2830
+ .vendor-link { color: inherit; text-decoration: none; }
2831
+ .vendor-link:hover { color: var(--ink); text-decoration: underline; }
2832
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
2833
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
2834
+ label.field input, label.field select, .controls input[type="password"] {
2835
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
2836
+ padding: 7px 8px; min-height: 36px;
2837
+ }
2838
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
2839
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
2840
+ background: var(--bg-elev);
2841
+ }
2842
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
2843
+ .btn-quiet { background: transparent; }
2844
+ .btn-danger { color: var(--err); }
2845
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
2846
+ record or the full nav row would widen the page past the viewport. */
2847
+ .layout {
2848
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
2849
+ flex: 1 0 auto; min-width: 0;
2850
+ }
2851
+ nav.side {
2852
+ border-right: 1px solid var(--line); padding: 12px;
2853
+ display: flex; flex-direction: column; gap: 4px;
2854
+ background: var(--bg-elev);
2855
+ }
2856
+ nav.side button {
2857
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
2858
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
2859
+ }
2860
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
2861
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
2862
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
2863
+ .lede { margin: 0 0 16px; color: var(--muted); }
2864
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
2865
+ .card {
2866
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
2867
+ padding: 14px 16px; box-shadow: var(--shadow);
2868
+ }
2869
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
2870
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
2871
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
2872
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
2873
+ .collection {
2874
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
2875
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
2876
+ }
2877
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
2878
+ .collection small { display: block; color: var(--faint); }
2879
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
2880
+ .chip {
2881
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
2882
+ border-radius: 999px; padding: 4px 8px;
2883
+ }
2884
+ .chip i { color: var(--faint); font-style: normal; }
2885
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
2886
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
2887
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
2888
+ tr.clickable { cursor: pointer; }
2889
+ tr.clickable:hover { background: var(--bg-muted); }
2890
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
2891
+ pre {
2892
+ margin: 0; white-space: pre-wrap; word-break: break-word;
2893
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
2894
+ }
2895
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
2896
+ .banner {
2897
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
2898
+ background: var(--err-soft); color: var(--err);
2899
+ }
2900
+ .banner.show { display: block; }
2901
+ .empty { color: var(--muted); padding: 24px 8px; }
2902
+ dialog {
2903
+ border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);
2904
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: none;
2905
+ }
2906
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
2907
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
2908
+ textarea {
2909
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
2910
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
2911
+ font-family: var(--mono); font-size: 12px;
2912
+ }
2913
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
2914
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
2915
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
2916
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
2917
+ .status-2 { color: var(--ok); }
2918
+ .status-4, .status-5, .status-0 { color: var(--err); }
2919
+ .stack { display: flex; flex-direction: column; gap: 12px; }
2920
+ .route {
2921
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
2922
+ padding: 8px 0; border-bottom: 1px solid var(--line);
2923
+ }
2924
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
2925
+ @media (max-width: 800px) {
2926
+ header.top {
2927
+ align-items: stretch; flex-direction: column;
2928
+ padding-top: max(10px, env(safe-area-inset-top));
2929
+ }
2930
+ input, select, textarea { font-size: 16px; }
2931
+ .brand, .vendor, .controls { width: 100%; }
2932
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
2933
+ .layout { grid-template-columns: minmax(0, 1fr); }
2934
+ nav.side {
2935
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
2936
+ border-right: 0; border-bottom: 1px solid var(--line);
2937
+ padding: 8px;
2938
+ }
2939
+ nav.side button { white-space: nowrap; flex: none; }
2940
+ .split { grid-template-columns: minmax(0, 1fr); }
2941
+ main { padding: 14px; }
2942
+ table, thead, tbody, tr, th, td { display: block; }
2943
+ thead { display: none; }
2944
+ tr {
2945
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
2946
+ background: var(--bg-elev); min-width: 0;
2947
+ }
2948
+ td {
2949
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
2950
+ min-width: 0; overflow-wrap: anywhere;
2951
+ }
2952
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
2953
+ .route { grid-template-columns: 72px 1fr; }
2954
+ .route button { grid-column: 1 / -1; }
2955
+ }
2956
+ </style>
2957
+ </head>
2958
+ <body>
2959
+ <div class="app" data-service="${name}" data-mockingbird-admin>
2960
+ <header class="top">
2961
+ <div class="brand">
2962
+ <div class="brand-id">
2963
+ <strong>${name}</strong>
2964
+ <span>Admin</span>
2965
+ </div>
2966
+ <div class="vendor" id="vendor" hidden></div>
2967
+ </div>
2968
+ <div class="controls">
2969
+ <label class="field">Namespace
2970
+ <select id="namespace" aria-label="Namespace"></select>
2971
+ </label>
2972
+ <label class="field">Admin key
2973
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
2974
+ </label>
2975
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
2976
+ <button class="btn" id="refresh" type="button">Refresh</button>
2977
+ </div>
2978
+ </header>
2979
+ <div class="layout">
2980
+ <nav class="side" id="nav" aria-label="Admin sections">
2981
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
2982
+ <button type="button" data-view="state">State</button>
2983
+ <button type="button" data-view="clock">Clock</button>
2984
+ <button type="button" data-view="faults">Faults</button>
2985
+ <button type="button" data-view="journal">Journal</button>
2986
+ <button type="button" data-view="routes">Routes</button>
2987
+ </nav>
2988
+ <main id="views">
2989
+ <p class="banner" id="banner" role="alert"></p>
2990
+ <section class="view" id="view-overview">
2991
+ <h2>Overview</h2>
2992
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
2993
+ <div class="grid" id="overview-cards"></div>
2994
+ <h3>Recent requests</h3>
2995
+ <div id="overview-requests"></div>
2996
+ </section>
2997
+ <section class="view" id="view-state" hidden>
2998
+ <h2>State</h2>
2999
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
3000
+ <div class="split">
3001
+ <div id="collections"></div>
3002
+ <div>
3003
+ <div id="schema"></div>
3004
+ <div class="row-actions">
3005
+ <button class="btn-primary" id="new-record" type="button">New record</button>
3006
+ </div>
3007
+ <div id="records"></div>
3008
+ </div>
3009
+ </div>
3010
+ </section>
3011
+ <section class="view" id="view-clock" hidden>
3012
+ <h2>Clock</h2>
3013
+ <p class="lede">The clock every timestamp in this mock reads.</p>
3014
+ <div class="card" id="clock-readout"></div>
3015
+ <div class="row-actions">
3016
+ <button class="btn" type="button" data-advance="60000">+1m</button>
3017
+ <button class="btn" type="button" data-advance="900000">+15m</button>
3018
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
3019
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
3020
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
3021
+ <button class="btn" id="freeze" type="button">Freeze</button>
3022
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
3023
+ </div>
3024
+ <form id="clock-set" class="row-actions">
3025
+ <label class="field">Set instant
3026
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
3027
+ </label>
3028
+ <button class="btn-primary" type="submit">Set</button>
3029
+ </form>
3030
+ </section>
3031
+ <section class="view" id="view-faults" hidden>
3032
+ <h2>Faults</h2>
3033
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
3034
+ <form id="fault-form" class="card stack">
3035
+ <label class="field">Preset
3036
+ <select id="fault-preset"><option value="">Custom rule</option></select>
3037
+ </label>
3038
+ <label class="field">Status
3039
+ <input id="fault-status" inputmode="numeric" placeholder="503">
3040
+ </label>
3041
+ <label class="field">Path prefix
3042
+ <input id="fault-path" placeholder="/v1">
3043
+ </label>
3044
+ <label class="field">Method
3045
+ <input id="fault-method" placeholder="GET">
3046
+ </label>
3047
+ <div class="dialog-actions">
3048
+ <button class="btn-primary" type="submit">Add fault</button>
3049
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
3050
+ </div>
3051
+ </form>
3052
+ <div id="fault-list"></div>
3053
+ </section>
3054
+ <section class="view" id="view-journal" hidden>
3055
+ <h2>Journal</h2>
3056
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
3057
+ <div class="row-actions">
3058
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
3059
+ </div>
3060
+ <div id="journal"></div>
3061
+ </section>
3062
+ <section class="view" id="view-routes" hidden>
3063
+ <h2>Routes</h2>
3064
+ <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>
3065
+ <div id="route-list"></div>
3066
+ <form id="route-form" class="card stack">
3067
+ <strong id="route-title">Select a route</strong>
3068
+ <label class="field">JSON body
3069
+ <textarea id="route-body" placeholder="{ }"></textarea>
3070
+ </label>
3071
+ <div class="dialog-actions">
3072
+ <button class="btn-primary" type="submit">Send</button>
3073
+ </div>
3074
+ <pre id="route-result">Response will show here.</pre>
3075
+ </form>
3076
+ </section>
3077
+ </main>
3078
+ </div>
3079
+ </div>
3080
+ <dialog id="editor">
3081
+ <form method="dialog" id="editor-form">
3082
+ <strong id="editor-title">Record</strong>
3083
+ <label class="field">Id
3084
+ <input id="editor-id" required>
3085
+ </label>
3086
+ <label class="field">JSON value
3087
+ <textarea id="editor-value"></textarea>
3088
+ </label>
3089
+ <div class="dialog-actions">
3090
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
3091
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
3092
+ <button class="btn-primary" type="submit" value="save">Save</button>
3093
+ </div>
3094
+ </form>
3095
+ </dialog>
3096
+ ${script}
3097
+ </body>
3098
+ </html>`;
3099
+ };
3100
+ var htmlResponse = (body) => new Response(body, {
3101
+ status: 200,
3102
+ headers: {
3103
+ "content-type": "text/html; charset=utf-8",
3104
+ "cache-control": "no-store"
3105
+ }
3106
+ });
3107
+ var json2 = (body) => new Response(JSON.stringify(body), {
3108
+ status: 200,
3109
+ headers: { "content-type": "application/json; charset=utf-8" }
3110
+ });
3111
+ var adminUiRoutes = (service, ui) => {
3112
+ const shell = () => renderAdminDocument(service);
3113
+ const document3 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
3114
+ return {
3115
+ "GET /ui": () => htmlResponse(document3()),
3116
+ "GET /ui/": () => htmlResponse(document3()),
3117
+ "GET /ui/manifest": () => json2({
3118
+ service,
3119
+ panels: (ui?.panels ?? []).map((panel) => ({
3120
+ id: panel.id,
3121
+ title: panel.title,
3122
+ ...panel.description !== void 0 ? { description: panel.description } : {},
3123
+ html: panel.html,
3124
+ ...panel.script !== void 0 ? { script: panel.script } : {}
3125
+ }))
3126
+ })
3127
+ };
3128
+ };
3129
+
1397
3130
  // ../../openapi/metadata/dist/types.js
1398
3131
  var EXTENSION_KEYS = {
1399
3132
  operation: "x-mockingbird",
@@ -1406,11 +3139,11 @@ var EXTENSION_KEYS = {
1406
3139
  };
1407
3140
 
1408
3141
  // ../../openapi/metadata/dist/read.js
1409
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3142
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1410
3143
  var extensionOf = (holder, key) => holder[key];
1411
3144
  var operationMetadata = (operation) => {
1412
3145
  const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1413
- const ext = isRecord2(raw) ? raw : {};
3146
+ const ext = isRecord3(raw) ? raw : {};
1414
3147
  const supported = ext.supported ?? true;
1415
3148
  const parity = ext.parity ?? {};
1416
3149
  return {
@@ -1520,9 +3253,9 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1520
3253
  this.name = "OperationRegistryError";
1521
3254
  }
1522
3255
  };
1523
- var verifyOperations = (document2, handlers) => {
3256
+ var verifyOperations = (document3, handlers) => {
1524
3257
  const problems = [];
1525
- const operations = listOperations(document2);
3258
+ const operations = listOperations(document3);
1526
3259
  const seen = /* @__PURE__ */ new Set();
1527
3260
  for (const operation of operations) {
1528
3261
  if (seen.has(operation.operationId))
@@ -1631,8 +3364,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1631
3364
  });
1632
3365
  };
1633
3366
 
3367
+ // ../core/dist/state-view.js
3368
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
3369
+ var RECORD_ID = /^[^\s/]{1,256}$/;
3370
+ var SAMPLE = 25;
3371
+ var WALK_LIMIT = 1e4;
3372
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
3373
+ var fail = (status, message) => ({ ok: false, status, message });
3374
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3375
+ var kindOf = (value) => {
3376
+ if (value === null)
3377
+ return "null";
3378
+ if (Array.isArray(value))
3379
+ return "array";
3380
+ switch (typeof value) {
3381
+ case "string":
3382
+ return "string";
3383
+ case "number":
3384
+ return Number.isFinite(value) ? "number" : "unknown";
3385
+ case "boolean":
3386
+ return "boolean";
3387
+ case "object":
3388
+ return "object";
3389
+ default:
3390
+ return "unknown";
3391
+ }
3392
+ };
3393
+ var humanize = (name) => {
3394
+ const words = name.replace(/[@:_-]+/g, " ").trim();
3395
+ if (words === "")
3396
+ return name;
3397
+ return words.charAt(0).toUpperCase() + words.slice(1);
3398
+ };
3399
+ var jsonValue = (value) => {
3400
+ if (value === void 0)
3401
+ return fail(400, "value is required");
3402
+ try {
3403
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
3404
+ } catch {
3405
+ return fail(400, "value must be JSON");
3406
+ }
3407
+ };
3408
+ var ctorName = (value) => {
3409
+ const ctor = value.constructor;
3410
+ return typeof ctor?.name === "string" ? ctor.name : "";
3411
+ };
3412
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
3413
+ var discoverCollections = (root) => {
3414
+ const found = [];
3415
+ const seen = /* @__PURE__ */ new Set();
3416
+ const visit = (value, depth) => {
3417
+ if (found.length + seen.size > WALK_LIMIT)
3418
+ return;
3419
+ if (value === null || typeof value !== "object")
3420
+ return;
3421
+ if (seen.has(value))
3422
+ return;
3423
+ seen.add(value);
3424
+ if (value instanceof Collection) {
3425
+ found.push(value);
3426
+ return;
3427
+ }
3428
+ if (value instanceof Map) {
3429
+ for (const child of value.values())
3430
+ visit(child, depth + 1);
3431
+ return;
3432
+ }
3433
+ if (value instanceof Set) {
3434
+ for (const child of value.values())
3435
+ visit(child, depth + 1);
3436
+ return;
3437
+ }
3438
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
3439
+ return;
3440
+ if (Array.isArray(value)) {
3441
+ const cap = Math.min(value.length, 32);
3442
+ for (let i = 0; i < cap; i++)
3443
+ visit(value[i], depth + 1);
3444
+ return;
3445
+ }
3446
+ let children;
3447
+ try {
3448
+ children = Object.values(value);
3449
+ } catch {
3450
+ return;
3451
+ }
3452
+ for (const child of children)
3453
+ visit(child, depth + 1);
3454
+ };
3455
+ visit(root, 0);
3456
+ return found;
3457
+ };
3458
+ var storedNames = (sqlite, namespace) => {
3459
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
3460
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
3461
+ return [...records, ...sequences].map((row) => row.name);
3462
+ };
3463
+ var blankAccum = (name) => ({
3464
+ name,
3465
+ kinds: /* @__PURE__ */ new Set(),
3466
+ present: 0,
3467
+ nested: /* @__PURE__ */ new Map()
3468
+ });
3469
+ var absorb = (accum, value) => {
3470
+ const kind = kindOf(value);
3471
+ accum.kinds.add(kind);
3472
+ accum.present++;
3473
+ if (!isRecord4(value))
3474
+ return;
3475
+ for (const [key, child] of Object.entries(value)) {
3476
+ const nested = accum.nested.get(key) ?? blankAccum(key);
3477
+ absorb(nested, child);
3478
+ accum.nested.set(key, nested);
3479
+ }
3480
+ };
3481
+ var finishField = (accum, samples) => {
3482
+ const kinds = [...accum.kinds];
3483
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
3484
+ const field = {
3485
+ name: accum.name,
3486
+ kind,
3487
+ optional: accum.present < samples || kinds.includes("null")
3488
+ };
3489
+ if (accum.nested.size > 0) {
3490
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
3491
+ }
3492
+ return field;
3493
+ };
3494
+ var inferFields = (records) => {
3495
+ if (records.length === 0)
3496
+ return [];
3497
+ const sample = records.slice(0, SAMPLE);
3498
+ const objects = sample.filter((record) => isRecord4(record.value));
3499
+ if (objects.length === 0) {
3500
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
3501
+ const list = [...kinds];
3502
+ return [
3503
+ {
3504
+ name: "(value)",
3505
+ kind: list.length === 1 ? list[0] : "unknown",
3506
+ optional: false
3507
+ }
3508
+ ];
3509
+ }
3510
+ const root = /* @__PURE__ */ new Map();
3511
+ for (const record of objects) {
3512
+ for (const [key, value] of Object.entries(record.value)) {
3513
+ const accum = root.get(key) ?? blankAccum(key);
3514
+ absorb(accum, value);
3515
+ root.set(key, accum);
3516
+ }
3517
+ }
3518
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
3519
+ };
3520
+ var mergeFields = (declared, inferred) => {
3521
+ const byName = /* @__PURE__ */ new Map();
3522
+ for (const field of inferred)
3523
+ byName.set(field.name, field);
3524
+ const ordered = [];
3525
+ const seen = /* @__PURE__ */ new Set();
3526
+ for (const field of declared ?? []) {
3527
+ const found = byName.get(field.name);
3528
+ seen.add(field.name);
3529
+ if (!found) {
3530
+ ordered.push({ ...field, optional: field.optional });
3531
+ continue;
3532
+ }
3533
+ ordered.push({
3534
+ ...found,
3535
+ kind: field.kind === "unknown" ? found.kind : field.kind,
3536
+ optional: field.optional || found.optional,
3537
+ ...field.description !== void 0 ? { description: field.description } : {},
3538
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
3539
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
3540
+ });
3541
+ }
3542
+ for (const field of inferred) {
3543
+ if (!seen.has(field.name))
3544
+ ordered.push(field);
3545
+ }
3546
+ return ordered;
3547
+ };
3548
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
3549
+ var readRecord = (collection, id) => {
3550
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
3551
+ const row = rows.find((entry) => entry.id === id);
3552
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
3553
+ };
3554
+ var inspectState = (scope) => {
3555
+ const declared = /* @__PURE__ */ new Map();
3556
+ for (const declaration of scope.declarations ?? []) {
3557
+ if (COLLECTION_NAME.test(declaration.name))
3558
+ declared.set(declaration.name, declaration);
3559
+ }
3560
+ const names = new Set(declared.keys());
3561
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
3562
+ names.add(name);
3563
+ for (const collection of discoverCollections(scope.root)) {
3564
+ if (collection.namespace === scope.storageNamespace)
3565
+ names.add(collection.collectionName);
3566
+ }
3567
+ const collections = [];
3568
+ for (const name of names) {
3569
+ if (!COLLECTION_NAME.test(name))
3570
+ continue;
3571
+ const declaration = declared.get(name);
3572
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3573
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
3574
+ const inferred = inferFields(records);
3575
+ const fields = mergeFields(declaration?.fields, inferred);
3576
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
3577
+ collections.push({
3578
+ name,
3579
+ label: declaration?.label ?? humanize(name),
3580
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
3581
+ count: collection.count(),
3582
+ source,
3583
+ fields,
3584
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
3585
+ });
3586
+ }
3587
+ const order = /* @__PURE__ */ new Map();
3588
+ for (const [index, item] of (scope.declarations ?? []).entries())
3589
+ order.set(item.name, index);
3590
+ collections.sort((a, b) => {
3591
+ const left = order.get(a.name);
3592
+ const right = order.get(b.name);
3593
+ if (left !== void 0 && right !== void 0)
3594
+ return left - right;
3595
+ if (left !== void 0)
3596
+ return -1;
3597
+ if (right !== void 0)
3598
+ return 1;
3599
+ return a.name.localeCompare(b.name);
3600
+ });
3601
+ return {
3602
+ namespace: scope.namespace,
3603
+ storageNamespace: scope.storageNamespace,
3604
+ collections
3605
+ };
3606
+ };
3607
+ var pageOf = (sqlite, storageNamespace, name, query) => {
3608
+ if (!COLLECTION_NAME.test(name))
3609
+ return fail(400, "collection name is not allowed");
3610
+ const limit = query.limit ?? 50;
3611
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
3612
+ return fail(400, "limit must be an integer from 1 to 200");
3613
+ }
3614
+ const order = query.order ?? "newest";
3615
+ if (order !== "newest" && order !== "oldest")
3616
+ return fail(400, 'order must be "newest" or "oldest"');
3617
+ const collection = collectionOf(sqlite, storageNamespace, name);
3618
+ const rows = collection.list({ order }).filter((row) => {
3619
+ if (query.after === void 0)
3620
+ return true;
3621
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
3622
+ });
3623
+ const slice = rows.slice(0, limit);
3624
+ const last = slice.at(-1);
3625
+ return {
3626
+ ok: true,
3627
+ value: {
3628
+ collection: name,
3629
+ count: collection.count(),
3630
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
3631
+ next: rows.length > limit && last ? last.seq : null
3632
+ }
3633
+ };
3634
+ };
3635
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
3636
+ var readStateRecord = (scope, name, id) => {
3637
+ if (!COLLECTION_NAME.test(name))
3638
+ return fail(400, "collection name is not allowed");
3639
+ if (!RECORD_ID.test(id))
3640
+ return fail(400, "record id is not allowed");
3641
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
3642
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
3643
+ };
3644
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
3645
+ var createStateRecord = (scope, name, input) => {
3646
+ if (!COLLECTION_NAME.test(name))
3647
+ return fail(400, "collection name is not allowed");
3648
+ const parsed = jsonValue(input.value);
3649
+ if (!parsed.ok)
3650
+ return parsed;
3651
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3652
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
3653
+ const checked = requireId(id);
3654
+ if (!checked.ok)
3655
+ return checked;
3656
+ if (collection.has(checked.value))
3657
+ return fail(409, `record ${checked.value} already exists`);
3658
+ const stored = collection.insert(checked.value, parsed.value);
3659
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3660
+ };
3661
+ var replaceStateRecord = (scope, name, id, value) => {
3662
+ if (!COLLECTION_NAME.test(name))
3663
+ return fail(400, "collection name is not allowed");
3664
+ const checked = requireId(id);
3665
+ if (!checked.ok)
3666
+ return checked;
3667
+ const parsed = jsonValue(value);
3668
+ if (!parsed.ok)
3669
+ return parsed;
3670
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3671
+ if (!collection.has(checked.value))
3672
+ return fail(404, `no record ${checked.value} in ${name}`);
3673
+ const stored = collection.update(checked.value, parsed.value);
3674
+ if (!stored)
3675
+ return fail(404, `no record ${checked.value} in ${name}`);
3676
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3677
+ };
3678
+ var patchStateRecord = (scope, name, id, value) => {
3679
+ const current = readStateRecord(scope, name, id);
3680
+ if (!current.ok)
3681
+ return current;
3682
+ const parsed = jsonValue(value);
3683
+ if (!parsed.ok)
3684
+ return parsed;
3685
+ const next = isRecord4(current.value.value) && isRecord4(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
3686
+ return replaceStateRecord(scope, name, id, next);
3687
+ };
3688
+ var deleteStateRecord = (scope, name, id) => {
3689
+ if (!COLLECTION_NAME.test(name))
3690
+ return fail(400, "collection name is not allowed");
3691
+ const checked = requireId(id);
3692
+ if (!checked.ok)
3693
+ return checked;
3694
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3695
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
3696
+ };
3697
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
3698
+ status,
3699
+ headers: { "content-type": "application/json; charset=utf-8" }
3700
+ });
3701
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
3702
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
3703
+ var integerParam = (value) => {
3704
+ if (value === null)
3705
+ return void 0;
3706
+ if (!/^-?\d+$/.test(value))
3707
+ return "bad";
3708
+ return Number(value);
3709
+ };
3710
+ var stateAdminRoutes = (routes) => {
3711
+ const open = (namespace) => {
3712
+ try {
3713
+ return { ok: true, value: routes.open(namespace) };
3714
+ } catch (error2) {
3715
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
3716
+ }
3717
+ };
3718
+ const wrote = (namespace) => {
3719
+ routes.afterWrite?.(namespace);
3720
+ };
3721
+ return {
3722
+ "GET /state": ({ namespace }) => {
3723
+ const scope = open(namespace);
3724
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
3725
+ },
3726
+ "GET /state/:collection": ({ namespace, params, url }) => {
3727
+ const scope = open(namespace);
3728
+ if (!scope.ok)
3729
+ return fromResult(scope, 200);
3730
+ const limit = integerParam(url.searchParams.get("limit"));
3731
+ const after = integerParam(url.searchParams.get("after"));
3732
+ if (limit === "bad")
3733
+ return adminError2(400, "limit: expected an integer");
3734
+ if (after === "bad")
3735
+ return adminError2(400, "after: expected a sequence number");
3736
+ const order = url.searchParams.get("order");
3737
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
3738
+ ...limit !== void 0 ? { limit } : {},
3739
+ ...after !== void 0 ? { after } : {},
3740
+ ...order === "newest" || order === "oldest" ? { order } : {}
3741
+ }), 200);
3742
+ },
3743
+ "GET /state/:collection/:id": ({ namespace, params }) => {
3744
+ const scope = open(namespace);
3745
+ if (!scope.ok)
3746
+ return fromResult(scope, 200);
3747
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
3748
+ },
3749
+ "POST /state/:collection": ({ namespace, params, body }) => {
3750
+ const scope = open(namespace);
3751
+ if (!scope.ok)
3752
+ return fromResult(scope, 201);
3753
+ if (!isRecord4(body) || !("value" in body)) {
3754
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3755
+ }
3756
+ const id = body.id;
3757
+ if (id !== void 0 && typeof id !== "string")
3758
+ return adminError2(400, "id must be a string");
3759
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3760
+ ...typeof id === "string" ? { id } : {},
3761
+ value: body.value
3762
+ });
3763
+ if (created.ok)
3764
+ wrote(namespace);
3765
+ return fromResult(created, 201);
3766
+ },
3767
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3768
+ const scope = open(namespace);
3769
+ if (!scope.ok)
3770
+ return fromResult(scope, 200);
3771
+ if (!isRecord4(body) || !("value" in body))
3772
+ return adminError2(400, 'expected {"value": <json>}');
3773
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3774
+ if (replaced.ok)
3775
+ wrote(namespace);
3776
+ return fromResult(replaced, 200);
3777
+ },
3778
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3779
+ const scope = open(namespace);
3780
+ if (!scope.ok)
3781
+ return fromResult(scope, 200);
3782
+ if (!isRecord4(body) || !("value" in body))
3783
+ return adminError2(400, 'expected {"value": <json>}');
3784
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3785
+ if (patched.ok)
3786
+ wrote(namespace);
3787
+ return fromResult(patched, 200);
3788
+ },
3789
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3790
+ const scope = open(namespace);
3791
+ if (!scope.ok)
3792
+ return fromResult(scope, 200);
3793
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3794
+ if (removed.ok)
3795
+ wrote(namespace);
3796
+ return fromResult(removed, 200);
3797
+ }
3798
+ };
3799
+ };
3800
+
1634
3801
  // ../core/dist/version.js
1635
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
3802
+ var PACKAGE_VERSION = true ? "1.5.0" : UNRELEASED_VERSION;
1636
3803
 
1637
3804
  // ../core/dist/signing.js
1638
3805
  var encoder = new TextEncoder();
@@ -1967,11 +4134,11 @@ var createWebhookHub = (options) => {
1967
4134
  };
1968
4135
  return hub;
1969
4136
  };
1970
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1971
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1972
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4137
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4138
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
4139
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1973
4140
  var parseEndpoint = (value) => {
1974
- if (!isRecord3(value) || typeof value.url !== "string")
4141
+ if (!isRecord5(value) || typeof value.url !== "string")
1975
4142
  return "each endpoint needs a url";
1976
4143
  try {
1977
4144
  new URL(value.url);
@@ -1988,18 +4155,18 @@ var parseEndpoint = (value) => {
1988
4155
  const events = value.events ?? value.enabledEvents;
1989
4156
  if (Array.isArray(events))
1990
4157
  endpoint.events = events.map(String);
1991
- if (isRecord3(value.tags)) {
4158
+ if (isRecord5(value.tags)) {
1992
4159
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1993
4160
  }
1994
4161
  if (typeof value.account === "string")
1995
4162
  endpoint.tags = { ...endpoint.tags, account: value.account };
1996
- if (isRecord3(value.headers)) {
4163
+ if (isRecord5(value.headers)) {
1997
4164
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1998
4165
  }
1999
4166
  return endpoint;
2000
4167
  };
2001
4168
  var webhookAdminRoutes = (hub) => ({
2002
- "GET /webhooks": ({ url, namespace }) => json2(200, {
4169
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
2003
4170
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2004
4171
  const type = url.searchParams.get("type");
2005
4172
  return type === null || d.type === type;
@@ -2007,51 +4174,51 @@ var webhookAdminRoutes = (hub) => ({
2007
4174
  }),
2008
4175
  "GET /webhooks/events": ({ url, namespace }) => {
2009
4176
  const type = url.searchParams.get("type");
2010
- return json2(200, {
4177
+ return json4(200, {
2011
4178
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2012
4179
  });
2013
4180
  },
2014
4181
  "POST /webhooks/:id/replay": async ({ params }) => {
2015
4182
  const replayed = await hub.replay(params.id);
2016
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
4183
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2017
4184
  },
2018
4185
  "POST /webhooks/flush": async () => {
2019
4186
  await hub.flush();
2020
- return json2(200, { status: "ok" });
4187
+ return json4(200, { status: "ok" });
2021
4188
  },
2022
4189
  "POST /webhooks/faults": ({ body, namespace }) => {
2023
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2024
- return adminError2(400, "mode must be duplicate, reorder or drop");
4190
+ if (!isRecord5(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
4191
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2025
4192
  }
2026
4193
  const fault = { mode: body.mode };
2027
4194
  if (typeof body.count === "number")
2028
4195
  fault.count = body.count;
2029
4196
  hub.fault(namespace, fault);
2030
- return json2(201, { namespace, ...fault });
4197
+ return json4(201, { namespace, ...fault });
2031
4198
  },
2032
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
4199
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
2033
4200
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2034
4201
  ...rest,
2035
4202
  secret: secret ? "(set)" : null
2036
4203
  }))
2037
4204
  }),
2038
4205
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2039
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
4206
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.endpoints : void 0;
2040
4207
  if (!Array.isArray(list))
2041
- return adminError2(400, "expected [{url, secret?, events?}]");
4208
+ return adminError3(400, "expected [{url, secret?, events?}]");
2042
4209
  const parsed = [];
2043
4210
  for (const each of list) {
2044
4211
  const endpoint = parseEndpoint(each);
2045
4212
  if (typeof endpoint === "string")
2046
- return adminError2(400, endpoint);
4213
+ return adminError3(400, endpoint);
2047
4214
  parsed.push(endpoint);
2048
4215
  }
2049
4216
  const set = hub.setEndpoints(namespace, parsed);
2050
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
4217
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2051
4218
  },
2052
4219
  "DELETE /webhook-endpoints": ({ namespace }) => {
2053
4220
  hub.setEndpoints(namespace, []);
2054
- return json2(200, { status: "ok" });
4221
+ return json4(200, { status: "ok" });
2055
4222
  }
2056
4223
  });
2057
4224
  var parsePayload = (message) => {
@@ -2106,8 +4273,8 @@ var DroppedConnectionError = class extends TypeError {
2106
4273
  this.name = "TypeError";
2107
4274
  }
2108
4275
  };
2109
- var operationMatcher = (document2) => {
2110
- const matchers = listOperations(document2).map((operation) => ({
4276
+ var operationMatcher = (document3) => {
4277
+ const matchers = listOperations(document3).map((operation) => ({
2111
4278
  operationId: operation.operationId,
2112
4279
  method: operation.method.toUpperCase(),
2113
4280
  pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
@@ -2116,6 +4283,7 @@ var operationMatcher = (document2) => {
2116
4283
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2117
4284
  };
2118
4285
  var createRuntime = (options) => {
4286
+ assertAdminUi(options.adminUi);
2119
4287
  const sqlite = bootSqlite(options.sqlite);
2120
4288
  const clock = options.clock ?? createClock();
2121
4289
  const rng = createRng(options.seed ?? 0);
@@ -2201,10 +4369,10 @@ var createRuntime = (options) => {
2201
4369
  const ensureBranch = (namespace, branch2, at) => {
2202
4370
  if (!BRANCH_PATTERN2.test(branch2))
2203
4371
  throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2204
- const history = timeline(namespace);
4372
+ const history2 = timeline(namespace);
2205
4373
  if (branch2 === "main") {
2206
4374
  if (at !== void 0) {
2207
- const point = history.checkout("main", at);
4375
+ const point = history2.checkout("main", at);
2208
4376
  restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2209
4377
  captured.set(namespace, point.value.snapshot);
2210
4378
  rng.setState(point.value.rngState);
@@ -2217,10 +4385,10 @@ var createRuntime = (options) => {
2217
4385
  return namespace;
2218
4386
  }
2219
4387
  const storage = physicalBranch(namespace, branch2);
2220
- if (!history.hasBranch(branch2)) {
4388
+ if (!history2.hasBranch(branch2)) {
2221
4389
  if (at === void 0)
2222
- history.commit(capture(namespace));
2223
- const point = history.fork(branch2, at === void 0 ? {} : { from: at });
4390
+ history2.commit(capture(namespace));
4391
+ const point = history2.fork(branch2, at === void 0 ? {} : { from: at });
2224
4392
  const branchRng = createRng(options.seed ?? 0);
2225
4393
  if (point)
2226
4394
  branchRng.setState(point.value.rngState);
@@ -2229,8 +4397,8 @@ var createRuntime = (options) => {
2229
4397
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2230
4398
  if (point)
2231
4399
  captured.set(storage, point.value.snapshot);
2232
- } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2233
- const point = history.checkout(branch2, at);
4400
+ } else if (at !== void 0 && history2.head(branch2)?.id !== at) {
4401
+ const point = history2.checkout(branch2, at);
2234
4402
  if (!instances.has(storage)) {
2235
4403
  const branchRng = createRng(options.seed ?? 0);
2236
4404
  branchRng.setState(point.value.rngState);
@@ -2241,7 +4409,7 @@ var createRuntime = (options) => {
2241
4409
  captured.set(storage, point.value.snapshot);
2242
4410
  } else {
2243
4411
  if (!instances.has(storage)) {
2244
- const point = history.head(branch2);
4412
+ const point = history2.head(branch2);
2245
4413
  const branchRng = createRng(options.seed ?? 0);
2246
4414
  if (point)
2247
4415
  branchRng.setState(point.value.rngState);
@@ -2265,8 +4433,8 @@ var createRuntime = (options) => {
2265
4433
  const checkout = (checkpointId, checkoutOptions = {}) => {
2266
4434
  const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2267
4435
  const branchName = checkoutOptions.branch ?? "main";
2268
- const history = timeline(namespace);
2269
- const point = history.checkout(branchName, checkpointId);
4436
+ const history2 = timeline(namespace);
4437
+ const point = history2.checkout(branchName, checkpointId);
2270
4438
  const storage = ensureBranch(namespace, branchName);
2271
4439
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2272
4440
  captured.set(storage, point.value.snapshot);
@@ -2316,12 +4484,25 @@ var createRuntime = (options) => {
2316
4484
  instance(name);
2317
4485
  restoreNamespace(sqlite, storageNamespace(name), from);
2318
4486
  captured.set(name, from);
2319
- const history = timelines.get(name);
2320
- if (history)
2321
- history.commit(capture(name), { branch: "main" });
4487
+ const history2 = timelines.get(name);
4488
+ if (history2)
4489
+ history2.commit(capture(name), { branch: "main" });
2322
4490
  else
2323
4491
  timeline(name);
2324
4492
  };
4493
+ const declarationsFor = (namespace) => {
4494
+ const declared = options.state;
4495
+ if (!declared)
4496
+ return [];
4497
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
4498
+ };
4499
+ const stateScope = (namespace) => ({
4500
+ sqlite,
4501
+ namespace,
4502
+ storageNamespace: storageNamespace(namespace),
4503
+ root: instance(namespace),
4504
+ declarations: declarationsFor(namespace)
4505
+ });
2325
4506
  const runtime = {
2326
4507
  name: options.name,
2327
4508
  sqlite,
@@ -2360,6 +4541,7 @@ var createRuntime = (options) => {
2360
4541
  branch,
2361
4542
  checkout,
2362
4543
  timeline,
4544
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2363
4545
  fetch: async (incoming) => {
2364
4546
  let request = incoming;
2365
4547
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2533,10 +4715,10 @@ var createRuntime = (options) => {
2533
4715
  },
2534
4716
  release: (name, checkpointId) => timeline(name).release(checkpointId),
2535
4717
  inspect: (name) => {
2536
- const history = timeline(name);
4718
+ const history2 = timeline(name);
2537
4719
  return {
2538
- branches: history.branches(),
2539
- checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
4720
+ branches: history2.branches(),
4721
+ checkpoints: history2.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2540
4722
  id,
2541
4723
  branch: branchName,
2542
4724
  parent,
@@ -2551,13 +4733,22 @@ var createRuntime = (options) => {
2551
4733
  } : {},
2552
4734
  routes: {
2553
4735
  ...credentialRoutes(credentials),
2554
- ...options.presets ? presetRoutes(options.presets, runtime) : {},
2555
4736
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2556
- ...options.admin?.(runtime) ?? {}
4737
+ ...options.admin?.(runtime) ?? {},
4738
+ // Shell routes win a colliding key. Fault presets are one of them: the admin page
4739
+ // maps `presets`, and a service route must not replace that list with a record.
4740
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
4741
+ ...stateAdminRoutes({
4742
+ open: stateScope,
4743
+ afterWrite: (namespace) => {
4744
+ checkpoint(namespace, "main");
4745
+ }
4746
+ }),
4747
+ ...adminUiRoutes(options.name, options.adminUi)
2557
4748
  },
2558
4749
  adminKey: options.adminKey
2559
4750
  });
2560
- return runtime;
4751
+ return defineMock(runtime);
2561
4752
  };
2562
4753
  var mutableResponse = (response) => {
2563
4754
  try {
@@ -2621,9 +4812,12 @@ var credentialRoutes = (registry) => ({
2621
4812
  }
2622
4813
  });
2623
4814
  var presetRoutes = (presets, runtime) => ({
2624
- "GET /faults/presets": () => adminJson(200, {
2625
- presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2626
- }),
4815
+ "GET /faults/presets": () => {
4816
+ const body = {
4817
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4818
+ };
4819
+ return adminJson(200, body);
4820
+ },
2627
4821
  "POST /faults/presets/:name": ({ params, body, namespace }) => {
2628
4822
  const name = params.name;
2629
4823
  if (!presets[name])
@@ -2634,7 +4828,7 @@ var presetRoutes = (presets, runtime) => ({
2634
4828
  });
2635
4829
 
2636
4830
  // src/generated/openapi.ts
2637
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Flex HSA/FSA payments API (Mockingbird subset)","description":"Stateful mock subset of the Flex (withflex.com) payments API: products, checkout sessions\\n(payment, subscription, off-session and setup modes), subscriptions, customers, setup\\nintents, refunds, and the hosted checkout page. Request and response bodies are wrapped in an envelope named after the\\nobject (\`{product: {...}}\`, \`{checkout_session: {...}}\`, \`{products: [...]}\`).\\nHand-authored from the consumer's wire shapes and the Flex API reference\\n(https://docs.withflex.com/api-reference); Flex publishes no machine-readable spec.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from the wire shapes our consumer reads and writes (flex-api.client.ts, flex-payment.types.ts, flex-product.types.ts, flex-webhook.service.ts, do-flex-hosted-checkout.ts). Subscription mode, recurring price_data and the Subscription object follow https://docs.withflex.com/api-reference/checkout-sessions/create-checkout-session, https://docs.withflex.com/api-reference/subscriptions/get-subscription and https://docs.withflex.com/api-reference/prices/create-price."}},"servers":[{"url":"https://api.withflex.com"}],"security":[{"bearerAuth":[]}],"paths":{"/v1/products":{"get":{"operationId":"ListProducts","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"starting_after","in":"query","required":false,"description":"The last product_id of the previous page.","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}}}],"responses":{"200":{"description":"A page of products, oldest first","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductList"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"CreateProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProductBody"}}}},"responses":{"200":{"description":"The created product","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}}},"/v1/products/{productId}":{"parameters":[{"name":"productId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}}}],"get":{"operationId":"GetProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The product","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}},"patch":{"operationId":"UpdateProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProductBody"}}}},"responses":{"200":{"description":"The updated product (emits product.updated)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions":{"get":{"operationId":"ListCheckoutSessions","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"client_reference_id","in":"query","required":false,"schema":{"type":"string","maxLength":255}},{"name":"expand_customer","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"expand_payment_intent","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"starting_after","in":"query","required":false,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"responses":{"200":{"description":"Sessions, newest first","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionList"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"CreateCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCheckoutSessionBody"}}}},"responses":{"200":{"description":"The created session. Off-session mode charges the saved payment method before answering, so the session is already complete (or its payment intent failed).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"},"500":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions/{sessionId}":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"get":{"operationId":"GetCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"expand_customer","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"expand_payment_intent","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}}],"responses":{"200":{"description":"The session","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions/{sessionId}/refund":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"post":{"operationId":"RefundCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RefundCheckoutSessionBody"}}}},"responses":{"200":{"description":"The session with amount_refunded updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"}}}},"/v1/customers":{"post":{"operationId":"CreateCustomer","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCustomerBody"}}}},"responses":{"200":{"description":"The created customer","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"}}}},"/v1/setup_intents/{setupIntentId}":{"parameters":[{"name":"setupIntentId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"setup_intent","missing":"fseti_00000000000000000000000000"}}}],"get":{"operationId":"GetSetupIntent","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"expand","in":"query","required":false,"description":"Comma-separated fields to expand (customer, payment_method).","schema":{"type":"string","enum":["customer","payment_method","customer,payment_method"]}}],"responses":{"200":{"description":"The setup intent","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SetupIntentEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/subscriptions/{subscriptionId}":{"parameters":[{"name":"subscriptionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"subscription","missing":"fsub_00000000000000000000000000"}}}],"get":{"operationId":"GetSubscription","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The subscription a completed subscription-mode checkout session created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubscriptionEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/pay/{sessionId}":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string"}}],"get":{"operationId":"HostedCheckoutPage","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":true,"reason":"A browser-facing HTML page; covered by the acceptance suite, not by JSON walks."}},"responses":{"200":{"description":"The card form (or the letter-of-medical-necessity step)","content":{"text/html":{"schema":{"type":"string"}}}},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}},"409":{"description":"The session is no longer payable","content":{"text/html":{"schema":{"type":"string"}}}}}},"post":{"operationId":"SubmitHostedCheckout","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":false,"reason":"A browser form post; covered by the acceptance suite."}},"requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"step":{"type":"string","enum":["card","lmn"]},"cardNumber":{"type":"string"},"expiry":{"type":"string"},"cvc":{"type":"string"},"postalCode":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"phone":{"type":"string"}}}}}},"responses":{"302":{"description":"Paid; redirects to success_url (or to the next action's page)"},"400":{"description":"The card form is incomplete or the card number is invalid","content":{"text/html":{"schema":{"type":"string"}}}},"402":{"description":"The card was declined","content":{"text/html":{"schema":{"type":"string"}}}},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}},"409":{"description":"The session is no longer payable","content":{"text/html":{"schema":{"type":"string"}}}}}}},"/pay/{sessionId}/cancel":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string"}}],"get":{"operationId":"CancelHostedCheckout","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":true,"reason":"A browser navigation to cancel_url; covered by the acceptance suite."}},"responses":{"302":{"description":"Redirects to cancel_url; the session stays open"},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","description":"A secret key, \`fsk_test_\u2026\` (test mode) or \`fsk_\u2026\` (live mode)."}},"responses":{"Error":{"description":"An error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}},"schemas":{"ErrorBody":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["type","message"],"properties":{"type":{"type":"string","enum":["invalid_request_error","authentication_error","idempotency_error","api_error","card_error"]},"code":{"type":"string"},"message":{"type":"string"},"param":{"type":"string"}}}}},"StringMap":{"type":"object","maxProperties":50,"additionalProperties":{"type":"string","maxLength":500}},"Product":{"type":"object","required":["product_id","name","active","test_mode","created_at"],"properties":{"product_id":{"type":"string","x-mockingbird-resource":{"type":"product","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"name":{"type":"string"},"description":{"type":["string","null"]},"url":{"type":["string","null"]},"client_reference_id":{"type":["string","null"]},"hsa_fsa_eligibility":{"description":"not_eligible, auto_substantiation, private_label, letter_of_medical_necessity, prescription, vision or service; null until Flex classifies a new product.","type":["string","null"]},"visit_type":{"type":["string","null"]},"active":{"type":"boolean"},"test_mode":{"type":"boolean"},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ProductEnvelope":{"type":"object","required":["product"],"properties":{"product":{"$ref":"#/components/schemas/Product"}}},"ProductList":{"type":"object","required":["products","has_more"],"properties":{"products":{"type":"array","items":{"$ref":"#/components/schemas/Product"}},"has_more":{"type":"boolean"}}},"CreateProductBody":{"type":"object","required":["product"],"properties":{"product":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":250},"description":{"type":"string","maxLength":1000},"url":{"type":"string","maxLength":2048},"client_reference_id":{"type":"string","minLength":1,"maxLength":255},"metadata":{"$ref":"#/components/schemas/StringMap"}}}}},"UpdateProductBody":{"type":"object","required":["product"],"properties":{"product":{"type":"object","properties":{"active":{"type":"boolean"},"name":{"type":"string","minLength":1,"maxLength":250},"description":{"type":"string","maxLength":1000},"url":{"type":"string","maxLength":2048},"metadata":{"$ref":"#/components/schemas/StringMap"}}}}},"LineItem":{"type":"object","required":["price_data","quantity"],"properties":{"price_data":{"type":"object","required":["product","unit_amount"],"properties":{"product":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}},"unit_amount":{"type":"integer","minimum":0,"maximum":10000000},"recurring":{"$ref":"#/components/schemas/Recurring"}}},"quantity":{"type":"integer","minimum":1,"maximum":100}}},"Recurring":{"type":"object","description":"Makes the line item's price recurring; a subscription-mode session needs at least one.","required":["interval"],"properties":{"interval":{"type":"string","enum":["day","week","month","year"]},"interval_count":{"type":"integer","minimum":1,"maximum":12}}},"SubscriptionData":{"type":"object","properties":{"cancel_at_period_end":{"type":"boolean"},"metadata":{"$ref":"#/components/schemas/StringMap"}}},"CreateCheckoutSessionBody":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"type":"object","required":["success_url","line_items"],"properties":{"allow_promotion_codes":{"type":"boolean"},"capture_method":{"type":"string","enum":["automatic"]},"cancel_url":{"type":"string","minLength":1,"maxLength":2048},"success_url":{"type":"string","minLength":1,"maxLength":2048},"client_reference_id":{"type":"string","minLength":1,"maxLength":255},"line_items":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/LineItem"}},"metadata":{"$ref":"#/components/schemas/StringMap"},"mode":{"type":"string","enum":["payment","subscription","off_session","setup"]},"subscription_data":{"$ref":"#/components/schemas/SubscriptionData"},"payment_method":{"type":"string","maxLength":255},"customer":{"type":"string","x-mockingbird-resource-ref":{"type":"customer","missing":"fcus_00000000000000000000000000"}},"setup_future_use":{"type":"string","enum":["off_session"]}}}}},"RefundCheckoutSessionBody":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"type":"object","properties":{"amount":{"type":"integer","minimum":1,"maximum":10000000}}}}},"CreateCustomerBody":{"type":"object","required":["customer"],"properties":{"customer":{"type":"object","required":["first_name","last_name","email","phone"],"properties":{"first_name":{"type":"string","minLength":1,"maxLength":100},"last_name":{"type":"string","minLength":1,"maxLength":100},"email":{"type":"string","format":"email","maxLength":254},"phone":{"type":"string","minLength":1,"maxLength":32}}}}},"Customer":{"type":"object","required":["customer_id","test_mode","created_at"],"properties":{"customer_id":{"type":"string","x-mockingbird-resource":{"type":"customer","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"first_name":{"type":["string","null"]},"last_name":{"type":["string","null"]},"email":{"type":["string","null"]},"phone":{"type":["string","null"]},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"CustomerEnvelope":{"type":"object","required":["customer"],"properties":{"customer":{"$ref":"#/components/schemas/Customer"}}},"PaymentMethod":{"type":"object","required":["payment_method_id","type"],"properties":{"payment_method_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string","enum":["card"]},"hsa_fsa":{"type":"boolean"},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}}}},"PaymentIntent":{"type":"object","required":["payment_intent_id","amount","status"],"properties":{"payment_intent_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"amount":{"type":"integer"},"amount_received":{"type":["integer","null"]},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"payment_method":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["requires_payment_method","requires_action","processing","succeeded","canceled"]},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SetupIntent":{"type":"object","required":["setup_intent_id","status"],"properties":{"setup_intent_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["requires_payment_method","requires_action","processing","succeeded","canceled"]},"customer":{"anyOf":[{"type":"string"},{"$ref":"#/components/schemas/Customer"},{"type":"null"}]},"payment_method":{"anyOf":[{"type":"string"},{"$ref":"#/components/schemas/PaymentMethod"},{"type":"null"}]},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SetupIntentEnvelope":{"type":"object","required":["setup_intent"],"properties":{"setup_intent":{"$ref":"#/components/schemas/SetupIntent"}}},"NextAction":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["collect_letter_of_medical_necessity","provide_second_payment_method","provide_alternative_payment_method","payment_failed"]},"collect_letter_of_medical_necessity":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"provide_second_payment_method":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"provide_alternative_payment_method":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"payment_failed":{"type":"object"}}},"ResponseLineItem":{"type":"object","required":["price_data","quantity","amount_total"],"properties":{"price_data":{"type":"object","required":["product","unit_amount"],"properties":{"product":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"unit_amount":{"type":"integer"},"recurring":{"anyOf":[{"$ref":"#/components/schemas/Recurring"},{"type":"null"}]}}},"quantity":{"type":"integer"},"amount_total":{"type":"integer"}}},"CheckoutSession":{"type":"object","required":["checkout_session_id","amount_total","status","mode","redirect_url","url","test_mode","created_at"],"properties":{"checkout_session_id":{"type":"string","x-mockingbird-resource":{"type":"checkout_session","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"client_reference_id":{"type":["string","null"]},"amount_total":{"type":"integer","minimum":0},"amount_received":{"type":["integer","null"]},"amount_refunded":{"type":"integer","minimum":0},"customer":{"anyOf":[{"type":"string","x-mockingbird-volatile":{"kind":"id"}},{"$ref":"#/components/schemas/Customer"},{"type":"null"}]},"payment_intent":{"anyOf":[{"type":"string","x-mockingbird-volatile":{"kind":"id"}},{"$ref":"#/components/schemas/PaymentIntent"},{"type":"null"}]},"setup_intent":{"type":["string","null"],"x-mockingbird-resource":{"type":"setup_intent","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"mode":{"type":"string","enum":["payment","subscription","off_session","setup"]},"subscription":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"subscription_data":{"anyOf":[{"$ref":"#/components/schemas/SubscriptionData"},{"type":"null"}]},"status":{"type":"string","enum":["open","paid","complete","canceled","expired"]},"redirect_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"success_url":{"type":"string"},"cancel_url":{"type":["string","null"]},"next_action":{"anyOf":[{"$ref":"#/components/schemas/NextAction"},{"type":"null"}]},"visit_type":{"type":["string","null"]},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"line_items":{"type":"array","items":{"$ref":"#/components/schemas/ResponseLineItem"}},"allow_promotion_codes":{"type":"boolean"},"capture_method":{"type":"string"},"setup_future_use":{"type":["string","null"]},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"expires_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"CheckoutSessionEnvelope":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"$ref":"#/components/schemas/CheckoutSession"}}},"CheckoutSessionList":{"type":"object","required":["checkout_sessions","has_more"],"properties":{"checkout_sessions":{"type":"array","items":{"$ref":"#/components/schemas/CheckoutSession"}},"has_more":{"type":"boolean"}}},"SubscriptionItem":{"type":"object","required":["price_data","quantity"],"properties":{"price_data":{"type":"object","required":["product","unit_amount","recurring"],"properties":{"product":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"unit_amount":{"type":"integer"},"recurring":{"$ref":"#/components/schemas/Recurring"}}},"quantity":{"type":"integer"}}},"Subscription":{"type":"object","required":["subscription_id","created_at","items","status","cancel_at_period_end","test_mode"],"properties":{"subscription_id":{"type":"string","x-mockingbird-resource":{"type":"subscription","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["incomplete","incomplete_expired","trialing","active","past_due","canceled","unpaid","paused"]},"items":{"type":"array","items":{"$ref":"#/components/schemas/SubscriptionItem"}},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"default_payment_method":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"cancel_at_period_end":{"type":"boolean"},"current_period_start":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"current_period_end":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"canceled_at":{"type":["string","null"]},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SubscriptionEnvelope":{"type":"object","required":["subscription"],"properties":{"subscription":{"$ref":"#/components/schemas/Subscription"}}}}}}`);
4831
+ var document2 = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Flex HSA/FSA payments API (Mockingbird subset)","description":"Stateful mock subset of the Flex (withflex.com) payments API: products, checkout sessions\\n(payment, subscription, off-session and setup modes), subscriptions, customers, setup\\nintents, refunds, and the hosted checkout page. Request and response bodies are wrapped in an envelope named after the\\nobject (\`{product: {...}}\`, \`{checkout_session: {...}}\`, \`{products: [...]}\`).\\nHand-authored from the consumer's wire shapes and the Flex API reference\\n(https://docs.withflex.com/api-reference); Flex publishes no machine-readable spec.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from the wire shapes our consumer reads and writes (flex-api.client.ts, flex-payment.types.ts, flex-product.types.ts, flex-webhook.service.ts, do-flex-hosted-checkout.ts). Subscription mode, recurring price_data and the Subscription object follow https://docs.withflex.com/api-reference/checkout-sessions/create-checkout-session, https://docs.withflex.com/api-reference/subscriptions/get-subscription and https://docs.withflex.com/api-reference/prices/create-price."}},"servers":[{"url":"https://api.withflex.com"}],"security":[{"bearerAuth":[]}],"paths":{"/v1/products":{"get":{"operationId":"ListProducts","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"starting_after","in":"query","required":false,"description":"The last product_id of the previous page.","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}}}],"responses":{"200":{"description":"A page of products, oldest first","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductList"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"CreateProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProductBody"}}}},"responses":{"200":{"description":"The created product","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}}},"/v1/products/{productId}":{"parameters":[{"name":"productId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}}}],"get":{"operationId":"GetProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The product","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}},"patch":{"operationId":"UpdateProduct","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProductBody"}}}},"responses":{"200":{"description":"The updated product (emits product.updated)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions":{"get":{"operationId":"ListCheckoutSessions","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"client_reference_id","in":"query","required":false,"schema":{"type":"string","maxLength":255}},{"name":"expand_customer","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"expand_payment_intent","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}},{"name":"starting_after","in":"query","required":false,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"responses":{"200":{"description":"Sessions, newest first","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionList"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"CreateCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCheckoutSessionBody"}}}},"responses":{"200":{"description":"The created session. Off-session mode charges the saved payment method before answering, so the session is already complete (or its payment intent failed).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"},"500":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions/{sessionId}":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"get":{"operationId":"GetCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"expand_customer","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}},{"name":"expand_payment_intent","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}}],"responses":{"200":{"description":"The session","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/checkout/sessions/{sessionId}/refund":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"checkout_session","missing":"fcs_00000000000000000000000000"}}}],"post":{"operationId":"RefundCheckoutSession","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RefundCheckoutSessionBody"}}}},"responses":{"200":{"description":"The session with amount_refunded updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckoutSessionEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"}}}},"/v1/customers":{"post":{"operationId":"CreateCustomer","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[A-Za-z0-9:_.-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCustomerBody"}}}},"responses":{"200":{"description":"The created customer","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerEnvelope"}}}},"400":{"$ref":"#/components/responses/Error"},"401":{"$ref":"#/components/responses/Error"},"409":{"$ref":"#/components/responses/Error"}}}},"/v1/setup_intents/{setupIntentId}":{"parameters":[{"name":"setupIntentId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"setup_intent","missing":"fseti_00000000000000000000000000"}}}],"get":{"operationId":"GetSetupIntent","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"expand","in":"query","required":false,"description":"Comma-separated fields to expand (customer, payment_method).","schema":{"type":"string","enum":["customer","payment_method","customer,payment_method"]}}],"responses":{"200":{"description":"The setup intent","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SetupIntentEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/v1/subscriptions/{subscriptionId}":{"parameters":[{"name":"subscriptionId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"subscription","missing":"fsub_00000000000000000000000000"}}}],"get":{"operationId":"GetSubscription","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The subscription a completed subscription-mode checkout session created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubscriptionEnvelope"}}}},"401":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}}},"/pay/{sessionId}":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string"}}],"get":{"operationId":"HostedCheckoutPage","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":true,"reason":"A browser-facing HTML page; covered by the acceptance suite, not by JSON walks."}},"responses":{"200":{"description":"The card form (or the letter-of-medical-necessity step)","content":{"text/html":{"schema":{"type":"string"}}}},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}},"409":{"description":"The session is no longer payable","content":{"text/html":{"schema":{"type":"string"}}}}}},"post":{"operationId":"SubmitHostedCheckout","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":false,"reason":"A browser form post; covered by the acceptance suite."}},"requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"step":{"type":"string","enum":["card","lmn"]},"cardNumber":{"type":"string"},"expiry":{"type":"string"},"cvc":{"type":"string"},"postalCode":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"phone":{"type":"string"}}}}}},"responses":{"302":{"description":"Paid; redirects to success_url (or to the next action's page)"},"400":{"description":"The card form is incomplete or the card number is invalid","content":{"text/html":{"schema":{"type":"string"}}}},"402":{"description":"The card was declined","content":{"text/html":{"schema":{"type":"string"}}}},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}},"409":{"description":"The session is no longer payable","content":{"text/html":{"schema":{"type":"string"}}}}}}},"/pay/{sessionId}/cancel":{"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string"}}],"get":{"operationId":"CancelHostedCheckout","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"safe":true,"reason":"A browser navigation to cancel_url; covered by the acceptance suite."}},"responses":{"302":{"description":"Redirects to cancel_url; the session stays open"},"404":{"description":"Unknown session","content":{"text/html":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","description":"A secret key, \`fsk_test_\u2026\` (test mode) or \`fsk_\u2026\` (live mode)."}},"responses":{"Error":{"description":"An error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}},"schemas":{"ErrorBody":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["type","message"],"properties":{"type":{"type":"string","enum":["invalid_request_error","authentication_error","idempotency_error","api_error","card_error"]},"code":{"type":"string"},"message":{"type":"string"},"param":{"type":"string"}}}}},"StringMap":{"type":"object","maxProperties":50,"additionalProperties":{"type":"string","maxLength":500}},"Product":{"type":"object","required":["product_id","name","active","test_mode","created_at"],"properties":{"product_id":{"type":"string","x-mockingbird-resource":{"type":"product","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"name":{"type":"string"},"description":{"type":["string","null"]},"url":{"type":["string","null"]},"client_reference_id":{"type":["string","null"]},"hsa_fsa_eligibility":{"description":"not_eligible, auto_substantiation, private_label, letter_of_medical_necessity, prescription, vision or service; null until Flex classifies a new product.","type":["string","null"]},"visit_type":{"type":["string","null"]},"active":{"type":"boolean"},"test_mode":{"type":"boolean"},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ProductEnvelope":{"type":"object","required":["product"],"properties":{"product":{"$ref":"#/components/schemas/Product"}}},"ProductList":{"type":"object","required":["products","has_more"],"properties":{"products":{"type":"array","items":{"$ref":"#/components/schemas/Product"}},"has_more":{"type":"boolean"}}},"CreateProductBody":{"type":"object","required":["product"],"properties":{"product":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":250},"description":{"type":"string","maxLength":1000},"url":{"type":"string","maxLength":2048},"client_reference_id":{"type":"string","minLength":1,"maxLength":255},"metadata":{"$ref":"#/components/schemas/StringMap"}}}}},"UpdateProductBody":{"type":"object","required":["product"],"properties":{"product":{"type":"object","properties":{"active":{"type":"boolean"},"name":{"type":"string","minLength":1,"maxLength":250},"description":{"type":"string","maxLength":1000},"url":{"type":"string","maxLength":2048},"metadata":{"$ref":"#/components/schemas/StringMap"}}}}},"LineItem":{"type":"object","required":["price_data","quantity"],"properties":{"price_data":{"type":"object","required":["product","unit_amount"],"properties":{"product":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":"fprod_00000000000000000000000000"}},"unit_amount":{"type":"integer","minimum":0,"maximum":10000000},"recurring":{"$ref":"#/components/schemas/Recurring"}}},"quantity":{"type":"integer","minimum":1,"maximum":100}}},"Recurring":{"type":"object","description":"Makes the line item's price recurring; a subscription-mode session needs at least one.","required":["interval"],"properties":{"interval":{"type":"string","enum":["day","week","month","year"]},"interval_count":{"type":"integer","minimum":1,"maximum":12}}},"SubscriptionData":{"type":"object","properties":{"cancel_at_period_end":{"type":"boolean"},"metadata":{"$ref":"#/components/schemas/StringMap"}}},"CreateCheckoutSessionBody":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"type":"object","required":["success_url","line_items"],"properties":{"allow_promotion_codes":{"type":"boolean"},"capture_method":{"type":"string","enum":["automatic"]},"cancel_url":{"type":"string","minLength":1,"maxLength":2048},"success_url":{"type":"string","minLength":1,"maxLength":2048},"client_reference_id":{"type":"string","minLength":1,"maxLength":255},"line_items":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/LineItem"}},"metadata":{"$ref":"#/components/schemas/StringMap"},"mode":{"type":"string","enum":["payment","subscription","off_session","setup"]},"subscription_data":{"$ref":"#/components/schemas/SubscriptionData"},"payment_method":{"type":"string","maxLength":255},"customer":{"type":"string","x-mockingbird-resource-ref":{"type":"customer","missing":"fcus_00000000000000000000000000"}},"setup_future_use":{"type":"string","enum":["off_session"]}}}}},"RefundCheckoutSessionBody":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"type":"object","properties":{"amount":{"type":"integer","minimum":1,"maximum":10000000}}}}},"CreateCustomerBody":{"type":"object","required":["customer"],"properties":{"customer":{"type":"object","required":["first_name","last_name","email","phone"],"properties":{"first_name":{"type":"string","minLength":1,"maxLength":100},"last_name":{"type":"string","minLength":1,"maxLength":100},"email":{"type":"string","format":"email","maxLength":254},"phone":{"type":"string","minLength":1,"maxLength":32}}}}},"Customer":{"type":"object","required":["customer_id","test_mode","created_at"],"properties":{"customer_id":{"type":"string","x-mockingbird-resource":{"type":"customer","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"first_name":{"type":["string","null"]},"last_name":{"type":["string","null"]},"email":{"type":["string","null"]},"phone":{"type":["string","null"]},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"CustomerEnvelope":{"type":"object","required":["customer"],"properties":{"customer":{"$ref":"#/components/schemas/Customer"}}},"PaymentMethod":{"type":"object","required":["payment_method_id","type"],"properties":{"payment_method_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string","enum":["card"]},"hsa_fsa":{"type":"boolean"},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}}}},"PaymentIntent":{"type":"object","required":["payment_intent_id","amount","status"],"properties":{"payment_intent_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"amount":{"type":"integer"},"amount_received":{"type":["integer","null"]},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"payment_method":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["requires_payment_method","requires_action","processing","succeeded","canceled"]},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SetupIntent":{"type":"object","required":["setup_intent_id","status"],"properties":{"setup_intent_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["requires_payment_method","requires_action","processing","succeeded","canceled"]},"customer":{"anyOf":[{"type":"string"},{"$ref":"#/components/schemas/Customer"},{"type":"null"}]},"payment_method":{"anyOf":[{"type":"string"},{"$ref":"#/components/schemas/PaymentMethod"},{"type":"null"}]},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SetupIntentEnvelope":{"type":"object","required":["setup_intent"],"properties":{"setup_intent":{"$ref":"#/components/schemas/SetupIntent"}}},"NextAction":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["collect_letter_of_medical_necessity","provide_second_payment_method","provide_alternative_payment_method","payment_failed"]},"collect_letter_of_medical_necessity":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"provide_second_payment_method":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"provide_alternative_payment_method":{"type":"object","required":["url"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"payment_failed":{"type":"object"}}},"ResponseLineItem":{"type":"object","required":["price_data","quantity","amount_total"],"properties":{"price_data":{"type":"object","required":["product","unit_amount"],"properties":{"product":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"unit_amount":{"type":"integer"},"recurring":{"anyOf":[{"$ref":"#/components/schemas/Recurring"},{"type":"null"}]}}},"quantity":{"type":"integer"},"amount_total":{"type":"integer"}}},"CheckoutSession":{"type":"object","required":["checkout_session_id","amount_total","status","mode","redirect_url","url","test_mode","created_at"],"properties":{"checkout_session_id":{"type":"string","x-mockingbird-resource":{"type":"checkout_session","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"client_reference_id":{"type":["string","null"]},"amount_total":{"type":"integer","minimum":0},"amount_received":{"type":["integer","null"]},"amount_refunded":{"type":"integer","minimum":0},"customer":{"anyOf":[{"type":"string","x-mockingbird-volatile":{"kind":"id"}},{"$ref":"#/components/schemas/Customer"},{"type":"null"}]},"payment_intent":{"anyOf":[{"type":"string","x-mockingbird-volatile":{"kind":"id"}},{"$ref":"#/components/schemas/PaymentIntent"},{"type":"null"}]},"setup_intent":{"type":["string","null"],"x-mockingbird-resource":{"type":"setup_intent","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"mode":{"type":"string","enum":["payment","subscription","off_session","setup"]},"subscription":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"subscription_data":{"anyOf":[{"$ref":"#/components/schemas/SubscriptionData"},{"type":"null"}]},"status":{"type":"string","enum":["open","paid","complete","canceled","expired"]},"redirect_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"success_url":{"type":"string"},"cancel_url":{"type":["string","null"]},"next_action":{"anyOf":[{"$ref":"#/components/schemas/NextAction"},{"type":"null"}]},"visit_type":{"type":["string","null"]},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"line_items":{"type":"array","items":{"$ref":"#/components/schemas/ResponseLineItem"}},"allow_promotion_codes":{"type":"boolean"},"capture_method":{"type":"string"},"setup_future_use":{"type":["string","null"]},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"expires_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"CheckoutSessionEnvelope":{"type":"object","required":["checkout_session"],"properties":{"checkout_session":{"$ref":"#/components/schemas/CheckoutSession"}}},"CheckoutSessionList":{"type":"object","required":["checkout_sessions","has_more"],"properties":{"checkout_sessions":{"type":"array","items":{"$ref":"#/components/schemas/CheckoutSession"}},"has_more":{"type":"boolean"}}},"SubscriptionItem":{"type":"object","required":["price_data","quantity"],"properties":{"price_data":{"type":"object","required":["product","unit_amount","recurring"],"properties":{"product":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"unit_amount":{"type":"integer"},"recurring":{"$ref":"#/components/schemas/Recurring"}}},"quantity":{"type":"integer"}}},"Subscription":{"type":"object","required":["subscription_id","created_at","items","status","cancel_at_period_end","test_mode"],"properties":{"subscription_id":{"type":"string","x-mockingbird-resource":{"type":"subscription","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["incomplete","incomplete_expired","trialing","active","past_due","canceled","unpaid","paused"]},"items":{"type":"array","items":{"$ref":"#/components/schemas/SubscriptionItem"}},"customer":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"default_payment_method":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"id"}},"cancel_at_period_end":{"type":"boolean"},"current_period_start":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"current_period_end":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"canceled_at":{"type":["string","null"]},"metadata":{"type":["object","null"],"additionalProperties":{"type":"string"}},"test_mode":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SubscriptionEnvelope":{"type":"object","required":["subscription"],"properties":{"subscription":{"$ref":"#/components/schemas/Subscription"}}}}}}`);
2638
4832
  var operationIds = ["ListProducts", "CreateProduct", "GetProduct", "UpdateProduct", "ListCheckoutSessions", "CreateCheckoutSession", "GetCheckoutSession", "RefundCheckoutSession", "CreateCustomer", "GetSetupIntent", "GetSubscription", "HostedCheckoutPage", "SubmitHostedCheckout", "CancelHostedCheckout"];
2639
4833
  var supportedOperationIds = ["ListProducts", "CreateProduct", "GetProduct", "UpdateProduct", "ListCheckoutSessions", "CreateCheckoutSession", "GetCheckoutSession", "RefundCheckoutSession", "CreateCustomer", "GetSetupIntent", "GetSubscription", "HostedCheckoutPage", "SubmitHostedCheckout", "CancelHostedCheckout"];
2640
4834
 
@@ -2675,19 +4869,23 @@ var classifyCard = (form) => {
2675
4869
  return { kind: "approve", hsa: number === CARDS.hsa };
2676
4870
  };
2677
4871
  var substituteSessionId = (url, sessionId) => url.replaceAll("{CHECKOUT_SESSION_ID}", sessionId).replace(/%7BCHECKOUT_SESSION_ID%7D/gi, sessionId);
2678
- var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4872
+ var escapeHtml2 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2679
4873
  var dollars = (cents) => `$${(cents / 100).toFixed(2)}`;
2680
4874
  var layout = (title, body) => `<!doctype html>
2681
4875
  <html lang="en">
2682
4876
  <head>
2683
4877
  <meta charset="utf-8">
2684
4878
  <meta name="viewport" content="width=device-width, initial-scale=1">
2685
- <title>${escapeHtml(title)}</title>
4879
+ <title>${escapeHtml2(title)}</title>
2686
4880
  <style>
2687
- body{font-family:system-ui,sans-serif;max-width:28rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a}
4881
+ ${CSS_RESET}
4882
+ body{font-family:system-ui,sans-serif;max-width:28rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a;background:#fff}
4883
+ h1{font-size:1.5rem;font-weight:650;margin:0 0 .75rem}
4884
+ p{margin:0 0 .75rem}
4885
+ ul{list-style:disc;padding-left:1.25rem}
2688
4886
  label{display:block;margin:.75rem 0 .25rem;font-size:.9rem}
2689
- input{width:100%;box-sizing:border-box;padding:.5rem;font-size:1rem}
2690
- button{margin-top:1rem;width:100%;padding:.75rem;font-size:1rem}
4887
+ input{width:100%;padding:.5rem;font-size:1rem;border:1px solid #c8c8c8;border-radius:6px;background:#fff}
4888
+ button{margin-top:1rem;width:100%;padding:.75rem;font-size:1rem;background:#1a1a1a;color:#fff;border-radius:6px}
2691
4889
  [role=alert]{color:#b00020;margin:1rem 0}
2692
4890
  .row{display:flex;gap:.5rem}.row>div{flex:1}
2693
4891
  </style>
@@ -2697,20 +4895,20 @@ ${body}
2697
4895
  </body>
2698
4896
  </html>
2699
4897
  `;
2700
- var alert = (error2) => error2 ? `<div role="alert" data-testid="flex-mock-error">${escapeHtml(error2)}</div>` : "";
4898
+ var alert = (error2) => error2 ? `<div role="alert" data-testid="flex-mock-error">${escapeHtml2(error2)}</div>` : "";
2701
4899
  var cancelLink = (session) => session.cancel_url ? `<p><a data-testid="flex-mock-cancel" href="./${encodeURIComponent(session.checkout_session_id)}/cancel">Cancel and return</a></p>` : "";
2702
4900
  var cadence = (session) => {
2703
4901
  const recurring = session.line_items.find((item) => item.price_data.recurring)?.price_data.recurring;
2704
4902
  if (!recurring) return "";
2705
4903
  const count = recurring.interval_count ?? 1;
2706
4904
  const every = count === 1 ? recurring.interval : `${count} ${recurring.interval}s`;
2707
- return ` <span data-testid="flex-mock-interval">per ${escapeHtml(every)}</span>`;
4905
+ return ` <span data-testid="flex-mock-interval">per ${escapeHtml2(every)}</span>`;
2708
4906
  };
2709
4907
  var summary = (input) => {
2710
4908
  const { session } = input;
2711
- const items = input.productNames.map((name) => `<li data-testid="flex-mock-line-item">${escapeHtml(name)}</li>`).join("");
4909
+ const items = input.productNames.map((name) => `<li data-testid="flex-mock-line-item">${escapeHtml2(name)}</li>`).join("");
2712
4910
  return `<h1>${session.mode === "subscription" ? "Subscribe with HSA/FSA" : "Pay with HSA/FSA"}</h1>
2713
- <p data-testid="flex-mock-session" data-session-id="${escapeHtml(session.checkout_session_id)}" data-mode="${escapeHtml(session.mode)}">
4911
+ <p data-testid="flex-mock-session" data-session-id="${escapeHtml2(session.checkout_session_id)}" data-mode="${escapeHtml2(session.mode)}">
2714
4912
  ${session.mode === "setup" ? "Save a card for future payments" : `Total <strong data-testid="flex-mock-amount">${dollars(session.amount_total)}</strong>${session.mode === "subscription" ? cadence(session) : ""}`}
2715
4913
  </p>
2716
4914
  ${items ? `<ul>${items}</ul>` : ""}`;
@@ -2766,8 +4964,8 @@ ${cancelLink(input.session)}`
2766
4964
  };
2767
4965
  var closedPage = (session) => layout(
2768
4966
  "Flex checkout (Mockingbird)",
2769
- `<h1>This checkout is ${escapeHtml(session.status)}</h1>
2770
- <p data-testid="flex-mock-closed" data-status="${escapeHtml(session.status)}">Nothing more to pay here.</p>`
4967
+ `<h1>This checkout is ${escapeHtml2(session.status)}</h1>
4968
+ <p data-testid="flex-mock-closed" data-status="${escapeHtml2(session.status)}">Nothing more to pay here.</p>`
2771
4969
  );
2772
4970
  var notFoundPage = () => layout(
2773
4971
  "Flex checkout (Mockingbird)",
@@ -3652,11 +5850,11 @@ var FLEX_PRESETS = {
3652
5850
  webhook: { mode: "drop" }
3653
5851
  }
3654
5852
  };
3655
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3656
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
3657
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5853
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5854
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
5855
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3658
5856
  var parseSettings = (body) => {
3659
- if (!isRecord4(body)) return "expected a JSON object";
5857
+ if (!isRecord6(body)) return "expected a JSON object";
3660
5858
  const patch = {};
3661
5859
  if (body.eventNaming !== void 0) {
3662
5860
  if (body.eventNaming !== "dotted" && body.eventNaming !== "underscored") {
@@ -3689,19 +5887,19 @@ var parseSettings = (body) => {
3689
5887
  };
3690
5888
  var adminRoutes = (runtime) => {
3691
5889
  const session = (namespace, id) => runtime.instance(namespace).state.sessions.get(id);
3692
- const found = (value, what) => value ? json3(200, value) : adminError3(404, `no ${what}`);
5890
+ const found = (value, what) => value ? json5(200, value) : adminError4(404, `no ${what}`);
3693
5891
  const notOpen = (namespace, id) => {
3694
5892
  const current = session(namespace, id);
3695
- if (!current) return adminError3(404, `no session ${id}`);
3696
- return current.status === "open" ? void 0 : adminError3(409, `session ${id} is ${current.status}, not open`);
5893
+ if (!current) return adminError4(404, `no session ${id}`);
5894
+ return current.status === "open" ? void 0 : adminError4(409, `session ${id} is ${current.status}, not open`);
3697
5895
  };
3698
5896
  return {
3699
- "GET /sessions": ({ namespace }) => json3(200, { sessions: runtime.instance(namespace).sessions() }),
5897
+ "GET /sessions": ({ namespace }) => json5(200, { sessions: runtime.instance(namespace).sessions() }),
3700
5898
  "GET /sessions/:id": ({ namespace, params }) => found(session(namespace, params.id), `session ${params.id}`),
3701
5899
  "POST /sessions/:id/complete": ({ namespace, params, body }) => {
3702
5900
  const closed = notOpen(namespace, params.id);
3703
5901
  if (closed) return closed;
3704
- const hsa = !(isRecord4(body) && body.card === "4242424242424242");
5902
+ const hsa = !(isRecord6(body) && body.card === "4242424242424242");
3705
5903
  return found(
3706
5904
  runtime.instance(namespace).settle(params.id, { hsa }),
3707
5905
  `session ${params.id}`
@@ -3712,9 +5910,9 @@ var adminRoutes = (runtime) => {
3712
5910
  "POST /sessions/:id/require_action": ({ namespace, params, body }) => {
3713
5911
  const closed = notOpen(namespace, params.id);
3714
5912
  if (closed) return closed;
3715
- const type = isRecord4(body) ? body.next_action_type : void 0;
5913
+ const type = isRecord6(body) ? body.next_action_type : void 0;
3716
5914
  if (type !== void 0 && !isNextActionType(type)) {
3717
- return adminError3(
5915
+ return adminError4(
3718
5916
  400,
3719
5917
  "next_action_type: collect_letter_of_medical_necessity | provide_second_payment_method | provide_alternative_payment_method | payment_failed"
3720
5918
  );
@@ -3725,8 +5923,8 @@ var adminRoutes = (runtime) => {
3725
5923
  );
3726
5924
  },
3727
5925
  "PUT /sessions/:id/payment-intent": ({ namespace, params, body }) => {
3728
- if (!isRecord4(body) || !PAYMENT_INTENT_STATUSES.includes(String(body.status))) {
3729
- return adminError3(400, `status: ${PAYMENT_INTENT_STATUSES.join(" | ")}`);
5926
+ if (!isRecord6(body) || !PAYMENT_INTENT_STATUSES.includes(String(body.status))) {
5927
+ return adminError4(400, `status: ${PAYMENT_INTENT_STATUSES.join(" | ")}`);
3730
5928
  }
3731
5929
  const api = runtime.instance(namespace);
3732
5930
  const intent = api.setPaymentIntent(params.id, {
@@ -3736,52 +5934,52 @@ var adminRoutes = (runtime) => {
3736
5934
  return found(intent, `session ${params.id}`);
3737
5935
  },
3738
5936
  "PUT /products/:id": ({ namespace, params, body }) => {
3739
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
5937
+ if (!isRecord6(body)) return adminError4(400, "expected a JSON object");
3740
5938
  const api = runtime.instance(namespace);
3741
5939
  const product = api.state.products.get(params.id);
3742
- if (!product) return adminError3(404, `no product ${params.id}`);
5940
+ if (!product) return adminError4(404, `no product ${params.id}`);
3743
5941
  const next = { ...product };
3744
5942
  for (const key of ["hsa_fsa_eligibility", "visit_type", "client_reference_id"]) {
3745
5943
  const value = body[key];
3746
5944
  if (value === void 0) continue;
3747
5945
  if (value !== null && typeof value !== "string")
3748
- return adminError3(400, `${key}: string | null`);
5946
+ return adminError4(400, `${key}: string | null`);
3749
5947
  next[key] = value;
3750
5948
  }
3751
5949
  for (const key of ["active", "test_mode"]) {
3752
5950
  const value = body[key];
3753
5951
  if (value === void 0) continue;
3754
- if (typeof value !== "boolean") return adminError3(400, `${key}: boolean`);
5952
+ if (typeof value !== "boolean") return adminError4(400, `${key}: boolean`);
3755
5953
  next[key] = value;
3756
5954
  }
3757
5955
  if (body.name !== void 0) {
3758
- if (typeof body.name !== "string") return adminError3(400, "name: string");
5956
+ if (typeof body.name !== "string") return adminError4(400, "name: string");
3759
5957
  next.name = body.name;
3760
5958
  }
3761
5959
  if (body.metadata !== void 0) {
3762
- if (body.metadata !== null && !isRecord4(body.metadata))
3763
- return adminError3(400, "metadata: object | null");
5960
+ if (body.metadata !== null && !isRecord6(body.metadata))
5961
+ return adminError4(400, "metadata: object | null");
3764
5962
  next.metadata = body.metadata;
3765
5963
  }
3766
- return json3(200, api.putProduct(next));
5964
+ return json5(200, api.putProduct(next));
3767
5965
  },
3768
5966
  "POST /events": ({ namespace, body }) => {
3769
- if (!isRecord4(body) || typeof body.type !== "string") {
3770
- return adminError3(400, 'expected {"type": "<event type>", "session"?: id, "product"?: id}');
5967
+ if (!isRecord6(body) || typeof body.type !== "string") {
5968
+ return adminError4(400, 'expected {"type": "<event type>", "session"?: id, "product"?: id}');
3771
5969
  }
3772
5970
  const event = runtime.instance(namespace).emitFor(body.type, {
3773
5971
  ...typeof body.session === "string" ? { sessionId: body.session } : {},
3774
5972
  ...typeof body.product === "string" ? { productId: body.product } : {}
3775
5973
  });
3776
- return event ? json3(201, event) : adminError3(404, "no such session or product");
5974
+ return event ? json5(201, event) : adminError4(404, "no such session or product");
3777
5975
  },
3778
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
5976
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
3779
5977
  "PUT /settings": ({ body, namespace }) => {
3780
5978
  const patch = parseSettings(body);
3781
- if (typeof patch === "string") return adminError3(400, patch);
3782
- return json3(200, runtime.instance(namespace).state.update(patch));
5979
+ if (typeof patch === "string") return adminError4(400, patch);
5980
+ return json5(200, runtime.instance(namespace).state.update(patch));
3783
5981
  },
3784
- "POST /tick": ({ namespace }) => json3(200, { expired: runtime.instance(namespace).tick() })
5982
+ "POST /tick": ({ namespace }) => json5(200, { expired: runtime.instance(namespace).tick() })
3785
5983
  };
3786
5984
  };
3787
5985
  var createRuntime2 = (options = {}) => {
@@ -3799,7 +5997,7 @@ var createRuntime2 = (options = {}) => {
3799
5997
  });
3800
5998
  const runtime = createRuntime({
3801
5999
  name: FLEX_NAMESPACE,
3802
- document,
6000
+ document: document2,
3803
6001
  ...options.sqlite ? { sqlite: options.sqlite } : {},
3804
6002
  ...options.clock ? { clock: options.clock } : {},
3805
6003
  ...options.seed !== void 0 ? { seed: options.seed } : {},
@@ -3870,11 +6068,11 @@ var keyMode = (key) => {
3870
6068
  var HOSTED = /* @__PURE__ */ new Set(["HostedCheckoutPage", "SubmitHostedCheckout", "CancelHostedCheckout"]);
3871
6069
  var error = (status, type, message, extra = {}) => jsonRes(status, { error: { type, message, ...extra } });
3872
6070
  var invalid = (message, param) => error(400, "invalid_request_error", message, param ? { param } : {});
3873
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6071
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3874
6072
  var envelope = (context, name) => {
3875
6073
  const body = context.body.kind === "json" ? context.body.value : void 0;
3876
- const inner = isRecord5(body) ? body[name] : void 0;
3877
- return isRecord5(inner) ? inner : {};
6074
+ const inner = isRecord7(body) ? body[name] : void 0;
6075
+ return isRecord7(inner) ? inner : {};
3878
6076
  };
3879
6077
  var flag = (value) => value === "true";
3880
6078
  var sleep = (ms, signal) => new Promise((resolve) => {
@@ -3942,7 +6140,7 @@ var FlexAPI = class {
3942
6140
  CancelHostedCheckout: (context) => this.cancelHosted(context)
3943
6141
  });
3944
6142
  this.service = createService({
3945
- document,
6143
+ document: document2,
3946
6144
  handlers,
3947
6145
  sqlite,
3948
6146
  namespace,
@@ -4044,7 +6242,7 @@ var FlexAPI = class {
4044
6242
  visit_type: null,
4045
6243
  active: true,
4046
6244
  test_mode: this.testMode(context),
4047
- metadata: isRecord5(input.metadata) ? input.metadata : null,
6245
+ metadata: isRecord7(input.metadata) ? input.metadata : null,
4048
6246
  created_at: this.iso()
4049
6247
  };
4050
6248
  this.state.products.put(product);
@@ -4069,7 +6267,7 @@ var FlexAPI = class {
4069
6267
  ...typeof input.name === "string" ? { name: input.name } : {},
4070
6268
  ...typeof input.description === "string" ? { description: input.description } : {},
4071
6269
  ...typeof input.url === "string" ? { url: input.url } : {},
4072
- ...isRecord5(input.metadata) ? { metadata: input.metadata } : {}
6270
+ ...isRecord7(input.metadata) ? { metadata: input.metadata } : {}
4073
6271
  };
4074
6272
  this.putProduct(next);
4075
6273
  return annotateResponse(jsonRes(200, { product: next }), {
@@ -4201,7 +6399,7 @@ var FlexAPI = class {
4201
6399
  payment_intent: null,
4202
6400
  setup_intent: setupIntent,
4203
6401
  subscription: null,
4204
- subscription_data: mode === "subscription" ? isRecord5(input.subscription_data) ? input.subscription_data : {} : null,
6402
+ subscription_data: mode === "subscription" ? isRecord7(input.subscription_data) ? input.subscription_data : {} : null,
4205
6403
  mode,
4206
6404
  status: "open",
4207
6405
  url: `${this.pageBase(context)}/pay/${encodeURIComponent(id)}`,
@@ -4209,7 +6407,7 @@ var FlexAPI = class {
4209
6407
  cancel_url: typeof input.cancel_url === "string" ? input.cancel_url : null,
4210
6408
  next_action: null,
4211
6409
  visit_type: products.map((p) => p.visit_type).find((v) => v && v !== "notApplicable") ?? products[0]?.visit_type ?? null,
4212
- metadata: isRecord5(input.metadata) ? input.metadata : null,
6410
+ metadata: isRecord7(input.metadata) ? input.metadata : null,
4213
6411
  line_items: items,
4214
6412
  allow_promotion_codes: input.allow_promotion_codes === true,
4215
6413
  capture_method: typeof input.capture_method === "string" ? input.capture_method : "automatic",
@@ -4711,7 +6909,7 @@ var FlexAPI = class {
4711
6909
  var isNextActionType = (value) => typeof value === "string" && NEXT_ACTION_TYPES.includes(value);
4712
6910
 
4713
6911
  export {
4714
- document,
6912
+ document2 as document,
4715
6913
  operationIds,
4716
6914
  supportedOperationIds,
4717
6915
  CARDS,
@@ -4733,4 +6931,4 @@ export {
4733
6931
  FlexAPI,
4734
6932
  isNextActionType
4735
6933
  };
4736
- //# sourceMappingURL=chunk-UQWTCFIV.js.map
6934
+ //# sourceMappingURL=chunk-MGSS74P5.js.map