@valbuild/shared 0.122.0 → 0.123.2

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.
@@ -3,125 +3,21 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@valbuild/core');
6
- var utils = require('../../dist/utils-d3d8b4b5.cjs.dev.js');
6
+ var getSitemapTree = require('../../dist/getSitemapTree-a0c9a0e3.cjs.dev.js');
7
7
  var zod = require('zod');
8
8
  var zodValidationError = require('zod-validation-error');
9
+ var FlexSearch = require('flexsearch');
10
+ var utils = require('../../dist/utils-d3d8b4b5.cjs.dev.js');
9
11
 
10
- function _toPrimitive(t, r) {
11
- if ("object" != typeof t || !t) return t;
12
- var e = t[Symbol.toPrimitive];
13
- if (void 0 !== e) {
14
- var i = e.call(t, r || "default");
15
- if ("object" != typeof i) return i;
16
- throw new TypeError("@@toPrimitive must return a primitive value.");
17
- }
18
- return ("string" === r ? String : Number)(t);
19
- }
20
-
21
- function _toPropertyKey(t) {
22
- var i = _toPrimitive(t, "string");
23
- return "symbol" == typeof i ? i : i + "";
24
- }
25
-
26
- function _defineProperty(e, r, t) {
27
- return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
28
- value: t,
29
- enumerable: !0,
30
- configurable: !0,
31
- writable: !0
32
- }) : e[r] = t, e;
33
- }
34
-
35
- function ownKeys(e, r) {
36
- var t = Object.keys(e);
37
- if (Object.getOwnPropertySymbols) {
38
- var o = Object.getOwnPropertySymbols(e);
39
- r && (o = o.filter(function (r) {
40
- return Object.getOwnPropertyDescriptor(e, r).enumerable;
41
- })), t.push.apply(t, o);
42
- }
43
- return t;
44
- }
45
- function _objectSpread2(e) {
46
- for (var r = 1; r < arguments.length; r++) {
47
- var t = null != arguments[r] ? arguments[r] : {};
48
- r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
49
- _defineProperty(e, r, t[r]);
50
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
51
- Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
52
- });
53
- }
54
- return e;
55
- }
56
-
57
- function _arrayLikeToArray(r, a) {
58
- (null == a || a > r.length) && (a = r.length);
59
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
60
- return n;
61
- }
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
62
13
 
63
- function _unsupportedIterableToArray(r, a) {
64
- if (r) {
65
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
66
- var t = {}.toString.call(r).slice(8, -1);
67
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
68
- }
69
- }
70
-
71
- function _createForOfIteratorHelper(r, e) {
72
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
73
- if (!t) {
74
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
75
- t && (r = t);
76
- var n = 0,
77
- F = function () {};
78
- return {
79
- s: F,
80
- n: function () {
81
- return n >= r.length ? {
82
- done: !0
83
- } : {
84
- done: !1,
85
- value: r[n++]
86
- };
87
- },
88
- e: function (r) {
89
- throw r;
90
- },
91
- f: F
92
- };
93
- }
94
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
95
- }
96
- var o,
97
- a = !0,
98
- u = !1;
99
- return {
100
- s: function () {
101
- t = t.call(r);
102
- },
103
- n: function () {
104
- var r = t.next();
105
- return a = r.done, r;
106
- },
107
- e: function (r) {
108
- u = !0, o = r;
109
- },
110
- f: function () {
111
- try {
112
- a || null == t.return || t.return();
113
- } finally {
114
- if (u) throw o;
115
- }
116
- }
117
- };
118
- }
14
+ var FlexSearch__default = /*#__PURE__*/_interopDefault(FlexSearch);
119
15
 
120
16
  function remirrorToRichTextSource(node, configDirectory, remoteOptions) {
121
17
  var files = {};
122
18
  var blocks = [];
123
19
  var i = 0;
124
- var _iterator = _createForOfIteratorHelper((node === null || node === void 0 ? void 0 : node.content) || []),
20
+ var _iterator = getSitemapTree._createForOfIteratorHelper((node === null || node === void 0 ? void 0 : node.content) || []),
125
21
  _step;
126
22
  try {
127
23
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -326,7 +222,7 @@ function convertImageNode(path, node, files, configDirectory, remoteOptions) {
326
222
  // file is added as src (see below):
327
223
  .concat("src");
328
224
  var remoteFileHash = core.Internal.remote.hashToRemoteFileHash(fullFileHash);
329
- var ref = remoteOptions ? core.Internal.remote.createRemoteRef(remoteOptions.remoteHost, _objectSpread2(_objectSpread2({}, remoteOptions), {}, {
225
+ var ref = remoteOptions ? core.Internal.remote.createRemoteRef(remoteOptions.remoteHost, getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, remoteOptions), {}, {
330
226
  fileHash: remoteFileHash,
331
227
  validationHash: core.Internal.remote.getValidationHash(remoteOptions.coreVersion, remoteOptions.schema, mimeType, {
332
228
  width: typeof node.attrs.width === "number" ? node.attrs.width : 0,
@@ -384,7 +280,7 @@ function convertImageNode(path, node, files, configDirectory, remoteOptions) {
384
280
  }
385
281
  var tag = {
386
282
  tag: "img",
387
- src: _objectSpread2({
283
+ src: getSitemapTree._objectSpread2({
388
284
  path: noParamsUrl,
389
285
  width: typeof node.attrs.width === "number" ? node.attrs.width : 0,
390
286
  height: typeof node.attrs.height === "number" ? node.attrs.height : 0,
@@ -494,7 +390,7 @@ var RemirrorJSON = zod.z.object({
494
390
  });
495
391
 
496
392
  function _arrayWithoutHoles(r) {
497
- if (Array.isArray(r)) return _arrayLikeToArray(r);
393
+ if (Array.isArray(r)) return getSitemapTree._arrayLikeToArray(r);
498
394
  }
499
395
 
500
396
  function _iterableToArray(r) {
@@ -506,7 +402,7 @@ function _nonIterableSpread() {
506
402
  }
507
403
 
508
404
  function _toConsumableArray(r) {
509
- return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
405
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || getSitemapTree._unsupportedIterableToArray(r) || _nonIterableSpread();
510
406
  }
511
407
 
512
408
  function richTextToRemirror(richtext) {
@@ -656,7 +552,7 @@ function convertLinkNodeToRemirror(linkNode) {
656
552
  if (remirrorNode.type !== "text") {
657
553
  return remirrorNode;
658
554
  }
659
- return _objectSpread2(_objectSpread2({}, remirrorNode), {}, {
555
+ return getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, remirrorNode), {}, {
660
556
  marks: (remirrorNode.marks || []).concat({
661
557
  type: "link",
662
558
  attrs: {
@@ -703,7 +599,7 @@ function convertListItemToRemirror(liNode) {
703
599
  }
704
600
  function convertListItemToRemirrorParagraph(rtChildren) {
705
601
  var children = [];
706
- var _iterator = _createForOfIteratorHelper(rtChildren),
602
+ var _iterator = getSitemapTree._createForOfIteratorHelper(rtChildren),
707
603
  _step;
708
604
  try {
709
605
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -1538,7 +1434,7 @@ var Api = {
1538
1434
  query: {
1539
1435
  redirect_to: onlyOneStringQueryParam.optional()
1540
1436
  },
1541
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1437
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1542
1438
  },
1543
1439
  res: zod.z.union([zod.z.object({
1544
1440
  status: zod.z.literal(401),
@@ -1560,7 +1456,7 @@ var Api = {
1560
1456
  query: {
1561
1457
  redirect_to: onlyOneStringQueryParam.optional()
1562
1458
  },
1563
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1459
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1564
1460
  },
1565
1461
  res: zod.z.union([zod.z.object({
1566
1462
  status: zod.z.literal(401),
@@ -1579,7 +1475,7 @@ var Api = {
1579
1475
  "/draft/stat": {
1580
1476
  GET: {
1581
1477
  req: {
1582
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1478
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1583
1479
  },
1584
1480
  res: zod.z.union([zod.z.object({
1585
1481
  status: zod.z.literal(401),
@@ -1598,7 +1494,7 @@ var Api = {
1598
1494
  query: {
1599
1495
  redirect_to: onlyOneStringQueryParam.optional()
1600
1496
  },
1601
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1497
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1602
1498
  },
1603
1499
  res: zod.z.union([zod.z.object({
1604
1500
  status: zod.z.literal(401),
@@ -1606,7 +1502,7 @@ var Api = {
1606
1502
  }), zod.z.object({
1607
1503
  status: zod.z.literal(302),
1608
1504
  redirectTo: zod.z.string(),
1609
- cookies: zod.z.object(_defineProperty(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, zod.z.object({
1505
+ cookies: zod.z.object(getSitemapTree._defineProperty(getSitemapTree._defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, zod.z.object({
1610
1506
  value: zod.z.string(),
1611
1507
  options: zod.z.object({
1612
1508
  httpOnly: zod.z.literal(true),
@@ -1617,7 +1513,7 @@ var Api = {
1617
1513
  }), zod.z.object({
1618
1514
  status: zod.z.literal(302),
1619
1515
  redirectTo: zod.z.string(),
1620
- cookies: zod.z.object(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue))
1516
+ cookies: zod.z.object(getSitemapTree._defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue))
1621
1517
  }), zod.z.object({
1622
1518
  status: zod.z.literal(400),
1623
1519
  json: zod.z.object({
@@ -1632,7 +1528,7 @@ var Api = {
1632
1528
  query: {
1633
1529
  redirect_to: onlyOneStringQueryParam.optional()
1634
1530
  },
1635
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1531
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
1636
1532
  },
1637
1533
  res: zod.z.union([zod.z.object({
1638
1534
  status: zod.z.literal(401),
@@ -1640,7 +1536,7 @@ var Api = {
1640
1536
  }), zod.z.object({
1641
1537
  status: zod.z.literal(302),
1642
1538
  redirectTo: zod.z.string(),
1643
- cookies: zod.z.object(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, zod.z.object({
1539
+ cookies: zod.z.object(getSitemapTree._defineProperty({}, VAL_ENABLE_COOKIE_NAME, zod.z.object({
1644
1540
  value: zod.z.literal("false")
1645
1541
  })))
1646
1542
  }), zod.z.object({
@@ -1661,7 +1557,7 @@ var Api = {
1661
1557
  res: zod.z.union([zod.z.object({
1662
1558
  status: zod.z.literal(302),
1663
1559
  redirectTo: zod.z.string(),
1664
- cookies: zod.z.object(_defineProperty(_defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, zod.z.object({
1560
+ cookies: zod.z.object(getSitemapTree._defineProperty(getSitemapTree._defineProperty({}, VAL_ENABLE_COOKIE_NAME, enableCookieValue), VAL_STATE_COOKIE, zod.z.object({
1665
1561
  value: zod.z.string(),
1666
1562
  options: zod.z.object({
1667
1563
  httpOnly: zod.z.literal(true),
@@ -1684,12 +1580,12 @@ var Api = {
1684
1580
  code: onlyOneStringQueryParam.optional(),
1685
1581
  state: onlyOneStringQueryParam.optional()
1686
1582
  },
1687
- cookies: _defineProperty({}, VAL_STATE_COOKIE, zod.z.string())
1583
+ cookies: getSitemapTree._defineProperty({}, VAL_STATE_COOKIE, zod.z.string())
1688
1584
  },
1689
1585
  res: zod.z.object({
1690
1586
  status: zod.z.literal(302),
1691
1587
  redirectTo: zod.z.string(),
1692
- cookies: zod.z.object(_defineProperty(_defineProperty(_defineProperty({}, VAL_STATE_COOKIE, zod.z.object({
1588
+ cookies: zod.z.object(getSitemapTree._defineProperty(getSitemapTree._defineProperty(getSitemapTree._defineProperty({}, VAL_STATE_COOKIE, zod.z.object({
1693
1589
  value: zod.z.literal(null)
1694
1590
  })), VAL_ENABLE_COOKIE_NAME, enableCookieValue.optional()), VAL_SESSION_COOKIE, zod.z.object({
1695
1591
  value: zod.z.string(),
@@ -1714,7 +1610,7 @@ var Api = {
1714
1610
  // TODO fix req types
1715
1611
  res: zod.z.union([zod.z.object({
1716
1612
  status: zod.z.literal(200),
1717
- cookies: zod.z.object(_defineProperty(_defineProperty({}, VAL_SESSION_COOKIE, zod.z.object({
1613
+ cookies: zod.z.object(getSitemapTree._defineProperty(getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.object({
1718
1614
  value: zod.z.string(),
1719
1615
  options: zod.z.object({
1720
1616
  httpOnly: zod.z.literal(true),
@@ -1736,7 +1632,7 @@ var Api = {
1736
1632
  }), zod.z.object({
1737
1633
  status: zod.z.literal(302),
1738
1634
  redirectTo: zod.z.string(),
1739
- cookies: zod.z.object(_defineProperty(_defineProperty({}, VAL_SESSION_COOKIE, zod.z.object({
1635
+ cookies: zod.z.object(getSitemapTree._defineProperty(getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.object({
1740
1636
  value: zod.z.string(),
1741
1637
  options: zod.z.object({
1742
1638
  httpOnly: zod.z.literal(true),
@@ -2697,7 +2593,7 @@ var Api = {
2697
2593
  */
2698
2594
  own_patch_groups_only: onlyOneBooleanQueryParam.optional()
2699
2595
  },
2700
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2596
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2701
2597
  },
2702
2598
  res: zod.z.union([unauthorizedResponse, notFoundResponse,
2703
2599
  // Shape (1): single `key`.
@@ -2744,7 +2640,7 @@ var Api = {
2744
2640
  "/ai/initialize": {
2745
2641
  POST: {
2746
2642
  req: {
2747
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2643
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2748
2644
  },
2749
2645
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2750
2646
  status: zod.z.literal(200),
@@ -2801,7 +2697,7 @@ var Api = {
2801
2697
  cursor_updatedAt: onlyOneStringQueryParam.optional(),
2802
2698
  cursor_id: onlyOneStringQueryParam.optional()
2803
2699
  },
2804
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2700
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2805
2701
  },
2806
2702
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2807
2703
  status: zod.z.literal(200),
@@ -2828,7 +2724,7 @@ var Api = {
2828
2724
  body: zod.z.object({
2829
2725
  name: zod.z.string()
2830
2726
  }),
2831
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2727
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2832
2728
  },
2833
2729
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2834
2730
  status: zod.z.literal(200),
@@ -2848,7 +2744,7 @@ var Api = {
2848
2744
  cursor_updatedAt: onlyOneStringQueryParam.optional(),
2849
2745
  cursor_id: onlyOneStringQueryParam.optional()
2850
2746
  },
2851
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2747
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2852
2748
  },
2853
2749
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2854
2750
  status: zod.z.literal(200),
@@ -2886,7 +2782,7 @@ var Api = {
2886
2782
  isRemote: zod.z["boolean"]().optional()
2887
2783
  })).min(1)
2888
2784
  }),
2889
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2785
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2890
2786
  },
2891
2787
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2892
2788
  status: zod.z.literal(200),
@@ -2923,7 +2819,7 @@ var Api = {
2923
2819
  metadata: zod.z.any(),
2924
2820
  contentType: zod.z.string()
2925
2821
  }),
2926
- cookies: _defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2822
+ cookies: getSitemapTree._defineProperty({}, VAL_SESSION_COOKIE, zod.z.string().optional())
2927
2823
  },
2928
2824
  res: zod.z.union([unauthorizedResponse, zod.z.object({
2929
2825
  status: zod.z.literal(200),
@@ -2966,18 +2862,8 @@ var Api = {
2966
2862
  // `number` is allowed because the client stringifies every query value before it
2967
2863
  // goes on the URL (see createValClient), so a numeric param round-trips fine.
2968
2864
 
2969
- function _typeof(o) {
2970
- "@babel/helpers - typeof";
2971
-
2972
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
2973
- return typeof o;
2974
- } : function (o) {
2975
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
2976
- }, _typeof(o);
2977
- }
2978
-
2979
2865
  function getErrorMessageFromUnknownJson(json, fallback) {
2980
- if (_typeof(json) === "object" && json !== null && "message" in json && typeof json.message === "string") {
2866
+ if (getSitemapTree._typeof(json) === "object" && json !== null && "message" in json && typeof json.message === "string") {
2981
2867
  return json.message;
2982
2868
  }
2983
2869
  return fallback;
@@ -3006,7 +2892,7 @@ var createValClient = function createValClient(host, config // We want to use th
3006
2892
  for (_i = 0, _Object$keys = Object.keys(anyReq.query); _i < _Object$keys.length; _i++) {
3007
2893
  key = _Object$keys[_i];
3008
2894
  if (Array.isArray((_anyReq$query = anyReq.query) === null || _anyReq$query === void 0 ? void 0 : _anyReq$query[key])) {
3009
- _iterator = _createForOfIteratorHelper(((_anyReq$query2 = anyReq.query) === null || _anyReq$query2 === void 0 ? void 0 : _anyReq$query2[key]) || []);
2895
+ _iterator = getSitemapTree._createForOfIteratorHelper(((_anyReq$query2 = anyReq.query) === null || _anyReq$query2 === void 0 ? void 0 : _anyReq$query2[key]) || []);
3010
2896
  try {
3011
2897
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
3012
2898
  value = _step.value;
@@ -3247,7 +3133,7 @@ function _nonIterableRest() {
3247
3133
  }
3248
3134
 
3249
3135
  function _slicedToArray(r, e) {
3250
- return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
3136
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || getSitemapTree._unsupportedIterableToArray(r, e) || _nonIterableRest();
3251
3137
  }
3252
3138
 
3253
3139
  var urlOf = function urlOf() {
@@ -3295,7 +3181,7 @@ var compatible = {
3295
3181
  * predicate is that check, said once.
3296
3182
  */
3297
3183
  function isJsonObject(value) {
3298
- return _typeof(value) === "object" && value !== null && !Array.isArray(value);
3184
+ return getSitemapTree._typeof(value) === "object" && value !== null && !Array.isArray(value);
3299
3185
  }
3300
3186
  function incompatible(reason) {
3301
3187
  return {
@@ -3402,7 +3288,7 @@ function checkCompatibility(from, to) {
3402
3288
  // wholesale would refuse a restore that is perfectly safe.
3403
3289
  if (to.schema.type === "union") {
3404
3290
  var key = typeof to.schema.key === "string" ? to.schema.key : "";
3405
- var _iterator = _createForOfIteratorHelper(to.schema.items),
3291
+ var _iterator = getSitemapTree._createForOfIteratorHelper(to.schema.items),
3406
3292
  _step;
3407
3293
  try {
3408
3294
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -3536,7 +3422,7 @@ function checkCompatibility(from, to) {
3536
3422
  });
3537
3423
  }
3538
3424
  var _unknown = null;
3539
- var _iterator2 = _createForOfIteratorHelper(from.value),
3425
+ var _iterator2 = getSitemapTree._createForOfIteratorHelper(from.value),
3540
3426
  _step2;
3541
3427
  try {
3542
3428
  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
@@ -3638,7 +3524,7 @@ function checkCompatibility(from, to) {
3638
3524
  function newestCommitSha(commits) {
3639
3525
  var _newest$commitSha, _newest;
3640
3526
  var newest = null;
3641
- var _iterator = _createForOfIteratorHelper(commits !== null && commits !== void 0 ? commits : []),
3527
+ var _iterator = getSitemapTree._createForOfIteratorHelper(commits !== null && commits !== void 0 ? commits : []),
3642
3528
  _step;
3643
3529
  try {
3644
3530
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -3655,10 +3541,6 @@ function newestCommitSha(commits) {
3655
3541
  return (_newest$commitSha = (_newest = newest) === null || _newest === void 0 ? void 0 : _newest.commitSha) !== null && _newest$commitSha !== void 0 ? _newest$commitSha : null;
3656
3542
  }
3657
3543
 
3658
- var VAL_CONFIG_SESSION_STORAGE_KEY = "val-config";
3659
- var VAL_THEME_SESSION_STORAGE_KEY = "val-theme";
3660
- var VAL_AI_SESSION_STORAGE_KEY = "val-ai-session";
3661
-
3662
3544
  var SharedValConfig = zod.z.object({
3663
3545
  contentHostUrl: zod.z.string().optional(),
3664
3546
  appHostUrl: zod.z.string().optional(),
@@ -3686,170 +3568,6 @@ var ValDeployment = zod.z.object({
3686
3568
  createdAt: zod.z.string()
3687
3569
  });
3688
3570
 
3689
- // Strictly speaking this should be in the next package but it's shared, because we want to use it in the ui package. We want to resolve that somehow
3690
- function getNextAppRouterSitemapTree(srcFolder, paths) {
3691
- var root = {
3692
- type: "node",
3693
- name: "/",
3694
- children: []
3695
- };
3696
- var _iterator = _createForOfIteratorHelper(paths),
3697
- _step;
3698
- try {
3699
- var _loop = function _loop() {
3700
- var path = _step.value;
3701
- var urlPath = path.urlPath,
3702
- moduleFilePathS = path.moduleFilePath;
3703
- var moduleFilePath = moduleFilePathS;
3704
- if (!urlPath.startsWith("/")) {
3705
- console.error("urlPath must start with /: ".concat(urlPath));
3706
- return 0; // continue
3707
- }
3708
- var pattern = getPatternFromModuleFilePath(moduleFilePath, srcFolder);
3709
- if (urlPath === "/") {
3710
- var fullPath = "/";
3711
- root.pattern = getPatternFromModuleFilePath(moduleFilePath, srcFolder);
3712
- root.page = {
3713
- fullPath: fullPath
3714
- };
3715
- root.sourcePath = core.Internal.joinModuleFilePathAndModulePath(moduleFilePath, "\"".concat(fullPath, "\""));
3716
- root.moduleFilePath = moduleFilePath;
3717
- return 0; // continue
3718
- }
3719
- var pathParts = urlPath.split("/").slice(1).filter(Boolean);
3720
- var currentNode = root;
3721
- pathParts.forEach(function (part, index) {
3722
- var hasChildren = index < pathParts.length - 1;
3723
- var isLast = index === pathParts.length - 1;
3724
- var fullPath = "/" + pathParts.slice(0, index + 1).join("/");
3725
- var sourcePath = core.Internal.joinModuleFilePathAndModulePath(moduleFilePath, "\"".concat(fullPath, "\""));
3726
- var node = hasChildren ? _objectSpread2(_objectSpread2({
3727
- type: "node",
3728
- name: part,
3729
- pattern: pattern,
3730
- moduleFilePath: moduleFilePath
3731
- }, isLast ? {
3732
- page: {
3733
- fullPath: fullPath
3734
- },
3735
- sourcePath: sourcePath
3736
- } : {}), {}, {
3737
- children: []
3738
- }) : {
3739
- type: "leaf",
3740
- name: part,
3741
- pattern: pattern,
3742
- fullPath: fullPath,
3743
- moduleFilePath: moduleFilePath,
3744
- sourcePath: sourcePath,
3745
- children: []
3746
- };
3747
- var existingNodeIndex = currentNode.children.findIndex(function (node) {
3748
- return node.name === part;
3749
- });
3750
- if (existingNodeIndex === -1) {
3751
- currentNode.children.push(node);
3752
- if (currentNode.type === "node") {
3753
- currentNode.isLinear = true;
3754
- if (currentNode.children.length > 1) {
3755
- delete currentNode.isLinear;
3756
- }
3757
- }
3758
- currentNode = node;
3759
- } else {
3760
- var existingNode = currentNode.children[existingNodeIndex];
3761
- if (existingNode.type === "leaf" && hasChildren) {
3762
- var _sourcePath = existingNode.sourcePath;
3763
- // convert leaf to node
3764
- currentNode.children[existingNodeIndex] = {
3765
- type: "node",
3766
- name: part,
3767
- pattern: pattern,
3768
- page: {
3769
- fullPath: fullPath
3770
- },
3771
- sourcePath: _sourcePath,
3772
- children: existingNode.children,
3773
- moduleFilePath: moduleFilePath
3774
- };
3775
- currentNode = currentNode.children[existingNodeIndex];
3776
- } else if (existingNode.type === "node" && isLast) {
3777
- // add page, source path and module file path
3778
- existingNode.page = {
3779
- fullPath: fullPath
3780
- };
3781
- existingNode.sourcePath = sourcePath;
3782
- existingNode.moduleFilePath = moduleFilePath;
3783
- existingNode.pattern = pattern;
3784
- } else {
3785
- currentNode = currentNode.children[existingNodeIndex];
3786
- }
3787
- }
3788
- });
3789
- },
3790
- _ret;
3791
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
3792
- _ret = _loop();
3793
- if (_ret === 0) continue;
3794
- }
3795
- } catch (err) {
3796
- _iterator.e(err);
3797
- } finally {
3798
- _iterator.f();
3799
- }
3800
- return root;
3801
- }
3802
- function getPatternFromModuleFilePath(moduleFilePath, srcFolder) {
3803
- return moduleFilePath.replace(srcFolder, "")
3804
- // TODO: hacky!
3805
- // remove route groups
3806
- .replace(/\/\([^/]+\)/g, "") // not sure we want to do this?
3807
- .replace("/page.val.ts", "").replace("/page.val.js", "");
3808
- }
3809
-
3810
- function parseRoutePattern(pattern) {
3811
- if (pattern === "" || pattern === "/") {
3812
- return [];
3813
- }
3814
- var p = pattern.startsWith("/") ? pattern.slice(1) : pattern;
3815
- return p.split("/").map(function (part) {
3816
- var isOptionalParam = part.startsWith("[[") && part.endsWith("]]");
3817
- var isNonOptionalParam = part.startsWith("[") && part.endsWith("]");
3818
- var nameStart = isOptionalParam ? 2 : isNonOptionalParam ? 1 : 0;
3819
- var nameEnd = part.indexOf("]", nameStart);
3820
- var isArrayParam = part.slice(nameStart, nameStart + 3) === "...";
3821
- var paramName = part.slice(nameStart + (isArrayParam ? 3 : 0), nameEnd);
3822
- if (isOptionalParam || isNonOptionalParam) {
3823
- if (isArrayParam) {
3824
- return {
3825
- type: "array-param",
3826
- paramName: paramName,
3827
- optional: isOptionalParam
3828
- };
3829
- } else {
3830
- return {
3831
- type: "string-param",
3832
- paramName: paramName,
3833
- optional: isOptionalParam
3834
- };
3835
- }
3836
- }
3837
- return {
3838
- type: "literal",
3839
- name: part
3840
- };
3841
- });
3842
- }
3843
-
3844
- function getNextAppRouterSourceFolder(moduleFilePath) {
3845
- if (moduleFilePath.startsWith("/app")) {
3846
- return "/app";
3847
- } else if (moduleFilePath.startsWith("/src/app")) {
3848
- return "/src/app";
3849
- }
3850
- return null;
3851
- }
3852
-
3853
3571
  /**
3854
3572
  * Shared route validation utilities
3855
3573
  */
@@ -3963,7 +3681,7 @@ function getRoutesWithModulePaths(schemas, sources) {
3963
3681
  var moduleFilePath = moduleFilePathS;
3964
3682
  var schema = schemas[moduleFilePath];
3965
3683
  var source = sources[moduleFilePath];
3966
- if (schema && schema.type === "record" && schema.router && source && _typeof(source) === "object" && !Array.isArray(source)) {
3684
+ if (schema && schema.type === "record" && schema.router && source && getSitemapTree._typeof(source) === "object" && !Array.isArray(source)) {
3967
3685
  for (var key in source) {
3968
3686
  if (!routeMap.has(key)) {
3969
3687
  routeMap.set(key, moduleFilePath);
@@ -4047,12 +3765,12 @@ function getKeyOfRecordAt(sourcePath, snapshot) {
4047
3765
  // returns undefined source on any mismatch.
4048
3766
  var source = moduleSource;
4049
3767
  var schema = moduleSchema;
4050
- var _iterator = _createForOfIteratorHelper(core.Internal.splitModulePath(modulePath)),
3768
+ var _iterator = getSitemapTree._createForOfIteratorHelper(core.Internal.splitModulePath(modulePath)),
4051
3769
  _step;
4052
3770
  try {
4053
3771
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
4054
3772
  var part = _step.value;
4055
- if (source && _typeof(source) === "object" && !Array.isArray(source) && part in source) {
3773
+ if (source && getSitemapTree._typeof(source) === "object" && !Array.isArray(source) && part in source) {
4056
3774
  source = source[part];
4057
3775
  } else {
4058
3776
  source = undefined;
@@ -4085,12 +3803,12 @@ function checkKeyIsValid(key, sourcePath, snapshot) {
4085
3803
  message: "Expected key at ".concat(sourcePath, " to be of type 'record'")
4086
3804
  };
4087
3805
  }
4088
- if (keyOfModuleSource && _typeof(keyOfModuleSource) === "object" && !Array.isArray(keyOfModuleSource) && key in keyOfModuleSource) {
3806
+ if (keyOfModuleSource && getSitemapTree._typeof(keyOfModuleSource) === "object" && !Array.isArray(keyOfModuleSource) && key in keyOfModuleSource) {
4089
3807
  return {
4090
3808
  error: false
4091
3809
  };
4092
3810
  }
4093
- if (!keyOfModuleSource || _typeof(keyOfModuleSource) !== "object" || Array.isArray(keyOfModuleSource)) {
3811
+ if (!keyOfModuleSource || getSitemapTree._typeof(keyOfModuleSource) !== "object" || Array.isArray(keyOfModuleSource)) {
4094
3812
  return {
4095
3813
  error: true,
4096
3814
  message: "Expected ".concat(sourcePath, " to be a truthy object")
@@ -4117,7 +3835,7 @@ function checkRouteIsValid(route, includePattern, excludePattern, snapshot) {
4117
3835
  var schema = snapshot.schemas[moduleFilePath];
4118
3836
  if ((schema === null || schema === void 0 ? void 0 : schema.type) === "record" && schema.router) {
4119
3837
  var source = snapshot.sources[moduleFilePath];
4120
- if (source && _typeof(source) === "object" && !Array.isArray(source)) {
3838
+ if (source && getSitemapTree._typeof(source) === "object" && !Array.isArray(source)) {
4121
3839
  routerModules[moduleFilePath] = Object.keys(source);
4122
3840
  }
4123
3841
  }
@@ -4179,18 +3897,18 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4179
3897
  if (!error.value) {
4180
3898
  return {
4181
3899
  status: "remaining",
4182
- error: _objectSpread2(_objectSpread2({}, error), {}, {
3900
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
4183
3901
  message: "Could not find a value for keyOf. ".concat(TYPE_ERROR_MESSAGE),
4184
3902
  typeError: true,
4185
3903
  fixes: undefined
4186
3904
  })
4187
3905
  };
4188
3906
  }
4189
- if (_typeof(error.value) !== "object") {
3907
+ if (getSitemapTree._typeof(error.value) !== "object") {
4190
3908
  return {
4191
3909
  status: "remaining",
4192
- error: _objectSpread2(_objectSpread2({}, error), {}, {
4193
- message: "Expected keyOf validation error to have a 'value' property of type 'object'. Found: ".concat(_typeof(error.value), ". ").concat(TYPE_ERROR_MESSAGE),
3910
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
3911
+ message: "Expected keyOf validation error to have a 'value' property of type 'object'. Found: ".concat(getSitemapTree._typeof(error.value), ". ").concat(TYPE_ERROR_MESSAGE),
4194
3912
  typeError: true,
4195
3913
  fixes: undefined
4196
3914
  })
@@ -4202,8 +3920,8 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4202
3920
  if (typeof key !== "string") {
4203
3921
  return {
4204
3922
  status: "remaining",
4205
- error: _objectSpread2(_objectSpread2({}, error), {}, {
4206
- message: "Expected keyOf validation error 'value' to have property 'key' of type 'string'. Found: ".concat(_typeof(key), ". ").concat(TYPE_ERROR_MESSAGE),
3923
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
3924
+ message: "Expected keyOf validation error 'value' to have property 'key' of type 'string'. Found: ".concat(getSitemapTree._typeof(key), ". ").concat(TYPE_ERROR_MESSAGE),
4207
3925
  typeError: true,
4208
3926
  fixes: undefined
4209
3927
  })
@@ -4212,8 +3930,8 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4212
3930
  if (typeof valueSourcePath !== "string") {
4213
3931
  return {
4214
3932
  status: "remaining",
4215
- error: _objectSpread2(_objectSpread2({}, error), {}, {
4216
- message: "Expected keyOf validation error 'value' to have property 'sourcePath' of type 'string'. Found: ".concat(_typeof(valueSourcePath), ". ").concat(TYPE_ERROR_MESSAGE),
3933
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
3934
+ message: "Expected keyOf validation error 'value' to have property 'sourcePath' of type 'string'. Found: ".concat(getSitemapTree._typeof(valueSourcePath), ". ").concat(TYPE_ERROR_MESSAGE),
4217
3935
  typeError: true,
4218
3936
  fixes: undefined
4219
3937
  })
@@ -4223,7 +3941,7 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4223
3941
  if (res.error) {
4224
3942
  return {
4225
3943
  status: "remaining",
4226
- error: _objectSpread2(_objectSpread2({}, error), {}, {
3944
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
4227
3945
  message: res.message,
4228
3946
  fixes: undefined
4229
3947
  })
@@ -4237,18 +3955,18 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4237
3955
  if (!error.value) {
4238
3956
  return {
4239
3957
  status: "remaining",
4240
- error: _objectSpread2(_objectSpread2({}, error), {}, {
3958
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
4241
3959
  message: "Could not find a value for route. ".concat(TYPE_ERROR_MESSAGE),
4242
3960
  typeError: true,
4243
3961
  fixes: undefined
4244
3962
  })
4245
3963
  };
4246
3964
  }
4247
- if (_typeof(error.value) !== "object") {
3965
+ if (getSitemapTree._typeof(error.value) !== "object") {
4248
3966
  return {
4249
3967
  status: "remaining",
4250
- error: _objectSpread2(_objectSpread2({}, error), {}, {
4251
- message: "Expected route validation error to have a 'value' property of type 'object'. Found: ".concat(_typeof(error.value), ". ").concat(TYPE_ERROR_MESSAGE),
3968
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
3969
+ message: "Expected route validation error to have a 'value' property of type 'object'. Found: ".concat(getSitemapTree._typeof(error.value), ". ").concat(TYPE_ERROR_MESSAGE),
4252
3970
  typeError: true,
4253
3971
  fixes: undefined
4254
3972
  })
@@ -4259,8 +3977,8 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4259
3977
  if (typeof route !== "string") {
4260
3978
  return {
4261
3979
  status: "remaining",
4262
- error: _objectSpread2(_objectSpread2({}, error), {}, {
4263
- message: "Expected route validation error 'value' to have property 'route' of type 'string'. Found: ".concat(_typeof(route), ". ").concat(TYPE_ERROR_MESSAGE),
3980
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
3981
+ message: "Expected route validation error 'value' to have property 'route' of type 'string'. Found: ".concat(getSitemapTree._typeof(route), ". ").concat(TYPE_ERROR_MESSAGE),
4264
3982
  typeError: true,
4265
3983
  fixes: undefined
4266
3984
  })
@@ -4272,7 +3990,7 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4272
3990
  if (_res.error) {
4273
3991
  return {
4274
3992
  status: "remaining",
4275
- error: _objectSpread2(_objectSpread2({}, error), {}, {
3993
+ error: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, error), {}, {
4276
3994
  message: _res.message,
4277
3995
  fixes: undefined
4278
3996
  })
@@ -4285,7 +4003,7 @@ function resolveSchemaSourceFixForError(error, snapshot) {
4285
4003
  return null;
4286
4004
  }
4287
4005
  function asRegExpPattern(value) {
4288
- if (value && _typeof(value) === "object" && "source" in value && "flags" in value && typeof value.source === "string" && typeof value.flags === "string") {
4006
+ if (value && getSitemapTree._typeof(value) === "object" && "source" in value && "flags" in value && typeof value.source === "string" && typeof value.flags === "string") {
4289
4007
  return value;
4290
4008
  }
4291
4009
  return undefined;
@@ -4307,7 +4025,7 @@ function resolveSchemaSourceFixes(validationErrors, snapshot) {
4307
4025
  for (var sourcePathS in validationErrors) {
4308
4026
  var sourcePath = sourcePathS;
4309
4027
  var remaining = [];
4310
- var _iterator2 = _createForOfIteratorHelper(validationErrors[sourcePath]),
4028
+ var _iterator2 = getSitemapTree._createForOfIteratorHelper(validationErrors[sourcePath]),
4311
4029
  _step2;
4312
4030
  try {
4313
4031
  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
@@ -4331,84 +4049,6 @@ function resolveSchemaSourceFixes(validationErrors, snapshot) {
4331
4049
  return result;
4332
4050
  }
4333
4051
 
4334
- /**
4335
- * The protocol between the studio's canvas and the page inside it.
4336
- *
4337
- * The canvas shows the running site in a frame. That frame is a different
4338
- * document — the customer's app, rendered by their components — so the studio
4339
- * cannot reach into it, and it cannot reach out. Everything they say to each
4340
- * other goes through `postMessage`, and this is the vocabulary.
4341
- *
4342
- * It lives in `shared` because both halves have to agree on it: the page half
4343
- * ships in `@valbuild/next`, the studio half in `@valbuild/ui`, and a message
4344
- * shape defined twice is a message shape that will differ once.
4345
- *
4346
- * ## Why a query parameter turns it on
4347
- *
4348
- * The frame has to render the page as Val sees it — draft content, with
4349
- * `data-val-path` on every element Val tracks — while *not* showing Val's own
4350
- * overlay, because the studio is already the UI. Nothing about the cookies can
4351
- * express that: they are per-origin, and the studio and the page share an
4352
- * origin, so a cookie would change the customer's own tabs too. A parameter on
4353
- * the frame's URL is scoped to exactly the one document that needs it.
4354
- */
4355
-
4356
- /** Marks a page load as the studio's canvas frame. */
4357
- var VAL_CANVAS_PARAM = "val_canvas";
4358
-
4359
- /**
4360
- * Every message is tagged with this, and the tag is checked on receipt.
4361
- *
4362
- * A window receives messages from anything that has a handle on it —
4363
- * extensions, embeds, other frames — and `event.data` is whatever they chose to
4364
- * send. Checking a discriminator before reading anything else is what keeps a
4365
- * stray message from being read as a canvas instruction.
4366
- */
4367
- var VAL_CANVAS_MESSAGE = "val-canvas";
4368
-
4369
- /** One element on the page that Val has a path for. */
4370
-
4371
- /** What the page tells the studio. */
4372
-
4373
- /** What the studio tells the page. */
4374
-
4375
- /** Narrow an unknown `event.data` to a message from the page. */
4376
- function isValCanvasPageMessage(data) {
4377
- if (_typeof(data) !== "object" || data === null) return false;
4378
- var message = data;
4379
- if (message.val !== VAL_CANVAS_MESSAGE) return false;
4380
- return message.type === "ready" || message.type === "elements" || message.type === "clicked" || message.type === "pinch" || message.type === "zoom" || message.type === "refreshing";
4381
- }
4382
-
4383
- /** Narrow an unknown `event.data` to a message from the studio. */
4384
- function isValCanvasStudioMessage(data) {
4385
- if (_typeof(data) !== "object" || data === null) return false;
4386
- var message = data;
4387
- if (message.val !== VAL_CANVAS_MESSAGE) return false;
4388
- return message.type === "rescan" || message.type === "highlight" || message.type === "setPicking" || message.type === "sourceUpdate" || message.type === "sourcesSynced";
4389
- }
4390
-
4391
- /**
4392
- * Whether this document was loaded as the studio's canvas frame.
4393
- *
4394
- * Reads the location directly rather than taking it as an argument, because
4395
- * every caller wants the answer for the document it is running in, and passing
4396
- * it around is how one of them ends up asking about the wrong one.
4397
- */
4398
- function isValCanvasFrame(search) {
4399
- try {
4400
- return new URLSearchParams(search).get(VAL_CANVAS_PARAM) !== null;
4401
- } catch (_unused) {
4402
- return false;
4403
- }
4404
- }
4405
-
4406
- /** Add the canvas marker to a page URL. */
4407
- function withValCanvasParam(url) {
4408
- var separator = url.includes("?") ? "&" : "?";
4409
- return "".concat(url).concat(separator).concat(VAL_CANVAS_PARAM, "=1");
4410
- }
4411
-
4412
4052
  /**
4413
4053
  * Local `yyyy-MM-dd`, which is the one thing this module used `date-fns` for.
4414
4054
  *
@@ -4509,13 +4149,13 @@ function emptyOf(schema) {
4509
4149
  var toolNames = ["get_all_schema", "get_source", "search_content", "validate_content", "create_patch", "add_session_image_to_gallery", "remove_image_gallery_entry", "navigate_to", "get_current_context", "get_patches", "get_source_path_from_route", "set_session_name", "show_compare_view", "ask_user_question", "duplicate_source", "empty_at_path", "count_entries", "get_record_keys"];
4510
4150
 
4511
4151
  function buildFileRefValue(filePath, metadata) {
4512
- return _objectSpread2({
4152
+ return getSitemapTree._objectSpread2({
4513
4153
  path: filePath
4514
4154
  }, metadata);
4515
4155
  }
4516
4156
  function getSourceAt(source, path) {
4517
4157
  var current = source;
4518
- var _iterator = _createForOfIteratorHelper(path),
4158
+ var _iterator = getSitemapTree._createForOfIteratorHelper(path),
4519
4159
  _step;
4520
4160
  try {
4521
4161
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -4525,7 +4165,7 @@ function getSourceAt(source, path) {
4525
4165
  var idx = Number(part);
4526
4166
  if (!Number.isInteger(idx)) return undefined;
4527
4167
  current = current[idx];
4528
- } else if (_typeof(current) === "object") {
4168
+ } else if (getSitemapTree._typeof(current) === "object") {
4529
4169
  current = current[part];
4530
4170
  } else {
4531
4171
  return undefined;
@@ -4575,7 +4215,7 @@ function resolveSerializedSchemaAtPath(schema, path) {
4575
4215
  };
4576
4216
  } else if (current.type === "union") {
4577
4217
  if (typeof current.key === "string") {
4578
- var _iterator2 = _createForOfIteratorHelper(current.items),
4218
+ var _iterator2 = getSitemapTree._createForOfIteratorHelper(current.items),
4579
4219
  _step2;
4580
4220
  try {
4581
4221
  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
@@ -4670,13 +4310,21 @@ function checkGallerySchema(moduleSchema) {
4670
4310
  };
4671
4311
  }
4672
4312
  function buildImageGalleryPatch(args, moduleSchema) {
4313
+ var _args$metadata$alt;
4673
4314
  var wrong = checkGallerySchema(moduleSchema);
4674
4315
  if (wrong) return wrong;
4675
4316
  var remote = isRemoteSchema(moduleSchema);
4676
4317
  var patch = [{
4677
4318
  op: "add",
4678
4319
  path: [args.filePath],
4679
- value: _objectSpread2({}, args.metadata)
4320
+ value: getSitemapTree._objectSpread2(getSitemapTree._objectSpread2({}, args.metadata), {}, {
4321
+ // `alt` is a REQUIRED field of a gallery entry (`s.images()` gives it a
4322
+ // nullable string schema), so an entry written without one is invalid
4323
+ // the moment it lands — and the caller that had no alt to give is the
4324
+ // common case, not the odd one. Null is what the Studio's own upload
4325
+ // writes there.
4326
+ alt: (_args$metadata$alt = args.metadata.alt) !== null && _args$metadata$alt !== void 0 ? _args$metadata$alt : null
4327
+ })
4680
4328
  }, {
4681
4329
  op: "file",
4682
4330
  path: [args.filePath],
@@ -4690,7 +4338,7 @@ function buildImageGalleryPatch(args, moduleSchema) {
4690
4338
  function buildRemoveImageGalleryEntryPatch(args, moduleSchema, moduleSource) {
4691
4339
  var wrong = checkGallerySchema(moduleSchema);
4692
4340
  if (wrong) return wrong;
4693
- if (!moduleSource || _typeof(moduleSource) !== "object" || Array.isArray(moduleSource)) {
4341
+ if (!moduleSource || getSitemapTree._typeof(moduleSource) !== "object" || Array.isArray(moduleSource)) {
4694
4342
  return {
4695
4343
  kind: "error",
4696
4344
  message: "Cannot remove from gallery: module source is not an object."
@@ -5012,11 +4660,11 @@ function describeContainerAtPath(moduleSchema, moduleSource, path) {
5012
4660
  };
5013
4661
  }
5014
4662
  if (schema.type === "record" || schema.type === "object") {
5015
- if (value === null || _typeof(value) !== "object" || Array.isArray(value)) {
4663
+ if (value === null || getSitemapTree._typeof(value) !== "object" || Array.isArray(value)) {
5016
4664
  return {
5017
4665
  kind: "error",
5018
4666
  reason: "not-a-container",
5019
- message: "Path ".concat(JSON.stringify(path), " points to a ").concat(value === null ? "null" : Array.isArray(value) ? "array" : _typeof(value), " value, which has no entries to count or list.")
4667
+ message: "Path ".concat(JSON.stringify(path), " points to a ").concat(value === null ? "null" : Array.isArray(value) ? "array" : getSitemapTree._typeof(value), " value, which has no entries to count or list.")
5020
4668
  };
5021
4669
  }
5022
4670
  return {
@@ -5061,7 +4709,7 @@ function partitionValidationErrors(validationErrors) {
5061
4709
  var skipped = {};
5062
4710
  for (var sourcePathS in validationErrors) {
5063
4711
  var sourcePath = sourcePathS;
5064
- var _iterator = _createForOfIteratorHelper(validationErrors[sourcePath]),
4712
+ var _iterator = getSitemapTree._createForOfIteratorHelper(validationErrors[sourcePath]),
5065
4713
  _step;
5066
4714
  try {
5067
4715
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
@@ -5168,12 +4816,725 @@ function filterBlockingValidationErrors(validationErrors, schemas, sources) {
5168
4816
  return partitionValidationErrors(resolved).surfaced;
5169
4817
  }
5170
4818
 
4819
+ /**
4820
+ * Every decision `encode` makes, with none of the pixels.
4821
+ *
4822
+ * The re-encode itself happens in two places that share nothing: the Studio
4823
+ * runs it on a `<canvas>` before the upload leaves the browser
4824
+ * (`packages/ui/spa/utils/encodeImage.ts`), and the MCP image tool runs it on
4825
+ * `sharp` in the server process (`@valbuild/mcp`). What must NOT differ between
4826
+ * them is what `s.image({ encode })` means — which images are converted, how
4827
+ * far they are scaled, and when the original wins anyway. So the decisions live
4828
+ * here, once, and each side supplies only its own encoder.
4829
+ *
4830
+ * See `architecture/media.md`.
4831
+ */
4832
+
4833
+ var ENCODE_DEFAULTS = {
4834
+ quality: 0.8,
4835
+ maxWidth: 2560,
4836
+ maxHeight: 2560
4837
+ };
4838
+ var ENCODE_MIME_TYPE_OF = {
4839
+ webp: "image/webp"
4840
+ };
4841
+
4842
+ /**
4843
+ * Formats an encoder cannot round-trip without losing something: SVG is vector,
4844
+ * an animated GIF keeps only its first frame, and AVIF is already smaller than
4845
+ * anything we would produce.
4846
+ */
4847
+ var NEVER_ENCODED = ["image/svg+xml", "image/gif", "image/avif"];
4848
+
4849
+ /** A dimension bound the encoder can act on, else the default. */
4850
+ function usableBound(value, fallback) {
4851
+ return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
4852
+ }
4853
+
4854
+ /**
4855
+ * The schema's own option first, then the gallery it references, then off.
4856
+ *
4857
+ * Mirrors how `ImageField` resolves `accept` and `directory`. A gallery-backed
4858
+ * field (`s.image(galleryVal)`) serializes with EMPTY options, so without the
4859
+ * gallery fallback it could never inherit what the gallery asked for — and
4860
+ * `s.image(galleryVal, { encode: false })` is how such a field opts back out.
4861
+ *
4862
+ * Nonsense numbers fall back to the defaults rather than through. `fitWithin`
4863
+ * reads a bound of 0 (or NaN, or a negative) as "everything already fits", so
4864
+ * an unusable `maxWidth` would otherwise SILENTLY disable the downscale it was
4865
+ * asking for, and a `quality` outside 0–1 is ignored by `canvas.toBlob` just as
4866
+ * quietly. Falling back is deliberately not throwing: a schema is evaluated by
4867
+ * the CLI's `node:vm` sandbox and by the Next server, so a typo'd quality would
4868
+ * take a whole project down over an upload-time optimisation.
4869
+ */
4870
+ function resolveEncodeSettings(fieldOption, galleryOption) {
4871
+ var option = fieldOption !== undefined ? fieldOption : galleryOption;
4872
+ if (!option) {
4873
+ return null;
4874
+ }
4875
+ var quality = option.quality;
4876
+ return {
4877
+ type: option.type,
4878
+ quality: quality !== undefined && Number.isFinite(quality) && quality > 0 ? Math.min(quality, 1) : ENCODE_DEFAULTS.quality,
4879
+ maxWidth: usableBound(option.maxWidth, ENCODE_DEFAULTS.maxWidth),
4880
+ maxHeight: usableBound(option.maxHeight, ENCODE_DEFAULTS.maxHeight)
4881
+ };
4882
+ }
4883
+
4884
+ /**
4885
+ * Dimensions scaled to fit inside the box, or null when the image already does.
4886
+ *
4887
+ * Null is the signal for "no downscale was needed", which the size comparison
4888
+ * in {@link chooseEncoded} turns on.
4889
+ */
4890
+ function fitWithin(width, height, maxWidth, maxHeight) {
4891
+ if (!(width > 0) || !(height > 0) || !(maxWidth > 0) || !(maxHeight > 0) || width <= maxWidth && height <= maxHeight) {
4892
+ return null;
4893
+ }
4894
+ var scale = Math.min(maxWidth / width, maxHeight / height);
4895
+ return {
4896
+ // At least one pixel: a very wide, very short image would otherwise round
4897
+ // its height to zero, and a zero-sized canvas cannot be encoded.
4898
+ width: Math.max(1, Math.round(width * scale)),
4899
+ height: Math.max(1, Math.round(height * scale))
4900
+ };
4901
+ }
4902
+
4903
+ /**
4904
+ * Whether a schema that declares `accept` would take this mime type.
4905
+ *
4906
+ * The same rules as `ImageSchema.executeValidate`, which validates the STORED
4907
+ * mimeType against `accept` — so converting to a type `accept` forbids would
4908
+ * upload a file the schema reports as invalid the moment it lands. Delegated to
4909
+ * `@valbuild/core` rather than re-spelled, because a second reading of one
4910
+ * `accept` string is how a converted image passes here and fails there.
4911
+ */
4912
+ function isMimeTypeAccepted(mimeType, accept) {
4913
+ if (!accept) {
4914
+ return true;
4915
+ }
4916
+ return core.Internal.mimeTypeMatchesAccept(mimeType, accept);
4917
+ }
4918
+
4919
+ /** Formats left alone: the lossy list, plus the target type when it already fits. */
4920
+ function isSkippedSource(sourceMimeType, targetMimeType, needsDownscale) {
4921
+ if (NEVER_ENCODED.includes(sourceMimeType)) {
4922
+ return true;
4923
+ }
4924
+ return sourceMimeType === targetMimeType && !needsDownscale;
4925
+ }
4926
+
4927
+ /**
4928
+ * Whether to upload what the encoder produced, or the file that was picked.
4929
+ *
4930
+ * Two ways the encoded bytes lose. They are not actually the type we asked for
4931
+ * — `canvas.toBlob` answers an unsupported type with a PNG rather than with
4932
+ * null, so "not null" is not the same question as "is a webp". Or they are
4933
+ * simply bigger, which happens for small and flat images: measured, an 8x8
4934
+ * solid PNG of 74 bytes becomes a 548 byte webp. A downscale overrides that,
4935
+ * since the original is then the wrong size whatever it weighs.
4936
+ */
4937
+ function chooseEncoded(input) {
4938
+ if (input.encodedSize === null || input.encodedType !== input.targetMimeType) {
4939
+ return false;
4940
+ }
4941
+ if (input.needsDownscale) {
4942
+ return true;
4943
+ }
4944
+ return input.encodedSize < input.originalSize;
4945
+ }
4946
+
4947
+ /**
4948
+ * `photo.png` -> `photo.webp`. The extension is re-derived downstream too, but
4949
+ * the name should not lie.
4950
+ */
4951
+ function withExtension(filename, ext) {
4952
+ var base = filename.split(".").slice(0, -1).join(".") || filename;
4953
+ return "".concat(base, ".").concat(ext);
4954
+ }
4955
+
4956
+ /**
4957
+ * The one way to build a child's source path.
4958
+ *
4959
+ * There were five hand-rolled versions of this, three of them subtly different
4960
+ * and two of them wrong, and the wrong ones were wrong in a way that hid: a
4961
+ * module path segment has to be JSON-quoted if it is a string and bare if it is
4962
+ * an array index, and both broken copies appended the raw key at the module
4963
+ * root. An unquoted key parses fine as long as it contains no `.` — so every
4964
+ * object field and every ordinary record key still resolved, and only a key with
4965
+ * a dot in it broke. That is exactly what a media gallery is keyed by, so
4966
+ * clicking a file in the Media panel navigated to
4967
+ * `?p=/public/val/red-8x8_bfbd0.png`, which `splitModulePath` reads as the two
4968
+ * segments `/public/val/red-8x8_bfbd0` and `png`, and the studio said the module
4969
+ * was not found.
4970
+ *
4971
+ * So: one function, and never a template string. `Internal.createValPathOfItem`
4972
+ * is the rule itself — `JSON.stringify` quotes a string and leaves a number
4973
+ * bare, which is precisely the module-path grammar — and everything here defers
4974
+ * to it rather than restating it.
4975
+ */
4976
+ function sourcePathOfChild(parent, key) {
4977
+ /**
4978
+ * A parent that is already `…?p=` gets the key with no separator.
4979
+ *
4980
+ * The search index walks from `moduleFilePath + "?p="` rather than from the
4981
+ * module file path, so that every path it produces has a module path — and
4982
+ * `createValPathOfItem` would see the separator and join with a `.`, giving
4983
+ * `?p=."title"`.
4984
+ */
4985
+ if (parent.endsWith(core.Internal.ModuleFilePathSep)) {
4986
+ return "".concat(parent).concat(JSON.stringify(key));
4987
+ }
4988
+ var path = core.Internal.createValPathOfItem(parent, key);
4989
+ if (path === undefined) {
4990
+ // Only when the parent is empty, which callers cannot produce: every walk
4991
+ // starts from a module file path. Thrown rather than skipped so a future
4992
+ // change that breaks that assumption is loud.
4993
+ throw new Error("Could not build a source path for '".concat(key, "' under ").concat(parent));
4994
+ }
4995
+ return path;
4996
+ }
4997
+
4998
+ /**
4999
+ * The same thing, for callers holding the module file path and module path apart.
5000
+ *
5001
+ * `ModulePath` is empty at the module root, which is the case both broken copies
5002
+ * got wrong: there is no separator in the path yet, so the key is the first
5003
+ * segment and still has to be quoted.
5004
+ */
5005
+ function concatModulePath(moduleFilePath, modulePath, key) {
5006
+ return sourcePathOfChild(modulePath ? core.Internal.joinModuleFilePathAndModulePath(moduleFilePath, modulePath) : moduleFilePath, key);
5007
+ }
5008
+
5009
+ /**
5010
+ * Traverses a schema and source pair, calling a callback for each leaf node.
5011
+ * Handles all schema types including primitives, objects, arrays, records, unions, richtext, files, images, etc.
5012
+ *
5013
+ * @param source - The JSON source data
5014
+ * @param schema - The serialized schema
5015
+ * @param path - The current source path
5016
+ * @param callback - Function called for each traversable node with { source, schema, path }
5017
+ */
5018
+ function traverseSchemaSource(source, schema, path, callback) {
5019
+ if (!(schema !== null && schema !== void 0 && schema.type)) {
5020
+ throw new Error("Schema not found for " + path);
5021
+ }
5022
+ if (source === null) {
5023
+ return;
5024
+ }
5025
+
5026
+ // An un-loaded `.jsonValues()` entry is an opaque `{_type:"json"}` marker, not
5027
+ // the value its schema describes. Skip it — its content is traversed once
5028
+ // loaded, since the sync engine substitutes it in place of the marker.
5029
+ //
5030
+ // Without this the marker falls through to whichever branch its ITEM schema
5031
+ // selects: an object/record item walks the marker's OWN keys, so an entry
5032
+ // schema with a field named `_type` or `patch_id` would index the marker's
5033
+ // internals as if they were content.
5034
+ if (core.Internal.isJson(source)) {
5035
+ return;
5036
+ }
5037
+
5038
+ // Handle primitives
5039
+ if (schema.type === "string") {
5040
+ if (typeof source === "string") {
5041
+ callback({
5042
+ source: source,
5043
+ schema: schema,
5044
+ path: path
5045
+ });
5046
+ }
5047
+ return;
5048
+ }
5049
+ if (schema.type === "number") {
5050
+ if (typeof source === "number") {
5051
+ callback({
5052
+ source: source,
5053
+ schema: schema,
5054
+ path: path
5055
+ });
5056
+ }
5057
+ return;
5058
+ }
5059
+ if (schema.type === "boolean") {
5060
+ if (typeof source === "boolean") {
5061
+ callback({
5062
+ source: source,
5063
+ schema: schema,
5064
+ path: path
5065
+ });
5066
+ }
5067
+ return;
5068
+ }
5069
+
5070
+ // Handle richtext - flatten and call callback
5071
+ if (schema.type === "richtext") {
5072
+ callback({
5073
+ source: source,
5074
+ schema: schema,
5075
+ path: path
5076
+ });
5077
+ return;
5078
+ }
5079
+
5080
+ // Handle file/image
5081
+ if (schema.type === "file" || schema.type === "image") {
5082
+ if (source && getSitemapTree._typeof(source) === "object" && "path" in source && typeof source.path === "string") {
5083
+ callback({
5084
+ source: source,
5085
+ schema: schema,
5086
+ path: path
5087
+ });
5088
+ }
5089
+ return;
5090
+ }
5091
+
5092
+ // Handle date
5093
+ if (schema.type === "date") {
5094
+ if (typeof source === "string") {
5095
+ callback({
5096
+ source: source,
5097
+ schema: schema,
5098
+ path: path
5099
+ });
5100
+ }
5101
+ return;
5102
+ }
5103
+
5104
+ // Handle dateTime
5105
+ if (schema.type === "dateTime") {
5106
+ if (typeof source === "string") {
5107
+ callback({
5108
+ source: source,
5109
+ schema: schema,
5110
+ path: path
5111
+ });
5112
+ }
5113
+ return;
5114
+ }
5115
+
5116
+ // Handle color
5117
+ if (schema.type === "color") {
5118
+ if (typeof source === "string") {
5119
+ callback({
5120
+ source: source,
5121
+ schema: schema,
5122
+ path: path
5123
+ });
5124
+ }
5125
+ return;
5126
+ }
5127
+
5128
+ // Handle code
5129
+ if (schema.type === "code") {
5130
+ if (typeof source === "string") {
5131
+ callback({
5132
+ source: source,
5133
+ schema: schema,
5134
+ path: path
5135
+ });
5136
+ }
5137
+ return;
5138
+ }
5139
+
5140
+ // Handle keyOf
5141
+ if (schema.type === "keyOf") {
5142
+ if (typeof source === "string" || typeof source === "number") {
5143
+ callback({
5144
+ source: source,
5145
+ schema: schema,
5146
+ path: path
5147
+ });
5148
+ }
5149
+ return;
5150
+ }
5151
+
5152
+ // Handle literal
5153
+ if (schema.type === "literal") {
5154
+ callback({
5155
+ source: source,
5156
+ schema: schema,
5157
+ path: path
5158
+ });
5159
+ return;
5160
+ }
5161
+
5162
+ // Handle route
5163
+ if (schema.type === "route") {
5164
+ if (typeof source === "string") {
5165
+ callback({
5166
+ source: source,
5167
+ schema: schema,
5168
+ path: path
5169
+ });
5170
+ }
5171
+ return;
5172
+ }
5173
+
5174
+ // Handle array
5175
+ if (schema.type === "array") {
5176
+ if (!Array.isArray(source)) {
5177
+ return;
5178
+ }
5179
+ if (!schema.item) {
5180
+ throw new Error("Schema (" + schema.type + ") item not found for " + path);
5181
+ }
5182
+ for (var i = 0; i < source.length; i++) {
5183
+ var subPath = sourcePathOfChild(path, i);
5184
+ traverseSchemaSource(source[i], schema.item, subPath, callback);
5185
+ }
5186
+ return;
5187
+ }
5188
+
5189
+ // Handle object, record and settings
5190
+ if (schema.type === "object" || schema.type === "record" ||
5191
+ // Settings walks like an object, and starting from the SOURCE is what makes
5192
+ // its optional keys work: an absent section has nothing to traverse.
5193
+ schema.type === "settings") {
5194
+ if (getSitemapTree._typeof(source) !== "object" || source === null || Array.isArray(source)) {
5195
+ return;
5196
+ }
5197
+ for (var key in source) {
5198
+ var _schema$items;
5199
+ var subSchema = schema.type === "record" ? schema.item : (_schema$items = schema.items) === null || _schema$items === void 0 ? void 0 : _schema$items[key];
5200
+ if (!subSchema) {
5201
+ continue;
5202
+ }
5203
+ var _subPath = sourcePathOfChild(path, key);
5204
+ traverseSchemaSource(source[key], subSchema, _subPath, callback);
5205
+ }
5206
+ return;
5207
+ }
5208
+
5209
+ // Handle union
5210
+ if (schema.type === "union") {
5211
+ var schemaKey = schema.key;
5212
+ if (typeof schemaKey === "string") {
5213
+ // Tagged union - find matching sub-schema
5214
+ if (source && getSitemapTree._typeof(source) === "object" && !Array.isArray(source) && schemaKey in source) {
5215
+ var itemKey = source[schemaKey];
5216
+ if (typeof itemKey === "string") {
5217
+ var schemaOfItem = schema.items.filter(function (item) {
5218
+ return item.type === "object";
5219
+ }).find(function (item) {
5220
+ var itemKeySchema = item.items[schemaKey];
5221
+ if ((itemKeySchema === null || itemKeySchema === void 0 ? void 0 : itemKeySchema.type) === "literal") {
5222
+ return itemKeySchema.value === itemKey;
5223
+ }
5224
+ return false;
5225
+ });
5226
+ if (schemaOfItem) {
5227
+ traverseSchemaSource(source, schemaOfItem, path, callback);
5228
+ }
5229
+ }
5230
+ }
5231
+ } else {
5232
+ // Literal union - treat as primitive
5233
+ if (typeof source === "string") {
5234
+ callback({
5235
+ source: source,
5236
+ schema: schema,
5237
+ path: path
5238
+ });
5239
+ }
5240
+ }
5241
+ return;
5242
+ }
5243
+
5244
+ // Exhaustive check
5245
+ var exhaustiveCheck = schema;
5246
+ throw new Error("Unsupported schema type: " + JSON.stringify(exhaustiveCheck));
5247
+ }
5248
+
5249
+ /**
5250
+ * Flattens richtext source to a plain string, extracting only text content.
5251
+ * Used for indexing richtext content in search.
5252
+ */
5253
+ function flattenRichText(source) {
5254
+ var res = "";
5255
+ function rec(child) {
5256
+ if (typeof child === "string") {
5257
+ res += child;
5258
+ } else {
5259
+ if (child && getSitemapTree._typeof(child) === "object" && "children" in child && Array.isArray(child.children)) {
5260
+ var _iterator = getSitemapTree._createForOfIteratorHelper(child.children),
5261
+ _step;
5262
+ try {
5263
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5264
+ var c = _step.value;
5265
+ rec(c);
5266
+ }
5267
+ } catch (err) {
5268
+ _iterator.e(err);
5269
+ } finally {
5270
+ _iterator.f();
5271
+ }
5272
+ }
5273
+ }
5274
+ }
5275
+ rec({
5276
+ children: source
5277
+ });
5278
+ return res;
5279
+ }
5280
+
5281
+ /**
5282
+ * Resolves a file ref (local path or remote URL) to a clean local-style path.
5283
+ */
5284
+ function cleanRefPath(ref) {
5285
+ var remoteRefRes = core.Internal.remote.splitRemoteRef(ref);
5286
+ return remoteRefRes.status === "success" ? "/".concat(remoteRefRes.filePath) : ref;
5287
+ }
5288
+
5289
+ /**
5290
+ * Extract a human-readable filename from a file ref (local path or remote URL).
5291
+ * Handles both remote refs (via splitRemoteRef) and plain `/public/...` paths.
5292
+ */
5293
+ function getFilenameFromRef(ref) {
5294
+ var cleanPath = cleanRefPath(ref);
5295
+ return cleanPath.split("/").pop() || cleanPath;
5296
+ }
5297
+
5298
+ /**
5299
+ * Parse a file ref into its constituent parts: a clean path, filename, and
5300
+ * folder (the path relative to `/public`).
5301
+ *
5302
+ * The `folder` strips the standard `/public` prefix so it shows a
5303
+ * concise location like `/images` instead of `/public/images`.
5304
+ */
5305
+ function getRefParts(ref) {
5306
+ var cleanPath = cleanRefPath(ref);
5307
+ var filename = cleanPath.split("/").pop() || cleanPath;
5308
+ // Only strip a leading "/public" path segment: "/publicity/a.png" must keep its folder
5309
+ var folder = cleanPath.replace(/^\/public(?=\/|$)/, "").replace(/\/[^/]+$/, "") || "/";
5310
+ return {
5311
+ cleanPath: cleanPath,
5312
+ filename: filename,
5313
+ folder: folder
5314
+ };
5315
+ }
5316
+
5317
+ /**
5318
+ * The search index and the labels to render for its hits.
5319
+ *
5320
+ * Kept as a plain module rather than living inside a worker so it can be tested:
5321
+ * a worker entry runs `self.onmessage` on import, which no test environment here
5322
+ * provides.
5323
+ *
5324
+ * In `@valbuild/shared` rather than the Studio because there are now two
5325
+ * realms searching the same content: the Studio's `SearchStore`, which keeps an
5326
+ * index alive in a worker and re-indexes a module at a time, and the MCP
5327
+ * `search_content` tool, which builds one per call and throws it away. What
5328
+ * counts as a document, and what a hit is labelled, must not differ between
5329
+ * them — an agent and an editor searching the same project should find the same
5330
+ * things.
5331
+ */
5332
+
5333
+ /** An index with nothing in it. Fill it with {@link indexModule}. */
5334
+ function createSearchIndex() {
5335
+ return {
5336
+ index: new FlexSearch__default["default"].Index({
5337
+ tokenize: "forward"
5338
+ }),
5339
+ pathToLabel: new Map(),
5340
+ docsByModule: new Map()
5341
+ };
5342
+ }
5343
+
5344
+ /**
5345
+ * Index one module, replacing whatever was previously indexed for it.
5346
+ *
5347
+ * Remove-then-add rather than `update`, because the set of paths in a module is
5348
+ * not stable: deleting an array item or a record entry means documents that must
5349
+ * disappear, and `update` only revises ids it is given.
5350
+ *
5351
+ * `.jsonValues()` entries are indexed only once their content is loaded — an
5352
+ * un-loaded entry is an opaque marker that {@link traverseSchemaSource} skips, so
5353
+ * the index is naturally PARTIAL and grows as batches land. That is why the search
5354
+ * UI loads the entries on the first query and re-indexes (debounced) as they
5355
+ * arrive, rather than pretending an empty result set is an answer.
5356
+ */
5357
+ function indexModule(searchIndex, moduleFilePath, source, schema) {
5358
+ var index = searchIndex.index,
5359
+ pathToLabel = searchIndex.pathToLabel,
5360
+ docsByModule = searchIndex.docsByModule;
5361
+ removeModule(searchIndex, moduleFilePath);
5362
+ var docs = new Set();
5363
+ docsByModule.set(moduleFilePath, docs);
5364
+ var path = moduleFilePath + "?p=";
5365
+ traverseSchemaSource(source, schema, path, function (_ref) {
5366
+ var source = _ref.source,
5367
+ schema = _ref.schema,
5368
+ path = _ref.path;
5369
+ if (source === null) {
5370
+ return;
5371
+ }
5372
+ var searchText = "";
5373
+ var label = "";
5374
+
5375
+ // Handle primitives
5376
+ if (schema.type === "string" || schema.type === "number" || schema.type === "boolean" || schema.type === "date" || schema.type === "dateTime" || schema.type === "color" || schema.type === "code" || schema.type === "keyOf" || schema.type === "route") {
5377
+ var _source$toString, _source$toString2;
5378
+ searchText = (_source$toString = source === null || source === void 0 ? void 0 : source.toString()) !== null && _source$toString !== void 0 ? _source$toString : "";
5379
+ label = (_source$toString2 = source === null || source === void 0 ? void 0 : source.toString()) !== null && _source$toString2 !== void 0 ? _source$toString2 : "";
5380
+ } else if (schema.type === "literal") {
5381
+ searchText = schema.value.toString();
5382
+ label = schema.value.toString();
5383
+ }
5384
+ // Handle richtext - flatten to get text content
5385
+ else if (schema.type === "richtext") {
5386
+ searchText = flattenRichText(source);
5387
+ // Use first 50 chars as label
5388
+ label = searchText.substring(0, 50) || "richtext";
5389
+ }
5390
+ // Handle file/image
5391
+ else if (schema.type === "file" || schema.type === "image") {
5392
+ if (source !== null && getSitemapTree._typeof(source) === "object" && "path" in source && typeof source.path === "string") {
5393
+ // The label is the bare filename - the folder is shown separately in
5394
+ // the UI - but both are searchable.
5395
+ var _getRefParts = getRefParts(source.path),
5396
+ filename = _getRefParts.filename,
5397
+ folder = _getRefParts.folder;
5398
+ var alt = "alt" in source ? source.alt : "";
5399
+ searchText = filename + " " + folder + " " + alt;
5400
+ label = filename;
5401
+ }
5402
+ }
5403
+
5404
+ // Add to index if we have search text
5405
+ if (searchText) {
5406
+ var _Internal$splitModule = core.Internal.splitModuleFilePathAndModulePath(path),
5407
+ _Internal$splitModule2 = _slicedToArray(_Internal$splitModule, 2),
5408
+ modulePath = _Internal$splitModule2[1];
5409
+ var cleanPath = fastRemoveNonWordChars(modulePath) + " ";
5410
+ index.add(path, cleanPath + " " + path + " " + searchText);
5411
+ pathToLabel.set(path, label);
5412
+ docs.add(path);
5413
+ }
5414
+ });
5415
+ }
5416
+
5417
+ /**
5418
+ * Drop everything indexed for one module.
5419
+ *
5420
+ * Also used for a module that has gone away entirely — otherwise its documents
5421
+ * stay searchable and a hit navigates to a path that no longer exists.
5422
+ */
5423
+ function removeModule(searchIndex, moduleFilePath) {
5424
+ var index = searchIndex.index,
5425
+ pathToLabel = searchIndex.pathToLabel,
5426
+ docsByModule = searchIndex.docsByModule;
5427
+ var existing = docsByModule.get(moduleFilePath);
5428
+ if (existing === undefined) return;
5429
+ var _iterator = getSitemapTree._createForOfIteratorHelper(existing),
5430
+ _step;
5431
+ try {
5432
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5433
+ var id = _step.value;
5434
+ index.remove(id);
5435
+ pathToLabel["delete"](id);
5436
+ }
5437
+ } catch (err) {
5438
+ _iterator.e(err);
5439
+ } finally {
5440
+ _iterator.f();
5441
+ }
5442
+ docsByModule["delete"](moduleFilePath);
5443
+ }
5444
+
5445
+ /**
5446
+ * Index every module, from scratch.
5447
+ *
5448
+ * Now a loop over {@link indexModule} rather than its own walk, so the full
5449
+ * build and the incremental one cannot drift in what they consider a document.
5450
+ */
5451
+ function buildSearchIndex(modules) {
5452
+ var searchIndex = createSearchIndex();
5453
+ for (var moduleFilePathS in modules) {
5454
+ var moduleFilePath = moduleFilePathS;
5455
+ var _modules$moduleFilePa = modules[moduleFilePath],
5456
+ source = _modules$moduleFilePa.source,
5457
+ schema = _modules$moduleFilePa.schema;
5458
+ indexModule(searchIndex, moduleFilePath, source, schema);
5459
+ }
5460
+ return searchIndex;
5461
+ }
5462
+ var NON_CHARS = new Set(["/", "-", "_", ".", ":", "?", "&", "=", "@", '"', "'"]);
5463
+ function fastRemoveNonWordChars(str) {
5464
+ var result = "";
5465
+ for (var i = 0; i < str.length; i++) {
5466
+ var _char = str[i];
5467
+ if (!NON_CHARS.has(_char)) {
5468
+ result += _char;
5469
+ } else {
5470
+ result += " ";
5471
+ }
5472
+ }
5473
+ return result;
5474
+ }
5475
+
5476
+ /**
5477
+ * How many hits are counted before `total` stops being a count.
5478
+ *
5479
+ * FlexSearch stops as soon as it has the number of ids it was asked for, so a
5480
+ * `total` taken from a page-sized search is just the page size again — which
5481
+ * reads as "that is all there is" to anyone who did not write it. Counting is
5482
+ * asking for more ids than the page needs, so it costs an array of ids and no
5483
+ * more; this bound is where that stops being free, and `totalIsLowerBound` says
5484
+ * it was reached rather than letting the number quietly lie.
5485
+ */
5486
+ var MAX_COUNTED_RESULTS = 10000;
5487
+ function performSearch(searchIndex, query) {
5488
+ var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
5489
+ var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
5490
+ if (searchIndex === null || !query.trim()) {
5491
+ return {
5492
+ results: [],
5493
+ total: 0,
5494
+ totalIsLowerBound: false
5495
+ };
5496
+ }
5497
+ var index = searchIndex.index,
5498
+ pathToLabel = searchIndex.pathToLabel;
5499
+ var counted = Math.max(offset + limit, MAX_COUNTED_RESULTS);
5500
+ var searchResults = index.search(query, {
5501
+ limit: counted
5502
+ });
5503
+ var total = searchResults.length;
5504
+ var paged = searchResults.slice(offset, offset + limit);
5505
+ return {
5506
+ results: paged.map(function (id) {
5507
+ return {
5508
+ path: id,
5509
+ label: pathToLabel.get(id) || id
5510
+ };
5511
+ }),
5512
+ total: total,
5513
+ totalIsLowerBound: total >= counted
5514
+ };
5515
+ }
5516
+
5517
+ exports.VAL_AI_SESSION_STORAGE_KEY = getSitemapTree.VAL_AI_SESSION_STORAGE_KEY;
5518
+ exports.VAL_CANVAS_MESSAGE = getSitemapTree.VAL_CANVAS_MESSAGE;
5519
+ exports.VAL_CANVAS_PARAM = getSitemapTree.VAL_CANVAS_PARAM;
5520
+ exports.VAL_CONFIG_SESSION_STORAGE_KEY = getSitemapTree.VAL_CONFIG_SESSION_STORAGE_KEY;
5521
+ exports.VAL_THEME_SESSION_STORAGE_KEY = getSitemapTree.VAL_THEME_SESSION_STORAGE_KEY;
5522
+ exports.getNextAppRouterSitemapTree = getSitemapTree.getNextAppRouterSitemapTree;
5523
+ exports.getNextAppRouterSourceFolder = getSitemapTree.getNextAppRouterSourceFolder;
5524
+ exports.getPatternFromModuleFilePath = getSitemapTree.getPatternFromModuleFilePath;
5525
+ exports.isValCanvasFrame = getSitemapTree.isValCanvasFrame;
5526
+ exports.isValCanvasPageMessage = getSitemapTree.isValCanvasPageMessage;
5527
+ exports.isValCanvasStudioMessage = getSitemapTree.isValCanvasStudioMessage;
5528
+ exports.parseRoutePattern = getSitemapTree.parseRoutePattern;
5529
+ exports.withValCanvasParam = getSitemapTree.withValCanvasParam;
5171
5530
  exports.Api = Api;
5172
5531
  exports.BinaryFileRef = BinaryFileRef;
5173
5532
  exports.CodeOptions = CodeOptions;
5174
5533
  exports.ColorOptions = ColorOptions;
5175
5534
  exports.DEFAULT_ERROR_MESSAGE = DEFAULT_ERROR_MESSAGE;
5176
5535
  exports.DateOptions = DateOptions;
5536
+ exports.ENCODE_DEFAULTS = ENCODE_DEFAULTS;
5537
+ exports.ENCODE_MIME_TYPE_OF = ENCODE_MIME_TYPE_OF;
5177
5538
  exports.FileOptions = FileOptions;
5178
5539
  exports.HistoricalCommit = HistoricalCommit;
5179
5540
  exports.HistoricalModule = HistoricalModule;
@@ -5184,6 +5545,7 @@ exports.ImageOptions = ImageOptions;
5184
5545
  exports.JSONValue = JSONValue;
5185
5546
  exports.JSON_ENTRIES_BATCH_MAX = JSON_ENTRIES_BATCH_MAX;
5186
5547
  exports.ModuleComparison = ModuleComparison;
5548
+ exports.NEVER_ENCODED = NEVER_ENCODED;
5187
5549
  exports.ParentRef = ParentRef$1;
5188
5550
  exports.Patch = Patch;
5189
5551
  exports.PatchBlock = PatchBlock;
@@ -5223,14 +5585,9 @@ exports.SerializedSettingsSchema = SerializedSettingsSchema;
5223
5585
  exports.SerializedStringSchema = SerializedStringSchema;
5224
5586
  exports.SerializedUnionSchema = SerializedUnionSchema;
5225
5587
  exports.SharedValConfig = SharedValConfig;
5226
- exports.VAL_AI_SESSION_STORAGE_KEY = VAL_AI_SESSION_STORAGE_KEY;
5227
- exports.VAL_CANVAS_MESSAGE = VAL_CANVAS_MESSAGE;
5228
- exports.VAL_CANVAS_PARAM = VAL_CANVAS_PARAM;
5229
- exports.VAL_CONFIG_SESSION_STORAGE_KEY = VAL_CONFIG_SESSION_STORAGE_KEY;
5230
5588
  exports.VAL_ENABLE_COOKIE_NAME = VAL_ENABLE_COOKIE_NAME;
5231
5589
  exports.VAL_SESSION_COOKIE = VAL_SESSION_COOKIE;
5232
5590
  exports.VAL_STATE_COOKIE = VAL_STATE_COOKIE;
5233
- exports.VAL_THEME_SESSION_STORAGE_KEY = VAL_THEME_SESSION_STORAGE_KEY;
5234
5591
  exports.ValCommit = ValCommit;
5235
5592
  exports.ValDeployment = ValDeployment;
5236
5593
  exports.buildDuplicatePatch = buildDuplicatePatch;
@@ -5238,8 +5595,12 @@ exports.buildEmptyAtPathPatch = buildEmptyAtPathPatch;
5238
5595
  exports.buildFileRefValue = buildFileRefValue;
5239
5596
  exports.buildImageGalleryPatch = buildImageGalleryPatch;
5240
5597
  exports.buildRemoveImageGalleryEntryPatch = buildRemoveImageGalleryEntryPatch;
5598
+ exports.buildSearchIndex = buildSearchIndex;
5241
5599
  exports.checkCompatibility = checkCompatibility;
5600
+ exports.chooseEncoded = chooseEncoded;
5601
+ exports.concatModulePath = concatModulePath;
5242
5602
  exports.createRegExpFromPattern = createRegExpFromPattern;
5603
+ exports.createSearchIndex = createSearchIndex;
5243
5604
  exports.createValClient = createValClient;
5244
5605
  exports.describeContainerAtPath = describeContainerAtPath;
5245
5606
  exports.emptyOf = emptyOf;
@@ -5247,29 +5608,34 @@ exports.explainIncompatible = explainIncompatible;
5247
5608
  exports.filterBlockingValidationErrors = filterBlockingValidationErrors;
5248
5609
  exports.filterRoutesByPatterns = filterRoutesByPatterns;
5249
5610
  exports.findSimilar = findSimilar;
5611
+ exports.fitWithin = fitWithin;
5612
+ exports.flattenRichText = flattenRichText;
5250
5613
  exports.getErrorMessageFromUnknownJson = getErrorMessageFromUnknownJson;
5614
+ exports.getFilenameFromRef = getFilenameFromRef;
5251
5615
  exports.getInlineImgInfo = getInlineImgInfo;
5252
- exports.getNextAppRouterSitemapTree = getNextAppRouterSitemapTree;
5253
- exports.getNextAppRouterSourceFolder = getNextAppRouterSourceFolder;
5254
- exports.getPatternFromModuleFilePath = getPatternFromModuleFilePath;
5616
+ exports.getRefParts = getRefParts;
5255
5617
  exports.getRoutesOf = getRoutesOf;
5256
5618
  exports.getRoutesWithModulePaths = getRoutesWithModulePaths;
5257
5619
  exports.getSourceAt = getSourceAt;
5620
+ exports.indexModule = indexModule;
5621
+ exports.isMimeTypeAccepted = isMimeTypeAccepted;
5258
5622
  exports.isRemoteSchema = isRemoteSchema;
5259
- exports.isValCanvasFrame = isValCanvasFrame;
5260
- exports.isValCanvasPageMessage = isValCanvasPageMessage;
5261
- exports.isValCanvasStudioMessage = isValCanvasStudioMessage;
5623
+ exports.isSkippedSource = isSkippedSource;
5262
5624
  exports.levenshtein = levenshtein;
5263
5625
  exports.newestCommitSha = newestCommitSha;
5264
- exports.parseRoutePattern = parseRoutePattern;
5265
5626
  exports.partitionValidationErrors = partitionValidationErrors;
5627
+ exports.performSearch = performSearch;
5266
5628
  exports.remirrorToRichTextSource = remirrorToRichTextSource;
5629
+ exports.removeModule = removeModule;
5630
+ exports.resolveEncodeSettings = resolveEncodeSettings;
5267
5631
  exports.resolveSchemaSourceFixForError = resolveSchemaSourceFixForError;
5268
5632
  exports.resolveSchemaSourceFixes = resolveSchemaSourceFixes;
5269
5633
  exports.resolveSerializedSchemaAtPath = resolveSerializedSchemaAtPath;
5270
5634
  exports.richTextToRemirror = richTextToRemirror;
5271
5635
  exports.safeParsePatch = safeParsePatch;
5636
+ exports.sourcePathOfChild = sourcePathOfChild;
5272
5637
  exports.toolNames = toolNames;
5638
+ exports.traverseSchemaSource = traverseSchemaSource;
5273
5639
  exports.urlOf = urlOf;
5274
5640
  exports.validateRoutePatterns = validateRoutePatterns;
5275
- exports.withValCanvasParam = withValCanvasParam;
5641
+ exports.withExtension = withExtension;