@zubra/router 5.18.0 → 5.20.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 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.18.0",
3
+ "version": "5.20.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.18.0",
26
- "@zubra/server": "^5.18.0"
25
+ "@zubra/compiler": "^5.20.0",
26
+ "@zubra/server": "^5.20.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@zubra/compiler": "file:../compiler",
package/src/answers.js CHANGED
@@ -5,11 +5,17 @@ export const ANSWER = Symbol.for('@zubra/router.answer');
5
5
  /** `return notFound()`: the path has nothing behind it (no such farm). The response is a 404. */
6
6
  export const notFound = () => ({ [ANSWER]: 'notFound' });
7
7
 
8
- /** `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise). */
9
- export const redirect = (location, status = 303) => {
8
+ /**
9
+ * `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise).
10
+ * Only on this site: another site needs `redirect(url, { external: true })` (or
11
+ * `redirect(url, 302, { external: true })`), so a `next` taken from the query string can't send
12
+ * a visitor off it.
13
+ */
14
+ export const redirect = (location, status = 303, { external = false } = {}) => {
15
+ if (status && typeof status === 'object') ({ status = 303, external = false } = status);
10
16
  if (typeof location !== 'string' || !location) throw new TypeError("@zubra/router: redirect() needs where to go: redirect('/cart')");
11
17
  if (![301, 302, 303, 307, 308].includes(status)) throw new TypeError(`@zubra/router: redirect()'s status is 301, 302, 303, 307 or 308, not ${status}`);
12
- return { [ANSWER]: 'redirect', location, status };
18
+ return { [ANSWER]: 'redirect', location, status, external: Boolean(external) };
13
19
  };
14
20
 
15
21
  /**
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
- /** Called when a `load` or a render throws; the browser gets the 500 page, never the message. */
50
- onError?(error: unknown, request: Request): void;
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,12 +24,13 @@
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';
30
31
  import { findCompiler } from '@zubra/server';
31
32
  import { ANSWER } from './answers.js';
32
- import { APP, buildTable, fromRoot, matcher, RouteError } from './table.js';
33
+ import { APP, buildTable, fromRoot, layoutMatcher, matcher, RouteError } from './table.js';
33
34
 
34
35
  export { notFound, redirect, show } from './answers.js';
35
36
 
@@ -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 plain 500, never the message. `lang`: the document's
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) => console.error(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,17 +122,44 @@ 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
- const response = compile({ emit: 'server', path, files: read(path) });
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
- const module = join(cacheDir, `${name.split('/').join('__')}.route.mjs`);
143
+ // One file name per component name, with no two names sharing one (`a/b` and `a__b` did).
144
+ const module = join(cacheDir, `${name.replace(/_/g, '_u').replace(/\//g, '_s')}.route.mjs`);
118
145
  const writing = `${module}.${process.pid}.${randomUUID()}.tmp`;
119
- writeFileSync(writing, rewriteImports(response.output, (specifier) => pathToFileURL(resolve(dirname(path), specifier)).href));
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);
120
156
  renameSync(writing, module);
121
157
  loads.set(name, (await import(`${pathToFileURL(module).href}?t=${Date.now()}`)).load);
122
158
  }
123
159
 
124
- const match = matcher(pages, await urlPattern());
160
+ const URLPatternClass = await urlPattern();
161
+ const match = matcher(pages, URLPatternClass);
162
+ const layoutsOver = layoutMatcher(layouts, URLPatternClass);
125
163
 
126
164
  /** A Response for a GET or HEAD to a route, or null. `extra` (`{ req }`, `{ c }`) goes to `context`. */
127
165
  async function respond(request, extra = {}, { unknown = false } = {}) {
@@ -129,11 +167,19 @@ export async function createRouter({
129
167
  const url = new URL(request.url);
130
168
  const found = unknown ? null : match(url.pathname);
131
169
  if (!found && !unknown) return null;
132
- const { page = null, params = {} } = found ?? {};
170
+ const { page = null, params: pageParams = {} } = found ?? {};
171
+ // The layouts over this path, matched against the path itself (`layoutMatcher`), and their
172
+ // parameters, so a layout's `load` reads its own (`params.org`) whatever the page calls it.
173
+ const over = page ? layoutsOver(url.pathname) : [];
174
+ const params = Object.assign({}, ...over.map((each) => each.params), pageParams);
133
175
  const route = { path: url.pathname, pattern: page?.pattern ?? null, params };
134
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) });
135
181
  const fail = (error) => {
136
- onError(error, request);
182
+ onError(error, request, about(error));
137
183
  return errorPage(500);
138
184
  };
139
185
  const document = async (body, title) => {
@@ -167,7 +213,7 @@ export async function createRouter({
167
213
  headers.set('content-type', 'text/html; charset=utf-8');
168
214
  return new Response(request.method === 'HEAD' ? null : html, { status, headers });
169
215
  } catch (failure) {
170
- onError(failure, request);
216
+ onError(failure, request, about(failure));
171
217
  return plain();
172
218
  }
173
219
  };
@@ -177,7 +223,9 @@ export async function createRouter({
177
223
  let given;
178
224
  const loadArguments = async () => {
179
225
  if (!given) {
180
- const result = actions ? actions.result(extra.req ?? request, (name, value) => headers.append(name, value)) : null;
226
+ // A HEAD (a prefetch, a link checker) doesn't use up an action's one-use answer: the
227
+ // GET that follows still shows it.
228
+ const result = actions && request.method !== 'HEAD' ? actions.result(extra.req ?? request, (name, value) => headers.append(name, value)) : null;
181
229
  given = { params, url, request, route, context: (context ? await context({ request, ...extra }) : null) ?? {}, result };
182
230
  }
183
231
  return given;
@@ -190,6 +238,7 @@ export async function createRouter({
190
238
  loaded.set(name, (await loads.get(name)(await loadArguments())) ?? {});
191
239
  } catch (error) {
192
240
  threw.add(name);
241
+ thrower = name;
193
242
  throw error;
194
243
  }
195
244
  }
@@ -201,7 +250,13 @@ export async function createRouter({
201
250
  // ones outside returned reaches the ones inside as props they declare. A `show()` puts
202
251
  // another component in the place of the one that answered, and the walk starts again with
203
252
  // it (the loads that already ran aren't run twice).
204
- let chain = page.layouts;
253
+ //
254
+ // Every layout over the path runs its `load`, a `root` layout's outer ones and `app.zb`'s
255
+ // included, so an outer check guards a root section too; only those from the innermost
256
+ // `root` one are rendered.
257
+ const around = over.map(({ layout }) => layout.name);
258
+ let rendered = new Set(fromRoot(over.map(({ layout }) => layout)).map((layout) => layout.name));
259
+ let chain = around;
205
260
  let leaf = { name: page.name };
206
261
  let status = 200;
207
262
  let parts;
@@ -209,7 +264,7 @@ export async function createRouter({
209
264
  try {
210
265
  walk: for (let walks = 0; ; walks++) {
211
266
  // Each show() from a layout leaves fewer layouts, so this can't go round for long.
212
- if (walks > page.around.length + 2) throw new RouteError(`${route.pattern}: show() kept being answered with another show()`);
267
+ if (walks > around.length + 2) throw new RouteError(`${route.pattern}: show() kept being answered with another show()`);
213
268
  parts = [];
214
269
  title = undefined;
215
270
  const data = {};
@@ -222,12 +277,15 @@ export async function createRouter({
222
277
  case 'notFound':
223
278
  return errorPage(404);
224
279
  case 'redirect':
225
- headers.set('location', answer.location);
280
+ headers.set('location', checkedLocation(answer, url));
226
281
  return new Response(null, { status: answer.status, headers });
227
282
  case 'show':
228
283
  // In place of a layout: inside the layouts over it, as if it weren't there (so a
229
284
  // `root` layout that turns someone away shows its notice in the app's shell).
230
- if (!last) chain = fromRoot(page.around.slice(0, page.around.indexOf(name)).map((each) => ({ name: each, root: isRoot.get(each) }))).map((each) => each.name);
285
+ if (!last) {
286
+ chain = around.slice(0, around.indexOf(name));
287
+ rendered = new Set(fromRoot(chain.map((each) => ({ name: each, root: isRoot.get(each) }))).map((each) => each.name));
288
+ }
231
289
  leaf = { name: answer.name, props: { ...answer.props } };
232
290
  status = answer.status;
233
291
  continue walk;
@@ -240,7 +298,7 @@ export async function createRouter({
240
298
  for (const [key, value] of Object.entries(params)) if (declared.has(key)) props[key] = value;
241
299
  // Props the component declares; anything else the loads return doesn't reach it.
242
300
  for (const [key, value] of Object.entries(data)) if (declared.has(key)) props[key] = value;
243
- parts.push({ name, props, last });
301
+ if (last || rendered.has(name)) parts.push({ name, props, last });
244
302
  }
245
303
  break;
246
304
  }
@@ -261,6 +319,9 @@ export async function createRouter({
261
319
  return fail(error);
262
320
  }
263
321
  headers.set('content-type', 'text/html; charset=utf-8');
322
+ // A page whose loads read the request (the session, an action's answer) is that visitor's:
323
+ // no shared cache keeps it for the next one. The app can say otherwise in its own handler.
324
+ if (given) headers.set('cache-control', 'private, no-store');
264
325
  return new Response(request.method === 'HEAD' ? null : html, { status, headers });
265
326
  }
266
327
 
@@ -334,6 +395,25 @@ function rewriteImports(code, to) {
334
395
  return code.replace(/(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.{1,2}\/[^'"]+)\2/g, (_, keyword, quote, specifier) => `${keyword}${quote}${to(specifier)}${quote}`);
335
396
  }
336
397
 
398
+ /**
399
+ * Where a `redirect()` sends the browser: on this site unless it says `{ external: true }`.
400
+ * A path starting `//` or `/\` is another site to a browser, so it's written with one slash;
401
+ * an absolute URL elsewhere (a `next` from the query string) is refused, and so is any scheme
402
+ * that isn't http(s). `redirect(next)` after a sign-in can't send anyone off the site.
403
+ */
404
+ function checkedLocation({ location, external }, url) {
405
+ if (/^[/\\]/.test(location)) return '/' + location.replace(/^[/\\]+/, '');
406
+ let target;
407
+ try {
408
+ target = new URL(location, url);
409
+ } catch {
410
+ throw new RouteError(`redirect() to ${JSON.stringify(location)}: not a URL`);
411
+ }
412
+ if (!['http:', 'https:'].includes(target.protocol)) throw new RouteError(`redirect() to a ${target.protocol} URL is refused`);
413
+ if (target.origin !== url.origin && !external) throw new RouteError(`redirect() to ${target.origin}, another site: say redirect(to, { external: true }) if that's meant`);
414
+ return target.origin === url.origin ? target.pathname + target.search + target.hash : target.href;
415
+ }
416
+
337
417
  // A Host header is a host and an optional port. Anything else (a path, a query, an empty one)
338
418
  // would move the URL's path away from the request's: `Host: site/admin` with `GET /public` would
339
419
  // read as `/admin/public`, past a proxy that allowed `/public`. That's refused (the callers answer
@@ -346,9 +426,15 @@ const hostOf = (req) => {
346
426
  return host;
347
427
  };
348
428
 
349
- /** A Node GET or HEAD request as a fetch Request. */
429
+ /**
430
+ * A Node GET or HEAD request as a fetch Request. The path routed is `req.url`'s, and nothing
431
+ * else: a target that isn't a path (`http://evil/staff`, `//evil/staff`) would make the URL's
432
+ * path differ from `req.url`, past any guard the app keeps on it. That throws, as a bad Host
433
+ * does, and `handle()` answers 400.
434
+ */
350
435
  function toRequest(req) {
351
436
  const host = hostOf(req);
437
+ if (typeof req.url !== 'string' || !req.url.startsWith('/') || req.url.startsWith('//')) throw new RouteError('a request target that is not a path');
352
438
  const protocol = req.socket?.encrypted ? 'https' : 'http';
353
439
  const headers = new Headers();
354
440
  for (const [name, value] of Object.entries(req.headers)) {
package/src/table.js CHANGED
@@ -150,10 +150,18 @@ function compareSpecificity(a, b) {
150
150
  return right.length - left.length || (a < b ? -1 : a > b ? 1 : 0);
151
151
  }
152
152
 
153
+ /**
154
+ * A pathname the router answers: one leading slash. The URLPattern polyfill (Node 22 has no
155
+ * global one) reads a leading `//host` as an authority, so `//evil/staff` would match `/staff`
156
+ * and pass any guard the app or a proxy keeps on the raw path.
157
+ */
158
+ const routable = (pathname) => typeof pathname === 'string' && pathname.startsWith('/') && !pathname.startsWith('//');
159
+
153
160
  /** A matcher over the pages: `match(pathname)` → `{ page, params }` or null. */
154
161
  export function matcher(pages, URLPatternClass) {
155
162
  const compiled = pages.map((page) => ({ page, pattern: new URLPatternClass({ pathname: page.pattern }) }));
156
163
  return (pathname) => {
164
+ if (!routable(pathname)) return null;
157
165
  for (const { page, pattern } of compiled) {
158
166
  const found = pattern.exec({ pathname });
159
167
  if (found) {
@@ -165,3 +173,30 @@ export function matcher(pages, URLPatternClass) {
165
173
  return null;
166
174
  };
167
175
  }
176
+
177
+ /**
178
+ * The layouts over a requested path, outermost first: every layout whose prefix matches the
179
+ * start of the path itself. Matched against the path, not compared with the page's pattern
180
+ * text, so a page written `/org/:id(\\d+)/x`, `/org/:orgId/x` or `/docs/:path*` is still inside
181
+ * the layouts of `/org/:org` and `/docs/private` whenever the path is under them: a layout's
182
+ * check guards every page under its prefix, however that page's pattern is spelled.
183
+ * `match(pathname)` → `[{ layout, params }]`.
184
+ */
185
+ export function layoutMatcher(layouts, URLPatternClass) {
186
+ const compiled = layouts.map((layout) => ({
187
+ layout,
188
+ pattern: new URLPatternClass({ pathname: layout.pattern === '/' ? '/*' : `${layout.pattern}{/*}?` }),
189
+ }));
190
+ return (pathname) => {
191
+ if (!routable(pathname)) return [];
192
+ const found = [];
193
+ for (const { layout, pattern } of compiled) {
194
+ const matched = pattern.exec({ pathname });
195
+ if (!matched) continue;
196
+ const params = {};
197
+ for (const [key, value] of Object.entries(matched.pathname.groups)) if (value !== undefined && !/^\d+$/.test(key)) params[key] = value;
198
+ found.push({ layout, params });
199
+ }
200
+ return found.sort((a, b) => segmentsOf(a.layout.pattern).length - segmentsOf(b.layout.pattern).length);
201
+ };
202
+ }