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.
Files changed (90) hide show
  1. package/README.md +10 -8
  2. package/cli/commands.mjs +32 -6
  3. package/cli/info.mjs +268 -31
  4. package/cli/routes.mjs +35 -8
  5. package/dist/actions.d.ts +3 -2
  6. package/dist/actions.d.ts.map +1 -1
  7. package/dist/actions.js +5 -4
  8. package/dist/actions.js.map +1 -1
  9. package/dist/document.d.ts +3 -1
  10. package/dist/document.d.ts.map +1 -1
  11. package/dist/document.js +4 -3
  12. package/dist/document.js.map +1 -1
  13. package/dist/href.d.ts +7 -0
  14. package/dist/href.d.ts.map +1 -1
  15. package/dist/href.js +16 -5
  16. package/dist/href.js.map +1 -1
  17. package/dist/index.d.ts +3 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/lang.d.ts +10 -0
  22. package/dist/lang.d.ts.map +1 -0
  23. package/dist/lang.js +26 -0
  24. package/dist/lang.js.map +1 -0
  25. package/dist/link.d.ts +15 -3
  26. package/dist/link.d.ts.map +1 -1
  27. package/dist/link.js +15 -9
  28. package/dist/link.js.map +1 -1
  29. package/dist/mounted.d.ts +51 -0
  30. package/dist/mounted.d.ts.map +1 -0
  31. package/dist/mounted.js +110 -0
  32. package/dist/mounted.js.map +1 -0
  33. package/dist/navigation-guard.d.ts +59 -0
  34. package/dist/navigation-guard.d.ts.map +1 -0
  35. package/dist/navigation-guard.js +116 -0
  36. package/dist/navigation-guard.js.map +1 -0
  37. package/dist/payload.d.ts +28 -2
  38. package/dist/payload.d.ts.map +1 -1
  39. package/dist/payload.js +53 -1
  40. package/dist/payload.js.map +1 -1
  41. package/dist/render-document.d.ts +18 -4
  42. package/dist/render-document.d.ts.map +1 -1
  43. package/dist/render-document.js +79 -16
  44. package/dist/render-document.js.map +1 -1
  45. package/dist/root.d.ts.map +1 -1
  46. package/dist/root.js +2 -1
  47. package/dist/root.js.map +1 -1
  48. package/dist/router.d.ts +101 -20
  49. package/dist/router.d.ts.map +1 -1
  50. package/dist/router.js +590 -68
  51. package/dist/router.js.map +1 -1
  52. package/dist/schema.d.ts +2 -0
  53. package/dist/schema.d.ts.map +1 -1
  54. package/dist/schema.js +5 -0
  55. package/dist/schema.js.map +1 -1
  56. package/dist/testing.d.ts +23 -0
  57. package/dist/testing.d.ts.map +1 -1
  58. package/dist/testing.js +63 -21
  59. package/dist/testing.js.map +1 -1
  60. package/package.json +5 -1
  61. package/sidecar/server.mjs +117 -24
  62. package/skills/netjes/SKILL.md +6 -5
  63. package/skills/netjes/references/data-and-actions.md +10 -5
  64. package/skills/netjes/references/deployment.md +1 -1
  65. package/skills/netjes/references/routing.md +21 -6
  66. package/skills/netjes/references/testing.md +6 -3
  67. package/src/actions.tsx +5 -4
  68. package/src/document.tsx +11 -4
  69. package/src/href.ts +16 -5
  70. package/src/index.ts +27 -1
  71. package/src/lang.ts +28 -0
  72. package/src/link.tsx +37 -9
  73. package/src/mounted.tsx +160 -0
  74. package/src/navigation-guard.ts +136 -0
  75. package/src/payload.ts +69 -3
  76. package/src/render-document.tsx +117 -20
  77. package/src/root.tsx +3 -1
  78. package/src/router.tsx +764 -104
  79. package/src/schema.ts +11 -0
  80. package/src/testing-vitest.ts +1 -1
  81. package/src/testing.tsx +74 -15
  82. package/src/virtual.d.ts +6 -1
  83. package/template/Dockerfile +1 -1
  84. package/template/README.md +1 -1
  85. package/template/_AGENTS.md +7 -4
  86. package/template/docker-compose.override.yml +15 -3
  87. package/template/generated/netjes.ts +1 -1
  88. package/vite/packages.mjs +345 -0
  89. package/vite/plugin.d.ts +7 -0
  90. package/vite/plugin.mjs +208 -30
package/src/schema.ts CHANGED
@@ -31,6 +31,17 @@ function topLevelKey(issue: StandardSchemaV1.Issue): string | undefined {
31
31
  return typeof key === 'string' ? key : undefined;
32
32
  }
33
33
 
34
+ /** `value` parsed by the schema, or `fallback` when the schema rejects it. */
35
+ export function parseOr<Schema extends StandardSchemaV1>(
36
+ schema: Schema,
37
+ value: unknown,
38
+ fallback: StandardSchemaV1.InferOutput<Schema>,
39
+ what: string,
40
+ ): StandardSchemaV1.InferOutput<Schema> {
41
+ const result = validateSync(schema, value, what);
42
+ return result.issues ? fallback : (result.value as StandardSchemaV1.InferOutput<Schema>);
43
+ }
44
+
34
45
  /**
35
46
  * Like {@link parseWith}, for input visitors control: values the schema rejects are dropped (so defaults and
36
47
  * optional fields apply) before giving up. Only a value that stays invalid without them throws.
@@ -1,5 +1,5 @@
1
1
  // Registered by netjes() as a Vitest setup file in every app, after the app's own: what the test harness needs from the
2
- // runner. Named by path, not exported.
2
+ // runner. Exported as netjes/testing/vitest, for a package's tests that run without the plugin to list in setupFiles.
3
3
  import type { DefaultOptions } from '@tanstack/react-query';
4
4
  import { inject, vi } from 'vitest';
5
5
 
package/src/testing.tsx CHANGED
@@ -7,7 +7,8 @@ import { type ActionClient, type ActionState, setActionClient } from './actions.
7
7
  import type { AntiforgeryToken, PagePayload, Params } from './payload.ts';
8
8
  import { PublicConfigProvider } from './public-config.tsx';
9
9
  import { dehydratedStateOf, mergeOptions } from './query.tsx';
10
- import { type InternalRouter, type NavigationState, RouterContexts, type SubmitBody } from './router.tsx';
10
+ import { NavigationGuards } from './navigation-guard.ts';
11
+ import { type HistoryContextValue, type InternalRouter, type NavigationState, RouterContexts, type SubmitBody } from './router.tsx';
11
12
 
12
13
  export { type RenderDocumentOptions, inlineScriptHashes, renderDocument } from './render-document.tsx';
13
14
 
@@ -26,6 +27,12 @@ export type TestAppOptions = {
26
27
  params?: Params;
27
28
  /** What the server would send as `SharedProps`. */
28
29
  shared?: unknown;
30
+ /**
31
+ * Each mounted page package's URL for the page, by npm name, as the server sends it: `{ '@acme/help-center': '/help' }`,
32
+ * without the base path, or `null` for a prefix whose value the page has none for. The links, forms and router hooks
33
+ * of the package's generated file go below it.
34
+ */
35
+ mounts?: Record<string, string | null>;
29
36
  /** Seeded into the QueryClient the way `PageResult.WithQuery` seeds it, as of now. */
30
37
  queries?: ReadonlyArray<{ key: readonly unknown[]; data: unknown }>;
31
38
  /**
@@ -35,6 +42,18 @@ export type TestAppOptions = {
35
42
  defaultOptions?: DefaultOptions;
36
43
  /** What `useNavigation()` returns. Default idle. */
37
44
  navigation?: NavigationState;
45
+ /**
46
+ * The `useHistoryState` values of the history entry on screen, by name: what a navigation carried into it
47
+ * (`historyState`), or what an earlier visit left there. Default none.
48
+ */
49
+ historyState?: Record<string, unknown>;
50
+ /**
51
+ * What `usePageActionState()` returns after the page action's input failed its checks, as the server sends it with a
52
+ * 422: the errors per field and the submitted values of the fields the action declares (default none). `status` is
53
+ * the failure's status, 422 by default, or 429 for a post the rate limiter refused. It belongs to the page, so `route`
54
+ * names it; without `route`, the page is the URL's path. Default no failure.
55
+ */
56
+ pageActionState?: { errors: Record<string, string[]>; values?: Record<string, string | string[]>; status?: number };
38
57
  /** The token `<Form method="post">` adds. Default a test token; `false` for none. */
39
58
  antiforgery?: AntiforgeryToken | false;
40
59
  queryClient?: QueryClient;
@@ -61,7 +80,7 @@ export type TestActionAnswer = ActionState<unknown> & {
61
80
 
62
81
  /** One thing the component under test did: a navigation, a router call, a form post or a server action call. */
63
82
  export type TestNavigation =
64
- | { type: 'push' | 'replace'; href: string }
83
+ | { type: 'push' | 'replace'; href: string; historyState?: Readonly<Record<string, unknown>> }
65
84
  | { type: 'refresh' | 'back' | 'forward' }
66
85
  | { type: 'submit'; action: string; data: URLSearchParams | FormData }
67
86
  | { type: 'action'; name: string; input: unknown };
@@ -142,17 +161,46 @@ export function createTestApp(options: TestAppOptions = {}): TestApp {
142
161
 
143
162
  function Wrapper({ children }: { children: ReactNode }) {
144
163
  const [url, setUrl] = useState(initialUrl);
164
+ // The useHistoryState values of the entry on screen, and their lineage: as the router's, a navigation to another page
165
+ // starts a new one, and a setter of the lineage before sets nothing.
166
+ const [historyEntry, setHistoryEntry] = useState<Pick<HistoryContextValue, 'lineage' | 'values'>>(() => ({
167
+ lineage: 0,
168
+ values: options.historyState ?? {},
169
+ }));
170
+ // Stable, as the router's, so a setter is a new function only in a new lineage.
171
+ const [historyWriters] = useState<Pick<HistoryContextValue, 'set' | 'onRestore'>>(() => ({
172
+ set: (lineage, name, compute) =>
173
+ setHistoryEntry((entry) => (entry.lineage === lineage ? { lineage, values: { ...entry.values, [name]: compute(entry.values) } } : entry)),
174
+ onRestore: () => () => {},
175
+ }));
176
+ const history = useMemo<HistoryContextValue>(() => ({ ...historyEntry, ...historyWriters }), [historyEntry, historyWriters]);
177
+ const [guards] = useState(() => new NavigationGuards());
145
178
  const router = useMemo<InternalRouter>(() => {
146
- const go = (type: 'push' | 'replace', href: string) => {
147
- navigations.push({ type, href });
179
+ const go = (type: 'push' | 'replace', href: string, historyState: Readonly<Record<string, unknown>> | undefined) => {
180
+ navigations.push(historyState ? { type, href, historyState } : { type, href });
148
181
  const next = new URL(href, window.location.href);
182
+ // As the router does: a page that stays keeps its values, another starts over; what the navigation carries goes on top.
183
+ const stays = next.pathname === window.location.pathname;
184
+ setHistoryEntry(({ lineage, values }) =>
185
+ stays ? { lineage, values: { ...values, ...historyState } } : { lineage: lineage + 1, values: { ...historyState } },
186
+ );
149
187
  window.history.replaceState(null, '', next.href);
150
188
  setUrl(next);
151
189
  return Promise.resolve();
152
190
  };
191
+ // As the router does: a guard that holds is asked first, except about a fragment of the page on screen or
192
+ // another site, and the navigation is recorded once the guards let it go on. One that goes at once, as no guard
193
+ // holds, takes the place of an attempt still waiting for its answer.
194
+ const guarded = (type: 'push' | 'replace', href: string, historyState: Readonly<Record<string, unknown>> | undefined) => {
195
+ const next = new URL(href, window.location.href);
196
+ const here = new URL(window.location.href);
197
+ const keepsPage = next.hash !== '' && next.pathname === here.pathname && next.search === here.search;
198
+ if (next.origin !== here.origin || keepsPage) return go(type, href, historyState);
199
+ return guards.attempt(next.pathname + next.search + next.hash, type, () => go(type, href, historyState));
200
+ };
153
201
  return {
154
- push: (href) => go('push', href),
155
- replace: (href) => go('replace', href),
202
+ push: (href, navigateOptions) => guarded('push', href, navigateOptions?.historyState),
203
+ replace: (href, navigateOptions) => guarded('replace', href, navigateOptions?.historyState),
156
204
  prefetch: () => {},
157
205
  refresh: () => {
158
206
  navigations.push({ type: 'refresh' });
@@ -167,30 +215,41 @@ export function createTestApp(options: TestAppOptions = {}): TestApp {
167
215
  onActionResponse: () => () => {},
168
216
  onCookiesChanged: () => () => {},
169
217
  };
170
- }, []);
171
- const payload = useMemo<PagePayload>(
172
- () => ({
218
+ }, [guards]);
219
+ const payload = useMemo<PagePayload>(() => {
220
+ const route = options.route ?? (options.pageActionState ? url.pathname : null);
221
+ return {
173
222
  kind: 'page',
174
- route: options.route ?? null,
223
+ route,
175
224
  page: null,
176
225
  segments: [],
177
226
  props: {},
178
227
  params: options.params ?? {},
179
228
  shared: options.shared ?? null,
180
- status: 200,
229
+ status: options.pageActionState ? (options.pageActionState.status ?? 422) : 200,
181
230
  url: url.pathname + url.search,
182
231
  version: 'test',
183
232
  ...(antiforgery ? { antiforgery } : {}),
184
233
  ...(options.draftMode ? { draftMode: true } : {}),
185
234
  ...(options.locale ? { locale: options.locale } : {}),
186
- }),
187
- [url],
188
- );
235
+ ...(options.mounts ? { mounts: options.mounts } : {}),
236
+ ...(options.pageActionState && route !== null
237
+ ? {
238
+ actionState: {
239
+ action: route,
240
+ status: options.pageActionState.status ?? 422,
241
+ errors: options.pageActionState.errors,
242
+ values: options.pageActionState.values ?? {},
243
+ },
244
+ }
245
+ : {}),
246
+ };
247
+ }, [url]);
189
248
 
190
249
  return (
191
250
  <QueryClientProvider client={queryClient}>
192
251
  <PublicConfigProvider value={options.publicConfig ?? {}}>
193
- <RouterContexts router={router} payload={payload} url={url} navigation={options.navigation ?? { state: 'idle' }}>
252
+ <RouterContexts router={router} payload={payload} url={url} navigation={options.navigation ?? { state: 'idle' }} history={history} guards={guards}>
194
253
  <RegisterActionClient client={actionClient} />
195
254
  {children}
196
255
  </RouterContexts>
package/src/virtual.d.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  declare module 'virtual:netjes/pages' {
2
- /** Every page, layout and other convention file, keyed `/app/...`, as lazy imports. Generated by the netjes Vite plugin. */
2
+ /**
3
+ * Every page, layout and other convention file, as lazy imports, keyed by `/` and the file's id: `/app/...` for the
4
+ * app's, `/<npm name>/<its pages folder>/...` for a page package's. Generated by the netjes Vite plugin.
5
+ */
3
6
  export const pages: Record<string, () => Promise<unknown>>;
4
7
  /** The folder of the page files, as the plugin's `appDir` names it: `app`, or e.g. `src/app`. */
5
8
  export const appDir: string;
9
+ /** The page packages `netjes({ packages })` lists, each with the folder of its pages; `[]` when it lists none. */
10
+ export const packages: ReadonlyArray<{ readonly name: string; readonly pages: string }>;
6
11
  }
7
12
 
8
13
  declare module 'virtual:netjes/query' {
@@ -23,8 +23,8 @@ RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
23
23
  && ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
24
24
  WORKDIR /src
25
25
  COPY --from=deps /src ./
26
+ # The image's ASPNETCORE_HTTP_PORTS (8080) is the app's port.
26
27
  ENV ASPNETCORE_ENVIRONMENT=Development \
27
- ASPNETCORE_URLS=http://+:8080 \
28
28
  DOTNET_USE_POLLING_FILE_WATCHER=1 \
29
29
  DOTNET_WATCH_SUPPRESS_BROWSER_REFRESH=1 \
30
30
  NETJES_VITE_HOST=0.0.0.0
@@ -25,4 +25,4 @@ dotnet publish -c Release
25
25
 
26
26
  Outside Development, `Program.cs` sends HSTS on https responses and redirects http to https once the app knows its https port (`ASPNETCORE_HTTPS_PORT` or `ASPNETCORE_HTTPS_PORTS`). Behind a proxy that terminates TLS, add `UseForwardedHeaders()` (trusting only that proxy) so proxied requests count as https and get HSTS, and let the proxy redirect plain http. Netjes adds `X-Content-Type-Options: nosniff` to every response that passes through `UseNetjes()`, static files and API endpoints included, and `Referrer-Policy` and `X-Frame-Options` (`SAMEORIGIN`, or what a Content-Security-Policy's `frame-ancestors` implies) to every document it renders; see `NetjesOptions.SecurityHeaders` to change that.
27
27
 
28
- With Docker: `docker compose up` for development, `docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d` for production. Both publish the app on port 8080 of the host, development on 127.0.0.1 only; set `APP_PORT`, in the shell or a `.env` file, to use another port (`APP_PORT=8090 docker compose up`). The production image runs the app under tini, which passes the signal of `docker stop` on to the app and ends the container when the app crashes, with exit code 134, so `restart: always` starts it again. In Development `appsettings.Development.json` limits `AllowedHosts` to loopback names (a DNS-rebinding guard); add a name there if you reach the dev app by another host. The Docker build restores Netjes from NuGet and npm, which is how any app made by `npx netjes new` references it. Only an app scaffolded from a Netjes checkout references the checkout instead; scaffold it with `netjes new --packages` to build it in Docker.
28
+ With Docker: `docker compose up` for development, `docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d` for production. Both publish the app on port 8080 of the host, development on 127.0.0.1 only; set `APP_PORT`, in the shell or a `.env` file, to use another port (`APP_PORT=8090 docker compose up`). Development also publishes Vite on 5173; `VITE_PORT` moves it (`VITE_PORT=5190 docker compose up`). The production image runs the app under tini, which passes the signal of `docker stop` on to the app and ends the container when the app crashes, with exit code 134, so `restart: always` starts it again. In Development `appsettings.Development.json` limits `AllowedHosts` to loopback names (a DNS-rebinding guard); add a name there if you reach the dev app by another host. The Docker build restores Netjes from NuGet and npm, which is how any app made by `npx netjes new` references it. Only an app scaffolded from a Netjes checkout references the checkout instead; scaffold it with `netjes new --packages` to build it in Docker.
@@ -12,9 +12,9 @@ How this app is built, for coding agents and the people working with them. It is
12
12
 
13
13
  | Path | What |
14
14
  |---|---|
15
- | `app/` | Pages, as in the Next.js App Router: `page.tsx` is `/`, `about/page.tsx` is `/about`, `blog/[slug]/page.tsx` is `/blog/{slug}`. `layout.tsx` wraps the pages below it and stays mounted. Netjes renders `<html>`, `<head>` and `<body>` around the root layout, so no layout renders them: the root one returns what goes inside `<body>`. `loading.tsx`, `error.tsx`, `not-found.tsx`, `forbidden.tsx` and `unauthorized.tsx` are boundaries. `(group)` folders add no URL segment, `_private` folders are not routed. `document.test.ts` renders the home page's whole document, as the server sends it, with `renderDocument` from `netjes/testing`. |
15
+ | `app/` | Pages, as in the Next.js App Router: `page.tsx` is `/`, `about/page.tsx` is `/about`, `blog/[slug]/page.tsx` is `/blog/{slug}`. `layout.tsx` wraps the pages below it and stays mounted. Netjes renders `<html>`, `<head>` and `<body>` around the root layout, so no layout renders them: the root one returns what goes inside `<body>`. `<html lang>` is `NetjesOptions.Lang`, or `PageMetadata.Lang` from a page's or a layout's C# loader. `loading.tsx`, `error.tsx`, `not-found.tsx`, `forbidden.tsx` and `unauthorized.tsx` are boundaries. `(group)` folders add no URL segment, `_private` folders are not routed. A mounted page package's pages, layouts and boundaries merge into these folders under its prefix, from `node_modules`. `document.test.ts` renders the home page's whole document, as the server sends it, with `renderDocument` from `netjes/testing`. |
16
16
  | `Features/` | The C# side, one folder per feature (`namespace __NAME__.Features.Home`): page loaders (`MapPageLoader`), layout loaders (`MapLayoutLoader`), server actions (`MapAction`) and JSON endpoints, with records for what they take and return. Each feature has a `Map...` extension method that `Program.cs` calls. |
17
- | `Program.cs` | Services and the pipeline: `AddNetjes`, `UseNetjes`, authentication (when you add it), `UseAntiforgery`, each feature's `Map...`, and `app.MapPages()` last. |
17
+ | `Program.cs` | Services and the pipeline: `AddNetjes`, `UseNetjes`, authentication (when you add it), `UseAntiforgery`, each page package's mount and each feature's `Map...`, and `app.MapPages()` last. |
18
18
  | `components/` | React components, with their Vitest tests next to them (`*.test.tsx`). |
19
19
  <!--netjes:if tests-->
20
20
  | `tests/__NAME__.Tests/` | The C# tests: a new test of a loader or an action goes here. In the project `netjes new` writes, on xUnit v3, `AppFactory.cs` runs the real app in memory with `WebApplicationFactory`, with no Node and no client build, and `HomePageTests.cs` requests the home page and posts its form as the client router does. C# for the app does not go in the root folders `tests/` and `e2e/`, which `netjes new` leaves out of the app's build (`DefaultItemExcludes` in `__NAME__.csproj`). |
@@ -22,7 +22,7 @@ How this app is built, for coding agents and the people working with them. It is
22
22
  <!--netjes:if e2e-->
23
23
  | `e2e/` | Playwright tests, which `npm run test:e2e` runs. The `playwright.config.ts` that `netjes new` writes runs them against the app twice: in Development (the Vite dev server) and in Production (the build). |
24
24
  <!--netjes:end-->
25
- | `generated/netjes.ts` | Generated from the C# types and the page files: zod schemas for page and layout props (`pages`, `layouts`), `sharedProps`, typed `serverActions`, `api` schemas for JSON endpoints, `endpointUrl()` for the URLs of the app's endpoints, `route()` and the `Href` type. Never edit it. |
25
+ | `generated/netjes.ts` | Generated from the C# types and the page files: zod schemas for page and layout props (`pages`, `layouts`), `sharedProps`, typed `serverActions`, `api` schemas for JSON endpoints, `endpointUrl()` for the URLs of the app's endpoints, `route()` and the `Href` type, the pages of mounted page packages included. Never edit it. |
26
26
  | `styles/global.css` | Tailwind CSS (`@import 'tailwindcss'`), imported by `app/layout.tsx`. |
27
27
  | `public/` | Static files, served at the site root. `favicon.svg` is the Netjes mark, linked by `icons` in the root layout's `metadata`; replace it with the app's own. |
28
28
 
@@ -59,16 +59,19 @@ A page without a loader is a plain default export and gets empty props. Forms ca
59
59
 
60
60
  - C# decides: data access, validation, authorization (`.RequireAuthorization()` on a loader, a layout loader or `MapPages()`; `Page.Forbidden()`), redirects and caching. React renders what the loader sends; hiding a button is not access control.
61
61
  - Never edit `generated/netjes.ts`. Change the C# type and regenerate; commit the file with the change. CI runs `npx netjes generate --check`.
62
- - zod at every boundary: `definePage` and `defineLayout` with the generated schemas (extended, as in `pages['/x'].extend({ link: Href })`, only where no C# type fits), `useSearchParams(schema)` and `useParams(schema)` for the URL, `api['GET /api/...'].response.parse(...)` for JSON you fetch from `useHref(endpointUrl('GET /api/...', params))`, `usePublicConfig(schema)` for public config, `Href` (or `isHref`) from the generated file for URLs that come from data, such as a CMS. No `any`, no casts of server data.
62
+ - zod at every boundary: `definePage` and `defineLayout` with the generated schemas (extended, as in `pages['/x'].extend({ link: Href })`, only where no C# type fits), `useSearchParams(schema)` and `useParams(schema)` for the URL, `useHistoryState(name, initial, schema)` for what a history entry holds, `api['GET /api/...'].response.parse(...)` for JSON you fetch from `useHref(endpointUrl('GET /api/...', params))`, `usePublicConfig(schema)` for public config, `Href` (or `isHref`) from the generated file for URLs that come from data, such as a CMS. No `any`, no casts of server data.
63
63
  - A link that C# sends to one of the app's pages is a `Href` in the C# record (`new Href("/about")`): it is generated as the `Href` schema, checked against the pages when the props are parsed, and goes to `<Link href>` as it is. C# checks only its shape, and a root-relative `Href` that no page serves fails the whole page, so a link to an endpoint or a file stays a `string`.
64
64
  - Server state goes through TanStack Query (`useQuery`), not `useEffect` and `fetch`. Seed it from the loader with `.WithQuery(key, data)` so it is server-rendered; actions update it with `.Invalidate(key)` or `.WithQuery(key, data)`.
65
65
  - Internal links are `<Link href={route('/blog/[slug]', { slug })}>`; a typo in an href is a type error. `route(pattern, params, search, { hash })` builds the query from `search` and a `#fragment` from `hash`, the id of an element on the page; pass `undefined` as `search` for a link with a fragment and no query.
66
+ - A form with changes that are not saved holds navigations with `useNavigationGuard({ when: changed, onAttempt })` and asks before the reader leaves: links, forms that navigate, the router's calls and the browser's Back and Forward wait for `attempt.proceed()` or `attempt.stay()`, and a reload or closing the tab gets the browser's own question. The page draws the question; `proceed()` always works. A redirect that answers a post, a server action or `router.refresh()`, such as to the sign-in page after the session expired, is not held: keep a draft in `sessionStorage` where the changes must outlast it.
67
+ - A navigation or `router.refresh()` that gets no answer while the browser is online, or a server error (5xx) that is no page, keeps the page on screen and sets `useNavigation().error` (`kind`, `status`, `location`); offline, an answer below 500 that is no page, and a redirect `fetch` cannot follow still load the URL as a document. Nothing shows it until the app does: show it in the app's shell (`app/layout.tsx`), with Try again (`router.refresh()`) for `kind: 'refresh'`, and leave `kind: 'submit'` to the form. `refresh()` never rejects, so read its failure there.
66
68
  - After a client navigation to another page, the router starts the focus over at the top of the document, as a page load does, and announces the page to screen readers by its title. Keep the "Skip to content" link the first thing in `app/layout.tsx` that takes the focus, with the content in `<main id="content">`, and give each page a title of its own (`metadata`, or `PageMetadata` from C#): the router says nothing for a page whose title is the previous page's.
67
69
  - Action inputs are records with `init` properties: `public sealed record NoteInput { [Required] public string? Text { get; init; } public bool Pinned { get; init; } }`. A field the post leaves out, such as an unchecked checkbox, keeps its default; form binding refuses (400) a post that lacks one of a positional record's constructor fields. DataAnnotations on them (`[Required]`, `[StringLength]`) are checked before the action runs and come back as field errors, with no setup, also for a post that has none of the input's fields. Return `ServerAction.Invalid(field, message)` for other errors the user can fix.
68
70
  - `.CachePage(...)` only for pages that are the same for every visitor: their loaders and shared props must not depend on cookies or other per-visitor state. In the Development environment pages are never output-cached (each request renders them), so check caching on `npx netjes build && npx netjes start`, or in a `WebApplicationFactory` test in the `Testing` environment with `Netjes:Mode` set to `Development`, as the `AppFactory.cs` that `netjes new` writes runs. Each query string as sent is an entry of its own: name the keys a cached page reads with `.CacheQueryKeys("page")`, or `.CacheQueryKeys()` for none, so other query strings render without being stored (`.claude/skills/netjes/references/caching-and-streaming.md`).
69
71
  - In the TypeScript configs `netjes new` writes, `tsconfig.app.json` checks the app's code without Node's types, so a component or page that reads `process` or imports `node:*` fails `npm run typecheck`. Code that runs only in Node goes in `scripts/`, which `tsconfig.node.json` checks with them; do not add `node` to the `types` of `tsconfig.app.json`.
70
72
  - An `error.tsx` renders `error.message` only when `!error.withheld`, and shows `error.status ?? 500` if it shows a status.
71
73
  - `Netjes:PublicConfig` is sent to the browser: never put secrets there. 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 ([security](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/security.md#errors-and-configuration)).
74
+ - Page packages (pages, layouts, loaders and actions from an npm and NuGet package pair) are mounted, never copied into `app/`: the package's extension in `Program.cs` before `app.MapPages()`, at a prefix in folder syntax (`app.MapHelpCenter("/help")`, `"/(marketing)/help"`), and the npm name in `netjes({ packages })` in `vite.config.ts`. Install both halves at one version. Its files merge into `app/` folder by folder, so an app page in its folder renders inside its layouts. An app page of the same shape as one of its pages stops the app: replace the package's page with `.Override("/help/contact")` on the mount, reading the props from the package's generated file. Conventions on the mount cover only the package's pages; protect the app's own pages under the prefix as usual. For a package that draws its own shell, keep `app/layout.tsx` to providers and the skip link, and put the site's chrome in `app/(site)/layout.tsx`. Run `npx netjes generate` after updating a package ([page packages](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/page-packages.md)).
72
75
  - Write the failing test first, then the change.
73
76
 
74
77
  ## Before you finish
@@ -1,16 +1,28 @@
1
1
  # Development: dotnet watch for C#, the Vite dev server for pages (HMR on 5173). Open http://localhost:8080, or the port
2
- # APP_PORT names. Both ports are bound to localhost only: dev error pages show stack traces and Vite serves the source.
2
+ # APP_PORT names; VITE_PORT moves Vite. Both ports are bound to localhost only: dev error pages show stack traces and
3
+ # Vite serves the source.
3
4
  services:
4
5
  app:
5
6
  build:
6
7
  target: dev
8
+ environment:
9
+ # The browser loads modules from http://localhost:<port>, so Vite listens on the port the host publishes: the same
10
+ # number inside and out.
11
+ Netjes__ViteDevPort: "${VITE_PORT:-5173}"
7
12
  ports:
8
- # The host's port for the app: APP_PORT, from the shell or a .env file next to this file, or 8080. Vite keeps 5173.
13
+ # The host's port for the app: APP_PORT, from the shell or a .env file next to this file, or 8080.
9
14
  - "127.0.0.1:${APP_PORT:-8080}:8080"
10
- - "127.0.0.1:5173:5173"
15
+ # Vite's: VITE_PORT, from the same places, or 5173.
16
+ - "127.0.0.1:${VITE_PORT:-5173}:${VITE_PORT:-5173}"
11
17
  volumes:
12
18
  - .:/src
13
19
  # Keep the container's own installs and build output out of the bind mount.
14
20
  - /src/node_modules
15
21
  - /src/bin
16
22
  - /src/obj
23
+ # The Data Protection keys, where ASP.NET Core keeps them for the dev container's root user: they sign the
24
+ # antiforgery tokens, so on a volume a rebuild does not fail the forms of pages that were open.
25
+ - dev-dataprotection:/root/.aspnet/DataProtection-Keys
26
+
27
+ volumes:
28
+ dev-dataprotection:
@@ -43,7 +43,7 @@ export const api = {} as const;
43
43
  /**
44
44
  * What the app's endpoints read from their URLs, by method and route as in `api`: the route values, then the
45
45
  * query string values the handler binds. A JSON endpoint has a key for each of its methods except HEAD, and any
46
- * other endpoint one for GET, if it answers GET.
46
+ * other endpoint one for GET, if it answers GET, and one for POST, if it reads a form.
47
47
  */
48
48
  export type EndpointParams = Record<never, never>;
49
49
  export type EndpointKey = keyof EndpointParams;