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/index.ts CHANGED
@@ -13,22 +13,48 @@ export { CSP_SCRIPT_HASHES } from './deferred.ts';
13
13
  export { useDraftMode } from './draft-mode.ts';
14
14
  export { type DynamicOptions, clientOnly, dynamic } from './dynamic.tsx';
15
15
  export { Form, type FormAction, type FormProps, SubmitButton, type SubmitButtonProps } from './form.tsx';
16
- export { type Href, type Register, type SearchParamsInput, type SearchValue, buildEndpointUrl, buildHref, isRouteHref } from './href.ts';
16
+ export {
17
+ type Href,
18
+ type Register,
19
+ type SearchParamsInput,
20
+ type SearchValue,
21
+ buildEndpointUrl,
22
+ buildHref,
23
+ isHrefShape,
24
+ isRouteHref,
25
+ } from './href.ts';
17
26
  export { Image, type ImageProps } from './image.tsx';
18
27
  export { Link, type LinkProps } from './link.tsx';
19
28
  export { useLocale } from './locale.ts';
20
29
  export type { ErrorPageProps, LayoutProps } from './modules.ts';
30
+ export {
31
+ type Mounted,
32
+ type MountedFormProps,
33
+ type MountedLinkProps,
34
+ type MountedRouter,
35
+ type MountedSubmitButtonProps,
36
+ mounted,
37
+ } from './mounted.tsx';
21
38
  export { useNonce } from './nonce.tsx';
22
39
  export type { PageKind, Params, SeededQuery, SegmentRef } from './payload.ts';
23
40
  export { usePublicConfig } from './public-config.tsx';
24
41
  export { Script, type ScriptProps, type ScriptStrategy } from './script.tsx';
25
42
  export {
43
+ type NavigateOptions,
44
+ type NavigationAttempt,
45
+ type NavigationAttemptType,
46
+ type NavigationError,
47
+ type NavigationGuardOptions,
26
48
  type NavigationState,
49
+ type SetHistoryState,
27
50
  type SubmitError,
28
51
  type Router,
29
52
  useBasePath,
53
+ useHistoryRestore,
54
+ useHistoryState,
30
55
  useHref,
31
56
  useNavigation,
57
+ useNavigationGuard,
32
58
  useParams,
33
59
  usePathname,
34
60
  useRouter,
package/src/lang.ts ADDED
@@ -0,0 +1,28 @@
1
+ // The `lang` of `<html>`: a page loader's or a layout loader's `PageMetadata.Lang`, else the root's.
2
+ import type { PagePayload } from './payload.ts';
3
+
4
+ /**
5
+ * The shape of a BCP 47 language tag (RFC 5646), as `PageMetadata.Lang` checks it in C#: a primary subtag of two to
6
+ * eight letters, or `x` (private use) or `i` (grandfathered) with at least one subtag after it, then subtags of one to
7
+ * eight letters and digits, each after one hyphen. ASCII only, so no quote, angle bracket or space reaches `<html>`.
8
+ */
9
+ const LANGUAGE_TAG = /^(?:[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*|[xXiI](?:-[A-Za-z0-9]{1,8})+)$/;
10
+
11
+ export function isLanguageTag(value: string): boolean {
12
+ return LANGUAGE_TAG.test(value);
13
+ }
14
+
15
+ /**
16
+ * The document's `lang` for a page: the page loader's, else the innermost layout loader's, else the locale the page
17
+ * was rendered in (`AddNetjesLocalization`), else `root`, the lang the app's root gave the document (the locale it was
18
+ * first rendered in, or `NetjesOptions.Lang`). It is what the server writes for a fresh load of the page's URL
19
+ * (`DocumentLang` in PageRenderer.cs). A reused segment holds the lang its loader gave it when it last ran.
20
+ */
21
+ export function documentLang(payload: Pick<PagePayload, 'lang' | 'segments' | 'locale'>, root: string): string {
22
+ if (payload.lang !== undefined) return payload.lang;
23
+ for (let i = payload.segments.length - 1; i >= 0; i--) {
24
+ const lang = payload.segments[i]?.lang;
25
+ if (lang !== undefined) return lang;
26
+ }
27
+ return payload.locale ?? root;
28
+ }
package/src/link.tsx CHANGED
@@ -16,6 +16,17 @@ export type LinkProps = Omit<ComponentPropsWithRef<'a'>, 'href'> & {
16
16
  prefetch?: 'intent' | 'none';
17
17
  /** Let the browser follow it with a full page load: for a page of the app that must load in full, or a page on another site. */
18
18
  reloadDocument?: boolean;
19
+ /**
20
+ * Mark the link `aria-current="page"` only when its query is the page's whole query: the same parameters with the
21
+ * same values, in any order. Default false: parameters the link leaves out do not count. For a list's paging and sort
22
+ * links, where a link that drops `page` goes to another page of the list.
23
+ */
24
+ exactQuery?: boolean;
25
+ /**
26
+ * `useHistoryState` values, by name, that the entry the link opens starts with: what a list tells the record it opens.
27
+ * A link the browser follows itself carries none.
28
+ */
29
+ historyState?: Readonly<Record<string, unknown>>;
19
30
  };
20
31
 
21
32
  const BASE = 'http://netjes.invalid';
@@ -34,17 +45,19 @@ function sameValues(a: string[], b: string[]) {
34
45
  /**
35
46
  * Whether the link goes to the page on screen. An href with a `#` points to a place in a page, so it never does.
36
47
  * Otherwise its URL under the base path has the page's path, give or take one trailing slash, and the page's
37
- * values for each query parameter it names; parameters it leaves out do not count. Only the path and the query
38
- * enter, against a fixed origin, so the server and the browser agree.
48
+ * values for each query parameter it names; parameters it leaves out do not count, unless `exactQuery` asks for the
49
+ * page's parameters too. Only the path and the query enter, against a fixed origin, so the server and the browser agree.
39
50
  */
40
- function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string) {
51
+ function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string, exactQuery: boolean) {
41
52
  if (href.includes('#')) return false;
42
53
  const query = search.toString();
43
54
  // The page's URL as the browser has it: the base path, then the page's path, even one that starts like the base path.
44
55
  const page = new URL(BASE + basePath + pathname + (query ? `?${query}` : ''));
45
56
  const target = new URL(withBasePath(href, basePath), page);
46
57
  if (target.origin !== BASE || withoutTrailingSlash(target.pathname) !== withoutTrailingSlash(page.pathname)) return false;
47
- return [...new Set(target.searchParams.keys())].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
58
+ const keys = new Set(target.searchParams.keys());
59
+ if (exactQuery) for (const key of search.keys()) keys.add(key);
60
+ return [...keys].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
48
61
  }
49
62
 
50
63
  function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
@@ -63,10 +76,24 @@ function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
63
76
  /**
64
77
  * An `<a>` that navigates on the client. Ctrl/cmd-click, new tabs and external URLs behave like a normal link. It sets
65
78
  * `aria-current="page"` on a link to the page on screen: the same path, one trailing slash aside, and the page's values
66
- * for each query parameter the link names. A link with a `#` is never marked, and an `aria-current` prop wins. After a
67
- * navigation to another page, the router announces the page and starts the focus over at the top of the document.
79
+ * for each query parameter the link names (with `exactQuery`, for every parameter the page has too). A link with a `#`
80
+ * is never marked, and an `aria-current` prop wins. After a navigation to another page, the router announces the page
81
+ * and starts the focus over at the top of the document.
68
82
  */
69
- export function Link({ href, replace = false, scroll = true, prefetch = 'intent', reloadDocument = false, onClick, onMouseEnter, onFocus, onTouchStart, ...rest }: LinkProps) {
83
+ export function Link({
84
+ href,
85
+ replace = false,
86
+ scroll = true,
87
+ prefetch = 'intent',
88
+ reloadDocument = false,
89
+ exactQuery = false,
90
+ historyState,
91
+ onClick,
92
+ onMouseEnter,
93
+ onFocus,
94
+ onTouchStart,
95
+ ...rest
96
+ }: LinkProps) {
70
97
  const router = useInternalRouter();
71
98
  const pathname = usePathname();
72
99
  const search = useSearchParams();
@@ -78,7 +105,7 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
78
105
  return (
79
106
  <a
80
107
  href={withBasePath(href, basePath)}
81
- aria-current={isCurrentPage(href, pathname, search, basePath) ? 'page' : undefined}
108
+ aria-current={isCurrentPage(href, pathname, search, basePath, exactQuery) ? 'page' : undefined}
82
109
  {...rest}
83
110
  onClick={(event) => {
84
111
  // Read before the app's own onClick, which runs as the link is followed: where it moves the focus, such as
@@ -88,7 +115,8 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
88
115
  if (event.defaultPrevented || reloadDocument || !isPlainLeftClick(event)) return;
89
116
  if (new URL(href, window.location.href).origin !== window.location.origin) return;
90
117
  event.preventDefault();
91
- void (replace ? router.replace(href, { scroll, focusedAtStart }) : router.push(href, { scroll, focusedAtStart }));
118
+ const options = { scroll, focusedAtStart, ...(historyState ? { historyState } : {}) };
119
+ void (replace ? router.replace(href, options) : router.push(href, options));
92
120
  }}
93
121
  onMouseEnter={(event) => {
94
122
  onMouseEnter?.(event);
@@ -0,0 +1,160 @@
1
+ import { type ReactNode, useMemo } from 'react';
2
+ import { Form, type FormAction, type FormProps, SubmitButton, type SubmitButtonProps } from './form.tsx';
3
+ import { type Href, isHrefShape } from './href.ts';
4
+ import { Link, type LinkProps } from './link.tsx';
5
+ import { isDotSegment } from './payload.ts';
6
+ import { type NavigateOptions, type Router, useHref, usePagePayload, usePathname, useRouter } from './router.tsx';
7
+
8
+ /** The props of a page package's `<Link>`: those of the core `<Link>`, with an href below the package's mount. */
9
+ export type MountedLinkProps<THref extends string = string> = Omit<LinkProps, 'href'> & { href: THref };
10
+
11
+ /** The props of a page package's `<Form>`: those of the core `<Form>`, with a URL `action` below the package's mount. */
12
+ export type MountedFormProps<THref extends string = string> = Omit<FormProps, 'action'> & { action?: THref | FormAction };
13
+
14
+ /** The props of a page package's `<SubmitButton>`, with a URL `formAction` below the package's mount. */
15
+ export type MountedSubmitButtonProps<THref extends string = string> = Omit<SubmitButtonProps, 'formAction'> & {
16
+ formAction?: THref | Exclude<SubmitButtonProps['formAction'], string>;
17
+ };
18
+
19
+ /** The client router, as a page package's `useRouter()` returns it: `push`, `replace` and `prefetch` go below its mount. */
20
+ export type MountedRouter<THref extends string = string> = Omit<Router, 'push' | 'replace' | 'prefetch'> & {
21
+ push(href: THref, options?: NavigateOptions): Promise<void>;
22
+ replace(href: THref, options?: NavigateOptions): Promise<void>;
23
+ prefetch(href: THref): void;
24
+ };
25
+
26
+ /** What {@link mounted} returns: the links, forms and router hooks of one page package. */
27
+ export type Mounted<THref extends string = string> = {
28
+ /** A `<Link>` whose href is below the mount: `/articles` goes to `/help/articles` for a package mounted at `/help`. */
29
+ Link: (props: MountedLinkProps<THref>) => ReactNode;
30
+ /** A `<Form>` whose URL `action` is below the mount. Without one it posts to the page on screen, as the core `<Form>`. */
31
+ Form: (props: MountedFormProps<THref>) => ReactNode;
32
+ /** A `<SubmitButton>` whose URL `formAction` is below the mount. */
33
+ SubmitButton: (props: MountedSubmitButtonProps<THref>) => ReactNode;
34
+ /** The client router, whose `push`, `replace` and `prefetch` take hrefs below the mount. */
35
+ useRouter: () => MountedRouter<THref>;
36
+ /**
37
+ * The path of the page on screen below the mount, without the base path: `/articles/x` for `/help/articles/x`, and
38
+ * `/` for the mount itself. A page outside the mount gets its whole path, as the core `usePathname` gives it.
39
+ */
40
+ usePathname: () => string;
41
+ /**
42
+ * An href below the mount, under the base path, for a plain `<a>`, another attribute or a `fetch`: a page's, or an
43
+ * endpoint's from the package's `endpointUrl()`. Untyped, as the core `useHref`.
44
+ */
45
+ useHref: (href: string) => string;
46
+ };
47
+
48
+ /** The package's URL for the page on screen, from the payload: null when the page has no value for the prefix. */
49
+ function useMountOrNull(name: string): string | null {
50
+ const mounts = usePagePayload().mounts;
51
+ const mount = mounts && Object.hasOwn(mounts, name) ? mounts[name] : undefined;
52
+ if (mount === undefined) {
53
+ throw new Error(`netjes: the page package '${name}' is not mounted: map it with app.MapPagePackage(...) before app.MapPages()`);
54
+ }
55
+ return mount;
56
+ }
57
+
58
+ /** The package's URL for the page on screen; throws when the page has none. */
59
+ function useMount(name: string): string {
60
+ const mount = useMountOrNull(name);
61
+ if (mount === null) throw new Error(`netjes: '${name}' is mounted at a prefix with a value, and this page has none for it`);
62
+ return mount;
63
+ }
64
+
65
+ /**
66
+ * A segment as routing compares it: decoded where it can be, as the server decodes a path, which leaves `%2F` as it is
67
+ * (so `a%2Fb` and `a%252Fb` hold the same value), in any case.
68
+ */
69
+ function comparable(segment: string): string {
70
+ try {
71
+ return decodeURIComponent(segment.replace(/%2F/gi, '%252F')).toLowerCase();
72
+ } catch {
73
+ return segment.toLowerCase();
74
+ }
75
+ }
76
+
77
+ /** `pathname` without the mount in front, `/` for the mount itself; the whole path when it is not below the mount. */
78
+ function belowMount(pathname: string, mount: string | null): string {
79
+ if (mount === null || mount === '/') return pathname;
80
+ const prefix = mount.split('/').slice(1);
81
+ const segments = pathname.split('/').slice(1);
82
+ if (segments.length < prefix.length || prefix.some((segment, i) => comparable(segment) !== comparable(segments[i] ?? ''))) return pathname;
83
+ const rest = segments.slice(prefix.length).join('/');
84
+ return rest === '' ? '/' : `/${rest}`;
85
+ }
86
+
87
+ /**
88
+ * `href` below `mount`: a path gets the mount in front, and a link within the page on screen (`?…`, `#…`) passes
89
+ * through. Anything else throws, as does a path with a dot segment, which would climb out of the mount.
90
+ */
91
+ function underMount(href: string, mount: string, name: string): string {
92
+ const withinThePage = href.startsWith('?') || href.startsWith('#');
93
+ const path = href.split(/[?#]/, 1)[0] ?? '';
94
+ // Browsers read a backslash in a path as a slash, and %2e as a dot.
95
+ if (!isHrefShape(href) || (!withinThePage && (!href.startsWith('/') || path.split(/[/\\]/).some(isDotSegment)))) {
96
+ throw new Error(
97
+ `netjes: '${href}' is no link below the mount of '${name}': start it with '/' (but not '//' or '/\\'), with no '.' or ` +
98
+ "'..' segment, or with '?' or '#'. Link to another site, or elsewhere in the app, with the Link from 'netjes'.",
99
+ );
100
+ }
101
+ if (withinThePage || mount === '/') return href;
102
+ return href === '/' || href[1] === '?' || href[1] === '#' ? mount + href.slice(1) : mount + href;
103
+ }
104
+
105
+ /**
106
+ * The links, forms and router hooks of the page package `name`, its npm name, bound to where the app mounted it. Each
107
+ * puts the package's URL for the page on screen in front of its hrefs, and the base path in front of that, so a
108
+ * package links to its own pages as if it were mounted at the root. A package's generated file calls it once:
109
+ * `export const { Link, Form, SubmitButton, useRouter, usePathname, useHref } = mounted<MountHref>('@acme/help-center')`.
110
+ */
111
+ export function mounted<THref extends string = string>(name: string): Mounted<THref> {
112
+ function MountedLink({ href, ...rest }: MountedLinkProps<THref>) {
113
+ const mount = useMount(name);
114
+ return <Link href={underMount(href, mount, name) as Href} {...rest} />;
115
+ }
116
+
117
+ function MountedForm({ action, ...rest }: MountedFormProps<THref>) {
118
+ const mount = useMount(name);
119
+ const url = typeof action === 'string' ? underMount(action, mount, name) : action;
120
+ return <Form {...(url === undefined ? {} : { action: url })} {...rest} />;
121
+ }
122
+
123
+ function MountedSubmitButton({ formAction, ...rest }: MountedSubmitButtonProps<THref>) {
124
+ const mount = useMount(name);
125
+ return <SubmitButton formAction={typeof formAction === 'string' ? underMount(formAction, mount, name) : formAction} {...rest} />;
126
+ }
127
+
128
+ function useMountedRouter(): MountedRouter<THref> {
129
+ const mount = useMount(name);
130
+ const router = useRouter();
131
+ return useMemo(
132
+ () => ({
133
+ push: (href, options) => router.push(underMount(href, mount, name) as Href, options),
134
+ replace: (href, options) => router.replace(underMount(href, mount, name) as Href, options),
135
+ prefetch: (href) => router.prefetch(underMount(href, mount, name) as Href),
136
+ refresh: () => router.refresh(),
137
+ back: () => router.back(),
138
+ forward: () => router.forward(),
139
+ }),
140
+ [router, mount],
141
+ );
142
+ }
143
+
144
+ function useMountedPathname(): string {
145
+ return belowMount(usePathname(), useMountOrNull(name));
146
+ }
147
+
148
+ function useMountedHref(href: string): string {
149
+ return useHref(underMount(href, useMount(name), name));
150
+ }
151
+
152
+ return {
153
+ Link: MountedLink,
154
+ Form: MountedForm,
155
+ SubmitButton: MountedSubmitButton,
156
+ useRouter: useMountedRouter,
157
+ usePathname: useMountedPathname,
158
+ useHref: useMountedHref,
159
+ };
160
+ }
@@ -0,0 +1,136 @@
1
+ /** How a navigation a guard holds would go: adding or replacing an entry, or through history, either way. */
2
+ export type NavigationAttemptType = 'push' | 'replace' | 'back' | 'forward';
3
+
4
+ /** A navigation `useNavigationGuard` holds: where it goes, how, and the two answers to it. */
5
+ export type NavigationAttempt = {
6
+ /** Where it goes: the path, query and fragment, without the base path, as `usePathname()` and the routes read them. */
7
+ to: string;
8
+ type: NavigationAttemptType;
9
+ /** Lets it go on: to the next guard that holds, if any, then to the page. */
10
+ proceed(): void;
11
+ /** Keeps the page on screen: the navigation does not happen. */
12
+ stay(): void;
13
+ };
14
+
15
+ /** What `useNavigationGuard` takes. */
16
+ export type NavigationGuardOptions = {
17
+ /** Whether to hold navigations now: a form with changes that are not saved, files on their way up. */
18
+ when: boolean;
19
+ /** Called with each navigation held, which waits until it calls `proceed()` or `stay()`. */
20
+ onAttempt(attempt: NavigationAttempt): void;
21
+ };
22
+
23
+ type Guard = { read(): NavigationGuardOptions };
24
+
25
+ /**
26
+ * The guards of one router: the ones that hold now, in the order they started to, and the attempt being asked about.
27
+ * Each navigation a guard holds asks the guards in turn, the one that started to hold last first, and runs once every
28
+ * one of them has let it proceed. A newer attempt takes the place of one still being asked about, so a guard that never
29
+ * answers keeps no navigation from being asked again, and so does a navigation that goes at once because no guard holds
30
+ * any more: the earlier attempt's answers then do nothing.
31
+ *
32
+ * While any guard holds, `beforeunload` has the browser ask its own question before the document unloads: a reload,
33
+ * closing the tab, typing an address, a link to another site. The listener is there only then, as such a listener has
34
+ * kept pages out of some browsers' back-forward cache.
35
+ */
36
+ export class NavigationGuards {
37
+ private readonly guards: Guard[] = [];
38
+ /** The attempt being asked about: dropping it ends it, as a stay does. */
39
+ private asking: { drop(): void } | null = null;
40
+ /** The next unload is a full page load the guards let through: the browser does not ask about it again. */
41
+ private unloadLetThrough = false;
42
+
43
+ private readonly onBeforeUnload = (event: BeforeUnloadEvent) => {
44
+ if (this.unloadLetThrough) {
45
+ this.unloadLetThrough = false;
46
+ return;
47
+ }
48
+ event.preventDefault();
49
+ // What browsers from before preventDefault() asked for.
50
+ event.returnValue = true;
51
+ };
52
+
53
+ /** Whether any guard holds now. */
54
+ get holding(): boolean {
55
+ return this.guards.length > 0;
56
+ }
57
+
58
+ /** Holds navigations until the function it returns is called; `read` gives the latest options. */
59
+ register(read: () => NavigationGuardOptions): () => void {
60
+ const guard: Guard = { read };
61
+ this.guards.push(guard);
62
+ if (this.guards.length === 1) {
63
+ this.unloadLetThrough = false;
64
+ window.addEventListener('beforeunload', this.onBeforeUnload);
65
+ }
66
+ return () => {
67
+ const at = this.guards.indexOf(guard);
68
+ if (at < 0) return;
69
+ this.guards.splice(at, 1);
70
+ if (this.guards.length === 0) window.removeEventListener('beforeunload', this.onBeforeUnload);
71
+ };
72
+ }
73
+
74
+ /**
75
+ * A navigation the guards let through is about to load a document (the router hands it to the browser): the
76
+ * `beforeunload` that follows does not ask again. Only that one.
77
+ */
78
+ letUnloadThrough(): void {
79
+ if (this.guards.length > 0) this.unloadLetThrough = true;
80
+ }
81
+
82
+ /**
83
+ * Drops the attempt still waiting for its answer, whose answers then do nothing: Back or Forward to another page took
84
+ * its place, whether a guard holds that step (and asks about it once its entry is put back) or it went on.
85
+ */
86
+ dropAttempt(): void {
87
+ this.asking?.drop();
88
+ }
89
+
90
+ /**
91
+ * Takes the place of the attempt still waiting for its answer, if any. Then runs `go` at once while no guard holds;
92
+ * else asks the guards that hold, newest first, and runs it once each has let it proceed. Resolves with `go`'s
93
+ * promise, or once a guard keeps the page or a newer attempt takes its place.
94
+ */
95
+ attempt(to: string, type: NavigationAttemptType, go: () => Promise<void>): Promise<void> {
96
+ this.asking?.drop();
97
+ if (this.guards.length === 0) return go();
98
+ return new Promise<void>((resolve) => {
99
+ const queue = [...this.guards].reverse();
100
+ const asking = {
101
+ drop: () => {
102
+ if (this.asking === asking) this.asking = null;
103
+ resolve();
104
+ },
105
+ };
106
+ this.asking = asking;
107
+ const next = () => {
108
+ if (this.asking !== asking) return;
109
+ // A guard that stopped holding while an earlier one was asked has nothing to say any more.
110
+ let guard = queue.shift();
111
+ while (guard && !this.guards.includes(guard)) guard = queue.shift();
112
+ if (!guard) {
113
+ this.asking = null;
114
+ resolve(go());
115
+ return;
116
+ }
117
+ let answered = false;
118
+ guard.read().onAttempt({
119
+ to,
120
+ type,
121
+ proceed: () => {
122
+ if (answered) return;
123
+ answered = true;
124
+ next();
125
+ },
126
+ stay: () => {
127
+ if (answered) return;
128
+ answered = true;
129
+ asking.drop();
130
+ },
131
+ });
132
+ };
133
+ next();
134
+ });
135
+ }
136
+ }
package/src/payload.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { isLanguageTag } from './lang.ts';
1
2
  import type { Metadata } from './metadata.tsx';
2
3
 
3
4
  // The JSON contract with the .NET side (src/Netjes/Rendering/PagePayload.cs). Keep the two in sync.
@@ -12,6 +13,11 @@ export const ANTIFORGERY_HEADER = 'X-Netjes-Antiforgery';
12
13
  * pages the router keeps for back and forward show the app as it was before.
13
14
  */
14
15
  export const COOKIES_HEADER = 'X-Netjes-Cookies';
16
+ /**
17
+ * `1` on the router's request for the URL a redirect sent it to (a redirect payload, or a server action's redirect):
18
+ * where no page answers that URL, the server answers `{ kind: 'document' }` without running the endpoint.
19
+ */
20
+ export const REDIRECTED_HEADER = 'X-Netjes-Redirected';
15
21
  export const DATA_ELEMENT_ID = '__NETJES_DATA__';
16
22
  /** The id of the empty element that ends the body of every server-rendered document, and so the shell. */
17
23
  export const SHELL_END_ID = '__NETJES_SHELL_END__';
@@ -46,6 +52,8 @@ export type SegmentRef = {
46
52
  depth?: number | undefined;
47
53
  /** Each slot page's own route values (its parameter names can differ from the page's). */
48
54
  slotParams?: Record<string, Params> | undefined;
55
+ /** The layout loader's `PageMetadata.Lang`. A reused segment's is the one the client holds, as its props. */
56
+ lang?: string | undefined;
49
57
  };
50
58
 
51
59
  export type SpecialPageRef = { page: string; segments: SegmentRef[] };
@@ -68,9 +76,14 @@ export type AntiforgeryToken = {
68
76
  /** A TanStack Query cache entry seeded by the C# loader (`PageResult.WithQuery`). `updatedAt` is Unix milliseconds. */
69
77
  export type SeededQuery = { key: readonly unknown[]; data: unknown; updatedAt: number };
70
78
 
71
- /** Left by a server action posted without JavaScript that failed validation; the form's page renders with it. */
79
+ /**
80
+ * Left by a form post that failed (a page action's, or a server action's posted without JavaScript); the form's page
81
+ * renders with it. `status` is 422 after a failed validation and 429 after the rate limiter refused the post
82
+ * (`Page.TooManyRequests`); 422 when absent.
83
+ */
72
84
  export type ActionStateRef = {
73
85
  action: string;
86
+ status?: number;
74
87
  errors: Record<string, string[]>;
75
88
  values: Record<string, string | string[]>;
76
89
  };
@@ -115,12 +128,20 @@ export type PagePayload = {
115
128
  intercepts?: InterceptRef[];
116
129
  /** From the C# loader (`.WithMetadata(...)`), merged over the files' `export const metadata`. */
117
130
  metadata?: Metadata;
131
+ /** The page loader's `PageMetadata.Lang`: the document's lang, before its layouts' and the root's (`documentLang`). */
132
+ lang?: string;
118
133
  /** The page was rendered in draft mode. */
119
134
  draftMode?: boolean;
120
135
  /** `UsePathBase`'s base path, when the app is not mounted at the root; `url` includes it. */
121
136
  basePath?: string;
122
137
  /** The request culture, with `AddNetjesLocalization`. */
123
138
  locale?: string;
139
+ /**
140
+ * Each mounted page package's URL for this request, by npm name, without the base path: `/help`, `/acme/help`, or `/`
141
+ * for a package mounted at the root. Null when the request has no value for one of the prefix's parameters. Left out
142
+ * when the app mounts no package.
143
+ */
144
+ mounts?: Record<string, string | null>;
124
145
  /**
125
146
  * Client only, never sent: how far the browser clock is ahead of the server's, measured when the payload arrived.
126
147
  * Server timestamps plus this offset are browser timestamps.
@@ -154,7 +175,10 @@ export type InitialPayload = PagePayload & { document: DocumentInfo };
154
175
 
155
176
  export type RedirectPayload = { kind: 'redirect'; location: string; version: string };
156
177
 
157
- export type NavigationPayload = PagePayload | RedirectPayload;
178
+ /** The answer to a request a redirect led to (`REDIRECTED_HEADER`) when no page answers its URL: load it as a document. */
179
+ export type LoadDocumentPayload = { kind: 'document' };
180
+
181
+ export type NavigationPayload = PagePayload | RedirectPayload | LoadDocumentPayload;
158
182
 
159
183
  export class PayloadError extends Error {
160
184
  override name = 'PayloadError';
@@ -215,6 +239,13 @@ function optionalString(value: unknown, what: string): string | undefined {
215
239
  return value === undefined || value === null ? undefined : string(value, what);
216
240
  }
217
241
 
242
+ /** A language tag's shape (`PageMetadata.Lang`), since the router writes it on `<html>`. */
243
+ function languageTag(value: unknown, what: string): string {
244
+ const tag = string(value, what);
245
+ if (!isLanguageTag(tag)) fail(`${what} must be a language tag, such as nl or en-GB`);
246
+ return tag;
247
+ }
248
+
218
249
  function segments(value: unknown, what: string): SegmentRef[] {
219
250
  if (!Array.isArray(value)) fail(`${what} must be an array`);
220
251
  return value.map((item, i) => {
@@ -228,6 +259,7 @@ function segments(value: unknown, what: string): SegmentRef[] {
228
259
  const key = optionalString(json.key, `${what}[${i}].key`);
229
260
  if (key !== undefined) segment.key = key;
230
261
  if (json.reused === true) segment.reused = true;
262
+ if (json.lang !== undefined && json.lang !== null) segment.lang = languageTag(json.lang, `${what}[${i}].lang`);
231
263
  if (json.depth !== undefined && json.depth !== null) {
232
264
  if (typeof json.depth !== 'number' || !Number.isInteger(json.depth) || json.depth < 0) {
233
265
  throw new PayloadError(`${what}[${i}].depth must be a whole number`);
@@ -262,7 +294,12 @@ function actionState(value: unknown): ActionStateRef {
262
294
  for (const [key, item] of Object.entries(object(json.values ?? {}, 'actionState.values'))) {
263
295
  values[key] = Array.isArray(item) ? strings(item, `actionState.values.${key}`) : string(item, `actionState.values.${key}`);
264
296
  }
265
- return { action: string(json.action, 'actionState.action'), errors: errorMap(json.errors ?? {}, 'actionState.errors'), values };
297
+ return {
298
+ action: string(json.action, 'actionState.action'),
299
+ ...(json.status !== undefined && json.status !== null ? { status: number(json.status, 'actionState.status') } : {}),
300
+ errors: errorMap(json.errors ?? {}, 'actionState.errors'),
301
+ values,
302
+ };
266
303
  }
267
304
 
268
305
  export function parseActionResponse(value: unknown): ActionResponse {
@@ -326,6 +363,7 @@ function pagePayload(json: Json): PagePayload {
326
363
  });
327
364
  }
328
365
  if (json.metadata !== undefined && json.metadata !== null) payload.metadata = object(json.metadata, 'metadata') as Metadata;
366
+ if (json.lang !== undefined && json.lang !== null) payload.lang = languageTag(json.lang, 'lang');
329
367
  if (json.pageKind !== undefined && json.pageKind !== null) {
330
368
  if (!PAGE_KINDS.includes(json.pageKind as PageKind)) fail(`unknown pageKind ${JSON.stringify(json.pageKind)}`);
331
369
  payload.pageKind = json.pageKind as PageKind;
@@ -333,6 +371,7 @@ function pagePayload(json: Json): PagePayload {
333
371
  if (json.renderedAt !== undefined && json.renderedAt !== null) payload.renderedAt = number(json.renderedAt, 'renderedAt');
334
372
  if (json.basePath !== undefined && json.basePath !== null) payload.basePath = string(json.basePath, 'basePath');
335
373
  if (json.locale !== undefined && json.locale !== null) payload.locale = string(json.locale, 'locale');
374
+ if (json.mounts !== undefined && json.mounts !== null) payload.mounts = mounts(json.mounts);
336
375
  if (json.draftMode !== undefined && json.draftMode !== null) {
337
376
  if (typeof json.draftMode !== 'boolean') fail('draftMode must be a boolean');
338
377
  payload.draftMode = json.draftMode;
@@ -340,6 +379,31 @@ function pagePayload(json: Json): PagePayload {
340
379
  return payload;
341
380
  }
342
381
 
382
+ /** A segment a browser resolves away, also when encoded: `.`, `..`, `%2e`, `.%2E` and the like. */
383
+ export function isDotSegment(segment: string): boolean {
384
+ return /^(?:\.|%2e){1,2}$/i.test(segment);
385
+ }
386
+
387
+ /**
388
+ * A mount's URL as the server writes it: `/`, or `/` and segments, none empty or a dot segment, with no query, fragment,
389
+ * backslash, whitespace or control character. The mounted components put it in front of their hrefs.
390
+ */
391
+ function mountUrl(value: unknown, what: string): string | null {
392
+ if (value === null) return null;
393
+ const url = string(value, what);
394
+ if (url === '/') return url;
395
+ const [first, ...segments] = url.split('/');
396
+ const unsafe = (segment: string) => segment === '' || isDotSegment(segment) || /[?#\\\s\u0000-\u001F\u007F]/.test(segment);
397
+ if (first !== '' || segments.length === 0 || segments.some(unsafe)) fail(`${what} must be a path of the app, such as /help`);
398
+ return url;
399
+ }
400
+
401
+ function mounts(value: unknown): Record<string, string | null> {
402
+ const result: Record<string, string | null> = {};
403
+ for (const [name, url] of Object.entries(object(value, 'mounts'))) result[name] = mountUrl(url, `mounts.${name}`);
404
+ return result;
405
+ }
406
+
343
407
  export function parseNavigationPayload(value: unknown): NavigationPayload {
344
408
  const json = object(value, 'payload');
345
409
  switch (json.kind) {
@@ -347,6 +411,8 @@ export function parseNavigationPayload(value: unknown): NavigationPayload {
347
411
  return pagePayload(json);
348
412
  case 'redirect':
349
413
  return { kind: 'redirect', location: string(json.location, 'location'), version: string(json.version, 'version') };
414
+ case 'document':
415
+ return { kind: 'document' };
350
416
  default:
351
417
  return fail(`unknown kind ${JSON.stringify(json.kind)}`);
352
418
  }