@unbase-app/pages 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/astro.d.mts +7 -0
- package/astro.mjs +3 -2
- package/binding.mjs +97 -7
- package/core.mjs +1148 -198
- package/package.json +2 -2
- package/pages-address.mjs +162 -0
package/core.mjs
CHANGED
|
@@ -5,12 +5,18 @@
|
|
|
5
5
|
// be kept off Live, shared by the build plugins (astro.mjs, vite.mjs, and
|
|
6
6
|
// @unbase-app/next's withUnbase) and by Unbase's backend. Exact copies in
|
|
7
7
|
// supabase/functions/_shared/pages-core.mjs, kit/vite/pages/core.mjs and
|
|
8
|
-
// kit/next/core.mjs; tests fail when
|
|
8
|
+
// kit/next/core.mjs (each with pages-address.mjs beside it); tests fail when
|
|
9
|
+
// they differ.
|
|
9
10
|
//
|
|
10
11
|
// Pure: no file system, no network, no clock. Everything reads the app's files
|
|
11
12
|
// through `text(path)` (paths relative to the app's root) and a list of
|
|
12
13
|
// `paths`, so the same commit always gives the same answer.
|
|
13
14
|
//
|
|
15
|
+
// One adapter per framework (`ADAPTERS`, below; docs/plan-page-engine.md PE4a):
|
|
16
|
+
// every framework-specific step goes through it, and nothing else here names a
|
|
17
|
+
// framework. What an address is (normalising, a name's slug, a pattern's
|
|
18
|
+
// match) is pages-address.mjs, beside this file in every copy.
|
|
19
|
+
//
|
|
14
20
|
// parsePageFile unbase.pages.json, validated
|
|
15
21
|
// deployContext production | preview | development, never from NODE_ENV
|
|
16
22
|
// discover the pages the code makes (Astro, Next.js, React Router, HTML files)
|
|
@@ -19,22 +25,119 @@
|
|
|
19
25
|
// leakPrints text that only a draft page has, to search the output for
|
|
20
26
|
// ============================================================================
|
|
21
27
|
|
|
28
|
+
import { normalisePath, redirectMatches as matchesPattern, slugOf, templateMatches, validAddress } from "./pages-address.mjs";
|
|
29
|
+
|
|
30
|
+
export { dynamicSegment, isPattern, normalisePath, routeTest, slugOf, templateMatches, templateTest, validAddress } from "./pages-address.mjs";
|
|
31
|
+
|
|
22
32
|
export const PAGE_FILE = "unbase.pages.json";
|
|
23
33
|
export const KIT = "@unbase-app/pages";
|
|
24
34
|
|
|
35
|
+
// ── Frameworks: one adapter each (docs/plan-page-engine.md PE4a; ADR-0030) ──
|
|
36
|
+
|
|
25
37
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
38
|
+
* What the core knows of each framework, in one place. Every framework-specific step of the core
|
|
39
|
+
* goes through its adapter; no other code here names a framework. A framework without one gets the
|
|
40
|
+
* honest answer: no pages from its code, no page actions (`framework`), no drafts.
|
|
41
|
+
*
|
|
42
|
+
* kits the packages that bring the kit into its build: the kit itself, the framework's
|
|
43
|
+
* own package that carries it (@unbase-app/astro; @unbase-app/vite, whose `unbase()`
|
|
44
|
+
* is the kit's Vite plugin and comment mode's loader in one; @unbase-app/next, whose
|
|
45
|
+
* `withUnbase` runs this core in a Next.js build), and the kit's name before K5
|
|
46
|
+
* (03-11), which sites installed then still have until they move across
|
|
47
|
+
* configs its build's config files, in the order they are looked for
|
|
48
|
+
* listTools packages that write its page list after the build, from its output (next-sitemap
|
|
49
|
+
* reads Next.js's manifests, where a draft's address still is): the kit cannot clean
|
|
50
|
+
* what they write
|
|
51
|
+
* discover its pages, from its code
|
|
52
|
+
* acts Rename, Duplicate, Delete, New page and redirects are planned for it (planPage)
|
|
53
|
+
* routeLines a page is a route element in a router file (React Router): a move rewrites the
|
|
54
|
+
* route's path, a copy adds a route, a delete takes the route out, and a template is
|
|
55
|
+
* no CMS detail page
|
|
56
|
+
* segments a page is a folder whose special files go with it (Next.js's app router): they keep
|
|
57
|
+
* it from being a draft, and move and go with it
|
|
58
|
+
* configSources the redirect sources its config sets (siteRedirects)
|
|
59
|
+
* configRedirects the redirects its config sets, each with where it goes (siteRedirectList)
|
|
60
|
+
* redirect a page file's redirect in the shape its package applies (redirectsFor); without
|
|
61
|
+
* it, `{ source, destination }`
|
|
62
|
+
* canCreate whether New page has a starter here (createCapability); without it, yes
|
|
63
|
+
* starter New page's starter files (planCreate)
|
|
64
|
+
* destination where a page's file goes when it moves or is copied; without it, the file
|
|
65
|
+
* routers' rule (`destination`)
|
|
66
|
+
* folderDirs where a folder's files are; without it, the file routers' rule (`folderDirs`)
|
|
67
|
+
* links the files whose links follow a move (a site of HTML files: every .html file);
|
|
68
|
+
* without it, the app's code and content
|
|
69
|
+
* relativeLinks its pages link each other by relative URLs (`about.html`, `../`), which follow
|
|
70
|
+
* a move too, and a moved or copied page's own relative URLs are pointed again
|
|
31
71
|
*/
|
|
32
|
-
|
|
33
|
-
astro:
|
|
34
|
-
|
|
35
|
-
|
|
72
|
+
const ADAPTERS = {
|
|
73
|
+
astro: {
|
|
74
|
+
kits: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
|
|
75
|
+
configs: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
|
|
76
|
+
listTools: [],
|
|
77
|
+
discover: (kept) => ({ pages: astroPages(kept), notFound: null }),
|
|
78
|
+
acts: true,
|
|
79
|
+
routeLines: false,
|
|
80
|
+
segments: false,
|
|
81
|
+
configSources: astroConfigSources,
|
|
82
|
+
configRedirects: astroConfigRedirects,
|
|
83
|
+
starter: astroStarter,
|
|
84
|
+
},
|
|
85
|
+
"vite-react": {
|
|
86
|
+
kits: [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
|
|
87
|
+
configs: ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
|
|
88
|
+
listTools: [],
|
|
89
|
+
discover: (kept, text) => reactRouterPages(kept, text),
|
|
90
|
+
acts: true,
|
|
91
|
+
routeLines: true,
|
|
92
|
+
segments: false,
|
|
93
|
+
redirect: ({ prefix, source, base, destBase }) => ({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix }),
|
|
94
|
+
canCreate: (discovered, kept, text) => (siblingRoutes(discovered, text).length ? { ok: true } : { ok: false, reason: "routes_unread" }),
|
|
95
|
+
starter: reactRouterStarter,
|
|
96
|
+
},
|
|
97
|
+
next: {
|
|
98
|
+
kits: ["@unbase-app/next"],
|
|
99
|
+
configs: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
|
|
100
|
+
listTools: ["next-sitemap"],
|
|
101
|
+
discover: (kept) => ({ pages: nextPages(kept), notFound: null }),
|
|
102
|
+
acts: true,
|
|
103
|
+
routeLines: false,
|
|
104
|
+
segments: true,
|
|
105
|
+
configSources: nextConfigSources,
|
|
106
|
+
configRedirects: nextConfigRedirects,
|
|
107
|
+
redirect: ({ prefix, source, destination, base, destBase }) => ({
|
|
108
|
+
source: prefix ? `${base === "/" ? "" : base}/:path*` : source,
|
|
109
|
+
destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination,
|
|
110
|
+
permanent: true,
|
|
111
|
+
}),
|
|
112
|
+
canCreate: (discovered, kept) =>
|
|
113
|
+
discovered.pages.some((p) => p.file && routesBase(p.file)) || kept.some((p) => /^(src\/)?app\/layout\.(tsx|jsx|js|ts)$/.test(p)) ? { ok: true } : { ok: false, reason: "unparsed" },
|
|
114
|
+
starter: nextStarter,
|
|
115
|
+
},
|
|
116
|
+
html: {
|
|
117
|
+
kits: [],
|
|
118
|
+
configs: [],
|
|
119
|
+
listTools: [],
|
|
120
|
+
discover: (kept) => ({ pages: htmlPages(kept), notFound: null }),
|
|
121
|
+
acts: true,
|
|
122
|
+
routeLines: false,
|
|
123
|
+
segments: false,
|
|
124
|
+
destination: (page, to) => htmlDestination(page, to),
|
|
125
|
+
folderDirs: (at, below) => (below.length && below.every((p) => p.file?.startsWith(`${at.slice(1)}/`)) ? [at.slice(1)] : null),
|
|
126
|
+
links: (p) => /\.html?$/.test(p),
|
|
127
|
+
relativeLinks: true,
|
|
128
|
+
canCreate: (discovered) => (discovered.pages.length ? { ok: true } : { ok: false, reason: "unparsed" }),
|
|
129
|
+
starter: htmlStarter,
|
|
130
|
+
},
|
|
36
131
|
};
|
|
37
132
|
|
|
133
|
+
/** A framework's adapter, or null where the core has none (an unknown framework, none detected). */
|
|
134
|
+
export const adapterOf = (framework) => (Object.prototype.hasOwnProperty.call(ADAPTERS, String(framework)) ? ADAPTERS[String(framework)] : null);
|
|
135
|
+
|
|
136
|
+
const FRAMEWORKS = Object.keys(ADAPTERS);
|
|
137
|
+
|
|
138
|
+
/** The packages that bring the kit into each framework's build (the adapters' `kits`). */
|
|
139
|
+
export const KITS = Object.fromEntries(FRAMEWORKS.filter((f) => ADAPTERS[f].kits.length).map((f) => [f, ADAPTERS[f].kits]));
|
|
140
|
+
|
|
38
141
|
/** Frameworks the kit keeps drafts out of: those with a package that brings it (KITS). */
|
|
39
142
|
export const DRAFTABLE = Object.keys(KITS);
|
|
40
143
|
|
|
@@ -45,11 +148,6 @@ const SKIP = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.out
|
|
|
45
148
|
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
46
149
|
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
47
150
|
|
|
48
|
-
/** "about/" → "/about"; "" → "/". */
|
|
49
|
-
export function normalisePath(p) {
|
|
50
|
-
const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
|
|
51
|
-
return s || "/";
|
|
52
|
-
}
|
|
53
151
|
|
|
54
152
|
// ── The page file ──────────────────────────────────────────────────────────
|
|
55
153
|
|
|
@@ -396,8 +494,235 @@ function importedComponents(src) {
|
|
|
396
494
|
return out;
|
|
397
495
|
}
|
|
398
496
|
|
|
497
|
+
/** A call that makes a router or reads routes from route objects: its first argument is their array. */
|
|
498
|
+
const ROUTER_CALL = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/g;
|
|
499
|
+
/** The same, to test a file with (a global regex keeps where its last test stopped). */
|
|
500
|
+
const MAKES_ROUTER = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/;
|
|
501
|
+
const IMPORTS_ROUTER = /from\s*["']react-router(-dom)?["']/;
|
|
502
|
+
|
|
503
|
+
/** The index of the first character after `i` that is no white space. */
|
|
504
|
+
const skipWs = (src, i) => {
|
|
505
|
+
while (i < src.length && /\s/.test(src[i])) i++;
|
|
506
|
+
return i;
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
/** Where the bracket that opens at `i` (`{`, `[` or `(`) closes, strings skipped: the index after it. */
|
|
510
|
+
function closing(src, i) {
|
|
511
|
+
let depth = 0;
|
|
512
|
+
for (let j = i; j < src.length; j++) {
|
|
513
|
+
const c = src[j];
|
|
514
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
515
|
+
j = stringEnd(src, j) - 1;
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (c === "{" || c === "[" || c === "(") depth++;
|
|
519
|
+
else if ((c === "}" || c === "]" || c === ")") && --depth === 0) return j + 1;
|
|
520
|
+
}
|
|
521
|
+
return src.length;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** From `i`, where the value that starts there ends: the next `,` or closing bracket at its own depth. */
|
|
525
|
+
function valueEnd(src, i, end) {
|
|
526
|
+
let depth = 0;
|
|
527
|
+
while (i < end) {
|
|
528
|
+
const c = src[i];
|
|
529
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
530
|
+
i = stringEnd(src, i);
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
if (c === "{" || c === "[" || c === "(") depth++;
|
|
534
|
+
else if (c === "}" || c === "]" || c === ")") {
|
|
535
|
+
if (depth === 0) return i;
|
|
536
|
+
depth--;
|
|
537
|
+
} else if (c === "," && depth === 0) return i;
|
|
538
|
+
i++;
|
|
539
|
+
}
|
|
540
|
+
return i;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** The elements of the array literal that opens at `at` (`[`), each as [start, end) without white space around it. */
|
|
544
|
+
function arrayElements(src, at) {
|
|
545
|
+
const end = closing(src, at) - 1;
|
|
546
|
+
const out = [];
|
|
547
|
+
let i = at + 1;
|
|
548
|
+
while (i < end) {
|
|
549
|
+
i = skipWs(src, i);
|
|
550
|
+
if (i >= end) break;
|
|
551
|
+
if (src[i] === ",") {
|
|
552
|
+
i++;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
const stop = valueEnd(src, i, end);
|
|
556
|
+
let e = stop;
|
|
557
|
+
while (e > i && /\s/.test(src[e - 1])) e--;
|
|
558
|
+
if (e > i) out.push({ start: i, end: src[i] === "{" ? closing(src, i) : e });
|
|
559
|
+
i = stop;
|
|
560
|
+
}
|
|
561
|
+
return out;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** The entries of the object literal that opens at `at` (`{`): each key with where its value is; spreads and shorthands left out. */
|
|
565
|
+
function objectEntries(src, at) {
|
|
566
|
+
const end = closing(src, at) - 1;
|
|
567
|
+
const out = [];
|
|
568
|
+
let i = at + 1;
|
|
569
|
+
while (i < end) {
|
|
570
|
+
i = skipWs(src, i);
|
|
571
|
+
if (i >= end) break;
|
|
572
|
+
if (src[i] === ",") {
|
|
573
|
+
i++;
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
const stop = valueEnd(src, i, end);
|
|
577
|
+
const key = src.slice(i, stop).match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:\s*/);
|
|
578
|
+
if (key) {
|
|
579
|
+
const valueStart = i + key[0].length;
|
|
580
|
+
let e = stop;
|
|
581
|
+
while (e > valueStart && /\s/.test(src[e - 1])) e--;
|
|
582
|
+
out.push({ key: key[2], valueStart, valueEnd: e });
|
|
583
|
+
}
|
|
584
|
+
i = stop;
|
|
585
|
+
}
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** A string literal's value ("…", '…', `…` without `${}`), or false when the text is not one. */
|
|
590
|
+
function literalString(value) {
|
|
591
|
+
const lit = value.trim().match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/);
|
|
592
|
+
return lit ? (lit.slice(1).find((v) => v !== undefined) ?? "") : false;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** Where an array of route objects named `name` is declared in `src` (`const routes = [`, typed or not), or null. */
|
|
596
|
+
function arrayDeclared(src, name) {
|
|
597
|
+
const m = new RegExp(`(?:^|[;\\s])(?:export\\s+)?(?:const|let|var)\\s+${escape(name)}\\s*(?::[^=;]+)?=\\s*`).exec(src);
|
|
598
|
+
if (!m) return null;
|
|
599
|
+
const at = skipWs(src, m.index + m[0].length);
|
|
600
|
+
return src[at] === "[" ? at : null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Where `src`'s default export is an array of route objects (`export default [`, or a name declared as one), or null. */
|
|
604
|
+
function defaultArray(src) {
|
|
605
|
+
const m = src.match(/\bexport\s+default\s+/);
|
|
606
|
+
if (!m) return null;
|
|
607
|
+
const at = skipWs(src, m.index + m[0].length);
|
|
608
|
+
if (src[at] === "[") return at;
|
|
609
|
+
const name = src.slice(at).match(/^([A-Za-z_$][\w$]*)\s*;?/)?.[1];
|
|
610
|
+
return name ? arrayDeclared(src, name) : null;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** How `src` imports `name`: its specifier, and whether as the default or a named export (`exported` the name it has there). */
|
|
614
|
+
function importOf(src, name) {
|
|
615
|
+
for (const m of src.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*["']([^"']+)["']/g)) {
|
|
616
|
+
if (m[1] === name) return { spec: m[3], exported: null };
|
|
617
|
+
for (const part of (m[2] ?? "").split(",")) {
|
|
618
|
+
const [exported, local] = part.trim().split(/\s+as\s+/);
|
|
619
|
+
if ((local ?? exported) === name && exported) return { spec: m[3], exported };
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return null;
|
|
623
|
+
}
|
|
624
|
+
|
|
399
625
|
/**
|
|
400
|
-
*
|
|
626
|
+
* Where the route objects of a site are: per file, the start of each array a router call takes
|
|
627
|
+
* (`createBrowserRouter([...])`, `useRoutes(routes)`), followed to its declaration in the same file
|
|
628
|
+
* or in the module it is imported from. Only files that import react-router(-dom) make a router.
|
|
629
|
+
* @returns {Map<string, number[]>}
|
|
630
|
+
*/
|
|
631
|
+
function routeArrays(paths, text, have) {
|
|
632
|
+
/** @type {Map<string, number[]>} */
|
|
633
|
+
const out = new Map();
|
|
634
|
+
const add = (f, at) => out.set(f, [...new Set([...(out.get(f) ?? []), at])]);
|
|
635
|
+
for (const file of paths) {
|
|
636
|
+
if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
|
|
637
|
+
const raw = text(file);
|
|
638
|
+
if (!raw || !IMPORTS_ROUTER.test(raw) || !MAKES_ROUTER.test(raw)) continue;
|
|
639
|
+
const src = stripComments(raw);
|
|
640
|
+
for (const m of src.matchAll(ROUTER_CALL)) {
|
|
641
|
+
const i = skipWs(src, m.index + m[0].length);
|
|
642
|
+
if (src[i] === "[") {
|
|
643
|
+
add(file, i);
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
const name = src.slice(i).match(/^([A-Za-z_$][\w$]*)\s*[,)]/)?.[1];
|
|
647
|
+
if (!name) continue;
|
|
648
|
+
const local = arrayDeclared(src, name);
|
|
649
|
+
if (local !== null) {
|
|
650
|
+
add(file, local);
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
const imp = importOf(src, name);
|
|
654
|
+
const target = imp ? resolveImport(file, imp.spec, have) : null;
|
|
655
|
+
const other = target ? text(target) : null;
|
|
656
|
+
if (!other) continue;
|
|
657
|
+
const tsrc = stripComments(other);
|
|
658
|
+
const at = imp.exported ? arrayDeclared(tsrc, imp.exported) : defaultArray(tsrc);
|
|
659
|
+
if (at !== null) add(target, at);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* The pages of one array of route objects (`{ path, element: <X />, Component: X, lazy, index,
|
|
667
|
+
* children }`), as JSX routes are read: an index route takes its parent's path, one without a path
|
|
668
|
+
* adds nothing, children nest under their parent's path. Each is traced to the file its component
|
|
669
|
+
* comes from (a default import, React.lazy, or `lazy: () => import(…)`).
|
|
670
|
+
*/
|
|
671
|
+
function routeObjectPages({ file, src, at, parent, have, imports, pages, found }) {
|
|
672
|
+
for (const el of arrayElements(src, at)) {
|
|
673
|
+
if (src[el.start] !== "{") continue; // a spread or a name: not read
|
|
674
|
+
const entries = objectEntries(src, el.start);
|
|
675
|
+
const value = (key) => {
|
|
676
|
+
const e = entries.find((x) => x.key === key);
|
|
677
|
+
return e ? src.slice(e.valueStart, e.valueEnd) : null;
|
|
678
|
+
};
|
|
679
|
+
const index = /^true$/.test((value("index") ?? "").trim());
|
|
680
|
+
const pathValue = value("path");
|
|
681
|
+
const p = pathValue === null ? null : literalString(pathValue);
|
|
682
|
+
const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
|
|
683
|
+
const childrenEntry = entries.find((x) => x.key === "children");
|
|
684
|
+
const childAt = childrenEntry && src[childrenEntry.valueStart] === "[" ? childrenEntry.valueStart : null;
|
|
685
|
+
const children = childAt !== null && arrayElements(src, childAt).length > 0;
|
|
686
|
+
let component = null;
|
|
687
|
+
let importKind = null;
|
|
688
|
+
let target = null;
|
|
689
|
+
let spec = null;
|
|
690
|
+
const comp = (value("Component") ?? "").trim().match(/^([A-Z][\w$]*)$/)?.[1] ?? (value("element") ?? "").trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/)?.[1];
|
|
691
|
+
if (comp) {
|
|
692
|
+
const imported = imports.get(comp);
|
|
693
|
+
if (imported) {
|
|
694
|
+
component = comp;
|
|
695
|
+
importKind = imported.kind;
|
|
696
|
+
target = resolveImport(file, imported.spec, have);
|
|
697
|
+
}
|
|
698
|
+
} else {
|
|
699
|
+
const lazy = (value("lazy") ?? "").match(/import\(\s*(["'])([^"']+)\1\s*\)/);
|
|
700
|
+
if (lazy) {
|
|
701
|
+
spec = lazy[2];
|
|
702
|
+
importKind = "inline";
|
|
703
|
+
target = resolveImport(file, spec, have);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (full === false) pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
|
|
707
|
+
else if (full !== null) {
|
|
708
|
+
if (full === "/*" || full.endsWith("/*") || full === "*") {
|
|
709
|
+
if (full === "/*" && target) found.notFound = target;
|
|
710
|
+
} else {
|
|
711
|
+
/** @type {Page} */
|
|
712
|
+
const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
|
|
713
|
+
if (target && importKind) page.router = { file, start: el.start, end: el.end, component, importKind, object: true, ...(spec ? { spec } : {}) };
|
|
714
|
+
if (children) page.reason = "nested";
|
|
715
|
+
else if (!target) page.reason = "unparsed";
|
|
716
|
+
pages.push(page);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
if (childAt !== null) routeObjectPages({ file, src, at: childAt, parent: typeof full === "string" ? full : parent, have, imports, pages, found });
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* React Router: the JSX `<Route>` elements of every file that imports react-router(-dom), and the
|
|
725
|
+
* route objects its routers are made of (`createBrowserRouter([...])`, `useRoutes(routes)`), with
|
|
401
726
|
* their nesting (an index route takes its parent's path, a layout route without a path adds
|
|
402
727
|
* nothing), each traced to the file its component comes from. `*` is the catch-all (Not Found).
|
|
403
728
|
* @returns {{ pages: Page[], notFound: string | null }}
|
|
@@ -406,11 +731,20 @@ function reactRouterPages(paths, text, only = paths) {
|
|
|
406
731
|
const have = new Set(paths);
|
|
407
732
|
/** @type {Page[]} */
|
|
408
733
|
const pages = [];
|
|
409
|
-
|
|
734
|
+
const found = { notFound: null };
|
|
735
|
+
const arrays = routeArrays(paths, text, have);
|
|
736
|
+
for (const file of only) {
|
|
737
|
+
const starts = arrays.get(file);
|
|
738
|
+
if (!starts?.length) continue;
|
|
739
|
+
const src = stripComments(text(file) ?? "");
|
|
740
|
+
const imports = importedComponents(src);
|
|
741
|
+
for (const at of starts) routeObjectPages({ file, src, at, parent: "", have, imports, pages, found });
|
|
742
|
+
}
|
|
743
|
+
let notFound = found.notFound;
|
|
410
744
|
for (const file of only) {
|
|
411
745
|
if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
|
|
412
746
|
const raw = text(file);
|
|
413
|
-
if (!raw || !raw.includes("<Route") ||
|
|
747
|
+
if (!raw || !raw.includes("<Route") || !IMPORTS_ROUTER.test(raw)) continue;
|
|
414
748
|
const src = stripComments(raw);
|
|
415
749
|
const imports = importedComponents(src);
|
|
416
750
|
/** @type {{ at: number, close?: true }[]} */
|
|
@@ -457,14 +791,28 @@ function reactRouterPages(paths, text, only = paths) {
|
|
|
457
791
|
}
|
|
458
792
|
|
|
459
793
|
/**
|
|
460
|
-
*
|
|
461
|
-
*
|
|
462
|
-
|
|
794
|
+
* Where a route is in its router file, to take it out: a `<Route … />` element as it stands, a route
|
|
795
|
+
* object with the comma after it, so the array stays an array without a hole.
|
|
796
|
+
*/
|
|
797
|
+
function routeSpan(src, router) {
|
|
798
|
+
if (!router.object) return { start: router.start, end: router.end };
|
|
799
|
+
let end = router.end;
|
|
800
|
+
let i = router.end;
|
|
801
|
+
while (i < src.length && (src[i] === " " || src[i] === "\t")) i++;
|
|
802
|
+
if (src[i] === ",") end = i + 1;
|
|
803
|
+
return { start: router.start, end };
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* A router file's `code` without the route (a `<Route … />` element, or a route object) of each
|
|
808
|
+
* address in `drop` that it holds, as discovery found them (the same parser, so what was checked is
|
|
809
|
+
* what goes). `removed` names them; the plugin refuses the build when a draft's route was removed
|
|
810
|
+
* nowhere.
|
|
463
811
|
* @param {{ file: string, code: string, paths: string[], text: (path: string) => string | null, drop: string[] }} input
|
|
464
812
|
*/
|
|
465
813
|
export function removeRoutes({ file, code, paths, text, drop }) {
|
|
466
814
|
const { pages } = reactRouterPages(paths, (p) => (p === file ? code : text(p)), [file]);
|
|
467
|
-
const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
|
|
815
|
+
const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...routeSpan(code, p.router) }));
|
|
468
816
|
spans.sort((a, b) => b.start - a.start);
|
|
469
817
|
let out = code;
|
|
470
818
|
for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
|
|
@@ -478,16 +826,7 @@ export function removeRoutes({ file, code, paths, text, drop }) {
|
|
|
478
826
|
*/
|
|
479
827
|
export function discover({ framework, paths, text }) {
|
|
480
828
|
const kept = paths.filter((p) => !SKIP.test(p));
|
|
481
|
-
const found =
|
|
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 };
|
|
829
|
+
const found = adapterOf(framework)?.discover(kept, text) ?? { pages: [], notFound: null };
|
|
491
830
|
const seen = new Set();
|
|
492
831
|
const pages = found.pages
|
|
493
832
|
.filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
|
|
@@ -959,14 +1298,9 @@ export function mediaGenerators(text) {
|
|
|
959
1298
|
return MEDIA.filter((m) => m in deps);
|
|
960
1299
|
}
|
|
961
1300
|
|
|
962
|
-
/**
|
|
963
|
-
* Packages that write a site's page list after the build, from its output (next-sitemap reads
|
|
964
|
-
* Next.js's manifests, where a draft's address still is): the kit cannot clean what they write.
|
|
965
|
-
*/
|
|
966
|
-
const LIST_TOOLS = { next: ["next-sitemap"] };
|
|
967
|
-
|
|
1301
|
+
/** The packages that write the site's page list after its build (its adapter's `listTools`) that it has. */
|
|
968
1302
|
export function listTools(framework, text) {
|
|
969
|
-
const tools =
|
|
1303
|
+
const tools = adapterOf(framework)?.listTools ?? [];
|
|
970
1304
|
if (!tools.length) return [];
|
|
971
1305
|
let pkg = null;
|
|
972
1306
|
try {
|
|
@@ -1005,7 +1339,9 @@ export function draftCheck(path, { framework, paths, text, found, importers }) {
|
|
|
1005
1339
|
if (page.kind === "template") return no("template", page.path);
|
|
1006
1340
|
if (page.reason) return no(page.reason);
|
|
1007
1341
|
if (!page.file) return no("unparsed");
|
|
1008
|
-
|
|
1342
|
+
// A route object is kept out only by a plugin that reads route objects (OBJECT_ROUTES_SINCE): an older one would not find it.
|
|
1343
|
+
if (page.router?.object && !kitAtLeast({ framework, text }, OBJECT_ROUTES_SINCE)) return no("kit_old", "route objects");
|
|
1344
|
+
if (adapterOf(framework)?.segments) {
|
|
1009
1345
|
const beside = segmentFiles(page.file, paths);
|
|
1010
1346
|
if (beside.length) return no("segment", beside.join(", "));
|
|
1011
1347
|
}
|
|
@@ -1036,13 +1372,6 @@ export function segmentFiles(file, paths) {
|
|
|
1036
1372
|
return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
|
|
1037
1373
|
}
|
|
1038
1374
|
|
|
1039
|
-
/** "/blog/:slug" or "/blog/[slug]" against "/blog/hello". */
|
|
1040
|
-
function templateMatches(template, path) {
|
|
1041
|
-
const t = template.split("/");
|
|
1042
|
-
const p = path.split("/");
|
|
1043
|
-
if (t.at(-1)?.startsWith("[...") || t.at(-1) === "*") return p.length >= t.length - 1 && t.slice(0, -1).every((s, i) => s === p[i] || /^(\[|:)/.test(s));
|
|
1044
|
-
return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
|
|
1045
|
-
}
|
|
1046
1375
|
|
|
1047
1376
|
/**
|
|
1048
1377
|
* Every draft in the page file, checked. `failed` holds the ones a production build cannot keep
|
|
@@ -1066,10 +1395,10 @@ const APP_SOURCE = /^(src|app|pages|components|lib)\//;
|
|
|
1066
1395
|
* anchor or a query) in code or content, other than the page's own files (`own`: its file and the
|
|
1067
1396
|
* content it owns) and its route's `path`. Built at runtime (`/${slug}`) is not found.
|
|
1068
1397
|
*/
|
|
1069
|
-
export function linksTo(path, { paths, text, own = [] }) {
|
|
1398
|
+
export function linksTo(path, { paths, text, own = [], framework = null }) {
|
|
1070
1399
|
if (path === "/") return [];
|
|
1071
1400
|
const mine = new Set(own);
|
|
1072
|
-
return [...(linkIndex(paths, text).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
|
|
1401
|
+
return [...(linkIndex(paths, text, adapterOf(framework)).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
|
|
1073
1402
|
}
|
|
1074
1403
|
|
|
1075
1404
|
/**
|
|
@@ -1077,35 +1406,48 @@ export function linksTo(path, { paths, text, own = [] }) {
|
|
|
1077
1406
|
* not once per page. The same quotes as a search for each address would find: an opening quote, the
|
|
1078
1407
|
* address, an optional trailing slash, anchor or query, and the same quote (the closing one may open
|
|
1079
1408
|
* the next); not a route's own `path` or `pad`.
|
|
1080
|
-
* @type {WeakMap<(path: string) => string | null, { paths: string[], index: Map<string, Set<string>> }
|
|
1409
|
+
* @type {WeakMap<(path: string) => string | null, Record<string, { paths: string[], index: Map<string, Set<string>> }>>}
|
|
1081
1410
|
*/
|
|
1082
1411
|
const linkIndexOf = new WeakMap();
|
|
1083
1412
|
const QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
|
|
1084
1413
|
|
|
1085
|
-
function linkIndex(paths, text) {
|
|
1086
|
-
const
|
|
1414
|
+
function linkIndex(paths, text, adapter = null) {
|
|
1415
|
+
const kind = adapter?.links ? "site" : "app";
|
|
1416
|
+
const kept = linkIndexOf.get(text)?.[kind];
|
|
1087
1417
|
if (kept?.paths === paths) return kept.index;
|
|
1088
1418
|
const index = new Map();
|
|
1419
|
+
const add = (address, p) => {
|
|
1420
|
+
if (!index.has(address)) index.set(address, new Set());
|
|
1421
|
+
index.get(address).add(p);
|
|
1422
|
+
};
|
|
1423
|
+
const linkFile = adapter?.links ?? ((p) => APP_SOURCE.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
|
|
1089
1424
|
for (const p of paths) {
|
|
1090
|
-
if (SKIP.test(p) || !
|
|
1091
|
-
|
|
1425
|
+
if (SKIP.test(p) || !linkFile(p)) continue;
|
|
1426
|
+
const raw = text(p) ?? "";
|
|
1427
|
+
// A code sample in a text names an address without linking it.
|
|
1428
|
+
const src = blankRanges(raw, codeRanges(raw, p));
|
|
1429
|
+
for (const [, , quoted] of src.matchAll(QUOTED_ADDRESS)) {
|
|
1092
1430
|
const bare = quoted.replace(/[#?][\s\S]*$/, "");
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1431
|
+
add(bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare, p);
|
|
1432
|
+
}
|
|
1433
|
+
// A site of HTML files links its pages by relative URLs too.
|
|
1434
|
+
if (adapter?.relativeLinks && /\.html?$/.test(p)) {
|
|
1435
|
+
for (const [, , , url] of src.matchAll(URL_ATTRIBUTE)) {
|
|
1436
|
+
const bare = url.replace(/[#?][\s\S]*$/, "");
|
|
1437
|
+
if (!relativeUrl(url) || !bare) continue;
|
|
1438
|
+
const address = servedAddress(resolvedUrl(dirname(p), bare), bare.endsWith("/"));
|
|
1439
|
+
if (address !== null) add(address, p);
|
|
1440
|
+
}
|
|
1096
1441
|
}
|
|
1097
1442
|
}
|
|
1098
|
-
linkIndexOf.set(text, { paths, index });
|
|
1443
|
+
linkIndexOf.set(text, { ...(linkIndexOf.get(text) ?? {}), [kind]: { paths, index } });
|
|
1099
1444
|
return index;
|
|
1100
1445
|
}
|
|
1101
1446
|
|
|
1102
1447
|
// ── Kit installed ──────────────────────────────────────────────────────────
|
|
1103
1448
|
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
"vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
|
|
1107
|
-
next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
|
|
1108
|
-
};
|
|
1449
|
+
/** Each framework's build config files (the adapters' `configs`). */
|
|
1450
|
+
const CONFIGS = Object.fromEntries(FRAMEWORKS.filter((f) => ADAPTERS[f].configs.length).map((f) => [f, ADAPTERS[f].configs]));
|
|
1109
1451
|
|
|
1110
1452
|
/** The files kitInstalled reads: the package and the build's config, relative to the app. */
|
|
1111
1453
|
export const kitFiles = (framework) => ["package.json", ...(CONFIGS[String(framework)] ?? [])];
|
|
@@ -1237,8 +1579,8 @@ export function withoutInContentMap(json, files) {
|
|
|
1237
1579
|
// a developer's own agent make byte-identical changes. What it cannot do by rule, it refuses with a
|
|
1238
1580
|
// reason; the editor says why, and offers the Operator where it can (`content_bound`).
|
|
1239
1581
|
|
|
1240
|
-
/** Frameworks the actions know how a page is made in. */
|
|
1241
|
-
export const PAGE_ACTION_FRAMEWORKS =
|
|
1582
|
+
/** Frameworks the actions know how a page is made in (the adapters that `act`). */
|
|
1583
|
+
export const PAGE_ACTION_FRAMEWORKS = FRAMEWORKS.filter((f) => ADAPTERS[f].acts);
|
|
1242
1584
|
|
|
1243
1585
|
/** Since which version each package applies the page file's redirects at build. */
|
|
1244
1586
|
export const REDIRECTS_SINCE = { "@unbase-app/pages": "0.4.0", "@unbase-app/astro": "0.3.0", "@unbase-app/vite": "0.3.0", "@unbase-app/next": "0.3.0" };
|
|
@@ -1262,6 +1604,17 @@ const atLeast = (have, want) => {
|
|
|
1262
1604
|
* old address silently.
|
|
1263
1605
|
*/
|
|
1264
1606
|
export function kitRedirects({ framework, text }) {
|
|
1607
|
+
return kitAtLeast({ framework, text }, REDIRECTS_SINCE);
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
/** Since which version each package keeps a route object (`createBrowserRouter([...])`) off Live: the release after 17-11 (PE4b). */
|
|
1611
|
+
export const OBJECT_ROUTES_SINCE = { "@unbase-app/vite": "0.4.0", "@unbase-app/pages": "0.5.0" };
|
|
1612
|
+
|
|
1613
|
+
/**
|
|
1614
|
+
* Whether the kit is installed (kitInstalled) by a package whose range in package.json starts at or
|
|
1615
|
+
* after the version `since` names for it. A range that does not say (a file, a tag) counts as not.
|
|
1616
|
+
*/
|
|
1617
|
+
function kitAtLeast({ framework, text }, since) {
|
|
1265
1618
|
if (!kitInstalled({ framework, text })) return false;
|
|
1266
1619
|
let pkg = null;
|
|
1267
1620
|
try {
|
|
@@ -1270,35 +1623,13 @@ export function kitRedirects({ framework, text }) {
|
|
|
1270
1623
|
const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
|
|
1271
1624
|
return (KITS[String(framework)] ?? []).some((name) => {
|
|
1272
1625
|
const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
|
|
1273
|
-
const
|
|
1626
|
+
const want = since[name];
|
|
1274
1627
|
const have = lowestVersion(spec);
|
|
1275
|
-
return !!
|
|
1628
|
+
return !!want && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(want));
|
|
1276
1629
|
});
|
|
1277
1630
|
}
|
|
1278
1631
|
|
|
1279
|
-
/** "Pricing plans" → "pricing-plans"; "Één agenda" → "een-agenda". */
|
|
1280
|
-
export function slugOf(name) {
|
|
1281
|
-
return String(name)
|
|
1282
|
-
.normalize("NFKD")
|
|
1283
|
-
.replace(/[̀-ͯ]/g, "")
|
|
1284
|
-
.toLowerCase()
|
|
1285
|
-
.replace(/[^a-z0-9]+/g, "-")
|
|
1286
|
-
.replace(/^-+|-+$/g, "")
|
|
1287
|
-
.slice(0, 80);
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
|
|
1291
1632
|
|
|
1292
|
-
/** Whether `p` is an address a page can be given: plain segments, no template, not too long. */
|
|
1293
|
-
export function validAddress(p) {
|
|
1294
|
-
const at = normalisePath(p);
|
|
1295
|
-
if (at.length > 200) return false;
|
|
1296
|
-
if (at === "/") return true;
|
|
1297
|
-
return at
|
|
1298
|
-
.slice(1)
|
|
1299
|
-
.split("/")
|
|
1300
|
-
.every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
|
|
1301
|
-
}
|
|
1302
1633
|
|
|
1303
1634
|
const under = (path, at) => (at === "/" ? path !== "/" : path.startsWith(`${at}/`));
|
|
1304
1635
|
const within = (path, at) => path === at || under(path, at);
|
|
@@ -1314,20 +1645,27 @@ export function siteRedirects({ framework, text }) {
|
|
|
1314
1645
|
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
1315
1646
|
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
|
|
1316
1647
|
} catch {}
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
if (
|
|
1320
|
-
|
|
1321
|
-
if (at < 0) continue;
|
|
1322
|
-
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
1323
|
-
for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
|
|
1324
|
-
} else if (framework === "next") {
|
|
1325
|
-
for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
|
|
1326
|
-
}
|
|
1648
|
+
const adapter = adapterOf(framework);
|
|
1649
|
+
for (const c of adapter?.configs ?? []) {
|
|
1650
|
+
if (!adapter.configSources) continue;
|
|
1651
|
+
for (const source of adapter.configSources(stripComments(text(c) ?? ""))) out.add(normalisePath(source));
|
|
1327
1652
|
}
|
|
1328
1653
|
return out;
|
|
1329
1654
|
}
|
|
1330
1655
|
|
|
1656
|
+
/** The redirect sources an Astro config's `redirects` literal sets. */
|
|
1657
|
+
function astroConfigSources(src) {
|
|
1658
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
1659
|
+
if (at < 0) return [];
|
|
1660
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
1661
|
+
return [...body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)].map((m) => m[1]);
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
/** The redirect sources a Next.js config's literal `source`s set. */
|
|
1665
|
+
function nextConfigSources(src) {
|
|
1666
|
+
return [...src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)].map((m) => m[1]);
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1331
1669
|
/** Whether a redirect source (a page file's or the site's) takes `path`. */
|
|
1332
1670
|
function sends(source, path) {
|
|
1333
1671
|
if (REST.test(source)) {
|
|
@@ -1337,11 +1675,6 @@ function sends(source, path) {
|
|
|
1337
1675
|
return source === path || matchesPattern(source, path);
|
|
1338
1676
|
}
|
|
1339
1677
|
|
|
1340
|
-
function matchesPattern(source, path) {
|
|
1341
|
-
if (!/\[|:/.test(source)) return false;
|
|
1342
|
-
const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => (i % 2 ? (part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+") : escape(part))).join("")}$`);
|
|
1343
|
-
return re.test(path);
|
|
1344
|
-
}
|
|
1345
1678
|
|
|
1346
1679
|
// ── Writing the page file ──
|
|
1347
1680
|
|
|
@@ -1443,8 +1776,56 @@ function respecified(src, was, now, moves, have) {
|
|
|
1443
1776
|
const QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
|
|
1444
1777
|
const MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
|
|
1445
1778
|
|
|
1446
|
-
/**
|
|
1447
|
-
|
|
1779
|
+
/**
|
|
1780
|
+
* Where `src` (the text of `file`) shows code rather than links: in Markdown and MDX its fenced
|
|
1781
|
+
* blocks and inline code; in HTML, Astro and MDX its `<pre>` and `<code>` elements. An address in
|
|
1782
|
+
* there is an example in a text (AstroWind's `getPermalink('/about')` in a blog post), not a link.
|
|
1783
|
+
* @returns {[number, number][]}
|
|
1784
|
+
*/
|
|
1785
|
+
function codeRanges(src, file) {
|
|
1786
|
+
/** @type {[number, number][]} */
|
|
1787
|
+
const out = [];
|
|
1788
|
+
if (/\.mdx?$/.test(file)) {
|
|
1789
|
+
let at = 0;
|
|
1790
|
+
let open = null;
|
|
1791
|
+
let start = 0;
|
|
1792
|
+
for (const line of src.split("\n")) {
|
|
1793
|
+
const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
|
|
1794
|
+
if (!open && fence) {
|
|
1795
|
+
open = fence[1];
|
|
1796
|
+
start = at;
|
|
1797
|
+
} else if (open && fence && fence[1][0] === open[0] && fence[1].length >= open.length && !line.slice(fence[0].length).trim()) {
|
|
1798
|
+
out.push([start, at + line.length]);
|
|
1799
|
+
open = null;
|
|
1800
|
+
}
|
|
1801
|
+
at += line.length + 1;
|
|
1802
|
+
}
|
|
1803
|
+
if (open) out.push([start, src.length]);
|
|
1804
|
+
for (const m of blankRanges(src, out).matchAll(/(`+)(?!`)(.+?)(?<!`)\1(?!`)/g)) out.push([m.index, m.index + m[0].length]);
|
|
1805
|
+
}
|
|
1806
|
+
if (/\.(html?|astro|mdx)$/.test(file)) for (const m of src.matchAll(/<(pre|code)\b[\s\S]*?<\/\1\s*>/gi)) out.push([m.index, m.index + m[0].length]);
|
|
1807
|
+
return out.sort((a, b) => a[0] - b[0]);
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
/** `src` with `change` applied to its text outside `ranges` only (each [start, end), in order). */
|
|
1811
|
+
function outside(src, ranges, change) {
|
|
1812
|
+
if (!ranges.length) return change(src);
|
|
1813
|
+
let out = "";
|
|
1814
|
+
let at = 0;
|
|
1815
|
+
for (const [start, end] of ranges) {
|
|
1816
|
+
if (end <= at) continue;
|
|
1817
|
+
out += change(src.slice(at, Math.max(at, start))) + src.slice(Math.max(at, start), end);
|
|
1818
|
+
at = end;
|
|
1819
|
+
}
|
|
1820
|
+
return out + change(src.slice(at));
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
/**
|
|
1824
|
+
* `src`, the text of `file`, with every address in `from` (or under it) moved to `to`; anchors,
|
|
1825
|
+
* queries and a trailing slash kept. Code samples in it stay as they are (`codeRanges`).
|
|
1826
|
+
*/
|
|
1827
|
+
function relinked(src, from, to, file) {
|
|
1828
|
+
const markdown = /\.mdx?$/.test(file);
|
|
1448
1829
|
const swap = (address) => {
|
|
1449
1830
|
const bare = address.replace(/[#?][\s\S]*$/, "");
|
|
1450
1831
|
const tail = address.slice(bare.length);
|
|
@@ -1454,11 +1835,16 @@ function relinked(src, from, to, markdown) {
|
|
|
1454
1835
|
if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
|
|
1455
1836
|
return address;
|
|
1456
1837
|
};
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1838
|
+
return outside(src, codeRanges(src, file), (piece) => {
|
|
1839
|
+
let out = piece.replace(QUOTED, (m, q, address) => `${q}${swap(address)}`);
|
|
1840
|
+
if (markdown) out = out.replace(MD_LINK, (m, a, address, b) => `${a}${swap(address)}${b}`);
|
|
1841
|
+
return out;
|
|
1842
|
+
});
|
|
1460
1843
|
}
|
|
1461
1844
|
|
|
1845
|
+
/** The files whose links follow a move, as the site's adapter says: by default the app's code and content, not its content config. */
|
|
1846
|
+
const linkFileOf = (adapter) => adapter?.links ?? ((p) => APP_SOURCE.test(p) && !CONTENT_CONFIG.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
|
|
1847
|
+
|
|
1462
1848
|
/** `src` with the inside of its string literals blanked, offsets kept: names in code, not in text. */
|
|
1463
1849
|
function blankStrings(src) {
|
|
1464
1850
|
let out = "";
|
|
@@ -1506,6 +1892,137 @@ function destination(page, to, discovered) {
|
|
|
1506
1892
|
return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
|
|
1507
1893
|
}
|
|
1508
1894
|
|
|
1895
|
+
/**
|
|
1896
|
+
* A site of HTML files: where a page at `to` has its file. An address that ends in `.html` is that
|
|
1897
|
+
* file (`/voorwaarden.html`); any other is a folder's index (`/shop` → `shop/index.html`), as the site
|
|
1898
|
+
* is served. A folder's index moves with its folder (its pages and files under it); a folder with
|
|
1899
|
+
* pages under it never becomes one file. Null when it cannot.
|
|
1900
|
+
*/
|
|
1901
|
+
function htmlDestination(page, to) {
|
|
1902
|
+
const folder = /(^|\/)index\.html?$/.test(page.file);
|
|
1903
|
+
const dir = folder ? dirname(page.file) : page.file;
|
|
1904
|
+
if (to.endsWith(".html") || to.endsWith(".htm")) {
|
|
1905
|
+
if (folder) return null;
|
|
1906
|
+
return { file: to.slice(1), dir, newDir: to.slice(1), folder: false };
|
|
1907
|
+
}
|
|
1908
|
+
return { file: `${to.slice(1)}/index.html`, dir, newDir: to.slice(1), folder };
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/** A URL attribute in HTML, with the URL it holds. */
|
|
1912
|
+
const URL_ATTRIBUTE = /(\s(?:href|src|action|poster)\s*=\s*)(["'])([^"']*)\2/gi;
|
|
1913
|
+
|
|
1914
|
+
/** A URL relative to the page it is on (`about.html`, `../`, `img/a.png`): no scheme, no root, no anchor or query alone, no template. */
|
|
1915
|
+
const relativeUrl = (url) => !!url && !/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?|\{|\$)/i.test(url);
|
|
1916
|
+
|
|
1917
|
+
/** A relative URL's path from the folder `dir` (no leading slash), `..` and `.` resolved; "" is the site's root. */
|
|
1918
|
+
function resolvedUrl(dir, url) {
|
|
1919
|
+
const segments = dir ? dir.split("/") : [];
|
|
1920
|
+
for (const s of url.split("/")) {
|
|
1921
|
+
if (s === "..") segments.pop();
|
|
1922
|
+
else if (s && s !== ".") segments.push(s);
|
|
1923
|
+
}
|
|
1924
|
+
return segments.join("/");
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
/**
|
|
1928
|
+
* The page address a site of HTML files serves a resolved URL path at, or null when it is a file
|
|
1929
|
+
* of another kind (a stylesheet, a picture): `x.html` is `/x.html`, `x/` and `x/index.html` are `/x`.
|
|
1930
|
+
*/
|
|
1931
|
+
function servedAddress(path, slash) {
|
|
1932
|
+
if (path === "" || path === "index.html" || path === "index.htm") return "/";
|
|
1933
|
+
if (/\/index\.html?$/.test(path)) return `/${path.replace(/\/index\.html?$/, "")}`;
|
|
1934
|
+
if (slash || /\.html?$/.test(path) || !/\.[a-z0-9]+$/i.test(path.split("/").pop() ?? "")) return `/${path}`;
|
|
1935
|
+
return null;
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
/** The relative URL from the folder `dir` to `target` (a path; ending in `/` for a folder, "" the root). */
|
|
1939
|
+
function relativeTo(dir, target) {
|
|
1940
|
+
const from = dir ? dir.split("/") : [];
|
|
1941
|
+
const folder = target === "" || target.endsWith("/");
|
|
1942
|
+
const parts = target.replace(/\/$/, "").split("/").filter(Boolean);
|
|
1943
|
+
const tdir = folder ? parts : parts.slice(0, -1);
|
|
1944
|
+
const base = folder ? "" : (parts.at(-1) ?? "");
|
|
1945
|
+
let i = 0;
|
|
1946
|
+
while (i < from.length && i < tdir.length && from[i] === tdir[i]) i++;
|
|
1947
|
+
const rest = tdir.slice(i);
|
|
1948
|
+
const out = `${"../".repeat(from.length - i)}${rest.length ? `${rest.join("/")}/` : ""}${base}`;
|
|
1949
|
+
return out || "./";
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/**
|
|
1953
|
+
* An HTML file's `src`, which was at `was` and is now at `now`, with its relative URLs pointed again:
|
|
1954
|
+
* a page `change` moved (`{ from, to }`, or anything under it) is linked at its new address in the
|
|
1955
|
+
* same form (a file, a folder, a folder's `index.html`), a file that moved (`moved`: old path → new
|
|
1956
|
+
* path) at its new path, and every other relative URL from the file's new folder. Unchanged URLs keep
|
|
1957
|
+
* their text.
|
|
1958
|
+
*/
|
|
1959
|
+
function htmlRelinked(src, was, now, change, moved) {
|
|
1960
|
+
return src.replace(URL_ATTRIBUTE, (m, lead, q, url) => {
|
|
1961
|
+
if (!relativeUrl(url)) return m;
|
|
1962
|
+
const bare = url.replace(/[#?][\s\S]*$/, "");
|
|
1963
|
+
if (!bare) return m;
|
|
1964
|
+
const tail = url.slice(bare.length);
|
|
1965
|
+
const slash = bare.endsWith("/");
|
|
1966
|
+
const path = resolvedUrl(dirname(was), bare);
|
|
1967
|
+
let target = null;
|
|
1968
|
+
const address = servedAddress(path, slash);
|
|
1969
|
+
if (change && address !== null && (address === change.from || under(address, change.from))) {
|
|
1970
|
+
const next = moveAddress(address, change.from, change.to);
|
|
1971
|
+
const index = /(^|\/)index\.html?$/.test(path);
|
|
1972
|
+
if (next.endsWith(".html") || next.endsWith(".htm")) target = next.slice(1);
|
|
1973
|
+
else if (index) target = next === "/" ? "index.html" : `${next.slice(1)}/index.html`;
|
|
1974
|
+
else target = next === "/" ? "" : `${next.slice(1)}/`;
|
|
1975
|
+
if (!slash && !index && !target.endsWith("/") && !/\.html?$/.test(target)) target = target.replace(/\/$/, "");
|
|
1976
|
+
} else if (moved?.has(path)) target = moved.get(path);
|
|
1977
|
+
else if (was === now) return m;
|
|
1978
|
+
else target = slash && path ? `${path}/` : path;
|
|
1979
|
+
const next = relativeTo(dirname(now), target);
|
|
1980
|
+
return next === bare ? m : `${lead}${q}${next}${tail}${q}`;
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
/**
|
|
1985
|
+
* New page's starter on a site of HTML files: its own page's shell (the home page's, else its first
|
|
1986
|
+
* page's): its head with the name as title and no description of another page, its header and
|
|
1987
|
+
* footer and scripts kept, and a `<main>` with the name as its heading in place of the content. At
|
|
1988
|
+
* `/x.html` a file, at any other address a folder's `index.html`; its relative URLs from there.
|
|
1989
|
+
*/
|
|
1990
|
+
function htmlStarter({ discovered, text, target, name, segments, files, fileTaken, no }) {
|
|
1991
|
+
const shellPage = discovered.pages.find((p) => p.path === "/") ?? discovered.pages.find((p) => p.file);
|
|
1992
|
+
const shell = shellPage ? text(shellPage.file) : null;
|
|
1993
|
+
if (!shell) return no("unparsed");
|
|
1994
|
+
const file = /\.html?$/.test(target) ? target.slice(1) : `${segments}/index.html`;
|
|
1995
|
+
if (fileTaken(file)) return no("taken", file);
|
|
1996
|
+
const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1997
|
+
const h1 = mostClass(discovered.pages.map((p) => text(p.file) ?? ""), "h1", "class");
|
|
1998
|
+
const heading = `<h1${h1 ? ` class="${esc(h1)}"` : ""}>${esc(name)}</h1>`;
|
|
1999
|
+
let out = shell;
|
|
2000
|
+
out = /<title\b[^>]*>[\s\S]*?<\/title>/i.test(out) ? out.replace(/(<title\b[^>]*>)[\s\S]*?(<\/title>)/i, `$1${esc(name)}$2`) : out.replace(/(\s*)<\/head>/i, `$1 <title>${esc(name)}</title>$1</head>`);
|
|
2001
|
+
out = out.replace(/[ \t]*<meta\s[^>]*name\s*=\s*["']description["'][^>]*>[ \t]*\r?\n?/i, "");
|
|
2002
|
+
const indentAt = (i) => out.slice(out.lastIndexOf("\n", i - 1) + 1, i).match(/^[ \t]*/)?.[0] ?? "";
|
|
2003
|
+
const main = /(<main\b[^>]*>)([\s\S]*?)(<\/main>)/i.exec(out);
|
|
2004
|
+
if (main) {
|
|
2005
|
+
const indent = indentAt(main.index);
|
|
2006
|
+
out = `${out.slice(0, main.index)}${main[1]}\n${indent} ${heading}\n${indent}${main[3]}${out.slice(main.index + main[0].length)}`;
|
|
2007
|
+
} else {
|
|
2008
|
+
const body = /(<body\b[^>]*>)([\s\S]*?)(<\/body>)/i.exec(out);
|
|
2009
|
+
if (!body) return no("unparsed");
|
|
2010
|
+
const inner = body[2];
|
|
2011
|
+
const header = /<header\b[\s\S]*?<\/header>/i.exec(inner);
|
|
2012
|
+
const footer = /<footer\b[\s\S]*?<\/footer>/i.exec(inner);
|
|
2013
|
+
const indent = inner.match(/\n([ \t]*)\S/)?.[1] ?? " ";
|
|
2014
|
+
// What stands between its header and its footer (all of the body where it has neither) gives way; its scripts stay.
|
|
2015
|
+
const start = header ? header.index + header[0].length : 0;
|
|
2016
|
+
const end = footer ? footer.index : inner.length;
|
|
2017
|
+
const scripts = [...inner.slice(start, end).matchAll(/<script\b[\s\S]*?<\/script>/gi)].map((m) => m[0]);
|
|
2018
|
+
const block = ["<main>", ` ${heading}`, "</main>", ...scripts].map((l) => `${indent}${l}`).join("\n");
|
|
2019
|
+
const head = header ? inner.slice(0, start) : "";
|
|
2020
|
+
const tail = footer ? `\n${indent}${inner.slice(end)}` : (inner.match(/\s*$/)?.[0] ?? "\n");
|
|
2021
|
+
out = `${out.slice(0, body.index)}${body[1]}${head}\n${block}${tail}${body[3]}${out.slice(body.index + body[0].length)}`;
|
|
2022
|
+
}
|
|
2023
|
+
files.push({ path: file, content: htmlRelinked(out, shellPage.file, file, null, null) });
|
|
2024
|
+
}
|
|
2025
|
+
|
|
1509
2026
|
/** Next.js app router files beside a page that are its own, not a route of their own: everything in its folder but the folders of other routes. */
|
|
1510
2027
|
function appSegmentOwn(dir, paths) {
|
|
1511
2028
|
return paths.filter((p) => {
|
|
@@ -1525,8 +2042,19 @@ const componentName = (address) =>
|
|
|
1525
2042
|
.join("")
|
|
1526
2043
|
.replace(/^(\d)/, "Page$1") || "Page";
|
|
1527
2044
|
|
|
1528
|
-
/** The route
|
|
2045
|
+
/** The route's `path` (a route element's attribute, a route object's own entry) and where its value sits in `src`, or null. */
|
|
1529
2046
|
function routePathAttr(src, router) {
|
|
2047
|
+
if (router.object) {
|
|
2048
|
+
// Its own entry only, at its top level: a child's `path` is the child's.
|
|
2049
|
+
const clean = stripComments(src);
|
|
2050
|
+
const entry = objectEntries(clean, router.start).find((e) => e.key === "path");
|
|
2051
|
+
if (!entry) return null;
|
|
2052
|
+
const raw = src.slice(entry.valueStart, entry.valueEnd);
|
|
2053
|
+
const value = literalString(raw);
|
|
2054
|
+
if (value === false) return null;
|
|
2055
|
+
const start = entry.valueStart + 1;
|
|
2056
|
+
return { value, start, end: start + value.length };
|
|
2057
|
+
}
|
|
1530
2058
|
const tag = src.slice(router.start, router.end);
|
|
1531
2059
|
const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
|
|
1532
2060
|
if (!m) return null;
|
|
@@ -1535,6 +2063,38 @@ function routePathAttr(src, router) {
|
|
|
1535
2063
|
return { value, start: valueAt, end: valueAt + value.length };
|
|
1536
2064
|
}
|
|
1537
2065
|
|
|
2066
|
+
/**
|
|
2067
|
+
* A router file's `src` with a copy of `router`'s route right after it: its path's value `value`, its
|
|
2068
|
+
* component `name` from `file`, whose import goes beside the original's (`original`) in the same
|
|
2069
|
+
* form. A route object comes after the original with a comma between them; one whose own
|
|
2070
|
+
* `lazy: () => import(…)` loads its page points at `file` instead of a new import.
|
|
2071
|
+
* @returns {{ ok: true, code: string } | PageRefusal}
|
|
2072
|
+
*/
|
|
2073
|
+
function routeCopy({ src, router, routerFile, attr, value, name, file, original }) {
|
|
2074
|
+
let tag = src.slice(router.start, attr.start) + value + src.slice(attr.end, router.end);
|
|
2075
|
+
let statement = null;
|
|
2076
|
+
let added = null;
|
|
2077
|
+
if (router.importKind === "inline") {
|
|
2078
|
+
tag = tag.replace(/(import\(\s*)(["'])([^"']+)\2/, (m, lead, q, spec) => `${lead}${q}${specFor(routerFile, file, spec, original)}${q}`);
|
|
2079
|
+
} else {
|
|
2080
|
+
const comp = router.component;
|
|
2081
|
+
statement =
|
|
2082
|
+
router.importKind === "lazy"
|
|
2083
|
+
? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
|
|
2084
|
+
: src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
|
|
2085
|
+
if (!statement) return { ok: false, reason: "unparsed", detail: "its import" };
|
|
2086
|
+
added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(routerFile, file, spec, original)}${q}`);
|
|
2087
|
+
tag = tag.replace(new RegExp(`(<|\\{\\s*|Component\\s*:\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
|
|
2088
|
+
}
|
|
2089
|
+
const indent = src.slice(src.lastIndexOf("\n", router.start) + 1, router.start).match(/^\s*/)?.[0] ?? "";
|
|
2090
|
+
let out = `${src.slice(0, router.end)}${router.object ? "," : ""}\n${indent}${tag}${src.slice(router.end)}`;
|
|
2091
|
+
if (statement) {
|
|
2092
|
+
const lineEnd = statement.index + statement[0].length;
|
|
2093
|
+
out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
|
|
2094
|
+
}
|
|
2095
|
+
return { ok: true, code: out };
|
|
2096
|
+
}
|
|
2097
|
+
|
|
1538
2098
|
// ── The plan ──
|
|
1539
2099
|
|
|
1540
2100
|
/**
|
|
@@ -1547,7 +2107,8 @@ function routePathAttr(src, router) {
|
|
|
1547
2107
|
*/
|
|
1548
2108
|
|
|
1549
2109
|
/**
|
|
1550
|
-
* What one action does to a site's code, or why it cannot: `
|
|
2110
|
+
* What one action does to a site's code, or why it cannot: `create` (a new page by rule, planCreate),
|
|
2111
|
+
* `rename` (to a new address, with a new
|
|
1551
2112
|
* name), `duplicate` (a copy at `to`, by default the first free `<address>-copy`) or `delete`
|
|
1552
2113
|
* (visitors to the old address sent to `redirect`, by default the page above it; null: Not
|
|
1553
2114
|
* Found). `live` says whether the page is on Live now: only then does a rename or delete leave a
|
|
@@ -1555,19 +2116,27 @@ function routePathAttr(src, router) {
|
|
|
1555
2116
|
*
|
|
1556
2117
|
* `paths` are every file of the app (a move takes files whose text was not read along);
|
|
1557
2118
|
* `text` gives the code and content files' text.
|
|
1558
|
-
*
|
|
1559
|
-
*
|
|
2119
|
+
*
|
|
2120
|
+
* `details` are the templates a CMS gives each of its items an address with (the collection's
|
|
2121
|
+
* detail page: docs/plan-cms-detail-page.md, decision 8), by address, each with the files that
|
|
2122
|
+
* stay whatever reads them (`keep`: the CMS's items). Such a template can be deleted, nothing else:
|
|
2123
|
+
* its file goes, and the content only it reads, never an item. `addresses` are its pages on Live
|
|
2124
|
+
* then (one per item), each sent on as a deleted page's own address is.
|
|
2125
|
+
* @param {{ action: "rename" | "duplicate" | "delete" | "create", path: string, to?: string, name?: string | null, redirect?: string | null, live?: boolean, drafts?: boolean, addresses?: string[] }} request
|
|
2126
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>>, details?: Record<string, { keep?: string[] }> }} input
|
|
1560
2127
|
* @returns {PagePlan | PageRefusal}
|
|
1561
2128
|
*/
|
|
1562
2129
|
export function planPage(request, input) {
|
|
1563
2130
|
const { framework, text } = input;
|
|
2131
|
+
const adapter = adapterOf(framework);
|
|
1564
2132
|
const paths = input.paths.filter((p) => !SKIP.test(p));
|
|
1565
2133
|
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1566
2134
|
const action = request.action;
|
|
1567
|
-
if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
|
|
1568
|
-
if (!
|
|
2135
|
+
if (!["rename", "duplicate", "delete", "create"].includes(action)) return no("invalid", action);
|
|
2136
|
+
if (!adapter?.acts) return no("framework");
|
|
1569
2137
|
const at = normalisePath(request.path);
|
|
1570
2138
|
const discovered = input.found ?? discover({ framework, paths, text });
|
|
2139
|
+
if (action === "create") return planCreate(request, { framework, paths, text, discovered });
|
|
1571
2140
|
const page = discovered.pages.find((p) => p.path === at);
|
|
1572
2141
|
// A folder: an address with pages under it and none of its own (docs/plan-folders-and-redirects.md).
|
|
1573
2142
|
if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
|
|
@@ -1575,7 +2144,9 @@ export function planPage(request, input) {
|
|
|
1575
2144
|
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
|
|
1576
2145
|
return template ? no("template", template.path) : no("missing");
|
|
1577
2146
|
}
|
|
1578
|
-
|
|
2147
|
+
// A CMS collection's detail page: Delete only, in a file router (`details`).
|
|
2148
|
+
const detail = page.kind === "template" && action === "delete" && !adapter?.routeLines ? (input.details?.[at] ?? null) : null;
|
|
2149
|
+
if (page.kind === "template" && !detail) return no("template", page.path);
|
|
1579
2150
|
if (!page.file || page.reason === "unparsed") return no("unparsed");
|
|
1580
2151
|
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1581
2152
|
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
@@ -1613,12 +2184,13 @@ export function planPage(request, input) {
|
|
|
1613
2184
|
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1614
2185
|
if (target !== at && within(target, at)) return no("address", target);
|
|
1615
2186
|
if (target !== at && taken(target)) return no("taken", target);
|
|
1616
|
-
|
|
2187
|
+
// Route objects: the published Vite plugin adds redirect routes to a JSX `<Routes>` only (PE5 teaches it objects).
|
|
2188
|
+
if (target !== at && live && (!redirects || page.router?.object)) return no("no_redirects", page.router?.object ? "route objects" : undefined);
|
|
1617
2189
|
to = target;
|
|
1618
2190
|
/** @type {Map<string, string>} old path → new path, of the files that move */
|
|
1619
2191
|
const moved = new Map();
|
|
1620
2192
|
if (target !== at) {
|
|
1621
|
-
if (
|
|
2193
|
+
if (adapter?.routeLines) {
|
|
1622
2194
|
// The route's own path, when it is relative to a parent route: its last part only.
|
|
1623
2195
|
const src = text(page.router.file) ?? "";
|
|
1624
2196
|
const attr = routePathAttr(src, page.router);
|
|
@@ -1630,7 +2202,7 @@ export function planPage(request, input) {
|
|
|
1630
2202
|
write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
|
|
1631
2203
|
}
|
|
1632
2204
|
} else {
|
|
1633
|
-
const dest = destination(page, target, discovered);
|
|
2205
|
+
const dest = (adapter?.destination ?? destination)(page, target, discovered);
|
|
1634
2206
|
if (!dest) return no("unparsed");
|
|
1635
2207
|
// Its file, and everything in its folder: the pages under it, and what they keep there.
|
|
1636
2208
|
for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
|
|
@@ -1651,14 +2223,17 @@ export function planPage(request, input) {
|
|
|
1651
2223
|
if (out !== src) write({ path: p, content: out });
|
|
1652
2224
|
}
|
|
1653
2225
|
}
|
|
1654
|
-
// Every link to it, or under it, in code and content (route files' own `pad` too)
|
|
2226
|
+
// Every link to it, or under it, in code and content (route files' own `pad` too); not the
|
|
2227
|
+
// content config, which defines schemas (an address there is an example in a message).
|
|
2228
|
+
const linkFile = linkFileOf(adapter);
|
|
1655
2229
|
for (const p of paths) {
|
|
1656
|
-
|
|
1657
|
-
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
2230
|
+
if (!linkFile(p)) continue;
|
|
1658
2231
|
const where = moved.get(p) ?? p;
|
|
1659
2232
|
const src = current(where);
|
|
1660
2233
|
if (!src) continue;
|
|
1661
|
-
|
|
2234
|
+
let out = relinked(src, at, target, p);
|
|
2235
|
+
// A site of HTML files links by relative URLs too: those follow, and a moved file's own are pointed again.
|
|
2236
|
+
if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at, to: target }, moved);
|
|
1662
2237
|
if (out === src) continue;
|
|
1663
2238
|
write({ path: where, content: out });
|
|
1664
2239
|
if (!moved.has(p)) links.add(where);
|
|
@@ -1693,7 +2268,7 @@ export function planPage(request, input) {
|
|
|
1693
2268
|
}
|
|
1694
2269
|
|
|
1695
2270
|
if (action === "duplicate") {
|
|
1696
|
-
if (
|
|
2271
|
+
if (adapter?.routeLines && page.reason === "nested") return no("nested");
|
|
1697
2272
|
let target;
|
|
1698
2273
|
if (request.to != null) {
|
|
1699
2274
|
target = normalisePath(request.to);
|
|
@@ -1765,7 +2340,7 @@ export function planPage(request, input) {
|
|
|
1765
2340
|
}
|
|
1766
2341
|
return out;
|
|
1767
2342
|
};
|
|
1768
|
-
if (
|
|
2343
|
+
if (adapter?.routeLines) {
|
|
1769
2344
|
const router = page.router.file;
|
|
1770
2345
|
const src = current(router) ?? "";
|
|
1771
2346
|
const attr = routePathAttr(src, page.router);
|
|
@@ -1776,31 +2351,20 @@ export function planPage(request, input) {
|
|
|
1776
2351
|
const file = freeFile(dirname(page.file), name, ext);
|
|
1777
2352
|
const original = text(page.file) ?? "";
|
|
1778
2353
|
write({ path: file, content: rebind(respecified(original, page.file, file, new Map([[page.file, file]]), have)) });
|
|
1779
|
-
// Its import, beside the original's, in the same form.
|
|
1780
|
-
const comp = page.router.component;
|
|
1781
|
-
const statement =
|
|
1782
|
-
page.router.importKind === "lazy"
|
|
1783
|
-
? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
|
|
1784
|
-
: src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
|
|
1785
|
-
if (!statement) return no("unparsed", "its import");
|
|
1786
|
-
const added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(router, file, spec, page.file)}${q}`);
|
|
2354
|
+
// Its import, beside the original's, in the same form; a route object's own `lazy: () => import(…)` points at the copy instead.
|
|
1787
2355
|
const value = attr.value.startsWith("/") ? target : (() => {
|
|
1788
2356
|
const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
|
|
1789
2357
|
return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
|
|
1790
2358
|
})();
|
|
1791
2359
|
if (value === null) return no("unparsed", "a route inside another route keeps its parent");
|
|
1792
|
-
const
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
let out = `${src.slice(0, at1)}\n${indent}${newTag}${src.slice(at1)}`;
|
|
1796
|
-
const lineEnd = statement.index + statement[0].length;
|
|
1797
|
-
out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
|
|
1798
|
-
write({ path: router, content: out });
|
|
2360
|
+
const added = routeCopy({ src, router: page.router, routerFile: router, attr, value, name, file, original: page.file });
|
|
2361
|
+
if (!added.ok) return added;
|
|
2362
|
+
write({ path: router, content: added.code });
|
|
1799
2363
|
} else {
|
|
1800
|
-
const dest = destination(page, target, discovered);
|
|
2364
|
+
const dest = (adapter?.destination ?? destination)(page, target, discovered);
|
|
1801
2365
|
if (!dest) return no("unparsed");
|
|
1802
2366
|
// A Next.js app router page brings what its folder keeps for it; Home's folder is the whole app's.
|
|
1803
|
-
const along =
|
|
2367
|
+
const along = adapter?.segments && routesBase(page.file).endsWith("app") && at !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
|
|
1804
2368
|
const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
|
|
1805
2369
|
for (const next of moved.values()) if (have.has(next)) return no("taken", next);
|
|
1806
2370
|
for (const [from, next] of moved) {
|
|
@@ -1811,6 +2375,7 @@ export function planPage(request, input) {
|
|
|
1811
2375
|
}
|
|
1812
2376
|
let out = respecified(src, from, next, moved, have);
|
|
1813
2377
|
if (from === page.file) out = rebind(out);
|
|
2378
|
+
if (adapter?.relativeLinks && /\.html?$/.test(from)) out = htmlRelinked(out, from, next, null, moved);
|
|
1814
2379
|
write(out === src ? { path: next, from } : { path: next, content: out });
|
|
1815
2380
|
}
|
|
1816
2381
|
}
|
|
@@ -1836,23 +2401,25 @@ export function planPage(request, input) {
|
|
|
1836
2401
|
if (action === "delete") {
|
|
1837
2402
|
if (at === "/") return no("home");
|
|
1838
2403
|
if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
|
|
2404
|
+
// Its addresses that visitors know: its own, or a detail page's, one per item on Live.
|
|
2405
|
+
const gone = detail ? [...new Set((request.addresses ?? []).map(normalisePath))].filter((p) => templateMatches(at, p)).sort() : [at];
|
|
1839
2406
|
let target = null;
|
|
1840
|
-
if (live && request.redirect !== null) {
|
|
2407
|
+
if (live && gone.length && request.redirect !== null) {
|
|
1841
2408
|
if (request.redirect !== undefined) {
|
|
1842
2409
|
target = normalisePath(request.redirect);
|
|
1843
|
-
if (within(target, at) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
|
|
2410
|
+
if (within(target, at) || gone.includes(target) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
|
|
1844
2411
|
} else {
|
|
1845
2412
|
for (let p = parentOf(at); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
|
|
1846
2413
|
target = target ?? "/";
|
|
1847
2414
|
}
|
|
1848
|
-
if (!redirects) return no("no_redirects");
|
|
2415
|
+
if (!redirects || page.router?.object) return no("no_redirects", page.router?.object ? "route objects" : undefined);
|
|
1849
2416
|
}
|
|
1850
2417
|
to = target;
|
|
1851
|
-
if (
|
|
2418
|
+
if (adapter?.routeLines) {
|
|
1852
2419
|
const router = page.router.file;
|
|
1853
2420
|
const src = current(router) ?? "";
|
|
1854
|
-
// Its route element, and its line when nothing else is on it.
|
|
1855
|
-
let { start, end } = page.router;
|
|
2421
|
+
// Its route (an element, or an object with its comma), and its line when nothing else is on it.
|
|
2422
|
+
let { start, end } = routeSpan(src, page.router);
|
|
1856
2423
|
const lineStart = src.lastIndexOf("\n", start - 1) + 1;
|
|
1857
2424
|
const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
|
|
1858
2425
|
if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
|
|
@@ -1861,32 +2428,45 @@ export function planPage(request, input) {
|
|
|
1861
2428
|
}
|
|
1862
2429
|
let out = src.slice(0, start) + src.slice(end);
|
|
1863
2430
|
const comp = page.router.component;
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
|
|
1867
|
-
if (uses <= 1) {
|
|
1868
|
-
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");
|
|
1869
|
-
out = out.replace(re, "");
|
|
2431
|
+
if (page.router.importKind === "inline") {
|
|
2432
|
+
// Loaded by its route object alone: its file goes when nothing else imports it.
|
|
1870
2433
|
if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
|
|
2434
|
+
} else {
|
|
2435
|
+
// Its import goes when nothing else in the file names it.
|
|
2436
|
+
const rest = blankStrings(stripComments(out));
|
|
2437
|
+
const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
|
|
2438
|
+
if (uses <= 1) {
|
|
2439
|
+
const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
|
|
2440
|
+
out = out.replace(re, "");
|
|
2441
|
+
if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
|
|
2442
|
+
}
|
|
1871
2443
|
}
|
|
1872
2444
|
write({ path: router, content: out });
|
|
1873
2445
|
} else {
|
|
1874
2446
|
const dir = dirname(page.file);
|
|
1875
|
-
const files =
|
|
2447
|
+
const files = adapter?.segments && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
|
|
1876
2448
|
for (const f of files) write({ path: f, deleted: true });
|
|
1877
2449
|
}
|
|
2450
|
+
// A detail page's items are the CMS's: they stay, whatever reads them now (`keep`).
|
|
2451
|
+
const keep = new Set(detail?.keep ?? []);
|
|
1878
2452
|
const content = ownedContent(page, { paths, text, importers });
|
|
1879
|
-
|
|
2453
|
+
const owned = content.files.filter((f) => !keep.has(f));
|
|
2454
|
+
for (const f of owned) {
|
|
1880
2455
|
write({ path: f, deleted: true });
|
|
1881
2456
|
if (collectionsAfter) delete collectionsAfter[f];
|
|
1882
2457
|
}
|
|
1883
|
-
for (const f of linksTo(at, { paths, text, own: [page.file, ...
|
|
2458
|
+
for (const f of linksTo(at, { paths, text, own: [page.file, ...owned], framework })) unlinked.add(f);
|
|
2459
|
+
/** A redirect's end that was this page: its address, or one of a detail page's. */
|
|
2460
|
+
const was = (d) => d === at || (!!detail && templateMatches(at, d));
|
|
1884
2461
|
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1885
|
-
delete pages[
|
|
2462
|
+
for (const key of Object.keys(pages)) if (was(key)) delete pages[key];
|
|
1886
2463
|
const before = { ...sendsOn };
|
|
1887
|
-
if (target)
|
|
1888
|
-
|
|
1889
|
-
|
|
2464
|
+
if (target) {
|
|
2465
|
+
for (const p of gone) sendsOn[p] = target;
|
|
2466
|
+
for (const p of gone) repoint(sendsOn, p, target);
|
|
2467
|
+
// Those that led to an item no visitor has now lead where its visitors go.
|
|
2468
|
+
if (detail) for (const [s, d] of Object.entries(sendsOn)) if (was(d)) s === target ? delete sendsOn[s] : (sendsOn[s] = target);
|
|
2469
|
+
} else for (const [s, d] of Object.entries(sendsOn)) if (was(d)) delete sendsOn[s];
|
|
1890
2470
|
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1891
2471
|
});
|
|
1892
2472
|
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
@@ -1904,6 +2484,358 @@ export function planPage(request, input) {
|
|
|
1904
2484
|
return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
|
|
1905
2485
|
}
|
|
1906
2486
|
|
|
2487
|
+
// ── New page (docs/plan-page-engine.md, PE3: New page without AI) ──
|
|
2488
|
+
|
|
2489
|
+
/** The class `tag` has most often in `sources` (`class=` in Astro, `className=` in JSX), kept by `keep`; null when none. */
|
|
2490
|
+
function mostClass(sources, tag, attr, keep = () => true) {
|
|
2491
|
+
const count = new Map();
|
|
2492
|
+
for (const src of sources) {
|
|
2493
|
+
for (const m of src.matchAll(new RegExp(`<${tag}\\b[^>]*\\s${attr}="([^"{]+)"`, "g"))) {
|
|
2494
|
+
const c = m[1].trim();
|
|
2495
|
+
if (c && keep(c)) count.set(c, (count.get(c) ?? 0) + 1);
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
return [...count].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0]?.[0] ?? null;
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
/** A page's width: the class that holds it (a container, max-w-…, mx-auto), not a band's colour. */
|
|
2502
|
+
const holdsWidth = (c) => /(^|\s)(container|wrap|wrapper|inner|max-w-\S+|mx-auto)(\s|$)/.test(c);
|
|
2503
|
+
|
|
2504
|
+
/** A JavaScript string literal for `s`: a name goes into code as data, never as code. */
|
|
2505
|
+
const literal = (s) => JSON.stringify(String(s));
|
|
2506
|
+
|
|
2507
|
+
/**
|
|
2508
|
+
* The routes a new React Router page can stand beside: parsed, self-closing, with a `path` of
|
|
2509
|
+
* their own, so a copy of the tag is a route of the same kind (its wrappers and its parent route).
|
|
2510
|
+
*/
|
|
2511
|
+
function siblingRoutes(discovered, text) {
|
|
2512
|
+
return discovered.pages.filter((p) => {
|
|
2513
|
+
if (p.kind !== "route" || p.reason || !p.router || !p.file) return false;
|
|
2514
|
+
const attr = routePathAttr(text(p.router.file) ?? "", p.router);
|
|
2515
|
+
return !!attr && attr.value !== "*" && !attr.value.endsWith("/*");
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
/**
|
|
2520
|
+
* Whether New page can make a page here without the Operator, and if not why: a framework the
|
|
2521
|
+
* rule has no starter for (`framework`), a page file that is not valid (`invalid`), a React
|
|
2522
|
+
* Router site whose routes Unbase can't read (`routes_unread`: route objects, a path from a
|
|
2523
|
+
* constant), or a Next.js site without a pages folder Unbase knows (`unparsed`).
|
|
2524
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null } }} input
|
|
2525
|
+
* @returns {Capability}
|
|
2526
|
+
*/
|
|
2527
|
+
export function createCapability({ framework, paths, text, found }) {
|
|
2528
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2529
|
+
const adapter = adapterOf(framework);
|
|
2530
|
+
if (!adapter?.acts) return no("framework");
|
|
2531
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2532
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
2533
|
+
const kept = paths.filter((p) => !SKIP.test(p));
|
|
2534
|
+
const discovered = found ?? discover({ framework, paths: kept, text });
|
|
2535
|
+
return adapter.canCreate?.(discovered, kept, text) ?? { ok: true };
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
/**
|
|
2539
|
+
* How a React Router page wraps itself, read from its source: a Layout component it renders, else the header and footer it
|
|
2540
|
+
* renders inside its outer element (Lovable's shape), each with its import line; nothing else.
|
|
2541
|
+
*/
|
|
2542
|
+
function wrapOfPage(src) {
|
|
2543
|
+
const imports = [...src.matchAll(/^import\s+(?:([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?|\{([^}]*)\})\s+from\s+["']([^"']+)["'];?[^\n]*$/gm)].map((m) => ({
|
|
2544
|
+
line: m[0],
|
|
2545
|
+
names: [m[1], ...(m[2] ?? m[3] ?? "").split(",").map((x) => x.trim().split(/\s+as\s+/).pop())].filter(Boolean),
|
|
2546
|
+
}));
|
|
2547
|
+
const used = (n) => new RegExp(`<${escape(n)}[\\s/>]`).test(src);
|
|
2548
|
+
const names = imports.flatMap((i) => i.names);
|
|
2549
|
+
const lineOf = (n) => imports.find((i) => i.names.includes(n))?.line;
|
|
2550
|
+
const layout = names.find((n) => /Layout$/.test(n) && used(n)) ?? null;
|
|
2551
|
+
if (layout) return { key: `layout:${lineOf(layout)}`, layout, header: null, footer: null, outer: null, imports: [lineOf(layout)] };
|
|
2552
|
+
const header = names.find((n) => /^(Header|Navbar|NavBar|Nav|Navigation|SiteHeader)$/.test(n) && used(n)) ?? null;
|
|
2553
|
+
const footer = names.find((n) => /^(Footer|SiteFooter)$/.test(n) && used(n)) ?? null;
|
|
2554
|
+
if (!header && !footer) return { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
|
|
2555
|
+
const outer = src.match(/return\s*\(\s*<([a-z][\w-]*)((?:\s+className="[^"]*")?)\s*>/);
|
|
2556
|
+
const imports2 = [...new Set([header, footer].filter(Boolean).map(lineOf))];
|
|
2557
|
+
const outerTag = outer ? `${outer[1]}${outer[2]}` : null;
|
|
2558
|
+
return { key: `chrome:${imports2.join("|")}:${outerTag}`, layout: null, header, footer, outer: outerTag, imports: imports2 };
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
/** The wrapping most of `sources` share (a tie goes to one that wraps). */
|
|
2562
|
+
function wrapOfPages(sources) {
|
|
2563
|
+
const seen = new Map();
|
|
2564
|
+
for (const src of sources) {
|
|
2565
|
+
const w = wrapOfPage(src);
|
|
2566
|
+
const had = seen.get(w.key) ?? { n: 0, w };
|
|
2567
|
+
had.n++;
|
|
2568
|
+
seen.set(w.key, had);
|
|
2569
|
+
}
|
|
2570
|
+
const best = [...seen.values()].sort((a, b) => b.n - a.n || (a.w.key === "none" ? 1 : b.w.key === "none" ? -1 : 0))[0];
|
|
2571
|
+
return best?.w ?? { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
|
|
2572
|
+
}
|
|
2573
|
+
|
|
2574
|
+
/**
|
|
2575
|
+
* New page's starter on Astro: a page in src/pages in the layout most of its pages import (a title
|
|
2576
|
+
* prop, or AstroWind's `metadata`), else a page of its own (planCreate). A refusal, or nothing when
|
|
2577
|
+
* its files are in `files`.
|
|
2578
|
+
*/
|
|
2579
|
+
function astroStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
|
|
2580
|
+
const own = discovered.pages.filter((p) => p.file && p.file.startsWith("src/pages/") && p.file.endsWith(".astro"));
|
|
2581
|
+
const sources = own.map((p) => text(p.file) ?? "");
|
|
2582
|
+
// The layout most of its pages import, by where it is, with how they name it.
|
|
2583
|
+
const layouts = new Map();
|
|
2584
|
+
own.forEach((p, i) => {
|
|
2585
|
+
for (const m of sources[i].matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']*layouts?\/[^"']+\.astro)["']/g)) {
|
|
2586
|
+
const spec = m[2];
|
|
2587
|
+
const abs = spec.startsWith(".") ? joinRelative(dirname(p.file), spec) : spec.replace(/^[@~]\//, "src/").replace(/^@layouts\//, "src/layouts/");
|
|
2588
|
+
const seen = layouts.get(abs) ?? { n: 0, local: m[1], alias: spec.startsWith(".") ? null : spec };
|
|
2589
|
+
seen.n++;
|
|
2590
|
+
layouts.set(abs, seen);
|
|
2591
|
+
}
|
|
2592
|
+
});
|
|
2593
|
+
const best = [...layouts].sort((a, b) => b[1].n - a[1].n || (a[0] < b[0] ? -1 : 1))[0];
|
|
2594
|
+
// A folder of that name with pages in it: the page is its index.
|
|
2595
|
+
const file = paths.some((p) => p.startsWith(`src/pages/${segments}/`)) ? `src/pages/${segments}/index.astro` : `src/pages/${segments}.astro`;
|
|
2596
|
+
if (fileTaken(file)) return no("taken", file);
|
|
2597
|
+
const h1 = mostClass(sources, "h1", "class");
|
|
2598
|
+
const box = mostClass(sources, "(?:main|section|div)", "class", holdsWidth);
|
|
2599
|
+
const heading = `<h1${h1 ? ` class=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
|
|
2600
|
+
const body = [`<main${box ? ` class=${literal(box)}` : ""}>`, ` ${heading}`, "</main>"];
|
|
2601
|
+
let src;
|
|
2602
|
+
if (best) {
|
|
2603
|
+
const [abs, use] = best;
|
|
2604
|
+
const layoutSrc = text(abs) ?? "";
|
|
2605
|
+
const tag = /^[A-Z]/.test(use.local) ? use.local : "Layout";
|
|
2606
|
+
const spec = use.alias ?? relativeSpec(file, abs);
|
|
2607
|
+
// Its props as the layout names them: a title, or AstroWind's `metadata` object.
|
|
2608
|
+
const metadata = /\bmetadata\b/.test(layoutSrc) && !/\btitle\s*[?:]/.test(layoutSrc);
|
|
2609
|
+
const props = metadata ? " metadata={metadata}" : /\btitle\b/.test(layoutSrc) ? ` title={${literal(name)}}` : "";
|
|
2610
|
+
const front = [`import ${tag} from ${literal(spec)};`, ...(metadata ? [`const metadata = { title: ${literal(name)} };`] : [])];
|
|
2611
|
+
src = ["---", ...front, "---", "", `<${tag}${props}>`, ...body.map((l) => ` ${l}`), `</${tag}>`, ""].join("\n");
|
|
2612
|
+
} else {
|
|
2613
|
+
src = [
|
|
2614
|
+
"---",
|
|
2615
|
+
`const title = ${literal(name)};`,
|
|
2616
|
+
"---",
|
|
2617
|
+
"",
|
|
2618
|
+
`<html lang="en">`,
|
|
2619
|
+
" <head>",
|
|
2620
|
+
` <meta charset="utf-8" />`,
|
|
2621
|
+
` <meta name="viewport" content="width=device-width" />`,
|
|
2622
|
+
" <title>{title}</title>",
|
|
2623
|
+
" </head>",
|
|
2624
|
+
" <body>",
|
|
2625
|
+
...body.map((l) => ` ${l}`),
|
|
2626
|
+
" </body>",
|
|
2627
|
+
"</html>",
|
|
2628
|
+
"",
|
|
2629
|
+
].join("\n");
|
|
2630
|
+
}
|
|
2631
|
+
files.push({ path: file, content: src });
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
/**
|
|
2635
|
+
* New page's starter on Next.js: a page in the app router whose metadata title is the name, so the
|
|
2636
|
+
* root layout wraps it; in the pages router where the site has only that (planCreate).
|
|
2637
|
+
*/
|
|
2638
|
+
function nextStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
|
|
2639
|
+
const own = discovered.pages.filter((p) => p.file && routesBase(p.file));
|
|
2640
|
+
const sources = own.map((p) => text(p.file) ?? "");
|
|
2641
|
+
const inApp = own.find((p) => routesBase(p.file).endsWith("app"));
|
|
2642
|
+
const inPages = own.find((p) => !routesBase(p.file).endsWith("app"));
|
|
2643
|
+
// The app router where the site has one (an app with only its root layout too), else the pages router.
|
|
2644
|
+
const appBase = inApp ? routesBase(inApp.file) : paths.some((p) => /^src\/app\/layout\./.test(p)) ? "src/app" : paths.some((p) => /^app\/layout\./.test(p)) ? "app" : null;
|
|
2645
|
+
const pagesBase = inPages ? routesBase(inPages.file) : null;
|
|
2646
|
+
const exts = own.map((p) => p.file.slice(p.file.lastIndexOf("."))).filter((e) => /^\.(tsx|jsx|js)$/.test(e));
|
|
2647
|
+
const ext = exts.includes(".tsx") || !exts.length ? ".tsx" : exts.includes(".jsx") ? ".jsx" : ".js";
|
|
2648
|
+
const typed = ext === ".tsx";
|
|
2649
|
+
const h1 = mostClass(sources, "h1", "className");
|
|
2650
|
+
const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
|
|
2651
|
+
const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
|
|
2652
|
+
if (appBase) {
|
|
2653
|
+
const file = `${appBase}/${segments}/page${ext}`;
|
|
2654
|
+
if (fileTaken(file)) return no("taken", file);
|
|
2655
|
+
const lines = [
|
|
2656
|
+
...(typed ? [`import type { Metadata } from "next";`, ""] : []),
|
|
2657
|
+
`export const metadata${typed ? ": Metadata" : ""} = { title: ${literal(name)} };`,
|
|
2658
|
+
"",
|
|
2659
|
+
"export default function Page() {",
|
|
2660
|
+
" return (",
|
|
2661
|
+
` <main${box ? ` className=${literal(box)}` : ""}>`,
|
|
2662
|
+
` ${heading}`,
|
|
2663
|
+
" </main>",
|
|
2664
|
+
" );",
|
|
2665
|
+
"}",
|
|
2666
|
+
"",
|
|
2667
|
+
];
|
|
2668
|
+
files.push({ path: file, content: lines.join("\n") });
|
|
2669
|
+
} else if (pagesBase) {
|
|
2670
|
+
const file = paths.some((p) => p.startsWith(`${pagesBase}/${segments}/`)) ? `${pagesBase}/${segments}/index${ext}` : `${pagesBase}/${segments}${ext}`;
|
|
2671
|
+
if (fileTaken(file)) return no("taken", file);
|
|
2672
|
+
const lines = [
|
|
2673
|
+
`import Head from "next/head";`,
|
|
2674
|
+
"",
|
|
2675
|
+
"export default function Page() {",
|
|
2676
|
+
" return (",
|
|
2677
|
+
" <>",
|
|
2678
|
+
" <Head>",
|
|
2679
|
+
` <title>{${literal(name)}}</title>`,
|
|
2680
|
+
" </Head>",
|
|
2681
|
+
` <main${box ? ` className=${literal(box)}` : ""}>`,
|
|
2682
|
+
` ${heading}`,
|
|
2683
|
+
" </main>",
|
|
2684
|
+
" </>",
|
|
2685
|
+
" );",
|
|
2686
|
+
"}",
|
|
2687
|
+
"",
|
|
2688
|
+
];
|
|
2689
|
+
files.push({ path: file, content: lines.join("\n") });
|
|
2690
|
+
} else return no("unparsed");
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
/**
|
|
2694
|
+
* New page's starter on React Router: a component beside another page's, its import, and a
|
|
2695
|
+
* `<Route>` beside that page's route, wrapped as that page is (planCreate).
|
|
2696
|
+
*/
|
|
2697
|
+
function reactRouterStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
|
|
2698
|
+
// The route it stands beside: one under the same parent first, else one at the top, else any that can hold it.
|
|
2699
|
+
const siblings = siblingRoutes(discovered, text);
|
|
2700
|
+
const parent = parentOf(target);
|
|
2701
|
+
const placement = (p) => {
|
|
2702
|
+
const src = text(p.router.file) ?? "";
|
|
2703
|
+
const attr = routePathAttr(src, p.router);
|
|
2704
|
+
if (!attr) return null;
|
|
2705
|
+
if (attr.value.startsWith("/")) return { src, attr, value: target };
|
|
2706
|
+
const base = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
|
|
2707
|
+
if (base !== "/" && !under(target, base)) return null;
|
|
2708
|
+
return { src, attr, value: base === "/" ? target.slice(1) : target.slice(base.length + 1) };
|
|
2709
|
+
};
|
|
2710
|
+
const ranked = [...siblings.filter((p) => parentOf(p.path) === parent), ...siblings.filter((p) => parentOf(p.path) === "/"), ...siblings];
|
|
2711
|
+
const sibling = ranked.find((p) => placement(p));
|
|
2712
|
+
if (!sibling) return no("routes_unread");
|
|
2713
|
+
const { src, attr, value } = placement(sibling);
|
|
2714
|
+
const router = sibling.router.file;
|
|
2715
|
+
let comp = componentName(target);
|
|
2716
|
+
for (let n = 2; new RegExp(`(?<![\\w$])${comp}(?![\\w$])`).test(src) && n < 100; n++) comp = `${componentName(target)}${n}`;
|
|
2717
|
+
const ext = sibling.file.slice(sibling.file.lastIndexOf("."));
|
|
2718
|
+
let file = `${dirname(sibling.file)}/${comp}${ext}`;
|
|
2719
|
+
for (let n = 2; fileTaken(file) && n < 100; n++) file = `${dirname(sibling.file)}/${comp}${n}${ext}`;
|
|
2720
|
+
// Wrapped as most pages in its folder are: a Layout component, else their header and footer inside their own outer element.
|
|
2721
|
+
const wrap = wrapOfPages(siblings.filter((p) => dirname(p.file) === dirname(sibling.file)).map((p) => text(p.file) ?? ""));
|
|
2722
|
+
const sources = siblings.map((p) => text(p.file) ?? "");
|
|
2723
|
+
const h1 = mostClass(sources, "h1", "className");
|
|
2724
|
+
const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
|
|
2725
|
+
const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
|
|
2726
|
+
const main = (indent) => [`${indent}<main${box ? ` className=${literal(box)}` : ""}>`, `${indent} ${heading}`, `${indent}</main>`];
|
|
2727
|
+
let jsx;
|
|
2728
|
+
const wrapImports = wrap.imports;
|
|
2729
|
+
if (wrap.layout) jsx = [` <${wrap.layout}>`, ...main(" "), ` </${wrap.layout}>`];
|
|
2730
|
+
else if (wrap.header || wrap.footer) {
|
|
2731
|
+
const open = wrap.outer ? `<${wrap.outer}>` : "<>";
|
|
2732
|
+
const close = wrap.outer ? `</${wrap.outer.split(/\s/)[0]}>` : "</>";
|
|
2733
|
+
jsx = [` ${open}`, ...(wrap.header ? [` <${wrap.header} />`] : []), ...main(" "), ...(wrap.footer ? [` <${wrap.footer} />`] : []), ` ${close}`];
|
|
2734
|
+
} else jsx = main(" ");
|
|
2735
|
+
const page = [...wrapImports, ...(wrapImports.length ? [""] : []), `export default function ${comp}() {`, " return (", ...jsx, " );", "}", ""].join("\n");
|
|
2736
|
+
files.push({ path: file, content: page });
|
|
2737
|
+
// Its import beside the sibling's, in the same form, and its route beside the sibling's route.
|
|
2738
|
+
const added = routeCopy({ src, router: sibling.router, routerFile: router, attr, value, name: comp, file, original: sibling.file });
|
|
2739
|
+
if (!added.ok) return added;
|
|
2740
|
+
files.push({ path: router, content: added.code });
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
/**
|
|
2744
|
+
* New page by rule (`create`): a blank page in the site's own layout, at `request.path`, with a
|
|
2745
|
+
* heading that is its name and nothing else.
|
|
2746
|
+
* - Astro: a page in src/pages in the layout most of its pages import (a title prop, or
|
|
2747
|
+
* AstroWind's `metadata`), else a page of its own.
|
|
2748
|
+
* - Next.js: a page in the app router whose metadata title is the name, so the root layout wraps
|
|
2749
|
+
* it; in the pages router where the site has only that.
|
|
2750
|
+
* - React Router: a component beside another page's, its import, and a `<Route>` beside that page's
|
|
2751
|
+
* route (so under the same parent route), wrapped as that page is: its Layout, or its header and
|
|
2752
|
+
* footer inside its outer element.
|
|
2753
|
+
* The address is checked (format, taken by a page or a redirect of the site's own); the name goes
|
|
2754
|
+
* into `unbase.pages.json`, with a draft flag where the site keeps drafts off Live (`drafts`).
|
|
2755
|
+
*/
|
|
2756
|
+
function planCreate(request, { framework, paths, text, discovered }) {
|
|
2757
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2758
|
+
const target = normalisePath(request.path);
|
|
2759
|
+
const name = String(request.name ?? "").trim().slice(0, 120) || componentName(target);
|
|
2760
|
+
if (target === "/" || !validAddress(target)) return no("address", target);
|
|
2761
|
+
const capability = createCapability({ framework, paths, text, found: discovered });
|
|
2762
|
+
if (!capability.ok) return capability;
|
|
2763
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2764
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
2765
|
+
if (discovered.pages.some((q) => q.path === target) || [...ownRedirects].some((s) => sends(s, target))) return no("taken", target);
|
|
2766
|
+
const have = new Set(paths);
|
|
2767
|
+
/** @type {PageWrite[]} */
|
|
2768
|
+
const files = [];
|
|
2769
|
+
const fileTaken = (f) => have.has(f) || files.some((w) => w.path === f);
|
|
2770
|
+
const segments = target.slice(1);
|
|
2771
|
+
|
|
2772
|
+
const refused = adapterOf(framework)?.starter?.({ discovered, text, paths, target, name, segments, files, fileTaken, no });
|
|
2773
|
+
if (refused) return refused;
|
|
2774
|
+
|
|
2775
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
|
|
2776
|
+
pages[target] = { ...(pages[target] ?? {}), ...(request.drafts ? { draft: true } : {}), name };
|
|
2777
|
+
});
|
|
2778
|
+
if (pageFileText !== null && pageFile.ok) files.push({ path: PAGE_FILE, content: pageFileText });
|
|
2779
|
+
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
2780
|
+
return { ok: true, action: "create", path: target, to: target, files, redirects: {}, links: [], unlinked: [], moves: [], renamed: [], message: `Unbase: new page ${target}` };
|
|
2781
|
+
}
|
|
2782
|
+
|
|
2783
|
+
// ── The operations (docs/plan-page-engine.md, PE3) ──
|
|
2784
|
+
|
|
2785
|
+
/**
|
|
2786
|
+
* One set of page operations for the editor, the Operator and the CLI. Names and URLs are apart
|
|
2787
|
+
* (Jens, 17-11): `rename` changes only what Unbase calls a page, `move` only its address (also into
|
|
2788
|
+
* another folder), and `create_page` makes the address from the name once, unless a slug is given.
|
|
2789
|
+
* Each structure operation is one `planPage` request (`requestOf`); `reorder`, `set_page` and
|
|
2790
|
+
* `set_site` are no commit of the code (the tree's order is the project's; titles and descriptions
|
|
2791
|
+
* are drafts where the site keeps them), so they are handled where they live.
|
|
2792
|
+
* @typedef {{ op: "create_page", parent?: string, name: string, slug?: string }
|
|
2793
|
+
* | { op: "rename", path: string, name: string | null }
|
|
2794
|
+
* | { op: "move", path: string, to: string }
|
|
2795
|
+
* | { op: "duplicate", path: string, to?: string, name?: string | null }
|
|
2796
|
+
* | { op: "delete", path: string, redirect?: string | null }
|
|
2797
|
+
* | { op: "rename_folder", path: string, name?: string | null, to?: string }
|
|
2798
|
+
* | { op: "reorder", parent: string, ids: string[] }
|
|
2799
|
+
* | { op: "set_page", path: string, title?: string, description?: string }
|
|
2800
|
+
* | { op: "set_site", title?: string, description?: string }} PageOperation
|
|
2801
|
+
*/
|
|
2802
|
+
export const PAGE_OPERATIONS = ["create_page", "rename", "move", "duplicate", "delete", "rename_folder", "reorder", "set_page", "set_site"];
|
|
2803
|
+
|
|
2804
|
+
/** The address `create_page` gives a page: its slug (else its name's) under its parent folder. Null when neither makes one. */
|
|
2805
|
+
export function createdAddress(op) {
|
|
2806
|
+
const slug = slugOf(op?.slug ?? op?.name ?? "");
|
|
2807
|
+
if (!slug) return null;
|
|
2808
|
+
const parent = op.parent ? normalisePath(op.parent) : "/";
|
|
2809
|
+
return normalisePath(`${parent === "/" ? "" : parent}/${slug}`);
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
/**
|
|
2813
|
+
* The `planPage` request a structure operation is; null for one that is no commit of the code
|
|
2814
|
+
* (`reorder`, `set_page`, `set_site`), or no operation at all.
|
|
2815
|
+
* @param {PageOperation} op
|
|
2816
|
+
*/
|
|
2817
|
+
export function requestOf(op) {
|
|
2818
|
+
if (!op || typeof op !== "object") return null;
|
|
2819
|
+
switch (op.op) {
|
|
2820
|
+
case "create_page": {
|
|
2821
|
+
const path = createdAddress(op);
|
|
2822
|
+
return path ? { action: "create", path, name: op.name } : null;
|
|
2823
|
+
}
|
|
2824
|
+
case "rename":
|
|
2825
|
+
return { action: "rename", path: op.path, name: op.name };
|
|
2826
|
+
case "move":
|
|
2827
|
+
return { action: "rename", path: op.path, to: op.to };
|
|
2828
|
+
case "rename_folder":
|
|
2829
|
+
return { action: "rename", path: op.path, ...(op.to !== undefined ? { to: op.to } : {}), ...(op.name !== undefined ? { name: op.name } : {}) };
|
|
2830
|
+
case "duplicate":
|
|
2831
|
+
return { action: "duplicate", path: op.path, ...(op.to !== undefined ? { to: op.to } : {}), ...(op.name !== undefined ? { name: op.name } : {}) };
|
|
2832
|
+
case "delete":
|
|
2833
|
+
return { action: "delete", path: op.path, ...(op.redirect !== undefined ? { redirect: op.redirect } : {}) };
|
|
2834
|
+
default:
|
|
2835
|
+
return null;
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
|
|
1907
2839
|
// ── Folders ──
|
|
1908
2840
|
|
|
1909
2841
|
/**
|
|
@@ -1961,6 +2893,7 @@ function folderDirs(at, below) {
|
|
|
1961
2893
|
* @returns {PagePlan | PageRefusal}
|
|
1962
2894
|
*/
|
|
1963
2895
|
function planFolder(request, { framework, paths, text, discovered, importers: given }) {
|
|
2896
|
+
const adapter = adapterOf(framework);
|
|
1964
2897
|
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1965
2898
|
const at = normalisePath(request.path);
|
|
1966
2899
|
if (at === "/") return no("home");
|
|
@@ -1973,7 +2906,7 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
|
|
|
1973
2906
|
const ownRedirects = siteRedirects({ framework, text });
|
|
1974
2907
|
if (target !== at && (discovered.pages.some((p) => within(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
|
|
1975
2908
|
const live = request.live === true;
|
|
1976
|
-
if (target !== at && live && !kitRedirects({ framework, text })) return no("no_redirects");
|
|
2909
|
+
if (target !== at && live && (!kitRedirects({ framework, text }) || below.some((p) => p.router?.object))) return no("no_redirects");
|
|
1977
2910
|
const have = new Set(paths);
|
|
1978
2911
|
/** @type {Map<string, PageWrite>} */
|
|
1979
2912
|
const writes = new Map();
|
|
@@ -1985,7 +2918,7 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
|
|
|
1985
2918
|
/** @type {Record<string, string | null>} */
|
|
1986
2919
|
const redirectChanges = {};
|
|
1987
2920
|
if (target !== at) {
|
|
1988
|
-
if (
|
|
2921
|
+
if (adapter?.routeLines) {
|
|
1989
2922
|
// Each route under it, its path's value rewritten; edits per router file from its end, so offsets hold.
|
|
1990
2923
|
/** @type {Map<string, { start: number, end: number, value: string }[]>} */
|
|
1991
2924
|
const edits = new Map();
|
|
@@ -2011,10 +2944,10 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
|
|
|
2011
2944
|
write({ path: file, content: out });
|
|
2012
2945
|
}
|
|
2013
2946
|
} else {
|
|
2014
|
-
const dirs = folderDirs(at, below);
|
|
2947
|
+
const dirs = (adapter?.folderDirs ?? folderDirs)(at, below);
|
|
2015
2948
|
if (!dirs) return no("unparsed", at);
|
|
2016
2949
|
for (const dir of dirs) {
|
|
2017
|
-
const newDir = `${dirname(dir)}/${lastOf(target)}
|
|
2950
|
+
const newDir = dirname(dir) ? `${dirname(dir)}/${lastOf(target)}` : lastOf(target);
|
|
2018
2951
|
for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
|
|
2019
2952
|
}
|
|
2020
2953
|
for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
@@ -2034,13 +2967,15 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
|
|
|
2034
2967
|
if (out !== src) write({ path: p, content: out });
|
|
2035
2968
|
}
|
|
2036
2969
|
}
|
|
2037
|
-
// Every link to anything under it, in code and content.
|
|
2970
|
+
// Every link to anything under it, in code and content (and a site of HTML files' relative URLs).
|
|
2971
|
+
const linkFile = linkFileOf(adapter);
|
|
2038
2972
|
for (const p of paths) {
|
|
2039
|
-
if (!
|
|
2973
|
+
if (!linkFile(p)) continue;
|
|
2040
2974
|
const where = moved.get(p) ?? p;
|
|
2041
2975
|
const src = current(where);
|
|
2042
2976
|
if (!src) continue;
|
|
2043
|
-
|
|
2977
|
+
let out = relinked(src, at, target, p);
|
|
2978
|
+
if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at, to: target }, moved);
|
|
2044
2979
|
if (out === src) continue;
|
|
2045
2980
|
write({ path: where, content: out });
|
|
2046
2981
|
if (!moved.has(p)) links.add(where);
|
|
@@ -2083,8 +3018,10 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
|
|
|
2083
3018
|
* address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
|
|
2084
3019
|
* `live`: the addresses on Live now (a live page needs the kit's redirects to move); `redirects`:
|
|
2085
3020
|
* whether this code's build applies them. Cheaper than a plan: no writes are worked out.
|
|
3021
|
+
* `details`: the templates that are a CMS collection's detail page (planPage): those can be deleted.
|
|
2086
3022
|
*/
|
|
2087
|
-
export function pageActions({ framework, paths, text, live = new Set(), found, importers }) {
|
|
3023
|
+
export function pageActions({ framework, paths, text, live = new Set(), found, importers, details = {} }) {
|
|
3024
|
+
const adapter = adapterOf(framework);
|
|
2088
3025
|
const kept = paths.filter((p) => !SKIP.test(p));
|
|
2089
3026
|
const discovered = found ?? discover({ framework, paths: kept, text });
|
|
2090
3027
|
const graph = importers ?? importGraph(kept, text);
|
|
@@ -2099,7 +3036,7 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
|
|
|
2099
3036
|
if (page.path.includes(" ")) continue;
|
|
2100
3037
|
const below = discovered.pages.filter((p) => under(p.path, page.path));
|
|
2101
3038
|
const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
|
|
2102
|
-
if (!
|
|
3039
|
+
if (!adapter?.acts) {
|
|
2103
3040
|
out[page.path] = all(no("framework"));
|
|
2104
3041
|
continue;
|
|
2105
3042
|
}
|
|
@@ -2108,7 +3045,11 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
|
|
|
2108
3045
|
continue;
|
|
2109
3046
|
}
|
|
2110
3047
|
if (page.kind === "template") {
|
|
2111
|
-
|
|
3048
|
+
// A CMS collection's detail page: Delete, in a file router; its items stay the CMS's.
|
|
3049
|
+
const detail = !!details[page.path] && !adapter?.routeLines && !!page.file && page.reason !== "unparsed";
|
|
3050
|
+
out[page.path] = detail
|
|
3051
|
+
? { rename: no("template"), duplicate: no("template"), delete: below.length ? no("nested", below.map((p) => p.path).join(", ")) : yes, under: below.length }
|
|
3052
|
+
: all(no("template"));
|
|
2112
3053
|
continue;
|
|
2113
3054
|
}
|
|
2114
3055
|
if (!page.file || page.reason === "unparsed") {
|
|
@@ -2116,10 +3057,10 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
|
|
|
2116
3057
|
continue;
|
|
2117
3058
|
}
|
|
2118
3059
|
const onLive = live.has(page.path);
|
|
2119
|
-
let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
|
|
2120
|
-
if (rename.ok &&
|
|
3060
|
+
let rename = page.path === "/" ? no("home") : onLive && (!redirects || page.router?.object) ? no("no_redirects", page.router?.object ? "route objects" : undefined) : yes;
|
|
3061
|
+
if (rename.ok && adapter?.routeLines && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
|
|
2121
3062
|
const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
|
|
2122
|
-
let duplicate =
|
|
3063
|
+
let duplicate = adapter?.routeLines && page.reason === "nested" ? no("nested") : yes;
|
|
2123
3064
|
if (duplicate.ok) {
|
|
2124
3065
|
const content = ownedContent(page, { paths: kept, text, importers: graph });
|
|
2125
3066
|
const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set() };
|
|
@@ -2156,14 +3097,15 @@ export function pageActions({ framework, paths, text, live = new Set(), found, i
|
|
|
2156
3097
|
const folders = {};
|
|
2157
3098
|
for (const at of folderPaths(discovered.pages)) {
|
|
2158
3099
|
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
2159
|
-
let rename = !
|
|
3100
|
+
let rename = !adapter?.acts ? no("framework") : !pageFile.ok ? no("invalid") : yes;
|
|
2160
3101
|
// 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 &&
|
|
2163
|
-
if (rename.ok &&
|
|
3102
|
+
if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && (!redirects || below.some((p) => p.router?.object))) rename = no("no_redirects");
|
|
3103
|
+
if (rename.ok && adapter?.routeLines && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
|
|
3104
|
+
if (rename.ok && !adapter?.routeLines && !(adapter?.folderDirs ?? folderDirs)(at, below)) rename = no("unparsed", at);
|
|
2164
3105
|
folders[at] = { rename, under: below.length };
|
|
2165
3106
|
}
|
|
2166
|
-
|
|
3107
|
+
// New page by rule (PE3): whether the site can have one without the Operator, and why not.
|
|
3108
|
+
return { redirects, actions: out, folders, create: createCapability({ framework, paths: kept, text, found: discovered }) };
|
|
2167
3109
|
}
|
|
2168
3110
|
|
|
2169
3111
|
/**
|
|
@@ -2185,9 +3127,8 @@ export function redirectsFor(framework, pageFile, pagePaths = []) {
|
|
|
2185
3127
|
continue;
|
|
2186
3128
|
}
|
|
2187
3129
|
const destBase = prefix ? normalisePath(destination.replace(REST, "")) : destination;
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
else list.push({ source, destination });
|
|
3130
|
+
const shape = adapterOf(framework)?.redirect;
|
|
3131
|
+
list.push(shape ? shape({ prefix, source, destination, base, destBase }) : { source, destination });
|
|
2191
3132
|
}
|
|
2192
3133
|
return { list, skipped };
|
|
2193
3134
|
}
|
|
@@ -2208,21 +3149,29 @@ export function siteRedirectList({ framework, text }) {
|
|
|
2208
3149
|
if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
|
|
2209
3150
|
}
|
|
2210
3151
|
} catch {}
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
if (
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
3152
|
+
const adapter = adapterOf(framework);
|
|
3153
|
+
for (const c of adapter?.configs ?? []) {
|
|
3154
|
+
if (adapter.configRedirects) out.push(...adapter.configRedirects(stripComments(text(c) ?? ""), c));
|
|
3155
|
+
}
|
|
3156
|
+
return out;
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
/** The redirects an Astro config's `redirects` literal sets, each with where it goes (a string or `{ destination }`). */
|
|
3160
|
+
function astroConfigRedirects(src, file) {
|
|
3161
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
3162
|
+
if (at < 0) return [];
|
|
3163
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
3164
|
+
const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
|
|
3165
|
+
return [...body.matchAll(entry)].map((m) => ({ from: m[1], to: m[2] ?? m[3], file }));
|
|
3166
|
+
}
|
|
3167
|
+
|
|
3168
|
+
/** The redirects a Next.js config's literal `{ source, destination }` objects set. */
|
|
3169
|
+
function nextConfigRedirects(src, file) {
|
|
3170
|
+
const out = [];
|
|
3171
|
+
for (const m of src.matchAll(/\{[^{}]*\}/g)) {
|
|
3172
|
+
const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
|
|
3173
|
+
const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
|
|
3174
|
+
if (from && to) out.push({ from, to, file });
|
|
2226
3175
|
}
|
|
2227
3176
|
return out;
|
|
2228
3177
|
}
|
|
@@ -2248,10 +3197,11 @@ function redirectEnd(p) {
|
|
|
2248
3197
|
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[] } }} input
|
|
2249
3198
|
*/
|
|
2250
3199
|
export function planRedirect(request, { framework, paths, text, found }) {
|
|
3200
|
+
const adapter = adapterOf(framework);
|
|
2251
3201
|
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2252
3202
|
const action = request.action;
|
|
2253
3203
|
if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
|
|
2254
|
-
if (!
|
|
3204
|
+
if (!adapter?.acts) return no("framework");
|
|
2255
3205
|
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2256
3206
|
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
2257
3207
|
const from = redirectEnd(request.from);
|