netjes 0.0.5 → 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.
- package/README.md +12 -8
- package/cli/commands.mjs +62 -9
- package/cli/process-io.mjs +2 -2
- package/cli/scaffold.mjs +89 -8
- package/dist/client-entry.js +4 -1
- package/dist/client-entry.js.map +1 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +1 -1
- package/dist/document.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/locale.d.ts +5 -0
- package/dist/locale.d.ts.map +1 -1
- package/dist/locale.js +4 -0
- package/dist/locale.js.map +1 -1
- package/dist/metadata.d.ts +81 -4
- package/dist/metadata.d.ts.map +1 -1
- package/dist/metadata.js +129 -7
- package/dist/metadata.js.map +1 -1
- package/dist/modules.d.ts +6 -1
- package/dist/modules.d.ts.map +1 -1
- package/dist/modules.js +15 -1
- package/dist/modules.js.map +1 -1
- package/dist/offline.d.ts +11 -0
- package/dist/offline.d.ts.map +1 -0
- package/dist/offline.js +98 -0
- package/dist/offline.js.map +1 -0
- package/dist/payload.d.ts +18 -0
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +29 -6
- package/dist/payload.js.map +1 -1
- package/dist/render-document.d.ts +8 -1
- package/dist/render-document.d.ts.map +1 -1
- package/dist/render-document.js +2 -0
- package/dist/render-document.js.map +1 -1
- package/dist/root.d.ts.map +1 -1
- package/dist/root.js +9 -1
- package/dist/root.js.map +1 -1
- package/dist/route-tree.d.ts +2 -1
- package/dist/route-tree.d.ts.map +1 -1
- package/dist/route-tree.js +14 -7
- package/dist/route-tree.js.map +1 -1
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +1 -1
- package/dist/router.js.map +1 -1
- package/dist/service-worker.d.ts +81 -0
- package/dist/service-worker.d.ts.map +1 -0
- package/dist/service-worker.js +584 -0
- package/dist/service-worker.js.map +1 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js.map +1 -1
- package/package.json +12 -5
- package/sidecar/server.mjs +25 -2
- package/skills/netjes/SKILL.md +3 -1
- package/skills/netjes/references/caching-and-streaming.md +22 -1
- package/skills/netjes/references/deployment.md +2 -2
- package/skills/netjes/references/routing.md +5 -1
- package/src/client-entry.tsx +4 -1
- package/src/document.tsx +6 -1
- package/src/index.ts +3 -2
- package/src/locale.ts +5 -0
- package/src/metadata.tsx +207 -11
- package/src/modules.ts +19 -3
- package/src/offline.ts +97 -0
- package/src/payload.ts +41 -5
- package/src/render-document.tsx +10 -1
- package/src/root.tsx +21 -11
- package/src/route-tree.tsx +18 -7
- package/src/router.tsx +1 -0
- package/src/service-worker.ts +632 -0
- package/src/testing.tsx +1 -0
- package/template/Dockerfile.pnpm +68 -0
- package/template/Dockerfile.workspace +52 -0
- package/template/Dockerfile.workspace.dockerignore +15 -0
- package/template/README.md +5 -1
- package/template/_AGENTS.md +5 -1
- package/template/app/layout.tsx +0 -1
- package/tsconfig.strict-app.json +27 -0
- package/vite/packages.mjs +97 -0
- package/vite/plugin.d.ts +8 -1
- package/vite/plugin.mjs +156 -9
- /package/template/{public/favicon.svg → app/icon.svg} +0 -0
package/src/modules.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ComponentType, ReactNode } from 'react';
|
|
2
|
-
import type { Metadata } from './metadata.tsx';
|
|
2
|
+
import type { Metadata, Viewport } from './metadata.tsx';
|
|
3
3
|
import type { Params, SegmentRef } from './payload.ts';
|
|
4
4
|
|
|
5
5
|
export type PageComponent = ComponentType<Record<string, unknown>>;
|
|
@@ -26,6 +26,8 @@ export type LoadedSegment = {
|
|
|
26
26
|
id: string;
|
|
27
27
|
/** The layout's `export const metadata`. */
|
|
28
28
|
metadata?: Metadata;
|
|
29
|
+
/** The layout's `export const viewport`. */
|
|
30
|
+
viewport?: Viewport;
|
|
29
31
|
Layout?: LayoutComponent;
|
|
30
32
|
Template?: ComponentType<{ children: ReactNode }>;
|
|
31
33
|
Loading?: ComponentType;
|
|
@@ -37,12 +39,14 @@ export type LoadedSegment = {
|
|
|
37
39
|
/** What `import.meta.glob` produces: root-relative paths (`/app/x/page.tsx`) to lazy imports. */
|
|
38
40
|
export type ModuleMap = Record<string, () => Promise<unknown>>;
|
|
39
41
|
|
|
40
|
-
export type RouteModules = { page: PageComponent | null; segments: LoadedSegment[]; pageMetadata?: Metadata };
|
|
42
|
+
export type RouteModules = { page: PageComponent | null; segments: LoadedSegment[]; pageMetadata?: Metadata; pageViewport?: Viewport };
|
|
41
43
|
|
|
42
44
|
export type ModuleLoader = {
|
|
43
45
|
load(file: string): Promise<ComponentType<never>>;
|
|
44
46
|
/** A loaded module's `export const metadata`, if any. */
|
|
45
47
|
metadataOf(file: string): Metadata | undefined;
|
|
48
|
+
/** A loaded module's `export const viewport`, if any. */
|
|
49
|
+
viewportOf(file: string): Viewport | undefined;
|
|
46
50
|
loadRoute(route: { page: string | null; segments: readonly SegmentRef[] }): Promise<RouteModules>;
|
|
47
51
|
};
|
|
48
52
|
|
|
@@ -87,6 +91,7 @@ function isComponent(value: unknown): value is ComponentType<never> {
|
|
|
87
91
|
export function createModuleLoader(modules: ModuleMap, options: ModuleLoaderOptions = {}): ModuleLoader {
|
|
88
92
|
const cache = new Map<string, Promise<ComponentType<never>>>();
|
|
89
93
|
const metadata = new Map<string, Metadata>();
|
|
94
|
+
const viewports = new Map<string, Viewport>();
|
|
90
95
|
|
|
91
96
|
function load(file: string): Promise<ComponentType<never>> {
|
|
92
97
|
const cached = cache.get(file);
|
|
@@ -99,6 +104,8 @@ export function createModuleLoader(modules: ModuleMap, options: ModuleLoaderOpti
|
|
|
99
104
|
if (!isComponent(component)) throw new Error(`netjes: ${file} must have a default export that is a React component`);
|
|
100
105
|
const exported = (module as { metadata?: unknown }).metadata;
|
|
101
106
|
if (typeof exported === 'object' && exported !== null) metadata.set(file, exported as Metadata);
|
|
107
|
+
const viewport = (module as { viewport?: unknown }).viewport;
|
|
108
|
+
if (typeof viewport === 'object' && viewport !== null) viewports.set(file, viewport as Viewport);
|
|
102
109
|
return component;
|
|
103
110
|
},
|
|
104
111
|
(error: unknown) => {
|
|
@@ -113,6 +120,7 @@ export function createModuleLoader(modules: ModuleMap, options: ModuleLoaderOpti
|
|
|
113
120
|
return {
|
|
114
121
|
load,
|
|
115
122
|
metadataOf: (file) => metadata.get(file),
|
|
123
|
+
viewportOf: (file) => viewports.get(file),
|
|
116
124
|
async loadRoute(route) {
|
|
117
125
|
const optional = (file: string | undefined) => (file ? load(file) : Promise.resolve(undefined));
|
|
118
126
|
const [page, segments] = await Promise.all([
|
|
@@ -131,6 +139,8 @@ export function createModuleLoader(modules: ModuleMap, options: ModuleLoaderOpti
|
|
|
131
139
|
}
|
|
132
140
|
const layoutMetadata = segment.layout ? metadata.get(segment.layout) : undefined;
|
|
133
141
|
if (layoutMetadata) loaded.metadata = layoutMetadata;
|
|
142
|
+
const layoutViewport = segment.layout ? viewports.get(segment.layout) : undefined;
|
|
143
|
+
if (layoutViewport) loaded.viewport = layoutViewport;
|
|
134
144
|
if (Layout) loaded.Layout = Layout as LayoutComponent;
|
|
135
145
|
if (Template) loaded.Template = Template as LoadedSegment['Template'] & object;
|
|
136
146
|
if (Loading) loaded.Loading = Loading as ComponentType;
|
|
@@ -140,7 +150,13 @@ export function createModuleLoader(modules: ModuleMap, options: ModuleLoaderOpti
|
|
|
140
150
|
),
|
|
141
151
|
]);
|
|
142
152
|
const pageMetadata = route.page ? metadata.get(route.page) : undefined;
|
|
143
|
-
|
|
153
|
+
const pageViewport = route.page ? viewports.get(route.page) : undefined;
|
|
154
|
+
return {
|
|
155
|
+
page: (page ?? null) as PageComponent | null,
|
|
156
|
+
segments,
|
|
157
|
+
...(pageMetadata ? { pageMetadata } : {}),
|
|
158
|
+
...(pageViewport ? { pageViewport } : {}),
|
|
159
|
+
};
|
|
144
160
|
},
|
|
145
161
|
};
|
|
146
162
|
}
|
package/src/offline.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/// <reference types="vite/client" />
|
|
2
|
+
|
|
3
|
+
import { type Href, isHrefShape } from './href.ts';
|
|
4
|
+
import { DATA_ELEMENT_ID } from './payload.ts';
|
|
5
|
+
import { withBasePath } from './router.tsx';
|
|
6
|
+
|
|
7
|
+
declare const __NETJES_DEV__: boolean;
|
|
8
|
+
|
|
9
|
+
const KEEP_TIMEOUT_MS = 30_000;
|
|
10
|
+
type OfflineMessage = { type: 'netjes:keep'; urls: string[] };
|
|
11
|
+
|
|
12
|
+
function basePath(): string {
|
|
13
|
+
const json = document.getElementById(DATA_ELEMENT_ID)?.textContent;
|
|
14
|
+
if (!json) return '';
|
|
15
|
+
const data: unknown = JSON.parse(json);
|
|
16
|
+
const path = data && typeof data === 'object' && 'basePath' in data ? data.basePath : undefined;
|
|
17
|
+
return typeof path === 'string' && path.startsWith('/') && isHrefShape(path) && !/[?#\\]/.test(path)
|
|
18
|
+
? path.replace(/\/+$/, '')
|
|
19
|
+
: '';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function serviceWorkers(): ServiceWorkerContainer | undefined {
|
|
23
|
+
return typeof window === 'undefined' ? undefined : navigator.serviceWorker;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Registers the app's production worker under the current Netjes base path. */
|
|
27
|
+
export async function registerServiceWorker(url?: string): Promise<ServiceWorkerRegistration | undefined> {
|
|
28
|
+
const development = typeof __NETJES_DEV__ === 'undefined' ? import.meta.env?.DEV : __NETJES_DEV__;
|
|
29
|
+
if (development) return undefined;
|
|
30
|
+
const workers = serviceWorkers();
|
|
31
|
+
if (!workers) return undefined;
|
|
32
|
+
const base = basePath();
|
|
33
|
+
return workers.register(url ?? `${base}/sw.js`, { scope: `${base}/` });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function registrationFor(workers: ServiceWorkerContainer, base: string): Promise<ServiceWorkerRegistration | undefined> {
|
|
37
|
+
const scope = new URL(`${base}/`, window.location.href).href;
|
|
38
|
+
const registration = await workers.getRegistration(scope);
|
|
39
|
+
// getRegistration can return a parent registration that also covers this URL.
|
|
40
|
+
return registration?.scope === scope ? registration : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function send(worker: ServiceWorker | null, message: OfflineMessage, timeoutMs: number): Promise<void> {
|
|
44
|
+
if (!worker) throw new Error('netjes: the service worker is not active');
|
|
45
|
+
const channel = new MessageChannel();
|
|
46
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
47
|
+
try {
|
|
48
|
+
await new Promise<void>((resolve, reject) => {
|
|
49
|
+
timeout = setTimeout(() => reject(new Error('netjes: the service worker did not acknowledge the offline request')), timeoutMs);
|
|
50
|
+
channel.port1.onmessage = ({ data }: MessageEvent<unknown>) => {
|
|
51
|
+
if (typeof data !== 'object' || data === null || !('type' in data)) return;
|
|
52
|
+
if (data.type === 'netjes:failed') reject(new Error('netjes: the service worker could not complete the offline request'));
|
|
53
|
+
if (data.type === 'netjes:done') resolve();
|
|
54
|
+
};
|
|
55
|
+
worker.postMessage(message, [channel.port2]);
|
|
56
|
+
});
|
|
57
|
+
} finally {
|
|
58
|
+
clearTimeout(timeout);
|
|
59
|
+
channel.port1.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Asks this app's worker to keep one or more pages, and waits for it to finish. */
|
|
64
|
+
export async function keepOffline(href: Href | readonly Href[]): Promise<void> {
|
|
65
|
+
const workers = serviceWorkers();
|
|
66
|
+
if (!workers) return;
|
|
67
|
+
const base = basePath();
|
|
68
|
+
const registration = await registrationFor(workers, base);
|
|
69
|
+
if (!registration) return;
|
|
70
|
+
const urls = (typeof href === 'string' ? [href] : href).map((url) => {
|
|
71
|
+
if (!url.startsWith('?') && !url.startsWith('#')) return withBasePath(url, base);
|
|
72
|
+
const current = new URL(url, window.location.href);
|
|
73
|
+
return current.pathname + current.search + current.hash;
|
|
74
|
+
});
|
|
75
|
+
await send(registration.active, { type: 'netjes:keep', urls }, KEEP_TIMEOUT_MS);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** What follows `<prefix>:pages:` in a page cache's name: the visitor's scope and the cache's random id, nothing more. */
|
|
79
|
+
const PAGE_CACHE_REST = /^[A-Za-z0-9_-]{1,64}:[0-9a-f]{32}$/;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Deletes this app's stored pages: every cache the worker named as a page cache of the app's base path, listed again
|
|
83
|
+
* until none is left. It needs no worker and sends no message. Sign the visitor out first, then await it.
|
|
84
|
+
*/
|
|
85
|
+
export async function clearOffline(): Promise<void> {
|
|
86
|
+
if (typeof caches === 'undefined') return;
|
|
87
|
+
// The worker names a visitor's cache `netjes-offline:<registration scope>:pages:<scope>:<id>`, registered at the base
|
|
88
|
+
// path. The whole name counts: a nested app at `/docs/:pages:x` has caches that start with this prefix too.
|
|
89
|
+
const prefix = `netjes-offline:${new URL(`${basePath()}/`, window.location.href).href}:pages:`;
|
|
90
|
+
const isPageCache = (name: string) => name.startsWith(prefix) && PAGE_CACHE_REST.test(name.slice(prefix.length));
|
|
91
|
+
// A worker can open a cache after a listing; it opens at most one per page response, so this ends.
|
|
92
|
+
for (;;) {
|
|
93
|
+
const names = (await caches.keys()).filter(isPageCache);
|
|
94
|
+
if (names.length === 0) return;
|
|
95
|
+
await Promise.all(names.map((name) => caches.delete(name)));
|
|
96
|
+
}
|
|
97
|
+
}
|
package/src/payload.ts
CHANGED
|
@@ -136,6 +136,8 @@ export type PagePayload = {
|
|
|
136
136
|
basePath?: string;
|
|
137
137
|
/** The request culture, with `AddNetjesLocalization`. */
|
|
138
138
|
locale?: string;
|
|
139
|
+
/** The current page’s alternate locale URLs, relative to the app root. */
|
|
140
|
+
localeAlternates?: Record<string, string>;
|
|
139
141
|
/**
|
|
140
142
|
* Each mounted page package's URL for this request, by npm name, without the base path: `/help`, `/acme/help`, or `/`
|
|
141
143
|
* for a package mounted at the root. Null when the request has no value for one of the prefix's parameters. Left out
|
|
@@ -152,6 +154,12 @@ export type PagePayload = {
|
|
|
152
154
|
/** The `<Image>` optimizer: its path and the widths it serves (Netjes:Images). */
|
|
153
155
|
export type ImageConfigInfo = { path: string; widths: number[]; qualities?: number[]; basePath?: string };
|
|
154
156
|
|
|
157
|
+
/** A link to one of the app's icon files: `rel` is `icon` or `apple-touch-icon`. */
|
|
158
|
+
export type HeadIcon = { rel: string; href: string; type?: string; sizes?: string };
|
|
159
|
+
|
|
160
|
+
/** The links to the app's metadata files (favicon.ico, icon*, apple-icon*, the web app manifest), under the base path. */
|
|
161
|
+
export type DocumentHead = { icons: HeadIcon[]; manifest?: string };
|
|
162
|
+
|
|
155
163
|
export type DocumentInfo = {
|
|
156
164
|
lang: string;
|
|
157
165
|
assets: DocumentAssets;
|
|
@@ -169,6 +177,10 @@ export type DocumentInfo = {
|
|
|
169
177
|
* it instead of hydrating.
|
|
170
178
|
*/
|
|
171
179
|
clientRender?: boolean;
|
|
180
|
+
/** The links to the app's metadata files, which the document writes in its head. */
|
|
181
|
+
head?: DocumentHead;
|
|
182
|
+
/** The server's `NetjesOptions.SiteUrl`: the metadata base relative metadata URLs resolve against. */
|
|
183
|
+
siteUrl?: string;
|
|
172
184
|
};
|
|
173
185
|
|
|
174
186
|
export type InitialPayload = PagePayload & { document: DocumentInfo };
|
|
@@ -371,6 +383,14 @@ function pagePayload(json: Json): PagePayload {
|
|
|
371
383
|
if (json.renderedAt !== undefined && json.renderedAt !== null) payload.renderedAt = number(json.renderedAt, 'renderedAt');
|
|
372
384
|
if (json.basePath !== undefined && json.basePath !== null) payload.basePath = string(json.basePath, 'basePath');
|
|
373
385
|
if (json.locale !== undefined && json.locale !== null) payload.locale = string(json.locale, 'locale');
|
|
386
|
+
if (json.localeAlternates !== undefined && json.localeAlternates !== null) {
|
|
387
|
+
payload.localeAlternates = Object.fromEntries(
|
|
388
|
+
Object.entries(object(json.localeAlternates, 'localeAlternates')).map(([locale, path]) => {
|
|
389
|
+
const field = `localeAlternates.${locale}`;
|
|
390
|
+
return [languageTag(locale, field), appPath(path, field)];
|
|
391
|
+
}),
|
|
392
|
+
);
|
|
393
|
+
}
|
|
374
394
|
if (json.mounts !== undefined && json.mounts !== null) payload.mounts = mounts(json.mounts);
|
|
375
395
|
if (json.draftMode !== undefined && json.draftMode !== null) {
|
|
376
396
|
if (typeof json.draftMode !== 'boolean') fail('draftMode must be a boolean');
|
|
@@ -385,11 +405,10 @@ export function isDotSegment(segment: string): boolean {
|
|
|
385
405
|
}
|
|
386
406
|
|
|
387
407
|
/**
|
|
388
|
-
* A
|
|
389
|
-
* backslash, whitespace or control character.
|
|
408
|
+
* A path relative to the app root as the server writes it: `/`, or `/` and segments, none empty or a dot segment, with no query, fragment,
|
|
409
|
+
* backslash, whitespace or control character.
|
|
390
410
|
*/
|
|
391
|
-
function
|
|
392
|
-
if (value === null) return null;
|
|
411
|
+
function appPath(value: unknown, what: string): string {
|
|
393
412
|
const url = string(value, what);
|
|
394
413
|
if (url === '/') return url;
|
|
395
414
|
const [first, ...segments] = url.split('/');
|
|
@@ -400,7 +419,7 @@ function mountUrl(value: unknown, what: string): string | null {
|
|
|
400
419
|
|
|
401
420
|
function mounts(value: unknown): Record<string, string | null> {
|
|
402
421
|
const result: Record<string, string | null> = {};
|
|
403
|
-
for (const [name, url] of Object.entries(object(value, 'mounts'))) result[name] =
|
|
422
|
+
for (const [name, url] of Object.entries(object(value, 'mounts'))) result[name] = url === null ? null : appPath(url, `mounts.${name}`);
|
|
404
423
|
return result;
|
|
405
424
|
}
|
|
406
425
|
|
|
@@ -463,6 +482,23 @@ export function parseInitialPayload(value: unknown): InitialPayload {
|
|
|
463
482
|
if (document.publicConfig !== undefined && document.publicConfig !== null) {
|
|
464
483
|
info.publicConfig = object(document.publicConfig, 'document.publicConfig');
|
|
465
484
|
}
|
|
485
|
+
if (document.head !== undefined && document.head !== null) {
|
|
486
|
+
const head = object(document.head, 'document.head');
|
|
487
|
+
if (!Array.isArray(head.icons)) fail('document.head.icons must be an array');
|
|
488
|
+
info.head = {
|
|
489
|
+
icons: head.icons.map((value, i) => {
|
|
490
|
+
const icon = object(value, `document.head.icons[${i}]`);
|
|
491
|
+
return {
|
|
492
|
+
rel: string(icon.rel, `document.head.icons[${i}].rel`),
|
|
493
|
+
href: string(icon.href, `document.head.icons[${i}].href`),
|
|
494
|
+
...(icon.type !== undefined && icon.type !== null ? { type: string(icon.type, `document.head.icons[${i}].type`) } : {}),
|
|
495
|
+
...(icon.sizes !== undefined && icon.sizes !== null ? { sizes: string(icon.sizes, `document.head.icons[${i}].sizes`) } : {}),
|
|
496
|
+
};
|
|
497
|
+
}),
|
|
498
|
+
...(head.manifest !== undefined && head.manifest !== null ? { manifest: string(head.manifest, 'document.head.manifest') } : {}),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
if (document.siteUrl !== undefined && document.siteUrl !== null) info.siteUrl = string(document.siteUrl, 'document.siteUrl');
|
|
466
502
|
if (document.clientRender !== undefined && document.clientRender !== null) {
|
|
467
503
|
if (typeof document.clientRender !== 'boolean') fail('document.clientRender must be a boolean');
|
|
468
504
|
if (document.clientRender) info.clientRender = true;
|
package/src/render-document.tsx
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// server's rules for the route and the segments (RouteTable and PageRenderer in src/Netjes). The two are checked
|
|
5
5
|
// against the same cases, test/fixtures/segments/cases.json, so a change to either rule fails a suite until both agree.
|
|
6
6
|
import { htmlSafeJson } from './deferred.ts';
|
|
7
|
-
import type { InitialPayload, PageKind, Params, SegmentRef } from './payload.ts';
|
|
7
|
+
import type { DocumentHead, InitialPayload, PageKind, Params, SegmentRef } from './payload.ts';
|
|
8
8
|
|
|
9
9
|
/** What {@link renderDocument} renders a page with: what the server would send with it. */
|
|
10
10
|
export type RenderDocumentOptions = {
|
|
@@ -46,6 +46,13 @@ export type RenderDocumentOptions = {
|
|
|
46
46
|
modules?: Record<string, () => Promise<unknown>>;
|
|
47
47
|
/** Stops the render, which then rejects with the signal's reason: for a page that waits on a Promise that never settles. */
|
|
48
48
|
signal?: AbortSignal;
|
|
49
|
+
/**
|
|
50
|
+
* The links to the app's metadata files (`favicon.ico`, `icon*`, `apple-icon*`, the manifest) the server would send,
|
|
51
|
+
* which the document writes in its head. Default none.
|
|
52
|
+
*/
|
|
53
|
+
head?: DocumentHead;
|
|
54
|
+
/** The server's `NetjesOptions.SiteUrl`, the base relative metadata URLs resolve against. Default none. */
|
|
55
|
+
siteUrl?: string;
|
|
49
56
|
};
|
|
50
57
|
|
|
51
58
|
/** The options {@link documentPayload} reads, with any Promise in the props already a placeholder. */
|
|
@@ -319,6 +326,8 @@ export function documentPayload(
|
|
|
319
326
|
errorPage: null,
|
|
320
327
|
...(options.publicConfig ? { publicConfig: options.publicConfig } : {}),
|
|
321
328
|
...(options.nonce ? { nonce: options.nonce } : {}),
|
|
329
|
+
...(options.head ? { head: options.head } : {}),
|
|
330
|
+
...(options.siteUrl ? { siteUrl: options.siteUrl } : {}),
|
|
322
331
|
},
|
|
323
332
|
};
|
|
324
333
|
}
|
package/src/root.tsx
CHANGED
|
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
|
|
|
2
2
|
import { QueryShell } from 'virtual:netjes/query';
|
|
3
3
|
import { Document } from './document.tsx';
|
|
4
4
|
import { ImageConfigProvider } from './image.tsx';
|
|
5
|
+
import { HeadContext } from './metadata.tsx';
|
|
5
6
|
import { documentLang } from './lang.ts';
|
|
6
7
|
import { NonceProvider } from './nonce.tsx';
|
|
7
8
|
import { PublicConfigProvider } from './public-config.tsx';
|
|
@@ -24,18 +25,27 @@ function RootProviders({ info, children }: { info: DocumentInfo; children: React
|
|
|
24
25
|
|
|
25
26
|
/** The same tree on the server and in the browser, so hydration matches. */
|
|
26
27
|
export function Root({ payload, modules, loader, dataJson }: RootProps) {
|
|
28
|
+
const info = payload.document;
|
|
29
|
+
const head = {
|
|
30
|
+
siteUrl: info.siteUrl,
|
|
31
|
+
basePath: payload.basePath ?? '',
|
|
32
|
+
manifestFile: Boolean(info.head?.manifest),
|
|
33
|
+
iconFiles: (info.head?.icons.length ?? 0) > 0,
|
|
34
|
+
};
|
|
27
35
|
return (
|
|
28
|
-
<Document info={
|
|
29
|
-
<
|
|
30
|
-
<
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
<Document info={info} lang={documentLang(payload, info.lang)} dataJson={dataJson}>
|
|
37
|
+
<HeadContext value={head}>
|
|
38
|
+
<RootProviders info={payload.document}>
|
|
39
|
+
<RouterProvider
|
|
40
|
+
initial={payload}
|
|
41
|
+
initialModules={modules}
|
|
42
|
+
loader={loader}
|
|
43
|
+
errorPage={payload.document.errorPage}
|
|
44
|
+
documentLang={payload.document.lang}
|
|
45
|
+
shell={QueryShell}
|
|
46
|
+
/>
|
|
47
|
+
</RootProviders>
|
|
48
|
+
</HeadContext>
|
|
39
49
|
</Document>
|
|
40
50
|
);
|
|
41
51
|
}
|
package/src/route-tree.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Component, type ReactElement, type ReactNode, Suspense, createContext } from 'react';
|
|
1
|
+
import { Component, type ReactElement, type ReactNode, Suspense, createContext, use } from 'react';
|
|
2
2
|
import { withheldError } from './errors.ts';
|
|
3
|
-
import { type Metadata,
|
|
3
|
+
import { HeadContext, HeadTags, type Metadata, resolveMetadata, resolveViewport, warnOnce } from './metadata.tsx';
|
|
4
4
|
import type { ErrorPageProps, LoadedSegment, RouteModules } from './modules.ts';
|
|
5
5
|
import type { PageKind, Params, SegmentRef } from './payload.ts';
|
|
6
6
|
|
|
@@ -22,6 +22,7 @@ type RouteTreeProps = {
|
|
|
22
22
|
error?: ErrorPageProps['error'];
|
|
23
23
|
/** Metadata from the C# loader. */
|
|
24
24
|
metadata?: Metadata | undefined;
|
|
25
|
+
localeAlternates?: Record<string, string> | undefined;
|
|
25
26
|
};
|
|
26
27
|
|
|
27
28
|
/** How many URL segments the layout rendering here covers: what useSelectedLayoutSegment(s) count from. */
|
|
@@ -81,7 +82,7 @@ function serverError(props: Record<string, unknown>): ErrorPageProps['error'] {
|
|
|
81
82
|
* layout > template > error boundary > Suspense (loading) > the next segment or the page. Layouts keep their state
|
|
82
83
|
* while the page underneath changes; templates remount.
|
|
83
84
|
*/
|
|
84
|
-
export function RouteTree({ modules, segments = [], props, params, status, pageKind, pageKey, retry, metadata, error }: RouteTreeProps): ReactElement {
|
|
85
|
+
export function RouteTree({ modules, segments = [], props, params, status, pageKind, pageKey, retry, metadata, localeAlternates, error }: RouteTreeProps): ReactElement {
|
|
85
86
|
const Page = modules.page;
|
|
86
87
|
const pageProps = pageKind === 'error' ? { ...props, error: error ?? serverError(props), reset: retry ?? (() => {}) } : props;
|
|
87
88
|
let element: ReactElement = Page ? <Page key={pageKey} {...pageProps} /> : <BuiltInPage key={pageKey} status={status} props={props} />;
|
|
@@ -107,13 +108,23 @@ export function RouteTree({ modules, segments = [], props, params, status, pageK
|
|
|
107
108
|
);
|
|
108
109
|
}
|
|
109
110
|
}
|
|
111
|
+
const head = use(HeadContext);
|
|
110
112
|
const layoutsMetadata = modules.segments.map((segment) => segment.metadata);
|
|
111
|
-
const hasMetadata = layoutsMetadata.some(Boolean) || Boolean(modules.pageMetadata) || Boolean(metadata);
|
|
112
|
-
|
|
113
|
-
|
|
113
|
+
const hasMetadata = layoutsMetadata.some(Boolean) || Boolean(modules.pageMetadata) || Boolean(metadata) || Boolean(localeAlternates);
|
|
114
|
+
const resolved = hasMetadata
|
|
115
|
+
? resolveMetadata(layoutsMetadata, modules.pageMetadata, metadata, { siteUrl: head.siteUrl, basePath: head.basePath, localeAlternates })
|
|
116
|
+
: undefined;
|
|
117
|
+
if (resolved?.icons && head.iconFiles) {
|
|
118
|
+
warnOnce(
|
|
119
|
+
'icons-and-files',
|
|
120
|
+
'netjes: metadata.icons sets icon links, and the app has icon files at the root of app/ as well, so the head links both. Use one or the other.',
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
// Always the head (every document has exactly one viewport tag, which the document itself no longer writes), and one
|
|
124
|
+
// shape for every page: the layouts stay at the same place in the tree, so React keeps them mounted between pages.
|
|
114
125
|
return (
|
|
115
126
|
<>
|
|
116
|
-
|
|
127
|
+
<HeadTags viewport={resolveViewport(modules.segments.map((segment) => segment.viewport), modules.pageViewport)} metadata={resolved} head={head} />
|
|
117
128
|
{element}
|
|
118
129
|
</>
|
|
119
130
|
);
|
package/src/router.tsx
CHANGED
|
@@ -1628,6 +1628,7 @@ export function RouterProvider({
|
|
|
1628
1628
|
pageKey={pageKeyOf(view.loaded)}
|
|
1629
1629
|
retry={() => void router.refresh()}
|
|
1630
1630
|
metadata={view.loaded.payload.metadata}
|
|
1631
|
+
localeAlternates={view.loaded.payload.localeAlternates}
|
|
1631
1632
|
/>
|
|
1632
1633
|
</ErrorBoundary>
|
|
1633
1634
|
</Shell>
|