netjes 0.0.4 → 0.0.6

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 (123) hide show
  1. package/README.md +12 -8
  2. package/cli/commands.mjs +94 -15
  3. package/cli/process-io.mjs +2 -2
  4. package/cli/scaffold.mjs +89 -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/client-entry.js +4 -1
  10. package/dist/client-entry.js.map +1 -1
  11. package/dist/document.d.ts +3 -1
  12. package/dist/document.d.ts.map +1 -1
  13. package/dist/document.js +4 -3
  14. package/dist/document.js.map +1 -1
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +3 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/lang.d.ts +10 -0
  20. package/dist/lang.d.ts.map +1 -0
  21. package/dist/lang.js +26 -0
  22. package/dist/lang.js.map +1 -0
  23. package/dist/link.d.ts +15 -3
  24. package/dist/link.d.ts.map +1 -1
  25. package/dist/link.js +15 -9
  26. package/dist/link.js.map +1 -1
  27. package/dist/locale.d.ts +5 -0
  28. package/dist/locale.d.ts.map +1 -1
  29. package/dist/locale.js +4 -0
  30. package/dist/locale.js.map +1 -1
  31. package/dist/metadata.d.ts +81 -4
  32. package/dist/metadata.d.ts.map +1 -1
  33. package/dist/metadata.js +129 -7
  34. package/dist/metadata.js.map +1 -1
  35. package/dist/modules.d.ts +6 -1
  36. package/dist/modules.d.ts.map +1 -1
  37. package/dist/modules.js +15 -1
  38. package/dist/modules.js.map +1 -1
  39. package/dist/mounted.d.ts +3 -7
  40. package/dist/mounted.d.ts.map +1 -1
  41. package/dist/mounted.js.map +1 -1
  42. package/dist/navigation-guard.d.ts +59 -0
  43. package/dist/navigation-guard.d.ts.map +1 -0
  44. package/dist/navigation-guard.js +116 -0
  45. package/dist/navigation-guard.js.map +1 -0
  46. package/dist/offline.d.ts +11 -0
  47. package/dist/offline.d.ts.map +1 -0
  48. package/dist/offline.js +98 -0
  49. package/dist/offline.js.map +1 -0
  50. package/dist/payload.d.ts +38 -2
  51. package/dist/payload.d.ts.map +1 -1
  52. package/dist/payload.js +54 -7
  53. package/dist/payload.js.map +1 -1
  54. package/dist/render-document.d.ts +8 -1
  55. package/dist/render-document.d.ts.map +1 -1
  56. package/dist/render-document.js +2 -0
  57. package/dist/render-document.js.map +1 -1
  58. package/dist/root.d.ts.map +1 -1
  59. package/dist/root.js +10 -1
  60. package/dist/root.js.map +1 -1
  61. package/dist/route-tree.d.ts +2 -1
  62. package/dist/route-tree.d.ts.map +1 -1
  63. package/dist/route-tree.js +14 -7
  64. package/dist/route-tree.js.map +1 -1
  65. package/dist/router.d.ts +101 -20
  66. package/dist/router.d.ts.map +1 -1
  67. package/dist/router.js +590 -68
  68. package/dist/router.js.map +1 -1
  69. package/dist/schema.d.ts +2 -0
  70. package/dist/schema.d.ts.map +1 -1
  71. package/dist/schema.js +5 -0
  72. package/dist/schema.js.map +1 -1
  73. package/dist/service-worker.d.ts +81 -0
  74. package/dist/service-worker.d.ts.map +1 -0
  75. package/dist/service-worker.js +584 -0
  76. package/dist/service-worker.js.map +1 -0
  77. package/dist/testing.d.ts +18 -0
  78. package/dist/testing.d.ts.map +1 -1
  79. package/dist/testing.js +63 -22
  80. package/dist/testing.js.map +1 -1
  81. package/package.json +16 -5
  82. package/sidecar/server.mjs +105 -16
  83. package/skills/netjes/SKILL.md +5 -3
  84. package/skills/netjes/references/caching-and-streaming.md +22 -1
  85. package/skills/netjes/references/data-and-actions.md +5 -4
  86. package/skills/netjes/references/deployment.md +3 -3
  87. package/skills/netjes/references/routing.md +14 -6
  88. package/skills/netjes/references/testing.md +6 -3
  89. package/src/actions.tsx +5 -4
  90. package/src/client-entry.tsx +4 -1
  91. package/src/document.tsx +17 -5
  92. package/src/index.ts +12 -2
  93. package/src/lang.ts +28 -0
  94. package/src/link.tsx +37 -9
  95. package/src/locale.ts +5 -0
  96. package/src/metadata.tsx +207 -11
  97. package/src/modules.ts +19 -3
  98. package/src/mounted.tsx +3 -3
  99. package/src/navigation-guard.ts +136 -0
  100. package/src/offline.ts +97 -0
  101. package/src/payload.ts +78 -8
  102. package/src/render-document.tsx +10 -1
  103. package/src/root.tsx +22 -10
  104. package/src/route-tree.tsx +18 -7
  105. package/src/router.tsx +765 -104
  106. package/src/schema.ts +11 -0
  107. package/src/service-worker.ts +632 -0
  108. package/src/testing-vitest.ts +1 -1
  109. package/src/testing.tsx +68 -15
  110. package/template/Dockerfile +1 -1
  111. package/template/Dockerfile.pnpm +68 -0
  112. package/template/Dockerfile.workspace +52 -0
  113. package/template/Dockerfile.workspace.dockerignore +15 -0
  114. package/template/README.md +6 -2
  115. package/template/_AGENTS.md +9 -3
  116. package/template/app/layout.tsx +0 -1
  117. package/template/docker-compose.override.yml +15 -3
  118. package/template/generated/netjes.ts +1 -1
  119. package/tsconfig.strict-app.json +27 -0
  120. package/vite/packages.mjs +97 -0
  121. package/vite/plugin.d.ts +8 -1
  122. package/vite/plugin.mjs +156 -9
  123. /package/template/{public/favicon.svg → app/icon.svg} +0 -0
package/src/testing.tsx CHANGED
@@ -7,9 +7,11 @@ 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';
14
+ export type { DocumentHead, HeadIcon } from './payload.ts';
13
15
 
14
16
  /** What the fake app of `createTestApp` reports to the components under test. */
15
17
  export type TestAppOptions = {
@@ -41,6 +43,18 @@ export type TestAppOptions = {
41
43
  defaultOptions?: DefaultOptions;
42
44
  /** What `useNavigation()` returns. Default idle. */
43
45
  navigation?: NavigationState;
46
+ /**
47
+ * The `useHistoryState` values of the history entry on screen, by name: what a navigation carried into it
48
+ * (`historyState`), or what an earlier visit left there. Default none.
49
+ */
50
+ historyState?: Record<string, unknown>;
51
+ /**
52
+ * What `usePageActionState()` returns after the page action's input failed its checks, as the server sends it with a
53
+ * 422: the errors per field and the submitted values of the fields the action declares (default none). `status` is
54
+ * the failure's status, 422 by default, or 429 for a post the rate limiter refused. It belongs to the page, so `route`
55
+ * names it; without `route`, the page is the URL's path. Default no failure.
56
+ */
57
+ pageActionState?: { errors: Record<string, string[]>; values?: Record<string, string | string[]>; status?: number };
44
58
  /** The token `<Form method="post">` adds. Default a test token; `false` for none. */
45
59
  antiforgery?: AntiforgeryToken | false;
46
60
  queryClient?: QueryClient;
@@ -67,7 +81,7 @@ export type TestActionAnswer = ActionState<unknown> & {
67
81
 
68
82
  /** One thing the component under test did: a navigation, a router call, a form post or a server action call. */
69
83
  export type TestNavigation =
70
- | { type: 'push' | 'replace'; href: string }
84
+ | { type: 'push' | 'replace'; href: string; historyState?: Readonly<Record<string, unknown>> }
71
85
  | { type: 'refresh' | 'back' | 'forward' }
72
86
  | { type: 'submit'; action: string; data: URLSearchParams | FormData }
73
87
  | { type: 'action'; name: string; input: unknown };
@@ -148,17 +162,46 @@ export function createTestApp(options: TestAppOptions = {}): TestApp {
148
162
 
149
163
  function Wrapper({ children }: { children: ReactNode }) {
150
164
  const [url, setUrl] = useState(initialUrl);
165
+ // The useHistoryState values of the entry on screen, and their lineage: as the router's, a navigation to another page
166
+ // starts a new one, and a setter of the lineage before sets nothing.
167
+ const [historyEntry, setHistoryEntry] = useState<Pick<HistoryContextValue, 'lineage' | 'values'>>(() => ({
168
+ lineage: 0,
169
+ values: options.historyState ?? {},
170
+ }));
171
+ // Stable, as the router's, so a setter is a new function only in a new lineage.
172
+ const [historyWriters] = useState<Pick<HistoryContextValue, 'set' | 'onRestore'>>(() => ({
173
+ set: (lineage, name, compute) =>
174
+ setHistoryEntry((entry) => (entry.lineage === lineage ? { lineage, values: { ...entry.values, [name]: compute(entry.values) } } : entry)),
175
+ onRestore: () => () => {},
176
+ }));
177
+ const history = useMemo<HistoryContextValue>(() => ({ ...historyEntry, ...historyWriters }), [historyEntry, historyWriters]);
178
+ const [guards] = useState(() => new NavigationGuards());
151
179
  const router = useMemo<InternalRouter>(() => {
152
- const go = (type: 'push' | 'replace', href: string) => {
153
- navigations.push({ type, href });
180
+ const go = (type: 'push' | 'replace', href: string, historyState: Readonly<Record<string, unknown>> | undefined) => {
181
+ navigations.push(historyState ? { type, href, historyState } : { type, href });
154
182
  const next = new URL(href, window.location.href);
183
+ // As the router does: a page that stays keeps its values, another starts over; what the navigation carries goes on top.
184
+ const stays = next.pathname === window.location.pathname;
185
+ setHistoryEntry(({ lineage, values }) =>
186
+ stays ? { lineage, values: { ...values, ...historyState } } : { lineage: lineage + 1, values: { ...historyState } },
187
+ );
155
188
  window.history.replaceState(null, '', next.href);
156
189
  setUrl(next);
157
190
  return Promise.resolve();
158
191
  };
192
+ // As the router does: a guard that holds is asked first, except about a fragment of the page on screen or
193
+ // another site, and the navigation is recorded once the guards let it go on. One that goes at once, as no guard
194
+ // holds, takes the place of an attempt still waiting for its answer.
195
+ const guarded = (type: 'push' | 'replace', href: string, historyState: Readonly<Record<string, unknown>> | undefined) => {
196
+ const next = new URL(href, window.location.href);
197
+ const here = new URL(window.location.href);
198
+ const keepsPage = next.hash !== '' && next.pathname === here.pathname && next.search === here.search;
199
+ if (next.origin !== here.origin || keepsPage) return go(type, href, historyState);
200
+ return guards.attempt(next.pathname + next.search + next.hash, type, () => go(type, href, historyState));
201
+ };
159
202
  return {
160
- push: (href) => go('push', href),
161
- replace: (href) => go('replace', href),
203
+ push: (href, navigateOptions) => guarded('push', href, navigateOptions?.historyState),
204
+ replace: (href, navigateOptions) => guarded('replace', href, navigateOptions?.historyState),
162
205
  prefetch: () => {},
163
206
  refresh: () => {
164
207
  navigations.push({ type: 'refresh' });
@@ -173,31 +216,41 @@ export function createTestApp(options: TestAppOptions = {}): TestApp {
173
216
  onActionResponse: () => () => {},
174
217
  onCookiesChanged: () => () => {},
175
218
  };
176
- }, []);
177
- const payload = useMemo<PagePayload>(
178
- () => ({
219
+ }, [guards]);
220
+ const payload = useMemo<PagePayload>(() => {
221
+ const route = options.route ?? (options.pageActionState ? url.pathname : null);
222
+ return {
179
223
  kind: 'page',
180
- route: options.route ?? null,
224
+ route,
181
225
  page: null,
182
226
  segments: [],
183
227
  props: {},
184
228
  params: options.params ?? {},
185
229
  shared: options.shared ?? null,
186
- status: 200,
230
+ status: options.pageActionState ? (options.pageActionState.status ?? 422) : 200,
187
231
  url: url.pathname + url.search,
188
232
  version: 'test',
189
233
  ...(antiforgery ? { antiforgery } : {}),
190
234
  ...(options.draftMode ? { draftMode: true } : {}),
191
235
  ...(options.locale ? { locale: options.locale } : {}),
192
236
  ...(options.mounts ? { mounts: options.mounts } : {}),
193
- }),
194
- [url],
195
- );
237
+ ...(options.pageActionState && route !== null
238
+ ? {
239
+ actionState: {
240
+ action: route,
241
+ status: options.pageActionState.status ?? 422,
242
+ errors: options.pageActionState.errors,
243
+ values: options.pageActionState.values ?? {},
244
+ },
245
+ }
246
+ : {}),
247
+ };
248
+ }, [url]);
196
249
 
197
250
  return (
198
251
  <QueryClientProvider client={queryClient}>
199
252
  <PublicConfigProvider value={options.publicConfig ?? {}}>
200
- <RouterContexts router={router} payload={payload} url={url} navigation={options.navigation ?? { state: 'idle' }}>
253
+ <RouterContexts router={router} payload={payload} url={url} navigation={options.navigation ?? { state: 'idle' }} history={history} guards={guards}>
201
254
  <RegisterActionClient client={actionClient} />
202
255
  {children}
203
256
  </RouterContexts>
@@ -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
@@ -0,0 +1,68 @@
1
+ # syntax=docker/dockerfile:1
2
+ # Build from the app folder: docker build .
3
+ # From a Netjes checkout, scaffold with --packages to use published packages in Docker.
4
+ ARG NODE_IMAGE=node:24.22.1-bookworm-slim
5
+ ARG SDK_IMAGE=mcr.microsoft.com/dotnet/sdk:10.0.403-noble
6
+ ARG RUNTIME_IMAGE=mcr.microsoft.com/dotnet/aspnet:10.0.14-noble
7
+
8
+ FROM ${NODE_IMAGE} AS node
9
+
10
+ FROM node AS deps
11
+ WORKDIR /src
12
+ RUN npm install --global pnpm@10.28.2
13
+ COPY package.json pnpm-lock.yaml ./
14
+ RUN pnpm install --frozen-lockfile
15
+
16
+ # netjes:if compose
17
+ # Development: the source is bind-mounted by docker-compose.override.yml.
18
+ FROM ${SDK_IMAGE} AS dev
19
+ COPY --from=node /usr/local/bin/node /usr/local/bin/node
20
+ COPY --from=deps /usr/local/lib/node_modules/pnpm /usr/local/lib/node_modules/pnpm
21
+ RUN ln -s /usr/local/lib/node_modules/pnpm/bin/pnpm.cjs /usr/local/bin/pnpm
22
+ WORKDIR /src
23
+ COPY --from=deps /src ./
24
+ # The CLI defaults to localhost:5080 unless ASPNETCORE_URLS is set.
25
+ ENV ASPNETCORE_URLS=http://+:8080 \
26
+ ASPNETCORE_ENVIRONMENT=Development \
27
+ DOTNET_USE_POLLING_FILE_WATCHER=1 \
28
+ DOTNET_WATCH_SUPPRESS_BROWSER_REFRESH=1 \
29
+ NETJES_VITE_HOST=0.0.0.0
30
+ EXPOSE 8080 5173
31
+ CMD ["pnpm", "dev"]
32
+
33
+ # netjes:end
34
+ # Client bundle (dist/client) and server bundle + sidecar (dist/server).
35
+ FROM deps AS client
36
+ COPY . .
37
+ RUN pnpm run build
38
+
39
+ FROM ${SDK_IMAGE} AS build
40
+ WORKDIR /src
41
+ COPY __NAME__.csproj ./
42
+ RUN dotnet restore
43
+ COPY . .
44
+ COPY --from=client /src/dist dist
45
+ RUN dotnet publish -c Release -o /app --no-restore -p:NetjesSkipClientBuild=true
46
+
47
+ # tini, the production image's PID 1 (below): Ubuntu's package, installed in the SDK image the build stage uses. The
48
+ # production stage takes its static binary, which needs no package manager and no library in RUNTIME_IMAGE.
49
+ FROM ${SDK_IMAGE} AS tini
50
+ RUN apt-get update && apt-get install -y --no-install-recommends tini && rm -rf /var/lib/apt/lists/*
51
+
52
+ # Production: ASP.NET Core runtime plus the node binary for the SSR sidecar. Runs as the non-root app user.
53
+ FROM ${RUNTIME_IMAGE} AS production
54
+ COPY --from=node /usr/local/bin/node /usr/local/bin/node
55
+ COPY --from=tini /usr/bin/tini-static /usr/bin/tini
56
+ # Mount a persistent volume here to keep ASP.NET Core Data Protection keys across container replacements.
57
+ RUN mkdir -p /home/app/.aspnet/DataProtection-Keys && chown -R app:app /home/app/.aspnet
58
+ WORKDIR /app
59
+ COPY --from=build /app ./
60
+ USER $APP_UID
61
+ EXPOSE 8080
62
+ HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
63
+ CMD ["node", "-e", "fetch('http://127.0.0.1:8080/healthz').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
64
+ # tini is PID 1 and runs the app as its child. The kernel ignores a signal that a container's PID 1 has no handler for,
65
+ # so an app that is PID 1 never dies of its own abort(): after a crash it spins (arm64) or exits with another code than
66
+ # 134. tini passes signals on (docker stop), reaps orphans and exits with the app's code; -s keeps it reaping when
67
+ # another process is PID 1, as under docker run --init.
68
+ ENTRYPOINT ["tini", "-s", "--", "dotnet", "__NAME__.dll"]
@@ -0,0 +1,52 @@
1
+ # syntax=docker/dockerfile:1
2
+ # Build from the workspace root with -f pointing to this Dockerfile.
3
+ # From a Netjes checkout, scaffold with --packages to use published packages in Docker.
4
+ ARG NODE_IMAGE=node:24.22.1-bookworm-slim
5
+ ARG SDK_IMAGE=mcr.microsoft.com/dotnet/sdk:10.0.403-noble
6
+ ARG RUNTIME_IMAGE=mcr.microsoft.com/dotnet/aspnet:10.0.14-noble
7
+
8
+ FROM ${NODE_IMAGE} AS node
9
+
10
+ FROM node AS deps
11
+ ARG APP_DIR=__APP_DIR__
12
+ WORKDIR /src
13
+ RUN npm install --global pnpm@10.28.2
14
+ # Keep the workspace packages and any vendored tarballs in the build context.
15
+ COPY . .
16
+ RUN pnpm install --frozen-lockfile --filter "{./${APP_DIR}}..."
17
+
18
+ # Client bundle (dist/client) and server bundle + sidecar (dist/server).
19
+ FROM deps AS client
20
+ WORKDIR /src/${APP_DIR}
21
+ RUN pnpm run build
22
+
23
+ FROM ${SDK_IMAGE} AS build
24
+ ARG APP_DIR=__APP_DIR__
25
+ WORKDIR /src
26
+ COPY . .
27
+ WORKDIR /src/${APP_DIR}
28
+ COPY --from=client ["/src/${APP_DIR}/dist", "dist"]
29
+ RUN dotnet publish -c Release -o /app -p:NetjesSkipClientBuild=true
30
+
31
+ # tini, the production image's PID 1 (below): Ubuntu's package, installed in the SDK image the build stage uses. The
32
+ # production stage takes its static binary, which needs no package manager and no library in RUNTIME_IMAGE.
33
+ FROM ${SDK_IMAGE} AS tini
34
+ RUN apt-get update && apt-get install -y --no-install-recommends tini && rm -rf /var/lib/apt/lists/*
35
+
36
+ # Production: ASP.NET Core runtime plus the node binary for the SSR sidecar. Runs as the non-root app user.
37
+ FROM ${RUNTIME_IMAGE} AS production
38
+ COPY --from=node /usr/local/bin/node /usr/local/bin/node
39
+ COPY --from=tini /usr/bin/tini-static /usr/bin/tini
40
+ # Mount a persistent volume here to keep ASP.NET Core Data Protection keys across container replacements.
41
+ RUN mkdir -p /home/app/.aspnet/DataProtection-Keys && chown -R app:app /home/app/.aspnet
42
+ WORKDIR /app
43
+ COPY --from=build /app ./
44
+ USER $APP_UID
45
+ EXPOSE 8080
46
+ HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
47
+ CMD ["node", "-e", "fetch('http://127.0.0.1:8080/healthz').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
48
+ # tini is PID 1 and runs the app as its child. The kernel ignores a signal that a container's PID 1 has no handler for,
49
+ # so an app that is PID 1 never dies of its own abort(): after a crash it spins (arm64) or exits with another code than
50
+ # 134. tini passes signals on (docker stop), reaps orphans and exits with the app's code; -s keeps it reaping when
51
+ # another process is PID 1, as under docker run --init.
52
+ ENTRYPOINT ["tini", "-s", "--", "dotnet", "__NAME__.dll"]
@@ -0,0 +1,15 @@
1
+ **/node_modules
2
+ **/.pnpm-store
3
+ __APP_DIR__/bin
4
+ __APP_DIR__/obj
5
+ __APP_DIR__/dist
6
+ **/.vite
7
+ **/test-results
8
+ **/playwright-report
9
+ __APP_DIR__/publish
10
+ __APP_DIR__/tests
11
+ __APP_DIR__/e2e
12
+ **/.git
13
+ **/.env
14
+ **/.env.*
15
+ !**/.env.example
@@ -15,7 +15,7 @@ dotnet publish -c Release
15
15
  ```
16
16
 
17
17
  - `app/` holds the pages, as in the Next.js App Router: `page.tsx` is `/`, `about/page.tsx` is `/about`, `layout.tsx` wraps them all, `not-found.tsx` and `error.tsx` handle the rest. `app/document.test.ts` renders the home page's whole document, as the server sends it, with `renderDocument` from `netjes/testing`.
18
- - `public/` is served at the site root. `public/favicon.svg`, which the metadata in `app/layout.tsx` links, is the Netjes mark: replace it with the app's own.
18
+ - `app/icon.svg` is the app's icon, the Netjes mark until you replace it: Netjes serves it at `/icon.svg` and links it from every page. `favicon.ico`, `apple-icon.png` and `manifest.webmanifest` next to it work the same way. Put other static files in `public/` (create it), which is served at the site root.
19
19
  - `Features/` holds the C# side, one folder per feature: `Features/Home/HomePage.cs` maps the home page's loader and the `home.greet` server action the form calls.
20
20
  - `tests/__NAME__.Tests/` holds the C# tests: `AppFactory.cs` runs the real app in memory, with no Node and no client build, and `HomePageTests.cs` tests the home page's loader and form. `e2e/` holds the Playwright tests, which `playwright.config.ts` runs against the app in Development and in Production. `__NAME__.csproj` leaves these two root folders out of the app's build, so keep the app's own C# out of them.
21
21
  - `tsconfig.json` points to two configs: `tsconfig.app.json` checks the app's code without Node's types, `tsconfig.node.json` checks `vite.config.ts`, `playwright.config.ts`, `e2e/` and `scripts/` with them.
@@ -25,4 +25,8 @@ 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
+ <!--netjes:if pnpm-->
29
+ Develop on the host with `pnpm dev`. __COMPOSE_SETUP__ Run `pnpm install` and commit `pnpm-lock.yaml`. To build the production image, run `__DOCKER_BUILD__` from the __DOCKER_CONTEXT__. The image runs as the non-root app user under tini and checks `/healthz` on port 8080. Mount a persistent volume writable by the `app` user at `/home/app/.aspnet/DataProtection-Keys` to keep ASP.NET Core Data Protection keys across container replacements. When scaffolding from a Netjes checkout for use with Docker, pass `netjes new --packages` so Docker can restore the published packages.
30
+ <!--netjes:else-->
31
+ 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.
32
+ <!--netjes:end-->
@@ -12,7 +12,7 @@ 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. 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`. |
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
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`). |
@@ -24,7 +24,8 @@ How this app is built, for coding agents and the people working with them. It is
24
24
  <!--netjes:end-->
25
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
- | `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. |
27
+ | `app/icon.svg` | The app's icon (the Netjes mark; replace it). Metadata files at the root of `app/` (`favicon.ico`, `icon.*`, `apple-icon.*`, `manifest.webmanifest`) are served at the site root and linked from every page: no `<link>` tags or `metadata.icons` needed. Only the root counts; the same name in `public/` stops the app. |
28
+ | `public/` | Other static files (create it when you need one), served at the site root. |
28
29
 
29
30
  ## Commands
30
31
 
@@ -59,17 +60,22 @@ A page without a loader is a plain default export and gets empty props. Forms ca
59
60
 
60
61
  - 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
62
  - 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.
63
+ - 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
64
  - 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
65
  - 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
66
  - 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.
67
+ - 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.
68
+ - 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
69
  - 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
70
  - 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
71
  - `.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
72
  - 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`.
73
+ - The viewport is `export const viewport: Viewport = { ... }` in a layout or page (`themeColor`, `viewportFit`, `colorScheme` and the rest); never render a `<meta name="viewport">`, which would be a second one. Write metadata URLs (`alternates.canonical`, `openGraph.images`) relative and set `Netjes:SiteUrl` in configuration: they resolve against it, under the base path.
70
74
  - An `error.tsx` renders `error.message` only when `!error.withheld`, and shows `error.status ?? 500` if it shows a status.
71
75
  - `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)).
72
76
  - 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)).
77
+ - Pages that must open without a network opt in with `.AvailableOffline()` and a service worker built with `netjes({ serviceWorker: 'sw.ts' })` (`netjes/service-worker`); read the offline guide in the Netjes docs before using it, since stored pages can hold personal data. A manifest, icons and `viewport` make the app installable.
78
+ - If the app uses pnpm: `pnpm dev` runs on the host, and the image is built with `docker build .` (from the workspace root with `-f <app>/Dockerfile` for an app in a pnpm workspace).
73
79
  - Write the failing test first, then the change.
74
80
 
75
81
  ## Before you finish
@@ -4,7 +4,6 @@ import '../styles/global.css';
4
4
 
5
5
  export const metadata: Metadata = {
6
6
  title: { default: '__TITLE__', template: '%s · __TITLE__' },
7
- icons: { icon: '/favicon.svg' },
8
7
  };
9
8
 
10
9
  const navLink = 'text-slate-500 no-underline hover:text-slate-900 aria-[current=page]:text-slate-900';
@@ -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;
@@ -0,0 +1,27 @@
1
+ {
2
+ // The flags of create-vite's React-TS template plus stricter checks on top of `strict`.
3
+ // Each project extending this base supplies its own include and may override the ambient types.
4
+ "compilerOptions": {
5
+ "target": "ES2023",
6
+ "lib": ["ES2023", "DOM"],
7
+ "module": "ESNext",
8
+ "moduleResolution": "bundler",
9
+ "moduleDetection": "force",
10
+ "types": ["vite/client", "node"],
11
+ "jsx": "react-jsx",
12
+ "strict": true,
13
+ "skipLibCheck": true,
14
+ "allowImportingTsExtensions": true,
15
+ "allowArbitraryExtensions": true,
16
+ "verbatimModuleSyntax": true,
17
+ "noEmit": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "erasableSyntaxOnly": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUncheckedSideEffectImports": true,
23
+ "noUncheckedIndexedAccess": true,
24
+ "noImplicitOverride": true,
25
+ "exactOptionalPropertyTypes": true
26
+ }
27
+ }
package/vite/packages.mjs CHANGED
@@ -3,7 +3,9 @@
3
3
  // The Vite plugin, the development sidecar (through the plugin's api) and the CLI read them from here.
4
4
  import { readFileSync, realpathSync, statSync } from 'node:fs';
5
5
  import { readdir } from 'node:fs/promises';
6
+ import { createRequire, registerHooks } from 'node:module';
6
7
  import path from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
9
  import { satisfies } from '../cli/info.mjs';
8
10
  import { findPackage } from '../cli/packages.mjs';
9
11
 
@@ -74,6 +76,101 @@ function isFile(file) {
74
76
  }
75
77
  }
76
78
 
79
+ /** @param {string} file @param {string} specifier @param {'require' | 'import'} mode */
80
+ function resolveConfigExport(file, specifier, mode) {
81
+ const parent = pathToFileURL(file);
82
+ // Node can cache by parent URL and specifier, so give each set of conditions its own parent URL.
83
+ parent.searchParams.set('netjes-tsconfig', mode);
84
+ const conditions = ['node', 'types', mode];
85
+ const hooks = registerHooks({
86
+ resolve: (name, context, nextResolve) => nextResolve(name, { ...context, parentURL: parent.href, conditions }),
87
+ });
88
+ try {
89
+ const target = fileURLToPath(import.meta.resolve(specifier));
90
+ if (path.extname(target) === '.json' && isFile(target)) return target;
91
+ } catch {
92
+ // The caller tries the next config filename or mode.
93
+ } finally {
94
+ hooks.deregister();
95
+ }
96
+ }
97
+
98
+ /** @param {string} file @param {string} specifier */
99
+ function resolveExtendedConfig(file, specifier) {
100
+ const dir = path.dirname(file);
101
+ if (/^\.{1,2}[/\\]/.test(specifier) || path.isAbsolute(specifier)) {
102
+ const target = path.resolve(dir, specifier);
103
+ return [target, `${target}.json`].find(isFile);
104
+ }
105
+
106
+ // Bare config packages may name their base with the tsconfig field. Subpath exports resolve from the package
107
+ // that owns this config, including when a base lives in a different workspace package.
108
+ const manifest = isPackageName(specifier) ? findPackage(dir, specifier) : null;
109
+ if (manifest) {
110
+ const { tsconfig } = JSON.parse(readFileSync(manifest, 'utf8'));
111
+ if (typeof tsconfig === 'string') {
112
+ const target = path.resolve(path.dirname(manifest), tsconfig);
113
+ if (isFile(target)) return target;
114
+ }
115
+ }
116
+ const requireFromConfig = createRequire(file);
117
+ for (const name of [specifier, `${specifier}.json`, `${specifier}/tsconfig.json`]) {
118
+ // TypeScript looks up base configs with `require` and `types`. Also accept import entries for Vite.
119
+ const exported = resolveConfigExport(file, name, 'require') ?? resolveConfigExport(file, name, 'import');
120
+ if (exported) return exported;
121
+ try {
122
+ const target = requireFromConfig.resolve(name);
123
+ if (path.extname(target) === '.json') return target;
124
+ } catch {
125
+ // Try the next TypeScript config filename.
126
+ }
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ /** Checks a linked page package's config before Vite transforms its pages. @param {PagePackage} pkg */
132
+ export function checkPackageTsconfig(pkg) {
133
+ const rootConfig = path.join(pkg.root, 'tsconfig.json');
134
+ if (!isFile(rootConfig)) return;
135
+ /** @type {Set<string>} */
136
+ const visited = new Set();
137
+
138
+ /** @param {string} config */
139
+ function check(config) {
140
+ const file = realpathSync(config);
141
+ if (visited.has(file)) return;
142
+ visited.add(file);
143
+
144
+ // TypeScript accepts comments and trailing commas. Keep quoted values intact, including comment-like text.
145
+ const strings = /"(?:[^"\\]|\\.)*"/;
146
+ const text = readFileSync(file, 'utf8')
147
+ .replace(/^\uFEFF/, '')
148
+ .replace(new RegExp(`${strings.source}|//[^\\r\\n]*|/\\*[\\s\\S]*?\\*/`, 'g'), (token) => token.startsWith('"') ? token : ' ')
149
+ .replace(new RegExp(`${strings.source}|,(?=\\s*[}\\]])`, 'g'), (token) => token === ',' ? '' : token);
150
+ let bases;
151
+ try {
152
+ const parsed = JSON.parse(text);
153
+ bases = Array.isArray(parsed?.extends) ? parsed.extends : [parsed?.extends];
154
+ } catch {
155
+ // Vite supplies its own syntax diagnostics. This check adds context to missing bases.
156
+ return;
157
+ }
158
+ for (const base of bases) {
159
+ if (typeof base !== 'string') continue;
160
+ const target = resolveExtendedConfig(file, base);
161
+ if (!target) {
162
+ throw new Error(
163
+ `netjes: ${pkg.name}: ${file} extends ${JSON.stringify(base)}, which does not resolve. ` +
164
+ `Add the shared config as a devDependency of ${pkg.name} or extend an installed config by its package name.`,
165
+ );
166
+ }
167
+ check(target);
168
+ }
169
+ }
170
+
171
+ check(rootConfig);
172
+ }
173
+
77
174
  /**
78
175
  * Reads and checks the page packages the app lists, in the order it lists them. Each error is one line that names the
79
176
  * package and what to do.
package/vite/plugin.d.ts CHANGED
@@ -4,13 +4,20 @@ import type { PluginOption } from 'vite';
4
4
 
5
5
  /** Options for the `netjes()` Vite plugin. */
6
6
  export type NetjesPluginOptions = {
7
- /** The directory of page files (Next.js App Router conventions), relative to the Vite root. Must match Netjes:AppDirectory. Default `app`. */
7
+ /**
8
+ * The directory of page files (Next.js App Router conventions), relative to the Vite root. Must match
9
+ * Netjes:AppDirectory. Default `app`. The client build copies the metadata files at its root (`favicon.ico`,
10
+ * `icon*`, `apple-icon*`, `manifest.webmanifest` or `manifest.json`) into `dist/client` and lists them in
11
+ * `dist/client/.vite/metadata-files.json`, which the .NET app links; a file of the same name in `public/` fails the build.
12
+ */
8
13
  appDir?: string;
9
14
  /**
10
15
  * Like Next.js's `basePath`: the path the app is mounted under with `app.UsePathBase(...)`, e.g. `/docs`.
11
16
  * Built asset URLs get it; links, forms, redirects and router calls get it from the server at runtime.
12
17
  */
13
18
  basePath?: string;
19
+ /** Service worker entry relative to the Vite root. The client build writes it as a classic script at `dist/client/sw.js`. */
20
+ serviceWorker?: string;
14
21
  /**
15
22
  * Page packages, by npm name: installed packages whose `package.json` has a `netjes` field, and which the .NET app
16
23
  * mounts at a prefix. Their convention files join the page module map and both builds, their sources and stylesheet