@unbase-app/pages 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/binding.mjs +1687 -0
- package/core.mjs +499 -56
- package/package.json +3 -2
package/core.mjs
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
//
|
|
14
14
|
// parsePageFile unbase.pages.json, validated
|
|
15
15
|
// deployContext production | preview | development, never from NODE_ENV
|
|
16
|
-
// discover the pages the code makes (Astro, Next.js, React Router)
|
|
16
|
+
// discover the pages the code makes (Astro, Next.js, React Router, HTML files)
|
|
17
17
|
// draftCheck whether one page can be kept out of a production build
|
|
18
18
|
// linksTo the files that name a page's address
|
|
19
19
|
// leakPrints text that only a draft page has, to search the output for
|
|
@@ -55,16 +55,18 @@ export function normalisePath(p) {
|
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
57
|
* unbase.pages.json: `{ "pages": { "/address": { "draft": true, "name": "Pricing" } },
|
|
58
|
-
* "redirects": { "/old": "/new" } }`. Absent is valid
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
58
|
+
* "folders": { "/legal": { "name": "Legal" } }, "redirects": { "/old": "/new" } }`. Absent is valid
|
|
59
|
+
* (no flags, no redirects). A page's or folder's `name` is what Unbase calls it (never rendered; a
|
|
60
|
+
* folder is an address with pages under it and none of its own, docs/plan-folders-and-redirects.md);
|
|
61
|
+
* `redirects` send an old address on, applied at build by the framework's package
|
|
62
|
+
* (docs/plan-page-actions.md). A redirect's address may end in `/[...path]`: everything under it,
|
|
63
|
+
* carried over.
|
|
62
64
|
* @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: {} }}
|
|
65
|
+
* @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
66
|
*/
|
|
65
67
|
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: {} });
|
|
68
|
+
if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
|
|
69
|
+
const fail = (error) => ({ ok: /** @type {const} */ (false), exists: /** @type {const} */ (true), error, pages: {}, folders: {}, redirects: {} });
|
|
68
70
|
let data;
|
|
69
71
|
try {
|
|
70
72
|
data = JSON.parse(text);
|
|
@@ -83,6 +85,15 @@ export function parsePageFile(text) {
|
|
|
83
85
|
if (entry.name !== undefined && typeof entry.name !== "string") return fail(`${address}: name is text`);
|
|
84
86
|
out[normalisePath(address)] = { ...(entry.draft === undefined ? {} : { draft: entry.draft }), ...(entry.name ? { name: entry.name } : {}) };
|
|
85
87
|
}
|
|
88
|
+
const folderData = data.folders ?? {};
|
|
89
|
+
if (!isObject(folderData)) return fail("`folders` is not an object");
|
|
90
|
+
/** @type {Record<string, { name: string }>} */
|
|
91
|
+
const folders = {};
|
|
92
|
+
for (const [address, entry] of Object.entries(folderData)) {
|
|
93
|
+
if (!address.startsWith("/")) return fail(`folders: ${address}: an address starts with /`);
|
|
94
|
+
if (!isObject(entry) || (entry.name !== undefined && typeof entry.name !== "string")) return fail(`folders: ${address}: name is text`);
|
|
95
|
+
if (entry.name) folders[normalisePath(address)] = { name: entry.name };
|
|
96
|
+
}
|
|
86
97
|
const redirects = data.redirects ?? {};
|
|
87
98
|
if (!isObject(redirects)) return fail("`redirects` is not an object");
|
|
88
99
|
/** @type {Record<string, string>} */
|
|
@@ -93,7 +104,7 @@ export function parsePageFile(text) {
|
|
|
93
104
|
if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
|
|
94
105
|
sends[normalisePath(from)] = normalisePath(to);
|
|
95
106
|
}
|
|
96
|
-
return { ok: true, exists: true, pages: out, redirects: sends };
|
|
107
|
+
return { ok: true, exists: true, pages: out, folders, redirects: sends };
|
|
97
108
|
}
|
|
98
109
|
|
|
99
110
|
/** A redirect's address that carries what is under it: `/old/[...path]`. */
|
|
@@ -152,14 +163,24 @@ function stringEnd(src, i) {
|
|
|
152
163
|
export function stripComments(src) {
|
|
153
164
|
let out = "";
|
|
154
165
|
let i = 0;
|
|
166
|
+
// Text up to the next comment or string goes across whole: a large file is not built a character at a time.
|
|
167
|
+
const special = /\/[/*]|["'`]/g;
|
|
155
168
|
while (i < src.length) {
|
|
169
|
+
special.lastIndex = i;
|
|
170
|
+
const next = special.exec(src);
|
|
171
|
+
const to = next ? next.index : src.length;
|
|
172
|
+
if (to > i) {
|
|
173
|
+
out += src.slice(i, to);
|
|
174
|
+
i = to;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
156
177
|
const c = src[i];
|
|
157
178
|
const d = src[i + 1];
|
|
158
179
|
if (c === "/" && d === "/") {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
180
|
+
const end = src.indexOf("\n", i);
|
|
181
|
+
const stop = end < 0 ? src.length : end;
|
|
182
|
+
out += " ".repeat(stop - i);
|
|
183
|
+
i = stop;
|
|
163
184
|
continue;
|
|
164
185
|
}
|
|
165
186
|
if (c === "/" && d === "*") {
|
|
@@ -263,6 +284,24 @@ function astroPages(paths) {
|
|
|
263
284
|
return out;
|
|
264
285
|
}
|
|
265
286
|
|
|
287
|
+
/**
|
|
288
|
+
* A site of HTML files (detection `html`: no build): a page per .html file, at the address Vercel
|
|
289
|
+
* serves it from (and the runner's static server, unbase-operator src/static-server.ts): `index.html`
|
|
290
|
+
* of a folder at the folder, any other file by its name. 404.html is the not-found page, no page.
|
|
291
|
+
*/
|
|
292
|
+
function htmlPages(paths) {
|
|
293
|
+
/** @type {Page[]} */
|
|
294
|
+
const out = [];
|
|
295
|
+
for (const p of paths) {
|
|
296
|
+
if (!p.endsWith(".html") || p === "404.html") continue;
|
|
297
|
+
const segments = p.split("/");
|
|
298
|
+
if (segments.some((s) => s.startsWith("."))) continue;
|
|
299
|
+
if (segments.at(-1) === "index.html") segments.pop();
|
|
300
|
+
out.push({ path: address(segments), kind: "file", file: p });
|
|
301
|
+
}
|
|
302
|
+
return out;
|
|
303
|
+
}
|
|
304
|
+
|
|
266
305
|
/** Next.js: app/**\/page.* and pages/**, as unbase-projects' pages.ts read them. */
|
|
267
306
|
function nextPages(paths) {
|
|
268
307
|
/** @type {Page[]} */
|
|
@@ -440,7 +479,15 @@ export function removeRoutes({ file, code, paths, text, drop }) {
|
|
|
440
479
|
export function discover({ framework, paths, text }) {
|
|
441
480
|
const kept = paths.filter((p) => !SKIP.test(p));
|
|
442
481
|
const found =
|
|
443
|
-
framework === "astro"
|
|
482
|
+
framework === "astro"
|
|
483
|
+
? { pages: astroPages(kept), notFound: null }
|
|
484
|
+
: framework === "next"
|
|
485
|
+
? { pages: nextPages(kept), notFound: null }
|
|
486
|
+
: framework === "vite-react"
|
|
487
|
+
? reactRouterPages(kept, text)
|
|
488
|
+
: framework === "html"
|
|
489
|
+
? { pages: htmlPages(kept), notFound: null }
|
|
490
|
+
: { pages: [], notFound: null };
|
|
444
491
|
const seen = new Set();
|
|
445
492
|
const pages = found.pages
|
|
446
493
|
.filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
|
|
@@ -453,8 +500,26 @@ export function discover({ framework, paths, text }) {
|
|
|
453
500
|
const CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
|
|
454
501
|
/** Where content collections are defined: naming one there is not using it. */
|
|
455
502
|
const CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
|
|
456
|
-
/**
|
|
457
|
-
|
|
503
|
+
/**
|
|
504
|
+
* Written by comment-modus: content file → its collection, where that is not its folder. 1.11 and
|
|
505
|
+
* newer write collections.json; LEGACY-NL: older ones only collecties.json. Both are read, merged as
|
|
506
|
+
* comment-modus merges them (the English one wins), and both are written.
|
|
507
|
+
*/
|
|
508
|
+
const COLLECTIONS = "src/content/.schemas/collections.json";
|
|
509
|
+
const LEGACY_COLLECTIONS = "src/content/.schemas/collecties.json";
|
|
510
|
+
|
|
511
|
+
/** The list from either file; null when neither is there or readable. */
|
|
512
|
+
function readCollections(text) {
|
|
513
|
+
/** @type {Record<string, unknown> | null} */
|
|
514
|
+
let out = null;
|
|
515
|
+
for (const p of [LEGACY_COLLECTIONS, COLLECTIONS]) {
|
|
516
|
+
try {
|
|
517
|
+
const d = JSON.parse(text(p) ?? "null");
|
|
518
|
+
if (isObject(d)) out = { ...(out ?? {}), ...d };
|
|
519
|
+
} catch {}
|
|
520
|
+
}
|
|
521
|
+
return out;
|
|
522
|
+
}
|
|
458
523
|
|
|
459
524
|
/** The names a content file goes by: its entry id (file name) and its collection. */
|
|
460
525
|
function contentNames(paths, text) {
|
|
@@ -464,9 +529,10 @@ function contentNames(paths, text) {
|
|
|
464
529
|
if (!files.has(name)) files.set(name, new Set());
|
|
465
530
|
files.get(name).add(f);
|
|
466
531
|
};
|
|
532
|
+
/** @type {Record<string, unknown>} */
|
|
467
533
|
let collections = {};
|
|
468
534
|
try {
|
|
469
|
-
collections =
|
|
535
|
+
collections = readCollections(text) ?? {};
|
|
470
536
|
} catch {}
|
|
471
537
|
for (const f of paths) {
|
|
472
538
|
if (!CONTENT_JSON.test(f)) continue;
|
|
@@ -503,22 +569,91 @@ function ownCode(page, importers, imports) {
|
|
|
503
569
|
|
|
504
570
|
/** Astro's own reading functions: collection first, then (getEntry) the entry. */
|
|
505
571
|
const ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
|
|
572
|
+
/** Whether a text names one of them. */
|
|
573
|
+
const ASTRO_NAMED = /getCollection|getEntry|getEntries/;
|
|
506
574
|
|
|
507
575
|
/**
|
|
508
576
|
* How the site reads content, as the editability manifest's `reads` say it (plan-editable F0):
|
|
509
577
|
* Astro's functions; the site's own functions that pass their first argument on as the collection
|
|
510
578
|
* (`getPagina(naam)`: `byName`); and those that read fixed content (`getEvenementen()` a whole
|
|
511
|
-
* collection, `getActieAgendaTeksten()` one entry: `fixed`). `
|
|
512
|
-
*
|
|
579
|
+
* collection, `getActieAgendaTeksten()` one entry: `fixed`). `files` is every code file with its
|
|
580
|
+
* text; `code` holds, without comments, the ones that can read content (`reading`).
|
|
581
|
+
*
|
|
582
|
+
* Only files that name a reading function are read for helpers: Astro's own, then the helpers
|
|
583
|
+
* found, again until no file is added. A file that names none of them defines no helper that reads
|
|
584
|
+
* and calls none, so the answer is the one all files give (a large repo's backend, tests and docs:
|
|
585
|
+
* 1.9 s of an Edge Function's 2 s on Unbase's own, docs/plan-page-analysis.md).
|
|
513
586
|
*/
|
|
514
587
|
function contentReads(paths, text) {
|
|
515
|
-
/** @type {
|
|
516
|
-
const
|
|
588
|
+
/** @type {[string, string][]} */
|
|
589
|
+
const files = [];
|
|
517
590
|
for (const p of paths) {
|
|
518
591
|
if (!CODE.test(p) || SKIP.test(p)) continue;
|
|
519
592
|
const src = text(p);
|
|
520
|
-
if (src)
|
|
593
|
+
if (src) files.push([p, src]);
|
|
594
|
+
}
|
|
595
|
+
const picked = new Set();
|
|
596
|
+
// Each round asks the files not yet read only about the names it found: they named none before.
|
|
597
|
+
// A file is parsed once, whichever round reads it.
|
|
598
|
+
const asked = new Set(ASTRO_READS);
|
|
599
|
+
const parsed = new Map();
|
|
600
|
+
let names = ASTRO_READS;
|
|
601
|
+
let reads = null;
|
|
602
|
+
for (;;) {
|
|
603
|
+
let grew = false;
|
|
604
|
+
if (names.length) {
|
|
605
|
+
const naming = new RegExp(names.map(escape).join("|"));
|
|
606
|
+
for (const [p, src] of files) {
|
|
607
|
+
if (picked.has(p) || !naming.test(src)) continue;
|
|
608
|
+
picked.add(p);
|
|
609
|
+
grew = true;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (reads && !grew) return { ...reads, files };
|
|
613
|
+
reads = readsOver(files.filter(([p]) => picked.has(p)), parsed);
|
|
614
|
+
names = [...reads.byName, ...reads.fixed.keys()].filter((n) => !asked.has(n));
|
|
615
|
+
names.forEach((n) => asked.add(n));
|
|
616
|
+
if (!names.length) return { ...reads, files };
|
|
521
617
|
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const DIRECT = new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
621
|
+
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;
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* One file's code without comments and its functions: each one's name, body and where it is, and
|
|
625
|
+
* what its own body reads (`byName`: it passes its first argument on as the collection, with the
|
|
626
|
+
* entry it always reads; `direct`: Astro's functions called with a literal). Only from the file.
|
|
627
|
+
*/
|
|
628
|
+
function parseCode(p, src) {
|
|
629
|
+
const code = stripComments(src);
|
|
630
|
+
const fns = [];
|
|
631
|
+
if (!/\.(ts|mts|js|mjs)$/.test(p)) return { code, fns };
|
|
632
|
+
// Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
|
|
633
|
+
for (const m of code.matchAll(FUNCTION)) {
|
|
634
|
+
const name = m[1] ?? m[3];
|
|
635
|
+
const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
|
|
636
|
+
// The body: a block, or for an arrow the expression up to the end of its statement.
|
|
637
|
+
let at = m.index + m[0].length;
|
|
638
|
+
while (/\s/.test(code[at] ?? "")) at++;
|
|
639
|
+
const block = code.indexOf("{", at);
|
|
640
|
+
const braces = code[at] === "{" ? at : m[1] && block > 0 ? block : -1;
|
|
641
|
+
const body = braces >= 0 ? (braced(code, braces) ?? "") : code.slice(at, code.slice(at).search(/;|\n\s*\n|$/) + at);
|
|
642
|
+
const start = braces >= 0 ? braces + 1 : at;
|
|
643
|
+
// Every reading below names one of Astro's functions: a body that names none is not searched.
|
|
644
|
+
const naming = ASTRO_NAMED.test(body);
|
|
645
|
+
const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
|
|
646
|
+
const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : undefined;
|
|
647
|
+
const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
|
|
648
|
+
fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
|
|
649
|
+
}
|
|
650
|
+
return { code, fns };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** contentReads over `files` (in path order): what their functions read, and their code without comments. */
|
|
654
|
+
function readsOver(files, parsed = new Map()) {
|
|
655
|
+
/** @type {Map<string, string>} */
|
|
656
|
+
const code = new Map();
|
|
522
657
|
const astro = ASTRO_READS.join("|");
|
|
523
658
|
const byName = new Set(ASTRO_READS);
|
|
524
659
|
/** The entry a reading function always reads: `getEntry(collectie, "pagina")` → "pagina". */
|
|
@@ -529,47 +664,38 @@ function contentReads(paths, text) {
|
|
|
529
664
|
const bodies = new Map();
|
|
530
665
|
/** Where each file's helpers have their bodies, [start, end): what a body reads, its callers read. */
|
|
531
666
|
const spans = new Map();
|
|
532
|
-
const DIRECT = new RegExp(`\\b(?:${astro})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
533
667
|
const addFixed = (name, whole, entry) => {
|
|
534
668
|
if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
|
|
535
669
|
if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
|
|
536
670
|
else fixed.get(name).whole.add(whole);
|
|
537
671
|
};
|
|
538
|
-
for (const [p, src] of
|
|
539
|
-
if (
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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;
|
|
672
|
+
for (const [p, src] of files) {
|
|
673
|
+
if (!parsed.has(p)) parsed.set(p, parseCode(p, src));
|
|
674
|
+
const file = parsed.get(p);
|
|
675
|
+
code.set(p, file.code);
|
|
676
|
+
for (const fn of file.fns) {
|
|
551
677
|
if (!spans.has(p)) spans.set(p, []);
|
|
552
|
-
spans.get(p).push([start,
|
|
553
|
-
if (
|
|
554
|
-
byName.add(name);
|
|
555
|
-
|
|
556
|
-
if (entry) entryOf.set(name, entry);
|
|
678
|
+
spans.get(p).push([fn.start, fn.end]);
|
|
679
|
+
if (fn.byName) {
|
|
680
|
+
byName.add(fn.name);
|
|
681
|
+
if (fn.entry) entryOf.set(fn.name, fn.entry);
|
|
557
682
|
}
|
|
558
|
-
bodies.set(name, body);
|
|
559
|
-
for (const
|
|
683
|
+
bodies.set(fn.name, fn.body);
|
|
684
|
+
for (const [whole, entry] of fn.direct) addFixed(fn.name, whole, entry);
|
|
560
685
|
}
|
|
561
686
|
}
|
|
562
687
|
// A helper that calls one of the site's reading functions with a literal reads that content
|
|
563
688
|
// (`getVerlangensOverzicht = () => enkel("verlangensOverzicht", …)`): its entry, else the collection.
|
|
564
689
|
for (const [name, body] of bodies) {
|
|
565
690
|
for (const fn of byName) {
|
|
566
|
-
if (fn === name || ASTRO_READS.includes(fn)) continue;
|
|
691
|
+
if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
|
|
567
692
|
for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
|
|
568
693
|
}
|
|
569
694
|
}
|
|
570
695
|
// A helper that calls a helper reads what that one reads (`getActieAgenda()` → `getActieAgendaTeksten()`).
|
|
571
696
|
// Each body's calls are read once and looked up, not searched for helper by helper.
|
|
572
|
-
|
|
697
|
+
// Nothing read yet: no call can pass anything on.
|
|
698
|
+
const calls = fixed.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : new Map();
|
|
573
699
|
for (let grew = true; grew; ) {
|
|
574
700
|
grew = false;
|
|
575
701
|
for (const [name, called] of calls) {
|
|
@@ -585,8 +711,10 @@ function contentReads(paths, text) {
|
|
|
585
711
|
}
|
|
586
712
|
}
|
|
587
713
|
}
|
|
714
|
+
// The helpers that read, as whole identifiers (as IDENTIFIER would find them), longest first.
|
|
715
|
+
const helpers = fixed.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
|
|
588
716
|
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 };
|
|
717
|
+
return { code, byName, byNameCall, entryOf, fixed, astro, spans, helpers };
|
|
590
718
|
}
|
|
591
719
|
|
|
592
720
|
/** A call: `name(`, not `obj.name(`. */
|
|
@@ -639,8 +767,9 @@ function readsIn(src, reads, path = null) {
|
|
|
639
767
|
}
|
|
640
768
|
// The file's names counted once, and the helpers among them looked up: one pass per file, however
|
|
641
769
|
// many helpers the site has (1,000 pages each with its own took 1.6 s searched one by one).
|
|
770
|
+
// Only the helpers' own names are counted: an identifier that is none of them adds nothing.
|
|
642
771
|
const mentions = new Map();
|
|
643
|
-
for (const [name] of code.matchAll(
|
|
772
|
+
if (reads.helpers) for (const [name] of code.matchAll(reads.helpers)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
|
|
644
773
|
const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
|
|
645
774
|
for (const [name, n] of mentions) {
|
|
646
775
|
const read = reads.fixed.get(name);
|
|
@@ -655,20 +784,30 @@ function readsIn(src, reads, path = null) {
|
|
|
655
784
|
* What the whole site reads, which no page changes: once per set of files, not once per page (20
|
|
656
785
|
* pages each reading a real site's 300 files ran out of an Edge Function's CPU, 26-10). Kept by the import
|
|
657
786
|
* graph, which a registry or a build makes once from the same files.
|
|
658
|
-
* @
|
|
787
|
+
* @typedef {{ collections: Record<string, unknown>, names: Map<string, Set<string>>, readsByFile: Map<string, ReturnType<typeof readsIn>>,
|
|
788
|
+
* counts: { names: Map<string, number>, entries: Map<string, number>, whole: Map<string, number> },
|
|
789
|
+
* byEntry: Map<string, string[]>, byCollection: Map<string, string[]>, namesOf: Map<string, string[]>, routeOf: Map<string, string[]>,
|
|
790
|
+
* isRoute: (f: string) => boolean, jsonOf: Map<string, string[]>, imports: Map<string, string[]>, byName: any }} SiteReads
|
|
791
|
+
* @type {WeakMap<Map<string, Set<string>>, SiteReads>}
|
|
659
792
|
*/
|
|
660
793
|
const siteReadsOf = new WeakMap();
|
|
661
794
|
|
|
662
795
|
function siteReads(paths, text, importers) {
|
|
663
796
|
const kept = siteReadsOf.get(importers);
|
|
664
797
|
if (kept) return kept;
|
|
798
|
+
/** @type {Record<string, unknown>} */
|
|
665
799
|
let collections = {};
|
|
666
800
|
try {
|
|
667
|
-
collections =
|
|
801
|
+
collections = readCollections(text) ?? {};
|
|
668
802
|
} catch {}
|
|
669
803
|
const reads = contentReads(paths, text);
|
|
670
804
|
const readsByFile = new Map();
|
|
671
|
-
|
|
805
|
+
// A file that names no reading function reads nothing (contentReads): its answer without a look.
|
|
806
|
+
for (const [p] of reads.files) {
|
|
807
|
+
if (CONTENT_CONFIG.test(p)) continue;
|
|
808
|
+
const code = reads.code.get(p);
|
|
809
|
+
readsByFile.set(p, code === undefined ? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() } : readsIn(code, reads, p));
|
|
810
|
+
}
|
|
672
811
|
// How many files read each name, entry and collection: "read elsewhere" is the site's count
|
|
673
812
|
// less the page's own files', not a union of every other file made again for each page.
|
|
674
813
|
const counts = { names: new Map(), entries: new Map(), whole: new Map() };
|
|
@@ -1211,6 +1350,7 @@ function matchesPattern(source, path) {
|
|
|
1211
1350
|
* were). Null when there is nothing to write: no file before and nothing in it after.
|
|
1212
1351
|
*/
|
|
1213
1352
|
function changedPageFile(before, change) {
|
|
1353
|
+
/** @type {Record<string, any>} */
|
|
1214
1354
|
let data = {};
|
|
1215
1355
|
try {
|
|
1216
1356
|
data = before == null ? {} : (JSON.parse(before) ?? {});
|
|
@@ -1220,11 +1360,15 @@ function changedPageFile(before, change) {
|
|
|
1220
1360
|
if (!isObject(data)) data = {};
|
|
1221
1361
|
if (!isObject(data.pages)) data.pages = {};
|
|
1222
1362
|
const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
|
|
1223
|
-
|
|
1363
|
+
const folders = isObject(data.folders) ? { ...data.folders } : {};
|
|
1364
|
+
change(data.pages, redirects, folders);
|
|
1224
1365
|
for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
|
|
1366
|
+
for (const [k, v] of Object.entries(folders)) if (!isObject(v) || !v.name) delete folders[k];
|
|
1367
|
+
if (Object.keys(folders).length) data.folders = folders;
|
|
1368
|
+
else delete data.folders;
|
|
1225
1369
|
if (Object.keys(redirects).length) data.redirects = redirects;
|
|
1226
1370
|
else delete data.redirects;
|
|
1227
|
-
const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
|
|
1371
|
+
const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
|
|
1228
1372
|
if (before == null && empty) return null;
|
|
1229
1373
|
const after = `${JSON.stringify(data, null, 2)}\n`;
|
|
1230
1374
|
return after === before ? null : after;
|
|
@@ -1397,7 +1541,8 @@ function routePathAttr(src, router) {
|
|
|
1397
1541
|
* @typedef {{ path: string, content?: string, from?: string, deleted?: true }} PageWrite
|
|
1398
1542
|
* `content`: the file's new text; `from`: the file whose bytes it gets (a move or copy keeps
|
|
1399
1543
|
* 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
|
|
1544
|
+
* @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
|
|
1545
|
+
* @typedef {{ ok: true } | { ok: false, reason: string, detail?: string }} Capability
|
|
1401
1546
|
* @typedef {{ ok: false, reason: string, detail?: string }} PageRefusal
|
|
1402
1547
|
*/
|
|
1403
1548
|
|
|
@@ -1424,6 +1569,8 @@ export function planPage(request, input) {
|
|
|
1424
1569
|
const at = normalisePath(request.path);
|
|
1425
1570
|
const discovered = input.found ?? discover({ framework, paths, text });
|
|
1426
1571
|
const page = discovered.pages.find((p) => p.path === at);
|
|
1572
|
+
// A folder: an address with pages under it and none of its own (docs/plan-folders-and-redirects.md).
|
|
1573
|
+
if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
|
|
1427
1574
|
if (!page) {
|
|
1428
1575
|
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
|
|
1429
1576
|
return template ? no("template", template.path) : no("missing");
|
|
@@ -1453,7 +1600,7 @@ export function planPage(request, input) {
|
|
|
1453
1600
|
const redirectChanges = {};
|
|
1454
1601
|
const collections = (() => {
|
|
1455
1602
|
try {
|
|
1456
|
-
return
|
|
1603
|
+
return readCollections(text);
|
|
1457
1604
|
} catch {
|
|
1458
1605
|
return null;
|
|
1459
1606
|
}
|
|
@@ -1747,7 +1894,9 @@ export function planPage(request, input) {
|
|
|
1747
1894
|
|
|
1748
1895
|
if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
|
|
1749
1896
|
const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
1750
|
-
|
|
1897
|
+
const content = `${JSON.stringify(sorted, null, 2)}\n`;
|
|
1898
|
+
write({ path: COLLECTIONS, content });
|
|
1899
|
+
write({ path: LEGACY_COLLECTIONS, content });
|
|
1751
1900
|
}
|
|
1752
1901
|
const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
1753
1902
|
const message =
|
|
@@ -1755,6 +1904,180 @@ export function planPage(request, input) {
|
|
|
1755
1904
|
return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
|
|
1756
1905
|
}
|
|
1757
1906
|
|
|
1907
|
+
// ── Folders ──
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* The folders of a tree of pages: every address above a page that is no page itself ("/juridisch"
|
|
1911
|
+
* above "/juridisch/[slug]"), sorted. Home is never one.
|
|
1912
|
+
* @param {{ path: string }[]} pages
|
|
1913
|
+
*/
|
|
1914
|
+
export function folderPaths(pages) {
|
|
1915
|
+
const own = new Set(pages.map((p) => p.path));
|
|
1916
|
+
const out = new Set();
|
|
1917
|
+
for (const p of pages) for (let up = parentOf(p.path); up && up !== "/"; up = parentOf(up)) if (!own.has(up)) out.add(up);
|
|
1918
|
+
return [...out].sort();
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/** A Next.js app router folder that is not a segment of the address: a route group `(x)` or a slot `@x`. */
|
|
1922
|
+
const unsegmented = (dir) => /^\(.*\)$|^@/.test(dir.slice(dir.lastIndexOf("/") + 1));
|
|
1923
|
+
|
|
1924
|
+
/**
|
|
1925
|
+
* Where a folder's files are, in the routers that are files: one folder per routes base (Astro's
|
|
1926
|
+
* src/pages, the pages router's pages, the app router's app, a route group there too). Null when a
|
|
1927
|
+
* page under it is not in a file router's folder of that name (React Router, or an odd layout).
|
|
1928
|
+
*/
|
|
1929
|
+
function folderDirs(at, below) {
|
|
1930
|
+
const dirs = new Set();
|
|
1931
|
+
for (const p of below) {
|
|
1932
|
+
if (!p.file) return null;
|
|
1933
|
+
const base = routesBase(p.file);
|
|
1934
|
+
if (!base) return null;
|
|
1935
|
+
if (!base.endsWith("app")) {
|
|
1936
|
+
const dir = `${base}${at}`;
|
|
1937
|
+
if (!p.file.startsWith(`${dir}/`)) return null;
|
|
1938
|
+
dirs.add(dir);
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
// app/(group)/juridisch/x/page.tsx: up from the page's folder, one real segment per part of the address under the folder.
|
|
1942
|
+
let d = dirname(p.file);
|
|
1943
|
+
let n = p.path.slice(at.length + 1).split("/").length;
|
|
1944
|
+
while (n > 0 && d.length > base.length) {
|
|
1945
|
+
if (!unsegmented(d)) n--;
|
|
1946
|
+
d = dirname(d);
|
|
1947
|
+
}
|
|
1948
|
+
while (unsegmented(d) && d.length > base.length) d = dirname(d);
|
|
1949
|
+
if (lastOf(d) !== lastOf(at)) return null;
|
|
1950
|
+
dirs.add(d);
|
|
1951
|
+
}
|
|
1952
|
+
return dirs.size ? [...dirs].sort() : null;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
/**
|
|
1956
|
+
* Renaming a folder: its name in the page file, its address (only its last part: a folder keeps its
|
|
1957
|
+
* place), and every page under it with it, in one plan. In the file routers its folder moves as a
|
|
1958
|
+
* whole, a template and the files its pages keep there too; in React Router each route under it.
|
|
1959
|
+
* Links to anything under it follow; a live folder leaves one redirect for everything under it,
|
|
1960
|
+
* `/old/[...path]` → `/new/[...path]`. `request.live`: any page under it is on Live now.
|
|
1961
|
+
* @returns {PagePlan | PageRefusal}
|
|
1962
|
+
*/
|
|
1963
|
+
function planFolder(request, { framework, paths, text, discovered, importers: given }) {
|
|
1964
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1965
|
+
const at = normalisePath(request.path);
|
|
1966
|
+
if (at === "/") return no("home");
|
|
1967
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1968
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
1969
|
+
const target = request.to == null ? at : normalisePath(request.to);
|
|
1970
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1971
|
+
if (target !== at && (within(target, at) || parentOf(target) !== parentOf(at))) return no("address", target);
|
|
1972
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
1973
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
1974
|
+
if (target !== at && (discovered.pages.some((p) => within(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
|
|
1975
|
+
const live = request.live === true;
|
|
1976
|
+
if (target !== at && live && !kitRedirects({ framework, text })) return no("no_redirects");
|
|
1977
|
+
const have = new Set(paths);
|
|
1978
|
+
/** @type {Map<string, PageWrite>} */
|
|
1979
|
+
const writes = new Map();
|
|
1980
|
+
const write = (w) => writes.set(w.path, w);
|
|
1981
|
+
const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
|
|
1982
|
+
const links = new Set();
|
|
1983
|
+
/** @type {Map<string, string>} old path → new path, of the files that move */
|
|
1984
|
+
const moved = new Map();
|
|
1985
|
+
/** @type {Record<string, string | null>} */
|
|
1986
|
+
const redirectChanges = {};
|
|
1987
|
+
if (target !== at) {
|
|
1988
|
+
if (framework === "vite-react") {
|
|
1989
|
+
// Each route under it, its path's value rewritten; edits per router file from its end, so offsets hold.
|
|
1990
|
+
/** @type {Map<string, { start: number, end: number, value: string }[]>} */
|
|
1991
|
+
const edits = new Map();
|
|
1992
|
+
for (const p of below) {
|
|
1993
|
+
if (!p.router) return no("unparsed", p.path);
|
|
1994
|
+
const src = text(p.router.file) ?? "";
|
|
1995
|
+
const attr = routePathAttr(src, p.router);
|
|
1996
|
+
if (!attr) return no("unparsed", "index route");
|
|
1997
|
+
const next = moveAddress(p.path, at, target);
|
|
1998
|
+
let value;
|
|
1999
|
+
if (attr.value.startsWith("/")) value = `${next}${attr.value.endsWith("/") && next !== "/" ? "/" : ""}`;
|
|
2000
|
+
else {
|
|
2001
|
+
const parent = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
|
|
2002
|
+
// Inside a route that is under the folder itself: that one moves, this one keeps its value.
|
|
2003
|
+
if (under(parent, at)) continue;
|
|
2004
|
+
value = parent === "/" ? next.slice(1) : next.slice(parent.length + 1);
|
|
2005
|
+
}
|
|
2006
|
+
edits.set(p.router.file, [...(edits.get(p.router.file) ?? []), { start: attr.start, end: attr.end, value }]);
|
|
2007
|
+
}
|
|
2008
|
+
for (const [file, list] of edits) {
|
|
2009
|
+
let out = text(file) ?? "";
|
|
2010
|
+
for (const e of [...list].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.value + out.slice(e.end);
|
|
2011
|
+
write({ path: file, content: out });
|
|
2012
|
+
}
|
|
2013
|
+
} else {
|
|
2014
|
+
const dirs = folderDirs(at, below);
|
|
2015
|
+
if (!dirs) return no("unparsed", at);
|
|
2016
|
+
for (const dir of dirs) {
|
|
2017
|
+
const newDir = `${dirname(dir)}/${lastOf(target)}`;
|
|
2018
|
+
for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
|
|
2019
|
+
}
|
|
2020
|
+
for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
2021
|
+
for (const [from, next] of moved) {
|
|
2022
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
2023
|
+
const content = src == null ? null : respecified(src, from, next, moved, have);
|
|
2024
|
+
write(content == null || content === src ? { path: next, from } : { path: next, content });
|
|
2025
|
+
write({ path: from, deleted: true });
|
|
2026
|
+
}
|
|
2027
|
+
const importers = given ?? null;
|
|
2028
|
+
for (const p of paths) {
|
|
2029
|
+
if (moved.has(p) || !CODE.test(p)) continue;
|
|
2030
|
+
if (importers && ![...moved.keys()].some((m) => importers.get(m)?.has(p))) continue;
|
|
2031
|
+
const src = text(p);
|
|
2032
|
+
if (!src) continue;
|
|
2033
|
+
const out = respecified(src, p, p, moved, have);
|
|
2034
|
+
if (out !== src) write({ path: p, content: out });
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
// Every link to anything under it, in code and content.
|
|
2038
|
+
for (const p of paths) {
|
|
2039
|
+
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
2040
|
+
const where = moved.get(p) ?? p;
|
|
2041
|
+
const src = current(where);
|
|
2042
|
+
if (!src) continue;
|
|
2043
|
+
const out = relinked(src, at, target, /\.mdx?$/.test(p));
|
|
2044
|
+
if (out === src) continue;
|
|
2045
|
+
write({ path: where, content: out });
|
|
2046
|
+
if (!moved.has(p)) links.add(where);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn, folders) => {
|
|
2050
|
+
if (target !== at) {
|
|
2051
|
+
for (const key of Object.keys(pages)) {
|
|
2052
|
+
if (!within(key, at)) continue;
|
|
2053
|
+
pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
|
|
2054
|
+
delete pages[key];
|
|
2055
|
+
}
|
|
2056
|
+
for (const key of Object.keys(folders)) {
|
|
2057
|
+
if (!within(key, at)) continue;
|
|
2058
|
+
folders[moveAddress(key, at, target)] = folders[key];
|
|
2059
|
+
delete folders[key];
|
|
2060
|
+
}
|
|
2061
|
+
const before = { ...sendsOn };
|
|
2062
|
+
if (live) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
|
|
2063
|
+
repoint(sendsOn, at, target);
|
|
2064
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
2065
|
+
}
|
|
2066
|
+
if (request.name !== undefined) {
|
|
2067
|
+
const name = request.name ? String(request.name).trim().slice(0, 120) : "";
|
|
2068
|
+
if (name) folders[target] = { name };
|
|
2069
|
+
else delete folders[target];
|
|
2070
|
+
}
|
|
2071
|
+
});
|
|
2072
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
2073
|
+
if (!writes.size) return no("same");
|
|
2074
|
+
const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
2075
|
+
const moves = target === at ? [] : [{ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) }))];
|
|
2076
|
+
const renamed = [...moved].map(([from, to]) => ({ from, to }));
|
|
2077
|
+
const message = target === at ? `Unbase: rename ${at}` : `Unbase: move ${at} to ${target}`;
|
|
2078
|
+
return { ok: true, action: "rename", path: at, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
|
|
2079
|
+
}
|
|
2080
|
+
|
|
1758
2081
|
/**
|
|
1759
2082
|
* What can be done to each page of the code here, and why not (the menu's grey lines): per
|
|
1760
2083
|
* address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
|
|
@@ -1829,7 +2152,18 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
|
|
|
1829
2152
|
}
|
|
1830
2153
|
out[page.path] = { rename, duplicate, delete: remove, under: below.length };
|
|
1831
2154
|
}
|
|
1832
|
-
|
|
2155
|
+
/** @type {Record<string, { rename: Capability, under: number }>} */
|
|
2156
|
+
const folders = {};
|
|
2157
|
+
for (const at of folderPaths(discovered.pages)) {
|
|
2158
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
2159
|
+
let rename = !PAGE_ACTION_FRAMEWORKS.includes(String(framework)) ? no("framework") : !pageFile.ok ? no("invalid") : yes;
|
|
2160
|
+
// A template's addresses are on Live without being listed: a folder with one counts as live.
|
|
2161
|
+
if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no("no_redirects");
|
|
2162
|
+
if (rename.ok && framework === "vite-react" && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
|
|
2163
|
+
if (rename.ok && framework !== "vite-react" && !folderDirs(at, below)) rename = no("unparsed", at);
|
|
2164
|
+
folders[at] = { rename, under: below.length };
|
|
2165
|
+
}
|
|
2166
|
+
return { redirects, actions: out, folders };
|
|
1833
2167
|
}
|
|
1834
2168
|
|
|
1835
2169
|
/**
|
|
@@ -1857,3 +2191,112 @@ export function redirectsFor(framework, pageFile, pagePaths = []) {
|
|
|
1857
2191
|
}
|
|
1858
2192
|
return { list, skipped };
|
|
1859
2193
|
}
|
|
2194
|
+
|
|
2195
|
+
// ── Redirects by hand (docs/plan-folders-and-redirects.md, Part 2) ──
|
|
2196
|
+
|
|
2197
|
+
/**
|
|
2198
|
+
* The redirects the site sets itself, where Unbase can read them, with where each goes and where it
|
|
2199
|
+
* is set: vercel.json's `redirects`, an Astro config's `redirects` literal (a string or `{
|
|
2200
|
+
* destination }`), a Next.js config's literal `{ source, destination }` objects. In the order found.
|
|
2201
|
+
* @returns {{ from: string, to: string, file: string }[]}
|
|
2202
|
+
*/
|
|
2203
|
+
export function siteRedirectList({ framework, text }) {
|
|
2204
|
+
const out = [];
|
|
2205
|
+
try {
|
|
2206
|
+
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
2207
|
+
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) {
|
|
2208
|
+
if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
|
|
2209
|
+
}
|
|
2210
|
+
} catch {}
|
|
2211
|
+
for (const c of CONFIGS[String(framework)] ?? []) {
|
|
2212
|
+
const src = stripComments(text(c) ?? "");
|
|
2213
|
+
if (framework === "astro") {
|
|
2214
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
2215
|
+
if (at < 0) continue;
|
|
2216
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
2217
|
+
const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
|
|
2218
|
+
for (const m of body.matchAll(entry)) out.push({ from: m[1], to: m[2] ?? m[3], file: c });
|
|
2219
|
+
} else if (framework === "next") {
|
|
2220
|
+
for (const m of src.matchAll(/\{[^{}]*\}/g)) {
|
|
2221
|
+
const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
|
|
2222
|
+
const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
|
|
2223
|
+
if (from && to) out.push({ from, to, file: c });
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
return out;
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
/** "/old/…", "/old/*" or "/old/[...path]" → the address and whether everything under it goes along. */
|
|
2231
|
+
function redirectEnd(p) {
|
|
2232
|
+
const s = String(p ?? "").trim();
|
|
2233
|
+
const prefix = /\/(…|\.\.\.|\*)$/.test(s) || REST.test(s);
|
|
2234
|
+
const base = normalisePath(prefix ? s.replace(REST, "").replace(/\/(…|\.\.\.|\*)$/, "") : s);
|
|
2235
|
+
return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
/**
|
|
2239
|
+
* A redirect added, changed or removed by hand, in the page file: the plan of that one write, or why
|
|
2240
|
+
* not. `from` may end in `/…` (or `/*`, `/[...path]`): everything under it, to the same place under
|
|
2241
|
+
* `to`. `was`: the redirect's address before a change. Refused: an address that is a page now
|
|
2242
|
+
* (`page`: the page wins), one already sent on (`exists`), none to change (`missing`), one sent to
|
|
2243
|
+
* itself or into itself (`self`), a loop (`loop`), an address the site's own redirects take
|
|
2244
|
+
* (`redirect_conflict`), and adding without the package that applies them (`no_redirects`). A `to`
|
|
2245
|
+
* that is sent on itself is followed to where it ends, so no chain of hops is made; redirects that
|
|
2246
|
+
* led to `from` lead to `to` too.
|
|
2247
|
+
* @param {{ action: "add" | "change" | "remove", from: string, to?: string, was?: string }} request
|
|
2248
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[] } }} input
|
|
2249
|
+
*/
|
|
2250
|
+
export function planRedirect(request, { framework, paths, text, found }) {
|
|
2251
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2252
|
+
const action = request.action;
|
|
2253
|
+
if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
|
|
2254
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
|
|
2255
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2256
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
2257
|
+
const from = redirectEnd(request.from);
|
|
2258
|
+
const was = request.was != null ? redirectEnd(request.was) : from;
|
|
2259
|
+
if (action !== "add" && !(was.key in pageFile.redirects)) return no("missing", was.key);
|
|
2260
|
+
/** @type {Record<string, string | null>} */
|
|
2261
|
+
const changes = {};
|
|
2262
|
+
let to = null;
|
|
2263
|
+
if (action !== "remove") {
|
|
2264
|
+
if (!kitRedirects({ framework, text })) return no("no_redirects");
|
|
2265
|
+
if (from.base === "/" || !validAddress(from.base)) return no("address", request.from);
|
|
2266
|
+
const end = redirectEnd(request.to);
|
|
2267
|
+
if (!validAddress(end.base)) return no("address", request.to);
|
|
2268
|
+
const discovered = found ?? discover({ framework, paths: paths.filter((p) => !SKIP.test(p)), text });
|
|
2269
|
+
const isPage = (p) => discovered.pages.some((q) => (q.kind === "template" ? templateMatches(q.path, p) : q.path === p));
|
|
2270
|
+
if (from.prefix ? discovered.pages.some((q) => within(q.path, from.base)) : isPage(from.base)) return no("page", from.base);
|
|
2271
|
+
if (from.key !== was.key && from.key in pageFile.redirects) return no("exists", from.key);
|
|
2272
|
+
if (action === "add" && from.key in pageFile.redirects) return no("exists", from.key);
|
|
2273
|
+
const own = [...siteRedirects({ framework, text })].find((s) => sends(s, from.base));
|
|
2274
|
+
if (own) return no("redirect_conflict", own);
|
|
2275
|
+
// Where `to` ends when it is sent on itself: never a chain of hops.
|
|
2276
|
+
let dest = end.base;
|
|
2277
|
+
const others = { ...pageFile.redirects };
|
|
2278
|
+
delete others[was.key];
|
|
2279
|
+
for (let hops = 0; hops < 20; hops++) {
|
|
2280
|
+
const next = Object.entries(others).find(([s]) => !REST.test(s) && s === dest);
|
|
2281
|
+
if (!next) break;
|
|
2282
|
+
dest = next[1];
|
|
2283
|
+
}
|
|
2284
|
+
if (from.prefix ? within(dest, from.base) : dest === from.base) return no(dest === from.base ? "self" : "loop", dest);
|
|
2285
|
+
if (Object.entries(others).some(([s, d]) => d === from.base && s === dest)) return no("loop", dest);
|
|
2286
|
+
to = from.prefix ? `${dest === "/" ? "" : dest}/[...path]` : dest;
|
|
2287
|
+
}
|
|
2288
|
+
const content = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
2289
|
+
const before = { ...sendsOn };
|
|
2290
|
+
delete sendsOn[was.key];
|
|
2291
|
+
if (to !== null) {
|
|
2292
|
+
sendsOn[from.key] = to;
|
|
2293
|
+
// What led to this address leads on to where it now goes, not through it.
|
|
2294
|
+
if (!from.prefix) for (const [s, d] of Object.entries(sendsOn)) if (d === from.base && s !== from.key) sendsOn[s] = to;
|
|
2295
|
+
}
|
|
2296
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) changes[k] = sendsOn[k] ?? null;
|
|
2297
|
+
});
|
|
2298
|
+
if (content === null) return no("same");
|
|
2299
|
+
const shown = (k) => k.replace(REST, "/…");
|
|
2300
|
+
const message = action === "remove" ? `Unbase: remove redirect ${shown(was.key)}` : `Unbase: redirect ${shown(from.key)} to ${shown(to)}`;
|
|
2301
|
+
return { ok: /** @type {const} */ (true), action, from: from.key, to, was: was.key, files: [{ path: PAGE_FILE, content }], redirects: changes, message };
|
|
2302
|
+
}
|