@unbase-app/cli 0.4.0 → 0.4.1

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.
package/lib/readers.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // ============================================================================
2
+ // @ts-nocheck: bundled from the Edge Functions, typed and checked where they are written.
2
3
  // GENERATED by kit/cli/scripts/readers.mjs; do not edit. Regenerate with
3
4
  // node kit/cli/scripts/readers.mjs
4
5
  //
@@ -8,6 +9,7 @@
8
9
  // registryOf supabase/functions/unbase-projects/pages.ts (list_pages)
9
10
  // core supabase/functions/_shared/pages-core.mjs (= kit/pages/core.mjs)
10
11
  // csp supabase/functions/_shared/csp.ts (analytics' collector in a CSP)
12
+ // binding supabase/functions/_shared/binding.mjs (= kit/pages/binding.mjs, the binding contract's checks)
11
13
  // ============================================================================
12
14
  var __defProp = Object.defineProperty;
13
15
  var __export = (target, all) => {
@@ -90,15 +92,15 @@ async function textLocation(repo, app, files) {
90
92
  const g = groupOf(page);
91
93
  groups.set(g, [...groups.get(g) ?? [], page]);
92
94
  }
93
- const literal = /* @__PURE__ */ new Map();
95
+ const literal2 = /* @__PURE__ */ new Map();
94
96
  await Promise.all(
95
97
  spread(groups, PAGE_CAP).map(async (page) => {
96
98
  const source = await repo.read(join(app.path, `src/pages/${page}`));
97
- if (source !== null) literal.set(page, literalText(source));
99
+ if (source !== null) literal2.set(page, literalText(source));
98
100
  })
99
101
  );
100
102
  const result = [...groups].map(([group, list]) => {
101
- const total = list.reduce((sum, p) => sum + (literal.get(p) ?? 0), 0);
103
+ const total = list.reduce((sum, p) => sum + (literal2.get(p) ?? 0), 0);
102
104
  return { group, pages: list.length, literal: total, in: total > LITERAL_IN_CODE ? "code" : "content" };
103
105
  });
104
106
  const inCode = result.filter((g) => g.in === "code").length;
@@ -233,6 +235,13 @@ var LOCKFILES = [
233
235
  ["bun.lockb", "bun"]
234
236
  ];
235
237
  var PACKAGE_JSON_CAP = 30;
238
+ var HOST_SIGNS = ["netlify.toml", "wrangler.toml", "wrangler.json", "wrangler.jsonc", "firebase.json", "render.yaml", "fly.toml", "CNAME", "public/CNAME", "static/CNAME", "static.json"];
239
+ function otherHostOf(paths, appPath) {
240
+ const has = new Set(paths);
241
+ const folders = appPath ? ["", `${appPath.replace(/\/+$/, "")}/`] : [""];
242
+ for (const folder of folders) for (const sign of HOST_SIGNS) if (has.has(folder + sign)) return folder + sign;
243
+ return null;
244
+ }
236
245
  function versionOf(range) {
237
246
  const m = /(\d+)(\.\d+)?(\.\d+)?/.exec(range ?? "");
238
247
  return m ? { version: m[0], major: Number(m[1]) } : { version: null, major: null };
@@ -382,7 +391,8 @@ async function detect(repo, branch, truncated, appPath) {
382
391
  settings: [],
383
392
  settings_truncated: false,
384
393
  services: [],
385
- image_hosts: []
394
+ image_hosts: [],
395
+ other_host: otherHostOf(repo.paths, null)
386
396
  };
387
397
  let chosen;
388
398
  if (appPath !== void 0) {
@@ -416,7 +426,8 @@ async function detect(repo, branch, truncated, appPath) {
416
426
  settings,
417
427
  settings_truncated: settingsTruncated,
418
428
  services: servicesOf(chosen, root),
419
- image_hosts: imageHosts
429
+ image_hosts: imageHosts,
430
+ other_host: otherHostOf(repo.paths, chosen.path)
420
431
  };
421
432
  }
422
433
 
@@ -549,6 +560,7 @@ __export(pages_core_exports, {
549
560
  draftCheck: () => draftCheck,
550
561
  draftPaths: () => draftPaths,
551
562
  draftPlan: () => draftPlan,
563
+ folderPaths: () => folderPaths,
552
564
  importGraph: () => importGraph,
553
565
  kitFiles: () => kitFiles,
554
566
  kitInstalled: () => kitInstalled,
@@ -564,11 +576,13 @@ __export(pages_core_exports, {
564
576
  pageActions: () => pageActions,
565
577
  parsePageFile: () => parsePageFile,
566
578
  planPage: () => planPage,
579
+ planRedirect: () => planRedirect,
567
580
  redirectsFor: () => redirectsFor,
568
581
  removeRoutes: () => removeRoutes,
569
582
  resolveImport: () => resolveImport,
570
583
  segmentFiles: () => segmentFiles,
571
584
  sentences: () => sentences,
585
+ siteRedirectList: () => siteRedirectList,
572
586
  siteRedirects: () => siteRedirects,
573
587
  slugOf: () => slugOf,
574
588
  stripComments: () => stripComments,
@@ -595,11 +609,14 @@ function normalisePath(p) {
595
609
  return s || "/";
596
610
  }
597
611
  function parsePageFile(text) {
598
- if (text == null) return { ok: true, exists: false, pages: {}, redirects: {} };
612
+ if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
599
613
  const fail = (error) => ({ ok: (
600
614
  /** @type {const} */
601
615
  false
602
- ), exists: true, error, pages: {}, redirects: {} });
616
+ ), exists: (
617
+ /** @type {const} */
618
+ true
619
+ ), error, pages: {}, folders: {}, redirects: {} });
603
620
  let data;
604
621
  try {
605
622
  data = JSON.parse(text);
@@ -617,6 +634,14 @@ function parsePageFile(text) {
617
634
  if (entry.name !== void 0 && typeof entry.name !== "string") return fail(`${address2}: name is text`);
618
635
  out[normalisePath(address2)] = { ...entry.draft === void 0 ? {} : { draft: entry.draft }, ...entry.name ? { name: entry.name } : {} };
619
636
  }
637
+ const folderData = data.folders ?? {};
638
+ if (!isObject(folderData)) return fail("`folders` is not an object");
639
+ const folders = {};
640
+ for (const [address2, entry] of Object.entries(folderData)) {
641
+ if (!address2.startsWith("/")) return fail(`folders: ${address2}: an address starts with /`);
642
+ if (!isObject(entry) || entry.name !== void 0 && typeof entry.name !== "string") return fail(`folders: ${address2}: name is text`);
643
+ if (entry.name) folders[normalisePath(address2)] = { name: entry.name };
644
+ }
620
645
  const redirects = data.redirects ?? {};
621
646
  if (!isObject(redirects)) return fail("`redirects` is not an object");
622
647
  const sends2 = {};
@@ -626,7 +651,7 @@ function parsePageFile(text) {
626
651
  if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
627
652
  sends2[normalisePath(from)] = normalisePath(to);
628
653
  }
629
- return { ok: true, exists: true, pages: out, redirects: sends2 };
654
+ return { ok: true, exists: true, pages: out, folders, redirects: sends2 };
630
655
  }
631
656
  var REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
632
657
  var draftPaths = (file) => Object.keys(file.pages).filter((p) => file.pages[p].draft === true).sort();
@@ -664,14 +689,23 @@ function stringEnd(src, i) {
664
689
  function stripComments(src) {
665
690
  let out = "";
666
691
  let i = 0;
692
+ const special = /\/[/*]|["'`]/g;
667
693
  while (i < src.length) {
694
+ special.lastIndex = i;
695
+ const next = special.exec(src);
696
+ const to = next ? next.index : src.length;
697
+ if (to > i) {
698
+ out += src.slice(i, to);
699
+ i = to;
700
+ continue;
701
+ }
668
702
  const c = src[i];
669
703
  const d = src[i + 1];
670
704
  if (c === "/" && d === "/") {
671
- while (i < src.length && src[i] !== "\n") {
672
- out += " ";
673
- i++;
674
- }
705
+ const end = src.indexOf("\n", i);
706
+ const stop = end < 0 ? src.length : end;
707
+ out += " ".repeat(stop - i);
708
+ i = stop;
675
709
  continue;
676
710
  }
677
711
  if (c === "/" && d === "*") {
@@ -752,6 +786,17 @@ function astroPages(paths) {
752
786
  }
753
787
  return out;
754
788
  }
789
+ function htmlPages(paths) {
790
+ const out = [];
791
+ for (const p of paths) {
792
+ if (!p.endsWith(".html") || p === "404.html") continue;
793
+ const segments = p.split("/");
794
+ if (segments.some((s) => s.startsWith("."))) continue;
795
+ if (segments.at(-1) === "index.html") segments.pop();
796
+ out.push({ path: address(segments), kind: "file", file: p });
797
+ }
798
+ return out;
799
+ }
755
800
  function nextPages(paths) {
756
801
  const out = [];
757
802
  const ext = /\.(tsx|ts|jsx|js|mdx|md)$/;
@@ -891,14 +936,26 @@ function removeRoutes({ file, code, paths, text, drop }) {
891
936
  }
892
937
  function discover({ framework, paths, text }) {
893
938
  const kept = paths.filter((p) => !SKIP2.test(p));
894
- const found = framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : { pages: [], notFound: null };
939
+ const found = framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : framework === "html" ? { pages: htmlPages(kept), notFound: null } : { pages: [], notFound: null };
895
940
  const seen = /* @__PURE__ */ new Set();
896
941
  const pages = found.pages.filter((p) => seen.has(p.path) ? false : (seen.add(p.path), true)).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
897
942
  return { pages, notFound: found.notFound };
898
943
  }
899
944
  var CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
900
945
  var CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
901
- var COLLECTIONS = "src/content/.schemas/collecties.json";
946
+ var COLLECTIONS = "src/content/.schemas/collections.json";
947
+ var LEGACY_COLLECTIONS = "src/content/.schemas/collecties.json";
948
+ function readCollections(text) {
949
+ let out = null;
950
+ for (const p of [LEGACY_COLLECTIONS, COLLECTIONS]) {
951
+ try {
952
+ const d = JSON.parse(text(p) ?? "null");
953
+ if (isObject(d)) out = { ...out ?? {}, ...d };
954
+ } catch {
955
+ }
956
+ }
957
+ return out;
958
+ }
902
959
  function contentNames(paths, text) {
903
960
  const files = /* @__PURE__ */ new Map();
904
961
  const add = (name, f) => {
@@ -907,7 +964,7 @@ function contentNames(paths, text) {
907
964
  };
908
965
  let collections = {};
909
966
  try {
910
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
967
+ collections = readCollections(text) ?? {};
911
968
  } catch {
912
969
  }
913
970
  for (const f of paths) {
@@ -935,62 +992,102 @@ function ownCode(page, importers, imports) {
935
992
  return own;
936
993
  }
937
994
  var ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
995
+ var ASTRO_NAMED = /getCollection|getEntry|getEntries/;
938
996
  function contentReads(paths, text) {
939
- const code = /* @__PURE__ */ new Map();
997
+ const files = [];
940
998
  for (const p of paths) {
941
999
  if (!CODE.test(p) || SKIP2.test(p)) continue;
942
1000
  const src = text(p);
943
- if (src) code.set(p, stripComments(src));
1001
+ if (src) files.push([p, src]);
944
1002
  }
1003
+ const picked = /* @__PURE__ */ new Set();
1004
+ const asked = new Set(ASTRO_READS);
1005
+ const parsed = /* @__PURE__ */ new Map();
1006
+ let names = ASTRO_READS;
1007
+ let reads2 = null;
1008
+ for (; ; ) {
1009
+ let grew = false;
1010
+ if (names.length) {
1011
+ const naming = new RegExp(names.map(escape).join("|"));
1012
+ for (const [p, src] of files) {
1013
+ if (picked.has(p) || !naming.test(src)) continue;
1014
+ picked.add(p);
1015
+ grew = true;
1016
+ }
1017
+ }
1018
+ if (reads2 && !grew) return { ...reads2, files };
1019
+ reads2 = readsOver(files.filter(([p]) => picked.has(p)), parsed);
1020
+ names = [...reads2.byName, ...reads2.fixed.keys()].filter((n) => !asked.has(n));
1021
+ names.forEach((n) => asked.add(n));
1022
+ if (!names.length) return { ...reads2, files };
1023
+ }
1024
+ }
1025
+ var DIRECT = new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1026
+ var FUNCTION = /(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::[^=]*)?=>/g;
1027
+ function parseCode(p, src) {
1028
+ const code = stripComments(src);
1029
+ const fns = [];
1030
+ if (!/\.(ts|mts|js|mjs)$/.test(p)) return { code, fns };
1031
+ for (const m of code.matchAll(FUNCTION)) {
1032
+ const name = m[1] ?? m[3];
1033
+ const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
1034
+ let at3 = m.index + m[0].length;
1035
+ while (/\s/.test(code[at3] ?? "")) at3++;
1036
+ const block = code.indexOf("{", at3);
1037
+ const braces = code[at3] === "{" ? at3 : m[1] && block > 0 ? block : -1;
1038
+ const body = braces >= 0 ? braced(code, braces) ?? "" : code.slice(at3, code.slice(at3).search(/;|\n\s*\n|$/) + at3);
1039
+ const start = braces >= 0 ? braces + 1 : at3;
1040
+ const naming = ASTRO_NAMED.test(body);
1041
+ const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
1042
+ const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : void 0;
1043
+ const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
1044
+ fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
1045
+ }
1046
+ return { code, fns };
1047
+ }
1048
+ function readsOver(files, parsed = /* @__PURE__ */ new Map()) {
1049
+ const code = /* @__PURE__ */ new Map();
945
1050
  const astro2 = ASTRO_READS.join("|");
946
1051
  const byName = new Set(ASTRO_READS);
947
1052
  const entryOf = /* @__PURE__ */ new Map();
948
- const fixed = /* @__PURE__ */ new Map();
1053
+ const fixed2 = /* @__PURE__ */ new Map();
949
1054
  const bodies = /* @__PURE__ */ new Map();
950
1055
  const spans = /* @__PURE__ */ new Map();
951
- const DIRECT = new RegExp(`\\b(?:${astro2})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
952
1056
  const addFixed = (name, whole, entry) => {
953
- if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
954
- if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
955
- else fixed.get(name).whole.add(whole);
1057
+ if (!fixed2.has(name)) fixed2.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
1058
+ if (entry) fixed2.get(name).entries.add(`${whole}/${entry}`);
1059
+ else fixed2.get(name).whole.add(whole);
956
1060
  };
957
- for (const [p, src] of code) {
958
- if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
959
- for (const m of src.matchAll(/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::[^=]*)?=>/g)) {
960
- const name = m[1] ?? m[3];
961
- const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
962
- let at2 = m.index + m[0].length;
963
- while (/\s/.test(src[at2] ?? "")) at2++;
964
- const block = src.indexOf("{", at2);
965
- const braces = src[at2] === "{" ? at2 : m[1] && block > 0 ? block : -1;
966
- const body = braces >= 0 ? braced(src, braces) ?? "" : src.slice(at2, src.slice(at2).search(/;|\n\s*\n|$/) + at2);
967
- const start = braces >= 0 ? braces + 1 : at2;
1061
+ for (const [p, src] of files) {
1062
+ if (!parsed.has(p)) parsed.set(p, parseCode(p, src));
1063
+ const file = parsed.get(p);
1064
+ code.set(p, file.code);
1065
+ for (const fn of file.fns) {
968
1066
  if (!spans.has(p)) spans.set(p, []);
969
- spans.get(p).push([start, start + body.length]);
970
- if (first && new RegExp(`\\b(?:${astro2})\\(\\s*${escape(first)}\\b`).test(body)) {
971
- byName.add(name);
972
- const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
973
- if (entry) entryOf.set(name, entry);
1067
+ spans.get(p).push([fn.start, fn.end]);
1068
+ if (fn.byName) {
1069
+ byName.add(fn.name);
1070
+ if (fn.entry) entryOf.set(fn.name, fn.entry);
974
1071
  }
975
- bodies.set(name, body);
976
- for (const d of body.matchAll(DIRECT)) addFixed(name, d[1], d[2]);
1072
+ bodies.set(fn.name, fn.body);
1073
+ for (const [whole, entry] of fn.direct) addFixed(fn.name, whole, entry);
977
1074
  }
978
1075
  }
979
1076
  for (const [name, body] of bodies) {
980
1077
  for (const fn of byName) {
981
- if (fn === name || ASTRO_READS.includes(fn)) continue;
1078
+ if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
982
1079
  for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
983
1080
  }
984
1081
  }
985
- const calls = new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))]));
1082
+ const calls = fixed2.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : /* @__PURE__ */ new Map();
986
1083
  for (let grew = true; grew; ) {
987
1084
  grew = false;
988
1085
  for (const [name, called] of calls) {
989
1086
  for (const other of called) {
990
- const read = fixed.get(other);
1087
+ const read = fixed2.get(other);
991
1088
  if (other === name || !read) continue;
992
- if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
993
- const mine = fixed.get(name);
1089
+ if (!fixed2.has(name)) fixed2.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
1090
+ const mine = fixed2.get(name);
994
1091
  const before = mine.whole.size + mine.entries.size;
995
1092
  read.whole.forEach((c) => mine.whole.add(c));
996
1093
  read.entries.forEach((e) => mine.entries.add(e));
@@ -998,45 +1095,45 @@ function contentReads(paths, text) {
998
1095
  }
999
1096
  }
1000
1097
  }
1098
+ const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
1001
1099
  const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1002
- return { code, byName, byNameCall, entryOf, fixed, astro: astro2, spans };
1100
+ return { code, byName, byNameCall, entryOf, fixed: fixed2, astro: astro2, spans, helpers };
1003
1101
  }
1004
1102
  var CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
1005
- var IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
1006
1103
  var DEFINITION = /function\s+([A-Za-z_$][\w$]*)|const\s+([A-Za-z_$][\w$]*)\s*=/g;
1007
1104
  function blankRanges(src, ranges) {
1008
1105
  if (!ranges.length) return src;
1009
1106
  let out = "";
1010
- let at2 = 0;
1107
+ let at3 = 0;
1011
1108
  for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
1012
- if (end <= at2) continue;
1013
- const from = Math.max(start, at2);
1014
- out += src.slice(at2, from) + blank(src.slice(from, end));
1015
- at2 = end;
1109
+ if (end <= at3) continue;
1110
+ const from = Math.max(start, at3);
1111
+ out += src.slice(at3, from) + blank(src.slice(from, end));
1112
+ at3 = end;
1016
1113
  }
1017
- return out + src.slice(at2);
1114
+ return out + src.slice(at3);
1018
1115
  }
1019
1116
  var IMPORT_STATEMENT = /\bimport\s+(?:type\s+)?[\s\S]*?\bfrom\s*["'][^"'\n]+["']/g;
1020
1117
  var blank = (s) => s.replace(/[^\n]/g, " ");
1021
- function readsIn(src, reads, path = null) {
1022
- const code = blankRanges(src, reads.spans?.get(path) ?? []).replace(IMPORT_STATEMENT, blank);
1118
+ function readsIn(src, reads2, path = null) {
1119
+ const code = blankRanges(src, reads2.spans?.get(path) ?? []).replace(IMPORT_STATEMENT, blank);
1023
1120
  const names = /* @__PURE__ */ new Set();
1024
1121
  const entries = /* @__PURE__ */ new Set();
1025
1122
  const whole = /* @__PURE__ */ new Set();
1026
1123
  const helped = /* @__PURE__ */ new Set();
1027
- for (const m of code.matchAll(reads.byNameCall)) {
1124
+ for (const m of code.matchAll(reads2.byNameCall)) {
1028
1125
  const [, fn, first, entry, other] = m;
1029
- if (reads.entryOf?.has(fn)) entries.add(`${first}/${reads.entryOf.get(fn)}`);
1126
+ if (reads2.entryOf?.has(fn)) entries.add(`${first}/${reads2.entryOf.get(fn)}`);
1030
1127
  else if (entry) entries.add(`${first}/${entry}`);
1031
1128
  else if (other && ASTRO_READS.includes(fn)) whole.add(first);
1032
1129
  else if (fn === "getCollection") whole.add(first);
1033
1130
  else names.add(first);
1034
1131
  }
1035
1132
  const mentions = /* @__PURE__ */ new Map();
1036
- for (const [name] of code.matchAll(IDENTIFIER)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
1133
+ if (reads2.helpers) for (const [name] of code.matchAll(reads2.helpers)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
1037
1134
  const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
1038
1135
  for (const [name, n] of mentions) {
1039
- const read = reads.fixed.get(name);
1136
+ const read = reads2.fixed.get(name);
1040
1137
  if (!read || n - (defined.has(name) ? 1 : 0) <= 0) continue;
1041
1138
  read.whole.forEach((c) => whole.add(c));
1042
1139
  read.entries.forEach((e) => helped.add(e));
@@ -1049,12 +1146,16 @@ function siteReads(paths, text, importers) {
1049
1146
  if (kept) return kept;
1050
1147
  let collections = {};
1051
1148
  try {
1052
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
1149
+ collections = readCollections(text) ?? {};
1053
1150
  } catch {
1054
1151
  }
1055
- const reads = contentReads(paths, text);
1152
+ const reads2 = contentReads(paths, text);
1056
1153
  const readsByFile = /* @__PURE__ */ new Map();
1057
- for (const [p, src] of reads.code) if (!CONTENT_CONFIG.test(p)) readsByFile.set(p, readsIn(src, reads, p));
1154
+ for (const [p] of reads2.files) {
1155
+ if (CONTENT_CONFIG.test(p)) continue;
1156
+ const code = reads2.code.get(p);
1157
+ readsByFile.set(p, code === void 0 ? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set(), whole: /* @__PURE__ */ new Set(), helped: /* @__PURE__ */ new Set() } : readsIn(code, reads2, p));
1158
+ }
1058
1159
  const counts = { names: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map(), whole: /* @__PURE__ */ new Map() };
1059
1160
  const count = (kind, keys) => keys.forEach((k) => counts[kind].set(k, (counts[kind].get(k) ?? 0) + 1));
1060
1161
  for (const r of readsByFile.values()) {
@@ -1091,7 +1192,7 @@ function siteReads(paths, text, importers) {
1091
1192
  if (target.endsWith(".json")) push(jsonOf, f, target);
1092
1193
  }
1093
1194
  }
1094
- const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads.byName };
1195
+ const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads2.byName };
1095
1196
  siteReadsOf.set(importers, site);
1096
1197
  return site;
1097
1198
  }
@@ -1186,21 +1287,21 @@ function listTools(framework, text) {
1186
1287
  return tools.filter((t) => t in deps);
1187
1288
  }
1188
1289
  function draftCheck(path, { framework, paths, text, found, importers }) {
1189
- const at2 = normalisePath(path);
1290
+ const at3 = normalisePath(path);
1190
1291
  const no = (reason, detail) => ({ ok: (
1191
1292
  /** @type {const} */
1192
1293
  false
1193
- ), path: at2, reason, ...detail ? { detail } : {} });
1294
+ ), path: at3, reason, ...detail ? { detail } : {} });
1194
1295
  if (!DRAFTABLE.includes(String(framework))) return no("framework");
1195
- if (at2 === "/") return no("home");
1296
+ if (at3 === "/") return no("home");
1196
1297
  const media = mediaGenerators(text);
1197
1298
  if (media.length) return no("generated_media", media.join(", "));
1198
1299
  const lists = listTools(framework, text);
1199
1300
  if (lists.length) return no("page_list", lists.join(", "));
1200
1301
  const discovered = found ?? discover({ framework, paths, text });
1201
- const page = discovered.pages.find((p) => p.path === at2);
1302
+ const page = discovered.pages.find((p) => p.path === at3);
1202
1303
  if (!page) {
1203
- const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at2));
1304
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at3));
1204
1305
  return template ? no("template", template.path) : no("missing");
1205
1306
  }
1206
1307
  if (page.kind === "template") return no("template", page.path);
@@ -1219,7 +1320,7 @@ function draftCheck(path, { framework, paths, text, found, importers }) {
1219
1320
  if (content.shared.length) return no("shared", content.shared.join(", "));
1220
1321
  if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1221
1322
  if (content.unknown) return no("content_unknown");
1222
- return { ok: true, path: at2, page, content: content.files };
1323
+ return { ok: true, path: at3, page, content: content.files };
1223
1324
  }
1224
1325
  var SEGMENT_FILE = /^(layout|template|loading|error|global-error|not-found|forbidden|unauthorized|default|route|sitemap|manifest|robots|(?:opengraph-image|twitter-image|icon|apple-icon)\d*)(\.alt)?\.[a-z]+$/;
1225
1326
  function segmentFiles(file, paths) {
@@ -1385,13 +1486,13 @@ function slugOf(name) {
1385
1486
  }
1386
1487
  var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
1387
1488
  function validAddress(p) {
1388
- const at2 = normalisePath(p);
1389
- if (at2.length > 200) return false;
1390
- if (at2 === "/") return true;
1391
- return at2.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
1489
+ const at3 = normalisePath(p);
1490
+ if (at3.length > 200) return false;
1491
+ if (at3 === "/") return true;
1492
+ return at3.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
1392
1493
  }
1393
- var under = (path, at2) => at2 === "/" ? path !== "/" : path.startsWith(`${at2}/`);
1394
- var within2 = (path, at2) => path === at2 || under(path, at2);
1494
+ var under = (path, at3) => at3 === "/" ? path !== "/" : path.startsWith(`${at3}/`);
1495
+ var within2 = (path, at3) => path === at3 || under(path, at3);
1395
1496
  var moveAddress = (path, from, to) => path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`);
1396
1497
  var parentOf = (p) => p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/")));
1397
1498
  var lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
@@ -1405,9 +1506,9 @@ function siteRedirects({ framework, text }) {
1405
1506
  for (const c of CONFIGS[String(framework)] ?? []) {
1406
1507
  const src = stripComments(text(c) ?? "");
1407
1508
  if (framework === "astro") {
1408
- const at2 = src.search(/\bredirects\s*:\s*\{/);
1409
- if (at2 < 0) continue;
1410
- const body = braced(src, src.indexOf("{", at2)) ?? "";
1509
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
1510
+ if (at3 < 0) continue;
1511
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
1411
1512
  for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
1412
1513
  } else if (framework === "next") {
1413
1514
  for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
@@ -1437,11 +1538,15 @@ function changedPageFile(before, change) {
1437
1538
  if (!isObject(data)) data = {};
1438
1539
  if (!isObject(data.pages)) data.pages = {};
1439
1540
  const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
1440
- change(data.pages, redirects);
1541
+ const folders = isObject(data.folders) ? { ...data.folders } : {};
1542
+ change(data.pages, redirects, folders);
1441
1543
  for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
1544
+ for (const [k, v] of Object.entries(folders)) if (!isObject(v) || !v.name) delete folders[k];
1545
+ if (Object.keys(folders).length) data.folders = folders;
1546
+ else delete data.folders;
1442
1547
  if (Object.keys(redirects).length) data.redirects = redirects;
1443
1548
  else delete data.redirects;
1444
- const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
1549
+ const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
1445
1550
  if (before == null && empty) return null;
1446
1551
  const after = `${JSON.stringify(data, null, 2)}
1447
1552
  `;
@@ -1570,18 +1675,19 @@ function planPage(request, input) {
1570
1675
  const action = request.action;
1571
1676
  if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
1572
1677
  if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
1573
- const at2 = normalisePath(request.path);
1678
+ const at3 = normalisePath(request.path);
1574
1679
  const discovered = input.found ?? discover({ framework, paths, text });
1575
- const page = discovered.pages.find((p) => p.path === at2);
1680
+ const page = discovered.pages.find((p) => p.path === at3);
1681
+ if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at3))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
1576
1682
  if (!page) {
1577
- const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at2));
1683
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at3));
1578
1684
  return template ? no("template", template.path) : no("missing");
1579
1685
  }
1580
1686
  if (page.kind === "template") return no("template", page.path);
1581
1687
  if (!page.file || page.reason === "unparsed") return no("unparsed");
1582
1688
  const pageFile = parsePageFile(text(PAGE_FILE));
1583
1689
  if (!pageFile.ok) return no("invalid", pageFile.error);
1584
- const below = discovered.pages.filter((p) => under(p.path, at2));
1690
+ const below = discovered.pages.filter((p) => under(p.path, at3));
1585
1691
  const have = new Set(paths);
1586
1692
  const importers = input.importers ?? importGraph(paths, text);
1587
1693
  const live = request.live === true;
@@ -1599,28 +1705,28 @@ function planPage(request, input) {
1599
1705
  const redirectChanges = {};
1600
1706
  const collections = (() => {
1601
1707
  try {
1602
- return JSON.parse(text(COLLECTIONS) ?? "null");
1708
+ return readCollections(text);
1603
1709
  } catch {
1604
1710
  return null;
1605
1711
  }
1606
1712
  })();
1607
1713
  const collectionsAfter = isObject(collections) ? { ...collections } : null;
1608
1714
  if (action === "rename") {
1609
- if (at2 === "/") return no("home");
1610
- const target = request.to == null ? at2 : normalisePath(request.to);
1715
+ if (at3 === "/") return no("home");
1716
+ const target = request.to == null ? at3 : normalisePath(request.to);
1611
1717
  if (!validAddress(target) || target === "/") return no("address", target);
1612
- if (target !== at2 && within2(target, at2)) return no("address", target);
1613
- if (target !== at2 && taken(target)) return no("taken", target);
1614
- if (target !== at2 && live && !redirects) return no("no_redirects");
1718
+ if (target !== at3 && within2(target, at3)) return no("address", target);
1719
+ if (target !== at3 && taken(target)) return no("taken", target);
1720
+ if (target !== at3 && live && !redirects) return no("no_redirects");
1615
1721
  to = target;
1616
1722
  const moved = /* @__PURE__ */ new Map();
1617
- if (target !== at2) {
1723
+ if (target !== at3) {
1618
1724
  if (framework === "vite-react") {
1619
1725
  const src = text(page.router.file) ?? "";
1620
1726
  const attr = routePathAttr(src, page.router);
1621
1727
  if (!attr) return no("unparsed", "index route");
1622
1728
  if (!attr.value.startsWith("/")) {
1623
- const parent = normalisePath(at2.slice(0, at2.length - normalisePath(attr.value).length));
1729
+ const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1624
1730
  if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
1625
1731
  const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
1626
1732
  write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
@@ -1650,27 +1756,27 @@ function planPage(request, input) {
1650
1756
  const where = moved.get(p) ?? p;
1651
1757
  const src = current(where);
1652
1758
  if (!src) continue;
1653
- const out = relinked(src, at2, target, /\.mdx?$/.test(p));
1759
+ const out = relinked(src, at3, target, /\.mdx?$/.test(p));
1654
1760
  if (out === src) continue;
1655
1761
  write({ path: where, content: out });
1656
1762
  if (!moved.has(p)) links.add(where);
1657
1763
  }
1658
- moves.push({ from: at2, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at2, target) })));
1764
+ moves.push({ from: at3, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at3, target) })));
1659
1765
  for (const [from, next] of moved) renamed.push({ from, to: next });
1660
1766
  }
1661
1767
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1662
- if (target !== at2) {
1768
+ if (target !== at3) {
1663
1769
  for (const key of Object.keys(pages)) {
1664
- if (!within2(key, at2)) continue;
1665
- pages[moveAddress(key, at2, target)] = { ...pages[key], ...pages[moveAddress(key, at2, target)] ?? {} };
1770
+ if (!within2(key, at3)) continue;
1771
+ pages[moveAddress(key, at3, target)] = { ...pages[key], ...pages[moveAddress(key, at3, target)] ?? {} };
1666
1772
  delete pages[key];
1667
1773
  }
1668
1774
  const before = { ...sendsOn };
1669
1775
  if (live) {
1670
- sendsOn[at2] = target;
1671
- if (below.length) sendsOn[`${at2}/[...path]`] = `${target}/[...path]`;
1776
+ sendsOn[at3] = target;
1777
+ if (below.length) sendsOn[`${at3}/[...path]`] = `${target}/[...path]`;
1672
1778
  }
1673
- repoint(sendsOn, at2, target);
1779
+ repoint(sendsOn, at3, target);
1674
1780
  for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1675
1781
  }
1676
1782
  if (request.name !== void 0) {
@@ -1691,7 +1797,7 @@ function planPage(request, input) {
1691
1797
  if (!validAddress(target) || target === "/") return no("address", target);
1692
1798
  if (taken(target)) return no("taken", target);
1693
1799
  } else {
1694
- const base = at2 === "/" ? "/home-copy" : `${at2}-copy`;
1800
+ const base = at3 === "/" ? "/home-copy" : `${at3}-copy`;
1695
1801
  target = base;
1696
1802
  for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
1697
1803
  }
@@ -1699,10 +1805,10 @@ function planPage(request, input) {
1699
1805
  const content = ownedContent(page, { paths, text, importers });
1700
1806
  if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1701
1807
  const own = new Set(content.files);
1702
- const reads = siteReads(paths, text, importers);
1703
- const ownCodeFiles = ownCode(page, importers, reads.imports);
1704
- const pageReads = reads.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set(), whole: /* @__PURE__ */ new Set(), helped: /* @__PURE__ */ new Set() };
1705
- const imported = new Set(reads.jsonOf.get(page.file) ?? []);
1808
+ const reads2 = siteReads(paths, text, importers);
1809
+ const ownCodeFiles = ownCode(page, importers, reads2.imports);
1810
+ const pageReads = reads2.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set(), whole: /* @__PURE__ */ new Set(), helped: /* @__PURE__ */ new Set() };
1811
+ const imported = new Set(reads2.jsonOf.get(page.file) ?? []);
1706
1812
  const copies = /* @__PURE__ */ new Map();
1707
1813
  const rebinds = [];
1708
1814
  const newId = slugOf(lastOf(target)) || "copy";
@@ -1712,14 +1818,14 @@ function planPage(request, input) {
1712
1818
  return f;
1713
1819
  };
1714
1820
  for (const f of own) {
1715
- if (reads.isRoute(f)) continue;
1821
+ if (reads2.isRoute(f)) continue;
1716
1822
  if (imported.has(f)) {
1717
1823
  copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
1718
1824
  continue;
1719
1825
  }
1720
- const collection = collectionOfFile(f, reads.collections);
1826
+ const collection = collectionOfFile(f, reads2.collections);
1721
1827
  const id = f.slice(f.lastIndexOf("/") + 1, -5);
1722
- const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
1828
+ const folder = (reads2.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads2.collections || !reads2.collections[f];
1723
1829
  const entry = `${collection}/${id}`;
1724
1830
  if (pageReads.entries.has(entry) && folder) {
1725
1831
  const next = freeFile(dirname(f), newId, ".json");
@@ -1736,14 +1842,14 @@ function planPage(request, input) {
1736
1842
  if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
1737
1843
  for (const m of ownCodeFiles) {
1738
1844
  if (m === page.file) continue;
1739
- const r = reads.readsByFile.get(m);
1740
- if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && [...own].some((f) => !reads.isRoute(f))) return no("content_bound", m);
1845
+ const r = reads2.readsByFile.get(m);
1846
+ if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && [...own].some((f) => !reads2.isRoute(f))) return no("content_bound", m);
1741
1847
  }
1742
1848
  const rebind = (src) => {
1743
1849
  let out = src;
1744
1850
  for (const r of rebinds) {
1745
1851
  if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape(r.collection)}["']\\s*,\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1746
- else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1852
+ else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1747
1853
  }
1748
1854
  for (const [f, next] of copies) {
1749
1855
  if (!imported.has(f)) continue;
@@ -1767,7 +1873,7 @@ function planPage(request, input) {
1767
1873
  if (!statement) return no("unparsed", "its import");
1768
1874
  const added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(router, file, spec, page.file)}${q}`);
1769
1875
  const value = attr.value.startsWith("/") ? target : (() => {
1770
- const parent = normalisePath(at2.slice(0, at2.length - normalisePath(attr.value).length));
1876
+ const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1771
1877
  return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1772
1878
  })();
1773
1879
  if (value === null) return no("unparsed", "a route inside another route keeps its parent");
@@ -1783,7 +1889,7 @@ ${added}${out.slice(lineEnd)}`;
1783
1889
  } else {
1784
1890
  const dest = destination(page, target, discovered);
1785
1891
  if (!dest) return no("unparsed");
1786
- const along = framework === "next" && routesBase(page.file).endsWith("app") && at2 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1892
+ const along = framework === "next" && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1787
1893
  const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1788
1894
  for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1789
1895
  for (const [from, next] of moved) {
@@ -1802,10 +1908,10 @@ ${added}${out.slice(lineEnd)}`;
1802
1908
  if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1803
1909
  }
1804
1910
  for (const f of own) {
1805
- if (!reads.isRoute(f)) continue;
1911
+ if (!reads2.isRoute(f)) continue;
1806
1912
  const src = text(f) ?? "";
1807
1913
  const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
1808
- write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at2)}(")`), `$1${target}$2`) });
1914
+ write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at3)}(")`), `$1${target}$2`) });
1809
1915
  if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1810
1916
  }
1811
1917
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
@@ -1815,15 +1921,15 @@ ${added}${out.slice(lineEnd)}`;
1815
1921
  if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1816
1922
  }
1817
1923
  if (action === "delete") {
1818
- if (at2 === "/") return no("home");
1924
+ if (at3 === "/") return no("home");
1819
1925
  if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
1820
1926
  let target = null;
1821
1927
  if (live && request.redirect !== null) {
1822
1928
  if (request.redirect !== void 0) {
1823
1929
  target = normalisePath(request.redirect);
1824
- if (within2(target, at2) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1930
+ if (within2(target, at3) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1825
1931
  } else {
1826
- for (let p = parentOf(at2); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
1932
+ for (let p = parentOf(at3); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
1827
1933
  target = target ?? "/";
1828
1934
  }
1829
1935
  if (!redirects) return no("no_redirects");
@@ -1859,25 +1965,171 @@ ${added}${out.slice(lineEnd)}`;
1859
1965
  write({ path: f, deleted: true });
1860
1966
  if (collectionsAfter) delete collectionsAfter[f];
1861
1967
  }
1862
- for (const f of linksTo(at2, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
1968
+ for (const f of linksTo(at3, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
1863
1969
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1864
- delete pages[at2];
1970
+ delete pages[at3];
1865
1971
  const before = { ...sendsOn };
1866
- if (target) sendsOn[at2] = target;
1867
- if (target) repoint(sendsOn, at2, target);
1868
- else for (const [s, d] of Object.entries(sendsOn)) if (d === at2) delete sendsOn[s];
1972
+ if (target) sendsOn[at3] = target;
1973
+ if (target) repoint(sendsOn, at3, target);
1974
+ else for (const [s, d] of Object.entries(sendsOn)) if (d === at3) delete sendsOn[s];
1869
1975
  for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1870
1976
  });
1871
1977
  if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1872
1978
  }
1873
1979
  if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
1874
1980
  const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
1875
- write({ path: COLLECTIONS, content: `${JSON.stringify(sorted, null, 2)}
1876
- ` });
1981
+ const content = `${JSON.stringify(sorted, null, 2)}
1982
+ `;
1983
+ write({ path: COLLECTIONS, content });
1984
+ write({ path: LEGACY_COLLECTIONS, content });
1985
+ }
1986
+ const files = [...writes.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
1987
+ const message = action === "rename" ? to === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${to}` : action === "duplicate" ? `Unbase: duplicate ${at3} as ${to}` : `Unbase: delete ${at3}${to ? ` (visitors go to ${to})` : ""}`;
1988
+ return { ok: true, action, path: at3, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
1989
+ }
1990
+ function folderPaths(pages) {
1991
+ const own = new Set(pages.map((p) => p.path));
1992
+ const out = /* @__PURE__ */ new Set();
1993
+ for (const p of pages) for (let up = parentOf(p.path); up && up !== "/"; up = parentOf(up)) if (!own.has(up)) out.add(up);
1994
+ return [...out].sort();
1995
+ }
1996
+ var unsegmented = (dir) => /^\(.*\)$|^@/.test(dir.slice(dir.lastIndexOf("/") + 1));
1997
+ function folderDirs(at3, below) {
1998
+ const dirs = /* @__PURE__ */ new Set();
1999
+ for (const p of below) {
2000
+ if (!p.file) return null;
2001
+ const base = routesBase(p.file);
2002
+ if (!base) return null;
2003
+ if (!base.endsWith("app")) {
2004
+ const dir = `${base}${at3}`;
2005
+ if (!p.file.startsWith(`${dir}/`)) return null;
2006
+ dirs.add(dir);
2007
+ continue;
2008
+ }
2009
+ let d = dirname(p.file);
2010
+ let n = p.path.slice(at3.length + 1).split("/").length;
2011
+ while (n > 0 && d.length > base.length) {
2012
+ if (!unsegmented(d)) n--;
2013
+ d = dirname(d);
2014
+ }
2015
+ while (unsegmented(d) && d.length > base.length) d = dirname(d);
2016
+ if (lastOf(d) !== lastOf(at3)) return null;
2017
+ dirs.add(d);
2018
+ }
2019
+ return dirs.size ? [...dirs].sort() : null;
2020
+ }
2021
+ function planFolder(request, { framework, paths, text, discovered, importers: given }) {
2022
+ const no = (reason, detail) => ({ ok: (
2023
+ /** @type {const} */
2024
+ false
2025
+ ), reason, ...detail ? { detail } : {} });
2026
+ const at3 = normalisePath(request.path);
2027
+ if (at3 === "/") return no("home");
2028
+ const pageFile = parsePageFile(text(PAGE_FILE));
2029
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2030
+ const target = request.to == null ? at3 : normalisePath(request.to);
2031
+ if (!validAddress(target) || target === "/") return no("address", target);
2032
+ if (target !== at3 && (within2(target, at3) || parentOf(target) !== parentOf(at3))) return no("address", target);
2033
+ const below = discovered.pages.filter((p) => under(p.path, at3));
2034
+ const ownRedirects = siteRedirects({ framework, text });
2035
+ if (target !== at3 && (discovered.pages.some((p) => within2(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
2036
+ const live = request.live === true;
2037
+ if (target !== at3 && live && !kitRedirects({ framework, text })) return no("no_redirects");
2038
+ const have = new Set(paths);
2039
+ const writes = /* @__PURE__ */ new Map();
2040
+ const write = (w) => writes.set(w.path, w);
2041
+ const current = (p) => writes.has(p) ? writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null) : text(p);
2042
+ const links = /* @__PURE__ */ new Set();
2043
+ const moved = /* @__PURE__ */ new Map();
2044
+ const redirectChanges = {};
2045
+ if (target !== at3) {
2046
+ if (framework === "vite-react") {
2047
+ const edits = /* @__PURE__ */ new Map();
2048
+ for (const p of below) {
2049
+ if (!p.router) return no("unparsed", p.path);
2050
+ const src = text(p.router.file) ?? "";
2051
+ const attr = routePathAttr(src, p.router);
2052
+ if (!attr) return no("unparsed", "index route");
2053
+ const next = moveAddress(p.path, at3, target);
2054
+ let value;
2055
+ if (attr.value.startsWith("/")) value = `${next}${attr.value.endsWith("/") && next !== "/" ? "/" : ""}`;
2056
+ else {
2057
+ const parent = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
2058
+ if (under(parent, at3)) continue;
2059
+ value = parent === "/" ? next.slice(1) : next.slice(parent.length + 1);
2060
+ }
2061
+ edits.set(p.router.file, [...edits.get(p.router.file) ?? [], { start: attr.start, end: attr.end, value }]);
2062
+ }
2063
+ for (const [file, list] of edits) {
2064
+ let out = text(file) ?? "";
2065
+ for (const e of [...list].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.value + out.slice(e.end);
2066
+ write({ path: file, content: out });
2067
+ }
2068
+ } else {
2069
+ const dirs = folderDirs(at3, below);
2070
+ if (!dirs) return no("unparsed", at3);
2071
+ for (const dir of dirs) {
2072
+ const newDir = `${dirname(dir)}/${lastOf(target)}`;
2073
+ for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
2074
+ }
2075
+ for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
2076
+ for (const [from, next] of moved) {
2077
+ const src = CODE.test(from) ? text(from) : null;
2078
+ const content = src == null ? null : respecified(src, from, next, moved, have);
2079
+ write(content == null || content === src ? { path: next, from } : { path: next, content });
2080
+ write({ path: from, deleted: true });
2081
+ }
2082
+ const importers = given ?? null;
2083
+ for (const p of paths) {
2084
+ if (moved.has(p) || !CODE.test(p)) continue;
2085
+ if (importers && ![...moved.keys()].some((m) => importers.get(m)?.has(p))) continue;
2086
+ const src = text(p);
2087
+ if (!src) continue;
2088
+ const out = respecified(src, p, p, moved, have);
2089
+ if (out !== src) write({ path: p, content: out });
2090
+ }
2091
+ }
2092
+ for (const p of paths) {
2093
+ if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2094
+ const where = moved.get(p) ?? p;
2095
+ const src = current(where);
2096
+ if (!src) continue;
2097
+ const out = relinked(src, at3, target, /\.mdx?$/.test(p));
2098
+ if (out === src) continue;
2099
+ write({ path: where, content: out });
2100
+ if (!moved.has(p)) links.add(where);
2101
+ }
1877
2102
  }
2103
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn, folders) => {
2104
+ if (target !== at3) {
2105
+ for (const key of Object.keys(pages)) {
2106
+ if (!within2(key, at3)) continue;
2107
+ pages[moveAddress(key, at3, target)] = { ...pages[key], ...pages[moveAddress(key, at3, target)] ?? {} };
2108
+ delete pages[key];
2109
+ }
2110
+ for (const key of Object.keys(folders)) {
2111
+ if (!within2(key, at3)) continue;
2112
+ folders[moveAddress(key, at3, target)] = folders[key];
2113
+ delete folders[key];
2114
+ }
2115
+ const before = { ...sendsOn };
2116
+ if (live) sendsOn[`${at3}/[...path]`] = `${target}/[...path]`;
2117
+ repoint(sendsOn, at3, target);
2118
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
2119
+ }
2120
+ if (request.name !== void 0) {
2121
+ const name = request.name ? String(request.name).trim().slice(0, 120) : "";
2122
+ if (name) folders[target] = { name };
2123
+ else delete folders[target];
2124
+ }
2125
+ });
2126
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
2127
+ if (!writes.size) return no("same");
1878
2128
  const files = [...writes.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
1879
- const message = action === "rename" ? to === at2 ? `Unbase: rename ${at2}` : `Unbase: move ${at2} to ${to}` : action === "duplicate" ? `Unbase: duplicate ${at2} as ${to}` : `Unbase: delete ${at2}${to ? ` (visitors go to ${to})` : ""}`;
1880
- return { ok: true, action, path: at2, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
2129
+ const moves = target === at3 ? [] : [{ from: at3, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at3, target) }))];
2130
+ const renamed = [...moved].map(([from, to]) => ({ from, to }));
2131
+ const message = target === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${target}`;
2132
+ return { ok: true, action: "rename", path: at3, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
1881
2133
  }
1882
2134
  function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers }) {
1883
2135
  const kept = paths.filter((p) => !SKIP2.test(p));
@@ -1885,7 +2137,7 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
1885
2137
  const graph = importers ?? importGraph(kept, text);
1886
2138
  const pageFile = parsePageFile(text(PAGE_FILE));
1887
2139
  const redirects = kitRedirects({ framework, text });
1888
- const reads = siteReads(kept, text, graph);
2140
+ const reads2 = siteReads(kept, text, graph);
1889
2141
  const out = {};
1890
2142
  const no = (reason, detail) => ({ ok: (
1891
2143
  /** @type {const} */
@@ -1922,16 +2174,16 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
1922
2174
  let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
1923
2175
  if (duplicate.ok) {
1924
2176
  const content = ownedContent(page, { paths: kept, text, importers: graph });
1925
- const pageReads = reads.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
1926
- const imported = new Set(reads.jsonOf.get(page.file) ?? []);
2177
+ const pageReads = reads2.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
2178
+ const imported = new Set(reads2.jsonOf.get(page.file) ?? []);
1927
2179
  if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
1928
2180
  else if (content.unknown) duplicate = no("content_bound");
1929
2181
  else
1930
2182
  for (const f of content.files) {
1931
- if (reads.isRoute(f) || imported.has(f)) continue;
1932
- const collection = collectionOfFile(f, reads.collections);
2183
+ if (reads2.isRoute(f) || imported.has(f)) continue;
2184
+ const collection = collectionOfFile(f, reads2.collections);
1933
2185
  const id = f.slice(f.lastIndexOf("/") + 1, -5);
1934
- const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
2186
+ const folder = (reads2.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads2.collections || !reads2.collections[f];
1935
2187
  const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || pageReads.names.has(id) && id !== collection);
1936
2188
  if (bound) {
1937
2189
  duplicate = no("content_bound", f);
@@ -1939,11 +2191,11 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
1939
2191
  }
1940
2192
  }
1941
2193
  if (duplicate.ok) {
1942
- const mine = ownCode(page, graph, reads.imports);
2194
+ const mine = ownCode(page, graph, reads2.imports);
1943
2195
  for (const m of mine) {
1944
2196
  if (m === page.file) continue;
1945
- const r = reads.readsByFile.get(m);
1946
- if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads.isRoute(f))) {
2197
+ const r = reads2.readsByFile.get(m);
2198
+ if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads2.isRoute(f))) {
1947
2199
  duplicate = no("content_bound", m);
1948
2200
  break;
1949
2201
  }
@@ -1952,7 +2204,16 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
1952
2204
  }
1953
2205
  out[page.path] = { rename, duplicate, delete: remove, under: below.length };
1954
2206
  }
1955
- return { redirects, actions: out };
2207
+ const folders = {};
2208
+ for (const at3 of folderPaths(discovered.pages)) {
2209
+ const below = discovered.pages.filter((p) => under(p.path, at3));
2210
+ let rename = !PAGE_ACTION_FRAMEWORKS.includes(String(framework)) ? no("framework") : !pageFile.ok ? no("invalid") : yes;
2211
+ if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no("no_redirects");
2212
+ if (rename.ok && framework === "vite-react" && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
2213
+ if (rename.ok && framework !== "vite-react" && !folderDirs(at3, below)) rename = no("unparsed", at3);
2214
+ folders[at3] = { rename, under: below.length };
2215
+ }
2216
+ return { redirects, actions: out, folders };
1956
2217
  }
1957
2218
  function redirectsFor(framework, pageFile, pagePaths = []) {
1958
2219
  const pages = new Set(pagePaths.map(normalisePath));
@@ -1972,6 +2233,97 @@ function redirectsFor(framework, pageFile, pagePaths = []) {
1972
2233
  }
1973
2234
  return { list, skipped };
1974
2235
  }
2236
+ function siteRedirectList({ framework, text }) {
2237
+ const out = [];
2238
+ try {
2239
+ const v = JSON.parse(text("vercel.json") ?? "null");
2240
+ for (const r of Array.isArray(v?.redirects) ? v.redirects : []) {
2241
+ if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
2242
+ }
2243
+ } catch {
2244
+ }
2245
+ for (const c of CONFIGS[String(framework)] ?? []) {
2246
+ const src = stripComments(text(c) ?? "");
2247
+ if (framework === "astro") {
2248
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
2249
+ if (at3 < 0) continue;
2250
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
2251
+ const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
2252
+ for (const m of body.matchAll(entry)) out.push({ from: m[1], to: m[2] ?? m[3], file: c });
2253
+ } else if (framework === "next") {
2254
+ for (const m of src.matchAll(/\{[^{}]*\}/g)) {
2255
+ const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
2256
+ const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
2257
+ if (from && to) out.push({ from, to, file: c });
2258
+ }
2259
+ }
2260
+ }
2261
+ return out;
2262
+ }
2263
+ function redirectEnd(p) {
2264
+ const s = String(p ?? "").trim();
2265
+ const prefix = /\/(…|\.\.\.|\*)$/.test(s) || REST.test(s);
2266
+ const base = normalisePath(prefix ? s.replace(REST, "").replace(/\/(…|\.\.\.|\*)$/, "") : s);
2267
+ return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
2268
+ }
2269
+ function planRedirect(request, { framework, paths, text, found }) {
2270
+ const no = (reason, detail) => ({ ok: (
2271
+ /** @type {const} */
2272
+ false
2273
+ ), reason, ...detail ? { detail } : {} });
2274
+ const action = request.action;
2275
+ if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
2276
+ if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
2277
+ const pageFile = parsePageFile(text(PAGE_FILE));
2278
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2279
+ const from = redirectEnd(request.from);
2280
+ const was = request.was != null ? redirectEnd(request.was) : from;
2281
+ if (action !== "add" && !(was.key in pageFile.redirects)) return no("missing", was.key);
2282
+ const changes = {};
2283
+ let to = null;
2284
+ if (action !== "remove") {
2285
+ if (!kitRedirects({ framework, text })) return no("no_redirects");
2286
+ if (from.base === "/" || !validAddress(from.base)) return no("address", request.from);
2287
+ const end = redirectEnd(request.to);
2288
+ if (!validAddress(end.base)) return no("address", request.to);
2289
+ const discovered = found ?? discover({ framework, paths: paths.filter((p) => !SKIP2.test(p)), text });
2290
+ const isPage = (p) => discovered.pages.some((q) => q.kind === "template" ? templateMatches(q.path, p) : q.path === p);
2291
+ if (from.prefix ? discovered.pages.some((q) => within2(q.path, from.base)) : isPage(from.base)) return no("page", from.base);
2292
+ if (from.key !== was.key && from.key in pageFile.redirects) return no("exists", from.key);
2293
+ if (action === "add" && from.key in pageFile.redirects) return no("exists", from.key);
2294
+ const own = [...siteRedirects({ framework, text })].find((s) => sends(s, from.base));
2295
+ if (own) return no("redirect_conflict", own);
2296
+ let dest = end.base;
2297
+ const others = { ...pageFile.redirects };
2298
+ delete others[was.key];
2299
+ for (let hops = 0; hops < 20; hops++) {
2300
+ const next = Object.entries(others).find(([s]) => !REST.test(s) && s === dest);
2301
+ if (!next) break;
2302
+ dest = next[1];
2303
+ }
2304
+ if (from.prefix ? within2(dest, from.base) : dest === from.base) return no(dest === from.base ? "self" : "loop", dest);
2305
+ if (Object.entries(others).some(([s, d]) => d === from.base && s === dest)) return no("loop", dest);
2306
+ to = from.prefix ? `${dest === "/" ? "" : dest}/[...path]` : dest;
2307
+ }
2308
+ const content = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
2309
+ const before = { ...sendsOn };
2310
+ delete sendsOn[was.key];
2311
+ if (to !== null) {
2312
+ sendsOn[from.key] = to;
2313
+ if (!from.prefix) {
2314
+ for (const [s, d] of Object.entries(sendsOn)) if (d === from.base && s !== from.key) sendsOn[s] = to;
2315
+ }
2316
+ }
2317
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) changes[k] = sendsOn[k] ?? null;
2318
+ });
2319
+ if (content === null) return no("same");
2320
+ const shown2 = (k) => k.replace(REST, "/\u2026");
2321
+ const message = action === "remove" ? `Unbase: remove redirect ${shown2(was.key)}` : `Unbase: redirect ${shown2(from.key)} to ${shown2(to)}`;
2322
+ return { ok: (
2323
+ /** @type {const} */
2324
+ true
2325
+ ), action, from: from.key, to, was: was.key, files: [{ path: PAGE_FILE, content }], redirects: changes, message };
2326
+ }
1975
2327
 
1976
2328
  // supabase/functions/_shared/next-metadata.ts
1977
2329
  var ID = /[A-Za-z0-9_$]/;
@@ -2158,15 +2510,15 @@ var CMS2 = /sanity|contentful|storyblok|prismic|datocms|payload|strapi|directus|
2158
2510
  var isCmsModule = (spec) => CMS2.test(spec);
2159
2511
  var importsOf = (src) => [...src.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']/gm), ...src.matchAll(/^\s*import\s*["']([^"']+)["']/gm)].map((m) => m[1]);
2160
2512
  function afterImports(src, code) {
2161
- let at2 = 0;
2513
+ let at3 = 0;
2162
2514
  const directive = /^\s*(["'])use [a-z]+\1;?[^\S\n]*\n?/.exec(src);
2163
- if (directive) at2 = directive[0].length;
2515
+ if (directive) at3 = directive[0].length;
2164
2516
  for (const m of code.matchAll(/^import\b/gm)) {
2165
2517
  const end = expressionEnd(src, m.index);
2166
2518
  const semi = src[end] === ";" ? end + 1 : end;
2167
- at2 = Math.max(at2, semi);
2519
+ at3 = Math.max(at3, semi);
2168
2520
  }
2169
- return at2;
2521
+ return at3;
2170
2522
  }
2171
2523
  function readMetadata(src) {
2172
2524
  const code = codeOnly(src);
@@ -2374,28 +2726,28 @@ async function viteSettings(repo, appPath) {
2374
2726
  if (text === null) return null;
2375
2727
  const head = readHead(text);
2376
2728
  const site = {};
2377
- for (const [field2, at2, kind] of HEAD_SETTINGS) {
2378
- const found = head[at2];
2379
- if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at2), kind, exists: true, value: found.value };
2729
+ for (const [field2, at3, kind] of HEAD_SETTINGS) {
2730
+ const found = head[at3];
2731
+ if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at3), kind, exists: true, value: found.value };
2380
2732
  }
2381
2733
  return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
2382
2734
  }
2383
2735
  async function readSettings(repo, appPath, framework = null) {
2384
2736
  if (framework === "vite-react") return viteSettings(repo, appPath);
2385
2737
  if (framework === "next") return nextSettings(repo, appPath);
2386
- const at2 = (p) => join(appPath, p);
2387
- const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at2(SCHEMAS)}/`) && p.endsWith(".schema.json"));
2738
+ const at3 = (p) => join(appPath, p);
2739
+ const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at3(SCHEMAS)}/`) && p.endsWith(".schema.json"));
2388
2740
  if (!schemaPaths.length) return null;
2389
- const named = (p) => p.slice(at2(SCHEMAS).length + 1, -".schema.json".length);
2741
+ const named = (p) => p.slice(at3(SCHEMAS).length + 1, -".schema.json".length);
2390
2742
  const schemas = /* @__PURE__ */ new Map();
2391
- const [map, ...read] = await inTurns([at2(`${SCHEMAS}/collecties.json`), ...schemaPaths], (p) => repo.read(p));
2743
+ const [legacyMap, map, ...read] = await inTurns([at3(`${SCHEMAS}/collecties.json`), at3(`${SCHEMAS}/collections.json`), ...schemaPaths], (p) => repo.read(p));
2392
2744
  schemaPaths.forEach((p, i) => {
2393
2745
  const s = parse(read[i] ?? null);
2394
2746
  if (s && typeof s === "object") schemas.set(named(p), s);
2395
2747
  });
2396
- const elsewhere = parse(map ?? null) ?? {};
2397
- const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at2(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at2(SCHEMAS)}/`));
2398
- const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at2(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
2748
+ const elsewhere = { ...parse(legacyMap ?? null) ?? {}, ...parse(map ?? null) ?? {} };
2749
+ const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at3(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at3(SCHEMAS)}/`));
2750
+ const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at3(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
2399
2751
  const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
2400
2752
  const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
2401
2753
  const pages = {};
@@ -2415,7 +2767,7 @@ async function readSettings(repo, appPath, framework = null) {
2415
2767
  const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
2416
2768
  routes = { dir, fields };
2417
2769
  }
2418
- const siteCollection = [...schemas].find(([, s]) => s["x-instellingen"] === "site");
2770
+ const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
2419
2771
  let site = null;
2420
2772
  const siteFile = siteCollection && filesOf(siteCollection[0])[0];
2421
2773
  if (siteCollection && siteFile) {
@@ -2596,15 +2948,15 @@ var CSP_FILES = ["vercel.json", "public/_headers"];
2596
2948
  var HEADER = /^content-security-policy$/i;
2597
2949
  function directivesOf(policy) {
2598
2950
  const out = [];
2599
- let at2 = 0;
2951
+ let at3 = 0;
2600
2952
  for (const part of policy.split(";")) {
2601
2953
  const lead = part.length - part.trimStart().length;
2602
2954
  const text = part.trim();
2603
2955
  if (text) {
2604
2956
  const [name, ...sources] = text.split(/\s+/);
2605
- out.push({ name: name.toLowerCase(), sources, start: at2 + lead, end: at2 + lead + text.length });
2957
+ out.push({ name: name.toLowerCase(), sources, start: at3 + lead, end: at3 + lead + text.length });
2606
2958
  }
2607
- at2 += part.length + 1;
2959
+ at3 += part.length + 1;
2608
2960
  }
2609
2961
  return out;
2610
2962
  }
@@ -2724,16 +3076,16 @@ var HEADERS_LINE = /^([ \t]+)(content-security-policy)([ \t]*:[ \t]*)(.*?)([ \t]
2724
3076
  function headersPolicies(text) {
2725
3077
  const out = [];
2726
3078
  let path = "";
2727
- let at2 = 0;
3079
+ let at3 = 0;
2728
3080
  text.split("\n").forEach((line, n) => {
2729
3081
  const plain2 = line.replace(/\r$/, "");
2730
3082
  if (/^\S/.test(plain2) && !plain2.startsWith("#")) path = plain2.trim();
2731
3083
  const m = HEADERS_LINE.exec(plain2);
2732
3084
  if (m) {
2733
- const start = at2 + m[1].length + m[2].length + m[3].length;
3085
+ const start = at3 + m[1].length + m[2].length + m[3].length;
2734
3086
  out.push({ file: "public/_headers", source: path, value: m[4], start, end: start + m[4].length, line: n + 1 });
2735
3087
  }
2736
- at2 += line.length + 1;
3088
+ at3 += line.length + 1;
2737
3089
  });
2738
3090
  return out;
2739
3091
  }
@@ -2754,8 +3106,8 @@ function edited(file, text, change) {
2754
3106
  for (const p of [...policies].sort((a, b) => b.start - a.start)) {
2755
3107
  const next = change(p.value);
2756
3108
  if (next === p.value) continue;
2757
- const literal = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
2758
- out = `${out.slice(0, p.start)}${literal}${out.slice(p.end)}`;
3109
+ const literal2 = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
3110
+ out = `${out.slice(0, p.start)}${literal2}${out.slice(p.end)}`;
2759
3111
  }
2760
3112
  return out;
2761
3113
  }
@@ -2789,7 +3141,1209 @@ function cspElsewhere(path, text) {
2789
3141
  if (/(^|\/)astro\.config\.[mc]?[jt]s$/.test(path) && /\bcsp\s*:/.test(text)) return "Astro's own CSP (its `csp` option)";
2790
3142
  return null;
2791
3143
  }
3144
+
3145
+ // supabase/functions/_shared/binding.mjs
3146
+ var binding_exports = {};
3147
+ __export(binding_exports, {
3148
+ ADAPTERS: () => ADAPTERS2,
3149
+ ASTRO: () => ASTRO,
3150
+ GATE_COLLECTIONS: () => GATE_COLLECTIONS,
3151
+ GATE_PAGES: () => GATE_PAGES,
3152
+ NEXT: () => NEXT,
3153
+ REASONS: () => REASONS,
3154
+ TAGGED_TYPES: () => TAGGED_TYPES,
3155
+ addressFor: () => addressFor,
3156
+ binds: () => binds,
3157
+ componentGate: () => componentGate,
3158
+ componentsOn: () => componentsOn,
3159
+ contentKeptCode: () => contentKeptCode,
3160
+ designKeptContent: () => designKeptContent,
3161
+ distinctive: () => distinctive,
3162
+ elementsOf: () => elementsOf,
3163
+ fieldUse: () => fieldUse,
3164
+ formatsIn: () => formatsIn,
3165
+ imageShows: () => imageShows,
3166
+ itemsIn: () => itemsIn,
3167
+ loaded: () => loaded,
3168
+ newItemShows: () => newItemShows,
3169
+ noCopiedContent: () => noCopiedContent,
3170
+ parseHtml: () => parseHtml,
3171
+ readerFunctionFiles: () => readerFunctionFiles,
3172
+ readerFunctions: () => readerFunctions,
3173
+ readersOf: () => readersOf,
3174
+ reads: () => reads,
3175
+ readsPattern: () => readsPattern,
3176
+ schemaValues: () => schemaValues,
3177
+ significant: () => significant,
3178
+ tagItem: () => tagItem,
3179
+ tagOf: () => tagOf,
3180
+ tagsIn: () => tagsIn2,
3181
+ testDraft: () => testDraft,
3182
+ untag: () => untag,
3183
+ wholeText: () => wholeText
3184
+ });
3185
+ var REASONS = ["no-identity", "computed", "dynamic", "cms", "ambiguous", "unproven", "unsupported"];
3186
+ var UNBASE_MARKERS = {
3187
+ /** `file#pointer` of the field the element shows: the runner's answer as the bridge applies it. */
3188
+ field: ["data-unbase-field", "data-cm-field", "data-cm-veld"],
3189
+ reason: "data-unbase-reason",
3190
+ /** Layer 1: where the element is written, and the chain of instances it sits in. */
3191
+ identity: ["data-unbase-src", "data-unbase-of"]
3192
+ };
3193
+ var ASTRO = {
3194
+ id: "astro",
3195
+ readers: [
3196
+ { kind: "call", names: ["getCollection", "getEntry", "getEntries", "getEntryBySlug", "getDataEntryById", "reference", "CollectionEntry"], open: "(<" },
3197
+ { kind: "helper", in: /^src\/(?:lib|utils)\/.*\.(?:ts|mts|js|mjs)$/, not: /\.test\./, imports: /from\s+["']astro:content["']/, calls: ["getCollection", "getEntry"], entry: "getEntry" }
3198
+ ],
3199
+ markers: UNBASE_MARKERS,
3200
+ content: ["src/content/"],
3201
+ assets: ["src/assets/images/"],
3202
+ formats: ["intl", "fixed"],
3203
+ // Astro's image service: `/_image?href=…` on the dev server, a hashed copy in /_astro/ in a build.
3204
+ images: [{ query: "href" }, { hashed: "/_astro/" }]
3205
+ };
3206
+ var NEXT = {
3207
+ id: "next",
3208
+ readers: [{ kind: "folder", root: "src/content" }],
3209
+ markers: null,
3210
+ content: ["src/content/"],
3211
+ assets: ["public/images/"],
3212
+ formats: ["intl", "fixed"],
3213
+ // next/image: `/_next/image?url=%2Fimages%2Fbike.jpg&w=640&q=75`.
3214
+ images: [{ query: "url" }]
3215
+ };
3216
+ var ADAPTERS2 = { astro: ASTRO, next: NEXT };
3217
+ var CODE3 = /\.(astro|tsx?|jsx?|mts|mjs|vue|svelte|mdx?)$/;
3218
+ var CONFIG2 = /content\.config\./;
3219
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
3220
+ var escapeText = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3221
+ var stripComments2 = (code) => code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
3222
+ function balanced(code, open) {
3223
+ const pairs = { "(": ")", "{": "}", "[": "]" };
3224
+ const stack = [];
3225
+ for (let i = open; i < code.length; i++) {
3226
+ const c = code[i];
3227
+ if (c === '"' || c === "'" || c === "`") {
3228
+ const q = c;
3229
+ for (i++; i < code.length && code[i] !== q; i++) if (code[i] === "\\") i++;
3230
+ continue;
3231
+ }
3232
+ if (pairs[c]) stack.push(pairs[c]);
3233
+ else if (c === stack.at(-1)) {
3234
+ stack.pop();
3235
+ if (!stack.length) return code.slice(open + 1, i);
3236
+ }
3237
+ }
3238
+ return null;
3239
+ }
3240
+ var literal = (s) => {
3241
+ const t = s.trim();
3242
+ const m = t.match(/^(["'`])([\s\S]*)\1$/);
3243
+ return m && (m[1] === "`" || !m[2].includes(m[1])) ? m[2] : null;
3244
+ };
3245
+ var fixed = (s) => {
3246
+ const v = literal(s);
3247
+ return v !== null && !v.includes("${") ? v : null;
3248
+ };
3249
+ function argumentsOf(inner) {
3250
+ const out = [];
3251
+ let depth = 0;
3252
+ let part = "";
3253
+ for (let i = 0; i < inner.length; i++) {
3254
+ const c = inner[i];
3255
+ if (c === '"' || c === "'" || c === "`") {
3256
+ let j = i + 1;
3257
+ for (; j < inner.length && inner[j] !== c; j++) if (inner[j] === "\\") j++;
3258
+ part += inner.slice(i, j + 1);
3259
+ i = j;
3260
+ continue;
3261
+ }
3262
+ if ("([{".includes(c)) depth++;
3263
+ if (")]}".includes(c)) depth--;
3264
+ if (c === "," && depth === 0) {
3265
+ out.push(part);
3266
+ part = "";
3267
+ } else part += c;
3268
+ }
3269
+ if (part.trim()) out.push(part);
3270
+ return out;
3271
+ }
3272
+ var shapes = (adapter) => (Array.isArray(adapter) ? adapter : [adapter]).flatMap((a) => a?.readers ?? []);
3273
+ var helperShapes = (adapter) => shapes(adapter).filter((s) => s.kind === "helper");
3274
+ function readerFunctionFiles(adapter, paths, root = "") {
3275
+ const helpers = helperShapes(adapter);
3276
+ return paths.filter((p) => p.startsWith(root) && helpers.some((h) => h.in.test(p.slice(root.length)) && !h.not?.test(p.slice(root.length))));
3277
+ }
3278
+ function readerFunctions({ files, adapter, root = "" }) {
3279
+ const out = [];
3280
+ for (const shape of helperShapes(adapter)) {
3281
+ const calls = new RegExp(`\\b(${shape.calls.map(escape2).join("|")})\\s*\\(\\s*([^,)]+)\\s*(?:,\\s*([^,)]+))?`);
3282
+ for (const { path, text } of files) {
3283
+ if (!path.startsWith(root)) continue;
3284
+ const rel = path.slice(root.length);
3285
+ if (!shape.in.test(rel) || shape.not?.test(rel)) continue;
3286
+ if (!text || !shape.imports.test(text)) continue;
3287
+ const code = stripComments2(text);
3288
+ for (const m of code.matchAll(/export\s+(?:async\s+)?function\s+(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)/g)) {
3289
+ const params = m[2].split(",").map((p) => p.trim().split(/[\s:=?]/)[0]).filter(Boolean);
3290
+ const open = code.indexOf("{", m.index + m[0].length);
3291
+ const body = open >= 0 ? balanced(code, open) : null;
3292
+ if (!body) continue;
3293
+ const call = body.match(calls);
3294
+ if (!call) continue;
3295
+ const which = (arg) => {
3296
+ const lit = literal(arg);
3297
+ if (lit !== null) return { name: lit };
3298
+ const i = params.indexOf(arg.trim());
3299
+ return i >= 0 ? { arg: i } : null;
3300
+ };
3301
+ const collection = which(call[2]);
3302
+ if (!collection) continue;
3303
+ const entryArg = call[1] === shape.entry && call[3] ? params.indexOf(call[3].trim()) : -1;
3304
+ out.push({ call: m[1], from: path, collection, ...entryArg >= 0 ? { entry: { arg: entryArg } } : {} });
3305
+ }
3306
+ }
3307
+ }
3308
+ return out;
3309
+ }
3310
+ function directReads(shape, text) {
3311
+ if (shape.kind === "call") {
3312
+ const re = new RegExp(`(?:${shape.names.map(escape2).join("|")})\\s*[${escape2(shape.open)}]\\s*["'\`]([^"'\`\\n]+)["'\`]`, "g");
3313
+ return Array.from(text.matchAll(re), (m) => m[1]);
3314
+ }
3315
+ if (shape.kind === "folder") {
3316
+ const root = escape2(shape.root);
3317
+ const re = new RegExp(`["'\`]${root}["'\`]\\s*,\\s*["'\`]([^"'\`\\n]+)["'\`]|["'\`]${root}/([^"'\`/\\n]+)["'\`/]`, "g");
3318
+ return Array.from(text.matchAll(re), (m) => m[1] ?? m[2]);
3319
+ }
3320
+ return [];
3321
+ }
3322
+ function readsPattern(adapter, collection) {
3323
+ const parts = [];
3324
+ for (const s of shapes(adapter)) {
3325
+ const name = escape2(collection);
3326
+ if (s.kind === "call") parts.push(`(?:${s.names.map(escape2).join("|")})\\s*[${escape2(s.open)}]\\s*["'\`]${name}["'\`]`);
3327
+ if (s.kind === "folder") parts.push(`["'\`]${escape2(s.root)}["'\`]\\s*,\\s*["'\`]${name}["'\`]|["'\`]${escape2(s.root)}/${name}["'\`/]`);
3328
+ }
3329
+ return new RegExp(parts.length ? parts.join("|") : "(?!)");
3330
+ }
3331
+ var collectionName = (n) => /^[A-Za-z0-9_][\w-]*$/.test(n ?? "");
3332
+ function reads({ files, adapter, collections, functions }) {
3333
+ const keep = collections ? new Set(collections) : null;
3334
+ const helpers = functions ?? readerFunctions({ files, adapter });
3335
+ const out = /* @__PURE__ */ new Map();
3336
+ const add = (r) => {
3337
+ if (!collectionName(r.collection) || keep && !keep.has(r.collection)) return;
3338
+ out.set(JSON.stringify([r.file, r.collection, r.via, r.call ?? "", r.entry ?? ""]), r);
3339
+ };
3340
+ const callOf = helpers.length ? new RegExp(`(?<![\\w$.])(${[...new Set(helpers.map((h) => h.call))].map(escape2).join("|")})\\s*\\(`, "g") : null;
3341
+ for (const { path, text } of files) {
3342
+ if (!CODE3.test(path) || CONFIG2.test(path) || !text) continue;
3343
+ for (const s of shapes(adapter)) for (const name of directReads(s, text)) add({ file: path, collection: name, via: s.kind });
3344
+ if (!callOf) continue;
3345
+ const code = stripComments2(text);
3346
+ for (const m of code.matchAll(callOf)) {
3347
+ if (/(?:function\s*\*?\s*|(?:const|let|var)\s+)$/.test(code.slice(Math.max(0, m.index - 20), m.index))) continue;
3348
+ const inner = balanced(code, m.index + m[0].length - 1);
3349
+ if (inner === null) continue;
3350
+ const args = argumentsOf(inner);
3351
+ for (const h of helpers.filter((x) => x.call === m[1])) {
3352
+ const collection = "name" in h.collection ? h.collection.name : fixed(args[h.collection.arg] ?? "");
3353
+ if (collection === null) continue;
3354
+ const entry = h.entry ? fixed(args[h.entry.arg] ?? "") : null;
3355
+ add({ file: path, collection, via: "helper", call: h.call, ...entry !== null ? { entry } : {} });
3356
+ }
3357
+ }
3358
+ }
3359
+ return [...out.values()].sort((a, b) => a.file.localeCompare(b.file) || a.collection.localeCompare(b.collection) || a.via.localeCompare(b.via));
3360
+ }
3361
+ function readersOf({ collection, reads: edges, importers, pages }) {
3362
+ const readers = new Set(edges.filter((r) => r.collection === collection).map((r) => r.file));
3363
+ const imports = /* @__PURE__ */ new Map();
3364
+ for (const [target, by] of importers) for (const f of by) imports.set(f, [...imports.get(f) ?? [], target]);
3365
+ const out = [];
3366
+ for (const page of pages) {
3367
+ if (!page.file) continue;
3368
+ const seen = /* @__PURE__ */ new Set([page.file]);
3369
+ const queue = [page.file];
3370
+ while (queue.length) {
3371
+ for (const next of imports.get(queue.pop()) ?? []) {
3372
+ if (seen.has(next)) continue;
3373
+ seen.add(next);
3374
+ queue.push(next);
3375
+ }
3376
+ }
3377
+ const through = [...seen].filter((f) => readers.has(f)).sort();
3378
+ if (through.length) out.push({ path: page.path, file: page.file, through });
3379
+ }
3380
+ return out.sort((a, b) => a.path.localeCompare(b.path));
3381
+ }
3382
+ var collapse = (s) => String(s).replace(/\s+/g, " ").trim();
3383
+ function significant(value) {
3384
+ if (typeof value !== "string") return false;
3385
+ const v = collapse(value);
3386
+ if (v.length < 12 || !v.includes(" ")) return false;
3387
+ if ((v.match(new RegExp("\\p{L}", "gu"))?.length ?? 0) < 8) return false;
3388
+ return !/^(?:[a-z][a-z0-9+.-]*:|\/|\.{1,2}\/|#|www\.)/i.test(v);
3389
+ }
3390
+ function distinctive(value) {
3391
+ if (typeof value === "number") return Number.isFinite(value) && Math.abs(value) >= 10;
3392
+ if (typeof value !== "string") return false;
3393
+ const v = collapse(value);
3394
+ return v.length >= 3 && new RegExp("\\p{L}", "u").test(v) && !/^(?:[a-z][a-z0-9+.-]*:|\/|\.{1,2}\/|#|www\.)/i.test(v);
3395
+ }
3396
+ var sameText = (v) => collapse(String(v)).toLowerCase().replace(/[\s_-]+/g, " ");
3397
+ function leaves(value, at3 = "", out = []) {
3398
+ if (Array.isArray(value)) value.forEach((v, i) => leaves(v, `${at3}/${i}`, out));
3399
+ else if (value && typeof value === "object") for (const [k, v] of Object.entries(value)) leaves(v, `${at3}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`, out);
3400
+ else out.push([at3 || "", value]);
3401
+ return out;
3402
+ }
3403
+ function at2(value, pointer) {
3404
+ if (pointer === "" || pointer === "/") return pointer === "" ? value : value?.[""];
3405
+ let here = value;
3406
+ for (const raw of pointer.slice(1).split("/")) {
3407
+ const key = raw.replace(/~1/g, "/").replace(/~0/g, "~");
3408
+ if (here === null || typeof here !== "object" || !(key in here)) return void 0;
3409
+ here = here[key];
3410
+ }
3411
+ return here;
3412
+ }
3413
+ var under2 = (pointer, set) => [...set].some((p) => pointer === p || pointer.startsWith(`${p}/`));
3414
+ var anyEntry = (pointer) => pointer.replace(/\/\d+(?=\/|$)/g, "/0");
3415
+ var BLOCK_KEYS = /* @__PURE__ */ new Set(["blockType", "_type"]);
3416
+ function schemaValues(schema) {
3417
+ const out = /* @__PURE__ */ new Set();
3418
+ const keep = (v) => (typeof v === "string" || typeof v === "number" && Number.isFinite(v)) && out.add(v);
3419
+ const walk = (node, depth) => {
3420
+ if (!node || typeof node !== "object" || depth > 64) return;
3421
+ if (Array.isArray(node)) return node.forEach((n) => walk(n, depth + 1));
3422
+ if ("const" in node) keep(node.const);
3423
+ if (Array.isArray(node.enum)) node.enum.forEach(keep);
3424
+ for (const [k, v] of Object.entries(node)) if (k !== "const" && k !== "enum" && k !== "default" && k !== "examples") walk(v, depth + 1);
3425
+ };
3426
+ walk(schema, 0);
3427
+ return [...out];
3428
+ }
3429
+ function structure(c) {
3430
+ const pointers = /* @__PURE__ */ new Set();
3431
+ const discriminators = /* @__PURE__ */ new Set();
3432
+ const fixed2 = /* @__PURE__ */ new Set();
3433
+ const keyOf = (v) => `${typeof v}:${typeof v === "string" ? sameText(v) : v}`;
3434
+ const walk = (fields) => {
3435
+ for (const f of fields ?? []) {
3436
+ const pointer = f.pointer ?? `/${f.key}`;
3437
+ if (f.type === "option" || f.type === "options" || f.type === "tags" || f.options?.length) pointers.add(pointer);
3438
+ for (const o of f.options ?? []) fixed2.add(keyOf(o));
3439
+ if (f.blocks) {
3440
+ discriminators.add(`${pointer}/0/${f.blocks.key ?? "blockType"}`);
3441
+ for (const t of f.blocks.types ?? []) {
3442
+ fixed2.add(keyOf(typeof t === "string" ? t : t.value));
3443
+ if (typeof t === "object") walk(t.fields);
3444
+ }
3445
+ }
3446
+ walk(f.fields);
3447
+ }
3448
+ };
3449
+ walk(c.fields);
3450
+ if (c.order) pointers.add(`/${c.order}`);
3451
+ for (const v of c.fixed ?? []) fixed2.add(keyOf(v));
3452
+ return (pointer, value) => {
3453
+ const any = anyEntry(pointer);
3454
+ if (under2(any, pointers) || discriminators.has(any)) return true;
3455
+ const parts = pointer.split("/");
3456
+ if (parts.length >= 3 && /^\d+$/.test(parts[parts.length - 2]) && BLOCK_KEYS.has(parts[parts.length - 1])) return true;
3457
+ return (typeof value === "string" || typeof value === "number") && fixed2.has(keyOf(value));
3458
+ };
3459
+ }
3460
+ function readable(text) {
3461
+ const map = [];
3462
+ let out = "";
3463
+ const push = (s, i) => {
3464
+ for (const c of s) {
3465
+ out += c;
3466
+ map.push(i);
3467
+ }
3468
+ };
3469
+ const ENTITIES2 = { "&amp;": "&", "&quot;": '"', "&#39;": "'", "&apos;": "'", "&lt;": "<", "&gt;": ">", "&nbsp;": " " };
3470
+ let space = false;
3471
+ for (let i = 0; i < text.length; i++) {
3472
+ const c = text[i];
3473
+ if (/\s/.test(c)) {
3474
+ if (!space) push(" ", i);
3475
+ space = true;
3476
+ continue;
3477
+ }
3478
+ space = false;
3479
+ if (c === "\\" && /["'`]/.test(text[i + 1] ?? "")) {
3480
+ push(text[i + 1], i);
3481
+ i++;
3482
+ continue;
3483
+ }
3484
+ if (c === "&") {
3485
+ const e = /^&(?:amp|quot|#39|apos|lt|gt|nbsp);/.exec(text.slice(i, i + 6));
3486
+ if (e) {
3487
+ const v = ENTITIES2[e[0]];
3488
+ if (v === " ") {
3489
+ if (!space) push(" ", i);
3490
+ space = true;
3491
+ } else push(v, i);
3492
+ i += e[0].length - 1;
3493
+ continue;
3494
+ }
3495
+ }
3496
+ push(c, i);
3497
+ }
3498
+ return { text: out, map };
3499
+ }
3500
+ var lineAt = (text, index) => text.slice(0, index).split("\n").length;
3501
+ var isContent = (path, adapter) => contentKind(path, adapter) !== null;
3502
+ function written(value, text) {
3503
+ const re = typeof value === "number" ? new RegExp(`(?<![\\p{N}.,])${escapeText(String(value))}(?![\\p{N}]|[.,]\\p{N})`, "u") : new RegExp(`(?<![\\p{L}\\p{N}])${escapeText(collapse(value))}(?![\\p{L}\\p{N}])`, "u");
3504
+ return re.exec(text);
3505
+ }
3506
+ function noCopiedContent({ files, collections, adapter }) {
3507
+ const values = /* @__PURE__ */ new Map();
3508
+ const shared = /* @__PURE__ */ new Set();
3509
+ const shorter = [];
3510
+ const holders = /* @__PURE__ */ new Map();
3511
+ for (const c of collections) {
3512
+ const schemaOwn = structure(c);
3513
+ const seen = /* @__PURE__ */ new Map();
3514
+ for (const item of c.items ?? []) {
3515
+ const own = [];
3516
+ for (const [pointer, v] of leaves(item.data)) {
3517
+ if (schemaOwn(pointer, v)) continue;
3518
+ if (significant(v)) {
3519
+ const key = collapse(v);
3520
+ if (seen.has(key) && seen.get(key) !== item.id) shared.add(key);
3521
+ seen.set(key, item.id);
3522
+ if (!values.has(key)) values.set(key, { collection: c.name, item: item.id, field: pointer });
3523
+ } else if (distinctive(v)) own.push([pointer, v]);
3524
+ }
3525
+ for (const k of new Set(own.map(([, v]) => `${typeof v}:${sameText(v)}`))) holders.set(k, (holders.get(k) ?? 0) + 1);
3526
+ shorter.push([c.name, item.id, own]);
3527
+ }
3528
+ }
3529
+ for (const k of shared) values.delete(k);
3530
+ const findings = [];
3531
+ const adapters = Array.isArray(adapter) ? adapter : [adapter];
3532
+ for (const f of files) {
3533
+ if (!f.text || !/\.(astro|tsx?|jsx?|mts|mjs|cjs|cts|vue|svelte|html)$/.test(f.path) || adapters.some((a) => isContent(f.path, a))) continue;
3534
+ const now = readable(f.text);
3535
+ const was = f.before ? readable(f.before).text : "";
3536
+ const reported = /* @__PURE__ */ new Set();
3537
+ for (const [value, where] of values) {
3538
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${escapeText(value)}(?![\\p{L}\\p{N}])`, "u");
3539
+ const m = re.exec(now.text);
3540
+ if (!m || re.test(was)) continue;
3541
+ reported.add(`${where.collection}\0${where.item}`);
3542
+ findings.push({ check: "noCopiedContent", file: f.path, line: lineAt(f.text, now.map[m.index]), ...where, value });
3543
+ }
3544
+ for (const [collection, item, own] of shorter) {
3545
+ if (reported.has(`${collection}\0${item}`)) continue;
3546
+ const found = /* @__PURE__ */ new Map();
3547
+ for (const [pointer, v] of own) {
3548
+ const k = `${typeof v}:${sameText(v)}`;
3549
+ if (found.has(k) || holders.get(k) > 1) continue;
3550
+ const m = written(v, now.text);
3551
+ if (!m || written(v, was)) continue;
3552
+ found.set(k, { field: pointer, value: v, at: m.index });
3553
+ }
3554
+ const all = [...found.values()].sort((a, b) => a.at - b.at);
3555
+ if (all.length < 2 || !all.some((x) => typeof x.value === "string")) continue;
3556
+ const first = all.find((x) => typeof x.value === "string");
3557
+ findings.push({
3558
+ check: "noCopiedContent",
3559
+ file: f.path,
3560
+ line: lineAt(f.text, now.map[all[0].at]),
3561
+ collection,
3562
+ item,
3563
+ field: first.field,
3564
+ value: collapse(first.value),
3565
+ together: all.map((x) => ({ field: x.field, value: x.value }))
3566
+ });
3567
+ }
3568
+ }
3569
+ return findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
3570
+ }
3571
+ var CONTENT_FILE = /\.(json|md|mdx|markdoc|ya?ml)$/;
3572
+ var ASSET_FILE = /\.(png|jpe?g|gif|webp|avif|svg|ico|mp4|webm|mov|pdf)$/i;
3573
+ function contentKind(path, adapter) {
3574
+ if (adapter.content.some((r) => path.startsWith(r))) {
3575
+ const rest = path.slice(adapter.content.find((r) => path.startsWith(r)).length);
3576
+ if (rest.split("/").pop() === ".gitkeep") return "content";
3577
+ return !rest.split("/").some((s) => s.startsWith(".")) && CONTENT_FILE.test(rest) ? "content" : null;
3578
+ }
3579
+ if (adapter.assets.some((r) => path.startsWith(r)) && ASSET_FILE.test(path)) return "asset";
3580
+ return null;
3581
+ }
3582
+ function contentKeptCode({ files, adapter }) {
3583
+ return files.filter((f) => contentKind(f.path, adapter) === null).map((f) => ({ check: "contentKeptCode", file: f.path, ...f.deleted ? { deleted: true } : {} })).sort((a, b) => a.file.localeCompare(b.file));
3584
+ }
3585
+ var asMap = (files) => new Map((Array.isArray(files) ? files : Object.entries(files ?? {}).map(([path, text]) => ({ path, text }))).map((f) => [f.path, f.text]));
3586
+ var bindingKey = (page, b) => JSON.stringify([page, b.collection, b.item, b.field]);
3587
+ function designKeptContent({ before, after, adapter }) {
3588
+ const findings = [];
3589
+ const was = asMap(before.files);
3590
+ const now = asMap(after.files);
3591
+ for (const path of [.../* @__PURE__ */ new Set([...was.keys(), ...now.keys()])].sort()) {
3592
+ if (contentKind(path, adapter) === null) continue;
3593
+ const a = was.get(path);
3594
+ const b = now.get(path);
3595
+ if (a === b) continue;
3596
+ findings.push({ check: "designKeptContent", kind: "content-changed", file: path, change: a === void 0 ? "added" : b === void 0 ? "removed" : "changed" });
3597
+ }
3598
+ const count = (all) => {
3599
+ const n = /* @__PURE__ */ new Map();
3600
+ for (const p of all ?? []) for (const e of p.elements) if (e.binding) n.set(bindingKey(p.page, e.binding), (n.get(bindingKey(p.page, e.binding)) ?? 0) + 1);
3601
+ return n;
3602
+ };
3603
+ const n0 = count(before.bindings);
3604
+ const n1 = count(after.bindings);
3605
+ for (const [k, n] of n0) {
3606
+ const m = n1.get(k) ?? 0;
3607
+ if (m >= n) continue;
3608
+ const [page, collection, item, field2] = JSON.parse(k);
3609
+ findings.push({ check: "designKeptContent", kind: "binding-lost", page, collection, item, field: field2, before: n, after: m });
3610
+ }
3611
+ const afterByKey = /* @__PURE__ */ new Map();
3612
+ for (const p of after.bindings ?? []) for (const e of p.elements) if (e.key) afterByKey.set(JSON.stringify([p.page, e.key]), e);
3613
+ for (const p of before.bindings ?? []) {
3614
+ for (const e of p.elements) {
3615
+ if (!e.binding || !e.key) continue;
3616
+ const later = afterByKey.get(JSON.stringify([p.page, e.key]));
3617
+ if (!later || later.binding && bindingKey(p.page, later.binding) === bindingKey(p.page, e.binding)) continue;
3618
+ findings.push({ check: "designKeptContent", kind: "binding-moved", page: p.page, key: e.key, from: e.binding, to: later.binding ?? { reason: later.reason } });
3619
+ }
3620
+ }
3621
+ return findings;
3622
+ }
3623
+ var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
3624
+ var RAW = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "template", "noscript", "xmp", "iframe"]);
3625
+ var OUT = /^(script|style|link|meta|template|noscript|astro-dev-toolbar|vite-error-overlay)$/;
3626
+ var NO_TEXT = /^(script|style|template|noscript|svg|title|head|iframe|canvas)$/;
3627
+ function decode(s) {
3628
+ return s.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp|#39);/gi, (_, e) => {
3629
+ const k = e.toLowerCase();
3630
+ if (k[0] === "#") {
3631
+ const n = k[1] === "x" ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10);
3632
+ return Number.isFinite(n) ? String.fromCodePoint(n) : _;
3633
+ }
3634
+ return { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }[k] ?? _;
3635
+ });
3636
+ }
3637
+ function parseHtml(html) {
3638
+ const root = { tag: "#root", attrs: {}, children: [], parent: null };
3639
+ let here = root;
3640
+ let i = 0;
3641
+ while (i < html.length) {
3642
+ const lt = html.indexOf("<", i);
3643
+ if (lt < 0) {
3644
+ here.children.push(decode(html.slice(i)));
3645
+ break;
3646
+ }
3647
+ if (lt > i) here.children.push(decode(html.slice(i, lt)));
3648
+ if (html.startsWith("<!--", lt)) {
3649
+ const end = html.indexOf("-->", lt + 4);
3650
+ i = end < 0 ? html.length : end + 3;
3651
+ continue;
3652
+ }
3653
+ if (html[lt + 1] === "!" || html[lt + 1] === "?") {
3654
+ const end = html.indexOf(">", lt);
3655
+ i = end < 0 ? html.length : end + 1;
3656
+ continue;
3657
+ }
3658
+ const close = /^<\/([A-Za-z][\w:-]*)\s*>/.exec(html.slice(lt, lt + 200));
3659
+ if (close) {
3660
+ const tag2 = close[1].toLowerCase();
3661
+ let n = here;
3662
+ while (n && n.tag !== tag2) n = n.parent;
3663
+ if (n && n.parent) here = n.parent;
3664
+ i = lt + close[0].length;
3665
+ continue;
3666
+ }
3667
+ const open = /^<([A-Za-z][\w:-]*)/.exec(html.slice(lt, lt + 100));
3668
+ if (!open) {
3669
+ here.children.push("<");
3670
+ i = lt + 1;
3671
+ continue;
3672
+ }
3673
+ let j = lt + open[0].length;
3674
+ let quote = null;
3675
+ for (; j < html.length; j++) {
3676
+ const c = html[j];
3677
+ if (quote) {
3678
+ if (c === quote) quote = null;
3679
+ } else if (c === '"' || c === "'") quote = c;
3680
+ else if (c === ">") break;
3681
+ }
3682
+ const body = html.slice(lt + open[0].length, j);
3683
+ const attrs = {};
3684
+ for (const a of body.matchAll(/([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) attrs[a[1].toLowerCase()] = decode(a[2] ?? a[3] ?? a[4] ?? "");
3685
+ const tag = open[1].toLowerCase();
3686
+ const node = { tag, attrs, children: [], parent: here, end: j };
3687
+ here.children.push(node);
3688
+ i = j + 1;
3689
+ if (VOID.has(tag) || body.trimEnd().endsWith("/")) continue;
3690
+ if (RAW.has(tag)) {
3691
+ const end = html.toLowerCase().indexOf(`</${tag}`, i);
3692
+ const inner = html.slice(i, end < 0 ? html.length : end);
3693
+ if (tag !== "template") node.children.push(tag === "title" || tag === "textarea" ? decode(inner) : inner);
3694
+ const gt = end < 0 ? -1 : html.indexOf(">", end);
3695
+ i = gt < 0 ? html.length : gt + 1;
3696
+ continue;
3697
+ }
3698
+ here = node;
3699
+ }
3700
+ return root;
3701
+ }
3702
+ function textOf(node) {
3703
+ if (typeof node === "string") return node;
3704
+ if (node.tag === "br") return " ";
3705
+ if (NO_TEXT.test(node.tag)) return "";
3706
+ return node.children.map(textOf).join("");
3707
+ }
3708
+ var wholeText = (node) => collapse(textOf(node));
3709
+ function elementsOf(html) {
3710
+ const root = typeof html === "string" ? parseHtml(html) : html;
3711
+ const find = (n, tag) => {
3712
+ for (const c of n.children) {
3713
+ if (typeof c === "string") continue;
3714
+ if (c.tag === tag) return c;
3715
+ const d = find(c, tag);
3716
+ if (d) return d;
3717
+ }
3718
+ return null;
3719
+ };
3720
+ const body = find(root, "body") ?? root;
3721
+ const out = [];
3722
+ const outside = (e) => OUT.test(e.tag) || e.attrs.id === "comment-modus" || e.attrs.id === "comment-modus-schil" || "data-cm-ignore" in e.attrs || "data-cm-negeer" in e.attrs || "data-unbase-layer" in e.attrs;
3723
+ const walk = (n, place, depth) => {
3724
+ const seen = /* @__PURE__ */ new Map();
3725
+ for (const c of n.children) {
3726
+ if (typeof c === "string" || outside(c)) continue;
3727
+ const k = seen.get(c.tag) ?? 0;
3728
+ seen.set(c.tag, k + 1);
3729
+ const at3 = `${place ? `${place}/` : ""}${c.tag}:${k}`;
3730
+ out.push({ node: c, at: at3, depth, text: wholeText(c) });
3731
+ walk(c, at3, depth + 1);
3732
+ }
3733
+ };
3734
+ walk(body, "", 0);
3735
+ return out;
3736
+ }
3737
+ var shown = (v) => typeof v === "string" && collapse(v).length >= 3 && /[\p{L}\p{N}]/u.test(v);
3738
+ function fieldRef(ref) {
3739
+ const i = ref.indexOf("#");
3740
+ if (i <= 0) return null;
3741
+ return { file: ref.slice(0, i), pointer: ref.slice(i + 1) };
3742
+ }
3743
+ function binds({ html, page = "", collections, adapter, answer }) {
3744
+ const byFile = /* @__PURE__ */ new Map();
3745
+ const byValue = /* @__PURE__ */ new Map();
3746
+ for (const c of collections) {
3747
+ for (const item of c.items ?? []) {
3748
+ if (item.file) byFile.set(item.file, { collection: c.name, item });
3749
+ for (const [pointer, v] of leaves(item.data)) {
3750
+ if (!shown(v)) continue;
3751
+ const k = collapse(v);
3752
+ byValue.set(k, [...byValue.get(k) ?? [], { collection: c.name, item: item.id, field: pointer }]);
3753
+ }
3754
+ }
3755
+ }
3756
+ const markers = adapter.markers;
3757
+ const answeredAt = new Map(Object.values(answer?.elements ?? {}).filter((x) => x.at).map((x) => [x.at, x]));
3758
+ const identityOf = (e) => {
3759
+ if (!markers) return null;
3760
+ const [src, ...rest] = markers.identity;
3761
+ const s = e.node.attrs[src];
3762
+ return s ? [s, ...rest.map((r) => e.node.attrs[r] ?? "")].join("|") : null;
3763
+ };
3764
+ const markedOf = (e, identity) => {
3765
+ if (!markers) return null;
3766
+ for (const a of markers.field) if (e.node.attrs[a]) return { field: e.node.attrs[a] };
3767
+ if (e.node.attrs[markers.reason]) return { reason: e.node.attrs[markers.reason] };
3768
+ const answered = identity && answer?.elements?.[identity] || answeredAt.get(e.at);
3769
+ if (answered?.reason) return { reason: answered.reason };
3770
+ if (answered?.field) {
3771
+ const f = answer?.fields?.[answered.field];
3772
+ if (f?.kind === "content" && f.file && f.pointer !== void 0) return { field: `${f.file}#${f.pointer}` };
3773
+ return f ? { outside: true } : fieldRef(answered.field) ? { field: answered.field } : null;
3774
+ }
3775
+ return null;
3776
+ };
3777
+ const all = elementsOf(html);
3778
+ const elements = [];
3779
+ const covered = /* @__PURE__ */ new Set();
3780
+ for (let i = 0; i < all.length; i++) {
3781
+ const e = all[i];
3782
+ const parentCovered = covered.has(e.node.parent) && e.node.parent && wholeText(e.node.parent) === e.text;
3783
+ if (parentCovered) {
3784
+ covered.add(e.node);
3785
+ continue;
3786
+ }
3787
+ const identity = identityOf(e);
3788
+ const marked = markedOf(e, identity);
3789
+ const candidates = byValue.get(e.text) ?? [];
3790
+ const key = identity ?? e.at;
3791
+ const base = { key, at: e.at, tag: e.node.tag, text: e.text };
3792
+ if (marked?.field) {
3793
+ const ref = fieldRef(marked.field);
3794
+ const owner = ref && byFile.get(ref.file);
3795
+ covered.add(e.node);
3796
+ if (!owner) continue;
3797
+ const value = at2(owner.item.data, ref.pointer);
3798
+ const binding = { collection: owner.collection, item: owner.item.id, field: ref.pointer };
3799
+ if (value !== void 0 && value !== null && typeof value !== "object" && collapse(value) === e.text) elements.push({ ...base, binding });
3800
+ else elements.push({ ...base, reason: "unproven", marked: binding });
3801
+ continue;
3802
+ }
3803
+ if (marked?.outside) {
3804
+ covered.add(e.node);
3805
+ continue;
3806
+ }
3807
+ if (!candidates.length) continue;
3808
+ if (marked?.reason) {
3809
+ covered.add(e.node);
3810
+ elements.push({ ...base, reason: marked.reason, candidates: candidates.length });
3811
+ continue;
3812
+ }
3813
+ const inner = e.node.children.some((c) => typeof c !== "string" && !NO_TEXT.test(c.tag) && wholeText(c) === e.text);
3814
+ if (inner) continue;
3815
+ const reason = !identity ? "no-identity" : candidates.length > 1 ? "ambiguous" : "unproven";
3816
+ elements.push({ ...base, reason, candidates: candidates.length });
3817
+ }
3818
+ const bound = elements.filter((e) => e.binding).length;
3819
+ return { page, elements, bound, unbound: elements.length - bound };
3820
+ }
3821
+ function testDraft({ collection, fields = [], id = "unbase-test-item", token = "Unbase test item", base = {} }) {
3822
+ const data = Object.fromEntries(Object.entries(base ?? {}).map(([k, v]) => [k, significant(v) ? `${k} ${token}` : v]));
3823
+ for (const f of fields) {
3824
+ if (f.pointer && f.pointer.split("/").length > 2) continue;
3825
+ if (f.type === "text" || f.type === "inline" || f.type === "longtext") data[f.key] = `${f.label ?? f.key} ${token}`;
3826
+ else if (f.type === "slug") data[f.key] = id;
3827
+ }
3828
+ return { collection, id, data };
3829
+ }
3830
+ function addressFor(path, slug) {
3831
+ const params = path.match(/\[[^\]]+\]/g) ?? [];
3832
+ if (!params.length) return path;
3833
+ if (params.length > 1 || /\/page\/\[[^\]]+\]$/.test(path)) return null;
3834
+ return path.replace(/\[[^\]]+\]/, slug);
3835
+ }
3836
+ function loaded(page) {
3837
+ const status = page.status ?? (page.html && !page.error ? 200 : 0);
3838
+ if (status >= 500) return false;
3839
+ return status >= 200 && status < 400 && !!page.html && !page.error ? true : null;
3840
+ }
3841
+ var unanswered = (page) => page.status ? `the page answered ${page.status}` : page.error ? `the page did not render: ${String(page.error).slice(0, 200)}` : "the page did not answer";
3842
+ async function newItemShows({ collection, draft, pages, render, adapter, collections = [], baseline = true }) {
3843
+ const tokens = [...new Set(leaves(draft.data).map(([, v]) => v).filter(significant).map(collapse))];
3844
+ if (!tokens.length) return { ok: false, reason: "unproven", why: "the test item has no value specific enough to find on a page", pages: [] };
3845
+ const overlay = { collection, op: (
3846
+ /** @type {const} */
3847
+ "create"
3848
+ ), id: draft.id, data: draft.data, ...draft.file ? { file: draft.file } : {} };
3849
+ const withItem = collections.map((c) => c.name === collection ? { ...c, items: [...c.items ?? [], { id: draft.id, file: draft.file, data: draft.data }] } : c);
3850
+ const asPage = (r) => typeof r === "string" ? { html: r } : r ?? {};
3851
+ const textIn = (html) => wholeText(parseHtml(html));
3852
+ const results = [];
3853
+ for (const p of pages) {
3854
+ const path = addressFor(p.path, draft.slug ?? draft.id);
3855
+ if (path === null) {
3856
+ results.push({ path: p.path, shows: null, reason: "unsupported" });
3857
+ continue;
3858
+ }
3859
+ const route = path !== p.path ? { route: p.path } : {};
3860
+ try {
3861
+ if (baseline) {
3862
+ const before = asPage(await render({ path, overlay: null }));
3863
+ const seen = loaded(before) ? textIn(before.html) : "";
3864
+ const there = tokens.filter((t) => seen.includes(t));
3865
+ if (there.length) {
3866
+ results.push({ path, ...route, shows: null, reason: "unproven", why: `already on the page without the item: ${there[0]}` });
3867
+ continue;
3868
+ }
3869
+ }
3870
+ const after = asPage(await render({ path, overlay }));
3871
+ const answer = loaded(after);
3872
+ if (answer !== true) {
3873
+ const said = { ...after.status ? { status: after.status } : {}, ...after.error ? { error: after.error } : {} };
3874
+ results.push(answer === false ? { path, ...route, shows: false, ...said } : { path, ...route, shows: null, reason: "unproven", why: unanswered(after), ...said });
3875
+ continue;
3876
+ }
3877
+ const bound = adapter.markers ? binds({ html: after.html, page: path, collections: withItem, adapter }).elements.some((e) => e.binding?.collection === collection && e.binding.item === draft.id) : false;
3878
+ const text = textIn(after.html);
3879
+ const shows = bound || tokens.some((t) => text.includes(t));
3880
+ results.push({ path, ...route, shows, ...shows ? { by: bound ? "binding" : "text" } : {} });
3881
+ } catch (err) {
3882
+ const error = err instanceof Error ? err.message : String(err);
3883
+ results.push({ path, ...route, shows: null, reason: "unproven", why: unanswered({ error }), error });
3884
+ }
3885
+ }
3886
+ return { ok: results.length > 0 && results.every((r) => r.shows === true), pages: results };
3887
+ }
3888
+ var FIELD_NAME = /^[A-Za-z_$][\w$]*$/;
3889
+ function fieldUse({ text, fields }) {
3890
+ const code = stripComments2(text ?? "");
3891
+ const taken = /* @__PURE__ */ new Set();
3892
+ for (const m of code.matchAll(/\{([^{}()]*)\}\s*(?::[^=;{}()]*)?\s*(?:=(?!=)|\))/g)) {
3893
+ for (const part of m[1].split(",")) {
3894
+ const name = part.trim().split(/\s*[:=]/)[0].trim();
3895
+ if (FIELD_NAME.test(name)) taken.add(name);
3896
+ }
3897
+ }
3898
+ return (fields ?? []).map((f) => f.key).filter((k, i, all) => FIELD_NAME.test(k) && all.indexOf(k) === i).filter((k) => taken.has(k) || new RegExp(`\\??\\.\\s*${escape2(k)}(?![\\w$])|\\[\\s*["'\`]${escape2(k)}["'\`]\\s*\\]`).test(code));
3899
+ }
3900
+ var isCode = (path) => CODE3.test(path) && !CONFIG2.test(path);
3901
+ function importedBy(importers) {
3902
+ const imports = /* @__PURE__ */ new Map();
3903
+ for (const [target, by] of importers ?? []) for (const f of by) imports.set(f, [...imports.get(f) ?? [], target]);
3904
+ return (from) => {
3905
+ const seen = /* @__PURE__ */ new Set([from]);
3906
+ const queue = [from];
3907
+ while (queue.length) {
3908
+ for (const next of imports.get(queue.pop()) ?? []) {
3909
+ if (seen.has(next)) continue;
3910
+ seen.add(next);
3911
+ queue.push(next);
3912
+ }
3913
+ }
3914
+ seen.delete(from);
3915
+ return seen;
3916
+ };
3917
+ }
3918
+ function componentsOn({ files, changed, collections, adapter, pages, importers, functions }) {
3919
+ const text = new Map(files.map((f) => [f.path, f.text]));
3920
+ const names = collections.map((c) => c.name);
3921
+ const edges = reads({ files, adapter, collections: names, ...functions ? { functions } : {} });
3922
+ const below = importedBy(importers);
3923
+ const wrote = changed.filter((f) => !f.deleted && isCode(f.path) && text.has(f.path) && !(Array.isArray(adapter) ? adapter : [adapter]).some((a) => isContent(f.path, a))).map((f) => f.path);
3924
+ const out = [];
3925
+ for (const c of collections) {
3926
+ const readers = new Set(edges.filter((r) => r.collection === c.name).map((r) => r.file));
3927
+ if (!readers.size) continue;
3928
+ const showing = readersOf({ collection: c.name, reads: edges, importers: importers ?? /* @__PURE__ */ new Map(), pages });
3929
+ const reading = new Set([...text.keys()].filter((f) => readers.has(f) || [...below(f)].some((x) => readers.has(x))));
3930
+ const uses = (file) => fieldUse({ text: text.get(file) ?? "", fields: c.fields ?? [] });
3931
+ for (const file of wrote) {
3932
+ const fields = uses(file);
3933
+ const passed = [...reading].some((r) => r !== file && below(r).has(file)) && (fields.length > 0 || [...below(file)].some((x) => uses(x).length > 0));
3934
+ const via = (
3935
+ /** @type {"reads" | "props" | "through" | null} */
3936
+ readers.has(file) ? "reads" : passed ? "props" : reading.has(file) ? "through" : null
3937
+ );
3938
+ if (!via) continue;
3939
+ const on = showing.filter((p) => p.file === file || below(p.file).has(file)).map((p) => p.path);
3940
+ out.push({ file, collection: c.name, via, fields, pages: on });
3941
+ }
3942
+ }
3943
+ return out.sort((a, b) => a.file.localeCompare(b.file) || a.collection.localeCompare(b.collection));
3944
+ }
3945
+ var GATE_COLLECTIONS = 2;
3946
+ var GATE_PAGES = 4;
3947
+ async function componentGate({ files, changed, collections, adapter, pages, importers, functions, render }) {
3948
+ const components = componentsOn({ files, changed, collections, adapter, pages, importers, functions });
3949
+ const code = changed.filter((f) => !f.deleted && typeof f.text === "string");
3950
+ const copied = noCopiedContent({ files: code, collections, adapter });
3951
+ const on = new Set(components.map((c) => `${c.file}\0${c.collection}`));
3952
+ const unread = [];
3953
+ for (const f of copied) {
3954
+ const key = `${f.file}\0${f.collection}`;
3955
+ if (on.has(key) || unread.some((u) => `${u.file}\0${u.collection}` === key)) continue;
3956
+ unread.push({ check: "reads", file: f.file, collection: f.collection });
3957
+ }
3958
+ const applies = components.length > 0 || copied.length > 0;
3959
+ const counts = /* @__PURE__ */ new Map();
3960
+ for (const c of components) counts.set(c.collection, (counts.get(c.collection) ?? 0) + 1);
3961
+ const plans = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, GATE_COLLECTIONS).map(([name]) => {
3962
+ const c = collections.find((x) => x.name === name);
3963
+ const draft = testDraft({ collection: name, fields: c.fields ?? [], base: c.items?.[0]?.data ?? {} });
3964
+ const routes = [...new Set(components.filter((x) => x.collection === name).flatMap((x) => x.pages))].slice(0, GATE_PAGES);
3965
+ return {
3966
+ collection: name,
3967
+ draft: { id: draft.id, data: draft.data, ...c.folder ? { file: `${c.folder}/${draft.id}.json` } : {} },
3968
+ routes,
3969
+ paths: routes.map((r) => addressFor(r, draft.id)).filter((p) => p !== null)
3970
+ };
3971
+ });
3972
+ const findings = [...copied, ...unread];
3973
+ const checks = {
3974
+ noCopiedContent: { ok: copied.length === 0, findings: copied },
3975
+ reads: { ok: unread.length === 0, findings: unread }
3976
+ };
3977
+ if (!render || !applies) return { applies, ok: !applies ? true : findings.length ? false : null, components, findings, checks, render: applies ? plans : [] };
3978
+ const kept = /* @__PURE__ */ new Map();
3979
+ const once = (req) => {
3980
+ const k = JSON.stringify([req.path, !!req.overlay]);
3981
+ if (!kept.has(k)) kept.set(k, Promise.resolve().then(() => render(req)));
3982
+ return kept.get(k);
3983
+ };
3984
+ const asPage = (r) => typeof r === "string" ? { html: r } : r ?? {};
3985
+ const build = [];
3986
+ const shows = [];
3987
+ const bindings = { bound: 0, unbound: 0, reasons: {} };
3988
+ for (const plan of plans) {
3989
+ const draft = plan.draft;
3990
+ const overlay = { collection: plan.collection, op: (
3991
+ /** @type {const} */
3992
+ "create"
3993
+ ), id: draft.id, data: draft.data, ...draft.file ? { file: draft.file } : {} };
3994
+ const own = new Set(plan.routes.filter((r) => r.includes("[")).map((r) => addressFor(r, draft.id)).filter((p) => p !== null));
3995
+ for (const path of plan.paths) {
3996
+ const page = asPage(await once({ path, overlay: own.has(path) ? overlay : null }).catch((e) => ({ error: e instanceof Error ? e.message : String(e) })));
3997
+ const ok = loaded(page);
3998
+ build.push({ path, ok, ...page.status ? { status: page.status } : {}, ...page.error ? { error: String(page.error).slice(0, 500) } : {} });
3999
+ }
4000
+ const shown2 = await newItemShows({ collection: plan.collection, draft, pages: plan.routes.map((path) => ({ path })), render: once, adapter, collections, baseline: true });
4001
+ shows.push({ collection: plan.collection, ...shown2 });
4002
+ if (adapter.markers) {
4003
+ const withItem = collections.map((c) => c.name === plan.collection ? { ...c, items: [...c.items ?? [], { id: draft.id, file: draft.file, data: draft.data }] } : c);
4004
+ for (const path of plan.paths) {
4005
+ const page = asPage(await once({ path, overlay }).catch(() => ({})));
4006
+ if (!page.html) continue;
4007
+ for (const e of binds({ html: page.html, page: path, collections: withItem, adapter }).elements) {
4008
+ if (e.binding) {
4009
+ if (e.binding.collection === plan.collection) bindings.bound++;
4010
+ } else {
4011
+ bindings.unbound++;
4012
+ bindings.reasons[e.reason] = (bindings.reasons[e.reason] ?? 0) + 1;
4013
+ }
4014
+ }
4015
+ }
4016
+ }
4017
+ }
4018
+ const broken = build.filter((p) => p.ok === false).map((p) => ({ check: "build", page: p.path, ...p.status ? { status: p.status } : {}, ...p.error ? { error: p.error } : {} }));
4019
+ const missing = shows.flatMap((s) => s.pages.filter((p) => p.shows === false && !broken.some((x) => x.page === p.path)).map((p) => ({ check: "newItemShows", collection: s.collection, page: p.path, ...p.status ? { status: p.status } : {}, ...p.error ? { error: String(p.error).slice(0, 500) } : {} })));
4020
+ const all = [...findings, ...broken, ...missing];
4021
+ const proven = shows.length > 0 && shows.every((s) => s.ok);
4022
+ return {
4023
+ applies,
4024
+ ok: all.length === 0,
4025
+ components,
4026
+ findings: all,
4027
+ checks: {
4028
+ ...checks,
4029
+ build: { ok: broken.length === 0, pages: build },
4030
+ newItemShows: { ok: missing.length ? false : proven ? true : null, collections: shows },
4031
+ binds: adapter.markers ? bindings : { bound: 0, unbound: null, reason: "no-identity" }
4032
+ },
4033
+ render: plans
4034
+ };
4035
+ }
4036
+ var TAG_OPEN = "\u{E0001}";
4037
+ var TAG_CLOSE = "\u{E007F}";
4038
+ var TAG = /\u{E0001}([\u{E0020}-\u{E007E}]*)\u{E007F}/gu;
4039
+ var TAG_CHAR = /[\u{E0000}-\u{E007F}]/gu;
4040
+ var TAGGED_TYPES = ["text", "inline", "longtext"];
4041
+ function tagOf({ collection, id, pointer }) {
4042
+ const plain2 = `${collection}|${id}|${pointer}`;
4043
+ if (!/^[\x20-\x7e]+$/.test(plain2) || collection.includes("|") || id.includes("|")) return null;
4044
+ return TAG_OPEN + [...plain2].map((c) => String.fromCodePoint(917504 + c.charCodeAt(0))).join("") + TAG_CLOSE;
4045
+ }
4046
+ function tagsIn2(text) {
4047
+ const out = [];
4048
+ for (const m of String(text ?? "").matchAll(TAG)) {
4049
+ const plain2 = [...m[1]].map((c) => String.fromCharCode(c.codePointAt(0) - 917504)).join("");
4050
+ const [collection, id, ...rest] = plain2.split("|");
4051
+ const pointer = rest.join("|");
4052
+ if (collection && id && pointer.startsWith("/")) out.push({ collection, id, pointer });
4053
+ }
4054
+ return out;
4055
+ }
4056
+ var untag = (text) => String(text ?? "").replace(TAG, "").replace(TAG_CHAR, "").replace(/\uDB40(?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC01-\uDC7F]/g, "");
4057
+ function tagItem({ collection, id, data, fields = [] }) {
4058
+ const esc = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
4059
+ const walk = (value, pointer, field2) => {
4060
+ if (typeof value === "string") {
4061
+ const v = value.trim();
4062
+ if (!field2 || !TAGGED_TYPES.includes(field2.type) || !v || /[\u{E0000}-\u{E007F}]/u.test(value) || /^(?:[a-z][a-z0-9+.-]*:|\/|#|www\.)/i.test(v)) return value;
4063
+ const tag = tagOf({ collection, id, pointer });
4064
+ return tag ? value + tag : value;
4065
+ }
4066
+ if (Array.isArray(value)) return field2?.type === "list" ? value.map((v, i) => walk(v, `${pointer}/${i}`, { type: "group", fields: field2.fields ?? [] })) : value;
4067
+ if (value && typeof value === "object" && field2 && (field2.type === "group" || field2.type === "item")) {
4068
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, `${pointer}/${esc(k)}`, (field2.fields ?? []).find((f) => f.key === k) ?? null)]));
4069
+ }
4070
+ return value;
4071
+ };
4072
+ return walk(data, "", { type: "item", fields });
4073
+ }
4074
+ function literalValue(src) {
4075
+ const t = src.trim();
4076
+ if (t === "undefined") return { value: void 0 };
4077
+ const s = fixed(t);
4078
+ if (s !== null) return { value: s };
4079
+ if (/^-?\d+(?:\.\d+)?$/.test(t)) return { value: Number(t) };
4080
+ if (t === "true" || t === "false") return { value: t === "true" };
4081
+ if (t.startsWith("[")) {
4082
+ const inner = balanced(t, 0);
4083
+ if (inner === null) return null;
4084
+ const parts = argumentsOf(inner).map((p) => fixed(p));
4085
+ return parts.every((p) => p !== null) ? { value: parts } : null;
4086
+ }
4087
+ if (t.startsWith("{")) {
4088
+ const inner = balanced(t, 0);
4089
+ if (inner === null) return null;
4090
+ const out = {};
4091
+ for (const part of argumentsOf(inner)) {
4092
+ const m = /^\s*(?:([A-Za-z_$][\w$]*)|"([^"]*)"|'([^']*)')\s*:\s*([\s\S]+)$/.exec(part);
4093
+ if (!m) return null;
4094
+ const v = literalValue(m[4]);
4095
+ if (!v || v.value && typeof v.value === "object") return null;
4096
+ out[m[1] ?? m[2] ?? m[3]] = v.value;
4097
+ }
4098
+ return { value: out };
4099
+ }
4100
+ return null;
4101
+ }
4102
+ function formatsIn({ files, adapter }) {
4103
+ const allowed = new Set(adapter?.formats ?? []);
4104
+ const out = [];
4105
+ const seen = /* @__PURE__ */ new Set();
4106
+ const add = (f) => {
4107
+ const { file: _file, ...rest } = f;
4108
+ const key = JSON.stringify(rest);
4109
+ if (seen.has(key)) return;
4110
+ try {
4111
+ if (f.kind === "intl") new Intl.NumberFormat(f.locale, f.options).format(1);
4112
+ else 1 .toFixed(f.digits);
4113
+ } catch {
4114
+ return;
4115
+ }
4116
+ seen.add(key);
4117
+ out.push(f);
4118
+ };
4119
+ for (const file of files ?? []) {
4120
+ if (!isCode(file.path)) continue;
4121
+ const code = stripComments2(file.text ?? "");
4122
+ if (allowed.has("intl")) {
4123
+ for (const m of code.matchAll(/(?:\bnew\s+Intl\.NumberFormat|\.toLocaleString)\s*\(/g)) {
4124
+ const inner = balanced(code, m.index + m[0].length - 1);
4125
+ if (inner === null) continue;
4126
+ const args = argumentsOf(inner);
4127
+ if (args.length > 2) continue;
4128
+ const locale = args[0] === void 0 ? { value: void 0 } : literalValue(args[0]);
4129
+ const options = args[1] === void 0 ? { value: void 0 } : literalValue(args[1]);
4130
+ if (!locale || !options) continue;
4131
+ if (locale.value !== void 0 && typeof locale.value !== "string" && !Array.isArray(locale.value)) continue;
4132
+ if (options.value !== void 0 && (typeof options.value !== "object" || Array.isArray(options.value))) continue;
4133
+ add({ kind: "intl", ...locale.value !== void 0 ? { locale: locale.value } : {}, ...options.value !== void 0 ? { options: options.value } : {}, file: file.path });
4134
+ }
4135
+ }
4136
+ if (allowed.has("fixed")) for (const m of code.matchAll(/\.toFixed\(\s*(\d{1,2})\s*\)/g)) add({ kind: "fixed", digits: Number(m[1]), file: file.path });
4137
+ }
4138
+ return out;
4139
+ }
4140
+ function renderings(value, formats) {
4141
+ if (typeof value === "number" && Number.isFinite(value)) {
4142
+ const out = [{ text: String(value), format: null }];
4143
+ for (const f of formats) {
4144
+ try {
4145
+ out.push({ text: f.kind === "intl" ? new Intl.NumberFormat(f.locale, f.options).format(value) : value.toFixed(f.digits), format: f });
4146
+ } catch {
4147
+ }
4148
+ }
4149
+ return out;
4150
+ }
4151
+ if (typeof value === "string" && value.trim()) return [{ text: value, format: null }];
4152
+ return [];
4153
+ }
4154
+ function imageShows(src, value, adapter) {
4155
+ if (typeof src !== "string" || typeof value !== "string" || !src || !value.trim()) return false;
4156
+ const pathOf = (p) => {
4157
+ try {
4158
+ return new URL(p, "http://site.invalid/").pathname;
4159
+ } catch {
4160
+ return p.split(/[?#]/)[0];
4161
+ }
4162
+ };
4163
+ const tail = (p) => {
4164
+ let d = p;
4165
+ try {
4166
+ d = decodeURIComponent(p);
4167
+ } catch {
4168
+ }
4169
+ return d.split(/[?#]/)[0].replace(/^(?:\.{1,2}\/)+/, "").replace(/^\/+/, "").replace(/^(?:public|src)\//, "");
4170
+ };
4171
+ const want = tail(value);
4172
+ if (!want) return false;
4173
+ const ends = (p) => {
4174
+ const t = tail(p);
4175
+ return t === want || t.endsWith(`/${want}`);
4176
+ };
4177
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value) && src === value) return true;
4178
+ if (ends(pathOf(src))) return true;
4179
+ for (const t of adapter?.images ?? []) {
4180
+ if ("query" in t) {
4181
+ let param = null;
4182
+ try {
4183
+ param = new URL(src, "http://site.invalid/").searchParams.get(t.query);
4184
+ } catch {
4185
+ }
4186
+ if (param && ends(pathOf(param))) return true;
4187
+ } else if ("hashed" in t) {
4188
+ const path = pathOf(src);
4189
+ const name = want.split("/").pop() ?? "";
4190
+ const stem = name.replace(/\.[^.]+$/, "");
4191
+ if (stem && path.startsWith(t.hashed) && new RegExp(`^${escapeText(stem)}\\.[\\w-]{6,}\\.\\w+$`).test(path.split("/").pop() ?? "")) return true;
4192
+ }
4193
+ }
4194
+ return false;
4195
+ }
4196
+ var escapeAttr = (v) => String(v).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
4197
+ var WHOLE_PAGE = /^(#root|html|body|main)$/;
4198
+ function itemsIn({ html, collections, adapter, uses = {}, formats = [] }) {
4199
+ const items = /* @__PURE__ */ new Map();
4200
+ for (const c of collections) for (const it of c.items ?? []) items.set(`${c.name}/${it.id}`, { collection: c.name, id: it.id, file: it.file ?? null, data: it.data, fields: c.fields ?? [] });
4201
+ const reads2 = (collection, key) => (uses[collection] ?? []).includes(key);
4202
+ const top = (pointer) => (pointer.split("/")[1] ?? "").replace(/~1/g, "/").replace(/~0/g, "~");
4203
+ const root = parseHtml(html);
4204
+ const under3 = /* @__PURE__ */ new Map();
4205
+ const collect = (n) => {
4206
+ const set = /* @__PURE__ */ new Set();
4207
+ for (const v of Object.values(n.attrs)) for (const r of tagsIn2(v)) set.add(`${r.collection}/${r.id}`);
4208
+ for (const c of n.children) {
4209
+ if (typeof c === "string") {
4210
+ if (!NO_TEXT.test(n.tag)) for (const r of tagsIn2(c)) set.add(`${r.collection}/${r.id}`);
4211
+ } else for (const k of collect(c)) set.add(k);
4212
+ }
4213
+ under3.set(n, set);
4214
+ return set;
4215
+ };
4216
+ collect(root);
4217
+ const ownerOf = (n) => {
4218
+ const s = under3.get(n);
4219
+ if (!s?.size) return null;
4220
+ if (s.size === 1) return [...s][0];
4221
+ const parts = n.children.map((c) => typeof c === "string" ? new Set(NO_TEXT.test(n.tag) ? [] : tagsIn2(c).map((r) => `${r.collection}/${r.id}`)) : under3.get(c));
4222
+ const nested = [...s].filter((k) => {
4223
+ const holding = parts.filter((p) => p?.has(k));
4224
+ return holding.length === 1 && holding[0].size === 1;
4225
+ });
4226
+ const left = [...s].filter((k) => !nested.includes(k));
4227
+ return left.length === 1 ? left[0] : null;
4228
+ };
4229
+ const cardItem = (node) => {
4230
+ for (let n = node; n; n = n.parent) {
4231
+ if (under3.get(n)?.size) return WHOLE_PAGE.test(n.tag) ? null : ownerOf(n);
4232
+ }
4233
+ return null;
4234
+ };
4235
+ const stamps = /* @__PURE__ */ new Map();
4236
+ const stamp = (node, attrs) => stamps.set(node, { ...stamps.get(node) ?? {}, ...attrs });
4237
+ const elements = [];
4238
+ const keyOf = (it, pointer) => it.file ? `${it.file}#${pointer}` : null;
4239
+ const list = (e, found, it) => {
4240
+ elements.push({ at: e.at, tag: e.node.tag, text: found.text ?? e.text, ...found, ...it ? { item: { collection: it.collection, id: it.id } } : {} });
4241
+ if (!it) return;
4242
+ const attrs = { "data-unbase-cms": `${it.collection}/${it.id}` };
4243
+ if (found.binding && found.key) attrs["data-unbase-cms-field"] = found.key;
4244
+ if (found.binding && found.key && found.exact) attrs["data-cm-field"] = attrs["data-cm-veld"] = found.key;
4245
+ if (found.reason) attrs["data-unbase-cms-reason"] = found.reason;
4246
+ stamp(e.node, attrs);
4247
+ };
4248
+ const bind = (it, pointer, extra = {}) => ({ binding: { collection: it.collection, item: it.id, field: pointer }, key: keyOf(it, pointer), ...extra });
4249
+ const ownText = (node) => node.children.filter((c) => typeof c === "string").join("");
4250
+ for (const e of elementsOf(root)) {
4251
+ const node = e.node;
4252
+ if (node.tag === "img") {
4253
+ const src = node.attrs.src ?? "";
4254
+ if (!src) continue;
4255
+ const own2 = new Set(Object.values(node.attrs).flatMap((v) => tagsIn2(v).map((r) => `${r.collection}/${r.id}`)));
4256
+ const itemKey2 = own2.size === 1 ? [...own2][0] : own2.size ? null : cardItem(node.parent);
4257
+ const showing = (it3) => it3.fields.filter((f) => f.type === "image" && reads2(it3.collection, f.key) && imageShows(src, it3.data?.[f.key], adapter)).map((f) => f.key);
4258
+ const it2 = itemKey2 ? items.get(itemKey2) : null;
4259
+ if (it2) {
4260
+ const fit = showing(it2);
4261
+ if (fit.length === 1) list(e, { text: "", ...bind(it2, `/${fit[0]}`, { image: true }) }, it2);
4262
+ else if (fit.length > 1) list(e, { text: "", reason: "ambiguous", candidates: fit.length }, it2);
4263
+ else if (it2.fields.some((f) => f.type === "image" && reads2(it2.collection, f.key))) list(e, { text: "", reason: "unproven" }, it2);
4264
+ } else {
4265
+ const anywhere = [...items.values()].flatMap((x) => showing(x));
4266
+ if (anywhere.length) list(e, { text: "", reason: anywhere.length > 1 ? "ambiguous" : "unproven", candidates: anywhere.length }, null);
4267
+ }
4268
+ continue;
4269
+ }
4270
+ const visible = collapse(untag(e.text));
4271
+ if (!visible) continue;
4272
+ if (node.children.some((c) => typeof c !== "string" && !NO_TEXT.test(c.tag) && wholeText(c) === e.text)) continue;
4273
+ const own = ownText(node);
4274
+ if (!collapse(untag(own))) continue;
4275
+ const refs = tagsIn2(own);
4276
+ if (refs.length) {
4277
+ const distinct = [...new Map(refs.map((r2) => [`${r2.collection}/${r2.id}#${r2.pointer}`, r2])).values()];
4278
+ const itemKeys = new Set(distinct.map((r2) => `${r2.collection}/${r2.id}`));
4279
+ if (itemKeys.size > 1) {
4280
+ list(e, { text: visible, reason: "computed", candidates: distinct.length }, null);
4281
+ continue;
4282
+ }
4283
+ const r = distinct[0];
4284
+ const it2 = items.get(`${r.collection}/${r.id}`);
4285
+ if (!it2) continue;
4286
+ if (distinct.length > 1) {
4287
+ list(e, { text: visible, reason: "computed", fields: distinct.map((x) => x.pointer) }, it2);
4288
+ continue;
4289
+ }
4290
+ const value = at2(it2.data, r.pointer);
4291
+ const shown2 = typeof value === "string" ? collapse(untag(value)) : null;
4292
+ const marked = { collection: it2.collection, item: it2.id, field: r.pointer };
4293
+ if (shown2 !== null && shown2 === visible && reads2(it2.collection, top(r.pointer))) list(e, { text: visible, ...bind(it2, r.pointer, { exact: true }) }, it2);
4294
+ else list(e, { text: visible, reason: shown2 && shown2 !== visible && visible.includes(shown2) ? "computed" : "unproven", marked }, it2);
4295
+ continue;
4296
+ }
4297
+ const plain2 = (it2) => it2.fields.filter((f) => !TAGGED_TYPES.includes(f.type) && f.type !== "image" && reads2(it2.collection, f.key)).flatMap((f) => {
4298
+ const r = renderings(it2.data?.[f.key], formats).find((x) => collapse(x.text) === visible);
4299
+ return r ? [{ key: f.key, format: r.format }] : [];
4300
+ });
4301
+ const itemKey = cardItem(node);
4302
+ const it = itemKey ? items.get(itemKey) : null;
4303
+ if (it) {
4304
+ const fit = plain2(it);
4305
+ if (fit.length === 1) {
4306
+ const f = fit[0];
4307
+ list(e, { text: visible, ...bind(it, `/${f.key}`, f.format ? { format: f.format.kind === "intl" ? `intl ${JSON.stringify([f.format.locale ?? null, f.format.options ?? null])}` : `fixed ${f.format.digits}` } : { exact: true }) }, it);
4308
+ } else if (fit.length > 1) list(e, { text: visible, reason: "ambiguous", candidates: fit.length }, it);
4309
+ else {
4310
+ const digits = visible.replace(/\D/g, "");
4311
+ const inside = it.fields.some((f) => {
4312
+ const v = it.data?.[f.key];
4313
+ return f.type !== "image" && reads2(it.collection, f.key) && typeof v === "number" && Math.abs(v) >= 10 && digits.includes(String(Math.trunc(Math.abs(v))));
4314
+ });
4315
+ if (inside) list(e, { text: visible, reason: "unproven" }, it);
4316
+ }
4317
+ } else {
4318
+ const anywhere = [...items.values()].flatMap((x) => plain2(x));
4319
+ if (anywhere.length) list(e, { text: visible, reason: anywhere.length > 1 ? "ambiguous" : "unproven", candidates: anywhere.length }, null);
4320
+ }
4321
+ }
4322
+ let cards = 0;
4323
+ for (const [node, attrs] of [...stamps]) {
4324
+ const key = attrs["data-unbase-cms"];
4325
+ let card = null;
4326
+ for (let n = node; n && !WHOLE_PAGE.test(n.tag); n = n.parent) {
4327
+ if (!under3.get(n)?.size) continue;
4328
+ if (ownerOf(n) === key) card = n;
4329
+ else break;
4330
+ }
4331
+ if (card && card !== node && !stamps.has(card)) {
4332
+ stamp(card, { "data-unbase-cms": key });
4333
+ cards++;
4334
+ }
4335
+ }
4336
+ const edits = [...stamps].filter(([n]) => typeof n.end === "number").map(([n, attrs]) => ({ at: n.end, text: Object.entries(attrs).filter(([k]) => !(k in n.attrs)).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("") })).filter((x) => x.text).sort((a, b) => b.at - a.at);
4337
+ let out = html;
4338
+ for (const x of edits) {
4339
+ const i = out[x.at - 1] === "/" ? x.at - 1 : x.at;
4340
+ out = out.slice(0, i) + x.text + out.slice(i);
4341
+ }
4342
+ const bound = elements.filter((e) => e.binding).length;
4343
+ return { html: untag(out), elements, bound, unbound: elements.length - bound, cards };
4344
+ }
2792
4345
  export {
4346
+ binding_exports as binding,
2793
4347
  pages_core_exports as core,
2794
4348
  csp_exports as csp,
2795
4349
  detect,