@zubra/router 5.19.0 → 5.21.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 +1 -1
- package/package.json +3 -3
- package/src/index.d.ts +8 -2
- package/src/index.js +47 -7
package/README.md
CHANGED
|
@@ -86,7 +86,7 @@ A layout's `load` works the same way, and for its whole section: what it returns
|
|
|
86
86
|
|
|
87
87
|
## Errors
|
|
88
88
|
|
|
89
|
-
An unknown path (`router.notFound(req, res)` at the end of the app's handlers, or `router.listener`), `notFound()`, and a `load` that throws render inside `app.zb`, with status 404 or 500. `error.zb`, if the app has one, goes in the shell's slot with a `status` prop; otherwise a heading does. A shell that declares an `error` prop is given `{ status }`. The message never reaches the browser; `onError(error, request)` is told. With no shell, or when the shell can't render, the response is plain text.
|
|
89
|
+
An unknown path (`router.notFound(req, res)` at the end of the app's handlers, or `router.listener`), `notFound()`, and a `load` that throws render inside `app.zb`, with status 404 or 500. `error.zb`, if the app has one, goes in the shell's slot with a `status` prop; otherwise a heading does. A shell that declares an `error` prop is given `{ status }`. The message never reaches the browser; `onError(error, request, about)` is told, with `about` naming the route and, for a `load`, the component, its file and the line of that file it threw at; without `onError` the server logs that line and the error. With no shell, or when the shell can't render, the response is plain text.
|
|
90
90
|
|
|
91
91
|
## What it doesn't do
|
|
92
92
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zubra/router",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.21.0",
|
|
4
4
|
"description": "Serve Zubra components that say 'use route <path>' as pages, with a server-only load, for apps with no host framework.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
"urlpattern-polyfill": "10.1.0"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"@zubra/compiler": "^5.
|
|
26
|
-
"@zubra/server": "^5.
|
|
25
|
+
"@zubra/compiler": "^5.21.0",
|
|
26
|
+
"@zubra/server": "^5.21.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@zubra/compiler": "file:../compiler",
|
package/src/index.d.ts
CHANGED
|
@@ -46,8 +46,14 @@ export interface RouterOptions {
|
|
|
46
46
|
components?: string;
|
|
47
47
|
/** Where the routes' server halves are written (default `node_modules/.cache/zubra-router`). */
|
|
48
48
|
cacheDir?: string;
|
|
49
|
-
/**
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Called when a `load` or a render throws; the browser gets the 500 page, never the message.
|
|
51
|
+
* `about` says what was being answered: the `route`, and when a `load` threw, the `component`
|
|
52
|
+
* it belongs to, its `file` (relative to where the server runs) and the `line` of that file it
|
|
53
|
+
* threw at; all null for a render.
|
|
54
|
+
* The default logs the request and the file, then the error.
|
|
55
|
+
*/
|
|
56
|
+
onError?(error: unknown, request: Request, about: { route: { path: string; pattern: string | null; params: Record<string, string> }; component: string | null; file: string | null; line: number | null }): void;
|
|
51
57
|
/** The document's language (default `en`). */
|
|
52
58
|
lang?: string;
|
|
53
59
|
/**
|
package/src/index.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
// answer after a post without JavaScript (`createRouter({ actions })`). Besides props it can
|
|
25
25
|
// return a `title`, `notFound()`, `redirect(to)` or `show(component, props)`.
|
|
26
26
|
import { randomUUID } from 'node:crypto';
|
|
27
|
+
import { SourceMap } from 'node:module';
|
|
27
28
|
import { existsSync, mkdirSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
28
29
|
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
29
30
|
import { pathToFileURL } from 'node:url';
|
|
@@ -57,8 +58,11 @@ async function urlPattern() {
|
|
|
57
58
|
/**
|
|
58
59
|
* `zubra`: the app's `createZubra()`, which renders the pages. `components`: the same folder
|
|
59
60
|
* (default `components`). `cacheDir`: where the routes' server halves are written (bare imports
|
|
60
|
-
* resolve from there, so keep it inside the project). `onError(error, request)`: called when a
|
|
61
|
-
* `load` throws; the browser gets a
|
|
61
|
+
* resolve from there, so keep it inside the project). `onError(error, request, about)`: called when a
|
|
62
|
+
* `load` throws or a page fails to render; the browser gets a 500, never the message. `about` is
|
|
63
|
+
* `{ route, component, file, line }`: the route answered, and the component whose `load` threw
|
|
64
|
+
* with its file and the line of that file it threw at (all null when it was the render; `line`
|
|
65
|
+
* also when the error has no stack to read it from). By default it is logged, with the request and the file. `lang`: the document's
|
|
62
66
|
* language (default `en`). `head`: HTML for every page's `<head>` (fonts, a stylesheet), or a
|
|
63
67
|
* function of `{ url, request, route }` returning it; written as given, so it is the app's own
|
|
64
68
|
* markup, never a visitor's text. `context({ request, req })`: what each `load` gets as
|
|
@@ -70,7 +74,13 @@ export async function createRouter({
|
|
|
70
74
|
zubra,
|
|
71
75
|
components = 'components',
|
|
72
76
|
cacheDir = join(process.cwd(), 'node_modules', '.cache', 'zubra-router'),
|
|
73
|
-
onError = (error) =>
|
|
77
|
+
onError = (error, request, about) => {
|
|
78
|
+
// Which request and which file, before the error: its own stack names only the generated
|
|
79
|
+
// server half in the cache (`boom-page.route.mjs`), not the component it was written in
|
|
80
|
+
// (unless Node runs with `--enable-source-maps`, which reads the half's map).
|
|
81
|
+
console.error(`@zubra/router: ${request.method} ${about.route.path}: ${about.file ? `the load in ${about.file} threw${about.line ? `, at line ${about.line}` : ''}` : 'the page failed to render'} (the browser got a 500 without the message):`);
|
|
82
|
+
console.error(error);
|
|
83
|
+
},
|
|
74
84
|
lang = 'en',
|
|
75
85
|
head = '',
|
|
76
86
|
context,
|
|
@@ -96,6 +106,7 @@ export async function createRouter({
|
|
|
96
106
|
if (info.route?.load) halves.set(name, path);
|
|
97
107
|
}
|
|
98
108
|
const { pages, layouts } = buildTable(entries);
|
|
109
|
+
const fileOf = new Map(entries.map((entry) => [entry.name, entry.file]));
|
|
99
110
|
// The props a component declares: only those are taken from what the loads return.
|
|
100
111
|
const declaredBy = new Map(entries.map((entry) => [entry.name, new Set(entry.props)]));
|
|
101
112
|
const propsOf = (name) => {
|
|
@@ -111,13 +122,37 @@ export async function createRouter({
|
|
|
111
122
|
// imports point back at the source; each is written beside its place and renamed in, so a
|
|
112
123
|
// second process starting at the same moment never imports half a file.
|
|
113
124
|
const loads = new Map();
|
|
125
|
+
const linesOf = new Map();
|
|
126
|
+
const MAP = /\n\/\/# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)\s*$/;
|
|
127
|
+
/** The line of the component's own file where `error` was thrown in its `load`, or null. */
|
|
128
|
+
const lineIn = (name, error) => {
|
|
129
|
+
const lines = linesOf.get(name);
|
|
130
|
+
if (!lines || typeof error?.stack !== 'string') return null;
|
|
131
|
+
// The first frame in the half itself (a function it called may be the one that threw).
|
|
132
|
+
const at = error.stack.indexOf(lines.href);
|
|
133
|
+
const frame = at < 0 ? null : /^(?:\?[^:\s)]*)?:(\d+):(\d+)/.exec(error.stack.slice(at + lines.href.length));
|
|
134
|
+
if (!frame) return null;
|
|
135
|
+
const entry = lines.map.findEntry(Number(frame[1]) - 1, Number(frame[2]) - 1);
|
|
136
|
+
return typeof entry?.originalLine === 'number' ? entry.originalLine + 1 : null;
|
|
137
|
+
};
|
|
114
138
|
for (const [name, path] of halves) {
|
|
115
|
-
|
|
139
|
+
// `sourceMap`: the half ends with a map of its functions' lines to the component's (a
|
|
140
|
+
// compiler from before it knew the word answers without one, and lines stay the half's).
|
|
141
|
+
const response = compile({ emit: 'server', path, files: read(path), sourceMap: true });
|
|
116
142
|
if (!response.ok) throw new Error(response.error);
|
|
117
143
|
// One file name per component name, with no two names sharing one (`a/b` and `a__b` did).
|
|
118
144
|
const module = join(cacheDir, `${name.replace(/_/g, '_u').replace(/\//g, '_s')}.route.mjs`);
|
|
119
145
|
const writing = `${module}.${process.pid}.${randomUUID()}.tmp`;
|
|
120
|
-
|
|
146
|
+
let code = rewriteImports(response.output, (specifier) => pathToFileURL(resolve(dirname(path), specifier)).href);
|
|
147
|
+
const mapped = MAP.exec(code);
|
|
148
|
+
if (mapped) {
|
|
149
|
+
// The map names the component by its address, so Node's own `--enable-source-maps` reads
|
|
150
|
+
// it too; and it is kept, to say the line when a `load` throws without that flag.
|
|
151
|
+
const map = { ...JSON.parse(Buffer.from(mapped[1], 'base64').toString()), sources: [pathToFileURL(path).href] };
|
|
152
|
+
code = `${code.slice(0, mapped.index)}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(map)).toString('base64')}\n`;
|
|
153
|
+
linesOf.set(name, { href: pathToFileURL(module).href, map: new SourceMap(map) });
|
|
154
|
+
}
|
|
155
|
+
writeFileSync(writing, code);
|
|
121
156
|
renameSync(writing, module);
|
|
122
157
|
loads.set(name, (await import(`${pathToFileURL(module).href}?t=${Date.now()}`)).load);
|
|
123
158
|
}
|
|
@@ -139,8 +174,12 @@ export async function createRouter({
|
|
|
139
174
|
const params = Object.assign({}, ...over.map((each) => each.params), pageParams);
|
|
140
175
|
const route = { path: url.pathname, pattern: page?.pattern ?? null, params };
|
|
141
176
|
const headers = new Headers();
|
|
177
|
+
// `about`: what was being answered (`route`), and, when a `load` threw, whose it was
|
|
178
|
+
// (`component`, and its `file` from where the server runs); both null for a render.
|
|
179
|
+
let thrower = null;
|
|
180
|
+
const about = (error) => ({ route, component: thrower, file: thrower === null ? null : fileOf.get(thrower) ?? null, line: thrower === null ? null : lineIn(thrower, error) });
|
|
142
181
|
const fail = (error) => {
|
|
143
|
-
onError(error, request);
|
|
182
|
+
onError(error, request, about(error));
|
|
144
183
|
return errorPage(500);
|
|
145
184
|
};
|
|
146
185
|
const document = async (body, title) => {
|
|
@@ -174,7 +213,7 @@ export async function createRouter({
|
|
|
174
213
|
headers.set('content-type', 'text/html; charset=utf-8');
|
|
175
214
|
return new Response(request.method === 'HEAD' ? null : html, { status, headers });
|
|
176
215
|
} catch (failure) {
|
|
177
|
-
onError(failure, request);
|
|
216
|
+
onError(failure, request, about(failure));
|
|
178
217
|
return plain();
|
|
179
218
|
}
|
|
180
219
|
};
|
|
@@ -199,6 +238,7 @@ export async function createRouter({
|
|
|
199
238
|
loaded.set(name, (await loads.get(name)(await loadArguments())) ?? {});
|
|
200
239
|
} catch (error) {
|
|
201
240
|
threw.add(name);
|
|
241
|
+
thrower = name;
|
|
202
242
|
throw error;
|
|
203
243
|
}
|
|
204
244
|
}
|