netjes 0.0.4 → 0.0.5

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.
Files changed (73) hide show
  1. package/README.md +8 -8
  2. package/cli/commands.mjs +32 -6
  3. package/dist/actions.d.ts +3 -2
  4. package/dist/actions.d.ts.map +1 -1
  5. package/dist/actions.js +5 -4
  6. package/dist/actions.js.map +1 -1
  7. package/dist/document.d.ts +3 -1
  8. package/dist/document.d.ts.map +1 -1
  9. package/dist/document.js +4 -3
  10. package/dist/document.js.map +1 -1
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/lang.d.ts +10 -0
  16. package/dist/lang.d.ts.map +1 -0
  17. package/dist/lang.js +26 -0
  18. package/dist/lang.js.map +1 -0
  19. package/dist/link.d.ts +15 -3
  20. package/dist/link.d.ts.map +1 -1
  21. package/dist/link.js +15 -9
  22. package/dist/link.js.map +1 -1
  23. package/dist/mounted.d.ts +3 -7
  24. package/dist/mounted.d.ts.map +1 -1
  25. package/dist/mounted.js.map +1 -1
  26. package/dist/navigation-guard.d.ts +59 -0
  27. package/dist/navigation-guard.d.ts.map +1 -0
  28. package/dist/navigation-guard.js +116 -0
  29. package/dist/navigation-guard.js.map +1 -0
  30. package/dist/payload.d.ts +20 -2
  31. package/dist/payload.d.ts.map +1 -1
  32. package/dist/payload.js +25 -1
  33. package/dist/payload.js.map +1 -1
  34. package/dist/root.d.ts.map +1 -1
  35. package/dist/root.js +2 -1
  36. package/dist/root.js.map +1 -1
  37. package/dist/router.d.ts +101 -20
  38. package/dist/router.d.ts.map +1 -1
  39. package/dist/router.js +590 -68
  40. package/dist/router.js.map +1 -1
  41. package/dist/schema.d.ts +2 -0
  42. package/dist/schema.d.ts.map +1 -1
  43. package/dist/schema.js +5 -0
  44. package/dist/schema.js.map +1 -1
  45. package/dist/testing.d.ts +17 -0
  46. package/dist/testing.d.ts.map +1 -1
  47. package/dist/testing.js +63 -22
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +5 -1
  50. package/sidecar/server.mjs +80 -14
  51. package/skills/netjes/SKILL.md +2 -2
  52. package/skills/netjes/references/data-and-actions.md +5 -4
  53. package/skills/netjes/references/deployment.md +1 -1
  54. package/skills/netjes/references/routing.md +9 -5
  55. package/skills/netjes/references/testing.md +6 -3
  56. package/src/actions.tsx +5 -4
  57. package/src/document.tsx +11 -4
  58. package/src/index.ts +9 -0
  59. package/src/lang.ts +28 -0
  60. package/src/link.tsx +37 -9
  61. package/src/mounted.tsx +3 -3
  62. package/src/navigation-guard.ts +136 -0
  63. package/src/payload.ts +37 -3
  64. package/src/root.tsx +3 -1
  65. package/src/router.tsx +764 -104
  66. package/src/schema.ts +11 -0
  67. package/src/testing-vitest.ts +1 -1
  68. package/src/testing.tsx +67 -15
  69. package/template/Dockerfile +1 -1
  70. package/template/README.md +1 -1
  71. package/template/_AGENTS.md +4 -2
  72. package/template/docker-compose.override.yml +15 -3
  73. package/template/generated/netjes.ts +1 -1
@@ -8,16 +8,21 @@
8
8
  // pings a process that has answered no render for a while; any answer will do, and a process that sends nothing back
9
9
  // within the render timeout (at least 5 s) is killed and restarted. Every request must carry the X-Netjes-Token the
10
10
  // parent passed in NETJES_TOKEN. Renders are aborted when the caller disconnects, when the shell is not ready after
11
- // NETJES_RENDER_TIMEOUT_MS, or when the whole stream takes longer than NETJES_STREAM_TIMEOUT_MS. Exits when stdin
12
- // closes.
13
- // Startup: prints NETJES_READY {"port","viteOrigin"} on stdout once it listens. When the Vite dev server does not start,
14
- // it prints NETJES_FAILED and exits with code 1: {"reason":"vite-port-in-use","port"} when its port is taken, and
11
+ // NETJES_RENDER_TIMEOUT_MS, or when the whole stream takes longer than NETJES_STREAM_TIMEOUT_MS. Reads lines on stdin:
12
+ // `stopping`, which the parent sends in development once the app begins to stop, makes the Vite dev server let go of
13
+ // its port and end its connections, while renders go on. Exits when stdin closes (or on SIGTERM or SIGINT), after
14
+ // letting go of the Vite port first.
15
+ // Startup: prints NETJES_READY {"port","viteOrigin"} on stdout once it listens. A Vite port that is taken is tried
16
+ // again for up to VITE_PORT_WAIT_MS, after a line on stdout that says so. When the Vite dev server does not start, it
17
+ // prints NETJES_FAILED and exits with code 1: {"reason":"vite-port-in-use","port"} when its port is still taken, and
15
18
  // {"reason":"vite-failed","message","code"} for anything else, such as an error in vite.config or a package it imports
16
19
  // that is not installed (message in plain text; code is the error's when it has one, such as ERR_MODULE_NOT_FOUND, or
17
20
  // MODULE_NOT_FOUND from a CommonJS config).
18
21
  import http from 'node:http';
19
22
  import path from 'node:path';
23
+ import { createInterface } from 'node:readline';
20
24
  import { pipeline } from 'node:stream/promises';
25
+ import { setTimeout as sleep } from 'node:timers/promises';
21
26
  import { pathToFileURL } from 'node:url';
22
27
 
23
28
  const mode = process.env.NETJES_MODE === 'development' ? 'development' : 'production';
@@ -30,6 +35,12 @@ delete process.env.NETJES_TOKEN;
30
35
  const renderTimeoutMs = Number(process.env.NETJES_RENDER_TIMEOUT_MS ?? 15_000);
31
36
  const streamTimeoutMs = Number(process.env.NETJES_STREAM_TIMEOUT_MS ?? 60_000);
32
37
  const vitePort = Number(process.env.NETJES_VITE_PORT ?? 5173);
38
+ // How long the Vite dev server waits for its port when something has it, and how often it tries the port meanwhile.
39
+ // dotnet watch starts an app again while the process of the one before may still have the port: that process lets go
40
+ // of it as soon as it hears that its app is stopping, or when its stdin closes (below). A port that something else
41
+ // keeps is reported once the wait is over.
42
+ const VITE_PORT_WAIT_MS = 5_000;
43
+ const VITE_PORT_RETRY_MS = 100;
33
44
  const MAX_BODY_BYTES = 16 * 1024 * 1024;
34
45
  const CSS_FILE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/;
35
46
  // Terminal escape sequences (ECMA-48): CSI, as ESC [ or its one-character form (colours, as in Vite's code frames, which
@@ -52,6 +63,11 @@ let render;
52
63
  let renderToStream;
53
64
  /** @type {import('vite').ViteDevServer | undefined} */
54
65
  let vite;
66
+ /**
67
+ * The connections to the Vite dev server (a browser's requests, its HMR socket), which releaseVitePort ends.
68
+ * @type {Set<import('node:net').Socket>}
69
+ */
70
+ const viteSockets = new Set();
55
71
 
56
72
  /**
57
73
  * Says why the Vite dev server did not start, for .NET to report in a line of its own (Node's report of an uncaught
@@ -90,14 +106,43 @@ if (mode === 'development') {
90
106
  dev = await viteFailed(error);
91
107
  }
92
108
  vite = dev;
93
- try {
94
- await dev.listen();
95
- } catch (error) {
96
- // Most often another app's Vite dev server: .NET names the port and how to move it.
97
- if (error instanceof Error && error.message === `Port ${vitePort} is already in use`) {
98
- await failStartup({ reason: 'vite-port-in-use', port: vitePort });
109
+ dev.httpServer?.on('connection', (/** @type {import('node:net').Socket} */ socket) => {
110
+ viteSockets.add(socket);
111
+ socket.once('close', () => viteSockets.delete(socket));
112
+ });
113
+ /**
114
+ * Starts the dev server listening. Vite adds a listener for the server's 'listening' event each time; a start that
115
+ * fails leaves it behind, and it goes, so that trying the port again and again (below) does not pile them up.
116
+ */
117
+ const listen = async () => {
118
+ const httpServer = dev.httpServer;
119
+ const before = new Set(httpServer?.listeners('listening'));
120
+ try {
121
+ await dev.listen();
122
+ } catch (error) {
123
+ for (const listener of httpServer?.listeners('listening') ?? []) {
124
+ if (!before.has(listener)) httpServer?.off('listening', /** @type {(...args: unknown[]) => void} */ (listener));
125
+ }
126
+ throw error;
127
+ }
128
+ };
129
+ const waitUntil = performance.now() + VITE_PORT_WAIT_MS;
130
+ for (let waiting = false; ; ) {
131
+ try {
132
+ await listen();
133
+ break;
134
+ } catch (error) {
135
+ if (!(error instanceof Error && error.message === `Port ${vitePort} is already in use`)) await viteFailed(error);
136
+ // Still taken: most often another app's Vite dev server. .NET names the port and how to move it.
137
+ if (performance.now() >= waitUntil) await failStartup({ reason: 'vite-port-in-use', port: vitePort });
138
+ if (!waiting) {
139
+ waiting = true;
140
+ console.log(
141
+ `netjes: port ${vitePort} is in use; waiting up to ${VITE_PORT_WAIT_MS / 1000}s for it, in case the app that ran before is still stopping`,
142
+ );
143
+ }
144
+ await sleep(VITE_PORT_RETRY_MS);
99
145
  }
100
- await viteFailed(error);
101
146
  }
102
147
  const netjes = /** @type {NetjesDevApi | undefined} */ (dev.config.plugins.find((plugin) => plugin.name === 'netjes')?.api);
103
148
  /** @param {unknown} error @returns {error is Error & { file: string }} */
@@ -403,7 +448,22 @@ server.listen(0, '127.0.0.1', () => {
403
448
  process.stdout.write(`NETJES_READY ${JSON.stringify({ port, viteOrigin })}\n`);
404
449
  });
405
450
 
451
+ /**
452
+ * Stops the Vite dev server listening, so that its port is free for the app that replaces this one, and ends the
453
+ * connections browsers have to it: their Vite client then waits for a dev server to answer on the port again, and
454
+ * reloads the page. Renders go on, since they load modules through Vite and not over its port. Once is enough.
455
+ */
456
+ function releaseVitePort() {
457
+ const httpServer = vite?.httpServer;
458
+ if (!httpServer?.listening) return;
459
+ // The port is free once close returns; the connections are not waited for.
460
+ httpServer.close();
461
+ for (const socket of viteSockets) socket.destroy();
462
+ }
463
+
406
464
  async function shutdown() {
465
+ // The port first: Vite's own close comes to its HTTP server last.
466
+ releaseVitePort();
407
467
  server.close();
408
468
  await vite?.close();
409
469
  process.exit(0);
@@ -412,8 +472,14 @@ async function shutdown() {
412
472
  // A promise rejected by page code without a handler would otherwise kill every render in flight.
413
473
  process.on('unhandledRejection', (reason) => console.error('netjes: unhandled promise rejection', reason));
414
474
 
415
- // The parent keeps our stdin open for as long as it lives; EOF means it is gone.
416
- process.stdin.on('end', shutdown);
475
+ // What the parent says, a line at a time. `stopping`: the app has begun to stop, and may take a while to finish the
476
+ // requests it has (in development; NodeSidecar.cs). The app that replaces it needs the Vite dev server's port now.
477
+ createInterface({ input: process.stdin }).on('line', (line) => {
478
+ if (line.trim() === 'stopping') releaseVitePort();
479
+ });
480
+ // The parent keeps our stdin open for as long as it lives; EOF means it is gone. Ahead of the handlers Vite adds for
481
+ // the same events, which close the dev server with its port last.
482
+ process.stdin.prependListener('end', shutdown);
417
483
  process.stdin.resume();
418
- process.on('SIGTERM', shutdown);
484
+ process.prependListener('SIGTERM', shutdown);
419
485
  process.on('SIGINT', shutdown);
@@ -70,9 +70,9 @@ export default definePage(pages['/blog/[slug]'], function Post({ title, body })
70
70
 
71
71
  - Decisions live in C#: data access, validation, authorization (`.RequireAuthorization()`, `Page.Forbidden()`), redirects, caching. React renders what it is sent.
72
72
  - Loaders and actions return Netjes results (`Page.Props(...)`, `Page.NotFound()`, `ServerAction.Ok(...)`), so their types reach `generated/netjes.ts`. Use records for everything that crosses to the browser.
73
- - zod at every boundary: `definePage`/`defineLayout` with the generated schemas, `useSearchParams(schema)` and `useParams(schema)` (schemas at module level), `api[...].response.parse(...)` for fetched JSON (from `useHref(endpointUrl(...))`, never a hand-built URL), `usePublicConfig(schema)`, `Href.parse(...)` or `isHref(...)` for URLs from a CMS. A link C# sends to one of the app's pages is a `Href` in the record (`new Href("/about")`), generated as the `Href` schema, so it reaches `<Link href>` checked; a link to an endpoint or a file stays a `string`. No `any`, no casts of server data.
73
+ - zod at every boundary: `definePage`/`defineLayout` with the generated schemas, `useSearchParams(schema)` and `useParams(schema)` (schemas at module level), `useHistoryState(name, initial, schema)` for what a history entry holds, `api[...].response.parse(...)` for fetched JSON (from `useHref(endpointUrl(...))`, never a hand-built URL), `usePublicConfig(schema)`, `Href.parse(...)` or `isHref(...)` for URLs from a CMS. A link C# sends to one of the app's pages is a `Href` in the record (`new Href("/about")`), generated as the `Href` schema, so it reaches `<Link href>` checked; a link to an endpoint or a file stays a `string`. No `any`, no casts of server data.
74
74
  - Server state goes through TanStack Query, seeded from the loader with `.WithQuery(key, data)`; no `useEffect` fetching.
75
- - Internal links use `<Link>` and `route()`; forms use `<Form>` with `useAction`, and must work without JavaScript.
75
+ - Internal links use `<Link>` and `route()`; forms use `<Form>` with `useAction`, and must work without JavaScript. A form whose changes would be lost by leaving holds navigations with `useNavigationGuard` and asks ([references/routing.md](references/routing.md)).
76
76
  - Give each page a title of its own (`metadata`, or `PageMetadata` from C#), and keep the "Skip to content" link the first thing in the root layout, `app/layout.tsx`, that takes the focus, also when the root layout is kept bare and the site's chrome is in a group layout such as `app/(site)/layout.tsx`: after a client navigation the router announces the page by its title and starts the focus over at the top ([references/routing.md](references/routing.md)).
77
77
  - Never edit `generated/netjes.ts`; regenerate it and commit it with the change.
78
78
  - Anything in `Netjes:PublicConfig` or shared props is sent to the browser. So is the route of each endpoint with an `endpointUrl` key, one mapped only in Development included, once any component calls `endpointUrl`: keep secrets out of routes, and authorize on the endpoint.
@@ -18,7 +18,7 @@ app.MapPageLoader("/projects/[id]", async (string id, ClaimsPrincipal user, AppD
18
18
 
19
19
  - It binds like a minimal API: route values by name, services, `ClaimsPrincipal`, `HttpContext`, `CancellationToken`, `[FromQuery]`.
20
20
  - It reads no request body, so a complex type that is not a registered service needs `[AsParameters]` or a static `BindAsync`. A loader or action whose parameters minimal APIs cannot bind stops the app at startup, saying which and why. So does a loader parameter that reads the body (`[FromBody]`, `[FromForm]`, `IFormFile`): posted data belongs in a page action or a server action. A page loader stops the app too for a type that adds accepts metadata (`IAcceptsMetadata`) for itself, and must not get `.Accepts<T>()`: routing would match the page only for requests with that Content-Type, and navigations would get the not-found page. Repeated query values bind to an array (`int[] ids`); `List<int>` and `IEnumerable<int>` stop the app at startup, the latter because minimal APIs would bind it from services.
21
- - `Page.Props(record)` names the props type for `pages['/projects/[id]']`. `Page.NotFound()`, `Page.Forbidden()`, `Page.Unauthorized()` render the nearest boundary file; `Page.Redirect(url)` and `Page.LocalRedirect(returnUrl)` (for URLs from the request) redirect, and the client router follows them. `.WithStatus(422)` changes the status.
21
+ - `Page.Props(record)` names the props type for `pages['/projects/[id]']`. `Page.NotFound()`, `Page.Forbidden()`, `Page.Unauthorized()` render the nearest boundary file; `Page.Redirect(url)` and `Page.LocalRedirect(returnUrl)` (for URLs from the request) redirect, and the client router follows them; one to a URL no page answers (a signed file URL, an endpoint) the browser loads once, as a document, so a page action's download form needs no `reloadDocument`. `.WithStatus(422)` changes the status.
22
22
  - A link to one of the app's pages is a `Href` in the props record (`public sealed record NavLink(Href Href, string Label)`, `new Href($"/projects/{Uri.EscapeDataString(id)}")`, with each value encoded), root-relative, in the page file's spelling (the props parse compares literal segments with their case, so `/About` fails for `app/about/page.tsx`) and without the base path. It is generated as the `Href` schema, so the props parse checks it against the pages and the component passes it to `<Link href>` as it is. `new Href(url)` throws `ArgumentException` unless the URL starts with `/` (and not `//` or `/\`), `?`, `#`, `http:`, `https:`, `mailto:` or `tel:`, and also for a control character anywhere in it or a space at either end; `Href.TryCreate` returns false instead. C# checks only that shape: a root-relative `Href` that no page serves fails the whole props parse and the page shows its error boundary (a 500 from the server only when no Suspense boundary, such as a `loading.tsx`, is above the component that parses; otherwise the server sends that boundary's fallback with the loader's status), so a link to an endpoint or a file, such as `/llms.txt`, stays a `string`, rendered with `useHref`, and so does a link from a CMS, checked with `isHref` where it is rendered. No query or route value binds to an `Href`: a `returnUrl` stays a `string` for `Page.LocalRedirect`, and a `[FromForm]` input takes a `string`, since form binding reads no `Href` from the field of its name. `LinkGenerator`'s `HttpContext` overloads add the base path, so pass `pathBase: PathString.Empty`.
23
23
  - It returns a `RouteHandlerBuilder`: `.RequireAuthorization()`, `.CachePage(...)` and filters apply.
24
24
  - A page's loader runs before its layouts' loaders, so a page under a layout that checks access checks it too.
@@ -74,11 +74,12 @@ const nameError = state?.ok === false ? state.errors.name?.[0] : undefined;
74
74
  - Every action needs `app.UseAntiforgery()` (after authentication) and checks the origin; `<Form>` and `serverActions` send the token. `MapAction` bodies are limited to 1 MB (`ActionBodySizeLimit`); an upload action sets `[RequestSizeLimit(bytes)]`. Page actions keep the server's limit.
75
75
  - Name actions `feature.verb`. Names are compared ignoring case, and a second `MapAction` of a name, the app's or a page package's, stops the app at startup. Every action answers at `/_netjes/actions/{name}`, so `MapAction` in a `MapGroup` with a prefix throws; map it on the app, or on `MapGroup("")` for shared conventions. Check authorization inside the action, or with `.RequireAuthorization()`, as for any endpoint.
76
76
  - `app.MapPageAction("/guestbook", ...)` is the other kind: a POST to the page's own URL from `<Form method="post">`, fields typed in `forms['/guestbook']`. Its input's DataAnnotations and `IValidatableObject` are checked as for `MapAction`: on a failure the delegate does not run, the page renders again from its loader (422), and `const failed = usePageActionState()` gives `failed.errors` and `failed.values` (null otherwise). Checks that need data stay in the delegate: return `Page.Props(...)` with your own errors and the typed values (`.WithStatus(422)`), or `Page.Redirect(...)` after a change.
77
- - An action or post that sets or deletes a cookie (signing in or out) makes the client router forget the pages it keeps for back and forward, reload the page on screen and clear the query cache, in every tab of the app in that browser. Nothing to do in the action; a proxy must pass `X-Netjes-Cookies` through.
77
+ - A rate limit goes on the action (`.RequireRateLimiting("sign-in")`, `app.UseRateLimiter()` after `app.UseNetjes()`), with `limiter.OnRejected = (context, _) => Page.TooManyRequests(context, "Too many attempts.")`: a refused page action renders its page again with 429, and `usePageActionState()` gives `failed.status === 429`, the message in `failed.errors['']` and the declared fields' values (never a password); a server action's form without JavaScript gets the same through `useAction`, and a script's call throws `ServerActionError` (429, the message). Without it, a refused post gets the error page.
78
+ - An action or post that sets or deletes a cookie (signing in or out) makes the client router forget the pages it keeps for back and forward, reload the page on screen and clear the query cache, in every tab of the app in that browser. Nothing to do in the action; a proxy must pass `X-Netjes-Cookies` through. A cookie that changes nothing another page shows, such as a cart's, goes in `options.NoReloadCookies = ["cart"]` (or a prefix ending in `*` for a name per store: `".app.cart.*"`; a `*` elsewhere stops the app at startup): an action that writes only those reloads nothing, so return what changed or call `.Refresh()`. A cookie authentication scheme's cookie always reloads, listed, covered by a prefix or not.
78
79
 
79
80
  ## Page packages
80
81
 
81
- A mounted page package's loaders, layout loaders, actions and endpoints are mapped by the package's extension, through its mount, and typed in the package's own generated file, not in the app's. The app's `generated/netjes.ts` routes the package's pages (`route('/help/contact')`) and holds only what the app maps itself; run `npx netjes generate` after updating a package. The app's `MapPageLoader`, `MapPageAction` and `MapLayoutLoader` refuse a package's page or layout, naming the mount. A page the app replaces with `.Override` renders with the package's loader, so it reads its props from the package's file: `definePage(pages['/contact'], ...)` with `pages` from `'@acme/help-center/generated'`. The app's own pages under the prefix, and their loaders, are the app's as before. Schemas both sides read by key, such as an export a package adds with `AddTypeScriptExport`, are in both files.
82
+ A mounted page package's loaders, layout loaders, actions and endpoints are mapped by the package's extension, through its mount, and typed in the package's own generated file, not in the app's. The app's `generated/netjes.ts` routes the package's pages (`route('/help/contact')`) and holds only what the app maps itself; run `npx netjes generate` after updating a package. The app's `MapPageLoader`, `MapPageAction` and `MapLayoutLoader` refuse a package's page or layout, naming the mount. A page the app replaces with `.Override` renders with the package's loader, so it reads its props from the package's file: `definePage(pages['/contact'], ...)` with `pages` from `'@acme/help-center/generated'`. The app's own pages under the prefix, and their loaders, are the app's as before. Schemas both sides read by key, such as an export a package adds with `AddTypeScriptExport`, are in both files; with `appOnly: true` an export is in the app's alone.
82
83
 
83
84
  ## JSON endpoints and TanStack Query
84
85
 
@@ -97,7 +98,7 @@ const url = useHref(endpointUrl('GET /api/projects/{slug}/stats', { slug }));
97
98
  const stats = useQuery({ queryKey: ['projects', slug, 'stats'], queryFn: () => fetchStats(url) });
98
99
  ```
99
100
 
100
- Typed results (`TypedResults`, `Results<...>`) give the endpoint its `api` schemas, keyed by method and route template. `endpointUrl(key, params, search)` builds the URL of the app's endpoints that are not pages, JSON or not (a JSON endpoint has a key per method except `HEAD`, any other endpoint one for `GET`, if it answers `GET`), by the same key: the route values and the query values its handler binds are typed from C#, an enum as its C# names and values, and `search` adds others. It has no base path: `useHref` adds it, for a `fetch` or an `<a href>`. Its result is a `string`, which the type of `<Link href>` does not accept, as an endpoint is not a page: link it with `<a href={useHref(endpointUrl(...))}>`. Seed the same query key from the loader with `.WithQuery(key, data)` and the query renders on the server with no fetch; keep the key in one place on each side. Seeded data is fresh for the default `staleTime` (one minute).
101
+ Typed results (`TypedResults`, `Results<...>`) give the endpoint its `api` schemas, keyed by method and route template. `endpointUrl(key, params, search)` builds the URL of the app's endpoints that are not pages, JSON or not (a JSON endpoint has a key per method except `HEAD`, any other endpoint one for `GET`, if it answers `GET`, and one for `POST`, if it accepts a posted form, so `<Form method="post" action={endpointUrl('POST /users/{id}/export', { id })}>` posts to a download), by the same key: the route values and the query values its handler binds are typed from C#, an enum as its C# names and values, and `search` adds others. It has no base path: `useHref` adds it, for a `fetch` or an `<a href>`. Its result is a `string`, which the type of `<Link href>` does not accept, as an endpoint is not a page: link it with `<a href={useHref(endpointUrl(...))}>`. Seed the same query key from the loader with `.WithQuery(key, data)` and the query renders on the server with no fetch; keep the key in one place on each side. Seeded data is fresh for the default `staleTime` (one minute).
101
102
 
102
103
  `MapGet` answers `GET` only: a `HEAD` to its URL goes to whatever else matches it, often the not-found page. For an endpoint that crawlers, link checkers or monitors ask with `HEAD`, map `app.MapMethods(pattern, [HttpMethods.Get, HttpMethods.Head], handler)`; its `api` key stays `GET` and the route. Pages, `/sitemap.xml`, `/robots.txt`, `/_netjes/image` and the locale redirect answer `HEAD` already.
103
104
 
@@ -22,7 +22,7 @@ For these startup failures the app logs one critical entry, saying what is wrong
22
22
 
23
23
  - `docker compose up`: development, with `dotnet watch` and Vite HMR, ports bound to localhost.
24
24
  - `docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d`: the production image, a non-root user on a read-only filesystem, with a health check on `/healthz` and Data Protection keys in a named volume.
25
- - Both publish the app on host port 8080; `APP_PORT` (in the shell or a `.env` file) moves it. Vite's 5173 stays.
25
+ - Both publish the app on host port 8080; `APP_PORT` (in the shell or a `.env` file) moves it. Development also publishes Vite on 5173, which `VITE_PORT` moves (the same port inside and out, with `Netjes__ViteDevPort` set to it).
26
26
  - The production image runs `tini -s -- dotnet MyApp.dll`: tini is PID 1, passes `docker stop`'s SIGTERM on, and exits with the app's code, so a crash ends the container (134) and `restart: always` acts. When .NET itself is a container's PID 1, its abort does not end it. On arm64 it spins at 100% CPU and never exits; after a crash later than startup the rest of the app keeps serving and `/healthz` still passes. On x86-64 under emulation it has been seen to exit after a few seconds, with 139 instead of 134. An image of the app's own, or one from an older template, needs an init too: the template's `tini` stage, its `COPY` and the `ENTRYPOINT`, or the host's (`docker run --init`, Compose `init: true`, ECS `initProcessEnabled`).
27
27
 
28
28
  The image restores Netjes from NuGet and npm, so the app must reference the packages, as an app made with `npx netjes new` does (from a Netjes checkout, pass `--packages`).
@@ -47,24 +47,28 @@ ASP.NET Core ranks the endpoints a URL matches by order (pages and `MapGet` endp
47
47
 
48
48
  - `<Link href={route('/blog/[slug]', { slug })}>`: client navigation with prefetch on hover and focus; takes a `ref`, as `<Form>`, `<SubmitButton>` and `<Image>` do. `route()` and the `Href` type come from `generated/netjes.ts`, so a wrong path or a missing parameter is a type error.
49
49
  - `route(pattern, params, search, { hash })` builds the query from `search` and a `#fragment` from `hash`, the id of an element on the page: `route('/docs/[...path]', { path }, undefined, { hash: 'keys' })`. Pass `undefined` as `search` for a link with a fragment and no query.
50
- - `aria-current="page"` goes on a link to the page on screen: the same path (`/x` and `/x/` are one) and the page's values for every query parameter the link names. Parameters it leaves out do not count, and a `#` link is never marked. Pass `aria-current` to decide yourself: `undefined` on an "All" filter (`/blog`) while a filter is on, `"true"` on a section link (Docs) below the section's page, from `useSelectedLayoutSegments()` or `usePathname()`.
50
+ - `aria-current="page"` goes on a link to the page on screen: the same path (`/x` and `/x/` are one) and the page's values for every query parameter the link names. Parameters it leaves out do not count (with `exactQuery`, they do: the page's query must be the link's, in any order, which a list's paging and sort links need, so Previous to page 1 is not marked on page 2), and a `#` link is never marked. Pass `aria-current` to decide yourself: `undefined` on an "All" filter (`/blog`) while a filter is on, `"true"` on a section link (Docs) below the section's page, from `useSelectedLayoutSegments()` or `usePathname()`.
51
51
  - `useRouter()`: `push`, `replace`, `prefetch`, `refresh`, `back`, `forward`. The promises of `push`, `replace` and `refresh` resolve once the router has handed the page to React, when the old page can still be on screen; code that needs the new page runs in an effect of that page, or in one that depends on `usePathname()` and `useSearchParams()`.
52
52
  - After a navigation to another page the router announces it in a polite live region (its title, else its first `h1`, else its path) and starts the focus over at the top of the document. A link to a `#fragment`, on the page on screen or on another, moves the focus to that element instead, which is how the skip link works; Back and Forward restore the scroll position and give a fragment no focus. The region speaks only when the name differs from the previous page's, so give each page its own title, and keep the skip link the first thing in the root layout that takes the focus: `<Link href="#content" prefetch="none" className="sr-only focus:not-sr-only">Skip to content</Link>` and `<main id="content">`. The focus stays on the same page (query changes, refreshes, a post that stays, a modal), on an `autoFocus` element or wherever the app's code moved it during the navigation (a link's `onClick` and a form's `onSubmit` included), on a `scroll={false}` link that still has it, and in a field the user types into. To put it elsewhere on the new page, do it in that page's `useEffect`, which runs after the router's. If a menu closes in an effect after the navigation, give the focus back to its button only while the focus is still inside the menu. In end-to-end tests, focus a field before typing after a navigation (`locator.fill()` does), and read the element you mean rather than a container's whole text.
53
53
  - `usePathname()`, `useSearchParams(schema?)`, `useParams(schema?)`: with a schema the values are parsed; catch-all params are arrays. Search values a schema rejects are dropped so its defaults apply; a rejected route param goes to the error page, so constrain route params in C#.
54
54
  - `useSelectedLayoutSegment()`, `useSelectedLayoutSegments()`: the active child segment in a layout (tabs).
55
- - `useNavigation()`: `idle`, `loading` or `submitting`, for progress indicators.
55
+ - `useNavigation()`: `idle`, `loading` or `submitting`, for progress indicators. After a navigation, `refresh()` or a form post that got no page (no answer while the browser is online, or a server error that is no page), the page stays and `idle` carries `error: { kind: 'navigate' | 'refresh' | 'submit', status, location }` (`status` null for no answer; a post the server redirected went through, so a failure of the page it leads to is `'navigate'`) until the next one starts; show it in the app's shell, with Try again (`router.refresh()`) for a refresh. `refresh()` never rejects: read its failure here, not in a `catch`. An offline browser still loads the URL as a document.
56
+ - `useHistoryState(name, initial, schema?)`: `useState` kept with the history entry, through Back, Forward and a reload, for what a page keeps of a visit (a list's ticks, the list a record was opened from). `initial` on the server and while hydrating. A new entry starts from `initial` or from what its navigation carried (`historyState` on `<Link>`, `router.push(href, { historyState })`, `router.replace`); a navigation that keeps the page on screen (a query, a fragment, a refresh) keeps the values, one to another page starts over. The setter, like `useState`'s, keeps working, as the same function, while the page stays (`await deleteTicked(ticked); setTicked([])` clears the ticks after an action that refreshes the page), and sets nothing once the page has left or Back or Forward went to another entry. Small values `structuredClone` can copy (ids, not rows); a page package prefixes its names. A schema at module level turns a value it rejects into `initial`. `createTestApp({ historyState })` seeds them in a test.
57
+ - `useNavigationGuard({ when, onAttempt })`: while `when` holds (a form with changes not saved), links, `<Form method="get">`, `router.push`, `replace`, `back`, `forward` and the browser's Back and Forward wait for `onAttempt(attempt)` to call `attempt.proceed()` or `attempt.stay()`; the page draws the question (`attempt.to`, `attempt.type`). For Back and Forward the entry is put back first. Not held: a fragment of the page on screen, form posts, server actions, `refresh()`, other origins, and the page a redirect that answers a post, an action or a refresh leads to (the sign-in page after the session expired): keep a draft in `sessionStorage` where changes must outlast that. While it holds, `beforeunload` covers a reload and closing the tab. `proceed()` always works, also after the form saved and `when` turned false. Navigate with the router, not `history.pushState` or `location.replace`: the guard counts Back and Forward by the places the router writes into `history.state`.
58
+ - `useHistoryRestore(callback)`: called when Back or Forward shows the page from memory (the router's, or the browser's back-forward cache), as it was when left; `useHistoryRestore(() => void router.refresh())` for a page that must show what is current, such as a list after its record changed.
56
59
  - External URLs, `target`, `download` and modified clicks behave like a plain `<a>`; `reloadDocument` forces a full load.
57
60
 
58
61
  ## Metadata
59
62
 
60
63
  - `export const metadata: Metadata = { title: 'About' }` on pages and layouts; a layout's `title: { default, template: '%s · Site' }` applies to the pages below it. A `default` below the root goes through the nearest template above it, like a string (`'Docs'` under `'%s · Site'` is `Docs · Site`), never through the one beside it; `{ absolute: 'Docs' }` skips every template.
61
- - From C#: `.WithMetadata(new PageMetadata { Title = post.Title, Description = ... })` on the loader's result, merged over the files' metadata.
64
+ - From C#: `.WithMetadata(new PageMetadata { Title = post.Title, Description = ... })` on the loader's result, merged over the files' metadata, so the layouts' title templates wrap `Title`; `AbsoluteTitle = ...` is a title they leave alone.
65
+ - `<html lang>` is `NetjesOptions.Lang` (or the locale), and `PageMetadata.Lang = "nl"` from a loader sets it: a layout loader's for the pages below it, a page loader's wins. A client navigation updates it, and a page without one goes back to the app's. It must be a BCP 47 tag's shape, or setting it throws. Do not set `document.documentElement.lang` in an effect.
62
66
  - Below a layout that sets a title, use `metadata`, not a `<title>` element (that makes a second title).
63
67
  - Code the first paint needs, such as a theme set on `<html>`, goes in `<Script id="theme" strategy="beforeInteractive">{code}</Script>` first in the root layout (a script takes no focus, so the skip link after it stays first): the server writes inline code where it stands and the parser runs it there. An external `beforeInteractive` script runs once the shell is parsed, in order, before the page's code; hydration waits for it, and inline code runs before it. That holds in a server-rendered document: a component that mounts in the browser, after a client navigation or when no sidecar was ready, adds its script after mounting, as `afterInteractive` does. Keep them outside Suspense boundaries. Under a hash-based policy, list the hash of the code as the document carries it, which `inlineScriptHashes` from `netjes/testing` gives, and an external script's origin in `script-src`.
64
68
 
65
69
  ## Protecting sections
66
70
 
67
- `app.MapLayoutLoader("/dashboard", ...).RequireAuthorization()` protects every page below `app/dashboard/`; `app.MapPages().RequireAuthorization()` protects every page that has no loader of its own; a page loader takes `.RequireAuthorization()` itself. With cookie authentication, answer 401/403 instead of redirecting (`OnRedirectToLogin`, `OnRedirectToAccessDenied`) so `unauthorized.tsx` and `forbidden.tsx` render. `MapPages()`'s conventions never challenge an unknown URL, which stays a 404; a fallback policy covers the not-found fallback too, and challenges a visitor it refuses there. The not-found page, like the status and error pages of server actions and minimal APIs and a page's 401, 403 and pre-authorization status pages (a rate limiter's 429), runs a layout loader only for a visitor the pages in its folder would let in (its conventions and those above it, which pages with a loader carry too, and for file pages `MapPages()`'s or the fallback policy), and renders inside the layouts above it for the rest. So under `MapPages().RequireAuthorization()` the root `unauthorized.tsx` renders without the root layout when that has a loader: make it stand on its own, and never put `.AllowAnonymous()` on a layout loader to keep it, since that opens every page below. `Page.Render(pattern)` from a minimal API runs the page's layout loaders under that endpoint's authorization: protect it as the page is.
71
+ `app.MapLayoutLoader("/dashboard", ...).RequireAuthorization()` protects every page below `app/dashboard/`; `app.MapPages().RequireAuthorization()` protects every page that has no loader of its own; a page loader takes `.RequireAuthorization()` itself. With cookie authentication, answer 401/403 instead of redirecting (`OnRedirectToLogin`, `OnRedirectToAccessDenied`) so `unauthorized.tsx` and `forbidden.tsx` render, or send the visitor to a sign-in page with `cookie.Events.OnRedirectToLogin = context => Page.RedirectToSignIn(context.HttpContext, "/sign-in")`: a document gets a redirect and a client navigation a redirect payload, to `/sign-in?returnUrl=<path and query>`, and a server action's call keeps an empty 401; the sign-in page checks `returnUrl` with `Page.IsLocalUrl` before `Page.LocalRedirect`. `MapPages()`'s conventions never challenge an unknown URL, which stays a 404; a fallback policy covers the not-found fallback too, and challenges a visitor it refuses there. The not-found page, like the status and error pages of server actions and minimal APIs and a page's 401, 403 and pre-authorization status pages (a rate limiter's 429), runs a layout loader only for a visitor the pages in its folder would let in (its conventions and those above it, which pages with a loader carry too, and for file pages `MapPages()`'s or the fallback policy), and renders inside the layouts above it for the rest. So under `MapPages().RequireAuthorization()` the root `unauthorized.tsx` renders without the root layout when that has a loader: make it stand on its own, and never put `.AllowAnonymous()` on a layout loader to keep it, since that opens every page below. `Page.Render(pattern)` from a minimal API runs the page's layout loaders under that endpoint's authorization: protect it as the page is.
68
72
 
69
73
  A check that depends on data (is this user a member of this project?) goes in the page loader as well as in the layout loader: a page's loader runs before its layouts' loaders, and a layout loader is skipped on client navigations within its section while its own route values, the user and the roles stay the same. A layout loader also binds only the route values of its own URL, so it cannot check a deeper one.
70
74
 
@@ -75,7 +79,7 @@ A page package is an npm package and a NuGet package of one version that bring p
75
79
  - The prefix is in folder syntax: `/help`, `/(marketing)/help` (the same URL, inside `app/(marketing)/layout.tsx`), `/[tenant]/help` (`tenant` is a route value). The package's folder of pages merges into `app/` under it, folder by folder: its `layout.tsx` at the mount wraps the app's own pages in `app/help/`, and its `(center)` group wraps an app page in `app/help/(center)/`. Link to its pages with the app's `route('/help/articles/[slug]', { slug })`.
76
80
  - An app page of the same shape as a package's page stops the app. To replace the package's page, put the app's in the same folder and add `.Override("/help/contact")` to the mount: it renders with the package's loader, so it reads `pages['/contact']` from the package's generated file (`import { pages } from '@acme/help-center/generated'`), and the app maps no loader for it. Layouts and boundaries cannot be replaced.
77
81
  - Conventions on the mount (`.RequireAuthorization()`, `.ExcludeFromExport()`, `.ExcludeFromSitemap()`) cover the package's pages and endpoints, not the app's pages under the prefix; protect those with a layout loader above them, as before. An app layout loader above the mount protects the package's pages too.
78
- - An unknown URL below the mount renders the package's `not-found.tsx`, after the layout loaders on the way, and `MapPages()`'s authorization, have authorized the visitor.
82
+ - An unknown URL below the mount renders the package's `not-found.tsx`, after the layout loaders on the way, and `MapPages()`'s authorization, have authorized the visitor; those loaders run for the user a page there would have (a package's own sign-in scheme included). Under a fallback policy, an unknown URL is challenged before that, unless the mount gives its not-found conventions of its own: `.ConfigureNotFound(notFound => notFound.AllowAnonymous())` answers the URLs below the mount with the package's 404.
79
83
  - A package that draws its own shell (a back-office package) should not render inside the site's header: keep `app/layout.tsx` to providers and the skip link, and move the site's header and footer into `app/(site)/layout.tsx` with the site's pages. URLs do not change. The `package-shell` route warning names an app that has not.
80
84
  - Route warnings for packages: `package-shell`, `package-unmounted` (in the build but not mounted), `package-nonce` (a package whose pages stream, under a Content-Security-Policy without a nonce), and `overlap` for a literal page of one source next to a parameter page of the other (`/help/settings` from the package next to the app's `app/help/[section]`).
81
85
 
@@ -4,7 +4,7 @@ Test first: write the test, watch it fail for the reason you expect, then change
4
4
 
5
5
  ## Components and pages: Vitest
6
6
 
7
- `netjes()` in `vite.config.ts` sets up Vitest: jsdom, Testing Library cleanup (a config with `setupFiles` of its own lists `netjes/testing/setup` in them), `e2e/`, `dist/`, `bin/` and `obj/` excluded, and in every app a setup file of Netjes's own, which lets Testing Library work with fake timers and hands `createTestApp` the app's query defaults. Inline `test.projects` that share the root's Vite server, Vitest 5's default, get none of this: set `sharedViteServer: false` in the root's `test` options. Tests sit next to the code as `*.test.tsx` and run with `npm test`.
7
+ `netjes()` in `vite.config.ts` sets up Vitest: jsdom, Testing Library cleanup (a config with `setupFiles` of its own lists `netjes/testing/setup` in them), `e2e/`, `dist/`, `bin/` and `obj/` excluded, and in every app a setup file of Netjes's own (`netjes/testing/vitest`; a page package's tests, which run without the plugin, list it in `setupFiles`), which lets Testing Library work with fake timers and hands `createTestApp` the app's query defaults. Inline `test.projects` that share the root's Vite server, Vitest 5's default, get none of this: set `sharedViteServer: false` in the root's `test` options. Tests sit next to the code as `*.test.tsx` and run with `npm test`.
8
8
 
9
9
  ```tsx
10
10
  import { render, screen } from '@testing-library/react';
@@ -25,12 +25,15 @@ it('shows the validation error from C# next to the field', async () => {
25
25
  });
26
26
  ```
27
27
 
28
- `createTestApp({ url, params, shared, queries, defaultOptions, navigation, antiforgery, actions })` returns `{ Wrapper, navigations, queryClient }`:
28
+ `createTestApp({ url, params, shared, queries, defaultOptions, navigation, antiforgery, pageActionState, historyState, actions })` returns `{ Wrapper, navigations, queryClient }`:
29
29
 
30
30
  - `url` and `params` set what `usePathname`, `useSearchParams` and `useParams` see; `shared` is what `useSharedProps` returns; `queries: [{ key, data }]` seeds TanStack Query as a loader's `.WithQuery` would.
31
31
  - The `QueryClient` starts from the app's `netjes({ query: { defaultOptions } })`: a failed query or mutation is tried as often as in the app, with no wait between the tries, so the test sees the error the app shows after its last try. `defaultOptions` goes over them: `{ queries: { retry: false } }` shows the error after the first request. Seeded data is fresh for the app's `staleTime` from when `createTestApp()` is called: with a `staleTime` of 0, or in a component rendered after a fake clock moved past it, a seeded query is fetched again as it mounts; answer that request (MSW) or pass `{ queries: { staleTime: 60_000 } }`.
32
32
  - `actions` answers server action calls by name: `{ ok: true, result }` or `{ ok: false, status: 422, errors }` (add `fields: ['email']` to name the fields a failed state's `values` keep, as the server does). A failure other than a 422 throws a `ServerActionError`, withheld unless the answer has the `message` the server would send: `{ ok: false, status: 403, errors: {}, message: 'Forbidden' }`. A component that calls an action, even from an effect as it mounts, must render inside `app.Wrapper`: outside it the call fails with "called before the page was ready".
33
- - `navigations` records what happened: `{ type: 'push' | 'replace', href }`, `{ type: 'refresh' | 'back' | 'forward' }`, `{ type: 'submit', action, data }` for form posts, `{ type: 'action', name, input }` for action calls.
33
+ - `pageActionState: { errors, values }` is what `usePageActionState()` returns after a page action's input failed its checks, with status 422 (or `status: 429` for a post the rate limiter refused), for the page `route` names (else the URL's path).
34
+ - `historyState: { name: value }` is what `useHistoryState` reads for the entry on screen, as a navigation carried it or an earlier visit left it (a record page's `{ list: '/orders?status=open' }`). A value a component sets is kept; a push or a replace keeps the values of the same path, starts another path over and sets what it carried on top, as the router does.
35
+ - A component with `useNavigationGuard` that holds is asked about a push or a replace (a link, a GET form) first, and `navigations` records it once the guard proceeds; `back` and `forward` are recorded without asking.
36
+ - `navigations` records what happened: `{ type: 'push' | 'replace', href }`, with `historyState` when the navigation carried any (`{ type: 'push', href: '/orders/7', historyState: { list: '/orders' } }`), `{ type: 'refresh' | 'back' | 'forward' }`, `{ type: 'submit', action, data }` for form posts, `{ type: 'action', name, input }` for action calls.
34
37
 
35
38
  Render a page component directly with the props its loader would send: `render(<Post title="Hello" body="..." />, { wrapper: createTestApp({ url: '/blog/hello' }).Wrapper })`. A page made with `definePage` parses them with its schema, so props the loader could not send fail the test with `Invalid props: ...`.
36
39
 
package/src/actions.tsx CHANGED
@@ -213,7 +213,7 @@ export function useAction<TInput, TResult>(
213
213
  const { actionState } = usePagePayload();
214
214
  const initial: ActionState<TResult> | null =
215
215
  actionState?.action === action.actionName
216
- ? { ok: false, status: 422, errors: actionState.errors, values: actionState.values }
216
+ ? { ok: false, status: actionState.status ?? 422, errors: actionState.errors, values: actionState.values }
217
217
  : (options.initialState ?? null);
218
218
  const { onSubmit } = options;
219
219
  const [state, dispatch, pending] = useActionState((_previous: ActionState<TResult> | null, formData: FormData) => {
@@ -232,15 +232,16 @@ export type PageActionFailure = { ok: false; status: number; errors: Record<stri
232
232
  /**
233
233
  * After the input of the page's action (`MapPageAction`) failed its checks, its DataAnnotations or
234
234
  * `IValidatableObject`: the errors per field and the submitted values of the fields the action declares, as the page
235
- * is rendered again from its loader, with and without JavaScript. Else null, also after a server action's failure,
236
- * which `useAction` reads.
235
+ * is rendered again from its loader, with and without JavaScript, with status 422. After the rate limiter refused the
236
+ * post (`Page.TooManyRequests` in C#), the same with status 429 and the limiter's message under `''`. Else null, also
237
+ * after a server action's failure, which `useAction` reads.
237
238
  */
238
239
  export function usePageActionState(): PageActionFailure | null {
239
240
  const { actionState, route } = usePagePayload();
240
241
  return useMemo(
241
242
  () =>
242
243
  actionState && route !== null && actionState.action === route
243
- ? { ok: false, status: 422, errors: actionState.errors, values: actionState.values }
244
+ ? { ok: false, status: actionState.status ?? 422, errors: actionState.errors, values: actionState.values }
244
245
  : null,
245
246
  [actionState, route],
246
247
  );
package/src/document.tsx CHANGED
@@ -2,7 +2,13 @@ import type { ReactNode } from 'react';
2
2
  import { DEFERRED_BOOTSTRAP } from './deferred.ts';
3
3
  import { DATA_ELEMENT_ID, type DocumentInfo, SHELL_END_ID } from './payload.ts';
4
4
 
5
- type DocumentProps = { info: DocumentInfo; dataJson: string; children: ReactNode };
5
+ type DocumentProps = {
6
+ info: DocumentInfo;
7
+ /** The `lang` of `<html>`: the first page's (`documentLang`), or else the document's own. */
8
+ lang?: string | undefined;
9
+ dataJson: string;
10
+ children: ReactNode;
11
+ };
6
12
 
7
13
  /**
8
14
  * The `<html>` shell around every page. React renders and hydrates the whole document, so `<title>`, `<meta>`
@@ -13,7 +19,7 @@ type DocumentProps = { info: DocumentInfo; dataJson: string; children: ReactNode
13
19
  * the head, the payload first in the body. The empty element at the end of the body is the last thing in the shell,
14
20
  * which the client entry waits for before it hydrates: a cached entry can run long before the parser gets there.
15
21
  */
16
- export function Document({ info, dataJson, children }: DocumentProps) {
22
+ export function Document({ info, lang = info.lang, dataJson, children }: DocumentProps) {
17
23
  const { nonce } = info;
18
24
  // Netjes owns <html> and <body>: the app's layout renders inside the body, so its markup cannot give either one an
19
25
  // attribute. A script that runs before hydration can (a theme, a browser extension, a translator), and in development
@@ -23,9 +29,10 @@ export function Document({ info, dataJson, children }: DocumentProps) {
23
29
  // the body, and a mismatch there is neither reported nor repaired. The elements in the body are checked as before,
24
30
  // their attributes and their text. React does not write the prop into the markup, and production does not check
25
31
  // attributes at all. The check is off for `lang` too: the server and the client read it from the same payload, so it
26
- // differs only when a script changed it, or when Netjes has a bug.
32
+ // differs only when a script changed it, or when Netjes has a bug. This element keeps the first page's `lang`: after
33
+ // a client navigation the router sets the attribute itself (RouterProvider's `documentLang`).
27
34
  return (
28
- <html lang={info.lang} suppressHydrationWarning>
35
+ <html lang={lang} suppressHydrationWarning>
29
36
  <head>
30
37
  <meta charSet="utf-8" />
31
38
  <meta name="viewport" content="width=device-width, initial-scale=1" />
package/src/index.ts CHANGED
@@ -40,12 +40,21 @@ export type { PageKind, Params, SeededQuery, SegmentRef } from './payload.ts';
40
40
  export { usePublicConfig } from './public-config.tsx';
41
41
  export { Script, type ScriptProps, type ScriptStrategy } from './script.tsx';
42
42
  export {
43
+ type NavigateOptions,
44
+ type NavigationAttempt,
45
+ type NavigationAttemptType,
46
+ type NavigationError,
47
+ type NavigationGuardOptions,
43
48
  type NavigationState,
49
+ type SetHistoryState,
44
50
  type SubmitError,
45
51
  type Router,
46
52
  useBasePath,
53
+ useHistoryRestore,
54
+ useHistoryState,
47
55
  useHref,
48
56
  useNavigation,
57
+ useNavigationGuard,
49
58
  useParams,
50
59
  usePathname,
51
60
  useRouter,
package/src/lang.ts ADDED
@@ -0,0 +1,28 @@
1
+ // The `lang` of `<html>`: a page loader's or a layout loader's `PageMetadata.Lang`, else the root's.
2
+ import type { PagePayload } from './payload.ts';
3
+
4
+ /**
5
+ * The shape of a BCP 47 language tag (RFC 5646), as `PageMetadata.Lang` checks it in C#: a primary subtag of two to
6
+ * eight letters, or `x` (private use) or `i` (grandfathered) with at least one subtag after it, then subtags of one to
7
+ * eight letters and digits, each after one hyphen. ASCII only, so no quote, angle bracket or space reaches `<html>`.
8
+ */
9
+ const LANGUAGE_TAG = /^(?:[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*|[xXiI](?:-[A-Za-z0-9]{1,8})+)$/;
10
+
11
+ export function isLanguageTag(value: string): boolean {
12
+ return LANGUAGE_TAG.test(value);
13
+ }
14
+
15
+ /**
16
+ * The document's `lang` for a page: the page loader's, else the innermost layout loader's, else the locale the page
17
+ * was rendered in (`AddNetjesLocalization`), else `root`, the lang the app's root gave the document (the locale it was
18
+ * first rendered in, or `NetjesOptions.Lang`). It is what the server writes for a fresh load of the page's URL
19
+ * (`DocumentLang` in PageRenderer.cs). A reused segment holds the lang its loader gave it when it last ran.
20
+ */
21
+ export function documentLang(payload: Pick<PagePayload, 'lang' | 'segments' | 'locale'>, root: string): string {
22
+ if (payload.lang !== undefined) return payload.lang;
23
+ for (let i = payload.segments.length - 1; i >= 0; i--) {
24
+ const lang = payload.segments[i]?.lang;
25
+ if (lang !== undefined) return lang;
26
+ }
27
+ return payload.locale ?? root;
28
+ }
package/src/link.tsx CHANGED
@@ -16,6 +16,17 @@ export type LinkProps = Omit<ComponentPropsWithRef<'a'>, 'href'> & {
16
16
  prefetch?: 'intent' | 'none';
17
17
  /** Let the browser follow it with a full page load: for a page of the app that must load in full, or a page on another site. */
18
18
  reloadDocument?: boolean;
19
+ /**
20
+ * Mark the link `aria-current="page"` only when its query is the page's whole query: the same parameters with the
21
+ * same values, in any order. Default false: parameters the link leaves out do not count. For a list's paging and sort
22
+ * links, where a link that drops `page` goes to another page of the list.
23
+ */
24
+ exactQuery?: boolean;
25
+ /**
26
+ * `useHistoryState` values, by name, that the entry the link opens starts with: what a list tells the record it opens.
27
+ * A link the browser follows itself carries none.
28
+ */
29
+ historyState?: Readonly<Record<string, unknown>>;
19
30
  };
20
31
 
21
32
  const BASE = 'http://netjes.invalid';
@@ -34,17 +45,19 @@ function sameValues(a: string[], b: string[]) {
34
45
  /**
35
46
  * Whether the link goes to the page on screen. An href with a `#` points to a place in a page, so it never does.
36
47
  * Otherwise its URL under the base path has the page's path, give or take one trailing slash, and the page's
37
- * values for each query parameter it names; parameters it leaves out do not count. Only the path and the query
38
- * enter, against a fixed origin, so the server and the browser agree.
48
+ * values for each query parameter it names; parameters it leaves out do not count, unless `exactQuery` asks for the
49
+ * page's parameters too. Only the path and the query enter, against a fixed origin, so the server and the browser agree.
39
50
  */
40
- function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string) {
51
+ function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string, exactQuery: boolean) {
41
52
  if (href.includes('#')) return false;
42
53
  const query = search.toString();
43
54
  // The page's URL as the browser has it: the base path, then the page's path, even one that starts like the base path.
44
55
  const page = new URL(BASE + basePath + pathname + (query ? `?${query}` : ''));
45
56
  const target = new URL(withBasePath(href, basePath), page);
46
57
  if (target.origin !== BASE || withoutTrailingSlash(target.pathname) !== withoutTrailingSlash(page.pathname)) return false;
47
- return [...new Set(target.searchParams.keys())].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
58
+ const keys = new Set(target.searchParams.keys());
59
+ if (exactQuery) for (const key of search.keys()) keys.add(key);
60
+ return [...keys].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
48
61
  }
49
62
 
50
63
  function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
@@ -63,10 +76,24 @@ function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
63
76
  /**
64
77
  * An `<a>` that navigates on the client. Ctrl/cmd-click, new tabs and external URLs behave like a normal link. It sets
65
78
  * `aria-current="page"` on a link to the page on screen: the same path, one trailing slash aside, and the page's values
66
- * for each query parameter the link names. A link with a `#` is never marked, and an `aria-current` prop wins. After a
67
- * navigation to another page, the router announces the page and starts the focus over at the top of the document.
79
+ * for each query parameter the link names (with `exactQuery`, for every parameter the page has too). A link with a `#`
80
+ * is never marked, and an `aria-current` prop wins. After a navigation to another page, the router announces the page
81
+ * and starts the focus over at the top of the document.
68
82
  */
69
- export function Link({ href, replace = false, scroll = true, prefetch = 'intent', reloadDocument = false, onClick, onMouseEnter, onFocus, onTouchStart, ...rest }: LinkProps) {
83
+ export function Link({
84
+ href,
85
+ replace = false,
86
+ scroll = true,
87
+ prefetch = 'intent',
88
+ reloadDocument = false,
89
+ exactQuery = false,
90
+ historyState,
91
+ onClick,
92
+ onMouseEnter,
93
+ onFocus,
94
+ onTouchStart,
95
+ ...rest
96
+ }: LinkProps) {
70
97
  const router = useInternalRouter();
71
98
  const pathname = usePathname();
72
99
  const search = useSearchParams();
@@ -78,7 +105,7 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
78
105
  return (
79
106
  <a
80
107
  href={withBasePath(href, basePath)}
81
- aria-current={isCurrentPage(href, pathname, search, basePath) ? 'page' : undefined}
108
+ aria-current={isCurrentPage(href, pathname, search, basePath, exactQuery) ? 'page' : undefined}
82
109
  {...rest}
83
110
  onClick={(event) => {
84
111
  // Read before the app's own onClick, which runs as the link is followed: where it moves the focus, such as
@@ -88,7 +115,8 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
88
115
  if (event.defaultPrevented || reloadDocument || !isPlainLeftClick(event)) return;
89
116
  if (new URL(href, window.location.href).origin !== window.location.origin) return;
90
117
  event.preventDefault();
91
- void (replace ? router.replace(href, { scroll, focusedAtStart }) : router.push(href, { scroll, focusedAtStart }));
118
+ const options = { scroll, focusedAtStart, ...(historyState ? { historyState } : {}) };
119
+ void (replace ? router.replace(href, options) : router.push(href, options));
92
120
  }}
93
121
  onMouseEnter={(event) => {
94
122
  onMouseEnter?.(event);
package/src/mounted.tsx CHANGED
@@ -3,7 +3,7 @@ import { Form, type FormAction, type FormProps, SubmitButton, type SubmitButtonP
3
3
  import { type Href, isHrefShape } from './href.ts';
4
4
  import { Link, type LinkProps } from './link.tsx';
5
5
  import { isDotSegment } from './payload.ts';
6
- import { type Router, useHref, usePagePayload, usePathname, useRouter } from './router.tsx';
6
+ import { type NavigateOptions, type Router, useHref, usePagePayload, usePathname, useRouter } from './router.tsx';
7
7
 
8
8
  /** The props of a page package's `<Link>`: those of the core `<Link>`, with an href below the package's mount. */
9
9
  export type MountedLinkProps<THref extends string = string> = Omit<LinkProps, 'href'> & { href: THref };
@@ -18,8 +18,8 @@ export type MountedSubmitButtonProps<THref extends string = string> = Omit<Submi
18
18
 
19
19
  /** The client router, as a page package's `useRouter()` returns it: `push`, `replace` and `prefetch` go below its mount. */
20
20
  export type MountedRouter<THref extends string = string> = Omit<Router, 'push' | 'replace' | 'prefetch'> & {
21
- push(href: THref, options?: { scroll?: boolean }): Promise<void>;
22
- replace(href: THref, options?: { scroll?: boolean }): Promise<void>;
21
+ push(href: THref, options?: NavigateOptions): Promise<void>;
22
+ replace(href: THref, options?: NavigateOptions): Promise<void>;
23
23
  prefetch(href: THref): void;
24
24
  };
25
25