netjes 0.0.3 → 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.
- package/README.md +10 -8
- package/cli/commands.mjs +32 -6
- package/cli/info.mjs +268 -31
- package/cli/routes.mjs +35 -8
- package/dist/actions.d.ts +3 -2
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +5 -4
- package/dist/actions.js.map +1 -1
- package/dist/document.d.ts +3 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +4 -3
- package/dist/document.js.map +1 -1
- package/dist/href.d.ts +7 -0
- package/dist/href.d.ts.map +1 -1
- package/dist/href.js +16 -5
- package/dist/href.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/lang.d.ts +10 -0
- package/dist/lang.d.ts.map +1 -0
- package/dist/lang.js +26 -0
- package/dist/lang.js.map +1 -0
- package/dist/link.d.ts +15 -3
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +15 -9
- package/dist/link.js.map +1 -1
- package/dist/mounted.d.ts +51 -0
- package/dist/mounted.d.ts.map +1 -0
- package/dist/mounted.js +110 -0
- package/dist/mounted.js.map +1 -0
- package/dist/navigation-guard.d.ts +59 -0
- package/dist/navigation-guard.d.ts.map +1 -0
- package/dist/navigation-guard.js +116 -0
- package/dist/navigation-guard.js.map +1 -0
- package/dist/payload.d.ts +28 -2
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +53 -1
- package/dist/payload.js.map +1 -1
- package/dist/render-document.d.ts +18 -4
- package/dist/render-document.d.ts.map +1 -1
- package/dist/render-document.js +79 -16
- package/dist/render-document.js.map +1 -1
- package/dist/root.d.ts.map +1 -1
- package/dist/root.js +2 -1
- package/dist/root.js.map +1 -1
- package/dist/router.d.ts +101 -20
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +590 -68
- package/dist/router.js.map +1 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +5 -0
- package/dist/schema.js.map +1 -1
- package/dist/testing.d.ts +23 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +63 -21
- package/dist/testing.js.map +1 -1
- package/package.json +5 -1
- package/sidecar/server.mjs +117 -24
- package/skills/netjes/SKILL.md +6 -5
- package/skills/netjes/references/data-and-actions.md +10 -5
- package/skills/netjes/references/deployment.md +1 -1
- package/skills/netjes/references/routing.md +21 -6
- package/skills/netjes/references/testing.md +6 -3
- package/src/actions.tsx +5 -4
- package/src/document.tsx +11 -4
- package/src/href.ts +16 -5
- package/src/index.ts +27 -1
- package/src/lang.ts +28 -0
- package/src/link.tsx +37 -9
- package/src/mounted.tsx +160 -0
- package/src/navigation-guard.ts +136 -0
- package/src/payload.ts +69 -3
- package/src/render-document.tsx +117 -20
- package/src/root.tsx +3 -1
- package/src/router.tsx +764 -104
- package/src/schema.ts +11 -0
- package/src/testing-vitest.ts +1 -1
- package/src/testing.tsx +74 -15
- package/src/virtual.d.ts +6 -1
- package/template/Dockerfile +1 -1
- package/template/README.md +1 -1
- package/template/_AGENTS.md +7 -4
- package/template/docker-compose.override.yml +15 -3
- package/template/generated/netjes.ts +1 -1
- package/vite/packages.mjs +345 -0
- package/vite/plugin.d.ts +7 -0
- package/vite/plugin.mjs +208 -30
package/sidecar/server.mjs
CHANGED
|
@@ -8,15 +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.
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
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';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { createInterface } from 'node:readline';
|
|
19
24
|
import { pipeline } from 'node:stream/promises';
|
|
25
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
20
26
|
import { pathToFileURL } from 'node:url';
|
|
21
27
|
|
|
22
28
|
const mode = process.env.NETJES_MODE === 'development' ? 'development' : 'production';
|
|
@@ -29,6 +35,12 @@ delete process.env.NETJES_TOKEN;
|
|
|
29
35
|
const renderTimeoutMs = Number(process.env.NETJES_RENDER_TIMEOUT_MS ?? 15_000);
|
|
30
36
|
const streamTimeoutMs = Number(process.env.NETJES_STREAM_TIMEOUT_MS ?? 60_000);
|
|
31
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;
|
|
32
44
|
const MAX_BODY_BYTES = 16 * 1024 * 1024;
|
|
33
45
|
const CSS_FILE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/;
|
|
34
46
|
// Terminal escape sequences (ECMA-48): CSI, as ESC [ or its one-character form (colours, as in Vite's code frames, which
|
|
@@ -41,12 +53,21 @@ const TERMINAL_ESCAPES = /(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|\u001b[\]PX^_][^\
|
|
|
41
53
|
const plainText = (text) => text.replace(TERMINAL_ESCAPES, '');
|
|
42
54
|
|
|
43
55
|
/** @typedef {{ signal: AbortSignal, waitForAll?: boolean, deferred?: (id: string) => PromiseLike<unknown> }} RenderOptions */
|
|
56
|
+
/**
|
|
57
|
+
* The netjes plugin's development API (vite/plugin.mjs).
|
|
58
|
+
* @typedef {{ rescanPages(): void, pageUrl(id: string): string | null, unlistedPackage(id: string): string | null }} NetjesDevApi
|
|
59
|
+
*/
|
|
44
60
|
/** @type {(data: string, options: RenderOptions) => Promise<string>} */
|
|
45
61
|
let render;
|
|
46
62
|
/** @type {((data: string, options: RenderOptions) => Promise<import('node:stream').Readable>) | undefined} */
|
|
47
63
|
let renderToStream;
|
|
48
64
|
/** @type {import('vite').ViteDevServer | undefined} */
|
|
49
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();
|
|
50
71
|
|
|
51
72
|
/**
|
|
52
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
|
|
@@ -85,17 +106,59 @@ if (mode === 'development') {
|
|
|
85
106
|
dev = await viteFailed(error);
|
|
86
107
|
}
|
|
87
108
|
vite = dev;
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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);
|
|
94
145
|
}
|
|
95
|
-
await viteFailed(error);
|
|
96
146
|
}
|
|
97
|
-
/**
|
|
98
|
-
|
|
147
|
+
const netjes = /** @type {NetjesDevApi | undefined} */ (dev.config.plugins.find((plugin) => plugin.name === 'netjes')?.api);
|
|
148
|
+
/** @param {unknown} error @returns {error is Error & { file: string }} */
|
|
149
|
+
const isMissingModule = (error) => error instanceof Error && error.name === 'MissingModuleError' && 'file' in error && typeof error.file === 'string';
|
|
150
|
+
/**
|
|
151
|
+
* Says what to do when the missing file is of an installed page package that the Vite config does not list.
|
|
152
|
+
* @param {Error & { file: string }} error
|
|
153
|
+
*/
|
|
154
|
+
const withPackageHint = (error) => {
|
|
155
|
+
const name = netjes?.unlistedPackage(error.file);
|
|
156
|
+
if (!name) return error;
|
|
157
|
+
const message = `${error.message}: add '${name}' to netjes({ packages }) in ${path.basename(dev.config.configFile ?? 'vite.config.ts')}`;
|
|
158
|
+
error.stack = error.stack?.replace(error.message, message);
|
|
159
|
+
error.message = message;
|
|
160
|
+
return error;
|
|
161
|
+
};
|
|
99
162
|
/**
|
|
100
163
|
* Runs a render with the server entry. .NET routes a page file as soon as its own watcher sees it, but the page
|
|
101
164
|
* module map changes only when Vite's watcher reports a page file, which for this one can be much later (a file it
|
|
@@ -108,17 +171,21 @@ if (mode === 'development') {
|
|
|
108
171
|
try {
|
|
109
172
|
return await run(await dev.ssrLoadModule('netjes/server-entry'));
|
|
110
173
|
} catch (error) {
|
|
111
|
-
if (!netjes || !(error
|
|
174
|
+
if (!netjes || !isMissingModule(error)) throw error;
|
|
112
175
|
netjes.rescanPages();
|
|
113
|
-
|
|
176
|
+
try {
|
|
177
|
+
return await run(await dev.ssrLoadModule('netjes/server-entry'));
|
|
178
|
+
} catch (again) {
|
|
179
|
+
throw isMissingModule(again) ? withPackageHint(again) : again;
|
|
180
|
+
}
|
|
114
181
|
}
|
|
115
182
|
};
|
|
116
183
|
render = async (data, options) => {
|
|
117
|
-
const styled = await withDevStyles(dev, data);
|
|
184
|
+
const styled = await withDevStyles(dev, data, netjes);
|
|
118
185
|
return withServerEntry((entry) => entry.render(styled, options));
|
|
119
186
|
};
|
|
120
187
|
renderToStream = async (data, options) => {
|
|
121
|
-
const styled = await withDevStyles(dev, data);
|
|
188
|
+
const styled = await withDevStyles(dev, data, netjes);
|
|
122
189
|
return withServerEntry((entry) => entry.renderToStream(styled, options));
|
|
123
190
|
};
|
|
124
191
|
} else {
|
|
@@ -132,11 +199,14 @@ if (mode === 'development') {
|
|
|
132
199
|
* script runs. Vite's client adopts these <style data-vite-dev-id> tags and keeps them updated through HMR: each CSS
|
|
133
200
|
* module sets its tag's text to its own as it loads, before hydration. The files are found in the SSR environment,
|
|
134
201
|
* which rendered the page, and their text comes from the client environment's build, which that module carries
|
|
135
|
-
* (clientCss): React then hydrates the text the server rendered.
|
|
202
|
+
* (clientCss): React then hydrates the text the server rendered. A page package's files are loaded by the URLs of
|
|
203
|
+
* their real paths, which the plugin knows; a file of a package the plugin does not list is left to the render, which
|
|
204
|
+
* says what to do.
|
|
136
205
|
* @param {import('vite').ViteDevServer} server
|
|
137
206
|
* @param {string} data
|
|
207
|
+
* @param {NetjesDevApi | undefined} netjes
|
|
138
208
|
*/
|
|
139
|
-
async function withDevStyles(server, data) {
|
|
209
|
+
async function withDevStyles(server, data, netjes) {
|
|
140
210
|
const payload = JSON.parse(data);
|
|
141
211
|
/** @type {Array<Record<string, unknown>>} */
|
|
142
212
|
const segments = payload.segments ?? [];
|
|
@@ -161,8 +231,10 @@ async function withDevStyles(server, data) {
|
|
|
161
231
|
}
|
|
162
232
|
|
|
163
233
|
for (const file of files) {
|
|
164
|
-
|
|
165
|
-
|
|
234
|
+
const url = netjes ? netjes.pageUrl(file) : `/${file}`;
|
|
235
|
+
if (url === null) continue;
|
|
236
|
+
await server.ssrLoadModule(url);
|
|
237
|
+
await collect(await environment.moduleGraph.getModuleByUrl(url));
|
|
166
238
|
}
|
|
167
239
|
if (styles.size === 0) return data;
|
|
168
240
|
payload.document.devStyles = [...styles].map(([id, css]) => ({ id, css }));
|
|
@@ -376,7 +448,22 @@ server.listen(0, '127.0.0.1', () => {
|
|
|
376
448
|
process.stdout.write(`NETJES_READY ${JSON.stringify({ port, viteOrigin })}\n`);
|
|
377
449
|
});
|
|
378
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
|
+
|
|
379
464
|
async function shutdown() {
|
|
465
|
+
// The port first: Vite's own close comes to its HTTP server last.
|
|
466
|
+
releaseVitePort();
|
|
380
467
|
server.close();
|
|
381
468
|
await vite?.close();
|
|
382
469
|
process.exit(0);
|
|
@@ -385,8 +472,14 @@ async function shutdown() {
|
|
|
385
472
|
// A promise rejected by page code without a handler would otherwise kill every render in flight.
|
|
386
473
|
process.on('unhandledRejection', (reason) => console.error('netjes: unhandled promise rejection', reason));
|
|
387
474
|
|
|
388
|
-
//
|
|
389
|
-
|
|
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);
|
|
390
483
|
process.stdin.resume();
|
|
391
|
-
process.
|
|
484
|
+
process.prependListener('SIGTERM', shutdown);
|
|
392
485
|
process.on('SIGINT', shutdown);
|
package/skills/netjes/SKILL.md
CHANGED
|
@@ -12,6 +12,7 @@ Netjes renders React pages from ASP.NET Core. C# receives every request and owns
|
|
|
12
12
|
- `app/**/page.tsx`: a page. `app/blog/[slug]/page.tsx` serves `/blog/{slug}`. Layouts, boundaries and folder rules: [references/routing.md](references/routing.md).
|
|
13
13
|
- `Features/<Feature>/*.cs`: the C# side of a feature, mapped by an extension method that `Program.cs` calls before `app.MapPages()`. Loaders and actions: [references/data-and-actions.md](references/data-and-actions.md).
|
|
14
14
|
- `generated/netjes.ts`: zod schemas and typed references generated from the C# types and the page files. Read it to see what a page receives; never edit it.
|
|
15
|
+
- Page packages: pages, layouts and loaders from an npm and NuGet package pair, mounted at a prefix by the package's extension in `Program.cs` (`app.MapHelpCenter("/help")`, before `app.MapPages()`) and listed in `netjes({ packages })` in `vite.config.ts`. Their files stay in `node_modules` and merge into `app/` folder by folder; never copy them into `app/`. Mounting, replacing a page and the root layout: [references/routing.md](references/routing.md#page-packages).
|
|
15
16
|
- `components/`: React components and their tests. Testing: [references/testing.md](references/testing.md).
|
|
16
17
|
- `tests/<App>.Tests/`: the C# tests (xUnit v3 and `WebApplicationFactory`), where the app has them, as an app made with `netjes new` does.
|
|
17
18
|
- `e2e/`: the Playwright specs, which `npm run test:e2e` runs.
|
|
@@ -21,7 +22,7 @@ Netjes renders React pages from ASP.NET Core. C# receives every request and owns
|
|
|
21
22
|
## The loop for any change
|
|
22
23
|
|
|
23
24
|
1. Write the failing test first: a Vitest component test, or a C# test for loader and action logic (in `tests/<App>.Tests`, where a new app has its test project).
|
|
24
|
-
2. Change the C# record, loader or action, then run `npx netjes generate` so `generated/netjes.ts` matches (a running `npm run dev` rewrites it when it restarts).
|
|
25
|
+
2. Change the C# record, loader or action, then run `npx netjes generate` so `generated/netjes.ts` matches (a running `npm run dev` rewrites it when it restarts). Run it after updating a page package too: the app's file routes the package's pages.
|
|
25
26
|
3. Use the generated names in React: `pages['/pattern']`, `layouts['app/folder']`, `serverActions['name']`, `api['GET /api/...']`, `route('/pattern', params)`, `endpointUrl('GET /api/...', params)`.
|
|
26
27
|
4. Check: `npm test`, `npm run typecheck`, `dotnet build` (warnings are errors), `npx netjes generate --check`, and `npm run routes` for route warnings. Where the app has them, which an app made with `netjes new` does: `dotnet test tests/<App>.Tests` for the C# tests, and `npm run test:e2e` for a change to a page or a form.
|
|
27
28
|
|
|
@@ -69,10 +70,10 @@ export default definePage(pages['/blog/[slug]'], function Post({ title, body })
|
|
|
69
70
|
|
|
70
71
|
- Decisions live in C#: data access, validation, authorization (`.RequireAuthorization()`, `Page.Forbidden()`), redirects, caching. React renders what it is sent.
|
|
71
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.
|
|
72
|
-
- 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.
|
|
73
74
|
- Server state goes through TanStack Query, seeded from the loader with `.WithQuery(key, data)`; no `useEffect` fetching.
|
|
74
|
-
- Internal links use `<Link>` and `route()`; forms use `<Form>` with `useAction`, and must work without JavaScript.
|
|
75
|
-
- Give each page a title of its own (`metadata`, or `PageMetadata` from C#), and keep the "Skip to content" link the first thing in `app/layout.tsx
|
|
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
|
+
- 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)).
|
|
76
77
|
- Never edit `generated/netjes.ts`; regenerate it and commit it with the change.
|
|
77
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.
|
|
78
79
|
- Caching, streaming and static export have sharp edges: read [references/caching-and-streaming.md](references/caching-and-streaming.md) before using `.CachePage`, `Page.Defer` or `netjes export`.
|
|
@@ -95,6 +96,6 @@ export default definePage(pages['/blog/[slug]'], function Post({ title, body })
|
|
|
95
96
|
|
|
96
97
|
## More
|
|
97
98
|
|
|
98
|
-
The guides go further than these references: [routing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/routing.md), [data loading](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/data-loading.md), [actions and forms](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/actions-and-forms.md), [rendering and streaming](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/rendering-and-streaming.md), [caching](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/caching.md), [images](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/images.md), [metadata](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/metadata.md), [security](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/security.md), [testing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/testing.md) and [deployment](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/deployment.md), with the [React API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/react-api.md), the [C# API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/csharp-api.md) and the [options](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/options.md) as reference.
|
|
99
|
+
The guides go further than these references: [routing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/routing.md), [data loading](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/data-loading.md), [actions and forms](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/actions-and-forms.md), [page packages](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/page-packages.md), [rendering and streaming](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/rendering-and-streaming.md), [caching](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/caching.md), [images](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/images.md), [metadata](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/metadata.md), [security](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/security.md), [testing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/testing.md) and [deployment](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/deployment.md), with the [React API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/react-api.md), the [C# API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/csharp-api.md) and the [options](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/options.md) as reference.
|
|
99
100
|
|
|
100
101
|
The same docs as plain text: https://raw.githubusercontent.com/DennisVerhoeven/netjes/main/llms.txt (an index) and https://raw.githubusercontent.com/DennisVerhoeven/netjes/main/llms-full.txt (everything in one file). They follow the main branch; the installed version's sources and types are in `node_modules/netjes/`.
|
|
@@ -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
|
|
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.
|
|
@@ -72,9 +72,14 @@ const nameError = state?.ok === false ? state.errors.name?.[0] : undefined;
|
|
|
72
72
|
- Validation: DataAnnotations (`[Required]`, `[StringLength]`, `[Range]`, `[EmailAddress]`) and `IValidatableObject` on an action's input are checked before the action runs (for a polymorphic JSON input, those of the `[JsonDerivedType]` the call sends). Failures come back as field errors (422, `state.errors`), also without JavaScript, and the action is not called. This needs no setup: `builder.Services.AddValidation()` is for your other minimal API endpoints, not for `MapAction` or `MapPageAction`. An attribute that cannot be read, such as a `[Display]` whose resource type has no such name, stops the app at startup, also on a derived type a JSON input lists with `[JsonDerivedType]`. A `[FromForm]` input is never `null` (unless declared nullable): a post with none of its fields, such as a form of unchecked checkboxes, gets an empty input, checked like any other. Give form inputs `init` properties, as above, not constructor parameters: a field the post leaves out (an unchecked checkbox, a list with nothing chosen) keeps its default, while form binding refuses such a post (400) for a positional record. A form input, and each type its properties and lists hold, needs exactly one public constructor: form binding never builds a type with several or none, or an abstract class or an interface, so that stops the app at startup. Bind a checkbox group or a list as a property of the input type (`public string[] Tags { get; init; } = [];`), not as a top-level `[FromForm]` parameter: a top-level list or dictionary reads fields named `[0]` or `[key]`, not its own name, and is `null` when none is posted.
|
|
73
73
|
- Optimistic UI: `useAction(action, { onSubmit(formData) { setOptimistic(...) } })` with React's `useOptimistic`.
|
|
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
|
-
- Name actions `feature.verb`. Check authorization inside the action, or with `.RequireAuthorization()`, as for any endpoint.
|
|
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
|
-
-
|
|
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.
|
|
79
|
+
|
|
80
|
+
## Page packages
|
|
81
|
+
|
|
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.
|
|
78
83
|
|
|
79
84
|
## JSON endpoints and TanStack Query
|
|
80
85
|
|
|
@@ -93,10 +98,10 @@ const url = useHref(endpointUrl('GET /api/projects/{slug}/stats', { slug }));
|
|
|
93
98
|
const stats = useQuery({ queryKey: ['projects', slug, 'stats'], queryFn: () => fetchStats(url) });
|
|
94
99
|
```
|
|
95
100
|
|
|
96
|
-
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).
|
|
97
102
|
|
|
98
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.
|
|
99
104
|
|
|
100
105
|
## More
|
|
101
106
|
|
|
102
|
-
[Data loading](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/data-loading.md)
|
|
107
|
+
[Data loading](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/data-loading.md), [Actions and forms](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/actions-and-forms.md) and [Page packages](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/page-packages.md) in the guides.
|
|
@@ -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
|
|
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`).
|
|
@@ -11,7 +11,7 @@ ASP.NET Core does the routing: every page file becomes an endpoint with an ordin
|
|
|
11
11
|
| `template.tsx` | Like a layout, but remounted on every navigation. |
|
|
12
12
|
| `loading.tsx` | Suspense fallback, streamed first while the page below waits on deferred values or lazy code. |
|
|
13
13
|
| `error.tsx` | Error boundary below its layout; props `{ error, reset }` (`ErrorPageProps`). `error.status` is the HTTP status of a server answer behind the error and is undefined for an error thrown in the browser, so show `error.status ?? 500`. Render `error.message` only when `!error.withheld`: `withheld` marks a stand-in for a message Netjes does not show (an exception's or a failed `Page.Defer` value's with error details off, a server action answer with no message, a thrown value that is neither an Error nor a string). `reset()` renders the segment again, or on an error page the server rendered loads the page again; on the page the router's own boundary shows it does nothing, so offer a link there too. In development `error.message` can take several lines (a syntax error's code frame): render it with `whitespace-pre-wrap`. |
|
|
14
|
-
| `not-found.tsx` | Rendered for `Page.NotFound()` from a loader below it, and the root one for unknown URLs. |
|
|
14
|
+
| `not-found.tsx` | Rendered for `Page.NotFound()` from a loader below it, and the root one for unknown URLs, except below a page package's mount, where the package's renders. |
|
|
15
15
|
| `forbidden.tsx`, `unauthorized.tsx` | Rendered for `Page.Forbidden()` / `Page.Unauthorized()` and for empty 403/401 responses from authorization; without one, the error page renders. |
|
|
16
16
|
| `global-error.tsx` | In `app/` only: rendered without any layout when even the error page fails. |
|
|
17
17
|
|
|
@@ -47,31 +47,46 @@ 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.
|
|
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
|
+
## Page packages
|
|
76
|
+
|
|
77
|
+
A page package is an npm package and a NuGet package of one version that bring pages, layouts, boundaries, loaders and actions. The app mounts it with the package's extension, before `app.MapPages()`, and lists the npm half in `netjes({ packages: ['@acme/help-center'] })`; both halves are installed at one version, or the app stops at startup in one line that says what to install.
|
|
78
|
+
|
|
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 })`.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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]`).
|
|
85
|
+
|
|
71
86
|
## Base path and locales
|
|
72
87
|
|
|
73
88
|
`app.UsePathBase("/docs")` with `netjes({ basePath: '/docs' })`; links, forms and redirects add it, and app code is written as if at the root (`useHref(path)` for a plain `<a>`). Locale routing is a `[lang]` folder with `AddNetjesLocalization`, `UseNetjesLocalization` and `MapLocaleRedirect`; `useLocale()` reads it.
|
|
74
89
|
|
|
75
90
|
## More
|
|
76
91
|
|
|
77
|
-
[Routing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/routing.md) and [Metadata](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/metadata.md) in the guides, and the [React API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/react-api.md) for every component and hook.
|
|
92
|
+
[Routing](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/routing.md), [Page packages](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/page-packages.md) and [Metadata](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/metadata.md) in the guides, and the [React API](https://github.com/DennisVerhoeven/netjes/blob/main/docs/reference/react-api.md) for every component and hook.
|
|
@@ -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
|
-
- `
|
|
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
|
|
236
|
-
*
|
|
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 = {
|
|
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={
|
|
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/href.ts
CHANGED
|
@@ -25,17 +25,28 @@ function matches(pattern: readonly string[], path: readonly string[]): boolean {
|
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
|
-
* Whether a URL
|
|
29
|
-
*
|
|
30
|
-
* control character
|
|
28
|
+
* Whether a URL has the shape of a link, as a C# `Href` checks it: root-relative (`/…`, but not `//…` or `/\…`, which
|
|
29
|
+
* browsers read as another host), a link within the page (`?…`, `#…`), or an `http:`, `https:`, `mailto:` or `tel:`
|
|
30
|
+
* URL, with no ASCII control character and no space at either end. It does not ask which page a path names: a page
|
|
31
|
+
* package's generated file, which cannot know the app's pages, checks its `Href` with this.
|
|
31
32
|
*/
|
|
32
|
-
export function
|
|
33
|
+
export function isHrefShape(value: string): boolean {
|
|
33
34
|
// Browsers drop tabs and newlines anywhere in a URL, and control characters and spaces at either end: `/\t/host`
|
|
34
35
|
// would be `//host`. A C# Href refuses the same.
|
|
35
36
|
if (/[\u0000-\u001F\u007F]/.test(value) || value.startsWith(' ') || value.endsWith(' ')) return false;
|
|
36
37
|
if (/^(https?:|mailto:|tel:)/i.test(value) || value.startsWith('?') || value.startsWith('#')) return true;
|
|
37
38
|
// "//host" and "/\host" are other hosts as far as browsers are concerned.
|
|
38
|
-
|
|
39
|
+
return value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Whether a URL is one of the app's pages (by route pattern), a link within the page (`?…`, `#…`), or another
|
|
44
|
+
* site. The generated `isHref()` and `Href` schema call this to check URLs that come from data. A URL with an ASCII
|
|
45
|
+
* control character, or with a space at either end, is none of these.
|
|
46
|
+
*/
|
|
47
|
+
export function isRouteHref(value: string, patterns: readonly string[]): boolean {
|
|
48
|
+
if (!isHrefShape(value)) return false;
|
|
49
|
+
if (!value.startsWith('/')) return true;
|
|
39
50
|
const path = (value.split(/[?#]/, 1)[0] ?? '').split('/').filter(Boolean);
|
|
40
51
|
return patterns.some((pattern) => matches(pattern.split('/').filter(Boolean), path));
|
|
41
52
|
}
|