@unbase-app/cli 0.3.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
 
@@ -541,28 +552,41 @@ __export(pages_core_exports, {
541
552
  DRAFTABLE: () => DRAFTABLE,
542
553
  KIT: () => KIT,
543
554
  KITS: () => KITS,
555
+ PAGE_ACTION_FRAMEWORKS: () => PAGE_ACTION_FRAMEWORKS,
544
556
  PAGE_FILE: () => PAGE_FILE,
557
+ REDIRECTS_SINCE: () => REDIRECTS_SINCE,
545
558
  deployContext: () => deployContext,
546
559
  discover: () => discover,
547
560
  draftCheck: () => draftCheck,
548
561
  draftPaths: () => draftPaths,
549
562
  draftPlan: () => draftPlan,
563
+ folderPaths: () => folderPaths,
550
564
  importGraph: () => importGraph,
551
565
  kitFiles: () => kitFiles,
552
566
  kitInstalled: () => kitInstalled,
567
+ kitRedirects: () => kitRedirects,
553
568
  leakPrints: () => leakPrints,
554
569
  leaksIn: () => leaksIn,
555
570
  linksTo: () => linksTo,
556
571
  listTools: () => listTools,
572
+ lowestVersion: () => lowestVersion,
557
573
  mediaGenerators: () => mediaGenerators,
558
574
  normalisePath: () => normalisePath,
559
575
  ownedContent: () => ownedContent,
576
+ pageActions: () => pageActions,
560
577
  parsePageFile: () => parsePageFile,
578
+ planPage: () => planPage,
579
+ planRedirect: () => planRedirect,
580
+ redirectsFor: () => redirectsFor,
561
581
  removeRoutes: () => removeRoutes,
562
582
  resolveImport: () => resolveImport,
563
583
  segmentFiles: () => segmentFiles,
564
584
  sentences: () => sentences,
585
+ siteRedirectList: () => siteRedirectList,
586
+ siteRedirects: () => siteRedirects,
587
+ slugOf: () => slugOf,
565
588
  stripComments: () => stripComments,
589
+ validAddress: () => validAddress,
566
590
  withoutInContentMap: () => withoutInContentMap,
567
591
  withoutInPageList: () => withoutInPageList,
568
592
  withoutInSitemap: () => withoutInSitemap
@@ -585,11 +609,14 @@ function normalisePath(p) {
585
609
  return s || "/";
586
610
  }
587
611
  function parsePageFile(text) {
588
- if (text == null) return { ok: true, exists: false, pages: {} };
612
+ if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
589
613
  const fail = (error) => ({ ok: (
590
614
  /** @type {const} */
591
615
  false
592
- ), exists: true, error, pages: {} });
616
+ ), exists: (
617
+ /** @type {const} */
618
+ true
619
+ ), error, pages: {}, folders: {}, redirects: {} });
593
620
  let data;
594
621
  try {
595
622
  data = JSON.parse(text);
@@ -604,10 +631,29 @@ function parsePageFile(text) {
604
631
  if (!address2.startsWith("/")) return fail(`${address2}: an address starts with /`);
605
632
  if (!isObject(entry)) return fail(`${address2}: not an object`);
606
633
  if (entry.draft !== void 0 && typeof entry.draft !== "boolean") return fail(`${address2}: draft is true or false`);
607
- out[normalisePath(address2)] = entry.draft === void 0 ? {} : { draft: entry.draft };
634
+ if (entry.name !== void 0 && typeof entry.name !== "string") return fail(`${address2}: name is text`);
635
+ out[normalisePath(address2)] = { ...entry.draft === void 0 ? {} : { draft: entry.draft }, ...entry.name ? { name: entry.name } : {} };
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 };
608
644
  }
609
- return { ok: true, exists: true, pages: out };
645
+ const redirects = data.redirects ?? {};
646
+ if (!isObject(redirects)) return fail("`redirects` is not an object");
647
+ const sends2 = {};
648
+ for (const [from, to] of Object.entries(redirects)) {
649
+ if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
650
+ if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
651
+ if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
652
+ sends2[normalisePath(from)] = normalisePath(to);
653
+ }
654
+ return { ok: true, exists: true, pages: out, folders, redirects: sends2 };
610
655
  }
656
+ var REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
611
657
  var draftPaths = (file) => Object.keys(file.pages).filter((p) => file.pages[p].draft === true).sort();
612
658
  var CONTEXTS = /* @__PURE__ */ new Set(["production", "preview", "development"]);
613
659
  function deployContext({ env = {}, command = "build" } = {}) {
@@ -643,14 +689,23 @@ function stringEnd(src, i) {
643
689
  function stripComments(src) {
644
690
  let out = "";
645
691
  let i = 0;
692
+ const special = /\/[/*]|["'`]/g;
646
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
+ }
647
702
  const c = src[i];
648
703
  const d = src[i + 1];
649
704
  if (c === "/" && d === "/") {
650
- while (i < src.length && src[i] !== "\n") {
651
- out += " ";
652
- i++;
653
- }
705
+ const end = src.indexOf("\n", i);
706
+ const stop = end < 0 ? src.length : end;
707
+ out += " ".repeat(stop - i);
708
+ i = stop;
654
709
  continue;
655
710
  }
656
711
  if (c === "/" && d === "*") {
@@ -731,6 +786,17 @@ function astroPages(paths) {
731
786
  }
732
787
  return out;
733
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
+ }
734
800
  function nextPages(paths) {
735
801
  const out = [];
736
802
  const ext = /\.(tsx|ts|jsx|js|mdx|md)$/;
@@ -870,14 +936,26 @@ function removeRoutes({ file, code, paths, text, drop }) {
870
936
  }
871
937
  function discover({ framework, paths, text }) {
872
938
  const kept = paths.filter((p) => !SKIP2.test(p));
873
- 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 };
874
940
  const seen = /* @__PURE__ */ new Set();
875
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);
876
942
  return { pages, notFound: found.notFound };
877
943
  }
878
944
  var CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
879
945
  var CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
880
- 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
+ }
881
959
  function contentNames(paths, text) {
882
960
  const files = /* @__PURE__ */ new Map();
883
961
  const add = (name, f) => {
@@ -886,7 +964,7 @@ function contentNames(paths, text) {
886
964
  };
887
965
  let collections = {};
888
966
  try {
889
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
967
+ collections = readCollections(text) ?? {};
890
968
  } catch {
891
969
  }
892
970
  for (const f of paths) {
@@ -914,62 +992,102 @@ function ownCode(page, importers, imports) {
914
992
  return own;
915
993
  }
916
994
  var ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
995
+ var ASTRO_NAMED = /getCollection|getEntry|getEntries/;
917
996
  function contentReads(paths, text) {
918
- const code = /* @__PURE__ */ new Map();
997
+ const files = [];
919
998
  for (const p of paths) {
920
999
  if (!CODE.test(p) || SKIP2.test(p)) continue;
921
1000
  const src = text(p);
922
- if (src) code.set(p, stripComments(src));
1001
+ if (src) files.push([p, src]);
923
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();
924
1050
  const astro2 = ASTRO_READS.join("|");
925
1051
  const byName = new Set(ASTRO_READS);
926
1052
  const entryOf = /* @__PURE__ */ new Map();
927
- const fixed = /* @__PURE__ */ new Map();
1053
+ const fixed2 = /* @__PURE__ */ new Map();
928
1054
  const bodies = /* @__PURE__ */ new Map();
929
1055
  const spans = /* @__PURE__ */ new Map();
930
- const DIRECT = new RegExp(`\\b(?:${astro2})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
931
1056
  const addFixed = (name, whole, entry) => {
932
- if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
933
- if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
934
- 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);
935
1060
  };
936
- for (const [p, src] of code) {
937
- if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
938
- 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)) {
939
- const name = m[1] ?? m[3];
940
- const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
941
- let at2 = m.index + m[0].length;
942
- while (/\s/.test(src[at2] ?? "")) at2++;
943
- const block = src.indexOf("{", at2);
944
- const braces = src[at2] === "{" ? at2 : m[1] && block > 0 ? block : -1;
945
- const body = braces >= 0 ? braced(src, braces) ?? "" : src.slice(at2, src.slice(at2).search(/;|\n\s*\n|$/) + at2);
946
- 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) {
947
1066
  if (!spans.has(p)) spans.set(p, []);
948
- spans.get(p).push([start, start + body.length]);
949
- if (first && new RegExp(`\\b(?:${astro2})\\(\\s*${escape(first)}\\b`).test(body)) {
950
- byName.add(name);
951
- const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
952
- 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);
953
1071
  }
954
- bodies.set(name, body);
955
- 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);
956
1074
  }
957
1075
  }
958
1076
  for (const [name, body] of bodies) {
959
1077
  for (const fn of byName) {
960
- if (fn === name || ASTRO_READS.includes(fn)) continue;
1078
+ if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
961
1079
  for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
962
1080
  }
963
1081
  }
964
- 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();
965
1083
  for (let grew = true; grew; ) {
966
1084
  grew = false;
967
1085
  for (const [name, called] of calls) {
968
1086
  for (const other of called) {
969
- const read = fixed.get(other);
1087
+ const read = fixed2.get(other);
970
1088
  if (other === name || !read) continue;
971
- if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
972
- 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);
973
1091
  const before = mine.whole.size + mine.entries.size;
974
1092
  read.whole.forEach((c) => mine.whole.add(c));
975
1093
  read.entries.forEach((e) => mine.entries.add(e));
@@ -977,45 +1095,45 @@ function contentReads(paths, text) {
977
1095
  }
978
1096
  }
979
1097
  }
1098
+ const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
980
1099
  const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
981
- return { code, byName, byNameCall, entryOf, fixed, astro: astro2, spans };
1100
+ return { code, byName, byNameCall, entryOf, fixed: fixed2, astro: astro2, spans, helpers };
982
1101
  }
983
1102
  var CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
984
- var IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
985
1103
  var DEFINITION = /function\s+([A-Za-z_$][\w$]*)|const\s+([A-Za-z_$][\w$]*)\s*=/g;
986
1104
  function blankRanges(src, ranges) {
987
1105
  if (!ranges.length) return src;
988
1106
  let out = "";
989
- let at2 = 0;
1107
+ let at3 = 0;
990
1108
  for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
991
- if (end <= at2) continue;
992
- const from = Math.max(start, at2);
993
- out += src.slice(at2, from) + blank(src.slice(from, end));
994
- 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;
995
1113
  }
996
- return out + src.slice(at2);
1114
+ return out + src.slice(at3);
997
1115
  }
998
1116
  var IMPORT_STATEMENT = /\bimport\s+(?:type\s+)?[\s\S]*?\bfrom\s*["'][^"'\n]+["']/g;
999
1117
  var blank = (s) => s.replace(/[^\n]/g, " ");
1000
- function readsIn(src, reads, path = null) {
1001
- 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);
1002
1120
  const names = /* @__PURE__ */ new Set();
1003
1121
  const entries = /* @__PURE__ */ new Set();
1004
1122
  const whole = /* @__PURE__ */ new Set();
1005
1123
  const helped = /* @__PURE__ */ new Set();
1006
- for (const m of code.matchAll(reads.byNameCall)) {
1124
+ for (const m of code.matchAll(reads2.byNameCall)) {
1007
1125
  const [, fn, first, entry, other] = m;
1008
- 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)}`);
1009
1127
  else if (entry) entries.add(`${first}/${entry}`);
1010
1128
  else if (other && ASTRO_READS.includes(fn)) whole.add(first);
1011
1129
  else if (fn === "getCollection") whole.add(first);
1012
1130
  else names.add(first);
1013
1131
  }
1014
1132
  const mentions = /* @__PURE__ */ new Map();
1015
- 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);
1016
1134
  const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
1017
1135
  for (const [name, n] of mentions) {
1018
- const read = reads.fixed.get(name);
1136
+ const read = reads2.fixed.get(name);
1019
1137
  if (!read || n - (defined.has(name) ? 1 : 0) <= 0) continue;
1020
1138
  read.whole.forEach((c) => whole.add(c));
1021
1139
  read.entries.forEach((e) => helped.add(e));
@@ -1028,12 +1146,16 @@ function siteReads(paths, text, importers) {
1028
1146
  if (kept) return kept;
1029
1147
  let collections = {};
1030
1148
  try {
1031
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
1149
+ collections = readCollections(text) ?? {};
1032
1150
  } catch {
1033
1151
  }
1034
- const reads = contentReads(paths, text);
1152
+ const reads2 = contentReads(paths, text);
1035
1153
  const readsByFile = /* @__PURE__ */ new Map();
1036
- 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
+ }
1037
1159
  const counts = { names: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map(), whole: /* @__PURE__ */ new Map() };
1038
1160
  const count = (kind, keys) => keys.forEach((k) => counts[kind].set(k, (counts[kind].get(k) ?? 0) + 1));
1039
1161
  for (const r of readsByFile.values()) {
@@ -1070,7 +1192,7 @@ function siteReads(paths, text, importers) {
1070
1192
  if (target.endsWith(".json")) push(jsonOf, f, target);
1071
1193
  }
1072
1194
  }
1073
- const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
1195
+ const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads2.byName };
1074
1196
  siteReadsOf.set(importers, site);
1075
1197
  return site;
1076
1198
  }
@@ -1165,21 +1287,21 @@ function listTools(framework, text) {
1165
1287
  return tools.filter((t) => t in deps);
1166
1288
  }
1167
1289
  function draftCheck(path, { framework, paths, text, found, importers }) {
1168
- const at2 = normalisePath(path);
1290
+ const at3 = normalisePath(path);
1169
1291
  const no = (reason, detail) => ({ ok: (
1170
1292
  /** @type {const} */
1171
1293
  false
1172
- ), path: at2, reason, ...detail ? { detail } : {} });
1294
+ ), path: at3, reason, ...detail ? { detail } : {} });
1173
1295
  if (!DRAFTABLE.includes(String(framework))) return no("framework");
1174
- if (at2 === "/") return no("home");
1296
+ if (at3 === "/") return no("home");
1175
1297
  const media = mediaGenerators(text);
1176
1298
  if (media.length) return no("generated_media", media.join(", "));
1177
1299
  const lists = listTools(framework, text);
1178
1300
  if (lists.length) return no("page_list", lists.join(", "));
1179
1301
  const discovered = found ?? discover({ framework, paths, text });
1180
- const page = discovered.pages.find((p) => p.path === at2);
1302
+ const page = discovered.pages.find((p) => p.path === at3);
1181
1303
  if (!page) {
1182
- 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));
1183
1305
  return template ? no("template", template.path) : no("missing");
1184
1306
  }
1185
1307
  if (page.kind === "template") return no("template", page.path);
@@ -1198,7 +1320,7 @@ function draftCheck(path, { framework, paths, text, found, importers }) {
1198
1320
  if (content.shared.length) return no("shared", content.shared.join(", "));
1199
1321
  if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1200
1322
  if (content.unknown) return no("content_unknown");
1201
- return { ok: true, path: at2, page, content: content.files };
1323
+ return { ok: true, path: at3, page, content: content.files };
1202
1324
  }
1203
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]+$/;
1204
1326
  function segmentFiles(file, paths) {
@@ -1333,6 +1455,875 @@ function withoutInContentMap(json, files) {
1333
1455
  }
1334
1456
  return JSON.stringify(map);
1335
1457
  }
1458
+ var PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
1459
+ var REDIRECTS_SINCE = { "@unbase-app/pages": "0.4.0", "@unbase-app/astro": "0.3.0", "@unbase-app/vite": "0.3.0", "@unbase-app/next": "0.3.0" };
1460
+ function lowestVersion(spec) {
1461
+ if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
1462
+ const m = spec.trim().replace(/^[\^~>=v\s]+/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
1463
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
1464
+ }
1465
+ var atLeast = (have, want) => {
1466
+ for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
1467
+ return true;
1468
+ };
1469
+ function kitRedirects({ framework, text }) {
1470
+ if (!kitInstalled({ framework, text })) return false;
1471
+ let pkg = null;
1472
+ try {
1473
+ pkg = JSON.parse(text("package.json") ?? "null");
1474
+ } catch {
1475
+ }
1476
+ const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1477
+ return (KITS[String(framework)] ?? []).some((name) => {
1478
+ const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
1479
+ const since = REDIRECTS_SINCE[name];
1480
+ const have = lowestVersion(spec);
1481
+ return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
1482
+ });
1483
+ }
1484
+ function slugOf(name) {
1485
+ return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
1486
+ }
1487
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
1488
+ function validAddress(p) {
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));
1493
+ }
1494
+ var under = (path, at3) => at3 === "/" ? path !== "/" : path.startsWith(`${at3}/`);
1495
+ var within2 = (path, at3) => path === at3 || under(path, at3);
1496
+ var moveAddress = (path, from, to) => path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`);
1497
+ var parentOf = (p) => p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/")));
1498
+ var lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
1499
+ function siteRedirects({ framework, text }) {
1500
+ const out = /* @__PURE__ */ new Set();
1501
+ try {
1502
+ const v = JSON.parse(text("vercel.json") ?? "null");
1503
+ for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
1504
+ } catch {
1505
+ }
1506
+ for (const c of CONFIGS[String(framework)] ?? []) {
1507
+ const src = stripComments(text(c) ?? "");
1508
+ if (framework === "astro") {
1509
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
1510
+ if (at3 < 0) continue;
1511
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
1512
+ for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
1513
+ } else if (framework === "next") {
1514
+ for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
1515
+ }
1516
+ }
1517
+ return out;
1518
+ }
1519
+ function sends(source, path) {
1520
+ if (REST.test(source)) {
1521
+ const base = normalisePath(source.replace(REST, ""));
1522
+ return within2(path, base);
1523
+ }
1524
+ return source === path || matchesPattern(source, path);
1525
+ }
1526
+ function matchesPattern(source, path) {
1527
+ if (!/\[|:/.test(source)) return false;
1528
+ const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
1529
+ return re.test(path);
1530
+ }
1531
+ function changedPageFile(before, change) {
1532
+ let data = {};
1533
+ try {
1534
+ data = before == null ? {} : JSON.parse(before) ?? {};
1535
+ } catch {
1536
+ data = {};
1537
+ }
1538
+ if (!isObject(data)) data = {};
1539
+ if (!isObject(data.pages)) data.pages = {};
1540
+ const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
1541
+ const folders = isObject(data.folders) ? { ...data.folders } : {};
1542
+ change(data.pages, redirects, folders);
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;
1547
+ if (Object.keys(redirects).length) data.redirects = redirects;
1548
+ else delete data.redirects;
1549
+ const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
1550
+ if (before == null && empty) return null;
1551
+ const after = `${JSON.stringify(data, null, 2)}
1552
+ `;
1553
+ return after === before ? null : after;
1554
+ }
1555
+ function repoint(redirects, from, to) {
1556
+ for (const [source, dest] of Object.entries(redirects)) {
1557
+ const rest = REST.test(dest);
1558
+ const base = rest ? normalisePath(dest.replace(REST, "")) : dest;
1559
+ if (within2(base, from)) redirects[source] = rest ? `${moveAddress(base, from, to)}${dest.slice(dest.lastIndexOf("/"))}` : moveAddress(base, from, to);
1560
+ }
1561
+ for (const [source, dest] of Object.entries(redirects)) {
1562
+ const base = REST.test(source) ? normalisePath(source.replace(REST, "")) : source;
1563
+ if (to && within2(to, base) && sends(source, to)) delete redirects[source];
1564
+ else if (source === dest) delete redirects[source];
1565
+ }
1566
+ }
1567
+ var SPECIFIER = /((?:\bfrom|\bimport|\brequire)\s*\(?\s*)(["'])([^"'\n]+)\2/g;
1568
+ var MD_LAYOUT = /^(layout:\s*)(["']?)([^"'\n]+?)\2\s*$/m;
1569
+ var relativeSpec = (fromFile, target) => {
1570
+ const from = dirname(fromFile).split("/").filter(Boolean);
1571
+ const to = target.split("/");
1572
+ let i = 0;
1573
+ while (i < from.length && i < to.length - 1 && from[i] === to[i]) i++;
1574
+ const up = from.length - i;
1575
+ const rest = to.slice(i).join("/");
1576
+ return up ? `${"../".repeat(up)}${rest}` : `./${rest}`;
1577
+ };
1578
+ function specFor(fromFile, target, old, oldTarget) {
1579
+ const index = /\/index\.[a-z]+$/.test(oldTarget) && !/\/index(\.[a-z]+)?$/.test(old);
1580
+ const ext = /\.[a-z]+$/.test(old.split("/").pop() ?? "") && old.endsWith(oldTarget.slice(oldTarget.lastIndexOf(".")));
1581
+ let t = target;
1582
+ if (index) t = dirname(target);
1583
+ else if (!ext) t = target.replace(/\.[a-z]+$/, "");
1584
+ if (old.startsWith("@/") && t.startsWith("src/")) return `@/${t.slice(4)}`;
1585
+ return relativeSpec(fromFile, t);
1586
+ }
1587
+ function respecified(src, was, now, moves, have) {
1588
+ const fix = (spec) => {
1589
+ const target = resolveImport(was, spec, have);
1590
+ if (!target) return spec;
1591
+ const next = moves.get(target) ?? target;
1592
+ if (next === target && was === now) return spec;
1593
+ if (!spec.startsWith(".") && next === target) return spec;
1594
+ return specFor(now, next, spec, target);
1595
+ };
1596
+ let out = src.replace(SPECIFIER, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
1597
+ if (/\.mdx?$/.test(now)) out = out.replace(MD_LAYOUT, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
1598
+ return out;
1599
+ }
1600
+ var QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
1601
+ var MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
1602
+ function relinked(src, from, to, markdown) {
1603
+ const swap = (address2) => {
1604
+ const bare = address2.replace(/[#?][\s\S]*$/, "");
1605
+ const tail = address2.slice(bare.length);
1606
+ const slash = bare.length > 1 && bare.endsWith("/") ? "/" : "";
1607
+ const clean = slash ? bare.slice(0, -1) : bare;
1608
+ if (clean === from) return `${to}${to === "/" ? "" : slash}${tail}`;
1609
+ if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
1610
+ return address2;
1611
+ };
1612
+ let out = src.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
1613
+ if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
1614
+ return out;
1615
+ }
1616
+ function blankStrings(src) {
1617
+ let out = "";
1618
+ let i = 0;
1619
+ while (i < src.length) {
1620
+ const c = src[i];
1621
+ if (c === '"' || c === "'" || c === "`") {
1622
+ const j = stringEnd(src, i);
1623
+ out += c + blank(src.slice(i + 1, j - 1)) + (j - 1 > i ? src[j - 1] : "");
1624
+ i = j;
1625
+ continue;
1626
+ }
1627
+ out += c;
1628
+ i++;
1629
+ }
1630
+ return out;
1631
+ }
1632
+ var routesBase = (file) => file.startsWith("src/pages/") ? "src/pages" : file.startsWith("pages/") ? "pages" : file.startsWith("src/app/") ? "src/app" : file.startsWith("app/") ? "app" : null;
1633
+ function destination(page, to, discovered) {
1634
+ const base = routesBase(page.file);
1635
+ if (!base) return null;
1636
+ const ext = page.file.slice(page.file.lastIndexOf("."));
1637
+ if (base.endsWith("app")) {
1638
+ const dir = dirname(page.file);
1639
+ const parent = parentOf(to);
1640
+ const sameParent = parent === parentOf(page.path);
1641
+ const parentPage = parent === null ? null : discovered.pages.find((p) => p.path === parent && p.file && routesBase(p.file) === base);
1642
+ const parentDir = sameParent ? dirname(dir) : parentPage ? dirname(parentPage.file) : `${base}${parent === "/" ? "" : parent}`;
1643
+ const newDir2 = to === "/" ? base : `${parentDir}/${lastOf(to)}`;
1644
+ return { file: `${newDir2}/${page.file.slice(dir.length + 1)}`, dir, newDir: newDir2, folder: true };
1645
+ }
1646
+ const index = /(^|\/)index\.[a-z]+$/.test(page.file);
1647
+ const oldDir = `${base}${page.path === "/" ? "" : page.path}`;
1648
+ const newDir = `${base}${to === "/" ? "" : to}`;
1649
+ return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
1650
+ }
1651
+ function appSegmentOwn(dir, paths) {
1652
+ return paths.filter((p) => {
1653
+ if (dirname(p) === dir) return true;
1654
+ if (!p.startsWith(`${dir}/`)) return false;
1655
+ const first = p.slice(dir.length + 1).split("/")[0];
1656
+ return first.startsWith("_");
1657
+ });
1658
+ }
1659
+ var componentName = (address2) => (lastOf(address2) || "Home").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("").replace(/^(\d)/, "Page$1") || "Page";
1660
+ function routePathAttr(src, router) {
1661
+ const tag = src.slice(router.start, router.end);
1662
+ const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
1663
+ if (!m) return null;
1664
+ const value = m.slice(2).find((v) => v !== void 0) ?? "";
1665
+ const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
1666
+ return { value, start: valueAt, end: valueAt + value.length };
1667
+ }
1668
+ function planPage(request, input) {
1669
+ const { framework, text } = input;
1670
+ const paths = input.paths.filter((p) => !SKIP2.test(p));
1671
+ const no = (reason, detail) => ({ ok: (
1672
+ /** @type {const} */
1673
+ false
1674
+ ), reason, ...detail ? { detail } : {} });
1675
+ const action = request.action;
1676
+ if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
1677
+ if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
1678
+ const at3 = normalisePath(request.path);
1679
+ const discovered = input.found ?? discover({ framework, paths, text });
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 });
1682
+ if (!page) {
1683
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at3));
1684
+ return template ? no("template", template.path) : no("missing");
1685
+ }
1686
+ if (page.kind === "template") return no("template", page.path);
1687
+ if (!page.file || page.reason === "unparsed") return no("unparsed");
1688
+ const pageFile = parsePageFile(text(PAGE_FILE));
1689
+ if (!pageFile.ok) return no("invalid", pageFile.error);
1690
+ const below = discovered.pages.filter((p) => under(p.path, at3));
1691
+ const have = new Set(paths);
1692
+ const importers = input.importers ?? importGraph(paths, text);
1693
+ const live = request.live === true;
1694
+ const redirects = live ? kitRedirects({ framework, text }) : false;
1695
+ const ownRedirects = siteRedirects({ framework, text });
1696
+ const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
1697
+ const writes = /* @__PURE__ */ new Map();
1698
+ const write = (w) => writes.set(w.path, w);
1699
+ const current = (p) => writes.has(p) ? writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null) : text(p);
1700
+ const links = /* @__PURE__ */ new Set();
1701
+ const unlinked = /* @__PURE__ */ new Set();
1702
+ const moves = [];
1703
+ const renamed = [];
1704
+ let to = null;
1705
+ const redirectChanges = {};
1706
+ const collections = (() => {
1707
+ try {
1708
+ return readCollections(text);
1709
+ } catch {
1710
+ return null;
1711
+ }
1712
+ })();
1713
+ const collectionsAfter = isObject(collections) ? { ...collections } : null;
1714
+ if (action === "rename") {
1715
+ if (at3 === "/") return no("home");
1716
+ const target = request.to == null ? at3 : normalisePath(request.to);
1717
+ if (!validAddress(target) || target === "/") return no("address", target);
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");
1721
+ to = target;
1722
+ const moved = /* @__PURE__ */ new Map();
1723
+ if (target !== at3) {
1724
+ if (framework === "vite-react") {
1725
+ const src = text(page.router.file) ?? "";
1726
+ const attr = routePathAttr(src, page.router);
1727
+ if (!attr) return no("unparsed", "index route");
1728
+ if (!attr.value.startsWith("/")) {
1729
+ const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1730
+ if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
1731
+ const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
1732
+ write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
1733
+ }
1734
+ } else {
1735
+ const dest = destination(page, target, discovered);
1736
+ if (!dest) return no("unparsed");
1737
+ for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
1738
+ moved.set(page.file, dest.file);
1739
+ for (const [from, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
1740
+ for (const [from, next] of moved) {
1741
+ const src = CODE.test(from) ? text(from) : null;
1742
+ const content = src == null ? null : respecified(src, from, next, moved, have);
1743
+ write(content == null || content === src ? { path: next, from } : { path: next, content });
1744
+ write({ path: from, deleted: true });
1745
+ }
1746
+ for (const p of paths) {
1747
+ if (moved.has(p) || !CODE.test(p)) continue;
1748
+ const src = text(p);
1749
+ if (!src) continue;
1750
+ const out = respecified(src, p, p, moved, have);
1751
+ if (out !== src) write({ path: p, content: out });
1752
+ }
1753
+ }
1754
+ for (const p of paths) {
1755
+ if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
1756
+ const where = moved.get(p) ?? p;
1757
+ const src = current(where);
1758
+ if (!src) continue;
1759
+ const out = relinked(src, at3, target, /\.mdx?$/.test(p));
1760
+ if (out === src) continue;
1761
+ write({ path: where, content: out });
1762
+ if (!moved.has(p)) links.add(where);
1763
+ }
1764
+ moves.push({ from: at3, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at3, target) })));
1765
+ for (const [from, next] of moved) renamed.push({ from, to: next });
1766
+ }
1767
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1768
+ if (target !== at3) {
1769
+ for (const key of Object.keys(pages)) {
1770
+ if (!within2(key, at3)) continue;
1771
+ pages[moveAddress(key, at3, target)] = { ...pages[key], ...pages[moveAddress(key, at3, target)] ?? {} };
1772
+ delete pages[key];
1773
+ }
1774
+ const before = { ...sendsOn };
1775
+ if (live) {
1776
+ sendsOn[at3] = target;
1777
+ if (below.length) sendsOn[`${at3}/[...path]`] = `${target}/[...path]`;
1778
+ }
1779
+ repoint(sendsOn, at3, target);
1780
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1781
+ }
1782
+ if (request.name !== void 0) {
1783
+ const entry = pages[target] ?? {};
1784
+ if (request.name) entry.name = String(request.name).trim().slice(0, 120);
1785
+ else delete entry.name;
1786
+ pages[target] = entry;
1787
+ }
1788
+ });
1789
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1790
+ if (!writes.size) return no("same");
1791
+ }
1792
+ if (action === "duplicate") {
1793
+ if (framework === "vite-react" && page.reason === "nested") return no("nested");
1794
+ let target;
1795
+ if (request.to != null) {
1796
+ target = normalisePath(request.to);
1797
+ if (!validAddress(target) || target === "/") return no("address", target);
1798
+ if (taken(target)) return no("taken", target);
1799
+ } else {
1800
+ const base = at3 === "/" ? "/home-copy" : `${at3}-copy`;
1801
+ target = base;
1802
+ for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
1803
+ }
1804
+ to = target;
1805
+ const content = ownedContent(page, { paths, text, importers });
1806
+ if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1807
+ const own = new Set(content.files);
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) ?? []);
1812
+ const copies = /* @__PURE__ */ new Map();
1813
+ const rebinds = [];
1814
+ const newId = slugOf(lastOf(target)) || "copy";
1815
+ const freeFile = (dir, base, ext) => {
1816
+ let f = `${dir}/${base}${ext}`;
1817
+ for (let n = 2; (have.has(f) || [...writes.keys()].includes(f) || [...copies.values()].includes(f)) && n < 100; n++) f = `${dir}/${base}-${n}${ext}`;
1818
+ return f;
1819
+ };
1820
+ for (const f of own) {
1821
+ if (reads2.isRoute(f)) continue;
1822
+ if (imported.has(f)) {
1823
+ copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
1824
+ continue;
1825
+ }
1826
+ const collection = collectionOfFile(f, reads2.collections);
1827
+ const id = f.slice(f.lastIndexOf("/") + 1, -5);
1828
+ const folder = (reads2.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads2.collections || !reads2.collections[f];
1829
+ const entry = `${collection}/${id}`;
1830
+ if (pageReads.entries.has(entry) && folder) {
1831
+ const next = freeFile(dirname(f), newId, ".json");
1832
+ copies.set(f, next);
1833
+ rebinds.push({ kind: "entry", name: id, collection, next: next.slice(next.lastIndexOf("/") + 1, -5) });
1834
+ } else if (pageReads.names.has(id) && id !== collection && folder) {
1835
+ const next = freeFile(dirname(f), newId, ".json");
1836
+ copies.set(f, next);
1837
+ rebinds.push({ kind: "name", name: id, next: next.slice(next.lastIndexOf("/") + 1, -5) });
1838
+ } else {
1839
+ return no("content_bound", f);
1840
+ }
1841
+ }
1842
+ if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
1843
+ for (const m of ownCodeFiles) {
1844
+ if (m === page.file) continue;
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);
1847
+ }
1848
+ const rebind = (src) => {
1849
+ let out = src;
1850
+ for (const r of rebinds) {
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`);
1852
+ else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1853
+ }
1854
+ for (const [f, next] of copies) {
1855
+ if (!imported.has(f)) continue;
1856
+ out = out.replace(SPECIFIER, (m, lead, q, spec) => resolveImport(page.file, spec, have) === f ? `${lead}${q}${spec.slice(0, spec.lastIndexOf("/") + 1)}${next.slice(next.lastIndexOf("/") + 1)}${q}` : m);
1857
+ }
1858
+ return out;
1859
+ };
1860
+ if (framework === "vite-react") {
1861
+ const router = page.router.file;
1862
+ const src = current(router) ?? "";
1863
+ const attr = routePathAttr(src, page.router);
1864
+ if (!attr) return no("unparsed", "index route");
1865
+ let name = componentName(target);
1866
+ for (let n = 2; new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(src) && n < 100; n++) name = `${componentName(target)}${n}`;
1867
+ const ext = page.file.slice(page.file.lastIndexOf("."));
1868
+ const file = freeFile(dirname(page.file), name, ext);
1869
+ const original = text(page.file) ?? "";
1870
+ write({ path: file, content: rebind(respecified(original, page.file, file, /* @__PURE__ */ new Map([[page.file, file]]), have)) });
1871
+ const comp = page.router.component;
1872
+ const statement = page.router.importKind === "lazy" ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m")) : src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
1873
+ if (!statement) return no("unparsed", "its import");
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}`);
1875
+ const value = attr.value.startsWith("/") ? target : (() => {
1876
+ const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1877
+ return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1878
+ })();
1879
+ if (value === null) return no("unparsed", "a route inside another route keeps its parent");
1880
+ const newTag = (src.slice(page.router.start, attr.start) + value + src.slice(attr.end, page.router.end)).replace(new RegExp(`(<|\\{\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
1881
+ const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
1882
+ const at1 = page.router.end;
1883
+ let out = `${src.slice(0, at1)}
1884
+ ${indent}${newTag}${src.slice(at1)}`;
1885
+ const lineEnd = statement.index + statement[0].length;
1886
+ out = `${out.slice(0, lineEnd)}
1887
+ ${added}${out.slice(lineEnd)}`;
1888
+ write({ path: router, content: out });
1889
+ } else {
1890
+ const dest = destination(page, target, discovered);
1891
+ if (!dest) return no("unparsed");
1892
+ const along = framework === "next" && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1893
+ const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1894
+ for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1895
+ for (const [from, next] of moved) {
1896
+ const src = CODE.test(from) ? text(from) : null;
1897
+ if (src == null) {
1898
+ write({ path: next, from });
1899
+ continue;
1900
+ }
1901
+ let out = respecified(src, from, next, moved, have);
1902
+ if (from === page.file) out = rebind(out);
1903
+ write(out === src ? { path: next, from } : { path: next, content: out });
1904
+ }
1905
+ }
1906
+ for (const [f, next] of copies) {
1907
+ write({ path: next, from: f });
1908
+ if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1909
+ }
1910
+ for (const f of own) {
1911
+ if (!reads2.isRoute(f)) continue;
1912
+ const src = text(f) ?? "";
1913
+ const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
1914
+ write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at3)}(")`), `$1${target}$2`) });
1915
+ if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1916
+ }
1917
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
1918
+ const entry = { ...request.drafts ? { draft: true } : {}, ...request.name ? { name: String(request.name).trim().slice(0, 120) } : {} };
1919
+ if (Object.keys(entry).length) pages[target] = entry;
1920
+ });
1921
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1922
+ }
1923
+ if (action === "delete") {
1924
+ if (at3 === "/") return no("home");
1925
+ if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
1926
+ let target = null;
1927
+ if (live && request.redirect !== null) {
1928
+ if (request.redirect !== void 0) {
1929
+ target = normalisePath(request.redirect);
1930
+ if (within2(target, at3) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1931
+ } else {
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;
1933
+ target = target ?? "/";
1934
+ }
1935
+ if (!redirects) return no("no_redirects");
1936
+ }
1937
+ to = target;
1938
+ if (framework === "vite-react") {
1939
+ const router = page.router.file;
1940
+ const src = current(router) ?? "";
1941
+ let { start, end } = page.router;
1942
+ const lineStart = src.lastIndexOf("\n", start - 1) + 1;
1943
+ const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
1944
+ if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
1945
+ start = lineStart;
1946
+ end = Math.min(src.length, lineEnd + 1);
1947
+ }
1948
+ let out = src.slice(0, start) + src.slice(end);
1949
+ const comp = page.router.component;
1950
+ const rest = blankStrings(stripComments(out));
1951
+ const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
1952
+ if (uses <= 1) {
1953
+ const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
1954
+ out = out.replace(re, "");
1955
+ if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
1956
+ }
1957
+ write({ path: router, content: out });
1958
+ } else {
1959
+ const dir = dirname(page.file);
1960
+ const files2 = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
1961
+ for (const f of files2) write({ path: f, deleted: true });
1962
+ }
1963
+ const content = ownedContent(page, { paths, text, importers });
1964
+ for (const f of content.files) {
1965
+ write({ path: f, deleted: true });
1966
+ if (collectionsAfter) delete collectionsAfter[f];
1967
+ }
1968
+ for (const f of linksTo(at3, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
1969
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1970
+ delete pages[at3];
1971
+ const before = { ...sendsOn };
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];
1975
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1976
+ });
1977
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1978
+ }
1979
+ if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
1980
+ const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
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
+ }
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");
2128
+ const files = [...writes.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
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 };
2133
+ }
2134
+ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers }) {
2135
+ const kept = paths.filter((p) => !SKIP2.test(p));
2136
+ const discovered = found ?? discover({ framework, paths: kept, text });
2137
+ const graph = importers ?? importGraph(kept, text);
2138
+ const pageFile = parsePageFile(text(PAGE_FILE));
2139
+ const redirects = kitRedirects({ framework, text });
2140
+ const reads2 = siteReads(kept, text, graph);
2141
+ const out = {};
2142
+ const no = (reason, detail) => ({ ok: (
2143
+ /** @type {const} */
2144
+ false
2145
+ ), reason, ...detail ? { detail } : {} });
2146
+ const yes = { ok: (
2147
+ /** @type {const} */
2148
+ true
2149
+ ) };
2150
+ for (const page of discovered.pages) {
2151
+ if (page.path.includes(" ")) continue;
2152
+ const below = discovered.pages.filter((p) => under(p.path, page.path));
2153
+ const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
2154
+ if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
2155
+ out[page.path] = all(no("framework"));
2156
+ continue;
2157
+ }
2158
+ if (!pageFile.ok) {
2159
+ out[page.path] = all(no("invalid"));
2160
+ continue;
2161
+ }
2162
+ if (page.kind === "template") {
2163
+ out[page.path] = all(no("template"));
2164
+ continue;
2165
+ }
2166
+ if (!page.file || page.reason === "unparsed") {
2167
+ out[page.path] = all(no("unparsed"));
2168
+ continue;
2169
+ }
2170
+ const onLive = live.has(page.path);
2171
+ let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
2172
+ if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
2173
+ const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
2174
+ let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
2175
+ if (duplicate.ok) {
2176
+ const content = ownedContent(page, { paths: kept, text, importers: graph });
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) ?? []);
2179
+ if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
2180
+ else if (content.unknown) duplicate = no("content_bound");
2181
+ else
2182
+ for (const f of content.files) {
2183
+ if (reads2.isRoute(f) || imported.has(f)) continue;
2184
+ const collection = collectionOfFile(f, reads2.collections);
2185
+ const id = f.slice(f.lastIndexOf("/") + 1, -5);
2186
+ const folder = (reads2.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads2.collections || !reads2.collections[f];
2187
+ const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || pageReads.names.has(id) && id !== collection);
2188
+ if (bound) {
2189
+ duplicate = no("content_bound", f);
2190
+ break;
2191
+ }
2192
+ }
2193
+ if (duplicate.ok) {
2194
+ const mine = ownCode(page, graph, reads2.imports);
2195
+ for (const m of mine) {
2196
+ if (m === page.file) continue;
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))) {
2199
+ duplicate = no("content_bound", m);
2200
+ break;
2201
+ }
2202
+ }
2203
+ }
2204
+ }
2205
+ out[page.path] = { rename, duplicate, delete: remove, under: below.length };
2206
+ }
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 };
2217
+ }
2218
+ function redirectsFor(framework, pageFile, pagePaths = []) {
2219
+ const pages = new Set(pagePaths.map(normalisePath));
2220
+ const list = [];
2221
+ const skipped = [];
2222
+ for (const [source, destination2] of Object.entries(pageFile.redirects ?? {})) {
2223
+ const prefix = REST.test(source);
2224
+ const base = prefix ? normalisePath(source.replace(REST, "")) : source;
2225
+ if (!prefix && pages.has(source)) {
2226
+ skipped.push(source);
2227
+ continue;
2228
+ }
2229
+ const destBase = prefix ? normalisePath(destination2.replace(REST, "")) : destination2;
2230
+ if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2, permanent: true });
2231
+ else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
2232
+ else list.push({ source, destination: destination2 });
2233
+ }
2234
+ return { list, skipped };
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
+ }
1336
2327
 
1337
2328
  // supabase/functions/_shared/next-metadata.ts
1338
2329
  var ID = /[A-Za-z0-9_$]/;
@@ -1519,15 +2510,15 @@ var CMS2 = /sanity|contentful|storyblok|prismic|datocms|payload|strapi|directus|
1519
2510
  var isCmsModule = (spec) => CMS2.test(spec);
1520
2511
  var importsOf = (src) => [...src.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']/gm), ...src.matchAll(/^\s*import\s*["']([^"']+)["']/gm)].map((m) => m[1]);
1521
2512
  function afterImports(src, code) {
1522
- let at2 = 0;
2513
+ let at3 = 0;
1523
2514
  const directive = /^\s*(["'])use [a-z]+\1;?[^\S\n]*\n?/.exec(src);
1524
- if (directive) at2 = directive[0].length;
2515
+ if (directive) at3 = directive[0].length;
1525
2516
  for (const m of code.matchAll(/^import\b/gm)) {
1526
2517
  const end = expressionEnd(src, m.index);
1527
2518
  const semi = src[end] === ";" ? end + 1 : end;
1528
- at2 = Math.max(at2, semi);
2519
+ at3 = Math.max(at3, semi);
1529
2520
  }
1530
- return at2;
2521
+ return at3;
1531
2522
  }
1532
2523
  function readMetadata(src) {
1533
2524
  const code = codeOnly(src);
@@ -1669,6 +2660,22 @@ var SCHEMAS = `${CONTENT}/.schemas`;
1669
2660
  var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
1670
2661
  var AT_ONCE2 = 8;
1671
2662
  var MAX_ROUTE_FILES = 300;
2663
+ var NEXT_AT_ONCE = 16;
2664
+ function limited(n) {
2665
+ let running = 0;
2666
+ const waiting = [];
2667
+ return async (work) => {
2668
+ if (running < n) running++;
2669
+ else await new Promise((go) => waiting.push(go));
2670
+ try {
2671
+ return await work();
2672
+ } finally {
2673
+ const next = waiting.shift();
2674
+ if (next) next();
2675
+ else running--;
2676
+ }
2677
+ };
2678
+ }
1672
2679
  async function inTurns(items, work) {
1673
2680
  const out = new Array(items.length);
1674
2681
  let next = 0;
@@ -1719,28 +2726,28 @@ async function viteSettings(repo, appPath) {
1719
2726
  if (text === null) return null;
1720
2727
  const head = readHead(text);
1721
2728
  const site = {};
1722
- for (const [field2, at2, kind] of HEAD_SETTINGS) {
1723
- const found = head[at2];
1724
- 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 };
1725
2732
  }
1726
2733
  return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
1727
2734
  }
1728
2735
  async function readSettings(repo, appPath, framework = null) {
1729
2736
  if (framework === "vite-react") return viteSettings(repo, appPath);
1730
2737
  if (framework === "next") return nextSettings(repo, appPath);
1731
- const at2 = (p) => join(appPath, p);
1732
- 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"));
1733
2740
  if (!schemaPaths.length) return null;
1734
- 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);
1735
2742
  const schemas = /* @__PURE__ */ new Map();
1736
- 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));
1737
2744
  schemaPaths.forEach((p, i) => {
1738
2745
  const s = parse(read[i] ?? null);
1739
2746
  if (s && typeof s === "object") schemas.set(named(p), s);
1740
2747
  });
1741
- const elsewhere = parse(map ?? null) ?? {};
1742
- const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at2(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at2(SCHEMAS)}/`));
1743
- 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$/, "");
1744
2751
  const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
1745
2752
  const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
1746
2753
  const pages = {};
@@ -1760,7 +2767,7 @@ async function readSettings(repo, appPath, framework = null) {
1760
2767
  const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
1761
2768
  routes = { dir, fields };
1762
2769
  }
1763
- const siteCollection = [...schemas].find(([, s]) => s["x-instellingen"] === "site");
2770
+ const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
1764
2771
  let site = null;
1765
2772
  const siteFile = siteCollection && filesOf(siteCollection[0])[0];
1766
2773
  if (siteCollection && siteFile) {
@@ -1788,8 +2795,9 @@ async function nextSettings(repo, appPath) {
1788
2795
  const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
1789
2796
  const have = new Set(paths);
1790
2797
  const texts = /* @__PURE__ */ new Map();
2798
+ const turn = limited(NEXT_AT_ONCE);
1791
2799
  const read = (p) => {
1792
- if (!texts.has(p)) texts.set(p, repo.read(join(appPath, p)));
2800
+ if (!texts.has(p)) texts.set(p, turn(() => repo.read(join(appPath, p))));
1793
2801
  return texts.get(p);
1794
2802
  };
1795
2803
  const { pages: found } = discover({ framework: "next", paths, text: () => null });
@@ -1804,28 +2812,34 @@ async function nextSettings(repo, appPath) {
1804
2812
  const specs = importsOf(src);
1805
2813
  if (specs.some(isCmsModule)) return true;
1806
2814
  if (!depth) return false;
1807
- for (const s of specs) {
1808
- const target = resolveIn(file, s, have);
1809
- if (target && await readsCms(target, depth - 1, seen)) return true;
1810
- }
1811
- return false;
2815
+ const targets = specs.map((s) => resolveIn(file, s, have)).filter((t) => t !== null);
2816
+ return (await Promise.all(targets.map((t) => readsCms(t, depth - 1, seen)))).some(Boolean);
1812
2817
  };
1813
2818
  const reasonOf = async (file, reason) => reason === "computed" && /\bgenerateMetadata\b/.test(await read(file) ?? "") && await readsCms(file) ? "cms" : reason;
1814
2819
  const out = {};
1815
2820
  const refused = {};
1816
- const answers = await inTurns(pages, async (p) => {
1817
- const file = p.file;
1818
- if (!NEXT_PAGE.test(file)) return { p, file, read: null };
1819
- const src = await read(file);
1820
- return { p, file, read: src === null ? null : pageMetaFields(src) };
1821
- });
1822
- for (const { p, file, read: r } of answers) {
2821
+ const [answers, layoutRead] = await Promise.all([
2822
+ Promise.all(
2823
+ pages.map(async (p) => {
2824
+ const file = p.file;
2825
+ if (!NEXT_PAGE.test(file)) return { p, file, read: null, reason: null };
2826
+ const src = await read(file);
2827
+ const r = src === null ? null : pageMetaFields(src);
2828
+ return { p, file, read: r, reason: r?.refused ? await reasonOf(file, r.refused) : null };
2829
+ })
2830
+ ),
2831
+ layout ? read(layout).then(async (src) => {
2832
+ const r = src === null ? null : siteMetaFields(src);
2833
+ return { read: r, reason: r?.refused ? await reasonOf(layout, r.refused) : null };
2834
+ }) : null
2835
+ ]);
2836
+ for (const { p, file, read: r, reason } of answers) {
1823
2837
  if (!r) {
1824
2838
  refused[p.path] = { file, reason: "unsupported" };
1825
2839
  continue;
1826
2840
  }
1827
2841
  if (r.refused) {
1828
- refused[p.path] = { file, reason: await reasonOf(file, r.refused) };
2842
+ refused[p.path] = { file, reason: reason ?? r.refused };
1829
2843
  continue;
1830
2844
  }
1831
2845
  if (r.fields.socialImage && drawnImage(file, have)) {
@@ -1839,9 +2853,8 @@ async function nextSettings(repo, appPath) {
1839
2853
  if (computed.length) refused[p.path] = { file, reason: "computed", fields: Object.fromEntries(computed) };
1840
2854
  }
1841
2855
  let site = null;
1842
- if (layout) {
1843
- const src = await read(layout);
1844
- const r = src === null ? null : siteMetaFields(src);
2856
+ if (layout && layoutRead) {
2857
+ const r = layoutRead.read;
1845
2858
  if (r?.fields.socialImage && drawnImage(layout, have)) {
1846
2859
  delete r.fields.socialImage;
1847
2860
  r.computed.socialImage = "computed";
@@ -1851,7 +2864,7 @@ async function nextSettings(repo, appPath) {
1851
2864
  for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_SITE_FIELDS[k]] = settingOf(layout, f);
1852
2865
  if (Object.keys(fields).length) site = fields;
1853
2866
  const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_SITE_FIELDS[k], why]);
1854
- if (r.refused) refused.site = { file: layout, reason: await reasonOf(layout, r.refused) };
2867
+ if (r.refused) refused.site = { file: layout, reason: layoutRead.reason ?? r.refused };
1855
2868
  else if (computed.length) refused.site = { file: layout, reason: "computed", fields: Object.fromEntries(computed) };
1856
2869
  }
1857
2870
  }
@@ -1935,15 +2948,15 @@ var CSP_FILES = ["vercel.json", "public/_headers"];
1935
2948
  var HEADER = /^content-security-policy$/i;
1936
2949
  function directivesOf(policy) {
1937
2950
  const out = [];
1938
- let at2 = 0;
2951
+ let at3 = 0;
1939
2952
  for (const part of policy.split(";")) {
1940
2953
  const lead = part.length - part.trimStart().length;
1941
2954
  const text = part.trim();
1942
2955
  if (text) {
1943
2956
  const [name, ...sources] = text.split(/\s+/);
1944
- 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 });
1945
2958
  }
1946
- at2 += part.length + 1;
2959
+ at3 += part.length + 1;
1947
2960
  }
1948
2961
  return out;
1949
2962
  }
@@ -2063,16 +3076,16 @@ var HEADERS_LINE = /^([ \t]+)(content-security-policy)([ \t]*:[ \t]*)(.*?)([ \t]
2063
3076
  function headersPolicies(text) {
2064
3077
  const out = [];
2065
3078
  let path = "";
2066
- let at2 = 0;
3079
+ let at3 = 0;
2067
3080
  text.split("\n").forEach((line, n) => {
2068
3081
  const plain2 = line.replace(/\r$/, "");
2069
3082
  if (/^\S/.test(plain2) && !plain2.startsWith("#")) path = plain2.trim();
2070
3083
  const m = HEADERS_LINE.exec(plain2);
2071
3084
  if (m) {
2072
- 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;
2073
3086
  out.push({ file: "public/_headers", source: path, value: m[4], start, end: start + m[4].length, line: n + 1 });
2074
3087
  }
2075
- at2 += line.length + 1;
3088
+ at3 += line.length + 1;
2076
3089
  });
2077
3090
  return out;
2078
3091
  }
@@ -2093,8 +3106,8 @@ function edited(file, text, change) {
2093
3106
  for (const p of [...policies].sort((a, b) => b.start - a.start)) {
2094
3107
  const next = change(p.value);
2095
3108
  if (next === p.value) continue;
2096
- const literal = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
2097
- 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)}`;
2098
3111
  }
2099
3112
  return out;
2100
3113
  }
@@ -2128,7 +3141,1209 @@ function cspElsewhere(path, text) {
2128
3141
  if (/(^|\/)astro\.config\.[mc]?[jt]s$/.test(path) && /\bcsp\s*:/.test(text)) return "Astro's own CSP (its `csp` option)";
2129
3142
  return null;
2130
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
+ }
2131
4345
  export {
4346
+ binding_exports as binding,
2132
4347
  pages_core_exports as core,
2133
4348
  csp_exports as csp,
2134
4349
  detect,