@unbase-app/pages 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  // @ts-check
2
2
  // ============================================================================
3
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, and finish its
5
- // output (page lists cleaned, the leak check).
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).
6
7
  // ============================================================================
7
8
 
8
9
  import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
@@ -116,6 +117,27 @@ export function planBuild({ root, framework, command, log = () => {} }) {
116
117
  return { root, files, drafts };
117
118
  }
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
+
119
141
  /** Every file a host would serve as text, under `dir`. */
120
142
  function servedFiles(dir) {
121
143
  /** @type {string[]} */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unbase-app/pages",
3
- "version": "0.3.0",
4
- "description": "Keeps draft pages out of a site's production build: an Astro integration and a Vite plugin, for Unbase.",
3
+ "version": "0.4.1",
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
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
@@ -17,6 +17,7 @@
17
17
  "vite-plugin",
18
18
  "react-router",
19
19
  "drafts",
20
+ "redirects",
20
21
  "unbase"
21
22
  ],
22
23
  "publishConfig": {
@@ -24,6 +25,7 @@
24
25
  },
25
26
  "exports": {
26
27
  ".": "./core.mjs",
28
+ "./binding": "./binding.mjs",
27
29
  "./astro": {
28
30
  "types": "./astro.d.mts",
29
31
  "default": "./astro.mjs"
@@ -34,7 +36,7 @@
34
36
  },
35
37
  "./package.json": "./package.json"
36
38
  },
37
- "files": ["core.mjs", "node.mjs", "astro.mjs", "astro.d.mts", "vite.mjs", "vite.d.mts", "README.md", "LICENSE"],
39
+ "files": ["core.mjs", "binding.mjs", "node.mjs", "astro.mjs", "astro.d.mts", "vite.mjs", "vite.d.mts", "README.md", "LICENSE"],
38
40
  "engines": {
39
41
  "node": ">=18.17"
40
42
  },
package/vite.d.mts CHANGED
@@ -2,7 +2,26 @@ import type { Plugin } from "vite";
2
2
 
3
3
  /**
4
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.
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.
6
7
  */
7
8
  export declare function unbasePages(): Plugin;
8
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 CHANGED
@@ -8,33 +8,237 @@
8
8
  // the output is checked for the page's text. Previews and the dev server show
9
9
  // drafts as they are. Fails closed: a draft it cannot keep out stops the build.
10
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
+ //
11
17
  // // vite.config.ts
12
18
  // import { unbasePages } from "@unbase-app/pages/vite";
13
19
  // plugins: [react(), unbasePages()]
14
20
  // ============================================================================
15
21
 
16
- import { resolve } from "node:path";
22
+ import { join, resolve } from "node:path";
17
23
  import * as core from "./core.mjs";
18
- import { finishOutput, planBuild } from "./node.mjs";
24
+ import { finishOutput, pageRedirects, planBuild } from "./node.mjs";
19
25
 
20
26
  const clean = (id) => id.replace(/\?.*$/, "");
21
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
+
22
188
  /** @returns {import("vite").Plugin} */
23
189
  export function unbasePages() {
24
190
  /** @type {ReturnType<typeof planBuild>} */
25
191
  let plan = null;
26
192
  let outDir = "";
193
+ let root = "";
194
+ /** @type {"build" | "dev"} */
195
+ let command = "build";
27
196
  const removed = new Set();
197
+ /** @type {ReturnType<typeof movedRoutes>} */
198
+ let moved = null;
199
+ let routed = false;
28
200
  /** @type {(line: string) => void} */
29
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
+ };
30
215
 
31
216
  return {
32
217
  name: "unbase-pages",
33
218
  enforce: "pre",
34
219
  configResolved(config) {
35
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";
36
224
  outDir = resolve(config.root, config.build.outDir);
37
- plan = planBuild({ root: config.root, framework: "vite-react", command: config.command === "serve" ? "dev" : "build", log });
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);
38
242
  },
39
243
  load(id) {
40
244
  if (!plan) return null;
@@ -43,19 +247,36 @@ export function unbasePages() {
43
247
  return null;
44
248
  },
45
249
  transform(code, id) {
46
- if (!plan) return null;
47
250
  const file = clean(id);
48
- const drop = plan.drafts.filter((d) => d.router === file).map((d) => d.path);
49
- if (!drop.length) return null;
50
- const rel = file.slice(plan.root.length + 1).split("\\").join("/");
51
- const out = core.removeRoutes({ file: rel, code, paths: plan.files.paths, text: plan.files.text, drop });
52
- for (const p of out.removed) removed.add(p);
53
- return { code: out.code, map: null };
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 };
54
272
  },
55
273
  buildEnd(error) {
56
- if (!plan || error) return;
57
- const left = plan.drafts.filter((d) => !removed.has(d.path)).map((d) => d.path);
58
- if (left.length) this.error(`[unbase-pages] The route of ${left.join(", ")} was not found in the router while building, so the build stops.`);
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.`);
59
280
  },
60
281
  closeBundle() {
61
282
  if (plan) finishOutput(outDir, plan, log);