@ultimat3/render 30.8.0 → 31.0.0
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/CLAUDE.md +23 -16
- package/README.md +27 -17
- package/package.json +9 -7
- package/src/adapter.ts +13 -0
- package/src/client-sync-tags.ts +11 -1
- package/src/client.ts +2 -0
- package/src/html.ts +57 -18
- package/src/index.ts +6 -28
- package/src/island-props.ts +3 -7
- package/src/jsx.ts +7 -1
- package/src/navigation-history.ts +12 -0
- package/src/navigation-intercept.ts +157 -0
- package/src/navigation.ts +20 -124
- package/src/registry.ts +9 -0
- package/src/render-html.ts +25 -159
- package/src/render-instrument.ts +66 -0
- package/src/render-isr-store-codec.ts +41 -0
- package/src/render-isr-store-storage.ts +194 -0
- package/src/render-isr-store.ts +68 -18
- package/src/render-isr-types.ts +8 -3
- package/src/render-isr.ts +72 -30
- package/src/render-walk.ts +275 -0
- package/src/server.ts +9 -1
- package/src/surfaces.ts +23 -5
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client router's interception: which DOM events it listens to, what each one turns into (a
|
|
3
|
+
* soft navigation, a prefetch, a Back that moves only the scroll), and the hover timer behind a
|
|
4
|
+
* prefetch. Split from `navigation.ts` (plan 101 slice 14 P5) so that file is the controller.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { anchorOf, intentUrl, linkFacts, submitFacts } from './navigation-dom';
|
|
8
|
+
import { entryOf, withoutFragment } from './navigation-history';
|
|
9
|
+
import type { ModalController } from './navigation-modal';
|
|
10
|
+
import { modalAddress } from './navigation-modal-rules';
|
|
11
|
+
import type { PressTracker } from './navigation-press';
|
|
12
|
+
import { formVerdict, linkVerdict, NAVIGATION_PREFETCH_DELAY_MS } from './navigation-rules';
|
|
13
|
+
import type { ScrollKeeper } from './navigation-scroll';
|
|
14
|
+
|
|
15
|
+
/** What a listener may start: a soft visit, a POST, or a Back that the page on screen answers. */
|
|
16
|
+
type Navigate = (
|
|
17
|
+
url: string,
|
|
18
|
+
options?: { method?: 'POST'; body?: BodyInit; history?: 'none' },
|
|
19
|
+
) => Promise<void>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `[cancelIntent, stop]`: a tuple and positional parameters rather than a host object, because
|
|
23
|
+
* this script ships to every opted-in page and a property name survives minification — the
|
|
24
|
+
* object form cost the router 219 B for nothing it did (axiom 9).
|
|
25
|
+
*/
|
|
26
|
+
export type Interception = readonly [cancelIntent: () => void, stop: () => void];
|
|
27
|
+
|
|
28
|
+
export function interceptNavigation(
|
|
29
|
+
win: Window,
|
|
30
|
+
press: PressTracker,
|
|
31
|
+
modal: Pick<ModalController, 'address' | 'close'>,
|
|
32
|
+
scroll: Pick<ScrollKeeper, 'cancel'>,
|
|
33
|
+
/** The document on screen, without its fragment. */
|
|
34
|
+
rendered: () => string,
|
|
35
|
+
/** After an answer for another principal or build was shown in place (`answerMovesTab`). */
|
|
36
|
+
untrusted: () => boolean,
|
|
37
|
+
navigate: Navigate,
|
|
38
|
+
prefetch: (url: string) => void,
|
|
39
|
+
/** A Back/Forward landed: the router's own Back is no longer traversing. */
|
|
40
|
+
popped: () => void,
|
|
41
|
+
reconcile: () => void,
|
|
42
|
+
): Interception {
|
|
43
|
+
const doc = win.document;
|
|
44
|
+
/** The pending prefetch of a hover, cancelled by anything that navigates. */
|
|
45
|
+
let intent: number | undefined;
|
|
46
|
+
const cancelIntent = (): void => win.clearTimeout(intent);
|
|
47
|
+
|
|
48
|
+
const onPress = (): void => {
|
|
49
|
+
press.onPress();
|
|
50
|
+
// A press is not a hover: the click it becomes navigates, and a guess on its heels is a
|
|
51
|
+
// second request for the same page.
|
|
52
|
+
cancelIntent();
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const onClick = (event: MouseEvent): void => {
|
|
56
|
+
cancelIntent();
|
|
57
|
+
if (press.overlayClick(event)) return;
|
|
58
|
+
const anchor = anchorOf(event.target);
|
|
59
|
+
if (anchor === null) return;
|
|
60
|
+
const verdict = linkVerdict(linkFacts(win, anchor, event));
|
|
61
|
+
if (verdict.kind !== 'soft') return;
|
|
62
|
+
event.preventDefault();
|
|
63
|
+
// A link to the page beneath an open modal (its Cancel) closes the modal: nothing is fetched.
|
|
64
|
+
if (modal.address !== undefined && withoutFragment(verdict.url) === rendered()) modal.close();
|
|
65
|
+
else void navigate(verdict.url);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const onSubmit = (event: SubmitEvent): void => {
|
|
69
|
+
const form = event.target;
|
|
70
|
+
// An untrusted tab (`answerMovesTab`) leaves every form to the browser.
|
|
71
|
+
if (!(form instanceof HTMLFormElement) || untrusted()) return;
|
|
72
|
+
const { facts, fields } = submitFacts(win, form, event.submitter, event.defaultPrevented);
|
|
73
|
+
const verdict = formVerdict(facts);
|
|
74
|
+
if (verdict.kind === 'native') return;
|
|
75
|
+
event.preventDefault();
|
|
76
|
+
if (verdict.kind === 'get') {
|
|
77
|
+
void navigate(verdict.url);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const body =
|
|
81
|
+
verdict.encoding === 'multipart'
|
|
82
|
+
? fields
|
|
83
|
+
: new URLSearchParams(facts.fields.map(([name, value]) => [name, value]));
|
|
84
|
+
void navigate(verdict.url, { method: 'POST', body });
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const onIntent = (event: Event): void => {
|
|
88
|
+
// The focus a press gives a link: its click is a moment away, and it navigates.
|
|
89
|
+
if (event.type === 'focusin' && press.pressed()) return;
|
|
90
|
+
const url = intentUrl(win, event.target);
|
|
91
|
+
if (url === undefined) return;
|
|
92
|
+
cancelIntent();
|
|
93
|
+
const delay = event.type === 'pointerover' ? NAVIGATION_PREFETCH_DELAY_MS : 0;
|
|
94
|
+
intent = win.setTimeout(() => prefetch(url), delay);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Back/forward. The router's own entries name the document they show; any other entry (an app's
|
|
99
|
+
* own `pushState`) shows the document of its PATH. Either way, when that is not the document on
|
|
100
|
+
* screen it is fetched; when it is, only the scroll moves — the app keeps its own history.
|
|
101
|
+
*/
|
|
102
|
+
const onPop = (event: PopStateEvent): void => {
|
|
103
|
+
scroll.cancel();
|
|
104
|
+
popped();
|
|
105
|
+
// The page is the PATH: a modal's hash is the modal's (`reconcile`), never the page's fragment.
|
|
106
|
+
const at = win.location.href;
|
|
107
|
+
const url = modalAddress(new URL(at).hash, at) === null ? at : withoutFragment(at);
|
|
108
|
+
const entry = entryOf(event.state);
|
|
109
|
+
const wanted = entry?.doc ?? withoutFragment(url);
|
|
110
|
+
const same =
|
|
111
|
+
entry !== undefined
|
|
112
|
+
? wanted === rendered()
|
|
113
|
+
: new URL(url).pathname === new URL(rendered()).pathname;
|
|
114
|
+
if (!same) {
|
|
115
|
+
void navigate(url, { history: 'none' });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (entry !== undefined) {
|
|
119
|
+
win.scrollTo({
|
|
120
|
+
left: entry.scroll[0],
|
|
121
|
+
top: entry.scroll[1],
|
|
122
|
+
behavior: 'instant' as ScrollBehavior,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
reconcile();
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// `window`, bubble phase: after every handler on the page — Solid delegates to `document` — has
|
|
129
|
+
// had its chance to `preventDefault`, which the rules then honour.
|
|
130
|
+
const passive = { passive: true };
|
|
131
|
+
const pressing = { capture: true, passive: true };
|
|
132
|
+
const listeners: readonly (readonly [EventTarget, string, EventListener, object?])[] = [
|
|
133
|
+
[win, 'click', onClick as EventListener],
|
|
134
|
+
[win, 'submit', onSubmit as EventListener],
|
|
135
|
+
[doc, 'pointerover', onIntent, passive],
|
|
136
|
+
[doc, 'pointerout', cancelIntent, passive],
|
|
137
|
+
[doc, 'focusin', onIntent],
|
|
138
|
+
[doc, 'touchstart', onIntent, passive],
|
|
139
|
+
[win, 'popstate', onPop as EventListener],
|
|
140
|
+
[win, 'hashchange', reconcile],
|
|
141
|
+
[doc, 'pointerdown', onPress, pressing],
|
|
142
|
+
[doc, 'pointerup', press.onRelease, pressing],
|
|
143
|
+
[doc, 'pointercancel', press.onRelease, pressing],
|
|
144
|
+
];
|
|
145
|
+
for (const [target, type, listener, options] of listeners) {
|
|
146
|
+
target.addEventListener(type, listener, options);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return [
|
|
150
|
+
cancelIntent,
|
|
151
|
+
() => {
|
|
152
|
+
for (const [target, type, listener, options] of listeners) {
|
|
153
|
+
target.removeEventListener(type, listener, options);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
];
|
|
157
|
+
}
|
package/src/navigation.ts
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
import { navigationCache } from './navigation-cache';
|
|
19
19
|
import { withinDeadline } from './navigation-deadline';
|
|
20
|
-
import {
|
|
20
|
+
import { announcer, handOver } from './navigation-dom';
|
|
21
21
|
import {
|
|
22
22
|
type Answer,
|
|
23
23
|
fetchDocument,
|
|
@@ -25,13 +25,8 @@ import {
|
|
|
25
25
|
metaOf,
|
|
26
26
|
responseFactsOf,
|
|
27
27
|
} from './navigation-fetch';
|
|
28
|
-
import {
|
|
29
|
-
|
|
30
|
-
entryOf,
|
|
31
|
-
STATE_KEY,
|
|
32
|
-
scrollAfter,
|
|
33
|
-
withoutFragment,
|
|
34
|
-
} from './navigation-history';
|
|
28
|
+
import { recordEntry, scrollAfter, withoutFragment } from './navigation-history';
|
|
29
|
+
import { interceptNavigation } from './navigation-intercept';
|
|
35
30
|
import { modalController } from './navigation-modal';
|
|
36
31
|
import { addressOf, modalAddress, modalHistory } from './navigation-modal-rules';
|
|
37
32
|
import { pressTracker } from './navigation-press';
|
|
@@ -45,15 +40,12 @@ import {
|
|
|
45
40
|
} from './navigation-refresh';
|
|
46
41
|
import {
|
|
47
42
|
answerMovesTab,
|
|
48
|
-
formVerdict,
|
|
49
|
-
linkVerdict,
|
|
50
43
|
NAVIGATE_EVENT,
|
|
51
44
|
NAVIGATED_EVENT,
|
|
52
45
|
NAVIGATING_ATTRIBUTE,
|
|
53
46
|
NAVIGATION_ERROR_EVENT,
|
|
54
47
|
NAVIGATION_MAX_HOPS,
|
|
55
48
|
NAVIGATION_META,
|
|
56
|
-
NAVIGATION_PREFETCH_DELAY_MS,
|
|
57
49
|
NAVIGATION_PROGRESS_DELAY_MS,
|
|
58
50
|
responseVerdict,
|
|
59
51
|
} from './navigation-rules';
|
|
@@ -120,8 +112,6 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
120
112
|
/** The URL a navigation in flight is fetching: a prefetch never asks for it a second time. */
|
|
121
113
|
let navigatingTo: string | undefined;
|
|
122
114
|
const press = pressTracker(doc);
|
|
123
|
-
/** The pending prefetch of a hover, cancelled by anything that navigates. */
|
|
124
|
-
let intent: number | undefined;
|
|
125
115
|
let untrusted = false;
|
|
126
116
|
let backing = false; // a Back this router started is traversing: the URL is still the one left
|
|
127
117
|
let inflight: AbortController | undefined;
|
|
@@ -200,7 +190,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
200
190
|
const mine = new AbortController();
|
|
201
191
|
inflight = mine;
|
|
202
192
|
modal.release();
|
|
203
|
-
|
|
193
|
+
cancelIntent();
|
|
204
194
|
navigatingTo = withoutFragment(url);
|
|
205
195
|
// A route the document names a modal opens NOW, in the click's own task; the answer fills it.
|
|
206
196
|
if (method === 'GET' && navigatingTo !== rendered) modal.loading(url);
|
|
@@ -298,12 +288,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
298
288
|
if (hold === undefined) live.textContent = '';
|
|
299
289
|
swapped.body.append(live);
|
|
300
290
|
rendered = withoutFragment(landed);
|
|
301
|
-
|
|
302
|
-
const same = landed === win.location.href || history === 'replace';
|
|
303
|
-
const state = { [STATE_KEY]: { scroll: [0, 0], doc: rendered } satisfies EntryState };
|
|
304
|
-
if (same) win.history.replaceState(state, '', landed);
|
|
305
|
-
else win.history.pushState(state, '', landed);
|
|
306
|
-
}
|
|
291
|
+
recordEntry(win, landed, rendered, history);
|
|
307
292
|
// Inside the swap, so a view transition's "after" frame is already where the page lands.
|
|
308
293
|
scrollAfter(win, doc, landed, history);
|
|
309
294
|
},
|
|
@@ -343,87 +328,6 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
343
328
|
}
|
|
344
329
|
};
|
|
345
330
|
|
|
346
|
-
const onPress = (): void => {
|
|
347
|
-
press.onPress();
|
|
348
|
-
// A press is not a hover: the click it becomes navigates, and a guess on its heels is a
|
|
349
|
-
// second request for the same page.
|
|
350
|
-
win.clearTimeout(intent);
|
|
351
|
-
};
|
|
352
|
-
|
|
353
|
-
const onClick = (event: MouseEvent): void => {
|
|
354
|
-
win.clearTimeout(intent);
|
|
355
|
-
if (press.overlayClick(event)) return;
|
|
356
|
-
const anchor = anchorOf(event.target);
|
|
357
|
-
if (anchor === null) return;
|
|
358
|
-
const verdict = linkVerdict(linkFacts(win, anchor, event));
|
|
359
|
-
if (verdict.kind !== 'soft') return;
|
|
360
|
-
event.preventDefault();
|
|
361
|
-
// A link to the page beneath an open modal (its Cancel) closes the modal: nothing is fetched.
|
|
362
|
-
if (modal.address !== undefined && withoutFragment(verdict.url) === rendered) modal.close();
|
|
363
|
-
else void navigate(verdict.url);
|
|
364
|
-
};
|
|
365
|
-
|
|
366
|
-
const onSubmit = (event: SubmitEvent): void => {
|
|
367
|
-
const form = event.target;
|
|
368
|
-
// An untrusted tab (`answerMovesTab`) leaves every form to the browser.
|
|
369
|
-
if (!(form instanceof HTMLFormElement) || untrusted) return;
|
|
370
|
-
const { facts, fields } = submitFacts(win, form, event.submitter, event.defaultPrevented);
|
|
371
|
-
const verdict = formVerdict(facts);
|
|
372
|
-
if (verdict.kind === 'native') return;
|
|
373
|
-
event.preventDefault();
|
|
374
|
-
if (verdict.kind === 'get') {
|
|
375
|
-
void navigate(verdict.url);
|
|
376
|
-
return;
|
|
377
|
-
}
|
|
378
|
-
const body =
|
|
379
|
-
verdict.encoding === 'multipart'
|
|
380
|
-
? fields
|
|
381
|
-
: new URLSearchParams(facts.fields.map(([name, value]) => [name, value]));
|
|
382
|
-
void navigate(verdict.url, { method: 'POST', body });
|
|
383
|
-
};
|
|
384
|
-
|
|
385
|
-
const onIntent = (event: Event): void => {
|
|
386
|
-
// The focus a press gives a link: its click is a moment away, and it navigates.
|
|
387
|
-
if (event.type === 'focusin' && press.pressed()) return;
|
|
388
|
-
const url = intentUrl(win, event.target);
|
|
389
|
-
if (url === undefined) return;
|
|
390
|
-
win.clearTimeout(intent);
|
|
391
|
-
const delay = event.type === 'pointerover' ? NAVIGATION_PREFETCH_DELAY_MS : 0;
|
|
392
|
-
intent = win.setTimeout(() => prefetch(url), delay);
|
|
393
|
-
};
|
|
394
|
-
const onLeave = (): void => win.clearTimeout(intent);
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* Back/forward. The router's own entries name the document they show; any other entry (an app's
|
|
398
|
-
* own `pushState`) shows the document of its PATH. Either way, when that is not the document on
|
|
399
|
-
* screen it is fetched; when it is, only the scroll moves — the app keeps its own history.
|
|
400
|
-
*/
|
|
401
|
-
const onPop = (event: PopStateEvent): void => {
|
|
402
|
-
scroll.cancel();
|
|
403
|
-
backing = false;
|
|
404
|
-
// The page is the PATH: a modal's hash is the modal's (`reconcile`), never the page's fragment.
|
|
405
|
-
const at = win.location.href;
|
|
406
|
-
const url = modalAddress(new URL(at).hash, at) === null ? at : withoutFragment(at);
|
|
407
|
-
const entry = entryOf(event.state);
|
|
408
|
-
const wanted = entry?.doc ?? withoutFragment(url);
|
|
409
|
-
const same =
|
|
410
|
-
entry !== undefined
|
|
411
|
-
? wanted === rendered
|
|
412
|
-
: new URL(url).pathname === new URL(rendered).pathname;
|
|
413
|
-
if (!same) {
|
|
414
|
-
void navigate(url, { history: 'none' });
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
if (entry !== undefined) {
|
|
418
|
-
win.scrollTo({
|
|
419
|
-
left: entry.scroll[0],
|
|
420
|
-
top: entry.scroll[1],
|
|
421
|
-
behavior: 'instant' as ScrollBehavior,
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
reconcile();
|
|
425
|
-
};
|
|
426
|
-
|
|
427
331
|
/**
|
|
428
332
|
* The modal follows the URL's hash, once the page on screen is the URL's: opened (fetched, as a
|
|
429
333
|
* hash address, so a stale one degrades), kept, or dismissed. On start, on Back/Forward, on a
|
|
@@ -441,26 +345,20 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
441
345
|
}
|
|
442
346
|
}
|
|
443
347
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
[doc, 'pointerup', press.onRelease, pressing],
|
|
459
|
-
[doc, 'pointercancel', press.onRelease, pressing],
|
|
460
|
-
];
|
|
461
|
-
for (const [target, type, listener, options] of listeners) {
|
|
462
|
-
target.addEventListener(type, listener, options);
|
|
463
|
-
}
|
|
348
|
+
const [cancelIntent, stopListening] = interceptNavigation(
|
|
349
|
+
win,
|
|
350
|
+
press,
|
|
351
|
+
modal,
|
|
352
|
+
scroll,
|
|
353
|
+
() => rendered,
|
|
354
|
+
() => untrusted,
|
|
355
|
+
navigate,
|
|
356
|
+
prefetch,
|
|
357
|
+
() => {
|
|
358
|
+
backing = false;
|
|
359
|
+
},
|
|
360
|
+
reconcile,
|
|
361
|
+
);
|
|
464
362
|
|
|
465
363
|
const router: NavigationRouter = {
|
|
466
364
|
navigate,
|
|
@@ -485,9 +383,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
|
|
|
485
383
|
},
|
|
486
384
|
closeModal: () => modal.close(),
|
|
487
385
|
stop() {
|
|
488
|
-
|
|
489
|
-
target.removeEventListener(type, listener, options);
|
|
490
|
-
}
|
|
386
|
+
stopListening();
|
|
491
387
|
modal.dismiss();
|
|
492
388
|
scroll.stop();
|
|
493
389
|
tabs.stop();
|
package/src/registry.ts
CHANGED
|
@@ -221,6 +221,8 @@ function toUrlSegment(segment: string): string {
|
|
|
221
221
|
}
|
|
222
222
|
|
|
223
223
|
const routes = new Map<string, RouteEntry>();
|
|
224
|
+
/** route file → its URL pattern: what `render.page` reports a component's render under. */
|
|
225
|
+
const patternsByFile = new Map<string, string>();
|
|
224
226
|
/**
|
|
225
227
|
* The config each path's module EXPORTED, before `withIslandBudget` may have copied it: a mount's
|
|
226
228
|
* `claimable` answers by identity, and the entry's own config is not always that object.
|
|
@@ -301,6 +303,7 @@ export function registerRoute<TData = RouteData>(
|
|
|
301
303
|
...(input.component === undefined ? {} : { component: input.component }),
|
|
302
304
|
};
|
|
303
305
|
routes.set(path, entry as RouteEntry);
|
|
306
|
+
patternsByFile.set(input.file, path);
|
|
304
307
|
declaredConfigs.set(path, input.config as RouteConfig);
|
|
305
308
|
described = undefined;
|
|
306
309
|
return entry;
|
|
@@ -350,6 +353,7 @@ export function registerMountedRoutes(
|
|
|
350
353
|
|
|
351
354
|
export function clearRoutes(): void {
|
|
352
355
|
routes.clear();
|
|
356
|
+
patternsByFile.clear();
|
|
353
357
|
declaredConfigs.clear();
|
|
354
358
|
clearMountedRoutes();
|
|
355
359
|
described = undefined;
|
|
@@ -369,6 +373,11 @@ export function routeFor(path: string): RouteEntry | undefined {
|
|
|
369
373
|
return routes.get(path);
|
|
370
374
|
}
|
|
371
375
|
|
|
376
|
+
/** The URL pattern a registered route FILE serves (`/blog/:slug`), or `undefined` for none. */
|
|
377
|
+
export function routePatternOfFile(file: string): string | undefined {
|
|
378
|
+
return patternsByFile.get(file);
|
|
379
|
+
}
|
|
380
|
+
|
|
372
381
|
/**
|
|
373
382
|
* The manifest projection: JSON-safe, sorted by path, identical for identical input.
|
|
374
383
|
* Determinism matters because `sw.js` and the sitemap are diffed across deploys.
|
package/src/render-html.ts
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Rendering a component tree: the options one render carries, its hole sink, and the two entry
|
|
3
|
+
* points. Every render mode gets the same markup from the same component — `static` at build
|
|
4
|
+
* time, `ssr`/`stream` per request — because all of them come through `renderToHtml`.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import { renderFixShellArg, renderThrowable } from '@ultimat3/core';
|
|
8
8
|
import {
|
|
9
9
|
IslandInvalidError,
|
|
10
10
|
IslandNotHydratedError,
|
|
11
11
|
IslandPropsInvalidError,
|
|
12
12
|
PrerenderFailedError,
|
|
13
13
|
} from './errors';
|
|
14
|
-
import type { HoleNode } from './hole';
|
|
15
|
-
import { isHoleNode } from './hole';
|
|
16
|
-
import { renderAttributes, VOID_ELEMENTS } from './html';
|
|
17
|
-
import { emitIslandAttributes, emitIslandProps } from './hydrate';
|
|
18
|
-
import type { IslandNode } from './island';
|
|
19
|
-
import { isIslandNode } from './island';
|
|
20
14
|
import type { IslandCollector } from './island-collector';
|
|
21
|
-
import { islandWithoutCollector } from './island-collector';
|
|
22
15
|
import type { JsxComponent, JsxProps } from './jsx';
|
|
23
|
-
import {
|
|
16
|
+
import { instrumentedHoles, routeOfFile, timedRender } from './render-instrument';
|
|
24
17
|
import type { StreamHole } from './render-stream';
|
|
25
|
-
import {
|
|
18
|
+
import { renderAlone } from './render-walk';
|
|
26
19
|
|
|
27
20
|
/**
|
|
28
21
|
* The id of the element every document wraps its route component in — one name, because a service
|
|
@@ -31,23 +24,6 @@ import { holeMarker } from './render-stream';
|
|
|
31
24
|
*/
|
|
32
25
|
export const ROOT_ELEMENT_ID = 'x-root';
|
|
33
26
|
|
|
34
|
-
/** Depth is bounded so a component that renders itself fails with a cause instead of a stack trace. */
|
|
35
|
-
const MAX_DEPTH = 500;
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Asserted at the top of `unwrap`, not only in `renderNode`. The element path was the only one
|
|
39
|
-
* bounded, and it is not the only one that recurses: `unwrap` walks arrays and calls thunks, both
|
|
40
|
-
* of which a component's `children` routinely are, so a self-referencing array or a self-returning
|
|
41
|
-
* accessor escaped `renderToHtml` as a bare `RangeError` — no code, no `fix:`, nothing to catch by.
|
|
42
|
-
*/
|
|
43
|
-
function assertDepth(depth: number): void {
|
|
44
|
-
if (depth <= MAX_DEPTH) return;
|
|
45
|
-
throw new PrerenderFailedError(
|
|
46
|
-
`component tree exceeded ${MAX_DEPTH} levels, so it renders itself`,
|
|
47
|
-
'remove the self-reference from the component that renders its own tag',
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
27
|
/**
|
|
52
28
|
* What the walk carries besides depth. One object per render, never module-global: two concurrent
|
|
53
29
|
* requests render different params, and a shared collector would bill one page for the other's JS.
|
|
@@ -99,140 +75,15 @@ export function holeSink(options: HoleSinkOptions = {}): HoleSink {
|
|
|
99
75
|
}
|
|
100
76
|
|
|
101
77
|
/**
|
|
102
|
-
*
|
|
103
|
-
* `
|
|
104
|
-
*
|
|
105
|
-
* Which is also why the depth bound belongs HERE and not only on the element path: the array and
|
|
106
|
-
* thunk branches below recurse, and both are ordinary shapes for a component's children.
|
|
107
|
-
*/
|
|
108
|
-
async function unwrap(value: unknown, depth: number, walk: RenderHtmlOptions): Promise<string> {
|
|
109
|
-
assertDepth(depth);
|
|
110
|
-
if (value === null || value === undefined || value === false || value === true) return '';
|
|
111
|
-
if (typeof value === 'string') return escapeHtml(value);
|
|
112
|
-
if (typeof value === 'number' || typeof value === 'bigint') return escapeHtml(String(value));
|
|
113
|
-
if (value instanceof Promise) return unwrap(await value, depth, walk);
|
|
114
|
-
// Before the array branch, never after: an island node IS an array — the only object shape the
|
|
115
|
-
// configured `JSX.Element` admits — so the generic branch would render its empty contents and
|
|
116
|
-
// drop the island, its props script and its budget line without a word.
|
|
117
|
-
if (isIslandNode(value)) return renderIsland(value, depth, walk);
|
|
118
|
-
if (isHoleNode(value)) return renderHole(value, depth, walk);
|
|
119
|
-
if (Array.isArray(value)) {
|
|
120
|
-
const parts = await Promise.all(value.map((item) => unwrap(item, depth + 1, walk)));
|
|
121
|
-
return parts.join('');
|
|
122
|
-
}
|
|
123
|
-
if (isJsxNode(value)) return renderNode(value.type, value.props, depth, walk);
|
|
124
|
-
if (typeof value === 'function') return unwrap((value as () => unknown)(), depth + 1, walk);
|
|
125
|
-
return escapeHtml(String(value));
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* `innerHTML` is the one escape hatch that emits unescaped markup, and it is deliberate: the
|
|
130
|
-
* `<head>` renderers and the streaming reveal chunks are already-serialized HTML, and re-escaping
|
|
131
|
-
* them would print the tags. Nothing else in this file trusts a string.
|
|
132
|
-
*/
|
|
133
|
-
async function renderElement(
|
|
134
|
-
tag: string,
|
|
135
|
-
props: JsxProps,
|
|
136
|
-
depth: number,
|
|
137
|
-
walk: RenderHtmlOptions,
|
|
138
|
-
): Promise<string> {
|
|
139
|
-
const open = `<${tag}${renderAttributes(props)}>`;
|
|
140
|
-
if (VOID_ELEMENTS.has(tag)) return open;
|
|
141
|
-
const raw = (props as { innerHTML?: unknown }).innerHTML;
|
|
142
|
-
const inner =
|
|
143
|
-
raw === undefined || raw === null
|
|
144
|
-
? await unwrap((props as { children?: unknown }).children, depth + 1, walk)
|
|
145
|
-
: String(raw);
|
|
146
|
-
return `${open}${inner}</${tag}>`;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* An island renders its SHELL on the server — the children the page wrote — and nothing of the
|
|
151
|
-
* client module: the specifier is data, so there is no import to follow and the static page's
|
|
152
|
-
* bundle graph never grows. The props script travels inside the wrapper so a document assembler
|
|
153
|
-
* has exactly one thing left to remember, the runtime.
|
|
154
|
-
*/
|
|
155
|
-
async function renderIsland(
|
|
156
|
-
node: IslandNode,
|
|
157
|
-
depth: number,
|
|
158
|
-
walk: RenderHtmlOptions,
|
|
159
|
-
): Promise<string> {
|
|
160
|
-
const collector = walk.islands;
|
|
161
|
-
if (collector === undefined) throw islandWithoutCollector(node.spec);
|
|
162
|
-
const directive = collector.record(node.spec, node.props);
|
|
163
|
-
const shell = await unwrap((node.props as { children?: unknown }).children, depth + 1, walk);
|
|
164
|
-
const tag = node.spec.tag;
|
|
165
|
-
return `<${tag} ${emitIslandAttributes(directive)}>${shell}${emitIslandProps(directive)}</${tag}>`;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* A promise already running when the tree was built is awaited only once the stream starts, after
|
|
170
|
-
* the fallback rendered; a rejection before then is unhandled. Marked through arrays and JSX
|
|
171
|
-
* children — never by calling a thunk or a component, which have not run — and the hole still
|
|
172
|
-
* awaits and sees it. `seen` stops a self-referencing array.
|
|
173
|
-
*/
|
|
174
|
-
function observeEagerPromises(value: unknown, seen: Set<object>): void {
|
|
175
|
-
if (value instanceof Promise) {
|
|
176
|
-
value.catch(() => undefined);
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (typeof value !== 'object' || value === null || seen.has(value)) return;
|
|
180
|
-
seen.add(value);
|
|
181
|
-
if (Array.isArray(value)) for (const item of value) observeEagerPromises(item, seen);
|
|
182
|
-
// An island or hole node is an array whose own items are empty: its tree is in `props`.
|
|
183
|
-
if (isJsxNode(value) || isIslandNode(value) || isHoleNode(value)) {
|
|
184
|
-
const props = value.props as { children?: unknown; fallback?: unknown; error?: unknown };
|
|
185
|
-
observeEagerPromises(props.children, seen);
|
|
186
|
-
observeEagerPromises(props.fallback, seen);
|
|
187
|
-
observeEagerPromises(props.error, seen);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/**
|
|
192
|
-
* Everything under a hole walks with no sink: a nested hole is inline inside the outer one, since
|
|
193
|
-
* the set of pending holes is fixed at the first flush (`renderStreamHtml`). `resolve` is a thunk,
|
|
194
|
-
* so `children` start inside `start()`, in the request's async context, after the shell is out.
|
|
195
|
-
*/
|
|
196
|
-
async function renderHole(node: HoleNode, depth: number, walk: RenderHtmlOptions): Promise<string> {
|
|
197
|
-
const sink = walk.holes;
|
|
198
|
-
const inner: RenderHtmlOptions = walk.islands === undefined ? {} : { islands: walk.islands };
|
|
199
|
-
const { children, error, fallback } = node.props;
|
|
200
|
-
if (sink === undefined) return unwrap(children, depth + 1, inner);
|
|
201
|
-
const id = sink.nextId();
|
|
202
|
-
observeEagerPromises(children, new Set());
|
|
203
|
-
const [shown, failed] = await Promise.all([
|
|
204
|
-
unwrap(fallback, depth + 1, inner),
|
|
205
|
-
error === undefined ? undefined : unwrap(error, depth + 1, inner),
|
|
206
|
-
]);
|
|
207
|
-
sink.add({
|
|
208
|
-
id,
|
|
209
|
-
fallback: shown,
|
|
210
|
-
...(failed === undefined ? {} : { error: failed }),
|
|
211
|
-
resolve: (signal) => sink.enter(signal, () => unwrap(children, depth + 1, inner)),
|
|
212
|
-
});
|
|
213
|
-
return holeMarker(id, shown);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async function renderNode(
|
|
217
|
-
type: string | JsxComponent,
|
|
218
|
-
props: JsxProps,
|
|
219
|
-
depth: number,
|
|
220
|
-
walk: RenderHtmlOptions,
|
|
221
|
-
): Promise<string> {
|
|
222
|
-
assertDepth(depth);
|
|
223
|
-
if (typeof type === 'string') return renderElement(type, props, depth, walk);
|
|
224
|
-
return unwrap(type(props), depth + 1, walk);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Render a component tree to HTML. Async throughout so a component may await its own data — the
|
|
229
|
-
* `ssr` mode's whole point — without a second sync renderer existing beside this one.
|
|
78
|
+
* Render a component tree to HTML. Always a promise so a component may await its own data — the
|
|
79
|
+
* `ssr` mode's whole point — while the walk itself (`render-walk.ts`) stays synchronous until the
|
|
80
|
+
* tree holds something to await: one walker, never a second sync renderer beside it.
|
|
230
81
|
*/
|
|
231
82
|
export async function renderToHtml(
|
|
232
83
|
node: unknown,
|
|
233
84
|
options: RenderHtmlOptions = {},
|
|
234
85
|
): Promise<string> {
|
|
235
|
-
return
|
|
86
|
+
return renderAlone(node, 0, options);
|
|
236
87
|
}
|
|
237
88
|
|
|
238
89
|
/**
|
|
@@ -244,6 +95,21 @@ export async function renderComponent(
|
|
|
244
95
|
props: JsxProps,
|
|
245
96
|
file: string,
|
|
246
97
|
options: RenderHtmlOptions = {},
|
|
98
|
+
): Promise<string> {
|
|
99
|
+
// Reported AS the caller sees it: the coded failure below, never the raw throw it wraps.
|
|
100
|
+
const route = routeOfFile(file);
|
|
101
|
+
const walk =
|
|
102
|
+
options.holes === undefined
|
|
103
|
+
? options
|
|
104
|
+
: { ...options, holes: instrumentedHoles(options.holes, route) };
|
|
105
|
+
return timedRender('render.page', { route }, () => renderPage(component, props, file, walk));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function renderPage(
|
|
109
|
+
component: JsxComponent,
|
|
110
|
+
props: JsxProps,
|
|
111
|
+
file: string,
|
|
112
|
+
options: RenderHtmlOptions,
|
|
247
113
|
): Promise<string> {
|
|
248
114
|
try {
|
|
249
115
|
return await renderToHtml(component(props), options);
|