netjes 0.0.2 → 0.0.4

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 (160) hide show
  1. package/README.md +13 -11
  2. package/cli/agents.mjs +25 -2
  3. package/cli/commands.mjs +56 -6
  4. package/cli/help.mjs +7 -2
  5. package/cli/info.mjs +275 -33
  6. package/cli/routes.mjs +35 -8
  7. package/cli/scaffold.mjs +31 -4
  8. package/dist/actions.d.ts +7 -2
  9. package/dist/actions.d.ts.map +1 -1
  10. package/dist/actions.js +9 -3
  11. package/dist/actions.js.map +1 -1
  12. package/dist/client-entry.d.ts +1 -0
  13. package/dist/client-entry.d.ts.map +1 -1
  14. package/dist/client-entry.js +19 -2
  15. package/dist/client-entry.js.map +1 -1
  16. package/dist/deferred.d.ts +11 -0
  17. package/dist/deferred.d.ts.map +1 -1
  18. package/dist/deferred.js +15 -1
  19. package/dist/deferred.js.map +1 -1
  20. package/dist/document.d.ts.map +1 -1
  21. package/dist/document.js +10 -1
  22. package/dist/document.js.map +1 -1
  23. package/dist/errors.d.ts +7 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +11 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/form.d.ts +5 -5
  28. package/dist/form.d.ts.map +1 -1
  29. package/dist/form.js +5 -2
  30. package/dist/form.js.map +1 -1
  31. package/dist/href.d.ts +31 -3
  32. package/dist/href.d.ts.map +1 -1
  33. package/dist/href.js +131 -10
  34. package/dist/href.js.map +1 -1
  35. package/dist/image.d.ts +3 -3
  36. package/dist/image.d.ts.map +1 -1
  37. package/dist/image.js.map +1 -1
  38. package/dist/index.d.ts +3 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +3 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/link.d.ts +15 -7
  43. package/dist/link.d.ts.map +1 -1
  44. package/dist/link.js +38 -7
  45. package/dist/link.js.map +1 -1
  46. package/dist/metadata.d.ts +8 -2
  47. package/dist/metadata.d.ts.map +1 -1
  48. package/dist/metadata.js +14 -5
  49. package/dist/metadata.js.map +1 -1
  50. package/dist/modules.d.ts +15 -1
  51. package/dist/modules.d.ts.map +1 -1
  52. package/dist/modules.js.map +1 -1
  53. package/dist/mounted.d.ts +55 -0
  54. package/dist/mounted.d.ts.map +1 -0
  55. package/dist/mounted.js +110 -0
  56. package/dist/mounted.js.map +1 -0
  57. package/dist/navigation-focus.d.ts +38 -0
  58. package/dist/navigation-focus.d.ts.map +1 -0
  59. package/dist/navigation-focus.js +71 -0
  60. package/dist/navigation-focus.js.map +1 -0
  61. package/dist/payload.d.ts +8 -0
  62. package/dist/payload.d.ts.map +1 -1
  63. package/dist/payload.js +28 -0
  64. package/dist/payload.js.map +1 -1
  65. package/dist/query.d.ts +5 -2
  66. package/dist/query.d.ts.map +1 -1
  67. package/dist/query.js +11 -8
  68. package/dist/query.js.map +1 -1
  69. package/dist/render-document.d.ts +74 -0
  70. package/dist/render-document.d.ts.map +1 -0
  71. package/dist/render-document.js +393 -0
  72. package/dist/render-document.js.map +1 -0
  73. package/dist/route-announcer.d.ts +18 -0
  74. package/dist/route-announcer.d.ts.map +1 -0
  75. package/dist/route-announcer.js +58 -0
  76. package/dist/route-announcer.js.map +1 -0
  77. package/dist/route-tree.d.ts +6 -2
  78. package/dist/route-tree.d.ts.map +1 -1
  79. package/dist/route-tree.js +17 -7
  80. package/dist/route-tree.js.map +1 -1
  81. package/dist/router.d.ts +28 -5
  82. package/dist/router.d.ts.map +1 -1
  83. package/dist/router.js +71 -26
  84. package/dist/router.js.map +1 -1
  85. package/dist/script.d.ts +28 -5
  86. package/dist/script.d.ts.map +1 -1
  87. package/dist/script.js +192 -21
  88. package/dist/script.js.map +1 -1
  89. package/dist/server-render.d.ts.map +1 -1
  90. package/dist/server-render.js +4 -1
  91. package/dist/server-render.js.map +1 -1
  92. package/dist/testing-vitest.d.ts +8 -0
  93. package/dist/testing-vitest.d.ts.map +1 -0
  94. package/dist/testing-vitest.js +26 -0
  95. package/dist/testing-vitest.js.map +1 -0
  96. package/dist/testing.d.ts +17 -1
  97. package/dist/testing.d.ts.map +1 -1
  98. package/dist/testing.js +18 -3
  99. package/dist/testing.js.map +1 -1
  100. package/dist/zod-jitless.d.ts +2 -0
  101. package/dist/zod-jitless.d.ts.map +1 -0
  102. package/dist/zod-jitless.js +4 -0
  103. package/dist/zod-jitless.js.map +1 -0
  104. package/package.json +1 -1
  105. package/sidecar/server.mjs +109 -15
  106. package/skills/netjes/SKILL.md +15 -7
  107. package/skills/netjes/references/caching-and-streaming.md +37 -4
  108. package/skills/netjes/references/data-and-actions.md +15 -7
  109. package/skills/netjes/references/deployment.md +7 -3
  110. package/skills/netjes/references/routing.md +32 -9
  111. package/skills/netjes/references/testing.md +23 -7
  112. package/src/actions.tsx +9 -3
  113. package/src/client-entry.tsx +20 -2
  114. package/src/deferred.ts +14 -1
  115. package/src/document.tsx +22 -3
  116. package/src/errors.ts +12 -0
  117. package/src/form.tsx +10 -7
  118. package/src/href.ts +137 -11
  119. package/src/image.tsx +3 -3
  120. package/src/index.ts +19 -1
  121. package/src/link.tsx +47 -13
  122. package/src/metadata.tsx +19 -6
  123. package/src/modules.ts +15 -2
  124. package/src/mounted.tsx +160 -0
  125. package/src/navigation-focus.ts +75 -0
  126. package/src/payload.ts +32 -0
  127. package/src/query.tsx +14 -8
  128. package/src/render-document.tsx +483 -0
  129. package/src/route-announcer.tsx +69 -0
  130. package/src/route-tree.tsx +17 -6
  131. package/src/router.tsx +116 -31
  132. package/src/script.tsx +214 -23
  133. package/src/server-render.tsx +4 -1
  134. package/src/testing-vitest.ts +37 -0
  135. package/src/testing.tsx +38 -5
  136. package/src/virtual.d.ts +8 -1
  137. package/src/zod-jitless.ts +15 -0
  138. package/template/.dockerignore +3 -0
  139. package/template/Dockerfile +11 -1
  140. package/template/README.md +11 -7
  141. package/template/_AGENTS.md +38 -9
  142. package/template/__NAME__.csproj +2 -0
  143. package/template/app/document.test.ts +29 -0
  144. package/template/app/error.tsx +3 -2
  145. package/template/app/layout.tsx +10 -1
  146. package/template/docker-compose.override.yml +4 -3
  147. package/template/docker-compose.prod.yml +2 -1
  148. package/template/e2e/home.spec.ts +32 -0
  149. package/template/generated/netjes.ts +43 -14
  150. package/template/package.json +4 -1
  151. package/template/playwright.config.ts +36 -0
  152. package/template/tests/__NAME__.Tests/AppFactory.cs +31 -0
  153. package/template/tests/__NAME__.Tests/HomePageTests.cs +55 -0
  154. package/template/tests/__NAME__.Tests/__NAME__.Tests.csproj +30 -0
  155. package/template/tsconfig.app.json +20 -0
  156. package/template/tsconfig.json +2 -17
  157. package/template/tsconfig.node.json +8 -0
  158. package/vite/packages.mjs +345 -0
  159. package/vite/plugin.d.ts +16 -1
  160. package/vite/plugin.mjs +224 -34
@@ -0,0 +1,75 @@
1
+ /** Input types the user does not type into: the focus can leave them when the page they are on is replaced. */
2
+ const NOT_TYPED_IN = new Set(['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit']);
3
+
4
+ /** Whether the user types into the element, or picks a value in it from the keyboard: a text field, a select, editable content. */
5
+ export function isEditable(element: Element): boolean {
6
+ if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) return true;
7
+ if (element instanceof HTMLInputElement) return !NOT_TYPED_IN.has(element.type);
8
+ return element instanceof HTMLElement && element.isContentEditable;
9
+ }
10
+
11
+ /**
12
+ * Focuses an element without scrolling to it. One that takes no focus of its own, such as a heading or `main`, gets
13
+ * `tabindex="-1"` for it, which goes again when it loses the focus. Returns whether the element has the focus.
14
+ */
15
+ export function focusElement(element: HTMLElement): boolean {
16
+ element.focus({ preventScroll: true });
17
+ if (document.activeElement === element) return true;
18
+ // A tabindex of the app's own did not help (a hidden or inert element): leave it as it is.
19
+ if (element.hasAttribute('tabindex')) return false;
20
+ element.setAttribute('tabindex', '-1');
21
+ element.focus({ preventScroll: true });
22
+ if (document.activeElement !== element) {
23
+ element.removeAttribute('tabindex');
24
+ return false;
25
+ }
26
+ element.addEventListener('blur', () => element.removeAttribute('tabindex'), { once: true });
27
+ return true;
28
+ }
29
+
30
+ /**
31
+ * Starts the focus over at the top of the document, as a page load does: the next Tab goes to the first element that
32
+ * takes the focus, such as a skip link. `body` takes the focus for this only, without scrolling, and gets its own
33
+ * `tabindex` back, or none.
34
+ */
35
+ export function resetFocus() {
36
+ const body = document.body;
37
+ const own = body.getAttribute('tabindex');
38
+ body.tabIndex = -1;
39
+ body.focus({ preventScroll: true, focusVisible: false });
40
+ if (own === null) body.removeAttribute('tabindex');
41
+ else body.setAttribute('tabindex', own);
42
+ }
43
+
44
+ export type NavigationFocus = {
45
+ /** The element the URL's fragment names, which the router scrolled to; null without a fragment, or when none matched. */
46
+ target: HTMLElement | null;
47
+ /** The page on screen is another one: its page key changed. */
48
+ replaced: boolean;
49
+ /** The navigation keeps the scroll position: `scroll={false}`. */
50
+ keep: boolean;
51
+ /** What had the focus when the navigation started. */
52
+ focusedAtStart: Element | null;
53
+ };
54
+
55
+ /**
56
+ * Moves the focus after a navigation, once the router has scrolled, by the first of these rules that applies:
57
+ *
58
+ * 1. The fragment's target takes it, on this page or on another. One that cannot (a hidden element) leaves it to the
59
+ * rules below.
60
+ * 2. It stays on the same page: a query that changed, a refresh, a post that stays on its page, a modal opening or
61
+ * closing over the page under it.
62
+ * 3. It stays where it went while the navigation ran: to the new page (`autoFocus`), or where the user or a handler
63
+ * of the app (a menu that closes) put it.
64
+ * 4. It stays on what had it when the navigation started, with `scroll={false}` or in a field the user types into,
65
+ * such as a search box in a layout that navigates as the user types.
66
+ * 5. Otherwise it starts over at the top of the document, as after a page load.
67
+ */
68
+ export function moveFocusAfterNavigation({ target, replaced, keep, focusedAtStart }: NavigationFocus) {
69
+ if (target && focusElement(target)) return;
70
+ if (!replaced) return;
71
+ const focused = document.activeElement;
72
+ if (focused && focused !== document.body && focused !== focusedAtStart) return;
73
+ if (focused && focused === focusedAtStart && (keep || isEditable(focused))) return;
74
+ resetFocus();
75
+ }
package/src/payload.ts CHANGED
@@ -121,6 +121,12 @@ export type PagePayload = {
121
121
  basePath?: string;
122
122
  /** The request culture, with `AddNetjesLocalization`. */
123
123
  locale?: string;
124
+ /**
125
+ * Each mounted page package's URL for this request, by npm name, without the base path: `/help`, `/acme/help`, or `/`
126
+ * for a package mounted at the root. Null when the request has no value for one of the prefix's parameters. Left out
127
+ * when the app mounts no package.
128
+ */
129
+ mounts?: Record<string, string | null>;
124
130
  /**
125
131
  * Client only, never sent: how far the browser clock is ahead of the server's, measured when the payload arrived.
126
132
  * Server timestamps plus this offset are browser timestamps.
@@ -333,6 +339,7 @@ function pagePayload(json: Json): PagePayload {
333
339
  if (json.renderedAt !== undefined && json.renderedAt !== null) payload.renderedAt = number(json.renderedAt, 'renderedAt');
334
340
  if (json.basePath !== undefined && json.basePath !== null) payload.basePath = string(json.basePath, 'basePath');
335
341
  if (json.locale !== undefined && json.locale !== null) payload.locale = string(json.locale, 'locale');
342
+ if (json.mounts !== undefined && json.mounts !== null) payload.mounts = mounts(json.mounts);
336
343
  if (json.draftMode !== undefined && json.draftMode !== null) {
337
344
  if (typeof json.draftMode !== 'boolean') fail('draftMode must be a boolean');
338
345
  payload.draftMode = json.draftMode;
@@ -340,6 +347,31 @@ function pagePayload(json: Json): PagePayload {
340
347
  return payload;
341
348
  }
342
349
 
350
+ /** A segment a browser resolves away, also when encoded: `.`, `..`, `%2e`, `.%2E` and the like. */
351
+ export function isDotSegment(segment: string): boolean {
352
+ return /^(?:\.|%2e){1,2}$/i.test(segment);
353
+ }
354
+
355
+ /**
356
+ * A mount's URL as the server writes it: `/`, or `/` and segments, none empty or a dot segment, with no query, fragment,
357
+ * backslash, whitespace or control character. The mounted components put it in front of their hrefs.
358
+ */
359
+ function mountUrl(value: unknown, what: string): string | null {
360
+ if (value === null) return null;
361
+ const url = string(value, what);
362
+ if (url === '/') return url;
363
+ const [first, ...segments] = url.split('/');
364
+ const unsafe = (segment: string) => segment === '' || isDotSegment(segment) || /[?#\\\s\u0000-\u001F\u007F]/.test(segment);
365
+ if (first !== '' || segments.length === 0 || segments.some(unsafe)) fail(`${what} must be a path of the app, such as /help`);
366
+ return url;
367
+ }
368
+
369
+ function mounts(value: unknown): Record<string, string | null> {
370
+ const result: Record<string, string | null> = {};
371
+ for (const [name, url] of Object.entries(object(value, 'mounts'))) result[name] = mountUrl(url, `mounts.${name}`);
372
+ return result;
373
+ }
374
+
343
375
  export function parseNavigationPayload(value: unknown): NavigationPayload {
344
376
  const json = object(value, 'payload');
345
377
  switch (json.kind) {
package/src/query.tsx CHANGED
@@ -11,14 +11,20 @@ export type QueryShellOptions = {
11
11
 
12
12
  const DEFAULTS: DefaultOptions = { queries: { staleTime: 60_000 } };
13
13
 
14
- /** The Netjes defaults with the app's options merged over them, as the built-in client and the test harness use. */
15
- export function mergeOptions(options: DefaultOptions | undefined): DefaultOptions {
16
- return {
17
- ...DEFAULTS,
18
- ...options,
19
- queries: { ...DEFAULTS.queries, ...options?.queries },
20
- mutations: { ...DEFAULTS.mutations, ...options?.mutations },
21
- };
14
+ /**
15
+ * The Netjes defaults with each layer of options merged over the ones before it, query and mutation options one by
16
+ * one: the built-in client merges the app's options, and the test harness more layers.
17
+ */
18
+ export function mergeOptions(...layers: ReadonlyArray<DefaultOptions | undefined>): DefaultOptions {
19
+ return [DEFAULTS, ...layers].reduce<DefaultOptions>(
20
+ (merged, layer) => ({
21
+ ...merged,
22
+ ...layer,
23
+ queries: { ...merged.queries, ...layer?.queries },
24
+ mutations: { ...merged.mutations, ...layer?.mutations },
25
+ }),
26
+ {},
27
+ );
22
28
  }
23
29
 
24
30
  /**
@@ -0,0 +1,483 @@
1
+ // renderDocument and inlineScriptHashes, which netjes/testing exports: a page's whole document, rendered from its
2
+ // props as the Node sidecar renders it for a crawler, and the hashes of the inline scripts in it. The server builds
3
+ // the payload the sidecar renders; documentPayload builds one here from the pages map and the test's options, by the
4
+ // server's rules for the route and the segments (RouteTable and PageRenderer in src/Netjes). The two are checked
5
+ // against the same cases, test/fixtures/segments/cases.json, so a change to either rule fails a suite until both agree.
6
+ import { htmlSafeJson } from './deferred.ts';
7
+ import type { InitialPayload, PageKind, Params, SegmentRef } from './payload.ts';
8
+
9
+ /** What {@link renderDocument} renders a page with: what the server would send with it. */
10
+ export type RenderDocumentOptions = {
11
+ /** The page's props, as its C# loader sends them. A Promise anywhere in them is a `Page.Defer` value. */
12
+ props?: Record<string, unknown>;
13
+ /** The route values, as `useParams()` returns them: a string per segment, an array per catch-all. Default none. */
14
+ params?: Params;
15
+ /** The page's URL, its path and query. Default `/`. */
16
+ url?: string;
17
+ /**
18
+ * The props of each layout's C# layout loader, by the layout's file, such as `app/blog/layout.tsx`. A Promise in
19
+ * them is a `Page.Defer` value. A layout that is not named here gets none.
20
+ */
21
+ layouts?: Record<string, Record<string, unknown>>;
22
+ /** What the server sends as the shared props (`UseSharedProps`). Default `null`. */
23
+ shared?: unknown;
24
+ /**
25
+ * The page's status. Default 200, or the status the server gives the file: 404 for a not-found file, 403 for a
26
+ * forbidden one, 401 for an unauthorized one and 500 for an error or global-error one.
27
+ */
28
+ status?: number;
29
+ /** A Content-Security-Policy nonce, which goes on every script and stylesheet, as for a policy with `{nonce}`. */
30
+ nonce?: string;
31
+ /** The `lang` of `<html>`. Default `en`, as `NetjesOptions.Lang`. */
32
+ lang?: string;
33
+ /** What `usePublicConfig()` reads, as the `Netjes:PublicConfig` section. */
34
+ publicConfig?: Record<string, unknown>;
35
+ /**
36
+ * The page packages the app mounts, by npm name, each at its prefix as `MapPagePackage` takes it:
37
+ * `{ '@acme/help-center': '/(marketing)/help' }`. Their files in the pages map go into the app's folders under the
38
+ * prefix, so an app page in a package's folder renders inside the package's layouts, and the payload's `mounts` gives
39
+ * each one's URL for the page's `params`. A package that `netjes({ packages })` does not list has its pages in `app`.
40
+ */
41
+ mounts?: Record<string, string>;
42
+ /**
43
+ * The page files, keyed `/app/...` as `import.meta.glob` keys them, and a page package's `/<npm name>/<its pages
44
+ * folder>/...`. Default: the app's and the listed packages', from the `netjes()` plugin.
45
+ */
46
+ modules?: Record<string, () => Promise<unknown>>;
47
+ /** Stops the render, which then rejects with the signal's reason: for a page that waits on a Promise that never settles. */
48
+ signal?: AbortSignal;
49
+ };
50
+
51
+ /** The options {@link documentPayload} reads, with any Promise in the props already a placeholder. */
52
+ type DocumentOptions = Omit<RenderDocumentOptions, 'modules' | 'signal'>;
53
+
54
+ /** The files renderDocument renders besides pages, with the kind and the status the server gives them. */
55
+ const BOUNDARIES = new Map<string, { kind: PageKind; status: number }>([
56
+ ['not-found', { kind: 'notFound', status: 404 }],
57
+ ['forbidden', { kind: 'forbidden', status: 403 }],
58
+ ['unauthorized', { kind: 'unauthorized', status: 401 }],
59
+ ['error', { kind: 'error', status: 500 }],
60
+ ['global-error', { kind: 'error', status: 500 }],
61
+ ]);
62
+
63
+ /** The files that make a folder a segment of the pages below it; the payload names the first four. */
64
+ const SEGMENT_FILES = ['layout', 'template', 'loading', 'error', 'not-found', 'forbidden', 'unauthorized'];
65
+
66
+ const PAGE_EXTENSION = /\.(?:tsx|jsx)$/i;
67
+ const isGroup = (folder: string) => folder.length > 2 && folder.startsWith('(') && folder.endsWith(')');
68
+ const isSlot = (folder: string) => folder.length > 1 && folder.startsWith('@');
69
+ const isPrivate = (folder: string) => folder.startsWith('_');
70
+ /** UTF-16 code unit order, as the server's ordinal order. */
71
+ const ordinal = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
72
+
73
+ /** "a", "a and b", "a, b and c". */
74
+ function list(items: readonly string[]): string {
75
+ return items.length < 2 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1) ?? ''}`;
76
+ }
77
+
78
+ /** A page package mounted at a prefix: the prefix's folders below the app directory (`''` for `/`), and its pages folder. */
79
+ type Mount = { name: string; folder: string; pages: string };
80
+
81
+ /**
82
+ * A file of the pages map the server routes: its id, its path in the app directory (a package's under its mount), and
83
+ * its source, `app` or the package's name.
84
+ */
85
+ type RoutedFile = { id: string; path: string; source: string };
86
+
87
+ const PREFIX_SEGMENT = /^(?:[\p{L}\p{N}._~-]+|\[[A-Za-z_][A-Za-z0-9_]*\]|\([\p{L}\p{N}_-]+\))$/u;
88
+
89
+ /** The mounts of `options.mounts`, with their pages folders from the plugin's list; throws for a prefix MapPagePackage refuses. */
90
+ function mountsOf(mounts: Readonly<Record<string, string>> | undefined, packages: readonly { name: string; pages: string }[]): Mount[] {
91
+ return Object.entries(mounts ?? {}).map(([name, prefix]) => {
92
+ const folders = prefix === '/' ? [] : prefix.split('/').slice(1);
93
+ const refused = (folder: string) => folder === '.' || folder === '..' || isPrivate(folder) || !PREFIX_SEGMENT.test(folder);
94
+ // A parameter used twice, in any case, as MapPagePackage refuses it.
95
+ const parameters = folders.filter((folder) => folder.startsWith('[')).map((folder) => folder.toLowerCase());
96
+ if (!prefix.startsWith('/') || folders.some(refused) || new Set(parameters).size < parameters.length) {
97
+ throw new Error(
98
+ `netjes: renderDocument cannot mount '${name}' at '${prefix}': write the prefix as MapPagePackage takes it, ` +
99
+ "such as '/help', '/(marketing)/help' or '/[tenant]/help'.",
100
+ );
101
+ }
102
+ return { name, folder: folders.join('/'), pages: packages.find((p) => p.name === name)?.pages ?? 'app' };
103
+ });
104
+ }
105
+
106
+ /** The files the server routes: the app's where they are, and a mounted package's under its prefix's folders. */
107
+ function routedFiles(files: readonly string[], appDir: string, mounts: readonly Mount[]): RoutedFile[] {
108
+ return files.flatMap((id): RoutedFile[] => {
109
+ if (id.startsWith(`${appDir}/`)) return [{ id, path: id, source: 'app' }];
110
+ const mount = mounts.find((m) => id.startsWith(`${m.name}/${m.pages}/`));
111
+ if (!mount) return [];
112
+ const below = id.slice(mount.name.length + mount.pages.length + 2);
113
+ return [{ id, path: [appDir, mount.folder, below].filter(Boolean).join('/'), source: mount.name }];
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Each mount's URL for these route values, as the server sends it: the literal segments as written and each value
119
+ * encoded as one segment, or null when a value is missing, a list, empty, `.` or `..`.
120
+ */
121
+ function mountUrls(mounts: readonly Mount[], params: Params): Record<string, string | null> {
122
+ // As the server encodes a value (Uri.EscapeDataString), which encodeURIComponent leaves these five unencoded.
123
+ const encode = (value: string) => encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
124
+ return Object.fromEntries(
125
+ mounts.map((mount) => {
126
+ const segments: string[] = [];
127
+ for (const folder of mount.folder.split('/').filter((f) => f && !isGroup(f))) {
128
+ const value = folder.startsWith('[') ? params[folder.slice(1, -1)] : folder;
129
+ if (typeof value !== 'string' || value === '' || value === '.' || value === '..') return [mount.name, null];
130
+ segments.push(folder.startsWith('[') ? encode(value) : value);
131
+ }
132
+ return [mount.name, `/${segments.join('/')}`];
133
+ }),
134
+ );
135
+ }
136
+
137
+ /** A file in the app directory: the folders below the directory and the file's name without its extension; null for any other file. */
138
+ function parse(file: string, appDir: string): { folders: string[]; name: string } | null {
139
+ if (!file.startsWith(`${appDir}/`) || !PAGE_EXTENSION.test(file)) return null;
140
+ const folders = file.slice(appDir.length + 1).split('/');
141
+ const name = (folders.pop() ?? '').replace(PAGE_EXTENSION, '');
142
+ return { folders, name };
143
+ }
144
+
145
+ type AppFiles = {
146
+ /** Each folder's convention files by name, by its path below the app directory (`''` for the directory itself). */
147
+ folders: Map<string, Map<string, RoutedFile>>;
148
+ /** The folders with parallel route slots, each with the first of its slots. */
149
+ slots: Map<string, string>;
150
+ };
151
+
152
+ /** The convention files the server routes: none in private folders, and the slots that pages and defaults make. */
153
+ function appFiles(files: readonly RoutedFile[], appDir: string): AppFiles {
154
+ const folders = new Map<string, Map<string, RoutedFile>>();
155
+ const slots = new Map<string, string>();
156
+ for (const file of [...files].sort((a, b) => ordinal(a.id, b.id))) {
157
+ const parsed = parse(file.path, appDir);
158
+ if (!parsed || parsed.folders.some(isPrivate)) continue;
159
+ const slot = parsed.folders.findIndex(isSlot);
160
+ if (slot >= 0) {
161
+ const parent = parsed.folders.slice(0, slot).join('/');
162
+ if ((parsed.name === 'page' || parsed.name === 'default') && !slots.has(parent)) {
163
+ slots.set(parent, [appDir, ...parsed.folders.slice(0, slot + 1)].join('/'));
164
+ }
165
+ continue;
166
+ }
167
+ const folder = parsed.folders.join('/');
168
+ let conventions = folders.get(folder);
169
+ if (!conventions) folders.set(folder, (conventions = new Map()));
170
+ const other = conventions.get(parsed.name);
171
+ // As the server, which refuses two sources' segment files in one folder.
172
+ if (other && other.source !== file.source && parsed.name !== 'page') {
173
+ throw new Error(`netjes: renderDocument has two ${parsed.name} files for ${[appDir, folder].filter(Boolean).join('/')}: ${other.id} and ${file.id}.`);
174
+ }
175
+ if (!other) conventions.set(parsed.name, file);
176
+ }
177
+ return { folders, slots };
178
+ }
179
+
180
+ /**
181
+ * How many URL segments a layout's folders cover for these route values, as the server counts them: one per folder,
182
+ * none for a route group, and a catch-all as many as its value has.
183
+ */
184
+ function urlDepth(folders: readonly string[], params: Params): number {
185
+ let depth = 0;
186
+ for (const folder of folders.filter((name) => !isGroup(name))) {
187
+ if (!folder.startsWith('[...') && !folder.startsWith('[[...')) {
188
+ depth++;
189
+ continue;
190
+ }
191
+ const value = params[folder.replace(/^[[\]]+|[[\]]+$/g, '').slice(3)];
192
+ depth += (Array.isArray(value) ? value.join('/') : (value ?? '')).split('/').filter(Boolean).length;
193
+ }
194
+ return depth;
195
+ }
196
+
197
+ function slotError(page: string, where: string, slot: string): Error {
198
+ return new Error(
199
+ `netjes: renderDocument cannot render ${page}, which ${where} the parallel route slot ${slot}: the server chooses what a slot renders.`,
200
+ );
201
+ }
202
+
203
+ /**
204
+ * The folders above `folders` and the folder itself that are segments, outermost first, as the server sends them:
205
+ * each folder with a segment file, its layout's props from `layouts` and, for a layout, the URL depth it covers.
206
+ */
207
+ function segmentsFor(page: string, app: AppFiles, folders: readonly string[], appDir: string, options: DocumentOptions): SegmentRef[] {
208
+ const segments: SegmentRef[] = [];
209
+ for (let end = 0; end <= folders.length; end++) {
210
+ const path = folders.slice(0, end);
211
+ const folder = path.join('/');
212
+ const slot = app.slots.get(folder);
213
+ if (slot) throw slotError(page, 'renders under', slot);
214
+ const conventions = app.folders.get(folder);
215
+ if (!conventions || !SEGMENT_FILES.some((name) => conventions.has(name))) continue;
216
+ const segment: SegmentRef = { id: folder ? `${appDir}/${folder}` : appDir };
217
+ for (const name of ['layout', 'template', 'loading', 'error'] as const) {
218
+ const file = conventions.get(name)?.id;
219
+ if (file) segment[name] = file;
220
+ }
221
+ if (segment.layout) {
222
+ if (options.layouts && Object.hasOwn(options.layouts, segment.layout)) segment.props = options.layouts[segment.layout];
223
+ segment.depth = urlDepth(path, options.params ?? {});
224
+ }
225
+ segments.push(segment);
226
+ }
227
+ return segments;
228
+ }
229
+
230
+ /** Every file renderDocument could render from these: the pages and the boundary files, in ordinal order. */
231
+ function renderable(files: readonly RoutedFile[], appDir: string): string[] {
232
+ return files
233
+ .filter((file) => {
234
+ const parsed = parse(file.path, appDir);
235
+ if (!parsed || parsed.folders.some((folder) => isPrivate(folder) || isSlot(folder))) return false;
236
+ return parsed.name === 'page' || (BOUNDARIES.has(parsed.name) && (parsed.name !== 'global-error' || isRootGlobalError(file, parsed)));
237
+ })
238
+ .map(({ id }) => id)
239
+ .sort(ordinal);
240
+ }
241
+
242
+ /** The global error page is the app's own, in the app directory itself; the server refuses one in a package. */
243
+ const isRootGlobalError = (file: RoutedFile, parsed: { folders: string[] }) => file.source === 'app' && parsed.folders.length === 0;
244
+
245
+ /**
246
+ * The payload the server sends with the document of `page`, a file of the pages map named without its leading slash,
247
+ * for the values in `options`: the route, kind, status and segments by the server's rules, and a build with no
248
+ * stylesheets or scripts. The files of the page packages `options.mounts` names go under their prefixes, with their
249
+ * pages folders from `packages`. Throws for a file it cannot render: one not in `files`, a layout, a page in a private
250
+ * folder or under a parallel route slot, or a file of a package it does not mount.
251
+ */
252
+ export function documentPayload(
253
+ page: string,
254
+ options: DocumentOptions,
255
+ files: readonly string[],
256
+ appDir: string,
257
+ packages: readonly { name: string; pages: string }[] = [],
258
+ ): InitialPayload {
259
+ const paths = files.map((file) => file.replace(/^\//, ''));
260
+ const mounts = mountsOf(options.mounts, packages);
261
+ const routed = routedFiles(paths, appDir, mounts);
262
+ if (!paths.includes(page)) {
263
+ const hint = page.startsWith('/') && paths.includes(page.slice(1))
264
+ ? `; name the file without the leading slash: ${page.slice(1)}.`
265
+ : `. The files it can render are ${list(renderable(routed, appDir))}.`;
266
+ throw new Error(`netjes: renderDocument has no ${page} in the pages map${hint}`);
267
+ }
268
+ const file = routed.find((routedFile) => routedFile.id === page);
269
+ const parsed = file && parse(file.path, appDir);
270
+ if (!parsed) {
271
+ const unmounted = packages.find((p) => page.startsWith(`${p.name}/`))?.name;
272
+ throw new Error(
273
+ unmounted
274
+ ? `netjes: renderDocument cannot render ${page}, a file of the page package '${unmounted}', which it does not mount: ` +
275
+ `pass its prefix as MapPagePackage takes it, as in mounts: { '${unmounted}': '/help' }.`
276
+ : `netjes: renderDocument cannot render ${page}, which is not in the app's directory, ${appDir}, or in a mounted page package's pages.`,
277
+ );
278
+ }
279
+ if (parsed.folders.some(isPrivate)) throw new Error(`netjes: renderDocument cannot render ${page}: a private folder is not routed.`);
280
+ const slot = parsed.folders.findIndex(isSlot);
281
+ if (slot >= 0) throw slotError(page, 'is in', [appDir, ...parsed.folders.slice(0, slot + 1)].join('/'));
282
+ const boundary = BOUNDARIES.get(parsed.name);
283
+ if ((parsed.name !== 'page' && !boundary) || (parsed.name === 'global-error' && !isRootGlobalError(file, parsed))) {
284
+ throw new Error(
285
+ `netjes: renderDocument renders a page or a not-found, error, forbidden, unauthorized or global-error file, not ${page}.`,
286
+ );
287
+ }
288
+
289
+ // The global error page renders without any layout, the others inside the segments down to their own folder.
290
+ const segments = parsed.name === 'global-error' ? [] : segmentsFor(page, appFiles(routed, appDir), parsed.folders, appDir, options);
291
+ for (const file of Object.keys(options.layouts ?? {})) {
292
+ if (!segments.some((segment) => segment.layout === file)) {
293
+ const layouts = segments.flatMap((segment) => (segment.layout ? [segment.layout] : []));
294
+ throw new Error(
295
+ `netjes: renderDocument has props for ${file}, which is not a layout of ${page}. ` +
296
+ (layouts.length > 0 ? `Its layouts are ${list(layouts)}.` : 'It has no layouts.'),
297
+ );
298
+ }
299
+ }
300
+ // An error boundary renders in place of the pages below its folder, so it is not wrapped in itself.
301
+ for (const segment of segments) if (segment.error === page) delete segment.error;
302
+
303
+ return {
304
+ kind: 'page',
305
+ route: parsed.name === 'page' ? `/${parsed.folders.filter((folder) => !isGroup(folder)).join('/')}` : null,
306
+ page,
307
+ ...(boundary ? { pageKind: boundary.kind } : {}),
308
+ segments,
309
+ props: options.props ?? {},
310
+ params: options.params ?? {},
311
+ shared: options.shared ?? null,
312
+ status: options.status ?? boundary?.status ?? 200,
313
+ url: options.url ?? '/',
314
+ version: 'test',
315
+ ...(mounts.length > 0 ? { mounts: mountUrls(mounts, options.params ?? {}) } : {}),
316
+ document: {
317
+ lang: options.lang ?? 'en',
318
+ assets: { stylesheets: [], modulePreloads: [], scripts: [] },
319
+ errorPage: null,
320
+ ...(options.publicConfig ? { publicConfig: options.publicConfig } : {}),
321
+ ...(options.nonce ? { nonce: options.nonce } : {}),
322
+ },
323
+ };
324
+ }
325
+
326
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
327
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false;
328
+ return typeof (value as { then?: unknown }).then === 'function';
329
+ }
330
+
331
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
332
+ if (typeof value !== 'object' || value === null) return false;
333
+ const prototype: unknown = Object.getPrototypeOf(value);
334
+ return prototype === Object.prototype || prototype === null;
335
+ }
336
+
337
+ /** A JSON value with each Promise in it, at any depth, replaced by a `Page.Defer` placeholder; `values` keeps the Promises by id. */
338
+ function withPlaceholders(value: unknown, values: Map<string, PromiseLike<unknown>>): unknown {
339
+ if (isThenable(value)) {
340
+ const id = `d${values.size}`;
341
+ values.set(id, value);
342
+ // Read once the document renders; until then a rejection is not an unhandled one.
343
+ Promise.resolve(value).catch(() => {});
344
+ return { $netjes: 'deferred', id };
345
+ }
346
+ if (Array.isArray(value)) return value.map((item: unknown) => withPlaceholders(item, values));
347
+ return isPlainObject(value) ? placeholdersIn(value, values) : value;
348
+ }
349
+
350
+ function placeholdersIn(props: Record<string, unknown>, values: Map<string, PromiseLike<unknown>>): Record<string, unknown> {
351
+ // Keys are defined, not assigned, so a "__proto__" key stays a key.
352
+ return Object.fromEntries(Object.entries(props).map(([key, item]) => [key, withPlaceholders(item, values)]));
353
+ }
354
+
355
+ async function text(stream: AsyncIterable<unknown>): Promise<string> {
356
+ const decoder = new TextDecoder();
357
+ let html = '';
358
+ for await (const chunk of stream) {
359
+ html += chunk instanceof Uint8Array ? decoder.decode(chunk, { stream: true }) : decoder.decode() + String(chunk);
360
+ }
361
+ return html + decoder.decode();
362
+ }
363
+
364
+ /**
365
+ * Renders a page's whole document, from `<!DOCTYPE html>` to `</html>`, as the Node sidecar renders it for a crawler:
366
+ * the page from `page`, a file of the pages map such as `app/blog/[slug]/page.tsx`, inside the layouts the server
367
+ * would wrap it in, with the head, Netjes's inline scripts and the payload. It waits for every Suspense boundary, and
368
+ * a Promise in the props or in a layout's props is a `Page.Defer` value: rendered in place once it resolves, left as its
369
+ * Suspense fallback when it rejects. The build's stylesheets and scripts, development styles and an antiforgery token
370
+ * are left out, and no C# runs: the props come from `options`. Runs in Vitest's node environment, with the `netjes()`
371
+ * plugin, which provides the pages map, the app's folder and the query shell, also when `modules` is given.
372
+ */
373
+ export async function renderDocument(page: string, options: RenderDocumentOptions = {}): Promise<string> {
374
+ const { modules, signal, props, layouts, ...rest } = options;
375
+ // Before the first await, so that a Promise that has failed already gets its handler before Node looks for one.
376
+ const values = new Map<string, PromiseLike<unknown>>();
377
+ const sent: DocumentOptions = {
378
+ ...rest,
379
+ props: placeholdersIn(props ?? {}, values),
380
+ ...(layouts
381
+ ? { layouts: Object.fromEntries(Object.entries(layouts).map(([file, layoutProps]) => [file, placeholdersIn(layoutProps, values)])) }
382
+ : {}),
383
+ };
384
+ // A form's server action, the query client and the router's first URL take their browser path where these exist.
385
+ if (typeof window !== 'undefined' || typeof document !== 'undefined') {
386
+ throw new Error(
387
+ 'netjes: renderDocument renders a page as the Node sidecar does, without a DOM. ' +
388
+ "Put '// @vitest-environment node' at the top of the test file.",
389
+ );
390
+ }
391
+ signal?.throwIfAborted();
392
+ const app = await import('virtual:netjes/pages');
393
+ const pages = modules ?? app.pages;
394
+ const payload = documentPayload(page, sent, Object.keys(pages), app.appDir, app.packages);
395
+ // Loaded here, so that component tests, which import netjes/testing too, never load react-dom/server.
396
+ const { createServerRenderer } = await import('./server-render.tsx');
397
+ const stream = await createServerRenderer(pages).renderToStream(htmlSafeJson(payload), {
398
+ waitForAll: true,
399
+ deferred: (id) => values.get(id) ?? new Promise<never>(() => {}),
400
+ ...(signal ? { signal } : {}),
401
+ });
402
+ return text(stream);
403
+ }
404
+
405
+ /** JavaScript MIME type essences: a script element whose type is one of them, in any case, runs as a classic script. */
406
+ const JAVASCRIPT_TYPES = new Set([
407
+ 'application/ecmascript',
408
+ 'application/javascript',
409
+ 'application/x-ecmascript',
410
+ 'application/x-javascript',
411
+ 'text/ecmascript',
412
+ 'text/javascript',
413
+ 'text/javascript1.0',
414
+ 'text/javascript1.1',
415
+ 'text/javascript1.2',
416
+ 'text/javascript1.3',
417
+ 'text/javascript1.4',
418
+ 'text/javascript1.5',
419
+ 'text/jscript',
420
+ 'text/livescript',
421
+ 'text/x-ecmascript',
422
+ 'text/x-javascript',
423
+ ]);
424
+
425
+ /** The other script types whose inline text a browser checks against a policy's script sources. */
426
+ const OTHER_SCRIPT_TYPES = new Set(['module', 'importmap', 'speculationrules']);
427
+
428
+ /** A script element: its start tag's attributes (quoted values can hold a `>`) and its text, up to `</script`. */
429
+ const SCRIPT = /<script(?=[\s/>])((?:"[^"]*"|'[^']*'|[^'">])*)>([\s\S]*?)<\/script(?=[\s/>])[^>]*>/gi;
430
+ const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
431
+
432
+ const asciiLowerCase = (text: string) => text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
433
+
434
+ function attributesOf(source: string): Map<string, string> {
435
+ const attributes = new Map<string, string>();
436
+ for (const [, name = '', double, single, bare] of source.matchAll(ATTRIBUTE)) {
437
+ const key = asciiLowerCase(name);
438
+ // As in HTML, the first of two attributes with one name counts.
439
+ if (!attributes.has(key)) attributes.set(key, double ?? single ?? bare ?? '');
440
+ }
441
+ return attributes;
442
+ }
443
+
444
+ /** Whether a browser runs an inline script element with these attributes, by HTML's rules for its type. */
445
+ function runs(attributes: Map<string, string>): boolean {
446
+ const type = attributes.get('type');
447
+ const language = attributes.get('language');
448
+ const typeString =
449
+ type === '' || (type === undefined && !language)
450
+ ? 'text/javascript'
451
+ : type === undefined
452
+ ? `text/${language ?? ''}`
453
+ : type.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '');
454
+ const kind = asciiLowerCase(typeString);
455
+ if (JAVASCRIPT_TYPES.has(kind)) return !attributes.has('nomodule');
456
+ return OTHER_SCRIPT_TYPES.has(kind);
457
+ }
458
+
459
+ async function hashSource(script: string): Promise<string> {
460
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(script)));
461
+ let bytes = '';
462
+ for (const byte of digest) bytes += String.fromCharCode(byte);
463
+ return `'sha256-${btoa(bytes)}'`;
464
+ }
465
+
466
+ /**
467
+ * The hash-sources, `'sha256-…'` in their quotes, of the inline scripts in `html` that a browser runs and checks
468
+ * against a Content-Security-Policy's script sources: each script element without `src` whose type a browser runs
469
+ * (none, a JavaScript type, `module`, `importmap` or `speculationrules`), with text. Each hash is listed once, in the
470
+ * order of the first script with it. Data blocks such as the page payload (`application/json`) are left out.
471
+ */
472
+ export async function inlineScriptHashes(html: string): Promise<string[]> {
473
+ const scripts: string[] = [];
474
+ for (const [, tag = '', body = ''] of html.matchAll(SCRIPT)) {
475
+ const attributes = attributesOf(tag);
476
+ if (attributes.has('src') || !runs(attributes)) continue;
477
+ // The HTML parser turns each CR LF, and each CR on its own, into LF before the script sees its text.
478
+ const script = body.replace(/\r\n?/g, '\n');
479
+ // A browser checks an empty script against no policy, since it does not run it.
480
+ if (script !== '') scripts.push(script);
481
+ }
482
+ return [...new Set(await Promise.all(scripts.map(hashSource)))];
483
+ }