@unbase-app/pages 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/core.mjs CHANGED
@@ -5,36 +5,139 @@
5
5
  // be kept off Live, shared by the build plugins (astro.mjs, vite.mjs, and
6
6
  // @unbase-app/next's withUnbase) and by Unbase's backend. Exact copies in
7
7
  // supabase/functions/_shared/pages-core.mjs, kit/vite/pages/core.mjs and
8
- // kit/next/core.mjs; tests fail when they differ.
8
+ // kit/next/core.mjs (each with pages-address.mjs beside it); tests fail when
9
+ // they differ.
9
10
  //
10
11
  // Pure: no file system, no network, no clock. Everything reads the app's files
11
12
  // through `text(path)` (paths relative to the app's root) and a list of
12
13
  // `paths`, so the same commit always gives the same answer.
13
14
  //
15
+ // One adapter per framework (`ADAPTERS`, below; docs/plan-page-engine.md PE4a):
16
+ // every framework-specific step goes through it, and nothing else here names a
17
+ // framework. What an address is (normalising, a name's slug, a pattern's
18
+ // match) is pages-address.mjs, beside this file in every copy.
19
+ //
14
20
  // parsePageFile unbase.pages.json, validated
15
21
  // deployContext production | preview | development, never from NODE_ENV
16
- // discover the pages the code makes (Astro, Next.js, React Router)
22
+ // discover the pages the code makes (Astro, Next.js, React Router, HTML files)
17
23
  // draftCheck whether one page can be kept out of a production build
18
24
  // linksTo the files that name a page's address
19
25
  // leakPrints text that only a draft page has, to search the output for
20
26
  // ============================================================================
21
27
 
28
+ import { normalisePath, redirectMatches as matchesPattern, slugOf, templateMatches, validAddress } from "./pages-address.mjs";
29
+
30
+ export { dynamicSegment, isPattern, normalisePath, routeTest, slugOf, templateMatches, templateTest, validAddress } from "./pages-address.mjs";
31
+
22
32
  export const PAGE_FILE = "unbase.pages.json";
23
33
  export const KIT = "@unbase-app/pages";
24
34
 
35
+ // ── Frameworks: one adapter each (docs/plan-page-engine.md PE4a; ADR-0030) ──
36
+
25
37
  /**
26
- * The packages that bring the kit into a framework's build: the kit itself, the framework's own
27
- * package that carries it (@unbase-app/astro; @unbase-app/vite, whose `unbase()` is the kit's Vite
28
- * plugin and comment mode's loader in one; @unbase-app/next, whose `withUnbase` runs this core in a
29
- * Next.js build), and the kit's name before K5 (03-11), which sites installed then still have until
30
- * they move across.
38
+ * What the core knows of each framework, in one place. Every framework-specific step of the core
39
+ * goes through its adapter; no other code here names a framework. A framework without one gets the
40
+ * honest answer: no pages from its code, no page actions (`framework`), no drafts.
41
+ *
42
+ * kits the packages that bring the kit into its build: the kit itself, the framework's
43
+ * own package that carries it (@unbase-app/astro; @unbase-app/vite, whose `unbase()`
44
+ * is the kit's Vite plugin and comment mode's loader in one; @unbase-app/next, whose
45
+ * `withUnbase` runs this core in a Next.js build), and the kit's name before K5
46
+ * (03-11), which sites installed then still have until they move across
47
+ * configs its build's config files, in the order they are looked for
48
+ * listTools packages that write its page list after the build, from its output (next-sitemap
49
+ * reads Next.js's manifests, where a draft's address still is): the kit cannot clean
50
+ * what they write
51
+ * discover its pages, from its code
52
+ * acts Rename, Duplicate, Delete, New page and redirects are planned for it (planPage)
53
+ * routeLines a page is a route element in a router file (React Router): a move rewrites the
54
+ * route's path, a copy adds a route, a delete takes the route out, and a template is
55
+ * no CMS detail page
56
+ * segments a page is a folder whose special files go with it (Next.js's app router): they keep
57
+ * it from being a draft, and move and go with it
58
+ * configSources the redirect sources its config sets (siteRedirects)
59
+ * configRedirects the redirects its config sets, each with where it goes (siteRedirectList)
60
+ * redirect a page file's redirect in the shape its package applies (redirectsFor); without
61
+ * it, `{ source, destination }`
62
+ * canCreate whether New page has a starter here (createCapability); without it, yes
63
+ * starter New page's starter files (planCreate)
64
+ * destination where a page's file goes when it moves or is copied; without it, the file
65
+ * routers' rule (`destination`)
66
+ * folderDirs where a folder's files are; without it, the file routers' rule (`folderDirs`)
67
+ * links the files whose links follow a move (a site of HTML files: every .html file);
68
+ * without it, the app's code and content
69
+ * relativeLinks its pages link each other by relative URLs (`about.html`, `../`), which follow
70
+ * a move too, and a moved or copied page's own relative URLs are pointed again
31
71
  */
32
- export const KITS = {
33
- astro: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
34
- "vite-react": [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
35
- next: ["@unbase-app/next"],
72
+ const ADAPTERS = {
73
+ astro: {
74
+ kits: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
75
+ configs: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
76
+ listTools: [],
77
+ discover: (kept) => ({ pages: astroPages(kept), notFound: null }),
78
+ acts: true,
79
+ routeLines: false,
80
+ segments: false,
81
+ configSources: astroConfigSources,
82
+ configRedirects: astroConfigRedirects,
83
+ starter: astroStarter,
84
+ },
85
+ "vite-react": {
86
+ kits: [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
87
+ configs: ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
88
+ listTools: [],
89
+ discover: (kept, text) => reactRouterPages(kept, text),
90
+ acts: true,
91
+ routeLines: true,
92
+ segments: false,
93
+ redirect: ({ prefix, source, base, destBase }) => ({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix }),
94
+ canCreate: (discovered, kept, text) => (siblingRoutes(discovered, text).length ? { ok: true } : { ok: false, reason: "routes_unread" }),
95
+ starter: reactRouterStarter,
96
+ },
97
+ next: {
98
+ kits: ["@unbase-app/next"],
99
+ configs: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
100
+ listTools: ["next-sitemap"],
101
+ discover: (kept) => ({ pages: nextPages(kept), notFound: null }),
102
+ acts: true,
103
+ routeLines: false,
104
+ segments: true,
105
+ configSources: nextConfigSources,
106
+ configRedirects: nextConfigRedirects,
107
+ redirect: ({ prefix, source, destination, base, destBase }) => ({
108
+ source: prefix ? `${base === "/" ? "" : base}/:path*` : source,
109
+ destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination,
110
+ permanent: true,
111
+ }),
112
+ canCreate: (discovered, kept) =>
113
+ discovered.pages.some((p) => p.file && routesBase(p.file)) || kept.some((p) => /^(src\/)?app\/layout\.(tsx|jsx|js|ts)$/.test(p)) ? { ok: true } : { ok: false, reason: "unparsed" },
114
+ starter: nextStarter,
115
+ },
116
+ html: {
117
+ kits: [],
118
+ configs: [],
119
+ listTools: [],
120
+ discover: (kept) => ({ pages: htmlPages(kept), notFound: null }),
121
+ acts: true,
122
+ routeLines: false,
123
+ segments: false,
124
+ destination: (page, to) => htmlDestination(page, to),
125
+ folderDirs: (at, below) => (below.length && below.every((p) => p.file?.startsWith(`${at.slice(1)}/`)) ? [at.slice(1)] : null),
126
+ links: (p) => /\.html?$/.test(p),
127
+ relativeLinks: true,
128
+ canCreate: (discovered) => (discovered.pages.length ? { ok: true } : { ok: false, reason: "unparsed" }),
129
+ starter: htmlStarter,
130
+ },
36
131
  };
37
132
 
133
+ /** A framework's adapter, or null where the core has none (an unknown framework, none detected). */
134
+ export const adapterOf = (framework) => (Object.prototype.hasOwnProperty.call(ADAPTERS, String(framework)) ? ADAPTERS[String(framework)] : null);
135
+
136
+ const FRAMEWORKS = Object.keys(ADAPTERS);
137
+
138
+ /** The packages that bring the kit into each framework's build (the adapters' `kits`). */
139
+ export const KITS = Object.fromEntries(FRAMEWORKS.filter((f) => ADAPTERS[f].kits.length).map((f) => [f, ADAPTERS[f].kits]));
140
+
38
141
  /** Frameworks the kit keeps drafts out of: those with a package that brings it (KITS). */
39
142
  export const DRAFTABLE = Object.keys(KITS);
40
143
 
@@ -45,26 +148,23 @@ const SKIP = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.out
45
148
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
46
149
  const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
47
150
 
48
- /** "about/" → "/about"; "" → "/". */
49
- export function normalisePath(p) {
50
- const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
51
- return s || "/";
52
- }
53
151
 
54
152
  // ── The page file ──────────────────────────────────────────────────────────
55
153
 
56
154
  /**
57
155
  * unbase.pages.json: `{ "pages": { "/address": { "draft": true, "name": "Pricing" } },
58
- * "redirects": { "/old": "/new" } }`. Absent is valid (no flags, no redirects). A page's `name` is
59
- * what Unbase calls it (never rendered); `redirects` send an old address on, applied at build by
60
- * the framework's package (docs/plan-page-actions.md). A redirect's address may end in
61
- * `/[...path]`: everything under it, carried over.
156
+ * "folders": { "/legal": { "name": "Legal" } }, "redirects": { "/old": "/new" } }`. Absent is valid
157
+ * (no flags, no redirects). A page's or folder's `name` is what Unbase calls it (never rendered; a
158
+ * folder is an address with pages under it and none of its own, docs/plan-folders-and-redirects.md);
159
+ * `redirects` send an old address on, applied at build by the framework's package
160
+ * (docs/plan-page-actions.md). A redirect's address may end in `/[...path]`: everything under it,
161
+ * carried over.
62
162
  * @param {string | null | undefined} text
63
- * @returns {{ ok: true, exists: boolean, pages: Record<string, { draft?: boolean, name?: string }>, redirects: Record<string, string> } | { ok: false, exists: true, error: string, pages: {}, redirects: {} }}
163
+ * @returns {{ ok: true, exists: boolean, error?: undefined, pages: Record<string, { draft?: boolean, name?: string }>, folders: Record<string, { name: string }>, redirects: Record<string, string> } | { ok: false, exists: true, error: string, pages: {}, folders: {}, redirects: {} }}
64
164
  */
65
165
  export function parsePageFile(text) {
66
- if (text == null) return { ok: true, exists: false, pages: {}, redirects: {} };
67
- const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {}, redirects: {} });
166
+ if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
167
+ const fail = (error) => ({ ok: /** @type {const} */ (false), exists: /** @type {const} */ (true), error, pages: {}, folders: {}, redirects: {} });
68
168
  let data;
69
169
  try {
70
170
  data = JSON.parse(text);
@@ -83,6 +183,15 @@ export function parsePageFile(text) {
83
183
  if (entry.name !== undefined && typeof entry.name !== "string") return fail(`${address}: name is text`);
84
184
  out[normalisePath(address)] = { ...(entry.draft === undefined ? {} : { draft: entry.draft }), ...(entry.name ? { name: entry.name } : {}) };
85
185
  }
186
+ const folderData = data.folders ?? {};
187
+ if (!isObject(folderData)) return fail("`folders` is not an object");
188
+ /** @type {Record<string, { name: string }>} */
189
+ const folders = {};
190
+ for (const [address, entry] of Object.entries(folderData)) {
191
+ if (!address.startsWith("/")) return fail(`folders: ${address}: an address starts with /`);
192
+ if (!isObject(entry) || (entry.name !== undefined && typeof entry.name !== "string")) return fail(`folders: ${address}: name is text`);
193
+ if (entry.name) folders[normalisePath(address)] = { name: entry.name };
194
+ }
86
195
  const redirects = data.redirects ?? {};
87
196
  if (!isObject(redirects)) return fail("`redirects` is not an object");
88
197
  /** @type {Record<string, string>} */
@@ -93,7 +202,7 @@ export function parsePageFile(text) {
93
202
  if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
94
203
  sends[normalisePath(from)] = normalisePath(to);
95
204
  }
96
- return { ok: true, exists: true, pages: out, redirects: sends };
205
+ return { ok: true, exists: true, pages: out, folders, redirects: sends };
97
206
  }
98
207
 
99
208
  /** A redirect's address that carries what is under it: `/old/[...path]`. */
@@ -152,14 +261,24 @@ function stringEnd(src, i) {
152
261
  export function stripComments(src) {
153
262
  let out = "";
154
263
  let i = 0;
264
+ // Text up to the next comment or string goes across whole: a large file is not built a character at a time.
265
+ const special = /\/[/*]|["'`]/g;
155
266
  while (i < src.length) {
267
+ special.lastIndex = i;
268
+ const next = special.exec(src);
269
+ const to = next ? next.index : src.length;
270
+ if (to > i) {
271
+ out += src.slice(i, to);
272
+ i = to;
273
+ continue;
274
+ }
156
275
  const c = src[i];
157
276
  const d = src[i + 1];
158
277
  if (c === "/" && d === "/") {
159
- while (i < src.length && src[i] !== "\n") {
160
- out += " ";
161
- i++;
162
- }
278
+ const end = src.indexOf("\n", i);
279
+ const stop = end < 0 ? src.length : end;
280
+ out += " ".repeat(stop - i);
281
+ i = stop;
163
282
  continue;
164
283
  }
165
284
  if (c === "/" && d === "*") {
@@ -263,6 +382,24 @@ function astroPages(paths) {
263
382
  return out;
264
383
  }
265
384
 
385
+ /**
386
+ * A site of HTML files (detection `html`: no build): a page per .html file, at the address Vercel
387
+ * serves it from (and the runner's static server, unbase-operator src/static-server.ts): `index.html`
388
+ * of a folder at the folder, any other file by its name. 404.html is the not-found page, no page.
389
+ */
390
+ function htmlPages(paths) {
391
+ /** @type {Page[]} */
392
+ const out = [];
393
+ for (const p of paths) {
394
+ if (!p.endsWith(".html") || p === "404.html") continue;
395
+ const segments = p.split("/");
396
+ if (segments.some((s) => s.startsWith("."))) continue;
397
+ if (segments.at(-1) === "index.html") segments.pop();
398
+ out.push({ path: address(segments), kind: "file", file: p });
399
+ }
400
+ return out;
401
+ }
402
+
266
403
  /** Next.js: app/**\/page.* and pages/**, as unbase-projects' pages.ts read them. */
267
404
  function nextPages(paths) {
268
405
  /** @type {Page[]} */
@@ -357,8 +494,235 @@ function importedComponents(src) {
357
494
  return out;
358
495
  }
359
496
 
497
+ /** A call that makes a router or reads routes from route objects: its first argument is their array. */
498
+ const ROUTER_CALL = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/g;
499
+ /** The same, to test a file with (a global regex keeps where its last test stopped). */
500
+ const MAKES_ROUTER = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/;
501
+ const IMPORTS_ROUTER = /from\s*["']react-router(-dom)?["']/;
502
+
503
+ /** The index of the first character after `i` that is no white space. */
504
+ const skipWs = (src, i) => {
505
+ while (i < src.length && /\s/.test(src[i])) i++;
506
+ return i;
507
+ };
508
+
509
+ /** Where the bracket that opens at `i` (`{`, `[` or `(`) closes, strings skipped: the index after it. */
510
+ function closing(src, i) {
511
+ let depth = 0;
512
+ for (let j = i; j < src.length; j++) {
513
+ const c = src[j];
514
+ if (c === '"' || c === "'" || c === "`") {
515
+ j = stringEnd(src, j) - 1;
516
+ continue;
517
+ }
518
+ if (c === "{" || c === "[" || c === "(") depth++;
519
+ else if ((c === "}" || c === "]" || c === ")") && --depth === 0) return j + 1;
520
+ }
521
+ return src.length;
522
+ }
523
+
524
+ /** From `i`, where the value that starts there ends: the next `,` or closing bracket at its own depth. */
525
+ function valueEnd(src, i, end) {
526
+ let depth = 0;
527
+ while (i < end) {
528
+ const c = src[i];
529
+ if (c === '"' || c === "'" || c === "`") {
530
+ i = stringEnd(src, i);
531
+ continue;
532
+ }
533
+ if (c === "{" || c === "[" || c === "(") depth++;
534
+ else if (c === "}" || c === "]" || c === ")") {
535
+ if (depth === 0) return i;
536
+ depth--;
537
+ } else if (c === "," && depth === 0) return i;
538
+ i++;
539
+ }
540
+ return i;
541
+ }
542
+
543
+ /** The elements of the array literal that opens at `at` (`[`), each as [start, end) without white space around it. */
544
+ function arrayElements(src, at) {
545
+ const end = closing(src, at) - 1;
546
+ const out = [];
547
+ let i = at + 1;
548
+ while (i < end) {
549
+ i = skipWs(src, i);
550
+ if (i >= end) break;
551
+ if (src[i] === ",") {
552
+ i++;
553
+ continue;
554
+ }
555
+ const stop = valueEnd(src, i, end);
556
+ let e = stop;
557
+ while (e > i && /\s/.test(src[e - 1])) e--;
558
+ if (e > i) out.push({ start: i, end: src[i] === "{" ? closing(src, i) : e });
559
+ i = stop;
560
+ }
561
+ return out;
562
+ }
563
+
564
+ /** The entries of the object literal that opens at `at` (`{`): each key with where its value is; spreads and shorthands left out. */
565
+ function objectEntries(src, at) {
566
+ const end = closing(src, at) - 1;
567
+ const out = [];
568
+ let i = at + 1;
569
+ while (i < end) {
570
+ i = skipWs(src, i);
571
+ if (i >= end) break;
572
+ if (src[i] === ",") {
573
+ i++;
574
+ continue;
575
+ }
576
+ const stop = valueEnd(src, i, end);
577
+ const key = src.slice(i, stop).match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:\s*/);
578
+ if (key) {
579
+ const valueStart = i + key[0].length;
580
+ let e = stop;
581
+ while (e > valueStart && /\s/.test(src[e - 1])) e--;
582
+ out.push({ key: key[2], valueStart, valueEnd: e });
583
+ }
584
+ i = stop;
585
+ }
586
+ return out;
587
+ }
588
+
589
+ /** A string literal's value ("…", '…', `…` without `${}`), or false when the text is not one. */
590
+ function literalString(value) {
591
+ const lit = value.trim().match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/);
592
+ return lit ? (lit.slice(1).find((v) => v !== undefined) ?? "") : false;
593
+ }
594
+
595
+ /** Where an array of route objects named `name` is declared in `src` (`const routes = [`, typed or not), or null. */
596
+ function arrayDeclared(src, name) {
597
+ const m = new RegExp(`(?:^|[;\\s])(?:export\\s+)?(?:const|let|var)\\s+${escape(name)}\\s*(?::[^=;]+)?=\\s*`).exec(src);
598
+ if (!m) return null;
599
+ const at = skipWs(src, m.index + m[0].length);
600
+ return src[at] === "[" ? at : null;
601
+ }
602
+
603
+ /** Where `src`'s default export is an array of route objects (`export default [`, or a name declared as one), or null. */
604
+ function defaultArray(src) {
605
+ const m = src.match(/\bexport\s+default\s+/);
606
+ if (!m) return null;
607
+ const at = skipWs(src, m.index + m[0].length);
608
+ if (src[at] === "[") return at;
609
+ const name = src.slice(at).match(/^([A-Za-z_$][\w$]*)\s*;?/)?.[1];
610
+ return name ? arrayDeclared(src, name) : null;
611
+ }
612
+
613
+ /** How `src` imports `name`: its specifier, and whether as the default or a named export (`exported` the name it has there). */
614
+ function importOf(src, name) {
615
+ for (const m of src.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*["']([^"']+)["']/g)) {
616
+ if (m[1] === name) return { spec: m[3], exported: null };
617
+ for (const part of (m[2] ?? "").split(",")) {
618
+ const [exported, local] = part.trim().split(/\s+as\s+/);
619
+ if ((local ?? exported) === name && exported) return { spec: m[3], exported };
620
+ }
621
+ }
622
+ return null;
623
+ }
624
+
625
+ /**
626
+ * Where the route objects of a site are: per file, the start of each array a router call takes
627
+ * (`createBrowserRouter([...])`, `useRoutes(routes)`), followed to its declaration in the same file
628
+ * or in the module it is imported from. Only files that import react-router(-dom) make a router.
629
+ * @returns {Map<string, number[]>}
630
+ */
631
+ function routeArrays(paths, text, have) {
632
+ /** @type {Map<string, number[]>} */
633
+ const out = new Map();
634
+ const add = (f, at) => out.set(f, [...new Set([...(out.get(f) ?? []), at])]);
635
+ for (const file of paths) {
636
+ if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
637
+ const raw = text(file);
638
+ if (!raw || !IMPORTS_ROUTER.test(raw) || !MAKES_ROUTER.test(raw)) continue;
639
+ const src = stripComments(raw);
640
+ for (const m of src.matchAll(ROUTER_CALL)) {
641
+ const i = skipWs(src, m.index + m[0].length);
642
+ if (src[i] === "[") {
643
+ add(file, i);
644
+ continue;
645
+ }
646
+ const name = src.slice(i).match(/^([A-Za-z_$][\w$]*)\s*[,)]/)?.[1];
647
+ if (!name) continue;
648
+ const local = arrayDeclared(src, name);
649
+ if (local !== null) {
650
+ add(file, local);
651
+ continue;
652
+ }
653
+ const imp = importOf(src, name);
654
+ const target = imp ? resolveImport(file, imp.spec, have) : null;
655
+ const other = target ? text(target) : null;
656
+ if (!other) continue;
657
+ const tsrc = stripComments(other);
658
+ const at = imp.exported ? arrayDeclared(tsrc, imp.exported) : defaultArray(tsrc);
659
+ if (at !== null) add(target, at);
660
+ }
661
+ }
662
+ return out;
663
+ }
664
+
360
665
  /**
361
- * React Router: the JSX `<Route>` elements of every file that imports react-router(-dom), with
666
+ * The pages of one array of route objects (`{ path, element: <X />, Component: X, lazy, index,
667
+ * children }`), as JSX routes are read: an index route takes its parent's path, one without a path
668
+ * adds nothing, children nest under their parent's path. Each is traced to the file its component
669
+ * comes from (a default import, React.lazy, or `lazy: () => import(…)`).
670
+ */
671
+ function routeObjectPages({ file, src, at, parent, have, imports, pages, found }) {
672
+ for (const el of arrayElements(src, at)) {
673
+ if (src[el.start] !== "{") continue; // a spread or a name: not read
674
+ const entries = objectEntries(src, el.start);
675
+ const value = (key) => {
676
+ const e = entries.find((x) => x.key === key);
677
+ return e ? src.slice(e.valueStart, e.valueEnd) : null;
678
+ };
679
+ const index = /^true$/.test((value("index") ?? "").trim());
680
+ const pathValue = value("path");
681
+ const p = pathValue === null ? null : literalString(pathValue);
682
+ const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
683
+ const childrenEntry = entries.find((x) => x.key === "children");
684
+ const childAt = childrenEntry && src[childrenEntry.valueStart] === "[" ? childrenEntry.valueStart : null;
685
+ const children = childAt !== null && arrayElements(src, childAt).length > 0;
686
+ let component = null;
687
+ let importKind = null;
688
+ let target = null;
689
+ let spec = null;
690
+ const comp = (value("Component") ?? "").trim().match(/^([A-Z][\w$]*)$/)?.[1] ?? (value("element") ?? "").trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/)?.[1];
691
+ if (comp) {
692
+ const imported = imports.get(comp);
693
+ if (imported) {
694
+ component = comp;
695
+ importKind = imported.kind;
696
+ target = resolveImport(file, imported.spec, have);
697
+ }
698
+ } else {
699
+ const lazy = (value("lazy") ?? "").match(/import\(\s*(["'])([^"']+)\1\s*\)/);
700
+ if (lazy) {
701
+ spec = lazy[2];
702
+ importKind = "inline";
703
+ target = resolveImport(file, spec, have);
704
+ }
705
+ }
706
+ if (full === false) pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
707
+ else if (full !== null) {
708
+ if (full === "/*" || full.endsWith("/*") || full === "*") {
709
+ if (full === "/*" && target) found.notFound = target;
710
+ } else {
711
+ /** @type {Page} */
712
+ const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
713
+ if (target && importKind) page.router = { file, start: el.start, end: el.end, component, importKind, object: true, ...(spec ? { spec } : {}) };
714
+ if (children) page.reason = "nested";
715
+ else if (!target) page.reason = "unparsed";
716
+ pages.push(page);
717
+ }
718
+ }
719
+ if (childAt !== null) routeObjectPages({ file, src, at: childAt, parent: typeof full === "string" ? full : parent, have, imports, pages, found });
720
+ }
721
+ }
722
+
723
+ /**
724
+ * React Router: the JSX `<Route>` elements of every file that imports react-router(-dom), and the
725
+ * route objects its routers are made of (`createBrowserRouter([...])`, `useRoutes(routes)`), with
362
726
  * their nesting (an index route takes its parent's path, a layout route without a path adds
363
727
  * nothing), each traced to the file its component comes from. `*` is the catch-all (Not Found).
364
728
  * @returns {{ pages: Page[], notFound: string | null }}
@@ -367,11 +731,20 @@ function reactRouterPages(paths, text, only = paths) {
367
731
  const have = new Set(paths);
368
732
  /** @type {Page[]} */
369
733
  const pages = [];
370
- let notFound = null;
734
+ const found = { notFound: null };
735
+ const arrays = routeArrays(paths, text, have);
736
+ for (const file of only) {
737
+ const starts = arrays.get(file);
738
+ if (!starts?.length) continue;
739
+ const src = stripComments(text(file) ?? "");
740
+ const imports = importedComponents(src);
741
+ for (const at of starts) routeObjectPages({ file, src, at, parent: "", have, imports, pages, found });
742
+ }
743
+ let notFound = found.notFound;
371
744
  for (const file of only) {
372
745
  if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
373
746
  const raw = text(file);
374
- if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
747
+ if (!raw || !raw.includes("<Route") || !IMPORTS_ROUTER.test(raw)) continue;
375
748
  const src = stripComments(raw);
376
749
  const imports = importedComponents(src);
377
750
  /** @type {{ at: number, close?: true }[]} */
@@ -418,14 +791,28 @@ function reactRouterPages(paths, text, only = paths) {
418
791
  }
419
792
 
420
793
  /**
421
- * A router file's `code` without the `<Route … />` of each address in `drop` that it holds, as
422
- * discovery found them (the same parser, so what was checked is what goes). `removed` names them;
423
- * the plugin refuses the build when a draft's route was removed nowhere.
794
+ * Where a route is in its router file, to take it out: a `<Route … />` element as it stands, a route
795
+ * object with the comma after it, so the array stays an array without a hole.
796
+ */
797
+ function routeSpan(src, router) {
798
+ if (!router.object) return { start: router.start, end: router.end };
799
+ let end = router.end;
800
+ let i = router.end;
801
+ while (i < src.length && (src[i] === " " || src[i] === "\t")) i++;
802
+ if (src[i] === ",") end = i + 1;
803
+ return { start: router.start, end };
804
+ }
805
+
806
+ /**
807
+ * A router file's `code` without the route (a `<Route … />` element, or a route object) of each
808
+ * address in `drop` that it holds, as discovery found them (the same parser, so what was checked is
809
+ * what goes). `removed` names them; the plugin refuses the build when a draft's route was removed
810
+ * nowhere.
424
811
  * @param {{ file: string, code: string, paths: string[], text: (path: string) => string | null, drop: string[] }} input
425
812
  */
426
813
  export function removeRoutes({ file, code, paths, text, drop }) {
427
814
  const { pages } = reactRouterPages(paths, (p) => (p === file ? code : text(p)), [file]);
428
- const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
815
+ const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...routeSpan(code, p.router) }));
429
816
  spans.sort((a, b) => b.start - a.start);
430
817
  let out = code;
431
818
  for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
@@ -439,8 +826,7 @@ export function removeRoutes({ file, code, paths, text, drop }) {
439
826
  */
440
827
  export function discover({ framework, paths, text }) {
441
828
  const kept = paths.filter((p) => !SKIP.test(p));
442
- const found =
443
- framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : { pages: [], notFound: null };
829
+ const found = adapterOf(framework)?.discover(kept, text) ?? { pages: [], notFound: null };
444
830
  const seen = new Set();
445
831
  const pages = found.pages
446
832
  .filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
@@ -453,8 +839,26 @@ export function discover({ framework, paths, text }) {
453
839
  const CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
454
840
  /** Where content collections are defined: naming one there is not using it. */
455
841
  const CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
456
- /** Written by comment-modus: content file → its collection, where that is not its folder. */
457
- const COLLECTIONS = "src/content/.schemas/collecties.json";
842
+ /**
843
+ * Written by comment-modus: content file → its collection, where that is not its folder. 1.11 and
844
+ * newer write collections.json; LEGACY-NL: older ones only collecties.json. Both are read, merged as
845
+ * comment-modus merges them (the English one wins), and both are written.
846
+ */
847
+ const COLLECTIONS = "src/content/.schemas/collections.json";
848
+ const LEGACY_COLLECTIONS = "src/content/.schemas/collecties.json";
849
+
850
+ /** The list from either file; null when neither is there or readable. */
851
+ function readCollections(text) {
852
+ /** @type {Record<string, unknown> | null} */
853
+ let out = null;
854
+ for (const p of [LEGACY_COLLECTIONS, COLLECTIONS]) {
855
+ try {
856
+ const d = JSON.parse(text(p) ?? "null");
857
+ if (isObject(d)) out = { ...(out ?? {}), ...d };
858
+ } catch {}
859
+ }
860
+ return out;
861
+ }
458
862
 
459
863
  /** The names a content file goes by: its entry id (file name) and its collection. */
460
864
  function contentNames(paths, text) {
@@ -464,9 +868,10 @@ function contentNames(paths, text) {
464
868
  if (!files.has(name)) files.set(name, new Set());
465
869
  files.get(name).add(f);
466
870
  };
871
+ /** @type {Record<string, unknown>} */
467
872
  let collections = {};
468
873
  try {
469
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
874
+ collections = readCollections(text) ?? {};
470
875
  } catch {}
471
876
  for (const f of paths) {
472
877
  if (!CONTENT_JSON.test(f)) continue;
@@ -503,22 +908,91 @@ function ownCode(page, importers, imports) {
503
908
 
504
909
  /** Astro's own reading functions: collection first, then (getEntry) the entry. */
505
910
  const ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
911
+ /** Whether a text names one of them. */
912
+ const ASTRO_NAMED = /getCollection|getEntry|getEntries/;
506
913
 
507
914
  /**
508
915
  * How the site reads content, as the editability manifest's `reads` say it (plan-editable F0):
509
916
  * Astro's functions; the site's own functions that pass their first argument on as the collection
510
917
  * (`getPagina(naam)`: `byName`); and those that read fixed content (`getEvenementen()` a whole
511
- * collection, `getActieAgendaTeksten()` one entry: `fixed`). `code` is every code file without
512
- * its comments.
918
+ * collection, `getActieAgendaTeksten()` one entry: `fixed`). `files` is every code file with its
919
+ * text; `code` holds, without comments, the ones that can read content (`reading`).
920
+ *
921
+ * Only files that name a reading function are read for helpers: Astro's own, then the helpers
922
+ * found, again until no file is added. A file that names none of them defines no helper that reads
923
+ * and calls none, so the answer is the one all files give (a large repo's backend, tests and docs:
924
+ * 1.9 s of an Edge Function's 2 s on Unbase's own, docs/plan-page-analysis.md).
513
925
  */
514
926
  function contentReads(paths, text) {
515
- /** @type {Map<string, string>} */
516
- const code = new Map();
927
+ /** @type {[string, string][]} */
928
+ const files = [];
517
929
  for (const p of paths) {
518
930
  if (!CODE.test(p) || SKIP.test(p)) continue;
519
931
  const src = text(p);
520
- if (src) code.set(p, stripComments(src));
932
+ if (src) files.push([p, src]);
933
+ }
934
+ const picked = new Set();
935
+ // Each round asks the files not yet read only about the names it found: they named none before.
936
+ // A file is parsed once, whichever round reads it.
937
+ const asked = new Set(ASTRO_READS);
938
+ const parsed = new Map();
939
+ let names = ASTRO_READS;
940
+ let reads = null;
941
+ for (;;) {
942
+ let grew = false;
943
+ if (names.length) {
944
+ const naming = new RegExp(names.map(escape).join("|"));
945
+ for (const [p, src] of files) {
946
+ if (picked.has(p) || !naming.test(src)) continue;
947
+ picked.add(p);
948
+ grew = true;
949
+ }
950
+ }
951
+ if (reads && !grew) return { ...reads, files };
952
+ reads = readsOver(files.filter(([p]) => picked.has(p)), parsed);
953
+ names = [...reads.byName, ...reads.fixed.keys()].filter((n) => !asked.has(n));
954
+ names.forEach((n) => asked.add(n));
955
+ if (!names.length) return { ...reads, files };
956
+ }
957
+ }
958
+
959
+ const DIRECT = new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
960
+ const 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;
961
+
962
+ /**
963
+ * One file's code without comments and its functions: each one's name, body and where it is, and
964
+ * what its own body reads (`byName`: it passes its first argument on as the collection, with the
965
+ * entry it always reads; `direct`: Astro's functions called with a literal). Only from the file.
966
+ */
967
+ function parseCode(p, src) {
968
+ const code = stripComments(src);
969
+ const fns = [];
970
+ if (!/\.(ts|mts|js|mjs)$/.test(p)) return { code, fns };
971
+ // Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
972
+ for (const m of code.matchAll(FUNCTION)) {
973
+ const name = m[1] ?? m[3];
974
+ const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
975
+ // The body: a block, or for an arrow the expression up to the end of its statement.
976
+ let at = m.index + m[0].length;
977
+ while (/\s/.test(code[at] ?? "")) at++;
978
+ const block = code.indexOf("{", at);
979
+ const braces = code[at] === "{" ? at : m[1] && block > 0 ? block : -1;
980
+ const body = braces >= 0 ? (braced(code, braces) ?? "") : code.slice(at, code.slice(at).search(/;|\n\s*\n|$/) + at);
981
+ const start = braces >= 0 ? braces + 1 : at;
982
+ // Every reading below names one of Astro's functions: a body that names none is not searched.
983
+ const naming = ASTRO_NAMED.test(body);
984
+ const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
985
+ const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : undefined;
986
+ const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
987
+ fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
521
988
  }
989
+ return { code, fns };
990
+ }
991
+
992
+ /** contentReads over `files` (in path order): what their functions read, and their code without comments. */
993
+ function readsOver(files, parsed = new Map()) {
994
+ /** @type {Map<string, string>} */
995
+ const code = new Map();
522
996
  const astro = ASTRO_READS.join("|");
523
997
  const byName = new Set(ASTRO_READS);
524
998
  /** The entry a reading function always reads: `getEntry(collectie, "pagina")` → "pagina". */
@@ -529,47 +1003,38 @@ function contentReads(paths, text) {
529
1003
  const bodies = new Map();
530
1004
  /** Where each file's helpers have their bodies, [start, end): what a body reads, its callers read. */
531
1005
  const spans = new Map();
532
- const DIRECT = new RegExp(`\\b(?:${astro})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
533
1006
  const addFixed = (name, whole, entry) => {
534
1007
  if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
535
1008
  if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
536
1009
  else fixed.get(name).whole.add(whole);
537
1010
  };
538
- for (const [p, src] of code) {
539
- if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
540
- // Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
541
- 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)) {
542
- const name = m[1] ?? m[3];
543
- const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
544
- // The body: a block, or for an arrow the expression up to the end of its statement.
545
- let at = m.index + m[0].length;
546
- while (/\s/.test(src[at] ?? "")) at++;
547
- const block = src.indexOf("{", at);
548
- const braces = src[at] === "{" ? at : m[1] && block > 0 ? block : -1;
549
- const body = braces >= 0 ? (braced(src, braces) ?? "") : src.slice(at, src.slice(at).search(/;|\n\s*\n|$/) + at);
550
- const start = braces >= 0 ? braces + 1 : at;
1011
+ for (const [p, src] of files) {
1012
+ if (!parsed.has(p)) parsed.set(p, parseCode(p, src));
1013
+ const file = parsed.get(p);
1014
+ code.set(p, file.code);
1015
+ for (const fn of file.fns) {
551
1016
  if (!spans.has(p)) spans.set(p, []);
552
- spans.get(p).push([start, start + body.length]);
553
- if (first && new RegExp(`\\b(?:${astro})\\(\\s*${escape(first)}\\b`).test(body)) {
554
- byName.add(name);
555
- const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
556
- if (entry) entryOf.set(name, entry);
1017
+ spans.get(p).push([fn.start, fn.end]);
1018
+ if (fn.byName) {
1019
+ byName.add(fn.name);
1020
+ if (fn.entry) entryOf.set(fn.name, fn.entry);
557
1021
  }
558
- bodies.set(name, body);
559
- for (const d of body.matchAll(DIRECT)) addFixed(name, d[1], d[2]);
1022
+ bodies.set(fn.name, fn.body);
1023
+ for (const [whole, entry] of fn.direct) addFixed(fn.name, whole, entry);
560
1024
  }
561
1025
  }
562
1026
  // A helper that calls one of the site's reading functions with a literal reads that content
563
1027
  // (`getVerlangensOverzicht = () => enkel("verlangensOverzicht", …)`): its entry, else the collection.
564
1028
  for (const [name, body] of bodies) {
565
1029
  for (const fn of byName) {
566
- if (fn === name || ASTRO_READS.includes(fn)) continue;
1030
+ if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
567
1031
  for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
568
1032
  }
569
1033
  }
570
1034
  // A helper that calls a helper reads what that one reads (`getActieAgenda()` → `getActieAgendaTeksten()`).
571
1035
  // Each body's calls are read once and looked up, not searched for helper by helper.
572
- const calls = new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))]));
1036
+ // Nothing read yet: no call can pass anything on.
1037
+ const calls = fixed.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : new Map();
573
1038
  for (let grew = true; grew; ) {
574
1039
  grew = false;
575
1040
  for (const [name, called] of calls) {
@@ -585,8 +1050,10 @@ function contentReads(paths, text) {
585
1050
  }
586
1051
  }
587
1052
  }
1053
+ // The helpers that read, as whole identifiers (as IDENTIFIER would find them), longest first.
1054
+ const helpers = fixed.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
588
1055
  const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
589
- return { code, byName, byNameCall, entryOf, fixed, astro, spans };
1056
+ return { code, byName, byNameCall, entryOf, fixed, astro, spans, helpers };
590
1057
  }
591
1058
 
592
1059
  /** A call: `name(`, not `obj.name(`. */
@@ -639,8 +1106,9 @@ function readsIn(src, reads, path = null) {
639
1106
  }
640
1107
  // The file's names counted once, and the helpers among them looked up: one pass per file, however
641
1108
  // many helpers the site has (1,000 pages each with its own took 1.6 s searched one by one).
1109
+ // Only the helpers' own names are counted: an identifier that is none of them adds nothing.
642
1110
  const mentions = new Map();
643
- for (const [name] of code.matchAll(IDENTIFIER)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
1111
+ if (reads.helpers) for (const [name] of code.matchAll(reads.helpers)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
644
1112
  const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
645
1113
  for (const [name, n] of mentions) {
646
1114
  const read = reads.fixed.get(name);
@@ -655,20 +1123,30 @@ function readsIn(src, reads, path = null) {
655
1123
  * What the whole site reads, which no page changes: once per set of files, not once per page (20
656
1124
  * pages each reading a real site's 300 files ran out of an Edge Function's CPU, 26-10). Kept by the import
657
1125
  * graph, which a registry or a build makes once from the same files.
658
- * @type {WeakMap<Map<string, Set<string>>, { collections: Record<string, unknown>, names: Map<string, Set<string>>, readsByFile: Map<string, ReturnType<typeof readsIn>>, isRoute: (f: string) => boolean }>}
1126
+ * @typedef {{ collections: Record<string, unknown>, names: Map<string, Set<string>>, readsByFile: Map<string, ReturnType<typeof readsIn>>,
1127
+ * counts: { names: Map<string, number>, entries: Map<string, number>, whole: Map<string, number> },
1128
+ * byEntry: Map<string, string[]>, byCollection: Map<string, string[]>, namesOf: Map<string, string[]>, routeOf: Map<string, string[]>,
1129
+ * isRoute: (f: string) => boolean, jsonOf: Map<string, string[]>, imports: Map<string, string[]>, byName: any }} SiteReads
1130
+ * @type {WeakMap<Map<string, Set<string>>, SiteReads>}
659
1131
  */
660
1132
  const siteReadsOf = new WeakMap();
661
1133
 
662
1134
  function siteReads(paths, text, importers) {
663
1135
  const kept = siteReadsOf.get(importers);
664
1136
  if (kept) return kept;
1137
+ /** @type {Record<string, unknown>} */
665
1138
  let collections = {};
666
1139
  try {
667
- collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
1140
+ collections = readCollections(text) ?? {};
668
1141
  } catch {}
669
1142
  const reads = contentReads(paths, text);
670
1143
  const readsByFile = new Map();
671
- for (const [p, src] of reads.code) if (!CONTENT_CONFIG.test(p)) readsByFile.set(p, readsIn(src, reads, p));
1144
+ // A file that names no reading function reads nothing (contentReads): its answer without a look.
1145
+ for (const [p] of reads.files) {
1146
+ if (CONTENT_CONFIG.test(p)) continue;
1147
+ const code = reads.code.get(p);
1148
+ readsByFile.set(p, code === undefined ? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() } : readsIn(code, reads, p));
1149
+ }
672
1150
  // How many files read each name, entry and collection: "read elsewhere" is the site's count
673
1151
  // less the page's own files', not a union of every other file made again for each page.
674
1152
  const counts = { names: new Map(), entries: new Map(), whole: new Map() };
@@ -820,14 +1298,9 @@ export function mediaGenerators(text) {
820
1298
  return MEDIA.filter((m) => m in deps);
821
1299
  }
822
1300
 
823
- /**
824
- * Packages that write a site's page list after the build, from its output (next-sitemap reads
825
- * Next.js's manifests, where a draft's address still is): the kit cannot clean what they write.
826
- */
827
- const LIST_TOOLS = { next: ["next-sitemap"] };
828
-
1301
+ /** The packages that write the site's page list after its build (its adapter's `listTools`) that it has. */
829
1302
  export function listTools(framework, text) {
830
- const tools = LIST_TOOLS[String(framework)] ?? [];
1303
+ const tools = adapterOf(framework)?.listTools ?? [];
831
1304
  if (!tools.length) return [];
832
1305
  let pkg = null;
833
1306
  try {
@@ -866,7 +1339,9 @@ export function draftCheck(path, { framework, paths, text, found, importers }) {
866
1339
  if (page.kind === "template") return no("template", page.path);
867
1340
  if (page.reason) return no(page.reason);
868
1341
  if (!page.file) return no("unparsed");
869
- if (framework === "next") {
1342
+ // A route object is kept out only by a plugin that reads route objects (OBJECT_ROUTES_SINCE): an older one would not find it.
1343
+ if (page.router?.object && !kitAtLeast({ framework, text }, OBJECT_ROUTES_SINCE)) return no("kit_old", "route objects");
1344
+ if (adapterOf(framework)?.segments) {
870
1345
  const beside = segmentFiles(page.file, paths);
871
1346
  if (beside.length) return no("segment", beside.join(", "));
872
1347
  }
@@ -897,13 +1372,6 @@ export function segmentFiles(file, paths) {
897
1372
  return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
898
1373
  }
899
1374
 
900
- /** "/blog/:slug" or "/blog/[slug]" against "/blog/hello". */
901
- function templateMatches(template, path) {
902
- const t = template.split("/");
903
- const p = path.split("/");
904
- if (t.at(-1)?.startsWith("[...") || t.at(-1) === "*") return p.length >= t.length - 1 && t.slice(0, -1).every((s, i) => s === p[i] || /^(\[|:)/.test(s));
905
- return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
906
- }
907
1375
 
908
1376
  /**
909
1377
  * Every draft in the page file, checked. `failed` holds the ones a production build cannot keep
@@ -927,10 +1395,10 @@ const APP_SOURCE = /^(src|app|pages|components|lib)\//;
927
1395
  * anchor or a query) in code or content, other than the page's own files (`own`: its file and the
928
1396
  * content it owns) and its route's `path`. Built at runtime (`/${slug}`) is not found.
929
1397
  */
930
- export function linksTo(path, { paths, text, own = [] }) {
1398
+ export function linksTo(path, { paths, text, own = [], framework = null }) {
931
1399
  if (path === "/") return [];
932
1400
  const mine = new Set(own);
933
- return [...(linkIndex(paths, text).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
1401
+ return [...(linkIndex(paths, text, adapterOf(framework)).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
934
1402
  }
935
1403
 
936
1404
  /**
@@ -938,35 +1406,48 @@ export function linksTo(path, { paths, text, own = [] }) {
938
1406
  * not once per page. The same quotes as a search for each address would find: an opening quote, the
939
1407
  * address, an optional trailing slash, anchor or query, and the same quote (the closing one may open
940
1408
  * the next); not a route's own `path` or `pad`.
941
- * @type {WeakMap<(path: string) => string | null, { paths: string[], index: Map<string, Set<string>> }>}
1409
+ * @type {WeakMap<(path: string) => string | null, Record<string, { paths: string[], index: Map<string, Set<string>> }>>}
942
1410
  */
943
1411
  const linkIndexOf = new WeakMap();
944
1412
  const QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
945
1413
 
946
- function linkIndex(paths, text) {
947
- const kept = linkIndexOf.get(text);
1414
+ function linkIndex(paths, text, adapter = null) {
1415
+ const kind = adapter?.links ? "site" : "app";
1416
+ const kept = linkIndexOf.get(text)?.[kind];
948
1417
  if (kept?.paths === paths) return kept.index;
949
1418
  const index = new Map();
1419
+ const add = (address, p) => {
1420
+ if (!index.has(address)) index.set(address, new Set());
1421
+ index.get(address).add(p);
1422
+ };
1423
+ const linkFile = adapter?.links ?? ((p) => APP_SOURCE.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
950
1424
  for (const p of paths) {
951
- if (SKIP.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
952
- for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
1425
+ if (SKIP.test(p) || !linkFile(p)) continue;
1426
+ const raw = text(p) ?? "";
1427
+ // A code sample in a text names an address without linking it.
1428
+ const src = blankRanges(raw, codeRanges(raw, p));
1429
+ for (const [, , quoted] of src.matchAll(QUOTED_ADDRESS)) {
953
1430
  const bare = quoted.replace(/[#?][\s\S]*$/, "");
954
- const address = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
955
- if (!index.has(address)) index.set(address, new Set());
956
- index.get(address).add(p);
1431
+ add(bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare, p);
1432
+ }
1433
+ // A site of HTML files links its pages by relative URLs too.
1434
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) {
1435
+ for (const [, , , url] of src.matchAll(URL_ATTRIBUTE)) {
1436
+ const bare = url.replace(/[#?][\s\S]*$/, "");
1437
+ if (!relativeUrl(url) || !bare) continue;
1438
+ const address = servedAddress(resolvedUrl(dirname(p), bare), bare.endsWith("/"));
1439
+ if (address !== null) add(address, p);
1440
+ }
957
1441
  }
958
1442
  }
959
- linkIndexOf.set(text, { paths, index });
1443
+ linkIndexOf.set(text, { ...(linkIndexOf.get(text) ?? {}), [kind]: { paths, index } });
960
1444
  return index;
961
1445
  }
962
1446
 
963
1447
  // ── Kit installed ──────────────────────────────────────────────────────────
964
1448
 
965
- const CONFIGS = {
966
- astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
967
- "vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
968
- next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
969
- };
1449
+ /** Each framework's build config files (the adapters' `configs`). */
1450
+ const CONFIGS = Object.fromEntries(FRAMEWORKS.filter((f) => ADAPTERS[f].configs.length).map((f) => [f, ADAPTERS[f].configs]));
970
1451
 
971
1452
  /** The files kitInstalled reads: the package and the build's config, relative to the app. */
972
1453
  export const kitFiles = (framework) => ["package.json", ...(CONFIGS[String(framework)] ?? [])];
@@ -1098,8 +1579,8 @@ export function withoutInContentMap(json, files) {
1098
1579
  // a developer's own agent make byte-identical changes. What it cannot do by rule, it refuses with a
1099
1580
  // reason; the editor says why, and offers the Operator where it can (`content_bound`).
1100
1581
 
1101
- /** Frameworks the actions know how a page is made in. */
1102
- export const PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
1582
+ /** Frameworks the actions know how a page is made in (the adapters that `act`). */
1583
+ export const PAGE_ACTION_FRAMEWORKS = FRAMEWORKS.filter((f) => ADAPTERS[f].acts);
1103
1584
 
1104
1585
  /** Since which version each package applies the page file's redirects at build. */
1105
1586
  export const REDIRECTS_SINCE = { "@unbase-app/pages": "0.4.0", "@unbase-app/astro": "0.3.0", "@unbase-app/vite": "0.3.0", "@unbase-app/next": "0.3.0" };
@@ -1123,6 +1604,17 @@ const atLeast = (have, want) => {
1123
1604
  * old address silently.
1124
1605
  */
1125
1606
  export function kitRedirects({ framework, text }) {
1607
+ return kitAtLeast({ framework, text }, REDIRECTS_SINCE);
1608
+ }
1609
+
1610
+ /** Since which version each package keeps a route object (`createBrowserRouter([...])`) off Live: the release after 17-11 (PE4b). */
1611
+ export const OBJECT_ROUTES_SINCE = { "@unbase-app/vite": "0.4.0", "@unbase-app/pages": "0.5.0" };
1612
+
1613
+ /**
1614
+ * Whether the kit is installed (kitInstalled) by a package whose range in package.json starts at or
1615
+ * after the version `since` names for it. A range that does not say (a file, a tag) counts as not.
1616
+ */
1617
+ function kitAtLeast({ framework, text }, since) {
1126
1618
  if (!kitInstalled({ framework, text })) return false;
1127
1619
  let pkg = null;
1128
1620
  try {
@@ -1131,35 +1623,13 @@ export function kitRedirects({ framework, text }) {
1131
1623
  const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1132
1624
  return (KITS[String(framework)] ?? []).some((name) => {
1133
1625
  const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
1134
- const since = REDIRECTS_SINCE[name];
1626
+ const want = since[name];
1135
1627
  const have = lowestVersion(spec);
1136
- return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
1628
+ return !!want && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(want));
1137
1629
  });
1138
1630
  }
1139
1631
 
1140
- /** "Pricing plans" → "pricing-plans"; "Één agenda" → "een-agenda". */
1141
- export function slugOf(name) {
1142
- return String(name)
1143
- .normalize("NFKD")
1144
- .replace(/[̀-ͯ]/g, "")
1145
- .toLowerCase()
1146
- .replace(/[^a-z0-9]+/g, "-")
1147
- .replace(/^-+|-+$/g, "")
1148
- .slice(0, 80);
1149
- }
1150
-
1151
- const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
1152
1632
 
1153
- /** Whether `p` is an address a page can be given: plain segments, no template, not too long. */
1154
- export function validAddress(p) {
1155
- const at = normalisePath(p);
1156
- if (at.length > 200) return false;
1157
- if (at === "/") return true;
1158
- return at
1159
- .slice(1)
1160
- .split("/")
1161
- .every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
1162
- }
1163
1633
 
1164
1634
  const under = (path, at) => (at === "/" ? path !== "/" : path.startsWith(`${at}/`));
1165
1635
  const within = (path, at) => path === at || under(path, at);
@@ -1175,20 +1645,27 @@ export function siteRedirects({ framework, text }) {
1175
1645
  const v = JSON.parse(text("vercel.json") ?? "null");
1176
1646
  for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
1177
1647
  } catch {}
1178
- for (const c of CONFIGS[String(framework)] ?? []) {
1179
- const src = stripComments(text(c) ?? "");
1180
- if (framework === "astro") {
1181
- const at = src.search(/\bredirects\s*:\s*\{/);
1182
- if (at < 0) continue;
1183
- const body = braced(src, src.indexOf("{", at)) ?? "";
1184
- for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
1185
- } else if (framework === "next") {
1186
- for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
1187
- }
1648
+ const adapter = adapterOf(framework);
1649
+ for (const c of adapter?.configs ?? []) {
1650
+ if (!adapter.configSources) continue;
1651
+ for (const source of adapter.configSources(stripComments(text(c) ?? ""))) out.add(normalisePath(source));
1188
1652
  }
1189
1653
  return out;
1190
1654
  }
1191
1655
 
1656
+ /** The redirect sources an Astro config's `redirects` literal sets. */
1657
+ function astroConfigSources(src) {
1658
+ const at = src.search(/\bredirects\s*:\s*\{/);
1659
+ if (at < 0) return [];
1660
+ const body = braced(src, src.indexOf("{", at)) ?? "";
1661
+ return [...body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)].map((m) => m[1]);
1662
+ }
1663
+
1664
+ /** The redirect sources a Next.js config's literal `source`s set. */
1665
+ function nextConfigSources(src) {
1666
+ return [...src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)].map((m) => m[1]);
1667
+ }
1668
+
1192
1669
  /** Whether a redirect source (a page file's or the site's) takes `path`. */
1193
1670
  function sends(source, path) {
1194
1671
  if (REST.test(source)) {
@@ -1198,11 +1675,6 @@ function sends(source, path) {
1198
1675
  return source === path || matchesPattern(source, path);
1199
1676
  }
1200
1677
 
1201
- function matchesPattern(source, path) {
1202
- if (!/\[|:/.test(source)) return false;
1203
- const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => (i % 2 ? (part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+") : escape(part))).join("")}$`);
1204
- return re.test(path);
1205
- }
1206
1678
 
1207
1679
  // ── Writing the page file ──
1208
1680
 
@@ -1211,6 +1683,7 @@ function matchesPattern(source, path) {
1211
1683
  * were). Null when there is nothing to write: no file before and nothing in it after.
1212
1684
  */
1213
1685
  function changedPageFile(before, change) {
1686
+ /** @type {Record<string, any>} */
1214
1687
  let data = {};
1215
1688
  try {
1216
1689
  data = before == null ? {} : (JSON.parse(before) ?? {});
@@ -1220,11 +1693,15 @@ function changedPageFile(before, change) {
1220
1693
  if (!isObject(data)) data = {};
1221
1694
  if (!isObject(data.pages)) data.pages = {};
1222
1695
  const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
1223
- change(data.pages, redirects);
1696
+ const folders = isObject(data.folders) ? { ...data.folders } : {};
1697
+ change(data.pages, redirects, folders);
1224
1698
  for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
1699
+ for (const [k, v] of Object.entries(folders)) if (!isObject(v) || !v.name) delete folders[k];
1700
+ if (Object.keys(folders).length) data.folders = folders;
1701
+ else delete data.folders;
1225
1702
  if (Object.keys(redirects).length) data.redirects = redirects;
1226
1703
  else delete data.redirects;
1227
- const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
1704
+ const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
1228
1705
  if (before == null && empty) return null;
1229
1706
  const after = `${JSON.stringify(data, null, 2)}\n`;
1230
1707
  return after === before ? null : after;
@@ -1299,8 +1776,56 @@ function respecified(src, was, now, moves, have) {
1299
1776
  const QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
1300
1777
  const MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
1301
1778
 
1302
- /** `src` with every address in `from` (or under it) moved to `to`; anchors, queries and a trailing slash kept. */
1303
- function relinked(src, from, to, markdown) {
1779
+ /**
1780
+ * Where `src` (the text of `file`) shows code rather than links: in Markdown and MDX its fenced
1781
+ * blocks and inline code; in HTML, Astro and MDX its `<pre>` and `<code>` elements. An address in
1782
+ * there is an example in a text (AstroWind's `getPermalink('/about')` in a blog post), not a link.
1783
+ * @returns {[number, number][]}
1784
+ */
1785
+ function codeRanges(src, file) {
1786
+ /** @type {[number, number][]} */
1787
+ const out = [];
1788
+ if (/\.mdx?$/.test(file)) {
1789
+ let at = 0;
1790
+ let open = null;
1791
+ let start = 0;
1792
+ for (const line of src.split("\n")) {
1793
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
1794
+ if (!open && fence) {
1795
+ open = fence[1];
1796
+ start = at;
1797
+ } else if (open && fence && fence[1][0] === open[0] && fence[1].length >= open.length && !line.slice(fence[0].length).trim()) {
1798
+ out.push([start, at + line.length]);
1799
+ open = null;
1800
+ }
1801
+ at += line.length + 1;
1802
+ }
1803
+ if (open) out.push([start, src.length]);
1804
+ for (const m of blankRanges(src, out).matchAll(/(`+)(?!`)(.+?)(?<!`)\1(?!`)/g)) out.push([m.index, m.index + m[0].length]);
1805
+ }
1806
+ if (/\.(html?|astro|mdx)$/.test(file)) for (const m of src.matchAll(/<(pre|code)\b[\s\S]*?<\/\1\s*>/gi)) out.push([m.index, m.index + m[0].length]);
1807
+ return out.sort((a, b) => a[0] - b[0]);
1808
+ }
1809
+
1810
+ /** `src` with `change` applied to its text outside `ranges` only (each [start, end), in order). */
1811
+ function outside(src, ranges, change) {
1812
+ if (!ranges.length) return change(src);
1813
+ let out = "";
1814
+ let at = 0;
1815
+ for (const [start, end] of ranges) {
1816
+ if (end <= at) continue;
1817
+ out += change(src.slice(at, Math.max(at, start))) + src.slice(Math.max(at, start), end);
1818
+ at = end;
1819
+ }
1820
+ return out + change(src.slice(at));
1821
+ }
1822
+
1823
+ /**
1824
+ * `src`, the text of `file`, with every address in `from` (or under it) moved to `to`; anchors,
1825
+ * queries and a trailing slash kept. Code samples in it stay as they are (`codeRanges`).
1826
+ */
1827
+ function relinked(src, from, to, file) {
1828
+ const markdown = /\.mdx?$/.test(file);
1304
1829
  const swap = (address) => {
1305
1830
  const bare = address.replace(/[#?][\s\S]*$/, "");
1306
1831
  const tail = address.slice(bare.length);
@@ -1310,11 +1835,16 @@ function relinked(src, from, to, markdown) {
1310
1835
  if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
1311
1836
  return address;
1312
1837
  };
1313
- let out = src.replace(QUOTED, (m, q, address) => `${q}${swap(address)}`);
1314
- if (markdown) out = out.replace(MD_LINK, (m, a, address, b) => `${a}${swap(address)}${b}`);
1315
- return out;
1838
+ return outside(src, codeRanges(src, file), (piece) => {
1839
+ let out = piece.replace(QUOTED, (m, q, address) => `${q}${swap(address)}`);
1840
+ if (markdown) out = out.replace(MD_LINK, (m, a, address, b) => `${a}${swap(address)}${b}`);
1841
+ return out;
1842
+ });
1316
1843
  }
1317
1844
 
1845
+ /** The files whose links follow a move, as the site's adapter says: by default the app's code and content, not its content config. */
1846
+ const linkFileOf = (adapter) => adapter?.links ?? ((p) => APP_SOURCE.test(p) && !CONTENT_CONFIG.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
1847
+
1318
1848
  /** `src` with the inside of its string literals blanked, offsets kept: names in code, not in text. */
1319
1849
  function blankStrings(src) {
1320
1850
  let out = "";
@@ -1362,6 +1892,137 @@ function destination(page, to, discovered) {
1362
1892
  return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
1363
1893
  }
1364
1894
 
1895
+ /**
1896
+ * A site of HTML files: where a page at `to` has its file. An address that ends in `.html` is that
1897
+ * file (`/voorwaarden.html`); any other is a folder's index (`/shop` → `shop/index.html`), as the site
1898
+ * is served. A folder's index moves with its folder (its pages and files under it); a folder with
1899
+ * pages under it never becomes one file. Null when it cannot.
1900
+ */
1901
+ function htmlDestination(page, to) {
1902
+ const folder = /(^|\/)index\.html?$/.test(page.file);
1903
+ const dir = folder ? dirname(page.file) : page.file;
1904
+ if (to.endsWith(".html") || to.endsWith(".htm")) {
1905
+ if (folder) return null;
1906
+ return { file: to.slice(1), dir, newDir: to.slice(1), folder: false };
1907
+ }
1908
+ return { file: `${to.slice(1)}/index.html`, dir, newDir: to.slice(1), folder };
1909
+ }
1910
+
1911
+ /** A URL attribute in HTML, with the URL it holds. */
1912
+ const URL_ATTRIBUTE = /(\s(?:href|src|action|poster)\s*=\s*)(["'])([^"']*)\2/gi;
1913
+
1914
+ /** A URL relative to the page it is on (`about.html`, `../`, `img/a.png`): no scheme, no root, no anchor or query alone, no template. */
1915
+ const relativeUrl = (url) => !!url && !/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?|\{|\$)/i.test(url);
1916
+
1917
+ /** A relative URL's path from the folder `dir` (no leading slash), `..` and `.` resolved; "" is the site's root. */
1918
+ function resolvedUrl(dir, url) {
1919
+ const segments = dir ? dir.split("/") : [];
1920
+ for (const s of url.split("/")) {
1921
+ if (s === "..") segments.pop();
1922
+ else if (s && s !== ".") segments.push(s);
1923
+ }
1924
+ return segments.join("/");
1925
+ }
1926
+
1927
+ /**
1928
+ * The page address a site of HTML files serves a resolved URL path at, or null when it is a file
1929
+ * of another kind (a stylesheet, a picture): `x.html` is `/x.html`, `x/` and `x/index.html` are `/x`.
1930
+ */
1931
+ function servedAddress(path, slash) {
1932
+ if (path === "" || path === "index.html" || path === "index.htm") return "/";
1933
+ if (/\/index\.html?$/.test(path)) return `/${path.replace(/\/index\.html?$/, "")}`;
1934
+ if (slash || /\.html?$/.test(path) || !/\.[a-z0-9]+$/i.test(path.split("/").pop() ?? "")) return `/${path}`;
1935
+ return null;
1936
+ }
1937
+
1938
+ /** The relative URL from the folder `dir` to `target` (a path; ending in `/` for a folder, "" the root). */
1939
+ function relativeTo(dir, target) {
1940
+ const from = dir ? dir.split("/") : [];
1941
+ const folder = target === "" || target.endsWith("/");
1942
+ const parts = target.replace(/\/$/, "").split("/").filter(Boolean);
1943
+ const tdir = folder ? parts : parts.slice(0, -1);
1944
+ const base = folder ? "" : (parts.at(-1) ?? "");
1945
+ let i = 0;
1946
+ while (i < from.length && i < tdir.length && from[i] === tdir[i]) i++;
1947
+ const rest = tdir.slice(i);
1948
+ const out = `${"../".repeat(from.length - i)}${rest.length ? `${rest.join("/")}/` : ""}${base}`;
1949
+ return out || "./";
1950
+ }
1951
+
1952
+ /**
1953
+ * An HTML file's `src`, which was at `was` and is now at `now`, with its relative URLs pointed again:
1954
+ * a page `change` moved (`{ from, to }`, or anything under it) is linked at its new address in the
1955
+ * same form (a file, a folder, a folder's `index.html`), a file that moved (`moved`: old path → new
1956
+ * path) at its new path, and every other relative URL from the file's new folder. Unchanged URLs keep
1957
+ * their text.
1958
+ */
1959
+ function htmlRelinked(src, was, now, change, moved) {
1960
+ return src.replace(URL_ATTRIBUTE, (m, lead, q, url) => {
1961
+ if (!relativeUrl(url)) return m;
1962
+ const bare = url.replace(/[#?][\s\S]*$/, "");
1963
+ if (!bare) return m;
1964
+ const tail = url.slice(bare.length);
1965
+ const slash = bare.endsWith("/");
1966
+ const path = resolvedUrl(dirname(was), bare);
1967
+ let target = null;
1968
+ const address = servedAddress(path, slash);
1969
+ if (change && address !== null && (address === change.from || under(address, change.from))) {
1970
+ const next = moveAddress(address, change.from, change.to);
1971
+ const index = /(^|\/)index\.html?$/.test(path);
1972
+ if (next.endsWith(".html") || next.endsWith(".htm")) target = next.slice(1);
1973
+ else if (index) target = next === "/" ? "index.html" : `${next.slice(1)}/index.html`;
1974
+ else target = next === "/" ? "" : `${next.slice(1)}/`;
1975
+ if (!slash && !index && !target.endsWith("/") && !/\.html?$/.test(target)) target = target.replace(/\/$/, "");
1976
+ } else if (moved?.has(path)) target = moved.get(path);
1977
+ else if (was === now) return m;
1978
+ else target = slash && path ? `${path}/` : path;
1979
+ const next = relativeTo(dirname(now), target);
1980
+ return next === bare ? m : `${lead}${q}${next}${tail}${q}`;
1981
+ });
1982
+ }
1983
+
1984
+ /**
1985
+ * New page's starter on a site of HTML files: its own page's shell (the home page's, else its first
1986
+ * page's): its head with the name as title and no description of another page, its header and
1987
+ * footer and scripts kept, and a `<main>` with the name as its heading in place of the content. At
1988
+ * `/x.html` a file, at any other address a folder's `index.html`; its relative URLs from there.
1989
+ */
1990
+ function htmlStarter({ discovered, text, target, name, segments, files, fileTaken, no }) {
1991
+ const shellPage = discovered.pages.find((p) => p.path === "/") ?? discovered.pages.find((p) => p.file);
1992
+ const shell = shellPage ? text(shellPage.file) : null;
1993
+ if (!shell) return no("unparsed");
1994
+ const file = /\.html?$/.test(target) ? target.slice(1) : `${segments}/index.html`;
1995
+ if (fileTaken(file)) return no("taken", file);
1996
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1997
+ const h1 = mostClass(discovered.pages.map((p) => text(p.file) ?? ""), "h1", "class");
1998
+ const heading = `<h1${h1 ? ` class="${esc(h1)}"` : ""}>${esc(name)}</h1>`;
1999
+ let out = shell;
2000
+ out = /<title\b[^>]*>[\s\S]*?<\/title>/i.test(out) ? out.replace(/(<title\b[^>]*>)[\s\S]*?(<\/title>)/i, `$1${esc(name)}$2`) : out.replace(/(\s*)<\/head>/i, `$1 <title>${esc(name)}</title>$1</head>`);
2001
+ out = out.replace(/[ \t]*<meta\s[^>]*name\s*=\s*["']description["'][^>]*>[ \t]*\r?\n?/i, "");
2002
+ const indentAt = (i) => out.slice(out.lastIndexOf("\n", i - 1) + 1, i).match(/^[ \t]*/)?.[0] ?? "";
2003
+ const main = /(<main\b[^>]*>)([\s\S]*?)(<\/main>)/i.exec(out);
2004
+ if (main) {
2005
+ const indent = indentAt(main.index);
2006
+ out = `${out.slice(0, main.index)}${main[1]}\n${indent} ${heading}\n${indent}${main[3]}${out.slice(main.index + main[0].length)}`;
2007
+ } else {
2008
+ const body = /(<body\b[^>]*>)([\s\S]*?)(<\/body>)/i.exec(out);
2009
+ if (!body) return no("unparsed");
2010
+ const inner = body[2];
2011
+ const header = /<header\b[\s\S]*?<\/header>/i.exec(inner);
2012
+ const footer = /<footer\b[\s\S]*?<\/footer>/i.exec(inner);
2013
+ const indent = inner.match(/\n([ \t]*)\S/)?.[1] ?? " ";
2014
+ // What stands between its header and its footer (all of the body where it has neither) gives way; its scripts stay.
2015
+ const start = header ? header.index + header[0].length : 0;
2016
+ const end = footer ? footer.index : inner.length;
2017
+ const scripts = [...inner.slice(start, end).matchAll(/<script\b[\s\S]*?<\/script>/gi)].map((m) => m[0]);
2018
+ const block = ["<main>", ` ${heading}`, "</main>", ...scripts].map((l) => `${indent}${l}`).join("\n");
2019
+ const head = header ? inner.slice(0, start) : "";
2020
+ const tail = footer ? `\n${indent}${inner.slice(end)}` : (inner.match(/\s*$/)?.[0] ?? "\n");
2021
+ out = `${out.slice(0, body.index)}${body[1]}${head}\n${block}${tail}${body[3]}${out.slice(body.index + body[0].length)}`;
2022
+ }
2023
+ files.push({ path: file, content: htmlRelinked(out, shellPage.file, file, null, null) });
2024
+ }
2025
+
1365
2026
  /** Next.js app router files beside a page that are its own, not a route of their own: everything in its folder but the folders of other routes. */
1366
2027
  function appSegmentOwn(dir, paths) {
1367
2028
  return paths.filter((p) => {
@@ -1381,8 +2042,19 @@ const componentName = (address) =>
1381
2042
  .join("")
1382
2043
  .replace(/^(\d)/, "Page$1") || "Page";
1383
2044
 
1384
- /** The route element's `path` attribute's value and where it sits in `src`, or null. */
2045
+ /** The route's `path` (a route element's attribute, a route object's own entry) and where its value sits in `src`, or null. */
1385
2046
  function routePathAttr(src, router) {
2047
+ if (router.object) {
2048
+ // Its own entry only, at its top level: a child's `path` is the child's.
2049
+ const clean = stripComments(src);
2050
+ const entry = objectEntries(clean, router.start).find((e) => e.key === "path");
2051
+ if (!entry) return null;
2052
+ const raw = src.slice(entry.valueStart, entry.valueEnd);
2053
+ const value = literalString(raw);
2054
+ if (value === false) return null;
2055
+ const start = entry.valueStart + 1;
2056
+ return { value, start, end: start + value.length };
2057
+ }
1386
2058
  const tag = src.slice(router.start, router.end);
1387
2059
  const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
1388
2060
  if (!m) return null;
@@ -1391,18 +2063,52 @@ function routePathAttr(src, router) {
1391
2063
  return { value, start: valueAt, end: valueAt + value.length };
1392
2064
  }
1393
2065
 
2066
+ /**
2067
+ * A router file's `src` with a copy of `router`'s route right after it: its path's value `value`, its
2068
+ * component `name` from `file`, whose import goes beside the original's (`original`) in the same
2069
+ * form. A route object comes after the original with a comma between them; one whose own
2070
+ * `lazy: () => import(…)` loads its page points at `file` instead of a new import.
2071
+ * @returns {{ ok: true, code: string } | PageRefusal}
2072
+ */
2073
+ function routeCopy({ src, router, routerFile, attr, value, name, file, original }) {
2074
+ let tag = src.slice(router.start, attr.start) + value + src.slice(attr.end, router.end);
2075
+ let statement = null;
2076
+ let added = null;
2077
+ if (router.importKind === "inline") {
2078
+ tag = tag.replace(/(import\(\s*)(["'])([^"']+)\2/, (m, lead, q, spec) => `${lead}${q}${specFor(routerFile, file, spec, original)}${q}`);
2079
+ } else {
2080
+ const comp = router.component;
2081
+ statement =
2082
+ router.importKind === "lazy"
2083
+ ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
2084
+ : src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
2085
+ if (!statement) return { ok: false, reason: "unparsed", detail: "its import" };
2086
+ added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(routerFile, file, spec, original)}${q}`);
2087
+ tag = tag.replace(new RegExp(`(<|\\{\\s*|Component\\s*:\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
2088
+ }
2089
+ const indent = src.slice(src.lastIndexOf("\n", router.start) + 1, router.start).match(/^\s*/)?.[0] ?? "";
2090
+ let out = `${src.slice(0, router.end)}${router.object ? "," : ""}\n${indent}${tag}${src.slice(router.end)}`;
2091
+ if (statement) {
2092
+ const lineEnd = statement.index + statement[0].length;
2093
+ out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
2094
+ }
2095
+ return { ok: true, code: out };
2096
+ }
2097
+
1394
2098
  // ── The plan ──
1395
2099
 
1396
2100
  /**
1397
2101
  * @typedef {{ path: string, content?: string, from?: string, deleted?: true }} PageWrite
1398
2102
  * `content`: the file's new text; `from`: the file whose bytes it gets (a move or copy keeps
1399
2103
  * them as they are, whatever kind of file); `deleted`: it goes.
1400
- * @typedef {{ ok: true, action: string, path: string, to: string | null, files: PageWrite[], redirects: Record<string, string | null>, links: string[], unlinked: string[], moves: { from: string, to: string }[], renamed: { from: string, to: string }[], message: string }} PagePlan
2104
+ * @typedef {{ ok: true, action: string, path: string, to: string | null, files: PageWrite[], redirects: Record<string, string | null>, links: string[], unlinked: string[], moves: { from: string, to: string }[], renamed: { from: string, to: string }[], message: string, folder?: boolean }} PagePlan
2105
+ * @typedef {{ ok: true } | { ok: false, reason: string, detail?: string }} Capability
1401
2106
  * @typedef {{ ok: false, reason: string, detail?: string }} PageRefusal
1402
2107
  */
1403
2108
 
1404
2109
  /**
1405
- * What one action does to a site's code, or why it cannot: `rename` (to a new address, with a new
2110
+ * What one action does to a site's code, or why it cannot: `create` (a new page by rule, planCreate),
2111
+ * `rename` (to a new address, with a new
1406
2112
  * name), `duplicate` (a copy at `to`, by default the first free `<address>-copy`) or `delete`
1407
2113
  * (visitors to the old address sent to `redirect`, by default the page above it; null: Not
1408
2114
  * Found). `live` says whether the page is on Live now: only then does a rename or delete leave a
@@ -1410,25 +2116,37 @@ function routePathAttr(src, router) {
1410
2116
  *
1411
2117
  * `paths` are every file of the app (a move takes files whose text was not read along);
1412
2118
  * `text` gives the code and content files' text.
1413
- * @param {{ action: "rename" | "duplicate" | "delete", path: string, to?: string, name?: string | null, redirect?: string | null, live?: boolean, drafts?: boolean }} request
1414
- * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>> }} input
2119
+ *
2120
+ * `details` are the templates a CMS gives each of its items an address with (the collection's
2121
+ * detail page: docs/plan-cms-detail-page.md, decision 8), by address, each with the files that
2122
+ * stay whatever reads them (`keep`: the CMS's items). Such a template can be deleted, nothing else:
2123
+ * its file goes, and the content only it reads, never an item. `addresses` are its pages on Live
2124
+ * then (one per item), each sent on as a deleted page's own address is.
2125
+ * @param {{ action: "rename" | "duplicate" | "delete" | "create", path: string, to?: string, name?: string | null, redirect?: string | null, live?: boolean, drafts?: boolean, addresses?: string[] }} request
2126
+ * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>>, details?: Record<string, { keep?: string[] }> }} input
1415
2127
  * @returns {PagePlan | PageRefusal}
1416
2128
  */
1417
2129
  export function planPage(request, input) {
1418
2130
  const { framework, text } = input;
2131
+ const adapter = adapterOf(framework);
1419
2132
  const paths = input.paths.filter((p) => !SKIP.test(p));
1420
2133
  const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
1421
2134
  const action = request.action;
1422
- if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
1423
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
2135
+ if (!["rename", "duplicate", "delete", "create"].includes(action)) return no("invalid", action);
2136
+ if (!adapter?.acts) return no("framework");
1424
2137
  const at = normalisePath(request.path);
1425
2138
  const discovered = input.found ?? discover({ framework, paths, text });
2139
+ if (action === "create") return planCreate(request, { framework, paths, text, discovered });
1426
2140
  const page = discovered.pages.find((p) => p.path === at);
2141
+ // A folder: an address with pages under it and none of its own (docs/plan-folders-and-redirects.md).
2142
+ if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
1427
2143
  if (!page) {
1428
2144
  const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
1429
2145
  return template ? no("template", template.path) : no("missing");
1430
2146
  }
1431
- if (page.kind === "template") return no("template", page.path);
2147
+ // A CMS collection's detail page: Delete only, in a file router (`details`).
2148
+ const detail = page.kind === "template" && action === "delete" && !adapter?.routeLines ? (input.details?.[at] ?? null) : null;
2149
+ if (page.kind === "template" && !detail) return no("template", page.path);
1432
2150
  if (!page.file || page.reason === "unparsed") return no("unparsed");
1433
2151
  const pageFile = parsePageFile(text(PAGE_FILE));
1434
2152
  if (!pageFile.ok) return no("invalid", pageFile.error);
@@ -1453,7 +2171,7 @@ export function planPage(request, input) {
1453
2171
  const redirectChanges = {};
1454
2172
  const collections = (() => {
1455
2173
  try {
1456
- return JSON.parse(text(COLLECTIONS) ?? "null");
2174
+ return readCollections(text);
1457
2175
  } catch {
1458
2176
  return null;
1459
2177
  }
@@ -1466,12 +2184,13 @@ export function planPage(request, input) {
1466
2184
  if (!validAddress(target) || target === "/") return no("address", target);
1467
2185
  if (target !== at && within(target, at)) return no("address", target);
1468
2186
  if (target !== at && taken(target)) return no("taken", target);
1469
- if (target !== at && live && !redirects) return no("no_redirects");
2187
+ // Route objects: the published Vite plugin adds redirect routes to a JSX `<Routes>` only (PE5 teaches it objects).
2188
+ if (target !== at && live && (!redirects || page.router?.object)) return no("no_redirects", page.router?.object ? "route objects" : undefined);
1470
2189
  to = target;
1471
2190
  /** @type {Map<string, string>} old path → new path, of the files that move */
1472
2191
  const moved = new Map();
1473
2192
  if (target !== at) {
1474
- if (framework === "vite-react") {
2193
+ if (adapter?.routeLines) {
1475
2194
  // The route's own path, when it is relative to a parent route: its last part only.
1476
2195
  const src = text(page.router.file) ?? "";
1477
2196
  const attr = routePathAttr(src, page.router);
@@ -1483,7 +2202,7 @@ export function planPage(request, input) {
1483
2202
  write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
1484
2203
  }
1485
2204
  } else {
1486
- const dest = destination(page, target, discovered);
2205
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1487
2206
  if (!dest) return no("unparsed");
1488
2207
  // Its file, and everything in its folder: the pages under it, and what they keep there.
1489
2208
  for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
@@ -1504,14 +2223,17 @@ export function planPage(request, input) {
1504
2223
  if (out !== src) write({ path: p, content: out });
1505
2224
  }
1506
2225
  }
1507
- // Every link to it, or under it, in code and content (route files' own `pad` too).
2226
+ // Every link to it, or under it, in code and content (route files' own `pad` too); not the
2227
+ // content config, which defines schemas (an address there is an example in a message).
2228
+ const linkFile = linkFileOf(adapter);
1508
2229
  for (const p of paths) {
1509
- // Not the content config: it defines schemas, and an address there is an example in a message.
1510
- if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2230
+ if (!linkFile(p)) continue;
1511
2231
  const where = moved.get(p) ?? p;
1512
2232
  const src = current(where);
1513
2233
  if (!src) continue;
1514
- const out = relinked(src, at, target, /\.mdx?$/.test(p));
2234
+ let out = relinked(src, at, target, p);
2235
+ // A site of HTML files links by relative URLs too: those follow, and a moved file's own are pointed again.
2236
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at, to: target }, moved);
1515
2237
  if (out === src) continue;
1516
2238
  write({ path: where, content: out });
1517
2239
  if (!moved.has(p)) links.add(where);
@@ -1546,7 +2268,7 @@ export function planPage(request, input) {
1546
2268
  }
1547
2269
 
1548
2270
  if (action === "duplicate") {
1549
- if (framework === "vite-react" && page.reason === "nested") return no("nested");
2271
+ if (adapter?.routeLines && page.reason === "nested") return no("nested");
1550
2272
  let target;
1551
2273
  if (request.to != null) {
1552
2274
  target = normalisePath(request.to);
@@ -1618,7 +2340,7 @@ export function planPage(request, input) {
1618
2340
  }
1619
2341
  return out;
1620
2342
  };
1621
- if (framework === "vite-react") {
2343
+ if (adapter?.routeLines) {
1622
2344
  const router = page.router.file;
1623
2345
  const src = current(router) ?? "";
1624
2346
  const attr = routePathAttr(src, page.router);
@@ -1629,31 +2351,20 @@ export function planPage(request, input) {
1629
2351
  const file = freeFile(dirname(page.file), name, ext);
1630
2352
  const original = text(page.file) ?? "";
1631
2353
  write({ path: file, content: rebind(respecified(original, page.file, file, new Map([[page.file, file]]), have)) });
1632
- // Its import, beside the original's, in the same form.
1633
- const comp = page.router.component;
1634
- const statement =
1635
- page.router.importKind === "lazy"
1636
- ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
1637
- : src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
1638
- if (!statement) return no("unparsed", "its import");
1639
- 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}`);
2354
+ // Its import, beside the original's, in the same form; a route object's own `lazy: () => import(…)` points at the copy instead.
1640
2355
  const value = attr.value.startsWith("/") ? target : (() => {
1641
2356
  const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
1642
2357
  return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1643
2358
  })();
1644
2359
  if (value === null) return no("unparsed", "a route inside another route keeps its parent");
1645
- const newTag = (src.slice(page.router.start, attr.start) + value + src.slice(attr.end, page.router.end)).replace(new RegExp(`(<|\\{\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
1646
- const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
1647
- const at1 = page.router.end;
1648
- let out = `${src.slice(0, at1)}\n${indent}${newTag}${src.slice(at1)}`;
1649
- const lineEnd = statement.index + statement[0].length;
1650
- out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
1651
- write({ path: router, content: out });
2360
+ const added = routeCopy({ src, router: page.router, routerFile: router, attr, value, name, file, original: page.file });
2361
+ if (!added.ok) return added;
2362
+ write({ path: router, content: added.code });
1652
2363
  } else {
1653
- const dest = destination(page, target, discovered);
2364
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1654
2365
  if (!dest) return no("unparsed");
1655
2366
  // A Next.js app router page brings what its folder keeps for it; Home's folder is the whole app's.
1656
- const along = framework === "next" && routesBase(page.file).endsWith("app") && at !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
2367
+ const along = adapter?.segments && routesBase(page.file).endsWith("app") && at !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1657
2368
  const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1658
2369
  for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1659
2370
  for (const [from, next] of moved) {
@@ -1664,6 +2375,7 @@ export function planPage(request, input) {
1664
2375
  }
1665
2376
  let out = respecified(src, from, next, moved, have);
1666
2377
  if (from === page.file) out = rebind(out);
2378
+ if (adapter?.relativeLinks && /\.html?$/.test(from)) out = htmlRelinked(out, from, next, null, moved);
1667
2379
  write(out === src ? { path: next, from } : { path: next, content: out });
1668
2380
  }
1669
2381
  }
@@ -1689,23 +2401,25 @@ export function planPage(request, input) {
1689
2401
  if (action === "delete") {
1690
2402
  if (at === "/") return no("home");
1691
2403
  if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
2404
+ // Its addresses that visitors know: its own, or a detail page's, one per item on Live.
2405
+ const gone = detail ? [...new Set((request.addresses ?? []).map(normalisePath))].filter((p) => templateMatches(at, p)).sort() : [at];
1692
2406
  let target = null;
1693
- if (live && request.redirect !== null) {
2407
+ if (live && gone.length && request.redirect !== null) {
1694
2408
  if (request.redirect !== undefined) {
1695
2409
  target = normalisePath(request.redirect);
1696
- if (within(target, at) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
2410
+ if (within(target, at) || gone.includes(target) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1697
2411
  } else {
1698
2412
  for (let p = parentOf(at); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
1699
2413
  target = target ?? "/";
1700
2414
  }
1701
- if (!redirects) return no("no_redirects");
2415
+ if (!redirects || page.router?.object) return no("no_redirects", page.router?.object ? "route objects" : undefined);
1702
2416
  }
1703
2417
  to = target;
1704
- if (framework === "vite-react") {
2418
+ if (adapter?.routeLines) {
1705
2419
  const router = page.router.file;
1706
2420
  const src = current(router) ?? "";
1707
- // Its route element, and its line when nothing else is on it.
1708
- let { start, end } = page.router;
2421
+ // Its route (an element, or an object with its comma), and its line when nothing else is on it.
2422
+ let { start, end } = routeSpan(src, page.router);
1709
2423
  const lineStart = src.lastIndexOf("\n", start - 1) + 1;
1710
2424
  const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
1711
2425
  if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
@@ -1714,32 +2428,45 @@ export function planPage(request, input) {
1714
2428
  }
1715
2429
  let out = src.slice(0, start) + src.slice(end);
1716
2430
  const comp = page.router.component;
1717
- // Its import goes when nothing else in the file names it.
1718
- const rest = blankStrings(stripComments(out));
1719
- const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
1720
- if (uses <= 1) {
1721
- const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
1722
- out = out.replace(re, "");
2431
+ if (page.router.importKind === "inline") {
2432
+ // Loaded by its route object alone: its file goes when nothing else imports it.
1723
2433
  if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
2434
+ } else {
2435
+ // Its import goes when nothing else in the file names it.
2436
+ const rest = blankStrings(stripComments(out));
2437
+ const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
2438
+ if (uses <= 1) {
2439
+ const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
2440
+ out = out.replace(re, "");
2441
+ if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
2442
+ }
1724
2443
  }
1725
2444
  write({ path: router, content: out });
1726
2445
  } else {
1727
2446
  const dir = dirname(page.file);
1728
- const files = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
2447
+ const files = adapter?.segments && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
1729
2448
  for (const f of files) write({ path: f, deleted: true });
1730
2449
  }
2450
+ // A detail page's items are the CMS's: they stay, whatever reads them now (`keep`).
2451
+ const keep = new Set(detail?.keep ?? []);
1731
2452
  const content = ownedContent(page, { paths, text, importers });
1732
- for (const f of content.files) {
2453
+ const owned = content.files.filter((f) => !keep.has(f));
2454
+ for (const f of owned) {
1733
2455
  write({ path: f, deleted: true });
1734
2456
  if (collectionsAfter) delete collectionsAfter[f];
1735
2457
  }
1736
- for (const f of linksTo(at, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
2458
+ for (const f of linksTo(at, { paths, text, own: [page.file, ...owned], framework })) unlinked.add(f);
2459
+ /** A redirect's end that was this page: its address, or one of a detail page's. */
2460
+ const was = (d) => d === at || (!!detail && templateMatches(at, d));
1737
2461
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1738
- delete pages[at];
2462
+ for (const key of Object.keys(pages)) if (was(key)) delete pages[key];
1739
2463
  const before = { ...sendsOn };
1740
- if (target) sendsOn[at] = target;
1741
- if (target) repoint(sendsOn, at, target);
1742
- else for (const [s, d] of Object.entries(sendsOn)) if (d === at) delete sendsOn[s];
2464
+ if (target) {
2465
+ for (const p of gone) sendsOn[p] = target;
2466
+ for (const p of gone) repoint(sendsOn, p, target);
2467
+ // Those that led to an item no visitor has now lead where its visitors go.
2468
+ if (detail) for (const [s, d] of Object.entries(sendsOn)) if (was(d)) s === target ? delete sendsOn[s] : (sendsOn[s] = target);
2469
+ } else for (const [s, d] of Object.entries(sendsOn)) if (was(d)) delete sendsOn[s];
1743
2470
  for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1744
2471
  });
1745
2472
  if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
@@ -1747,7 +2474,9 @@ export function planPage(request, input) {
1747
2474
 
1748
2475
  if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
1749
2476
  const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1750
- write({ path: COLLECTIONS, content: `${JSON.stringify(sorted, null, 2)}\n` });
2477
+ const content = `${JSON.stringify(sorted, null, 2)}\n`;
2478
+ write({ path: COLLECTIONS, content });
2479
+ write({ path: LEGACY_COLLECTIONS, content });
1751
2480
  }
1752
2481
  const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1753
2482
  const message =
@@ -1755,13 +2484,544 @@ export function planPage(request, input) {
1755
2484
  return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
1756
2485
  }
1757
2486
 
2487
+ // ── New page (docs/plan-page-engine.md, PE3: New page without AI) ──
2488
+
2489
+ /** The class `tag` has most often in `sources` (`class=` in Astro, `className=` in JSX), kept by `keep`; null when none. */
2490
+ function mostClass(sources, tag, attr, keep = () => true) {
2491
+ const count = new Map();
2492
+ for (const src of sources) {
2493
+ for (const m of src.matchAll(new RegExp(`<${tag}\\b[^>]*\\s${attr}="([^"{]+)"`, "g"))) {
2494
+ const c = m[1].trim();
2495
+ if (c && keep(c)) count.set(c, (count.get(c) ?? 0) + 1);
2496
+ }
2497
+ }
2498
+ return [...count].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0]?.[0] ?? null;
2499
+ }
2500
+
2501
+ /** A page's width: the class that holds it (a container, max-w-…, mx-auto), not a band's colour. */
2502
+ const holdsWidth = (c) => /(^|\s)(container|wrap|wrapper|inner|max-w-\S+|mx-auto)(\s|$)/.test(c);
2503
+
2504
+ /** A JavaScript string literal for `s`: a name goes into code as data, never as code. */
2505
+ const literal = (s) => JSON.stringify(String(s));
2506
+
2507
+ /**
2508
+ * The routes a new React Router page can stand beside: parsed, self-closing, with a `path` of
2509
+ * their own, so a copy of the tag is a route of the same kind (its wrappers and its parent route).
2510
+ */
2511
+ function siblingRoutes(discovered, text) {
2512
+ return discovered.pages.filter((p) => {
2513
+ if (p.kind !== "route" || p.reason || !p.router || !p.file) return false;
2514
+ const attr = routePathAttr(text(p.router.file) ?? "", p.router);
2515
+ return !!attr && attr.value !== "*" && !attr.value.endsWith("/*");
2516
+ });
2517
+ }
2518
+
2519
+ /**
2520
+ * Whether New page can make a page here without the Operator, and if not why: a framework the
2521
+ * rule has no starter for (`framework`), a page file that is not valid (`invalid`), a React
2522
+ * Router site whose routes Unbase can't read (`routes_unread`: route objects, a path from a
2523
+ * constant), or a Next.js site without a pages folder Unbase knows (`unparsed`).
2524
+ * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null } }} input
2525
+ * @returns {Capability}
2526
+ */
2527
+ export function createCapability({ framework, paths, text, found }) {
2528
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
2529
+ const adapter = adapterOf(framework);
2530
+ if (!adapter?.acts) return no("framework");
2531
+ const pageFile = parsePageFile(text(PAGE_FILE));
2532
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2533
+ const kept = paths.filter((p) => !SKIP.test(p));
2534
+ const discovered = found ?? discover({ framework, paths: kept, text });
2535
+ return adapter.canCreate?.(discovered, kept, text) ?? { ok: true };
2536
+ }
2537
+
2538
+ /**
2539
+ * How a React Router page wraps itself, read from its source: a Layout component it renders, else the header and footer it
2540
+ * renders inside its outer element (Lovable's shape), each with its import line; nothing else.
2541
+ */
2542
+ function wrapOfPage(src) {
2543
+ const imports = [...src.matchAll(/^import\s+(?:([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?|\{([^}]*)\})\s+from\s+["']([^"']+)["'];?[^\n]*$/gm)].map((m) => ({
2544
+ line: m[0],
2545
+ names: [m[1], ...(m[2] ?? m[3] ?? "").split(",").map((x) => x.trim().split(/\s+as\s+/).pop())].filter(Boolean),
2546
+ }));
2547
+ const used = (n) => new RegExp(`<${escape(n)}[\\s/>]`).test(src);
2548
+ const names = imports.flatMap((i) => i.names);
2549
+ const lineOf = (n) => imports.find((i) => i.names.includes(n))?.line;
2550
+ const layout = names.find((n) => /Layout$/.test(n) && used(n)) ?? null;
2551
+ if (layout) return { key: `layout:${lineOf(layout)}`, layout, header: null, footer: null, outer: null, imports: [lineOf(layout)] };
2552
+ const header = names.find((n) => /^(Header|Navbar|NavBar|Nav|Navigation|SiteHeader)$/.test(n) && used(n)) ?? null;
2553
+ const footer = names.find((n) => /^(Footer|SiteFooter)$/.test(n) && used(n)) ?? null;
2554
+ if (!header && !footer) return { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2555
+ const outer = src.match(/return\s*\(\s*<([a-z][\w-]*)((?:\s+className="[^"]*")?)\s*>/);
2556
+ const imports2 = [...new Set([header, footer].filter(Boolean).map(lineOf))];
2557
+ const outerTag = outer ? `${outer[1]}${outer[2]}` : null;
2558
+ return { key: `chrome:${imports2.join("|")}:${outerTag}`, layout: null, header, footer, outer: outerTag, imports: imports2 };
2559
+ }
2560
+
2561
+ /** The wrapping most of `sources` share (a tie goes to one that wraps). */
2562
+ function wrapOfPages(sources) {
2563
+ const seen = new Map();
2564
+ for (const src of sources) {
2565
+ const w = wrapOfPage(src);
2566
+ const had = seen.get(w.key) ?? { n: 0, w };
2567
+ had.n++;
2568
+ seen.set(w.key, had);
2569
+ }
2570
+ const best = [...seen.values()].sort((a, b) => b.n - a.n || (a.w.key === "none" ? 1 : b.w.key === "none" ? -1 : 0))[0];
2571
+ return best?.w ?? { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2572
+ }
2573
+
2574
+ /**
2575
+ * New page's starter on Astro: a page in src/pages in the layout most of its pages import (a title
2576
+ * prop, or AstroWind's `metadata`), else a page of its own (planCreate). A refusal, or nothing when
2577
+ * its files are in `files`.
2578
+ */
2579
+ function astroStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2580
+ const own = discovered.pages.filter((p) => p.file && p.file.startsWith("src/pages/") && p.file.endsWith(".astro"));
2581
+ const sources = own.map((p) => text(p.file) ?? "");
2582
+ // The layout most of its pages import, by where it is, with how they name it.
2583
+ const layouts = new Map();
2584
+ own.forEach((p, i) => {
2585
+ for (const m of sources[i].matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']*layouts?\/[^"']+\.astro)["']/g)) {
2586
+ const spec = m[2];
2587
+ const abs = spec.startsWith(".") ? joinRelative(dirname(p.file), spec) : spec.replace(/^[@~]\//, "src/").replace(/^@layouts\//, "src/layouts/");
2588
+ const seen = layouts.get(abs) ?? { n: 0, local: m[1], alias: spec.startsWith(".") ? null : spec };
2589
+ seen.n++;
2590
+ layouts.set(abs, seen);
2591
+ }
2592
+ });
2593
+ const best = [...layouts].sort((a, b) => b[1].n - a[1].n || (a[0] < b[0] ? -1 : 1))[0];
2594
+ // A folder of that name with pages in it: the page is its index.
2595
+ const file = paths.some((p) => p.startsWith(`src/pages/${segments}/`)) ? `src/pages/${segments}/index.astro` : `src/pages/${segments}.astro`;
2596
+ if (fileTaken(file)) return no("taken", file);
2597
+ const h1 = mostClass(sources, "h1", "class");
2598
+ const box = mostClass(sources, "(?:main|section|div)", "class", holdsWidth);
2599
+ const heading = `<h1${h1 ? ` class=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2600
+ const body = [`<main${box ? ` class=${literal(box)}` : ""}>`, ` ${heading}`, "</main>"];
2601
+ let src;
2602
+ if (best) {
2603
+ const [abs, use] = best;
2604
+ const layoutSrc = text(abs) ?? "";
2605
+ const tag = /^[A-Z]/.test(use.local) ? use.local : "Layout";
2606
+ const spec = use.alias ?? relativeSpec(file, abs);
2607
+ // Its props as the layout names them: a title, or AstroWind's `metadata` object.
2608
+ const metadata = /\bmetadata\b/.test(layoutSrc) && !/\btitle\s*[?:]/.test(layoutSrc);
2609
+ const props = metadata ? " metadata={metadata}" : /\btitle\b/.test(layoutSrc) ? ` title={${literal(name)}}` : "";
2610
+ const front = [`import ${tag} from ${literal(spec)};`, ...(metadata ? [`const metadata = { title: ${literal(name)} };`] : [])];
2611
+ src = ["---", ...front, "---", "", `<${tag}${props}>`, ...body.map((l) => ` ${l}`), `</${tag}>`, ""].join("\n");
2612
+ } else {
2613
+ src = [
2614
+ "---",
2615
+ `const title = ${literal(name)};`,
2616
+ "---",
2617
+ "",
2618
+ `<html lang="en">`,
2619
+ " <head>",
2620
+ ` <meta charset="utf-8" />`,
2621
+ ` <meta name="viewport" content="width=device-width" />`,
2622
+ " <title>{title}</title>",
2623
+ " </head>",
2624
+ " <body>",
2625
+ ...body.map((l) => ` ${l}`),
2626
+ " </body>",
2627
+ "</html>",
2628
+ "",
2629
+ ].join("\n");
2630
+ }
2631
+ files.push({ path: file, content: src });
2632
+ }
2633
+
2634
+ /**
2635
+ * New page's starter on Next.js: a page in the app router whose metadata title is the name, so the
2636
+ * root layout wraps it; in the pages router where the site has only that (planCreate).
2637
+ */
2638
+ function nextStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2639
+ const own = discovered.pages.filter((p) => p.file && routesBase(p.file));
2640
+ const sources = own.map((p) => text(p.file) ?? "");
2641
+ const inApp = own.find((p) => routesBase(p.file).endsWith("app"));
2642
+ const inPages = own.find((p) => !routesBase(p.file).endsWith("app"));
2643
+ // The app router where the site has one (an app with only its root layout too), else the pages router.
2644
+ const appBase = inApp ? routesBase(inApp.file) : paths.some((p) => /^src\/app\/layout\./.test(p)) ? "src/app" : paths.some((p) => /^app\/layout\./.test(p)) ? "app" : null;
2645
+ const pagesBase = inPages ? routesBase(inPages.file) : null;
2646
+ const exts = own.map((p) => p.file.slice(p.file.lastIndexOf("."))).filter((e) => /^\.(tsx|jsx|js)$/.test(e));
2647
+ const ext = exts.includes(".tsx") || !exts.length ? ".tsx" : exts.includes(".jsx") ? ".jsx" : ".js";
2648
+ const typed = ext === ".tsx";
2649
+ const h1 = mostClass(sources, "h1", "className");
2650
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2651
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2652
+ if (appBase) {
2653
+ const file = `${appBase}/${segments}/page${ext}`;
2654
+ if (fileTaken(file)) return no("taken", file);
2655
+ const lines = [
2656
+ ...(typed ? [`import type { Metadata } from "next";`, ""] : []),
2657
+ `export const metadata${typed ? ": Metadata" : ""} = { title: ${literal(name)} };`,
2658
+ "",
2659
+ "export default function Page() {",
2660
+ " return (",
2661
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2662
+ ` ${heading}`,
2663
+ " </main>",
2664
+ " );",
2665
+ "}",
2666
+ "",
2667
+ ];
2668
+ files.push({ path: file, content: lines.join("\n") });
2669
+ } else if (pagesBase) {
2670
+ const file = paths.some((p) => p.startsWith(`${pagesBase}/${segments}/`)) ? `${pagesBase}/${segments}/index${ext}` : `${pagesBase}/${segments}${ext}`;
2671
+ if (fileTaken(file)) return no("taken", file);
2672
+ const lines = [
2673
+ `import Head from "next/head";`,
2674
+ "",
2675
+ "export default function Page() {",
2676
+ " return (",
2677
+ " <>",
2678
+ " <Head>",
2679
+ ` <title>{${literal(name)}}</title>`,
2680
+ " </Head>",
2681
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2682
+ ` ${heading}`,
2683
+ " </main>",
2684
+ " </>",
2685
+ " );",
2686
+ "}",
2687
+ "",
2688
+ ];
2689
+ files.push({ path: file, content: lines.join("\n") });
2690
+ } else return no("unparsed");
2691
+ }
2692
+
2693
+ /**
2694
+ * New page's starter on React Router: a component beside another page's, its import, and a
2695
+ * `<Route>` beside that page's route, wrapped as that page is (planCreate).
2696
+ */
2697
+ function reactRouterStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2698
+ // The route it stands beside: one under the same parent first, else one at the top, else any that can hold it.
2699
+ const siblings = siblingRoutes(discovered, text);
2700
+ const parent = parentOf(target);
2701
+ const placement = (p) => {
2702
+ const src = text(p.router.file) ?? "";
2703
+ const attr = routePathAttr(src, p.router);
2704
+ if (!attr) return null;
2705
+ if (attr.value.startsWith("/")) return { src, attr, value: target };
2706
+ const base = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
2707
+ if (base !== "/" && !under(target, base)) return null;
2708
+ return { src, attr, value: base === "/" ? target.slice(1) : target.slice(base.length + 1) };
2709
+ };
2710
+ const ranked = [...siblings.filter((p) => parentOf(p.path) === parent), ...siblings.filter((p) => parentOf(p.path) === "/"), ...siblings];
2711
+ const sibling = ranked.find((p) => placement(p));
2712
+ if (!sibling) return no("routes_unread");
2713
+ const { src, attr, value } = placement(sibling);
2714
+ const router = sibling.router.file;
2715
+ let comp = componentName(target);
2716
+ for (let n = 2; new RegExp(`(?<![\\w$])${comp}(?![\\w$])`).test(src) && n < 100; n++) comp = `${componentName(target)}${n}`;
2717
+ const ext = sibling.file.slice(sibling.file.lastIndexOf("."));
2718
+ let file = `${dirname(sibling.file)}/${comp}${ext}`;
2719
+ for (let n = 2; fileTaken(file) && n < 100; n++) file = `${dirname(sibling.file)}/${comp}${n}${ext}`;
2720
+ // Wrapped as most pages in its folder are: a Layout component, else their header and footer inside their own outer element.
2721
+ const wrap = wrapOfPages(siblings.filter((p) => dirname(p.file) === dirname(sibling.file)).map((p) => text(p.file) ?? ""));
2722
+ const sources = siblings.map((p) => text(p.file) ?? "");
2723
+ const h1 = mostClass(sources, "h1", "className");
2724
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2725
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2726
+ const main = (indent) => [`${indent}<main${box ? ` className=${literal(box)}` : ""}>`, `${indent} ${heading}`, `${indent}</main>`];
2727
+ let jsx;
2728
+ const wrapImports = wrap.imports;
2729
+ if (wrap.layout) jsx = [` <${wrap.layout}>`, ...main(" "), ` </${wrap.layout}>`];
2730
+ else if (wrap.header || wrap.footer) {
2731
+ const open = wrap.outer ? `<${wrap.outer}>` : "<>";
2732
+ const close = wrap.outer ? `</${wrap.outer.split(/\s/)[0]}>` : "</>";
2733
+ jsx = [` ${open}`, ...(wrap.header ? [` <${wrap.header} />`] : []), ...main(" "), ...(wrap.footer ? [` <${wrap.footer} />`] : []), ` ${close}`];
2734
+ } else jsx = main(" ");
2735
+ const page = [...wrapImports, ...(wrapImports.length ? [""] : []), `export default function ${comp}() {`, " return (", ...jsx, " );", "}", ""].join("\n");
2736
+ files.push({ path: file, content: page });
2737
+ // Its import beside the sibling's, in the same form, and its route beside the sibling's route.
2738
+ const added = routeCopy({ src, router: sibling.router, routerFile: router, attr, value, name: comp, file, original: sibling.file });
2739
+ if (!added.ok) return added;
2740
+ files.push({ path: router, content: added.code });
2741
+ }
2742
+
2743
+ /**
2744
+ * New page by rule (`create`): a blank page in the site's own layout, at `request.path`, with a
2745
+ * heading that is its name and nothing else.
2746
+ * - Astro: a page in src/pages in the layout most of its pages import (a title prop, or
2747
+ * AstroWind's `metadata`), else a page of its own.
2748
+ * - Next.js: a page in the app router whose metadata title is the name, so the root layout wraps
2749
+ * it; in the pages router where the site has only that.
2750
+ * - React Router: a component beside another page's, its import, and a `<Route>` beside that page's
2751
+ * route (so under the same parent route), wrapped as that page is: its Layout, or its header and
2752
+ * footer inside its outer element.
2753
+ * The address is checked (format, taken by a page or a redirect of the site's own); the name goes
2754
+ * into `unbase.pages.json`, with a draft flag where the site keeps drafts off Live (`drafts`).
2755
+ */
2756
+ function planCreate(request, { framework, paths, text, discovered }) {
2757
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
2758
+ const target = normalisePath(request.path);
2759
+ const name = String(request.name ?? "").trim().slice(0, 120) || componentName(target);
2760
+ if (target === "/" || !validAddress(target)) return no("address", target);
2761
+ const capability = createCapability({ framework, paths, text, found: discovered });
2762
+ if (!capability.ok) return capability;
2763
+ const pageFile = parsePageFile(text(PAGE_FILE));
2764
+ const ownRedirects = siteRedirects({ framework, text });
2765
+ if (discovered.pages.some((q) => q.path === target) || [...ownRedirects].some((s) => sends(s, target))) return no("taken", target);
2766
+ const have = new Set(paths);
2767
+ /** @type {PageWrite[]} */
2768
+ const files = [];
2769
+ const fileTaken = (f) => have.has(f) || files.some((w) => w.path === f);
2770
+ const segments = target.slice(1);
2771
+
2772
+ const refused = adapterOf(framework)?.starter?.({ discovered, text, paths, target, name, segments, files, fileTaken, no });
2773
+ if (refused) return refused;
2774
+
2775
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
2776
+ pages[target] = { ...(pages[target] ?? {}), ...(request.drafts ? { draft: true } : {}), name };
2777
+ });
2778
+ if (pageFileText !== null && pageFile.ok) files.push({ path: PAGE_FILE, content: pageFileText });
2779
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
2780
+ return { ok: true, action: "create", path: target, to: target, files, redirects: {}, links: [], unlinked: [], moves: [], renamed: [], message: `Unbase: new page ${target}` };
2781
+ }
2782
+
2783
+ // ── The operations (docs/plan-page-engine.md, PE3) ──
2784
+
2785
+ /**
2786
+ * One set of page operations for the editor, the Operator and the CLI. Names and URLs are apart
2787
+ * (Jens, 17-11): `rename` changes only what Unbase calls a page, `move` only its address (also into
2788
+ * another folder), and `create_page` makes the address from the name once, unless a slug is given.
2789
+ * Each structure operation is one `planPage` request (`requestOf`); `reorder`, `set_page` and
2790
+ * `set_site` are no commit of the code (the tree's order is the project's; titles and descriptions
2791
+ * are drafts where the site keeps them), so they are handled where they live.
2792
+ * @typedef {{ op: "create_page", parent?: string, name: string, slug?: string }
2793
+ * | { op: "rename", path: string, name: string | null }
2794
+ * | { op: "move", path: string, to: string }
2795
+ * | { op: "duplicate", path: string, to?: string, name?: string | null }
2796
+ * | { op: "delete", path: string, redirect?: string | null }
2797
+ * | { op: "rename_folder", path: string, name?: string | null, to?: string }
2798
+ * | { op: "reorder", parent: string, ids: string[] }
2799
+ * | { op: "set_page", path: string, title?: string, description?: string }
2800
+ * | { op: "set_site", title?: string, description?: string }} PageOperation
2801
+ */
2802
+ export const PAGE_OPERATIONS = ["create_page", "rename", "move", "duplicate", "delete", "rename_folder", "reorder", "set_page", "set_site"];
2803
+
2804
+ /** The address `create_page` gives a page: its slug (else its name's) under its parent folder. Null when neither makes one. */
2805
+ export function createdAddress(op) {
2806
+ const slug = slugOf(op?.slug ?? op?.name ?? "");
2807
+ if (!slug) return null;
2808
+ const parent = op.parent ? normalisePath(op.parent) : "/";
2809
+ return normalisePath(`${parent === "/" ? "" : parent}/${slug}`);
2810
+ }
2811
+
2812
+ /**
2813
+ * The `planPage` request a structure operation is; null for one that is no commit of the code
2814
+ * (`reorder`, `set_page`, `set_site`), or no operation at all.
2815
+ * @param {PageOperation} op
2816
+ */
2817
+ export function requestOf(op) {
2818
+ if (!op || typeof op !== "object") return null;
2819
+ switch (op.op) {
2820
+ case "create_page": {
2821
+ const path = createdAddress(op);
2822
+ return path ? { action: "create", path, name: op.name } : null;
2823
+ }
2824
+ case "rename":
2825
+ return { action: "rename", path: op.path, name: op.name };
2826
+ case "move":
2827
+ return { action: "rename", path: op.path, to: op.to };
2828
+ case "rename_folder":
2829
+ return { action: "rename", path: op.path, ...(op.to !== undefined ? { to: op.to } : {}), ...(op.name !== undefined ? { name: op.name } : {}) };
2830
+ case "duplicate":
2831
+ return { action: "duplicate", path: op.path, ...(op.to !== undefined ? { to: op.to } : {}), ...(op.name !== undefined ? { name: op.name } : {}) };
2832
+ case "delete":
2833
+ return { action: "delete", path: op.path, ...(op.redirect !== undefined ? { redirect: op.redirect } : {}) };
2834
+ default:
2835
+ return null;
2836
+ }
2837
+ }
2838
+
2839
+ // ── Folders ──
2840
+
2841
+ /**
2842
+ * The folders of a tree of pages: every address above a page that is no page itself ("/juridisch"
2843
+ * above "/juridisch/[slug]"), sorted. Home is never one.
2844
+ * @param {{ path: string }[]} pages
2845
+ */
2846
+ export function folderPaths(pages) {
2847
+ const own = new Set(pages.map((p) => p.path));
2848
+ const out = new Set();
2849
+ for (const p of pages) for (let up = parentOf(p.path); up && up !== "/"; up = parentOf(up)) if (!own.has(up)) out.add(up);
2850
+ return [...out].sort();
2851
+ }
2852
+
2853
+ /** A Next.js app router folder that is not a segment of the address: a route group `(x)` or a slot `@x`. */
2854
+ const unsegmented = (dir) => /^\(.*\)$|^@/.test(dir.slice(dir.lastIndexOf("/") + 1));
2855
+
2856
+ /**
2857
+ * Where a folder's files are, in the routers that are files: one folder per routes base (Astro's
2858
+ * src/pages, the pages router's pages, the app router's app, a route group there too). Null when a
2859
+ * page under it is not in a file router's folder of that name (React Router, or an odd layout).
2860
+ */
2861
+ function folderDirs(at, below) {
2862
+ const dirs = new Set();
2863
+ for (const p of below) {
2864
+ if (!p.file) return null;
2865
+ const base = routesBase(p.file);
2866
+ if (!base) return null;
2867
+ if (!base.endsWith("app")) {
2868
+ const dir = `${base}${at}`;
2869
+ if (!p.file.startsWith(`${dir}/`)) return null;
2870
+ dirs.add(dir);
2871
+ continue;
2872
+ }
2873
+ // app/(group)/juridisch/x/page.tsx: up from the page's folder, one real segment per part of the address under the folder.
2874
+ let d = dirname(p.file);
2875
+ let n = p.path.slice(at.length + 1).split("/").length;
2876
+ while (n > 0 && d.length > base.length) {
2877
+ if (!unsegmented(d)) n--;
2878
+ d = dirname(d);
2879
+ }
2880
+ while (unsegmented(d) && d.length > base.length) d = dirname(d);
2881
+ if (lastOf(d) !== lastOf(at)) return null;
2882
+ dirs.add(d);
2883
+ }
2884
+ return dirs.size ? [...dirs].sort() : null;
2885
+ }
2886
+
2887
+ /**
2888
+ * Renaming a folder: its name in the page file, its address (only its last part: a folder keeps its
2889
+ * place), and every page under it with it, in one plan. In the file routers its folder moves as a
2890
+ * whole, a template and the files its pages keep there too; in React Router each route under it.
2891
+ * Links to anything under it follow; a live folder leaves one redirect for everything under it,
2892
+ * `/old/[...path]` → `/new/[...path]`. `request.live`: any page under it is on Live now.
2893
+ * @returns {PagePlan | PageRefusal}
2894
+ */
2895
+ function planFolder(request, { framework, paths, text, discovered, importers: given }) {
2896
+ const adapter = adapterOf(framework);
2897
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
2898
+ const at = normalisePath(request.path);
2899
+ if (at === "/") return no("home");
2900
+ const pageFile = parsePageFile(text(PAGE_FILE));
2901
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2902
+ const target = request.to == null ? at : normalisePath(request.to);
2903
+ if (!validAddress(target) || target === "/") return no("address", target);
2904
+ if (target !== at && (within(target, at) || parentOf(target) !== parentOf(at))) return no("address", target);
2905
+ const below = discovered.pages.filter((p) => under(p.path, at));
2906
+ const ownRedirects = siteRedirects({ framework, text });
2907
+ if (target !== at && (discovered.pages.some((p) => within(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
2908
+ const live = request.live === true;
2909
+ if (target !== at && live && (!kitRedirects({ framework, text }) || below.some((p) => p.router?.object))) return no("no_redirects");
2910
+ const have = new Set(paths);
2911
+ /** @type {Map<string, PageWrite>} */
2912
+ const writes = new Map();
2913
+ const write = (w) => writes.set(w.path, w);
2914
+ const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
2915
+ const links = new Set();
2916
+ /** @type {Map<string, string>} old path → new path, of the files that move */
2917
+ const moved = new Map();
2918
+ /** @type {Record<string, string | null>} */
2919
+ const redirectChanges = {};
2920
+ if (target !== at) {
2921
+ if (adapter?.routeLines) {
2922
+ // Each route under it, its path's value rewritten; edits per router file from its end, so offsets hold.
2923
+ /** @type {Map<string, { start: number, end: number, value: string }[]>} */
2924
+ const edits = new Map();
2925
+ for (const p of below) {
2926
+ if (!p.router) return no("unparsed", p.path);
2927
+ const src = text(p.router.file) ?? "";
2928
+ const attr = routePathAttr(src, p.router);
2929
+ if (!attr) return no("unparsed", "index route");
2930
+ const next = moveAddress(p.path, at, target);
2931
+ let value;
2932
+ if (attr.value.startsWith("/")) value = `${next}${attr.value.endsWith("/") && next !== "/" ? "/" : ""}`;
2933
+ else {
2934
+ const parent = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
2935
+ // Inside a route that is under the folder itself: that one moves, this one keeps its value.
2936
+ if (under(parent, at)) continue;
2937
+ value = parent === "/" ? next.slice(1) : next.slice(parent.length + 1);
2938
+ }
2939
+ edits.set(p.router.file, [...(edits.get(p.router.file) ?? []), { start: attr.start, end: attr.end, value }]);
2940
+ }
2941
+ for (const [file, list] of edits) {
2942
+ let out = text(file) ?? "";
2943
+ for (const e of [...list].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.value + out.slice(e.end);
2944
+ write({ path: file, content: out });
2945
+ }
2946
+ } else {
2947
+ const dirs = (adapter?.folderDirs ?? folderDirs)(at, below);
2948
+ if (!dirs) return no("unparsed", at);
2949
+ for (const dir of dirs) {
2950
+ const newDir = dirname(dir) ? `${dirname(dir)}/${lastOf(target)}` : lastOf(target);
2951
+ for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
2952
+ }
2953
+ for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
2954
+ for (const [from, next] of moved) {
2955
+ const src = CODE.test(from) ? text(from) : null;
2956
+ const content = src == null ? null : respecified(src, from, next, moved, have);
2957
+ write(content == null || content === src ? { path: next, from } : { path: next, content });
2958
+ write({ path: from, deleted: true });
2959
+ }
2960
+ const importers = given ?? null;
2961
+ for (const p of paths) {
2962
+ if (moved.has(p) || !CODE.test(p)) continue;
2963
+ if (importers && ![...moved.keys()].some((m) => importers.get(m)?.has(p))) continue;
2964
+ const src = text(p);
2965
+ if (!src) continue;
2966
+ const out = respecified(src, p, p, moved, have);
2967
+ if (out !== src) write({ path: p, content: out });
2968
+ }
2969
+ }
2970
+ // Every link to anything under it, in code and content (and a site of HTML files' relative URLs).
2971
+ const linkFile = linkFileOf(adapter);
2972
+ for (const p of paths) {
2973
+ if (!linkFile(p)) continue;
2974
+ const where = moved.get(p) ?? p;
2975
+ const src = current(where);
2976
+ if (!src) continue;
2977
+ let out = relinked(src, at, target, p);
2978
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at, to: target }, moved);
2979
+ if (out === src) continue;
2980
+ write({ path: where, content: out });
2981
+ if (!moved.has(p)) links.add(where);
2982
+ }
2983
+ }
2984
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn, folders) => {
2985
+ if (target !== at) {
2986
+ for (const key of Object.keys(pages)) {
2987
+ if (!within(key, at)) continue;
2988
+ pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
2989
+ delete pages[key];
2990
+ }
2991
+ for (const key of Object.keys(folders)) {
2992
+ if (!within(key, at)) continue;
2993
+ folders[moveAddress(key, at, target)] = folders[key];
2994
+ delete folders[key];
2995
+ }
2996
+ const before = { ...sendsOn };
2997
+ if (live) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
2998
+ repoint(sendsOn, at, target);
2999
+ for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
3000
+ }
3001
+ if (request.name !== undefined) {
3002
+ const name = request.name ? String(request.name).trim().slice(0, 120) : "";
3003
+ if (name) folders[target] = { name };
3004
+ else delete folders[target];
3005
+ }
3006
+ });
3007
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
3008
+ if (!writes.size) return no("same");
3009
+ const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
3010
+ const moves = target === at ? [] : [{ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) }))];
3011
+ const renamed = [...moved].map(([from, to]) => ({ from, to }));
3012
+ const message = target === at ? `Unbase: rename ${at}` : `Unbase: move ${at} to ${target}`;
3013
+ return { ok: true, action: "rename", path: at, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
3014
+ }
3015
+
1758
3016
  /**
1759
3017
  * What can be done to each page of the code here, and why not (the menu's grey lines): per
1760
3018
  * address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
1761
3019
  * `live`: the addresses on Live now (a live page needs the kit's redirects to move); `redirects`:
1762
3020
  * whether this code's build applies them. Cheaper than a plan: no writes are worked out.
3021
+ * `details`: the templates that are a CMS collection's detail page (planPage): those can be deleted.
1763
3022
  */
1764
- export function pageActions({ framework, paths, text, live = new Set(), found, importers }) {
3023
+ export function pageActions({ framework, paths, text, live = new Set(), found, importers, details = {} }) {
3024
+ const adapter = adapterOf(framework);
1765
3025
  const kept = paths.filter((p) => !SKIP.test(p));
1766
3026
  const discovered = found ?? discover({ framework, paths: kept, text });
1767
3027
  const graph = importers ?? importGraph(kept, text);
@@ -1776,7 +3036,7 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
1776
3036
  if (page.path.includes(" ")) continue;
1777
3037
  const below = discovered.pages.filter((p) => under(p.path, page.path));
1778
3038
  const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
1779
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
3039
+ if (!adapter?.acts) {
1780
3040
  out[page.path] = all(no("framework"));
1781
3041
  continue;
1782
3042
  }
@@ -1785,7 +3045,11 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
1785
3045
  continue;
1786
3046
  }
1787
3047
  if (page.kind === "template") {
1788
- out[page.path] = all(no("template"));
3048
+ // A CMS collection's detail page: Delete, in a file router; its items stay the CMS's.
3049
+ const detail = !!details[page.path] && !adapter?.routeLines && !!page.file && page.reason !== "unparsed";
3050
+ out[page.path] = detail
3051
+ ? { rename: no("template"), duplicate: no("template"), delete: below.length ? no("nested", below.map((p) => p.path).join(", ")) : yes, under: below.length }
3052
+ : all(no("template"));
1789
3053
  continue;
1790
3054
  }
1791
3055
  if (!page.file || page.reason === "unparsed") {
@@ -1793,10 +3057,10 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
1793
3057
  continue;
1794
3058
  }
1795
3059
  const onLive = live.has(page.path);
1796
- let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
1797
- if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
3060
+ let rename = page.path === "/" ? no("home") : onLive && (!redirects || page.router?.object) ? no("no_redirects", page.router?.object ? "route objects" : undefined) : yes;
3061
+ if (rename.ok && adapter?.routeLines && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
1798
3062
  const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
1799
- let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
3063
+ let duplicate = adapter?.routeLines && page.reason === "nested" ? no("nested") : yes;
1800
3064
  if (duplicate.ok) {
1801
3065
  const content = ownedContent(page, { paths: kept, text, importers: graph });
1802
3066
  const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set() };
@@ -1829,7 +3093,19 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
1829
3093
  }
1830
3094
  out[page.path] = { rename, duplicate, delete: remove, under: below.length };
1831
3095
  }
1832
- return { redirects, actions: out };
3096
+ /** @type {Record<string, { rename: Capability, under: number }>} */
3097
+ const folders = {};
3098
+ for (const at of folderPaths(discovered.pages)) {
3099
+ const below = discovered.pages.filter((p) => under(p.path, at));
3100
+ let rename = !adapter?.acts ? no("framework") : !pageFile.ok ? no("invalid") : yes;
3101
+ // A template's addresses are on Live without being listed: a folder with one counts as live.
3102
+ if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && (!redirects || below.some((p) => p.router?.object))) rename = no("no_redirects");
3103
+ if (rename.ok && adapter?.routeLines && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
3104
+ if (rename.ok && !adapter?.routeLines && !(adapter?.folderDirs ?? folderDirs)(at, below)) rename = no("unparsed", at);
3105
+ folders[at] = { rename, under: below.length };
3106
+ }
3107
+ // New page by rule (PE3): whether the site can have one without the Operator, and why not.
3108
+ return { redirects, actions: out, folders, create: createCapability({ framework, paths: kept, text, found: discovered }) };
1833
3109
  }
1834
3110
 
1835
3111
  /**
@@ -1851,9 +3127,126 @@ export function redirectsFor(framework, pageFile, pagePaths = []) {
1851
3127
  continue;
1852
3128
  }
1853
3129
  const destBase = prefix ? normalisePath(destination.replace(REST, "")) : destination;
1854
- if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination, permanent: true });
1855
- else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
1856
- else list.push({ source, destination });
3130
+ const shape = adapterOf(framework)?.redirect;
3131
+ list.push(shape ? shape({ prefix, source, destination, base, destBase }) : { source, destination });
1857
3132
  }
1858
3133
  return { list, skipped };
1859
3134
  }
3135
+
3136
+ // ── Redirects by hand (docs/plan-folders-and-redirects.md, Part 2) ──
3137
+
3138
+ /**
3139
+ * The redirects the site sets itself, where Unbase can read them, with where each goes and where it
3140
+ * is set: vercel.json's `redirects`, an Astro config's `redirects` literal (a string or `{
3141
+ * destination }`), a Next.js config's literal `{ source, destination }` objects. In the order found.
3142
+ * @returns {{ from: string, to: string, file: string }[]}
3143
+ */
3144
+ export function siteRedirectList({ framework, text }) {
3145
+ const out = [];
3146
+ try {
3147
+ const v = JSON.parse(text("vercel.json") ?? "null");
3148
+ for (const r of Array.isArray(v?.redirects) ? v.redirects : []) {
3149
+ if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
3150
+ }
3151
+ } catch {}
3152
+ const adapter = adapterOf(framework);
3153
+ for (const c of adapter?.configs ?? []) {
3154
+ if (adapter.configRedirects) out.push(...adapter.configRedirects(stripComments(text(c) ?? ""), c));
3155
+ }
3156
+ return out;
3157
+ }
3158
+
3159
+ /** The redirects an Astro config's `redirects` literal sets, each with where it goes (a string or `{ destination }`). */
3160
+ function astroConfigRedirects(src, file) {
3161
+ const at = src.search(/\bredirects\s*:\s*\{/);
3162
+ if (at < 0) return [];
3163
+ const body = braced(src, src.indexOf("{", at)) ?? "";
3164
+ const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
3165
+ return [...body.matchAll(entry)].map((m) => ({ from: m[1], to: m[2] ?? m[3], file }));
3166
+ }
3167
+
3168
+ /** The redirects a Next.js config's literal `{ source, destination }` objects set. */
3169
+ function nextConfigRedirects(src, file) {
3170
+ const out = [];
3171
+ for (const m of src.matchAll(/\{[^{}]*\}/g)) {
3172
+ const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
3173
+ const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
3174
+ if (from && to) out.push({ from, to, file });
3175
+ }
3176
+ return out;
3177
+ }
3178
+
3179
+ /** "/old/…", "/old/*" or "/old/[...path]" → the address and whether everything under it goes along. */
3180
+ function redirectEnd(p) {
3181
+ const s = String(p ?? "").trim();
3182
+ const prefix = /\/(…|\.\.\.|\*)$/.test(s) || REST.test(s);
3183
+ const base = normalisePath(prefix ? s.replace(REST, "").replace(/\/(…|\.\.\.|\*)$/, "") : s);
3184
+ return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
3185
+ }
3186
+
3187
+ /**
3188
+ * A redirect added, changed or removed by hand, in the page file: the plan of that one write, or why
3189
+ * not. `from` may end in `/…` (or `/*`, `/[...path]`): everything under it, to the same place under
3190
+ * `to`. `was`: the redirect's address before a change. Refused: an address that is a page now
3191
+ * (`page`: the page wins), one already sent on (`exists`), none to change (`missing`), one sent to
3192
+ * itself or into itself (`self`), a loop (`loop`), an address the site's own redirects take
3193
+ * (`redirect_conflict`), and adding without the package that applies them (`no_redirects`). A `to`
3194
+ * that is sent on itself is followed to where it ends, so no chain of hops is made; redirects that
3195
+ * led to `from` lead to `to` too.
3196
+ * @param {{ action: "add" | "change" | "remove", from: string, to?: string, was?: string }} request
3197
+ * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[] } }} input
3198
+ */
3199
+ export function planRedirect(request, { framework, paths, text, found }) {
3200
+ const adapter = adapterOf(framework);
3201
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
3202
+ const action = request.action;
3203
+ if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
3204
+ if (!adapter?.acts) return no("framework");
3205
+ const pageFile = parsePageFile(text(PAGE_FILE));
3206
+ if (!pageFile.ok) return no("invalid", pageFile.error);
3207
+ const from = redirectEnd(request.from);
3208
+ const was = request.was != null ? redirectEnd(request.was) : from;
3209
+ if (action !== "add" && !(was.key in pageFile.redirects)) return no("missing", was.key);
3210
+ /** @type {Record<string, string | null>} */
3211
+ const changes = {};
3212
+ let to = null;
3213
+ if (action !== "remove") {
3214
+ if (!kitRedirects({ framework, text })) return no("no_redirects");
3215
+ if (from.base === "/" || !validAddress(from.base)) return no("address", request.from);
3216
+ const end = redirectEnd(request.to);
3217
+ if (!validAddress(end.base)) return no("address", request.to);
3218
+ const discovered = found ?? discover({ framework, paths: paths.filter((p) => !SKIP.test(p)), text });
3219
+ const isPage = (p) => discovered.pages.some((q) => (q.kind === "template" ? templateMatches(q.path, p) : q.path === p));
3220
+ if (from.prefix ? discovered.pages.some((q) => within(q.path, from.base)) : isPage(from.base)) return no("page", from.base);
3221
+ if (from.key !== was.key && from.key in pageFile.redirects) return no("exists", from.key);
3222
+ if (action === "add" && from.key in pageFile.redirects) return no("exists", from.key);
3223
+ const own = [...siteRedirects({ framework, text })].find((s) => sends(s, from.base));
3224
+ if (own) return no("redirect_conflict", own);
3225
+ // Where `to` ends when it is sent on itself: never a chain of hops.
3226
+ let dest = end.base;
3227
+ const others = { ...pageFile.redirects };
3228
+ delete others[was.key];
3229
+ for (let hops = 0; hops < 20; hops++) {
3230
+ const next = Object.entries(others).find(([s]) => !REST.test(s) && s === dest);
3231
+ if (!next) break;
3232
+ dest = next[1];
3233
+ }
3234
+ if (from.prefix ? within(dest, from.base) : dest === from.base) return no(dest === from.base ? "self" : "loop", dest);
3235
+ if (Object.entries(others).some(([s, d]) => d === from.base && s === dest)) return no("loop", dest);
3236
+ to = from.prefix ? `${dest === "/" ? "" : dest}/[...path]` : dest;
3237
+ }
3238
+ const content = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
3239
+ const before = { ...sendsOn };
3240
+ delete sendsOn[was.key];
3241
+ if (to !== null) {
3242
+ sendsOn[from.key] = to;
3243
+ // What led to this address leads on to where it now goes, not through it.
3244
+ if (!from.prefix) for (const [s, d] of Object.entries(sendsOn)) if (d === from.base && s !== from.key) sendsOn[s] = to;
3245
+ }
3246
+ for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) changes[k] = sendsOn[k] ?? null;
3247
+ });
3248
+ if (content === null) return no("same");
3249
+ const shown = (k) => k.replace(REST, "/…");
3250
+ const message = action === "remove" ? `Unbase: remove redirect ${shown(was.key)}` : `Unbase: redirect ${shown(from.key)} to ${shown(to)}`;
3251
+ return { ok: /** @type {const} */ (true), action, from: from.key, to, was: was.key, files: [{ path: PAGE_FILE, content }], redirects: changes, message };
3252
+ }