@unbase-app/pages 0.3.0 → 0.4.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
@@ -54,13 +54,17 @@ export function normalisePath(p) {
54
54
  // ── The page file ──────────────────────────────────────────────────────────
55
55
 
56
56
  /**
57
- * unbase.pages.json: `{ "pages": { "/address": { "draft": true } } }`. Absent is valid (no flags).
57
+ * 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.
58
62
  * @param {string | null | undefined} text
59
- * @returns {{ ok: true, exists: boolean, pages: Record<string, { draft?: boolean }> } | { ok: false, exists: true, error: string, pages: {} }}
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: {} }}
60
64
  */
61
65
  export function parsePageFile(text) {
62
- if (text == null) return { ok: true, exists: false, pages: {} };
63
- const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {} });
66
+ if (text == null) return { ok: true, exists: false, pages: {}, redirects: {} };
67
+ const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {}, redirects: {} });
64
68
  let data;
65
69
  try {
66
70
  data = JSON.parse(text);
@@ -70,17 +74,31 @@ export function parsePageFile(text) {
70
74
  if (!isObject(data)) return fail("the file is not an object");
71
75
  const pages = data.pages ?? {};
72
76
  if (!isObject(pages)) return fail("`pages` is not an object");
73
- /** @type {Record<string, { draft?: boolean }>} */
77
+ /** @type {Record<string, { draft?: boolean, name?: string }>} */
74
78
  const out = {};
75
79
  for (const [address, entry] of Object.entries(pages)) {
76
80
  if (!address.startsWith("/")) return fail(`${address}: an address starts with /`);
77
81
  if (!isObject(entry)) return fail(`${address}: not an object`);
78
82
  if (entry.draft !== undefined && typeof entry.draft !== "boolean") return fail(`${address}: draft is true or false`);
79
- out[normalisePath(address)] = entry.draft === undefined ? {} : { draft: entry.draft };
83
+ if (entry.name !== undefined && typeof entry.name !== "string") return fail(`${address}: name is text`);
84
+ out[normalisePath(address)] = { ...(entry.draft === undefined ? {} : { draft: entry.draft }), ...(entry.name ? { name: entry.name } : {}) };
80
85
  }
81
- return { ok: true, exists: true, pages: out };
86
+ const redirects = data.redirects ?? {};
87
+ if (!isObject(redirects)) return fail("`redirects` is not an object");
88
+ /** @type {Record<string, string>} */
89
+ const sends = {};
90
+ for (const [from, to] of Object.entries(redirects)) {
91
+ if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
92
+ if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
93
+ if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
94
+ sends[normalisePath(from)] = normalisePath(to);
95
+ }
96
+ return { ok: true, exists: true, pages: out, redirects: sends };
82
97
  }
83
98
 
99
+ /** A redirect's address that carries what is under it: `/old/[...path]`. */
100
+ const REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
101
+
84
102
  /** The addresses flagged as draft, sorted. */
85
103
  export const draftPaths = (file) =>
86
104
  Object.keys(file.pages)
@@ -691,7 +709,7 @@ function siteReads(paths, text, importers) {
691
709
  if (target.endsWith(".json")) push(jsonOf, f, target);
692
710
  }
693
711
  }
694
- const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
712
+ const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads.byName };
695
713
  siteReadsOf.set(importers, site);
696
714
  return site;
697
715
  }
@@ -1072,3 +1090,770 @@ export function withoutInContentMap(json, files) {
1072
1090
  }
1073
1091
  return JSON.stringify(map);
1074
1092
  }
1093
+
1094
+ // ── Page actions: rename, duplicate, delete (docs/plan-page-actions.md) ────
1095
+ //
1096
+ // One rule for what each action changes, from the code at one commit: the same files always give
1097
+ // the same writes, so Unbase's editor (unbase-projects page_action), the CLI (`unbase page …`) and
1098
+ // a developer's own agent make byte-identical changes. What it cannot do by rule, it refuses with a
1099
+ // reason; the editor says why, and offers the Operator where it can (`content_bound`).
1100
+
1101
+ /** Frameworks the actions know how a page is made in. */
1102
+ export const PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
1103
+
1104
+ /** Since which version each package applies the page file's redirects at build. */
1105
+ 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" };
1106
+
1107
+ /** The lowest version a dependency's range allows ("^0.4.0" → [0, 4, 0]); null when it does not say (a file, a tag, "*"). */
1108
+ export function lowestVersion(spec) {
1109
+ if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
1110
+ const m = spec.trim().replace(/^[\^~>=v\s]+/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
1111
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
1112
+ }
1113
+
1114
+ const atLeast = (have, want) => {
1115
+ for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
1116
+ return true;
1117
+ };
1118
+
1119
+ /**
1120
+ * Whether the site's build applies the page file's redirects: the kit is installed (kitInstalled)
1121
+ * by a package whose range in package.json starts at or after the version that applies them. A
1122
+ * range that does not say (a file, a tag) counts as not: a moved live page must never lose its
1123
+ * old address silently.
1124
+ */
1125
+ export function kitRedirects({ framework, text }) {
1126
+ if (!kitInstalled({ framework, text })) return false;
1127
+ let pkg = null;
1128
+ try {
1129
+ pkg = JSON.parse(text("package.json") ?? "null");
1130
+ } catch {}
1131
+ const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1132
+ return (KITS[String(framework)] ?? []).some((name) => {
1133
+ const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
1134
+ const since = REDIRECTS_SINCE[name];
1135
+ const have = lowestVersion(spec);
1136
+ return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
1137
+ });
1138
+ }
1139
+
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
+
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
+
1164
+ const under = (path, at) => (at === "/" ? path !== "/" : path.startsWith(`${at}/`));
1165
+ const within = (path, at) => path === at || under(path, at);
1166
+ /** `path` with its `from` part replaced by `to`: "/a/b" from "/a" to "/c" → "/c/b". */
1167
+ const moveAddress = (path, from, to) => (path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`));
1168
+ const parentOf = (p) => (p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/"))));
1169
+ const lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
1170
+
1171
+ /** The redirects the site sets itself where Unbase can read them: an Astro config's `redirects` literal, vercel.json, a literal in next.config. Sources only. */
1172
+ export function siteRedirects({ framework, text }) {
1173
+ const out = new Set();
1174
+ try {
1175
+ const v = JSON.parse(text("vercel.json") ?? "null");
1176
+ for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
1177
+ } 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
+ }
1188
+ }
1189
+ return out;
1190
+ }
1191
+
1192
+ /** Whether a redirect source (a page file's or the site's) takes `path`. */
1193
+ function sends(source, path) {
1194
+ if (REST.test(source)) {
1195
+ const base = normalisePath(source.replace(REST, ""));
1196
+ return within(path, base);
1197
+ }
1198
+ return source === path || matchesPattern(source, path);
1199
+ }
1200
+
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
+
1207
+ // ── Writing the page file ──
1208
+
1209
+ /**
1210
+ * The page file after `change`, as text (two spaces, a newline at the end, keys in the order they
1211
+ * were). Null when there is nothing to write: no file before and nothing in it after.
1212
+ */
1213
+ function changedPageFile(before, change) {
1214
+ let data = {};
1215
+ try {
1216
+ data = before == null ? {} : (JSON.parse(before) ?? {});
1217
+ } catch {
1218
+ data = {};
1219
+ }
1220
+ if (!isObject(data)) data = {};
1221
+ if (!isObject(data.pages)) data.pages = {};
1222
+ const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
1223
+ change(data.pages, redirects);
1224
+ for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
1225
+ if (Object.keys(redirects).length) data.redirects = redirects;
1226
+ else delete data.redirects;
1227
+ const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
1228
+ if (before == null && empty) return null;
1229
+ const after = `${JSON.stringify(data, null, 2)}\n`;
1230
+ return after === before ? null : after;
1231
+ }
1232
+
1233
+ /** The redirects with every one that leads into `from` (or under it) led to `to` instead, and none left that takes `to` itself. */
1234
+ function repoint(redirects, from, to) {
1235
+ for (const [source, dest] of Object.entries(redirects)) {
1236
+ const rest = REST.test(dest);
1237
+ const base = rest ? normalisePath(dest.replace(REST, "")) : dest;
1238
+ if (within(base, from)) redirects[source] = rest ? `${moveAddress(base, from, to)}${dest.slice(dest.lastIndexOf("/"))}` : moveAddress(base, from, to);
1239
+ }
1240
+ for (const [source, dest] of Object.entries(redirects)) {
1241
+ const base = REST.test(source) ? normalisePath(source.replace(REST, "")) : source;
1242
+ if (to && within(to, base) && sends(source, to)) delete redirects[source];
1243
+ else if (source === dest) delete redirects[source];
1244
+ }
1245
+ }
1246
+
1247
+ // ── Moving code ──
1248
+
1249
+ /** Import specifiers, with where each sits: `from "x"`, `import "x"`, `import("x")`, `require("x")`. */
1250
+ const SPECIFIER = /((?:\bfrom|\bimport|\brequire)\s*\(?\s*)(["'])([^"'\n]+)\2/g;
1251
+ /** An Astro Markdown page's layout. */
1252
+ const MD_LAYOUT = /^(layout:\s*)(["']?)([^"'\n]+?)\2\s*$/m;
1253
+
1254
+ const relativeSpec = (fromFile, target) => {
1255
+ const from = dirname(fromFile).split("/").filter(Boolean);
1256
+ const to = target.split("/");
1257
+ let i = 0;
1258
+ while (i < from.length && i < to.length - 1 && from[i] === to[i]) i++;
1259
+ const up = from.length - i;
1260
+ const rest = to.slice(i).join("/");
1261
+ return up ? `${"../".repeat(up)}${rest}` : `./${rest}`;
1262
+ };
1263
+
1264
+ /**
1265
+ * The specifier `fromFile` now needs for `target`, in the style the old one had: an alias stays
1266
+ * an alias, a specifier with an extension keeps it, one to a folder's index names the folder.
1267
+ */
1268
+ function specFor(fromFile, target, old, oldTarget) {
1269
+ const index = /\/index\.[a-z]+$/.test(oldTarget) && !/\/index(\.[a-z]+)?$/.test(old);
1270
+ const ext = /\.[a-z]+$/.test(old.split("/").pop() ?? "") && old.endsWith(oldTarget.slice(oldTarget.lastIndexOf(".")));
1271
+ let t = target;
1272
+ if (index) t = dirname(target);
1273
+ else if (!ext) t = target.replace(/\.[a-z]+$/, "");
1274
+ if (old.startsWith("@/") && t.startsWith("src/")) return `@/${t.slice(4)}`;
1275
+ return relativeSpec(fromFile, t);
1276
+ }
1277
+
1278
+ /**
1279
+ * `src` of a file now at `now` (before at `was`) with each specifier pointed where its target is
1280
+ * after `moves` (old path → new path). Unchanged when nothing it imports moved and it did not.
1281
+ */
1282
+ function respecified(src, was, now, moves, have) {
1283
+ const fix = (spec) => {
1284
+ const target = resolveImport(was, spec, have);
1285
+ if (!target) return spec;
1286
+ const next = moves.get(target) ?? target;
1287
+ if (next === target && was === now) return spec;
1288
+ if (!spec.startsWith(".") && next === target) return spec;
1289
+ return specFor(now, next, spec, target);
1290
+ };
1291
+ let out = src.replace(SPECIFIER, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
1292
+ if (/\.mdx?$/.test(now)) out = out.replace(MD_LAYOUT, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
1293
+ return out;
1294
+ }
1295
+
1296
+ // ── Links ──
1297
+
1298
+ /** Quoted addresses in code and content, and Markdown links: what a rename rewrites. */
1299
+ const QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
1300
+ const MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
1301
+
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) {
1304
+ const swap = (address) => {
1305
+ const bare = address.replace(/[#?][\s\S]*$/, "");
1306
+ const tail = address.slice(bare.length);
1307
+ const slash = bare.length > 1 && bare.endsWith("/") ? "/" : "";
1308
+ const clean = slash ? bare.slice(0, -1) : bare;
1309
+ if (clean === from) return `${to}${to === "/" ? "" : slash}${tail}`;
1310
+ if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
1311
+ return address;
1312
+ };
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;
1316
+ }
1317
+
1318
+ /** `src` with the inside of its string literals blanked, offsets kept: names in code, not in text. */
1319
+ function blankStrings(src) {
1320
+ let out = "";
1321
+ let i = 0;
1322
+ while (i < src.length) {
1323
+ const c = src[i];
1324
+ if (c === '"' || c === "'" || c === "`") {
1325
+ const j = stringEnd(src, i);
1326
+ out += c + blank(src.slice(i + 1, j - 1)) + (j - 1 > i ? src[j - 1] : "");
1327
+ i = j;
1328
+ continue;
1329
+ }
1330
+ out += c;
1331
+ i++;
1332
+ }
1333
+ return out;
1334
+ }
1335
+
1336
+ // ── Per framework: where a page's files are ──
1337
+
1338
+ /** The folder the pages router or Astro keeps routes in, from the page's file. */
1339
+ const routesBase = (file) => (file.startsWith("src/pages/") ? "src/pages" : file.startsWith("pages/") ? "pages" : file.startsWith("src/app/") ? "src/app" : file.startsWith("app/") ? "app" : null);
1340
+
1341
+ /**
1342
+ * Where a page at `to` would have its file, in the form the page at `page` has (a file, a folder's
1343
+ * index, a Next.js app router folder), and the folder whose files go along with it.
1344
+ */
1345
+ function destination(page, to, discovered) {
1346
+ const base = routesBase(page.file);
1347
+ if (!base) return null;
1348
+ const ext = page.file.slice(page.file.lastIndexOf("."));
1349
+ if (base.endsWith("app")) {
1350
+ // app/(group)/x/page.tsx: the folder is the page. Its new folder sits where its new parent's does.
1351
+ const dir = dirname(page.file);
1352
+ const parent = parentOf(to);
1353
+ const sameParent = parent === parentOf(page.path);
1354
+ const parentPage = parent === null ? null : discovered.pages.find((p) => p.path === parent && p.file && routesBase(p.file) === base);
1355
+ const parentDir = sameParent ? dirname(dir) : parentPage ? dirname(parentPage.file) : `${base}${parent === "/" ? "" : parent}`;
1356
+ const newDir = to === "/" ? base : `${parentDir}/${lastOf(to)}`;
1357
+ return { file: `${newDir}/${page.file.slice(dir.length + 1)}`, dir, newDir, folder: true };
1358
+ }
1359
+ const index = /(^|\/)index\.[a-z]+$/.test(page.file);
1360
+ const oldDir = `${base}${page.path === "/" ? "" : page.path}`;
1361
+ const newDir = `${base}${to === "/" ? "" : to}`;
1362
+ return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
1363
+ }
1364
+
1365
+ /** 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
+ function appSegmentOwn(dir, paths) {
1367
+ return paths.filter((p) => {
1368
+ if (dirname(p) === dir) return true;
1369
+ if (!p.startsWith(`${dir}/`)) return false;
1370
+ const first = p.slice(dir.length + 1).split("/")[0];
1371
+ return first.startsWith("_");
1372
+ });
1373
+ }
1374
+
1375
+ /** A component name for a new route's file: "/pricing-copy" → "PricingCopy". */
1376
+ const componentName = (address) =>
1377
+ (lastOf(address) || "Home")
1378
+ .split(/[^A-Za-z0-9]+/)
1379
+ .filter(Boolean)
1380
+ .map((w) => w[0].toUpperCase() + w.slice(1))
1381
+ .join("")
1382
+ .replace(/^(\d)/, "Page$1") || "Page";
1383
+
1384
+ /** The route element's `path` attribute's value and where it sits in `src`, or null. */
1385
+ function routePathAttr(src, router) {
1386
+ const tag = src.slice(router.start, router.end);
1387
+ const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
1388
+ if (!m) return null;
1389
+ const value = m.slice(2).find((v) => v !== undefined) ?? "";
1390
+ const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
1391
+ return { value, start: valueAt, end: valueAt + value.length };
1392
+ }
1393
+
1394
+ // ── The plan ──
1395
+
1396
+ /**
1397
+ * @typedef {{ path: string, content?: string, from?: string, deleted?: true }} PageWrite
1398
+ * `content`: the file's new text; `from`: the file whose bytes it gets (a move or copy keeps
1399
+ * 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
1401
+ * @typedef {{ ok: false, reason: string, detail?: string }} PageRefusal
1402
+ */
1403
+
1404
+ /**
1405
+ * What one action does to a site's code, or why it cannot: `rename` (to a new address, with a new
1406
+ * name), `duplicate` (a copy at `to`, by default the first free `<address>-copy`) or `delete`
1407
+ * (visitors to the old address sent to `redirect`, by default the page above it; null: Not
1408
+ * Found). `live` says whether the page is on Live now: only then does a rename or delete leave a
1409
+ * redirect, and only then does it need the kit to apply one. `drafts`: a copy starts as a draft.
1410
+ *
1411
+ * `paths` are every file of the app (a move takes files whose text was not read along);
1412
+ * `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
1415
+ * @returns {PagePlan | PageRefusal}
1416
+ */
1417
+ export function planPage(request, input) {
1418
+ const { framework, text } = input;
1419
+ const paths = input.paths.filter((p) => !SKIP.test(p));
1420
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
1421
+ 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");
1424
+ const at = normalisePath(request.path);
1425
+ const discovered = input.found ?? discover({ framework, paths, text });
1426
+ const page = discovered.pages.find((p) => p.path === at);
1427
+ if (!page) {
1428
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
1429
+ return template ? no("template", template.path) : no("missing");
1430
+ }
1431
+ if (page.kind === "template") return no("template", page.path);
1432
+ if (!page.file || page.reason === "unparsed") return no("unparsed");
1433
+ const pageFile = parsePageFile(text(PAGE_FILE));
1434
+ if (!pageFile.ok) return no("invalid", pageFile.error);
1435
+ const below = discovered.pages.filter((p) => under(p.path, at));
1436
+ const have = new Set(paths);
1437
+ const importers = input.importers ?? importGraph(paths, text);
1438
+ const live = request.live === true;
1439
+ const redirects = live ? kitRedirects({ framework, text }) : false;
1440
+ const ownRedirects = siteRedirects({ framework, text });
1441
+ const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
1442
+ /** @type {Map<string, PageWrite>} */
1443
+ const writes = new Map();
1444
+ const write = (w) => writes.set(w.path, w);
1445
+ const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
1446
+ const links = new Set();
1447
+ const unlinked = new Set();
1448
+ const moves = [];
1449
+ /** Files that moved, old path → new path: drafts waiting on them follow. */
1450
+ const renamed = [];
1451
+ let to = null;
1452
+ /** @type {Record<string, string | null>} */
1453
+ const redirectChanges = {};
1454
+ const collections = (() => {
1455
+ try {
1456
+ return JSON.parse(text(COLLECTIONS) ?? "null");
1457
+ } catch {
1458
+ return null;
1459
+ }
1460
+ })();
1461
+ const collectionsAfter = isObject(collections) ? { ...collections } : null;
1462
+
1463
+ if (action === "rename") {
1464
+ if (at === "/") return no("home");
1465
+ const target = request.to == null ? at : normalisePath(request.to);
1466
+ if (!validAddress(target) || target === "/") return no("address", target);
1467
+ if (target !== at && within(target, at)) return no("address", target);
1468
+ if (target !== at && taken(target)) return no("taken", target);
1469
+ if (target !== at && live && !redirects) return no("no_redirects");
1470
+ to = target;
1471
+ /** @type {Map<string, string>} old path → new path, of the files that move */
1472
+ const moved = new Map();
1473
+ if (target !== at) {
1474
+ if (framework === "vite-react") {
1475
+ // The route's own path, when it is relative to a parent route: its last part only.
1476
+ const src = text(page.router.file) ?? "";
1477
+ const attr = routePathAttr(src, page.router);
1478
+ if (!attr) return no("unparsed", "index route");
1479
+ if (!attr.value.startsWith("/")) {
1480
+ const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
1481
+ if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
1482
+ const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
1483
+ write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
1484
+ }
1485
+ } else {
1486
+ const dest = destination(page, target, discovered);
1487
+ if (!dest) return no("unparsed");
1488
+ // Its file, and everything in its folder: the pages under it, and what they keep there.
1489
+ for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
1490
+ moved.set(page.file, dest.file);
1491
+ for (const [from, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
1492
+ for (const [from, next] of moved) {
1493
+ const src = CODE.test(from) ? text(from) : null;
1494
+ const content = src == null ? null : respecified(src, from, next, moved, have);
1495
+ write(content == null || content === src ? { path: next, from } : { path: next, content });
1496
+ write({ path: from, deleted: true });
1497
+ }
1498
+ // Files that import a moved one.
1499
+ for (const p of paths) {
1500
+ if (moved.has(p) || !CODE.test(p)) continue;
1501
+ const src = text(p);
1502
+ if (!src) continue;
1503
+ const out = respecified(src, p, p, moved, have);
1504
+ if (out !== src) write({ path: p, content: out });
1505
+ }
1506
+ }
1507
+ // Every link to it, or under it, in code and content (route files' own `pad` too).
1508
+ 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;
1511
+ const where = moved.get(p) ?? p;
1512
+ const src = current(where);
1513
+ if (!src) continue;
1514
+ const out = relinked(src, at, target, /\.mdx?$/.test(p));
1515
+ if (out === src) continue;
1516
+ write({ path: where, content: out });
1517
+ if (!moved.has(p)) links.add(where);
1518
+ }
1519
+ moves.push({ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) })));
1520
+ for (const [from, next] of moved) renamed.push({ from, to: next });
1521
+ }
1522
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1523
+ if (target !== at) {
1524
+ for (const key of Object.keys(pages)) {
1525
+ if (!within(key, at)) continue;
1526
+ pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
1527
+ delete pages[key];
1528
+ }
1529
+ const before = { ...sendsOn };
1530
+ if (live) {
1531
+ sendsOn[at] = target;
1532
+ if (below.length) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
1533
+ }
1534
+ repoint(sendsOn, at, target);
1535
+ for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1536
+ }
1537
+ if (request.name !== undefined) {
1538
+ const entry = pages[target] ?? {};
1539
+ if (request.name) entry.name = String(request.name).trim().slice(0, 120);
1540
+ else delete entry.name;
1541
+ pages[target] = entry;
1542
+ }
1543
+ });
1544
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1545
+ if (!writes.size) return no("same");
1546
+ }
1547
+
1548
+ if (action === "duplicate") {
1549
+ if (framework === "vite-react" && page.reason === "nested") return no("nested");
1550
+ let target;
1551
+ if (request.to != null) {
1552
+ target = normalisePath(request.to);
1553
+ if (!validAddress(target) || target === "/") return no("address", target);
1554
+ if (taken(target)) return no("taken", target);
1555
+ } else {
1556
+ const base = at === "/" ? "/home-copy" : `${at}-copy`;
1557
+ target = base;
1558
+ for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
1559
+ }
1560
+ to = target;
1561
+ const content = ownedContent(page, { paths, text, importers });
1562
+ if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1563
+ const own = new Set(content.files);
1564
+ const reads = siteReads(paths, text, importers);
1565
+ const ownCodeFiles = ownCode(page, importers, reads.imports);
1566
+ // How the page reads each content file it owns, and whether its copy can read a copy instead.
1567
+ const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() };
1568
+ const imported = new Set(reads.jsonOf.get(page.file) ?? []);
1569
+ /** @type {Map<string, string>} content file → its copy */
1570
+ const copies = new Map();
1571
+ /** @type {{ kind: "name" | "entry", name: string, collection?: string, next: string }[]} */
1572
+ const rebinds = [];
1573
+ const newId = slugOf(lastOf(target)) || "copy";
1574
+ const freeFile = (dir, base, ext) => {
1575
+ let f = `${dir}/${base}${ext}`;
1576
+ for (let n = 2; (have.has(f) || [...writes.keys()].includes(f) || [...copies.values()].includes(f)) && n < 100; n++) f = `${dir}/${base}-${n}${ext}`;
1577
+ return f;
1578
+ };
1579
+ for (const f of own) {
1580
+ if (reads.isRoute(f)) continue;
1581
+ if (imported.has(f)) {
1582
+ copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
1583
+ continue;
1584
+ }
1585
+ const collection = collectionOfFile(f, reads.collections);
1586
+ const id = f.slice(f.lastIndexOf("/") + 1, -5);
1587
+ // A collection several files make (a folder): a copy beside it is one more entry.
1588
+ const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
1589
+ const entry = `${collection}/${id}`;
1590
+ if (pageReads.entries.has(entry) && folder) {
1591
+ const next = freeFile(dirname(f), newId, ".json");
1592
+ copies.set(f, next);
1593
+ rebinds.push({ kind: "entry", name: id, collection, next: next.slice(next.lastIndexOf("/") + 1, -5) });
1594
+ } else if (pageReads.names.has(id) && id !== collection && folder) {
1595
+ const next = freeFile(dirname(f), newId, ".json");
1596
+ copies.set(f, next);
1597
+ rebinds.push({ kind: "name", name: id, next: next.slice(next.lastIndexOf("/") + 1, -5) });
1598
+ } else {
1599
+ return no("content_bound", f);
1600
+ }
1601
+ }
1602
+ if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
1603
+ // Its own modules stay shared; a module of its own that reads its content would read the original's.
1604
+ for (const m of ownCodeFiles) {
1605
+ if (m === page.file) continue;
1606
+ const r = reads.readsByFile.get(m);
1607
+ if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && [...own].some((f) => !reads.isRoute(f))) return no("content_bound", m);
1608
+ }
1609
+ const rebind = (src) => {
1610
+ let out = src;
1611
+ for (const r of rebinds) {
1612
+ if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape(r.collection)}["']\\s*,\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1613
+ else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1614
+ }
1615
+ for (const [f, next] of copies) {
1616
+ if (!imported.has(f)) continue;
1617
+ out = out.replace(SPECIFIER, (m, lead, q, spec) => (resolveImport(page.file, spec, have) === f ? `${lead}${q}${spec.slice(0, spec.lastIndexOf("/") + 1)}${next.slice(next.lastIndexOf("/") + 1)}${q}` : m));
1618
+ }
1619
+ return out;
1620
+ };
1621
+ if (framework === "vite-react") {
1622
+ const router = page.router.file;
1623
+ const src = current(router) ?? "";
1624
+ const attr = routePathAttr(src, page.router);
1625
+ if (!attr) return no("unparsed", "index route");
1626
+ let name = componentName(target);
1627
+ for (let n = 2; new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(src) && n < 100; n++) name = `${componentName(target)}${n}`;
1628
+ const ext = page.file.slice(page.file.lastIndexOf("."));
1629
+ const file = freeFile(dirname(page.file), name, ext);
1630
+ const original = text(page.file) ?? "";
1631
+ 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}`);
1640
+ const value = attr.value.startsWith("/") ? target : (() => {
1641
+ const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
1642
+ return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1643
+ })();
1644
+ 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 });
1652
+ } else {
1653
+ const dest = destination(page, target, discovered);
1654
+ if (!dest) return no("unparsed");
1655
+ // 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];
1657
+ const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1658
+ for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1659
+ for (const [from, next] of moved) {
1660
+ const src = CODE.test(from) ? text(from) : null;
1661
+ if (src == null) {
1662
+ write({ path: next, from });
1663
+ continue;
1664
+ }
1665
+ let out = respecified(src, from, next, moved, have);
1666
+ if (from === page.file) out = rebind(out);
1667
+ write(out === src ? { path: next, from } : { path: next, content: out });
1668
+ }
1669
+ }
1670
+ for (const [f, next] of copies) {
1671
+ write({ path: next, from: f });
1672
+ if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1673
+ }
1674
+ // Its route file (its address and SEO), copied with the new address.
1675
+ for (const f of own) {
1676
+ if (!reads.isRoute(f)) continue;
1677
+ const src = text(f) ?? "";
1678
+ const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
1679
+ write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at)}(")`), `$1${target}$2`) });
1680
+ if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1681
+ }
1682
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
1683
+ const entry = { ...(request.drafts ? { draft: true } : {}), ...(request.name ? { name: String(request.name).trim().slice(0, 120) } : {}) };
1684
+ if (Object.keys(entry).length) pages[target] = entry;
1685
+ });
1686
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1687
+ }
1688
+
1689
+ if (action === "delete") {
1690
+ if (at === "/") return no("home");
1691
+ if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
1692
+ let target = null;
1693
+ if (live && request.redirect !== null) {
1694
+ if (request.redirect !== undefined) {
1695
+ target = normalisePath(request.redirect);
1696
+ if (within(target, at) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1697
+ } else {
1698
+ 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
+ target = target ?? "/";
1700
+ }
1701
+ if (!redirects) return no("no_redirects");
1702
+ }
1703
+ to = target;
1704
+ if (framework === "vite-react") {
1705
+ const router = page.router.file;
1706
+ const src = current(router) ?? "";
1707
+ // Its route element, and its line when nothing else is on it.
1708
+ let { start, end } = page.router;
1709
+ const lineStart = src.lastIndexOf("\n", start - 1) + 1;
1710
+ const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
1711
+ if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
1712
+ start = lineStart;
1713
+ end = Math.min(src.length, lineEnd + 1);
1714
+ }
1715
+ let out = src.slice(0, start) + src.slice(end);
1716
+ 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, "");
1723
+ if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
1724
+ }
1725
+ write({ path: router, content: out });
1726
+ } else {
1727
+ const dir = dirname(page.file);
1728
+ const files = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
1729
+ for (const f of files) write({ path: f, deleted: true });
1730
+ }
1731
+ const content = ownedContent(page, { paths, text, importers });
1732
+ for (const f of content.files) {
1733
+ write({ path: f, deleted: true });
1734
+ if (collectionsAfter) delete collectionsAfter[f];
1735
+ }
1736
+ for (const f of linksTo(at, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
1737
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1738
+ delete pages[at];
1739
+ 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];
1743
+ for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1744
+ });
1745
+ if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
1746
+ }
1747
+
1748
+ if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
1749
+ 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` });
1751
+ }
1752
+ const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1753
+ const message =
1754
+ action === "rename" ? (to === at ? `Unbase: rename ${at}` : `Unbase: move ${at} to ${to}`) : action === "duplicate" ? `Unbase: duplicate ${at} as ${to}` : `Unbase: delete ${at}${to ? ` (visitors go to ${to})` : ""}`;
1755
+ return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
1756
+ }
1757
+
1758
+ /**
1759
+ * What can be done to each page of the code here, and why not (the menu's grey lines): per
1760
+ * address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
1761
+ * `live`: the addresses on Live now (a live page needs the kit's redirects to move); `redirects`:
1762
+ * whether this code's build applies them. Cheaper than a plan: no writes are worked out.
1763
+ */
1764
+ export function pageActions({ framework, paths, text, live = new Set(), found, importers }) {
1765
+ const kept = paths.filter((p) => !SKIP.test(p));
1766
+ const discovered = found ?? discover({ framework, paths: kept, text });
1767
+ const graph = importers ?? importGraph(kept, text);
1768
+ const pageFile = parsePageFile(text(PAGE_FILE));
1769
+ const redirects = kitRedirects({ framework, text });
1770
+ const reads = siteReads(kept, text, graph);
1771
+ /** @type {Record<string, { rename: Capability, duplicate: Capability, delete: Capability, under: number }>} */
1772
+ const out = {};
1773
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
1774
+ const yes = { ok: /** @type {const} */ (true) };
1775
+ for (const page of discovered.pages) {
1776
+ if (page.path.includes(" ")) continue;
1777
+ const below = discovered.pages.filter((p) => under(p.path, page.path));
1778
+ const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
1779
+ if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
1780
+ out[page.path] = all(no("framework"));
1781
+ continue;
1782
+ }
1783
+ if (!pageFile.ok) {
1784
+ out[page.path] = all(no("invalid"));
1785
+ continue;
1786
+ }
1787
+ if (page.kind === "template") {
1788
+ out[page.path] = all(no("template"));
1789
+ continue;
1790
+ }
1791
+ if (!page.file || page.reason === "unparsed") {
1792
+ out[page.path] = all(no("unparsed"));
1793
+ continue;
1794
+ }
1795
+ 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");
1798
+ 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;
1800
+ if (duplicate.ok) {
1801
+ const content = ownedContent(page, { paths: kept, text, importers: graph });
1802
+ const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set() };
1803
+ const imported = new Set(reads.jsonOf.get(page.file) ?? []);
1804
+ if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
1805
+ else if (content.unknown) duplicate = no("content_bound");
1806
+ else
1807
+ for (const f of content.files) {
1808
+ if (reads.isRoute(f) || imported.has(f)) continue;
1809
+ const collection = collectionOfFile(f, reads.collections);
1810
+ const id = f.slice(f.lastIndexOf("/") + 1, -5);
1811
+ const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
1812
+ const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || (pageReads.names.has(id) && id !== collection));
1813
+ if (bound) {
1814
+ duplicate = no("content_bound", f);
1815
+ break;
1816
+ }
1817
+ }
1818
+ if (duplicate.ok) {
1819
+ const mine = ownCode(page, graph, reads.imports);
1820
+ for (const m of mine) {
1821
+ if (m === page.file) continue;
1822
+ const r = reads.readsByFile.get(m);
1823
+ if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads.isRoute(f))) {
1824
+ duplicate = no("content_bound", m);
1825
+ break;
1826
+ }
1827
+ }
1828
+ }
1829
+ }
1830
+ out[page.path] = { rename, duplicate, delete: remove, under: below.length };
1831
+ }
1832
+ return { redirects, actions: out };
1833
+ }
1834
+
1835
+ /**
1836
+ * The page file's redirects for a framework's build, without those whose address is a page now (a
1837
+ * page made where one used to send visitors on: the page wins). `skipped` names them.
1838
+ * Astro gets `[...path]` as it is here; a static Astro site needs it as one redirect per page
1839
+ * under the new address, which the Astro integration makes (astro.mjs). Next.js `:path*`; React
1840
+ * Router a route per address, `prefix` when everything under it goes along.
1841
+ */
1842
+ export function redirectsFor(framework, pageFile, pagePaths = []) {
1843
+ const pages = new Set(pagePaths.map(normalisePath));
1844
+ const list = [];
1845
+ const skipped = [];
1846
+ for (const [source, destination] of Object.entries(pageFile.redirects ?? {})) {
1847
+ const prefix = REST.test(source);
1848
+ const base = prefix ? normalisePath(source.replace(REST, "")) : source;
1849
+ if (!prefix && pages.has(source)) {
1850
+ skipped.push(source);
1851
+ continue;
1852
+ }
1853
+ 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 });
1857
+ }
1858
+ return { list, skipped };
1859
+ }