@unbase-app/cli 0.4.0 → 0.5.0

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