@unbase-app/pages 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +138 -2
- package/astro.d.mts +29 -0
- package/astro.mjs +202 -0
- package/core.mjs +1859 -0
- package/node.mjs +205 -0
- package/package.json +43 -4
- package/vite.d.mts +27 -0
- package/vite.mjs +287 -0
package/node.mjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// @unbase-app/pages — what the build plugins do on disk: read the app's
|
|
4
|
+
// files for core.mjs, plan the drafts of a production build, read the page
|
|
5
|
+
// file's redirects, and finish its output (page lists cleaned, the leak
|
|
6
|
+
// check).
|
|
7
|
+
// ============================================================================
|
|
8
|
+
|
|
9
|
+
import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { join, relative, sep } from "node:path";
|
|
11
|
+
import { brotliDecompressSync, gunzipSync } from "node:zlib";
|
|
12
|
+
import * as core from "./core.mjs";
|
|
13
|
+
|
|
14
|
+
const SKIP_DIRS = new Set(["node_modules", "dist", "build", "out", ".git", ".astro", ".next", ".vercel", ".output", ".netlify", ".turbo", ".cache"]);
|
|
15
|
+
const SOURCE = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html|json)$/;
|
|
16
|
+
/** What a host serves or runs as text, compressed or not: where a page's words could end up. */
|
|
17
|
+
const SERVED_TEXT = /\.(html?|js|mjs|cjs|css|json|xml|txt|map|webmanifest|svg|md)(\.(gz|br))?$/;
|
|
18
|
+
|
|
19
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A served file's text as a reader would get it: decompressed (.gz, .br), HTML entities and
|
|
23
|
+
* JavaScript escapes decoded, whitespace as one space. The leak check matches on this, so a
|
|
24
|
+
* sentence a minifier or an HTML writer encoded is still found.
|
|
25
|
+
*/
|
|
26
|
+
export function readServed(file) {
|
|
27
|
+
let bytes = readFileSync(file);
|
|
28
|
+
if (file.endsWith(".gz")) bytes = gunzipSync(bytes);
|
|
29
|
+
else if (file.endsWith(".br")) bytes = brotliDecompressSync(bytes);
|
|
30
|
+
return decodeText(bytes.toString("utf8"));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function decodeText(text) {
|
|
34
|
+
return text
|
|
35
|
+
.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})/g, (_, a, b, c) => String.fromCodePoint(parseInt(a ?? b ?? c, 16)))
|
|
36
|
+
.replace(/\\(["'`/])/g, "$1")
|
|
37
|
+
.replace(/\\[nrt]/g, " ")
|
|
38
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
|
39
|
+
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
|
|
40
|
+
.replace(/&([a-z]+);/g, (m, n) => ENTITIES[n] ?? m)
|
|
41
|
+
.replace(/\s+/g, " ");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The app's source files, relative to `root`, read once when asked. */
|
|
45
|
+
export function appFiles(root) {
|
|
46
|
+
/** @type {string[]} */
|
|
47
|
+
const paths = [];
|
|
48
|
+
const walk = (dir) => {
|
|
49
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
50
|
+
if (e.isDirectory()) {
|
|
51
|
+
if (SKIP_DIRS.has(e.name) || (e.name.startsWith(".") && e.name !== ".schemas")) continue;
|
|
52
|
+
walk(join(dir, e.name));
|
|
53
|
+
} else if (SOURCE.test(e.name)) {
|
|
54
|
+
paths.push(relative(root, join(dir, e.name)).split(sep).join("/"));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
walk(root);
|
|
59
|
+
paths.sort();
|
|
60
|
+
const cache = new Map();
|
|
61
|
+
const text = (p) => {
|
|
62
|
+
if (!cache.has(p)) {
|
|
63
|
+
let t = null;
|
|
64
|
+
try {
|
|
65
|
+
t = readFileSync(join(root, p), "utf8");
|
|
66
|
+
} catch {}
|
|
67
|
+
cache.set(p, t);
|
|
68
|
+
}
|
|
69
|
+
return cache.get(p);
|
|
70
|
+
};
|
|
71
|
+
return { paths, text };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const WHY = {
|
|
75
|
+
invalid: (d) => `${core.PAGE_FILE} is not valid: ${d}`,
|
|
76
|
+
framework: () => "this framework has no draft support in the kit yet",
|
|
77
|
+
home: () => "Home cannot be a draft",
|
|
78
|
+
template: (d) => `it is made by a dynamic route (${d}); keep it off the site where its data lives`,
|
|
79
|
+
missing: () => `the code makes no page at this address; remove it from ${core.PAGE_FILE}`,
|
|
80
|
+
nested: () => "its route has child routes",
|
|
81
|
+
unparsed: () => "its route is not one component the kit can trace (element={<Page />})",
|
|
82
|
+
shared: (d) => `its file or its content is also used by ${d}`,
|
|
83
|
+
content_unknown: () => "it reads content the kit cannot attribute to it",
|
|
84
|
+
generated_media: (d) => `the site draws pages into images (${d}), which the kit cannot check`,
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** The refusal of a production build, one line per page. */
|
|
88
|
+
export function refusal(failed) {
|
|
89
|
+
const lines = failed.map((f) => ` ${f.path}: ${(WHY[f.reason] ?? (() => f.reason))(f.detail ?? "")}`);
|
|
90
|
+
return `[unbase-pages] This production build would publish draft pages it cannot keep out, so it stops:\n${lines.join("\n")}\nMark them as ready in Unbase, or fix the reason, and build again.`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* What a build keeps out, or null when nothing is a draft or this is not a production build.
|
|
95
|
+
* Throws the refusal when a draft cannot be kept out (fail closed).
|
|
96
|
+
* @param {{ root: string, framework: string, command: "build" | "dev", log?: (line: string) => void }} input
|
|
97
|
+
*/
|
|
98
|
+
export function planBuild({ root, framework, command, log = () => {} }) {
|
|
99
|
+
const ctx = core.deployContext({ env: process.env, command });
|
|
100
|
+
log(`${ctx.context} build (${ctx.source})`);
|
|
101
|
+
if (ctx.context !== "production") return null;
|
|
102
|
+
const files = appFiles(root);
|
|
103
|
+
const pageFile = core.parsePageFile(files.text(core.PAGE_FILE));
|
|
104
|
+
const plan = core.draftPlan({ framework, ...files, pageFile });
|
|
105
|
+
if (plan.failed.length) throw new Error(refusal(plan.failed));
|
|
106
|
+
if (!plan.checks.length) return null;
|
|
107
|
+
/** @type {any[]} */
|
|
108
|
+
const checks = plan.checks;
|
|
109
|
+
const drafts = checks.map((c) => ({
|
|
110
|
+
path: c.path,
|
|
111
|
+
file: join(root, c.page.file),
|
|
112
|
+
router: c.page.router ? join(root, c.page.router.file) : null,
|
|
113
|
+
content: c.content,
|
|
114
|
+
prints: core.leakPrints(c, files),
|
|
115
|
+
}));
|
|
116
|
+
log(`keeping out: ${drafts.map((d) => d.path).join(", ")}`);
|
|
117
|
+
return { root, files, drafts };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The redirects unbase.pages.json holds, for `framework`'s build (core.redirectsFor), or null when
|
|
122
|
+
* it holds none. The page file is read first, and the app's files only when it sends something on,
|
|
123
|
+
* so a site without redirects is not walked. `skipped`: sources that are a page now (the page
|
|
124
|
+
* wins). Throws when the file is not valid: a build that cannot read where an old address goes must
|
|
125
|
+
* not drop it silently.
|
|
126
|
+
* @param {{ root: string, framework: "astro" | "vite-react" }} input
|
|
127
|
+
*/
|
|
128
|
+
export function pageRedirects({ root, framework }) {
|
|
129
|
+
let raw = null;
|
|
130
|
+
try {
|
|
131
|
+
raw = readFileSync(join(root, core.PAGE_FILE), "utf8");
|
|
132
|
+
} catch {}
|
|
133
|
+
const pageFile = core.parsePageFile(raw);
|
|
134
|
+
if (!pageFile.ok) throw new Error(`[unbase-pages] ${core.PAGE_FILE} is not valid (${pageFile.error}), so the addresses it sends on cannot be applied, and the build stops.`);
|
|
135
|
+
if (!Object.keys(pageFile.redirects).length) return null;
|
|
136
|
+
const files = appFiles(root);
|
|
137
|
+
const found = core.discover({ framework, ...files });
|
|
138
|
+
return { ...core.redirectsFor(framework, pageFile, found.pages.map((p) => p.path)), redirects: pageFile.redirects, files, found };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Every file a host would serve as text, under `dir`. */
|
|
142
|
+
function servedFiles(dir) {
|
|
143
|
+
/** @type {string[]} */
|
|
144
|
+
const out = [];
|
|
145
|
+
const walk = (d) => {
|
|
146
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
147
|
+
const p = join(d, e.name);
|
|
148
|
+
if (e.isDirectory()) walk(p);
|
|
149
|
+
else if (SERVED_TEXT.test(e.name)) out.push(p);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
if (existsSync(dir)) walk(dir);
|
|
153
|
+
return out.sort();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* After a production build: the drafts' pages out of every list in `dir` (sitemaps,
|
|
158
|
+
* comment-modus/pages.json, the content map), then the leak check over everything served. Throws
|
|
159
|
+
* when a draft's text is still there.
|
|
160
|
+
* @param {string} dir
|
|
161
|
+
* @param {{ drafts: { path: string, content: string[], prints: string[] }[] }} plan
|
|
162
|
+
*/
|
|
163
|
+
export function finishOutput(dir, plan, log = (_line) => {}, scan = [dir]) {
|
|
164
|
+
const paths = plan.drafts.map((d) => d.path);
|
|
165
|
+
const owned = plan.drafts.flatMap((d) => d.content);
|
|
166
|
+
for (const f of servedFiles(dir)) {
|
|
167
|
+
const name = relative(dir, f).split(sep).join("/");
|
|
168
|
+
let next = null;
|
|
169
|
+
if (/\.(gz|br)$/.test(name)) continue;
|
|
170
|
+
const text = readFileSync(f, "utf8");
|
|
171
|
+
if (/(^|\/)sitemap[^/]*\.xml$/.test(name)) next = core.withoutInSitemap(text, paths);
|
|
172
|
+
else if (name === "comment-modus/pages.json") next = core.withoutInPageList(text, paths);
|
|
173
|
+
else if (name === "comment-modus/content-map.json") next = core.withoutInContentMap(text, owned);
|
|
174
|
+
if (next !== null && next !== text) {
|
|
175
|
+
writeFileSync(f, next);
|
|
176
|
+
log(`cleaned ${name}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const leaks = [];
|
|
180
|
+
for (const root of scan) {
|
|
181
|
+
for (const f of servedFiles(root)) {
|
|
182
|
+
const text = readServed(f);
|
|
183
|
+
for (const d of plan.drafts) for (const p of core.leaksIn(text, d.prints)) leaks.push(` ${d.path}: "${p.slice(0, 60)}…" in ${relative(root, f)}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (leaks.length) throw new Error(`[unbase-pages] Draft text is still in the production output, so the build stops:\n${leaks.join("\n")}`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* A built page's HTML, wherever the build's format put it. Anything else written right under the
|
|
191
|
+
* draft's address (an image made for it, a feed) is output the kit does not know: the build stops.
|
|
192
|
+
*/
|
|
193
|
+
export function removePageHtml(dir, path) {
|
|
194
|
+
const gone = [];
|
|
195
|
+
for (const f of [join(dir, path, "index.html"), join(dir, `${path}.html`), join(dir, `${path}.html.gz`), join(dir, `${path}.html.br`), join(dir, path, "index.html.gz"), join(dir, path, "index.html.br")]) {
|
|
196
|
+
if (existsSync(f)) {
|
|
197
|
+
rmSync(f);
|
|
198
|
+
gone.push(f);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const folder = join(dir, path);
|
|
202
|
+
const left = existsSync(folder) ? readdirSync(folder, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name) : [];
|
|
203
|
+
if (left.length) throw new Error(`[unbase-pages] ${path} is a draft, and the build wrote ${left.join(", ")} under its address, which the kit cannot check, so the build stops.`);
|
|
204
|
+
return gone;
|
|
205
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unbase-app/pages",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Keeps draft pages out of a site's production build and applies the redirects a moved page leaves: an Astro integration and a Vite plugin, for Unbase.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/unbase-app/kit.git",
|
|
10
|
+
"directory": "pages"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/unbase-app/kit/tree/main/pages#readme",
|
|
13
|
+
"bugs": "https://github.com/unbase-app/kit/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"astro",
|
|
16
|
+
"astro-integration",
|
|
17
|
+
"vite-plugin",
|
|
18
|
+
"react-router",
|
|
19
|
+
"drafts",
|
|
20
|
+
"redirects",
|
|
21
|
+
"unbase"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./core.mjs",
|
|
28
|
+
"./astro": {
|
|
29
|
+
"types": "./astro.d.mts",
|
|
30
|
+
"default": "./astro.mjs"
|
|
31
|
+
},
|
|
32
|
+
"./vite": {
|
|
33
|
+
"types": "./vite.d.mts",
|
|
34
|
+
"default": "./vite.mjs"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"files": ["core.mjs", "node.mjs", "astro.mjs", "astro.d.mts", "vite.mjs", "vite.d.mts", "README.md", "LICENSE"],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18.17"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"test": "node --test test/*.test.mjs"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/vite.d.mts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Plugin } from "vite";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The Vite plugin for a React Router app: in a production build every draft in unbase.pages.json
|
|
5
|
+
* is kept out, or the build stops; in the dev server and every build the addresses its `redirects`
|
|
6
|
+
* send on become routes that navigate to the new address.
|
|
7
|
+
*/
|
|
8
|
+
export declare function unbasePages(): Plugin;
|
|
9
|
+
export default unbasePages;
|
|
10
|
+
|
|
11
|
+
/** A redirect as a route (the core's redirectsFor for "vite-react"). */
|
|
12
|
+
export type RedirectRoute = { path: string; from: string; to: string; prefix: boolean };
|
|
13
|
+
|
|
14
|
+
/** The component a redirect for everything under an address renders. */
|
|
15
|
+
export declare const MOVED: "UnbaseMoved";
|
|
16
|
+
|
|
17
|
+
/** A router file's code with a route per redirect, or null when it has no `<Routes>` to take them (exported for its tests). */
|
|
18
|
+
export declare function withRedirectRoutes(code: string, list: RedirectRoute[]): { code: string; added: string[] } | null;
|
|
19
|
+
|
|
20
|
+
/** The file with the app's top-level `<Routes>`, relative to the app (exported for its tests). */
|
|
21
|
+
export declare function routerFile(
|
|
22
|
+
pages: { path: string; router?: { file: string } }[],
|
|
23
|
+
files: { paths: string[]; text: (path: string) => string | null },
|
|
24
|
+
): string | null;
|
|
25
|
+
|
|
26
|
+
/** unbase.pages.json's redirects as routes and the router file they go in, or null (exported for its tests). */
|
|
27
|
+
export declare function movedRoutes(root: string, warn?: (line: string) => void): { router: string; file: string; list: RedirectRoute[] } | null;
|
package/vite.mjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// @unbase-app/pages/vite — the Vite plugin for a React Router app (what
|
|
4
|
+
// Lovable makes). In a production build every draft in unbase.pages.json is
|
|
5
|
+
// kept out: its <Route … /> is removed from the router before JSX is compiled,
|
|
6
|
+
// and its page module becomes an empty one, so neither its route nor its text
|
|
7
|
+
// reaches a chunk; its address falls to the app's own "*" (Not Found). Then
|
|
8
|
+
// the output is checked for the page's text. Previews and the dev server show
|
|
9
|
+
// drafts as they are. Fails closed: a draft it cannot keep out stops the build.
|
|
10
|
+
//
|
|
11
|
+
// The addresses unbase.pages.json sends on (`redirects`: a page Unbase renamed
|
|
12
|
+
// or deleted while it was live) become routes in the same router, in the dev
|
|
13
|
+
// server and every build alike: UnbaseMoved to the new address (query and hash kept), the
|
|
14
|
+
// opposite of keeping a draft out. A single-page app has no server status to
|
|
15
|
+
// give, so this is a client redirect, and it works on any host.
|
|
16
|
+
//
|
|
17
|
+
// // vite.config.ts
|
|
18
|
+
// import { unbasePages } from "@unbase-app/pages/vite";
|
|
19
|
+
// plugins: [react(), unbasePages()]
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
import { join, resolve } from "node:path";
|
|
23
|
+
import * as core from "./core.mjs";
|
|
24
|
+
import { finishOutput, pageRedirects, planBuild } from "./node.mjs";
|
|
25
|
+
|
|
26
|
+
const clean = (id) => id.replace(/\?.*$/, "");
|
|
27
|
+
|
|
28
|
+
/** The component a redirect for everything under an address renders, added once to the router file. */
|
|
29
|
+
export const MOVED = "UnbaseMoved";
|
|
30
|
+
|
|
31
|
+
/** A route whose path is the catch-all: `path="*"`, `path="/*"`, `path={"*"}`. */
|
|
32
|
+
const CATCH_ALL = /(?:^|\s)path\s*=\s*(?:"\/?\*"|'\/?\*'|\{\s*(["'`])\/?\*\1\s*\})/;
|
|
33
|
+
|
|
34
|
+
/** Where a quoted string that starts at `i` ends (after its closing quote). One line for ' and ". */
|
|
35
|
+
function stringEnd(src, i) {
|
|
36
|
+
const q = src[i];
|
|
37
|
+
for (let j = i + 1; j < src.length; j++) {
|
|
38
|
+
if (src[j] === "\\") j++;
|
|
39
|
+
else if (src[j] === q) return j + 1;
|
|
40
|
+
else if (src[j] === "\n" && q !== "`") return i + 1;
|
|
41
|
+
}
|
|
42
|
+
return src.length;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Where a JSX tag whose name ends at `from` ends, braces and strings skipped. */
|
|
46
|
+
function tagEnd(src, from) {
|
|
47
|
+
let depth = 0;
|
|
48
|
+
for (let i = from; i < src.length; i++) {
|
|
49
|
+
const c = src[i];
|
|
50
|
+
if (c === '"' || c === "'" || c === "`") i = stringEnd(src, i) - 1;
|
|
51
|
+
else if (c === "{") depth++;
|
|
52
|
+
else if (c === "}") depth--;
|
|
53
|
+
else if (depth === 0 && c === "/" && src[i + 1] === ">") return { end: i + 2, selfClosing: true };
|
|
54
|
+
else if (depth === 0 && c === ">") return { end: i + 1, selfClosing: false };
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const used = (src, name) => new RegExp(`(?<![\\w$.])${name}(?![\\w$])`).test(src);
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A router file's `code` with a route for each of the page file's redirects (core.redirectsFor's
|
|
63
|
+
* React Router form), in its top-level `<Routes>`: before the catch-all `*` when it has one, else
|
|
64
|
+
* before its first route. Each renders UnbaseMoved, which sends the visitor on with the query and
|
|
65
|
+
* the hash kept (a link with UTM tags still counts), and for everything under an address
|
|
66
|
+
* (`prefix`) the rest of the address too. `Navigate` and `useLocation` join the import `Route` comes from when it lacks them,
|
|
67
|
+
* under a name of their own when the file has the name already. Null when the file has no
|
|
68
|
+
* `<Routes>` with children, or no import of `Route` to add to.
|
|
69
|
+
* @param {string} code
|
|
70
|
+
* @param {{ path: string, from: string, to: string, prefix: boolean }[]} list
|
|
71
|
+
*/
|
|
72
|
+
export function withRedirectRoutes(code, list) {
|
|
73
|
+
if (!list.length) return { code, added: [] };
|
|
74
|
+
const src = core.stripComments(code);
|
|
75
|
+
const open = /<Routes(?=[\s>])/.exec(src);
|
|
76
|
+
const head = open ? tagEnd(src, open.index + "<Routes".length) : null;
|
|
77
|
+
if (!open || !head || head.selfClosing) return null;
|
|
78
|
+
|
|
79
|
+
// The top-level routes: the first, the catch-all, and where <Routes> closes.
|
|
80
|
+
let depth = 0;
|
|
81
|
+
let first = -1;
|
|
82
|
+
let catchAll = -1;
|
|
83
|
+
let close = -1;
|
|
84
|
+
const tags = /<(\/?)(Routes?)(?=[\s/>])/g;
|
|
85
|
+
tags.lastIndex = head.end;
|
|
86
|
+
for (let m = tags.exec(src); m; m = tags.exec(src)) {
|
|
87
|
+
if (m[1]) {
|
|
88
|
+
if (depth === 0) {
|
|
89
|
+
if (m[2] === "Routes") close = m.index;
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
depth--;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const tag = tagEnd(src, m.index + m[0].length);
|
|
96
|
+
if (!tag) return null;
|
|
97
|
+
if (depth === 0 && m[2] === "Route") {
|
|
98
|
+
if (first < 0) first = m.index;
|
|
99
|
+
if (catchAll < 0 && CATCH_ALL.test(src.slice(m.index + m[0].length, tag.end))) catchAll = m.index;
|
|
100
|
+
}
|
|
101
|
+
if (!tag.selfClosing) depth++;
|
|
102
|
+
tags.lastIndex = tag.end;
|
|
103
|
+
}
|
|
104
|
+
if (close < 0) return null;
|
|
105
|
+
|
|
106
|
+
// The import Route comes from, and the names Navigate and useLocation have in this file.
|
|
107
|
+
const importOf = [...src.matchAll(/\bimport\s*\{([^}]*)\}\s*from\s*(["'])([^"'\n]+)\2/g)].find((m) =>
|
|
108
|
+
m[1].split(",").some((s) => (s.trim().split(/\s+as\s+/)[1] ?? s.trim()) === "Route"),
|
|
109
|
+
);
|
|
110
|
+
if (!importOf || importOf.index === undefined) return null;
|
|
111
|
+
const specs = importOf[1]
|
|
112
|
+
.split(",")
|
|
113
|
+
.map((s) => s.trim().replace(/^type\s+/, ""))
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.map((s) => {
|
|
116
|
+
const [imported, local = imported] = s.split(/\s+as\s+/);
|
|
117
|
+
return { imported: imported.trim(), local: local.trim() };
|
|
118
|
+
});
|
|
119
|
+
const adds = [];
|
|
120
|
+
const nameOf = (name, alias) => {
|
|
121
|
+
const have = specs.find((s) => s.imported === name);
|
|
122
|
+
if (have) return have.local;
|
|
123
|
+
const local = used(src, name) ? alias : name;
|
|
124
|
+
adds.push(local === name ? name : `${name} as ${local}`);
|
|
125
|
+
return local;
|
|
126
|
+
};
|
|
127
|
+
const navigate = nameOf("Navigate", "UnbaseNavigate");
|
|
128
|
+
const location = nameOf("useLocation", "useUnbaseLocation");
|
|
129
|
+
|
|
130
|
+
const routes = list.map((r) => `<Route path={${JSON.stringify(r.path)}} element={<${MOVED} from={${JSON.stringify(r.prefix ? r.from : r.path)}} to={${JSON.stringify(r.to)}} />} />`);
|
|
131
|
+
const at = catchAll >= 0 ? catchAll : first >= 0 ? first : close;
|
|
132
|
+
const lead = code.slice(code.lastIndexOf("\n", at - 1) + 1, at);
|
|
133
|
+
const routesText = /^\s*$/.test(lead) ? `${routes.join(`\n${lead}`)}\n${lead}` : `${routes.join(" ")} `;
|
|
134
|
+
|
|
135
|
+
/** @type {{ at: number, text: string }[]} */
|
|
136
|
+
const edits = [{ at, text: routesText }];
|
|
137
|
+
if (adds.length) {
|
|
138
|
+
const inner = importOf[1];
|
|
139
|
+
const braceAt = importOf.index + importOf[0].indexOf("{") + 1;
|
|
140
|
+
const tail = inner.search(/,?\s*$/);
|
|
141
|
+
edits.push({ at: braceAt + tail, text: `${inner.trim() ? ", " : " "}${adds.join(", ")}${inner.trim() ? "" : " "}` });
|
|
142
|
+
}
|
|
143
|
+
if (!used(src, MOVED)) {
|
|
144
|
+
edits.push({
|
|
145
|
+
at: code.length,
|
|
146
|
+
text: `\n\n// Added by @unbase-app/pages: an address unbase.pages.json moved, and what is under it, with its query and hash.\nfunction ${MOVED}({ from, to }) {\n const { pathname, search, hash } = ${location}();\n const rest = pathname.slice(from === "/" ? 0 : from.length);\n return <${navigate} to={{ pathname: (to === "/" ? "" : to) + rest || "/", search, hash }} replace />;\n}\n`,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
let out = code;
|
|
150
|
+
for (const e of edits.sort((a, b) => b.at - a.at)) out = out.slice(0, e.at) + e.text + out.slice(e.at);
|
|
151
|
+
return { code: out, added: list.map((r) => r.path) };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The file with the app's top-level `<Routes>`: of the files discovery found routes in that have
|
|
156
|
+
* one, the one with Home's route, else the one with the most routes. Routes discovery could not
|
|
157
|
+
* trace to a component still have a `<Routes>`: then the first file that has one and imports
|
|
158
|
+
* React Router.
|
|
159
|
+
* @param {import("./core.mjs").Page[]} pages
|
|
160
|
+
* @param {{ paths: string[], text: (path: string) => string | null }} files
|
|
161
|
+
*/
|
|
162
|
+
export function routerFile(pages, files) {
|
|
163
|
+
const hasRoutes = (f) => /<Routes(?=[\s>])/.test(core.stripComments(files.text(f) ?? ""));
|
|
164
|
+
/** @type {Map<string, number>} */
|
|
165
|
+
const score = new Map();
|
|
166
|
+
for (const p of pages) if (p.router) score.set(p.router.file, (score.get(p.router.file) ?? 0) + (p.path === "/" ? 1000 : 1));
|
|
167
|
+
const ranked = [...score].filter(([f]) => hasRoutes(f)).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));
|
|
168
|
+
if (ranked.length) return ranked[0][0];
|
|
169
|
+
return files.paths.find((f) => /\.(tsx|jsx|ts|js)$/.test(f) && /from\s*["']react-router(-dom)?["']/.test(files.text(f) ?? "") && hasRoutes(f)) ?? null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The page file's redirects as routes, and the router file they go in (absolute), or null when it
|
|
174
|
+
* sends nothing on. Throws when it does and no router file has a `<Routes>` to take them.
|
|
175
|
+
* @param {string} root
|
|
176
|
+
* @param {(line: string) => void} warn
|
|
177
|
+
*/
|
|
178
|
+
export function movedRoutes(root, warn = () => {}) {
|
|
179
|
+
const found = pageRedirects({ root, framework: "vite-react" });
|
|
180
|
+
if (!found) return null;
|
|
181
|
+
for (const s of found.skipped) warn(`${s} is a page now, so the redirect ${core.PAGE_FILE} has for it is not applied: the page wins.`);
|
|
182
|
+
if (!found.list.length) return null;
|
|
183
|
+
const router = routerFile(found.found.pages, found.files);
|
|
184
|
+
if (!router) throw new Error(`[unbase-pages] ${core.PAGE_FILE} sends addresses on, and no file has the app's <Routes> to add them to, so the build stops.`);
|
|
185
|
+
return { router: join(root, router), file: router, list: /** @type {{ path: string, from: string, to: string, prefix: boolean }[]} */ (found.list) };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @returns {import("vite").Plugin} */
|
|
189
|
+
export function unbasePages() {
|
|
190
|
+
/** @type {ReturnType<typeof planBuild>} */
|
|
191
|
+
let plan = null;
|
|
192
|
+
let outDir = "";
|
|
193
|
+
let root = "";
|
|
194
|
+
/** @type {"build" | "dev"} */
|
|
195
|
+
let command = "build";
|
|
196
|
+
const removed = new Set();
|
|
197
|
+
/** @type {ReturnType<typeof movedRoutes>} */
|
|
198
|
+
let moved = null;
|
|
199
|
+
let routed = false;
|
|
200
|
+
/** @type {(line: string) => void} */
|
|
201
|
+
let log = () => {};
|
|
202
|
+
/** @type {(line: string) => void} */
|
|
203
|
+
let warn = () => {};
|
|
204
|
+
|
|
205
|
+
// A page file that cannot be read, or redirects with nowhere to go, stop a build; the dev server says so and goes on.
|
|
206
|
+
const readMoved = () => {
|
|
207
|
+
try {
|
|
208
|
+
moved = movedRoutes(root, warn);
|
|
209
|
+
} catch (e) {
|
|
210
|
+
if (command === "build") throw e;
|
|
211
|
+
warn(/** @type {Error} */ (e).message);
|
|
212
|
+
moved = null;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
return {
|
|
217
|
+
name: "unbase-pages",
|
|
218
|
+
enforce: "pre",
|
|
219
|
+
configResolved(config) {
|
|
220
|
+
log = (line) => config.logger.info(`[unbase-pages] ${line}`);
|
|
221
|
+
warn = (line) => config.logger.warn(line.startsWith("[unbase-pages]") ? line : `[unbase-pages] ${line}`);
|
|
222
|
+
root = config.root;
|
|
223
|
+
command = config.command === "serve" ? "dev" : "build";
|
|
224
|
+
outDir = resolve(config.root, config.build.outDir);
|
|
225
|
+
plan = planBuild({ root: config.root, framework: "vite-react", command, log });
|
|
226
|
+
readMoved();
|
|
227
|
+
},
|
|
228
|
+
configureServer(server) {
|
|
229
|
+
// A page renamed while the dev server runs: its old address is sent on at once.
|
|
230
|
+
const file = join(root, core.PAGE_FILE);
|
|
231
|
+
server.watcher.add(file);
|
|
232
|
+
const again = (/** @type {string} */ changed) => {
|
|
233
|
+
if (resolve(changed) !== file) return;
|
|
234
|
+
const before = moved?.router;
|
|
235
|
+
readMoved();
|
|
236
|
+
for (const f of new Set([before, moved?.router])) if (f) for (const m of server.moduleGraph.getModulesByFile(f) ?? []) server.moduleGraph.invalidateModule(m);
|
|
237
|
+
server.ws.send({ type: "full-reload" });
|
|
238
|
+
};
|
|
239
|
+
server.watcher.on("add", again);
|
|
240
|
+
server.watcher.on("change", again);
|
|
241
|
+
server.watcher.on("unlink", again);
|
|
242
|
+
},
|
|
243
|
+
load(id) {
|
|
244
|
+
if (!plan) return null;
|
|
245
|
+
const file = clean(id);
|
|
246
|
+
if (plan.drafts.some((d) => d.file === file)) return "export default function UnbaseDraftPage() {\n return null;\n}\n";
|
|
247
|
+
return null;
|
|
248
|
+
},
|
|
249
|
+
transform(code, id) {
|
|
250
|
+
const file = clean(id);
|
|
251
|
+
let out = code;
|
|
252
|
+
const drop = plan ? plan.drafts.filter((d) => d.router === file).map((d) => d.path) : [];
|
|
253
|
+
if (plan && drop.length) {
|
|
254
|
+
const rel = file.slice(plan.root.length + 1).split("\\").join("/");
|
|
255
|
+
const kept = core.removeRoutes({ file: rel, code, paths: plan.files.paths, text: plan.files.text, drop });
|
|
256
|
+
for (const p of kept.removed) removed.add(p);
|
|
257
|
+
out = kept.code;
|
|
258
|
+
}
|
|
259
|
+
if (moved && file === moved.router) {
|
|
260
|
+
const next = withRedirectRoutes(out, moved.list);
|
|
261
|
+
if (next) {
|
|
262
|
+
out = next.code;
|
|
263
|
+
routed = true;
|
|
264
|
+
log(`redirects from ${core.PAGE_FILE} in ${moved.file}: ${moved.list.map((r) => `${r.path} → ${r.to}${r.prefix ? "/*" : ""}`).join(", ")}`);
|
|
265
|
+
} else {
|
|
266
|
+
const message = `[unbase-pages] ${moved.file} has no <Routes> with routes and no import of Route to add the redirects in ${core.PAGE_FILE} to, so the build stops.`;
|
|
267
|
+
if (command === "build") this.error(message);
|
|
268
|
+
warn(message);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return out === code ? null : { code: out, map: null };
|
|
272
|
+
},
|
|
273
|
+
buildEnd(error) {
|
|
274
|
+
if (error) return;
|
|
275
|
+
if (plan) {
|
|
276
|
+
const left = plan.drafts.filter((d) => !removed.has(d.path)).map((d) => d.path);
|
|
277
|
+
if (left.length) this.error(`[unbase-pages] The route of ${left.join(", ")} was not found in the router while building, so the build stops.`);
|
|
278
|
+
}
|
|
279
|
+
if (moved && command === "build" && !routed) this.error(`[unbase-pages] ${moved.file} was not built, so the redirects in ${core.PAGE_FILE} are not in the app, and the build stops.`);
|
|
280
|
+
},
|
|
281
|
+
closeBundle() {
|
|
282
|
+
if (plan) finishOutput(outDir, plan, log);
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export default unbasePages;
|