@ultimat3/render 31.48.0 → 31.50.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 CHANGED
@@ -61,9 +61,9 @@ axiom 6). Never `cli` (upward).
61
61
  | A byte count in a message | `formatBytes` from `@ultimat3/core`, never a local one. |
62
62
  | Island bytes | **not this package's**: `@ultimat3/cli`'s `packages/cli/src/budgets.ts` measures the EMITTED document and is the gate. What stays here is the budget grammar (`parseByteBudget`) and `defaultIslandBudget`. |
63
63
  | The hydration runtime's CSP | `HYDRATE_RUNTIME_BODIES` — every inline body `hydrateRuntime` can emit, hashed by `@ultimat3/cli`'s `script-csp.ts`; `runtimeBody` is the one string served and hashed † |
64
- | Island markup | the props `<script>` is emitted INSIDE the wrapper by `render-walk.ts`; an assembler only adds `hydrateRuntime(directives)`. |
64
+ | Island markup | the props `<script>` is emitted INSIDE the wrapper by `render-walk.ts`; an assembler only adds `hydrateRuntime(directives)`. `boot` reads `:scope>script[data-x-props]` first — an id repeats per render (page under a modal) — and by id only a script in no island's wrapper. |
65
65
  | Island boot | `el.__x` holds the boot PROMISE, never a boolean. |
66
- | Island mount markers | `data-x-mounted=""` when `mount()` resolved, `data-x-failed="<message>"` when it rejected — set by the runtime, never by `emitIslandAttributes`. The rejection handler RETHROWS. Prelude sizes `As of 2026-10-05`: `idle` 1,843, `visible` 886, `interaction` 1,728 B (what `DEFAULT_ISLAND_JS_BYTES` derives from). |
66
+ | Island mount markers | `data-x-mounted=""` when `mount()` resolved, `data-x-failed="<message>"` when it rejected — set by the runtime, never by `emitIslandAttributes`. The rejection handler RETHROWS. Prelude sizes `As of 2026-11-19`: `idle` 1,943, `visible` 986, `interaction` 1,828 B (what `DEFAULT_ISLAND_JS_BYTES` derives from). |
67
67
  | A runtime that calls `boot` | TERMINATES the chain: `idle`/`visible` end in `.catch(hush)`, `interaction` passes `off` as the rejection arm. `hydrate-runtime.test.ts` reds on an unhandled rejection. |
68
68
  | `idle` replays too | `idle` and `interaction` share ONE `catchUp(el)` in `hydrate.ts` (capture listeners for `data-x-events`, default `click`; a queue; `aim`; one flush). A caught event wakes an `idle` island early; each event replays once. `hydrate-replay.test.ts`. |
69
69
  | Where `interaction` replays | `aim(el, ev)`, never `ev.target` (`mount` detaches the pressed node). Fallback order: `docs/history/render.md`. `hydrate-replay.test.ts`. |
package/README.md CHANGED
@@ -236,7 +236,8 @@ From code — an island, an app script — `navigate(url, { replace? })`, `refre
236
236
  `openModal(path)` and `closeModal()` go through the router when the page has one and fall back to
237
237
  `location.assign`/`replace`/`reload` when it does not; they import the router's type only. An
238
238
  island imports them from **`@ultimat3/render/client`**, never the barrel — see
239
- [Two entry points](#two-entry-points). [Navigating from code](../../wiki/Client-Navigation.md#navigating-from-code).
239
+ [Two entry points](#two-entry-points). `navigate()` to a fragment of the page on screen (`#top`,
240
+ same path and query) is the browser's scroll, as a click on that link is: no fetch, no swap. [Navigating from code](../../wiki/Client-Navigation.md#navigating-from-code).
240
241
 
241
242
  `refresh()` is the same page for the same visitor (`navigation-refresh.ts`): no view transition,
242
243
  focus kept on the control the visitor was in (`markFocus`/`restoreFocus` in `navigation-dom.ts`: by
@@ -744,7 +745,9 @@ a job boundary the class is gone and the `code` is what survives — match on th
744
745
  the route's `revalidate.tags` — `revalidate: { tags: [tag.post] }` answers `post e:post` — on a
745
746
  miss, a hit and a served-stale response alike. That is what lets the same `invalidates` purge
746
747
  the document at the CDN; before it, the edge held every ISR page for its whole `s-maxage`. A
747
- TTL-only route carries neither header. A tag a CDN would split (whitespace, a comma) is refused
748
+ served-stale response is never leased to a shared cache (`public, max-age=0, s-maxage=0`, no
749
+ `stale-while-revalidate`): nothing purges the edge again when the regeneration lands, so a lease
750
+ would undo the purge for the route's whole `ttl`. A TTL-only route carries neither header. A tag a CDN would split (whitespace, a comma) is refused
748
751
  when the route registers — `X_ROUTE_MODE_INVALID`, naming the file — for file routes and
749
752
  mounted routes both.
750
753
  - **`stream`** flushes the shell first, then reveals holes in completion order with a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/render",
3
- "version": "31.48.0",
3
+ "version": "31.50.0",
4
4
  "description": "The route primitive and the five render modes: static, isr, ssr, stream, spa.",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,12 +52,12 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/cache": "31.48.0",
56
- "@ultimat3/core": "31.48.0",
57
- "@ultimat3/http": "31.48.0",
58
- "@ultimat3/i18n": "31.48.0",
59
- "@ultimat3/schema": "31.48.0",
60
- "@ultimat3/seo": "31.48.0",
61
- "sass": "1.107.1"
55
+ "@ultimat3/cache": "31.50.0",
56
+ "@ultimat3/core": "31.50.0",
57
+ "@ultimat3/http": "31.50.0",
58
+ "@ultimat3/i18n": "31.50.0",
59
+ "@ultimat3/schema": "31.50.0",
60
+ "@ultimat3/seo": "31.50.0",
61
+ "sass": "1.108.1"
62
62
  }
63
63
  }
package/src/asset.ts CHANGED
@@ -100,14 +100,14 @@ export function asset(path: AssetPath): string {
100
100
  if (problem !== undefined) {
101
101
  throw new AssetMissingError(
102
102
  `asset(${renderCauseValue(path)}): ${problem}`,
103
- `asset('logo.svg') // a file under apps/web/site/${ASSET_DIR}/ with one of: ${ASSET_EXTENSIONS.join(', ')}`,
103
+ `asset('${ASSET_DIR}/logo.svg') // a file under apps/web/site/${ASSET_DIR}/ with one of: ${ASSET_EXTENSIONS.join(', ')}`,
104
104
  );
105
105
  }
106
106
  const resolver = holder[RESOLVER_SLOT];
107
107
  if (resolver === undefined) {
108
108
  throw new AssetMissingError(
109
109
  `asset(${renderCauseValue(path)}) ran with no site asset table installed — in a browser (an island), or in a test that never loaded the app`,
110
- 'asset(path) // in the page, the URL passed to the island as a prop; a unit test installs a table with setAssetResolver((path) => "/" + path)',
110
+ 'asset(path) // in the page, the URL passed to the island as a prop; a test run from the app root gets the app\'s table from @ultimat3/testing/preload, any other installs one with setAssetResolver((path) => "/" + path)',
111
111
  );
112
112
  }
113
113
  return resolver(path);
package/src/errors.ts CHANGED
@@ -54,7 +54,7 @@ export const RENDER_ERROR_TITLES: Readonly<Record<RenderErrorCode, string>> = {
54
54
  X_ASSET_MISSING: 'a page names a site asset the app does not have',
55
55
  X_ROUTE_POST_INVALID: "a page route's post binding cannot be mounted",
56
56
  X_ROUTE_NAVIGATION_INVALID:
57
- "a route's navigation is not 'prefetch', 'document', 'modal' or { modal: true, prefetch: 'intent' }, or its surface has no client navigation",
57
+ "a route's navigation is not 'prefetch', 'document', 'modal' or { modal: true, prefetch: 'intent' }, or is a mode other than 'document' on a surface with no client navigation",
58
58
  X_NAVIGATION_MODAL_PATH_INVALID:
59
59
  'openModal was given something that is not a path of this origin',
60
60
  };
@@ -209,7 +209,7 @@ export class RoutePostInvalidError extends UltimateError {
209
209
  /**
210
210
  * `defineRoute({ navigation })` that says nothing a process can honour: a value other than
211
211
  * `'prefetch'`, `'document'`, `'modal'` or `{ modal: true, prefetch: 'intent' }`, or — at boot — a
212
- * page whose surface has no client navigation.
212
+ * mode other than `'document'` on a page whose surface has no client navigation.
213
213
  */
214
214
  export class RouteNavigationInvalidError extends UltimateError {
215
215
  static readonly code = 'X_ROUTE_NAVIGATION_INVALID' as const;
@@ -217,7 +217,7 @@ export class RouteNavigationInvalidError extends UltimateError {
217
217
  super({
218
218
  code: RouteNavigationInvalidError.code,
219
219
  cause,
220
- fix: "defineRoute({ ..., navigation: 'prefetch' | 'document' | 'modal' | { modal: true, prefetch: 'intent' } }) on a page whose surface is listed in app.config.ts navigation.client, or remove the key",
220
+ fix: "defineRoute({ ..., navigation: 'prefetch' | 'document' | 'modal' | { modal: true, prefetch: 'intent' } }) on a page whose surface is listed in app.config.ts navigation.client — navigation: 'document' needs no router and boots on any surface — or remove the key",
221
221
  });
222
222
  }
223
223
  }
package/src/head.ts CHANGED
@@ -13,7 +13,7 @@ import { BudgetExceededError } from './errors';
13
13
  // The raw-text escapers are `html.ts`'s and the text/attribute table is core's `escapeHtml` — a
14
14
  // second one is how a character ends up missing.
15
15
  import { headAttributes } from './head-attributes';
16
- import { escapeJsonContent, escapeRawTextContent } from './html';
16
+ import { carriesJson, escapeJsonContent, escapeRawTextContent } from './html';
17
17
 
18
18
  export type HeadTagKind = 'title' | 'base' | 'meta' | 'link' | 'script' | 'style';
19
19
 
@@ -132,23 +132,7 @@ function renderTag(tag: HeadTag): string {
132
132
  */
133
133
  function contentOf(tag: HeadTag, raw: string): string {
134
134
  if (tag.kind !== 'script' && tag.kind !== 'style') return escapeHtml(raw);
135
- return carriesJson(tag) ? escapeJsonContent(raw) : escapeRawTextContent(raw);
136
- }
137
-
138
- /**
139
- * `application/ld+json`, `application/json`, any `…+json`: the body is data, not code.
140
- *
141
- * The MIME parameter is cut before the suffix test, because a real document writes
142
- * `type="application/ld+json; charset=utf-8"` and that does not end in `json` — so the block built
143
- * from route data, which is the path attacker text takes, silently took the raw-text escaper
144
- * instead of the total one. `</` is escaped either way, so this was a weakened boundary rather than
145
- * a break-out; the JSON rule is total on purpose, and a `charset` is not a reason to leave it.
146
- */
147
- function carriesJson(tag: HeadTag): boolean {
148
- const declared = tag.attrs?.['type'];
149
- if (typeof declared !== 'string') return false;
150
- const [type = ''] = declared.split(';');
151
- return type.trim().toLowerCase().endsWith('json');
135
+ return carriesJson(tag.attrs?.['type']) ? escapeJsonContent(raw) : escapeRawTextContent(raw);
152
136
  }
153
137
 
154
138
  export type ThemeFallback = 'light' | 'dark' | 'system';
package/src/html.ts CHANGED
@@ -61,6 +61,21 @@ export function escapeJsonContent(json: string): string {
61
61
  .replaceAll('\u2029', '\\u2029');
62
62
  }
63
63
 
64
+ /**
65
+ * `application/ld+json`, `application/json`, any `…+json`: the body is data, not code.
66
+ *
67
+ * The MIME parameter is cut before the suffix test, because a real document writes
68
+ * `type="application/ld+json; charset=utf-8"` and that does not end in `json` — so the block built
69
+ * from route data, which is the path attacker text takes, silently took the raw-text escaper
70
+ * instead of the total one. `</` is escaped either way, so this was a weakened boundary rather than
71
+ * a break-out; the JSON rule is total on purpose, and a `charset` is not a reason to leave it.
72
+ */
73
+ export function carriesJson(declared: unknown): boolean {
74
+ if (typeof declared !== 'string') return false;
75
+ const [type = ''] = declared.split(';');
76
+ return type.trim().toLowerCase().endsWith('json');
77
+ }
78
+
64
79
  /**
65
80
  * JSX prop name → attribute name. Solid authors write the HTML spelling (`class`, `for`), but the
66
81
  * React spellings compile too, and an author who writes one and gets no attribute has a bug with
package/src/hydrate.ts CHANGED
@@ -126,13 +126,20 @@ export function requiredStrategies(
126
126
  // runtime below would then flush its replay queue into an island that never mounted — the bug
127
127
  // `el.__x`-as-a-promise was introduced to fix, reintroduced one layer further out.
128
128
  //
129
+ // The props are the script INSIDE this wrapper (`render-walk.ts` emits it as a child), never the
130
+ // first one in the document carrying the id: an id is `<moduleId>-<instance>` per RENDER, so the
131
+ // page under a modal and the modal's document both hold `like-1`, and so does an island carried
132
+ // across a swap (`data-x-persist`). A script loose in the document — a hand-assembled page —
133
+ // is still read by id, and one that sits in another island's wrapper is that island's.
134
+ //
129
135
  // `el.__x` resolves to whatever `mount()` returned. An island's `mount` may return `() => void`,
130
136
  // its disposer (Solid's `render` answers one); the runtime keeps it there and
131
137
  // `@ultimat3/testing`'s `mountIsland` calls it on dispose. Nothing here ever calls it.
132
138
  const RUNTIME_PRELUDE = `
133
139
  function boot(el){var e=el.getAttribute('data-x-entry');
134
140
  if(!e)return Promise.resolve();if(el.__x)return el.__x;
135
- var p=document.querySelector('script[data-x-props="'+el.getAttribute('data-x-island')+'"]');
141
+ var p=el.querySelector(':scope>script[data-x-props]');
142
+ if(!p){p=document.querySelector('script[data-x-props="'+el.getAttribute('data-x-island')+'"]');if(p&&p.closest('[data-x-island]'))p=null}
136
143
  var props=p?JSON.parse(p.textContent||'{}'):{};
137
144
  return el.__x=import(e).then(function(m){return m.mount(el,props)}).then(
138
145
  function(r){el.setAttribute('${ISLAND_MOUNTED_ATTRIBUTE}','');return r},
package/src/modes.ts CHANGED
@@ -244,7 +244,7 @@ export function defaultHydrate(surface: Surface): HydrateStrategy {
244
244
  * runtimes an island gets unasked; `DEFAULT_ISLAND_HYDRATE`'s `'interaction'` is 1,669) =
245
245
  * **19,581**. That is the worst case an app reaches without writing a number down. 20,480 is the
246
246
  * next whole kilobyte above it, leaving 899 B of headroom and still under 2x 19,581, so a route
247
- * bundling the same island twice is refused. `island-budget.test.ts` asserts all three. `visible` costs 886, so an island route
247
+ * bundling the same island twice is refused. `island-budget.test.ts` asserts all three. `visible` costs 986, so an island route
248
248
  * that declares it pays less; the default is what the budget has to clear.
249
249
  *
250
250
  * All three grew by 129 B on 2026-08-21 (from 881 / 615 / 687), when the prelude learned to mark a
@@ -257,7 +257,9 @@ export function defaultHydrate(surface: Surface): HydrateStrategy {
257
257
  * shared `catchUp`, and both learned to aim a keyboard press by the pressed node's path (774 -> 1,744;
258
258
  * `interaction` 1,251 -> 1,629), and `idle` became the worst case. The
259
259
  * headroom absorbed all four and the conclusion is unchanged, which is the point of stating the
260
- * arithmetic here rather than the answer alone. It is not
260
+ * arithmetic here rather than the answer alone. As of 2026-11-19 `idle` is 1,943 (+59 B on
261
+ * 2026-10-05, a held island's listeners; +100 B in the shared prelude, `boot` reading the props
262
+ * script inside its own wrapper): 17,797 + 1,943 = 19,740, 740 B under the default. It is not
261
263
  * derived from Solid's own size on purpose — this package may not import or name `solid-js`
262
264
  * (`CLAUDE.md`), so a constant tracking the runtime's version would be a dependency in a comment.
263
265
  *
@@ -29,14 +29,21 @@ const page = (): NavigationWindow | undefined =>
29
29
  /**
30
30
  * Go to `url` (resolved against the page) as a click on a link to it would: through the router on
31
31
  * this origin — its own rules and the server's gate decide swap, modal or full load — and as a
32
- * document load anywhere else, or when the page has no router.
32
+ * document load anywhere else, or when the page has no router. A fragment of the page on screen
33
+ * (`#top`, same path and query) is the browser's: it scrolls, nothing is fetched or swapped.
33
34
  */
34
35
  export function navigate(url: string, options: NavigateToOptions = {}): Promise<void> {
35
36
  const win = page();
36
37
  if (win === undefined) return Promise.resolve();
37
- const to = new URL(url, win.location.href);
38
+ const from = new URL(win.location.href);
39
+ const to = new URL(url, from);
38
40
  const router = win.__xNavigation;
39
- if (router === undefined || to.origin !== new URL(win.location.href).origin) {
41
+ // The link rule (`linkVerdict`'s `hashOnly`), asked here because the router's `navigate` is
42
+ // reached past it: a fragment of the page on screen is the browser's scroll, and a fetch plus a
43
+ // swap for it disposes every island on the page.
44
+ const fragmentOnly =
45
+ to.href.includes('#') && to.pathname === from.pathname && to.search === from.search;
46
+ if (router === undefined || to.origin !== from.origin || fragmentOnly) {
40
47
  if (options.replace === true) win.location.replace(to.href);
41
48
  else win.location.assign(to.href);
42
49
  return Promise.resolve();
@@ -4,8 +4,9 @@
4
4
  *
5
5
  * The headers: purpose, the document's `<app>:<surface>`, its principal, its build on a GET.
6
6
  * `redirect: 'manual'` so no redirect is followed behind the router's back; `cache: 'no-cache'` so
7
- * the browser's HTTP cache never answers. The `Answer` is the page's text, or a non-page's bytes to
8
- * hand over (a prefetch's are dropped unread).
7
+ * the browser's HTTP cache never answers. The `Answer` is the page's text (a soft visit's streamed
8
+ * page: its shell, and the rest to read), or a non-page's bytes to hand over (a prefetch's are
9
+ * dropped unread).
9
10
  */
10
11
 
11
12
  import {
@@ -18,6 +19,7 @@ import {
18
19
  } from '@ultimat3/core/page';
19
20
  import type { NavigationCache } from './navigation-cache';
20
21
  import { NAVIGATION_META, type ResponseFacts, reusable } from './navigation-rules';
22
+ import { type PageRest, readShell } from './navigation-stream';
21
23
 
22
24
  /** One fetched answer, read once — a prefetch and the click after it share it. */
23
25
  export interface Answer {
@@ -28,6 +30,11 @@ export interface Answer {
28
30
  readonly contentType: string;
29
31
  readonly build: string | null;
30
32
  readonly html: string | null;
33
+ /**
34
+ * A soft visit's page that streams holes: `html` is its shell, and this the rest, read by the
35
+ * router once the shell is on screen. `null` for a page read whole (and every prefetch).
36
+ */
37
+ readonly rest: PageRest | null;
31
38
  readonly noStore: boolean;
32
39
  /** A non-page answer's bytes, kept to hand over — never for a prefetch. */
33
40
  readonly body: Blob | null;
@@ -68,7 +75,14 @@ export function fetchDocument(
68
75
  const contentType = response.headers.get('content-type') ?? '';
69
76
  const opaqueRedirect = response.type === 'opaqueredirect';
70
77
  const isHtml = /^\s*text\/html\b/i.test(contentType);
71
- const html = !opaqueRedirect && isHtml ? await response.text() : null;
78
+ // A prefetch is read whole: it is held for a click that may never come, and a held stream
79
+ // would keep its request open until its slowest hole closed.
80
+ const page =
81
+ opaqueRedirect || !isHtml
82
+ ? { html: null, rest: null }
83
+ : purpose === 'soft' && response.body !== null
84
+ ? await readShell(response.body)
85
+ : { html: await response.text(), rest: null };
72
86
  let body: Blob | null = null;
73
87
  if (!opaqueRedirect && !isHtml && response.status !== 204) {
74
88
  if (purpose === 'prefetch') await response.body?.cancel();
@@ -81,7 +95,8 @@ export function fetchDocument(
81
95
  location: location === null ? null : new URL(location, url).href,
82
96
  contentType,
83
97
  build: response.headers.get(CLIENT_BUILD_META),
84
- html,
98
+ html: page.html,
99
+ rest: page.rest,
85
100
  noStore: /\bno-store\b/i.test(response.headers.get('cache-control') ?? ''),
86
101
  body,
87
102
  disposition: response.headers.get('content-disposition') ?? '',
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { isJsonObject } from '@ultimat3/core/page';
9
+ import { decodeSegment } from './decode-segment';
9
10
 
10
11
  /** The router's own slot in `history.state`, beside whatever an app keeps there. */
11
12
  export const STATE_KEY = '__x';
@@ -66,8 +67,10 @@ export function recordEntry(win: Window, landed: string, doc: string, mode: Hist
66
67
  * `smooth`, and a new page is a new place, which a full load jumps to rather than glides to.
67
68
  */
68
69
  export function scrollAfter(win: Window, doc: Document, url: string, mode: HistoryMode): void {
69
- const hash = new URL(url).hash;
70
- const target = hash.length > 1 ? doc.getElementById(decodeURIComponent(hash.slice(1))) : null;
70
+ const raw = new URL(url).hash.slice(1);
71
+ // A malformed escape (`#50%`) is the raw id, as the browser's own fragment lookup reads it: a
72
+ // throw here is inside the swap, after the body was replaced and before any script ran.
73
+ const target = raw === '' ? null : doc.getElementById(decodeSegment(raw) ?? raw);
71
74
  const saved = entryOf(win.history.state);
72
75
  const to = (left: number, top: number): void =>
73
76
  win.scrollTo({ left, top, behavior: 'instant' as ScrollBehavior });
@@ -75,3 +78,42 @@ export function scrollAfter(win: Window, doc: Document, url: string, mode: Histo
75
78
  else if (target !== null) target.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
76
79
  else to(0, 0);
77
80
  }
81
+
82
+ /**
83
+ * `url` loaded for real. One that differs from the page on screen only by its fragment is reloaded:
84
+ * `assign` there is a same-document fragment navigation, which scrolls and leaves the page as it is.
85
+ * An empty fragment (`/a#`) is one too, though `URL.hash` reads it as none. Another fragment is
86
+ * pushed first, as `assign` would: a reload of the address bar's own would land on that anchor.
87
+ */
88
+ export function loadForReal(win: Window, url: string): void {
89
+ const here = win.location.href;
90
+ if (url.includes('#') && withoutFragment(url) === withoutFragment(here)) {
91
+ if (url !== here) win.history.pushState(null, '', url);
92
+ win.location.reload();
93
+ } else win.location.assign(url);
94
+ }
95
+
96
+ /**
97
+ * The fragment's element, scrolled to once a hole brings it — when the swap found none to scroll to
98
+ * and the visitor has not moved since: `true` once there is nothing left to wait for. Back/Forward
99
+ * restored a saved offset, which a late element never overrides.
100
+ */
101
+ export function lateFragment(
102
+ win: Window,
103
+ doc: Document,
104
+ url: string,
105
+ mode: HistoryMode,
106
+ ): (() => boolean) | undefined {
107
+ const raw = new URL(url).hash.slice(1);
108
+ if (raw === '' || mode === 'none') return undefined;
109
+ const id = decodeSegment(raw) ?? raw;
110
+ if (doc.getElementById(id) !== null) return undefined;
111
+ const at = [win.scrollX, win.scrollY, win.location.hash] as const;
112
+ return () => {
113
+ if (win.scrollX !== at[0] || win.scrollY !== at[1] || win.location.hash !== at[2]) return true;
114
+ const target = doc.getElementById(id);
115
+ if (target === null) return false;
116
+ target.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
117
+ return true;
118
+ };
119
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * A soft visit's page read as it arrives, so it paints before its slowest hole: the shell up to the
3
+ * server's first `STREAM_FLUSH_MARK`, then each hole's chunk as its mark lands, appended to the
4
+ * live body with its scripts run — the reveal a full load's parser runs. No mark: read whole.
5
+ */
6
+
7
+ import { runScripts } from './navigation-swap';
8
+ import { STREAM_FLUSH_MARK, STREAM_KEEPALIVE_CHUNK } from './stream-scripts';
9
+
10
+ /** `Node.ELEMENT_NODE`, without reading a global the router's tests do not have. */
11
+ const ELEMENT_NODE = 1;
12
+
13
+ /** What follows a streamed shell: whole chunks, until the document ends or is cancelled. */
14
+ export interface PageRest {
15
+ /** The next run of whole chunks; `null` once the document ended (its tail is dropped). */
16
+ next(): Promise<string | null>;
17
+ /** Stops reading: the request is cancelled, and the server aborts each open hole's signal. */
18
+ cancel(): void;
19
+ }
20
+
21
+ /** The page's markup up to the shell's end, and the rest when the page streams any. */
22
+ export interface PageHead {
23
+ readonly html: string;
24
+ readonly rest: PageRest | null;
25
+ }
26
+
27
+ export async function readShell(body: ReadableStream<Uint8Array>): Promise<PageHead> {
28
+ const reader = body.getReader();
29
+ const decoder = new TextDecoder();
30
+ let buffer = '';
31
+ for (;;) {
32
+ const { done, value } = await reader.read();
33
+ if (done) return { html: buffer + decoder.decode(), rest: null };
34
+ buffer += decoder.decode(value, { stream: true });
35
+ const end = buffer.indexOf(STREAM_FLUSH_MARK);
36
+ if (end === -1) continue;
37
+ const html = buffer.slice(0, end);
38
+ buffer = buffer.slice(end + STREAM_FLUSH_MARK.length);
39
+ return { html, rest: restOf(reader, decoder, buffer) };
40
+ }
41
+ }
42
+
43
+ function restOf(
44
+ reader: ReadableStreamDefaultReader<Uint8Array>,
45
+ decoder: TextDecoder,
46
+ start: string,
47
+ ): PageRest {
48
+ let buffer = withoutKeepAlives(start);
49
+ return {
50
+ async next() {
51
+ for (;;) {
52
+ const end = buffer.lastIndexOf(STREAM_FLUSH_MARK);
53
+ if (end !== -1) {
54
+ // Keep-alives between two chunks of one read never reach the page either.
55
+ const whole = buffer
56
+ .slice(0, end)
57
+ .split(STREAM_FLUSH_MARK)
58
+ .map(withoutKeepAlives)
59
+ .join(STREAM_FLUSH_MARK);
60
+ buffer = buffer.slice(end + STREAM_FLUSH_MARK.length);
61
+ return whole;
62
+ }
63
+ const { done, value } = await reader.read();
64
+ if (done) return null;
65
+ buffer = withoutKeepAlives(buffer + decoder.decode(value, { stream: true }));
66
+ }
67
+ },
68
+ cancel() {
69
+ // Settles once the request is torn down; a cancel that fails has nothing left to stop.
70
+ reader.cancel().catch(() => undefined);
71
+ },
72
+ };
73
+ }
74
+
75
+ /**
76
+ * The buffer with the keep-alive frames at its head dropped. The server writes one between two whole
77
+ * chunks every second a hole is open, so this is the only place one can stand: kept, a hole with no
78
+ * deadline grew the buffer for as long as it stayed open.
79
+ */
80
+ function withoutKeepAlives(buffer: string): string {
81
+ let start = 0;
82
+ while (buffer.startsWith(STREAM_KEEPALIVE_CHUNK, start)) start += STREAM_KEEPALIVE_CHUNK.length;
83
+ return start === 0 ? buffer : buffer.slice(start);
84
+ }
85
+
86
+ /** Everything left, for an answer shown whole (a modal): the chunks joined, the tail dropped. */
87
+ export async function drain(rest: PageRest): Promise<string> {
88
+ let html = '';
89
+ for (let chunk = await rest.next(); chunk !== null; chunk = await rest.next()) html += chunk;
90
+ return html;
91
+ }
92
+
93
+ /**
94
+ * Each chunk into the live body, in arrival order, then its scripts: the hole's `$X()` reveal and
95
+ * whatever its `after` carries (a hole's islands). Stops at `signal` — a newer page took the body —
96
+ * and cancels the request either way. Rejects when the stream broke under a page still on screen.
97
+ * `landed`, after each chunk, until it answers `true`: what waits on a hole's content (a fragment).
98
+ */
99
+ export async function fillHoles(
100
+ doc: Document,
101
+ rest: PageRest,
102
+ ran: Set<string>,
103
+ signal: AbortSignal,
104
+ landed?: () => boolean,
105
+ ): Promise<void> {
106
+ let waiting = landed;
107
+ const stop = (): void => rest.cancel();
108
+ signal.addEventListener('abort', stop, { once: true });
109
+ try {
110
+ for (let chunk = await rest.next(); chunk !== null; chunk = await rest.next()) {
111
+ if (signal.aborted) return;
112
+ const parsed = new DOMParser().parseFromString(`<body>${chunk}`, 'text/html');
113
+ const nodes = [...parsed.body.childNodes].map((node) => doc.adoptNode(node));
114
+ doc.body.append(...nodes);
115
+ const scripts = nodes
116
+ .filter((node): node is Element => node.nodeType === ELEMENT_NODE)
117
+ .flatMap((el) =>
118
+ el.tagName === 'SCRIPT' ? [el as HTMLScriptElement] : [...el.querySelectorAll('script')],
119
+ );
120
+ await runScripts(scripts, ran, (fresh, inert) => inert.replaceWith(fresh));
121
+ // A stop or a newer page while the scripts ran: this page is no longer the visitor's.
122
+ if (signal.aborted) return;
123
+ if (waiting?.() === true) waiting = undefined;
124
+ }
125
+ } catch (error) {
126
+ if (!signal.aborted) throw error;
127
+ } finally {
128
+ signal.removeEventListener('abort', stop);
129
+ rest.cancel();
130
+ }
131
+ }
package/src/navigation.ts CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  import { navigationCache } from './navigation-cache';
20
20
  import { withinDeadline } from './navigation-deadline';
21
- import { announcer, handOver } from './navigation-dom';
21
+ import { announcer, handOver, isAttachment } from './navigation-dom';
22
22
  import {
23
23
  type Answer,
24
24
  fetchDocument,
@@ -26,7 +26,13 @@ import {
26
26
  metaOf,
27
27
  responseFactsOf,
28
28
  } from './navigation-fetch';
29
- import { recordEntry, scrollAfter, withoutFragment } from './navigation-history';
29
+ import {
30
+ lateFragment,
31
+ loadForReal,
32
+ recordEntry,
33
+ scrollAfter,
34
+ withoutFragment,
35
+ } from './navigation-history';
30
36
  import { interceptNavigation } from './navigation-intercept';
31
37
  import { modalController } from './navigation-modal';
32
38
  import { addressOf, modalAddress, modalHistory } from './navigation-modal-rules';
@@ -51,6 +57,7 @@ import {
51
57
  responseVerdict,
52
58
  } from './navigation-rules';
53
59
  import { scrollKeeper } from './navigation-scroll';
60
+ import { drain, fillHoles, type PageRest } from './navigation-stream';
54
61
  import {
55
62
  documentHead,
56
63
  loadStylesheets,
@@ -116,6 +123,10 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
116
123
  let untrusted = false;
117
124
  let backing = false; // a Back this router started is traversing: the URL is still the one left
118
125
  let inflight: AbortController | undefined;
126
+ /** The page on screen still filling its holes; aborted by the next swap and by `stop()`. */
127
+ let filling: AbortController | undefined;
128
+ /** A broken stream's recovery, held while a newer navigation is on its way (`fill`). */
129
+ let recoverOnSettle: (() => void) | undefined;
119
130
  const live = announcer(doc);
120
131
  const owned = documentHead(doc);
121
132
  notePersisted(doc);
@@ -144,14 +155,33 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
144
155
  cache.set(url, request(url, 'prefetch'));
145
156
  };
146
157
 
158
+ /**
159
+ * The tab is about to be the browser's: the page on screen stops reading its holes and a held
160
+ * recovery (`fill`) is dropped. Either would otherwise load the page being left, over the load the
161
+ * browser has not committed yet.
162
+ */
163
+ const abandon = (): void => {
164
+ recoverOnSettle = undefined;
165
+ filling?.abort();
166
+ };
167
+
168
+ // Back/Forward put `url` in the address bar already: `assign` of it would only scroll (loadForReal).
169
+ // The visit in flight goes too: a POST whose `ultimate:navigated` listener started this never fills.
170
+ const loadInstead = (url: string): void => {
171
+ inflight?.abort();
172
+ abandon();
173
+ loadForReal(win, url);
174
+ };
175
+
147
176
  /** Cancelable; its default is a GET of the page the visitor is on. Nothing is re-sent. */
148
177
  const failed = (url: string, method: string, reason: string): void => {
149
178
  const detail = { url, method, reason };
150
179
  const event = new CustomEvent(NAVIGATION_ERROR_EVENT, { detail, cancelable: true });
151
180
  if (!doc.dispatchEvent(event)) return;
181
+ abandon();
152
182
  // Under a modal the URL differs only by its hash, which `assign` merely scrolls to: reloaded,
153
183
  // the page and its modal are both asked for again (the entry is the router's own GET).
154
- if (modal.address === undefined) win.location.assign(win.location.href);
184
+ if (modal.address === undefined) loadForReal(win, win.location.href);
155
185
  else win.location.reload();
156
186
  };
157
187
 
@@ -181,7 +211,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
181
211
  // trusted to swap: every navigation is a real load (`answerMovesTab`).
182
212
  if (untrusted && method === 'GET') {
183
213
  if (options.fromHash === true) modal.clear();
184
- else win.location.assign(url);
214
+ else loadInstead(url);
185
215
  return;
186
216
  }
187
217
  if (refreshYields(options.refresh, inflight)) return;
@@ -200,6 +230,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
200
230
  () => doc.documentElement.setAttribute(NAVIGATING_ATTRIBUTE, ''),
201
231
  NAVIGATION_PROGRESS_DELAY_MS,
202
232
  );
233
+ /** A streamed answer's rest no page took: cancelled on the way out, so its request ends. */
234
+ let unread: PageRest | null = null;
203
235
  try {
204
236
  let answer: Answer;
205
237
  try {
@@ -207,10 +239,11 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
207
239
  } catch {
208
240
  if (mine.signal.aborted || refreshFailsQuietly(options.refresh)) return;
209
241
  // A GET that never arrived is the browser's to try; a POST that failed is never re-sent.
210
- if (method === 'GET') win.location.assign(url);
242
+ if (method === 'GET') loadInstead(url);
211
243
  else failed(url, method, 'the request failed on the network');
212
244
  return;
213
245
  }
246
+ unread = answer.rest;
214
247
  if (mine.signal.aborted) return;
215
248
  const next =
216
249
  answer.html === null ? null : new DOMParser().parseFromString(answer.html, 'text/html');
@@ -239,7 +272,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
239
272
  // A principal change the router saw, or one the server may have signalled by handing
240
273
  // over the very URL it was asked for (it cannot say which): every tab forgets.
241
274
  if (verdict.reason === 'another principal' || verdict.url === url) forget();
242
- win.location.assign(verdict.url);
275
+ loadInstead(verdict.url);
243
276
  return;
244
277
  case 'follow':
245
278
  await navigate(verdict.url, {
@@ -249,6 +282,9 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
249
282
  });
250
283
  return;
251
284
  case 'hand-over':
285
+ // A download leaves the page on screen, still filling; anything else is shown by the
286
+ // browser in its place.
287
+ if (!isAttachment(answer.disposition)) abandon();
252
288
  if (answer.body !== null) handOver(win, answer.body, answer.disposition);
253
289
  return;
254
290
  default:
@@ -270,12 +306,19 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
270
306
  if (!sheetsLoaded) {
271
307
  if (refreshFailsQuietly(options.refresh)) return;
272
308
  if (method === 'GET') {
273
- win.location.assign(url);
309
+ loadInstead(url);
274
310
  return;
275
311
  }
276
312
  }
277
313
  if (shown === 'modal') {
278
- await modal.present(next, addressOf(landed), landed, modalHistory(method, history));
314
+ // A modal is shown whole: its holes are read to the end first.
315
+ let whole = next;
316
+ if (unread !== null) {
317
+ const rest = await drain(unread);
318
+ if (mine.signal.aborted) return;
319
+ whole = new DOMParser().parseFromString(`${answer.html ?? ''}${rest}`, 'text/html');
320
+ }
321
+ await modal.present(whole, addressOf(landed), landed, modalHistory(method, history));
279
322
  doc.dispatchEvent(new CustomEvent(NAVIGATED_EVENT, { detail: { url: landed } }));
280
323
  return;
281
324
  }
@@ -286,6 +329,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
286
329
  modal.release();
287
330
  modal.dismiss();
288
331
  let swapped: ReturnType<typeof swapDocument> | undefined;
332
+ let scrolled: (() => boolean) | undefined;
289
333
  const hold = holdFor(doc, options.refresh);
290
334
  if (hold === null) return;
291
335
  await swapIn(
@@ -294,6 +338,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
294
338
  () => {
295
339
  // A newer navigation started while the sheets loaded: this answer is no longer asked for.
296
340
  if (mine.signal.aborted) return;
341
+ // The page leaving stops reading its holes: nothing of it lands in this one.
342
+ filling?.abort();
297
343
  swapped = swapDocument(doc, next, owned, sheetsLoaded);
298
344
  // Emptied here and filled after the scripts, so a page with the same title still reads out.
299
345
  if (hold === undefined) live.textContent = '';
@@ -302,6 +348,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
302
348
  recordEntry(win, landed, rendered, history);
303
349
  // Inside the swap, so a view transition's "after" frame is already where the page lands.
304
350
  scrollAfter(win, doc, landed, history);
351
+ // Where the visitor is now, before any script or listener moves them.
352
+ scrolled = lateFragment(win, doc, landed, history);
305
353
  },
306
354
  press.track,
307
355
  );
@@ -321,13 +369,23 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
321
369
  landFocus(doc, live, hold);
322
370
  doc.dispatchEvent(new CustomEvent(NAVIGATED_EVENT, { detail: { url: landed } }));
323
371
  reconcile();
372
+ // Scripts and listeners ran since the swap: a newer navigation, or `stop()`, may have
373
+ // taken the body. The holes left unread are then cancelled below, never filled.
374
+ if (mine.signal.aborted) return;
375
+ if (unread !== null) {
376
+ fill(unread, landed, method, scrolled);
377
+ unread = null;
378
+ }
324
379
  } catch {
325
380
  // A swap that failed part-way leaves a page nobody rendered: a GET is loaded for real; a
326
381
  // POST's answer cannot be asked for again, so the visitor is told and shown this page.
327
- if (method === 'GET') win.location.assign(landed);
328
- else failed(url, method, 'the answer could not be shown');
382
+ if (method === 'GET') {
383
+ abandon();
384
+ loadForReal(win, landed);
385
+ } else failed(url, method, 'the answer could not be shown');
329
386
  }
330
387
  } finally {
388
+ unread?.cancel();
331
389
  win.clearTimeout(progress);
332
390
  if (inflight === mine) {
333
391
  inflight = undefined;
@@ -335,10 +393,39 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
335
393
  // Whatever the answer was, a frame nothing filled goes; an open modal is no longer busy.
336
394
  modal.settle();
337
395
  doc.documentElement.removeAttribute(NAVIGATING_ATTRIBUTE);
396
+ const recover = recoverOnSettle;
397
+ recoverOnSettle = undefined;
398
+ recover?.();
338
399
  }
339
400
  }
340
401
  };
341
402
 
403
+ /**
404
+ * The holes of the page just shown, filled as they arrive: the shell painted without them. A
405
+ * stream that breaks under the page is a page nobody rendered — a GET is loaded for real, a POST
406
+ * (never re-sent) is reported. One the next swap cut short is nobody's failure; one that breaks
407
+ * while the visitor's next page is on its way waits for it, and recovers only if that visit
408
+ * stayed or failed quietly — one that took the body, or handed the tab to the browser, drops it.
409
+ */
410
+ function fill(
411
+ rest: PageRest,
412
+ landed: string,
413
+ method: 'GET' | 'POST',
414
+ scrolled: (() => boolean) | undefined,
415
+ ): void {
416
+ const own = new AbortController();
417
+ filling = own;
418
+ fillHoles(doc, rest, ran, own.signal, scrolled).catch(() => {
419
+ const recover = (): void => {
420
+ if (own.signal.aborted) return;
421
+ if (method === 'GET') loadForReal(win, landed);
422
+ else failed(landed, method, 'the answer could not be shown');
423
+ };
424
+ if (inflight === undefined) recover();
425
+ else recoverOnSettle = recover;
426
+ });
427
+ }
428
+
342
429
  /**
343
430
  * The modal follows the URL's hash, once the page on screen is the URL's: opened (fetched, as a
344
431
  * hash address, so a stale one degrades), kept, or dismissed. On start, on Back/Forward, on a
@@ -395,6 +482,9 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
395
482
  closeModal: () => modal.close(),
396
483
  stop() {
397
484
  stopListening();
485
+ // The answer still being read, too: a stopped router mutates nothing after this.
486
+ inflight?.abort();
487
+ filling?.abort();
398
488
  modal.dismiss();
399
489
  scroll.stop();
400
490
  tabs.stop();
@@ -62,6 +62,15 @@ function cacheControl(ttlMs: number | null, policy: IsrPolicy, ageMs: number): s
62
62
  return stale === 0 ? base : `${base}, stale-while-revalidate=${stale}`;
63
63
  }
64
64
 
65
+ /**
66
+ * A served-stale answer is the copy the bust just withdrew. The edge was purged by surrogate key
67
+ * when the tag was busted and nothing purges it again when the regeneration lands, so a lease on
68
+ * this answer is the pre-write page for the route's whole ttl, then again under
69
+ * `stale-while-revalidate`. Storable (it keeps its validator and its purge keys) but never fresh
70
+ * in a shared cache: the edge asks again, and the next answer is the regenerated one.
71
+ */
72
+ const SERVED_STALE_CACHE_CONTROL = 'public, max-age=0, s-maxage=0';
73
+
65
74
  /**
66
75
  * `entryTtlMs`'s reason, one field over: a store may hand back an entry with no `status`, or one
67
76
  * that JSON turned into something else, on the request path. Absent is 200 — the only value any
@@ -108,7 +117,10 @@ export function isrResult(entry: IsrEntry, options: IsrResultOptions): RenderRes
108
117
  }
109
118
  const headers: Record<string, string> = {
110
119
  ...staticHeaders(entry.hash, buildId),
111
- 'cache-control': cacheControl(entryTtlMs(entry), policy, options.ageMs),
120
+ 'cache-control':
121
+ options.servedStale === true
122
+ ? SERVED_STALE_CACHE_CONTROL
123
+ : cacheControl(entryTtlMs(entry), policy, options.ageMs),
112
124
  vary,
113
125
  };
114
126
  // The keys an edge purges this document by — `@ultimat3/cache`'s list, never a second one, so
@@ -22,7 +22,12 @@ import {
22
22
  } from '@ultimat3/core';
23
23
  import { finiteStatus } from './finite-status';
24
24
  import type { RenderResult } from './route';
25
- import { REVEAL_BODY, REVEAL_CALL } from './stream-scripts';
25
+ import {
26
+ REVEAL_BODY,
27
+ REVEAL_CALL,
28
+ STREAM_FLUSH_MARK,
29
+ STREAM_KEEPALIVE_CHUNK,
30
+ } from './stream-scripts';
26
31
 
27
32
  export interface StreamHole {
28
33
  /** Stable within a response; becomes the DOM id, so keep it short. */
@@ -118,8 +123,8 @@ export interface StreamOptions {
118
123
  /** Under the shortest `idleTimeout` `@ultimat3/http` derives: `ceil(requestTimeoutMs / 1000) + 2` ≥ 3 s. */
119
124
  export const DEFAULT_STREAM_KEEPALIVE_MS = 1_000;
120
125
 
121
- /** The keep-alive write: a comment, inert wherever the parser is between two chunks. */
122
- export const STREAM_KEEPALIVE_CHUNK = '<!---->';
126
+ /** The keep-alive write, declared beside the flush mark so the client router reads the same one. */
127
+ export { STREAM_KEEPALIVE_CHUNK } from './stream-scripts';
123
128
 
124
129
  /**
125
130
  * `null` is the declared "this hole owns its own timeout" opt-out; every other value is a
@@ -233,8 +238,12 @@ export function renderStreamHtml(
233
238
  controller.close();
234
239
  };
235
240
 
236
- // No holes, no reveal script: a page that streams nothing pays nothing.
237
- write(plan.head + (plan.holes.length > 0 ? REVEAL_SCRIPT : '') + plan.shell);
241
+ // No holes, no reveal script and no mark: a page that streams nothing pays nothing.
242
+ write(
243
+ plan.holes.length > 0
244
+ ? plan.head + REVEAL_SCRIPT + plan.shell + STREAM_FLUSH_MARK
245
+ : plan.head + plan.shell,
246
+ );
238
247
 
239
248
  let pending = plan.holes.length;
240
249
  if (pending === 0) {
@@ -268,7 +277,7 @@ export function renderStreamHtml(
268
277
  if (revealed) return;
269
278
  revealed = true;
270
279
  if (timer !== undefined) clearTimeout(timer);
271
- write(revealChunk(hole.id, html, after));
280
+ write(revealChunk(hole.id, html, after) + STREAM_FLUSH_MARK);
272
281
  settle();
273
282
  };
274
283
  const failed = (): string => hole.error ?? fallbackOf(errorFallback, hole.id);
@@ -9,7 +9,13 @@ import { JSX_NODE } from '@ultimat3/core/render-node';
9
9
  import { PrerenderFailedError } from './errors';
10
10
  import type { HoleNode } from './hole';
11
11
  import { isHoleNode } from './hole';
12
- import { renderAttributes, VOID_ELEMENTS } from './html';
12
+ import {
13
+ carriesJson,
14
+ escapeJsonContent,
15
+ escapeRawTextContent,
16
+ renderAttributes,
17
+ VOID_ELEMENTS,
18
+ } from './html';
13
19
  import { emitIslandAttributes, emitIslandProps } from './hydrate';
14
20
  import type { IslandNode } from './island';
15
21
  import { isIslandNode } from './island';
@@ -183,11 +189,45 @@ function emitNode(node: JsxNode, depth: number, walk: RenderHtmlOptions, out: Bu
183
189
  if (VOID_ELEMENTS.has(type)) return;
184
190
  const raw = (props as { innerHTML?: unknown }).innerHTML;
185
191
  if (raw === undefined || raw === null) {
186
- emit((props as { children?: unknown }).children, depth + 1, walk, out);
192
+ const children = (props as { children?: unknown }).children;
193
+ const text = type === 'script' || type === 'style' ? rawText(children, depth + 1) : undefined;
194
+ if (text === undefined) emit(children, depth + 1, walk, out);
195
+ else if (typeof text !== 'string') emit(text.resolved, depth + 1, walk, out);
196
+ else {
197
+ const json = type === 'script' && carriesJson((props as { type?: unknown }).type);
198
+ write(out, json ? escapeJsonContent(text) : escapeRawTextContent(text));
199
+ }
187
200
  } else write(out, String(raw));
188
201
  write(out, `</${type}>`);
189
202
  }
190
203
 
204
+ /**
205
+ * The text a `<script>` or `<style>` holds, unescaped — the two raw text elements, where a
206
+ * character reference is never decoded, so `&gt;` in a selector or `&amp;&amp;` in a condition
207
+ * reaches the parser as written and breaks it. When a child is anything but text (an element, a
208
+ * promise) the caller walks the children as any other, escaped — as `resolved`, the children with
209
+ * every thunk this read already called swapped for its value: a thunk runs once, never twice.
210
+ */
211
+ function rawText(value: unknown, depth: number): string | { readonly resolved: unknown } {
212
+ assertDepth(depth);
213
+ if (value === null || value === undefined || value === false || value === true) return '';
214
+ if (typeof value === 'string') return value;
215
+ if (typeof value === 'number' || typeof value === 'bigint') return String(value);
216
+ if (typeof value === 'function') return rawText((value as () => unknown)(), depth + 1);
217
+ if (!Array.isArray(value) || isIslandNode(value) || isHoleNode(value)) return { resolved: value };
218
+ let text = '';
219
+ const resolved: unknown[] = [];
220
+ let markup = false;
221
+ for (const item of value) {
222
+ // Past the first non-text child no thunk is called here: the walk calls each, once.
223
+ const piece = markup ? { resolved: item } : rawText(item, depth + 1);
224
+ if (typeof piece === 'string') text += piece;
225
+ else markup = true;
226
+ resolved.push(typeof piece === 'string' ? piece : piece.resolved);
227
+ }
228
+ return markup ? { resolved } : text;
229
+ }
230
+
191
231
  /**
192
232
  * An island renders its SHELL on the server — the children the page wrote — and nothing of the
193
233
  * client module: the specifier is data, so there is no import to follow and the static page's
package/src/server.ts CHANGED
@@ -99,4 +99,15 @@ export {
99
99
  } from './render-stream';
100
100
  // ---- the Sass compile cache: where it lives, and how often this process ran Sass instead --------
101
101
  export { sassCompilations, setSassCacheDir } from './sass-cache';
102
+ export type { SiteAsset, SiteAssetTable } from './site-assets';
103
+ export {
104
+ ASSET_CONTENT_TYPES,
105
+ hashedAssetUrl,
106
+ parseHashedAssetUrl,
107
+ SITE_ASSET_BASE_PATH,
108
+ SITE_ASSETS_SOURCE,
109
+ siteAssetTable,
110
+ } from './site-assets';
111
+ /** The comment a `stream` page writes after its shell and after each hole: what a reader splits on. */
112
+ export { STREAM_FLUSH_MARK } from './stream-scripts';
102
113
  export { serverTsxBuildPlugin } from './tsx-build-plugin';
@@ -0,0 +1,160 @@
1
+ // The site asset table: every file under `apps/web/site/assets/` by content-hashed URL, one per app
2
+ // root, answering `asset()`, `/assets/*` and the static export's copy alike. Below the CLI so the
3
+ // test preload installs the same table the boot does.
4
+
5
+ // why: `asset()` is called from a synchronous render, so the table answers synchronously — and Bun
6
+ // ships no sync stat or sync read; `join`/`relative` because Bun ships no path API either.
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { join } from 'node:path'; // why: Bun ships no path API.
9
+ import { renderFixShellArg } from '@ultimat3/core';
10
+ import { ASSET_DIR, type AssetExtension, type AssetPath, assetPathProblem } from './asset';
11
+ import { AssetMissingError } from './errors';
12
+ import { contentHash } from './render-static';
13
+
14
+ /** App-root-relative, beside `favicon.ico`: `apps/web/site/` is where an app's public files live. */
15
+ export const SITE_ASSETS_SOURCE = `apps/web/site/${ASSET_DIR}`;
16
+
17
+ /** The URL prefix every hashed asset is served under, and the export directory it is copied to. */
18
+ export const SITE_ASSET_BASE_PATH = `/${ASSET_DIR}`;
19
+
20
+ /** What each served extension IS. `vtt` carries a charset: captions are text a player decodes. */
21
+ export const ASSET_CONTENT_TYPES: Readonly<Record<AssetExtension, string>> = {
22
+ avif: 'image/avif',
23
+ webp: 'image/webp',
24
+ png: 'image/png',
25
+ jpg: 'image/jpeg',
26
+ jpeg: 'image/jpeg',
27
+ gif: 'image/gif',
28
+ svg: 'image/svg+xml',
29
+ ico: 'image/x-icon',
30
+ woff2: 'font/woff2',
31
+ mp4: 'video/mp4',
32
+ webm: 'video/webm',
33
+ vtt: 'text/vtt; charset=utf-8',
34
+ };
35
+
36
+ export interface SiteAsset {
37
+ /** As `asset()` names it: `assets/brand/logo.svg`. */
38
+ readonly path: AssetPath;
39
+ /** Absolute path on disk. */
40
+ readonly file: string;
41
+ /** `@ultimat3/render`'s `contentHash` of the bytes, 8 hex characters — the one CSS and HTML get. */
42
+ readonly hash: string;
43
+ /** `/assets/brand/logo.<hash>.svg`. */
44
+ readonly url: string;
45
+ readonly contentType: string;
46
+ readonly bytes: number;
47
+ }
48
+
49
+ const splitExtension = (path: string): { readonly stem: string; readonly extension: string } => {
50
+ const dot = path.lastIndexOf('.');
51
+ return { stem: path.slice(0, dot), extension: path.slice(dot + 1) };
52
+ };
53
+
54
+ /** The hash goes before the extension, so a static host still infers the type from the name. */
55
+ export function hashedAssetUrl(path: AssetPath, hash: string): string {
56
+ const { stem, extension } = splitExtension(path);
57
+ return `/${stem}.${hash}.${extension}`;
58
+ }
59
+
60
+ const HASHED = /^\/(assets\/.+)\.([0-9a-f]{8})\.([a-z0-9]+)$/i;
61
+
62
+ /** The inverse of `hashedAssetUrl`: which asset a request names, and at which content. */
63
+ export function parseHashedAssetUrl(
64
+ pathname: string,
65
+ ): { readonly path: AssetPath; readonly hash: string } | undefined {
66
+ const match = HASHED.exec(pathname);
67
+ if (match === null) return undefined;
68
+ const path = `${match[1] ?? ''}.${match[3] ?? ''}`;
69
+ if (assetPathProblem(path) !== undefined) return undefined;
70
+ return { path: path as AssetPath, hash: match[2] ?? '' };
71
+ }
72
+
73
+ export interface SiteAssetTable {
74
+ /** The asset `asset()` named, hashed as the bytes are NOW. Throws `X_ASSET_MISSING`. */
75
+ resolve(path: AssetPath): SiteAsset;
76
+ /** Every servable file under the source directory, sorted by path. */
77
+ all(): readonly SiteAsset[];
78
+ }
79
+
80
+ const missing = (path: string, cause: string): AssetMissingError =>
81
+ new AssetMissingError(
82
+ `asset(${JSON.stringify(path)}): ${cause}`,
83
+ `ls ${renderFixShellArg(SITE_ASSETS_SOURCE, '<assets>')} # add ${SITE_ASSETS_SOURCE}/${path.slice(ASSET_DIR.length + 1)} there, or correct the path passed to asset(); then x build --target static --json`,
84
+ );
85
+
86
+ /**
87
+ * A stat per call, a read only when the file changed: `x dev` sees an edited image under a new URL
88
+ * on the next render with no watcher, and the container — whose files never change — pays one
89
+ * `stat` per `asset()` call and nothing else. One behaviour in both, never a dev-only rescan.
90
+ */
91
+ function createSiteAssetTable(root: string): SiteAssetTable {
92
+ const source = join(root, SITE_ASSETS_SOURCE);
93
+ const cache = new Map<string, { readonly stamp: string; readonly asset: SiteAsset }>();
94
+
95
+ const resolve = (path: AssetPath): SiteAsset => {
96
+ const problem = assetPathProblem(path);
97
+ if (problem !== undefined) throw missing(path, problem);
98
+ const file = join(source, path.slice(ASSET_DIR.length + 1));
99
+ let stamp: string;
100
+ try {
101
+ const stat = statSync(file);
102
+ if (!stat.isFile()) throw missing(path, `${file} is not a file`);
103
+ stamp = `${String(stat.mtimeMs)}:${String(stat.size)}`;
104
+ } catch (error) {
105
+ if (error instanceof AssetMissingError) throw error;
106
+ throw missing(path, `no file at ${SITE_ASSETS_SOURCE}/${path.slice(ASSET_DIR.length + 1)}`);
107
+ }
108
+ const cached = cache.get(path);
109
+ if (cached !== undefined && cached.stamp === stamp) return cached.asset;
110
+ const bytes = readFileSync(file);
111
+ const hash = contentHash(bytes);
112
+ // `assetPathProblem` already refused an unknown extension; the guard keeps `constructor` from
113
+ // ever answering an `Object` member if that check is loosened.
114
+ const extension = splitExtension(path).extension.toLowerCase();
115
+ const asset: SiteAsset = {
116
+ path,
117
+ file,
118
+ hash,
119
+ url: hashedAssetUrl(path, hash),
120
+ contentType: Object.hasOwn(ASSET_CONTENT_TYPES, extension)
121
+ ? ASSET_CONTENT_TYPES[extension as AssetExtension]
122
+ : 'application/octet-stream',
123
+ bytes: bytes.byteLength,
124
+ };
125
+ cache.set(path, { stamp, asset });
126
+ return asset;
127
+ };
128
+
129
+ const all = (): readonly SiteAsset[] => {
130
+ const found: SiteAsset[] = [];
131
+ let files: string[];
132
+ try {
133
+ files = [...new Bun.Glob('**/*').scanSync({ cwd: source, onlyFiles: true })];
134
+ } catch {
135
+ // No `assets/` directory is an app with no assets, not an error.
136
+ return [];
137
+ }
138
+ for (const relativePath of files.sort()) {
139
+ const path = `${ASSET_DIR}/${relativePath.split('\\').join('/')}`;
140
+ // A source file beside its renditions (a `.psd`, a `README.md`) is not a served asset.
141
+ if (assetPathProblem(path) !== undefined) continue;
142
+ found.push(resolve(path as AssetPath));
143
+ }
144
+ return found;
145
+ };
146
+
147
+ return { resolve, all };
148
+ }
149
+
150
+ /** One table per root, so the renderer and the route read the same cache. */
151
+ const tables = new Map<string, SiteAssetTable>();
152
+
153
+ export function siteAssetTable(root: string): SiteAssetTable {
154
+ let table = tables.get(root);
155
+ if (table === undefined) {
156
+ table = createSiteAssetTable(root);
157
+ tables.set(root, table);
158
+ }
159
+ return table;
160
+ }
@@ -16,3 +16,16 @@ export const REVEAL_CALL = '$X()';
16
16
  * every template that has arrived.
17
17
  */
18
18
  export const STREAM_REVEAL_BODIES: readonly string[] = Object.freeze([REVEAL_BODY, REVEAL_CALL]);
19
+
20
+ /**
21
+ * Written after the shell and after each hole's chunk, in the same write: everything before it is
22
+ * whole markup. The client router reads a soft visit as it arrives and swaps the shell at the first
23
+ * mark, then fills each hole at the next; a full load's parser reads it as an empty comment.
24
+ */
25
+ export const STREAM_FLUSH_MARK = '<!--x:flush-->';
26
+
27
+ /**
28
+ * Written every `keepAliveMs` while a hole is open, always between two whole chunks: a comment the
29
+ * parser reads as nothing, and the client router drops as it arrives (`navigation-stream.ts`).
30
+ */
31
+ export const STREAM_KEEPALIVE_CHUNK = '<!---->';
package/src/surfaces.ts CHANGED
@@ -275,8 +275,16 @@ function classify(i: ClassifyInput): BoundaryViolation | null {
275
275
  const chainText = i.chain.join(' → ');
276
276
  const base = { entry: i.entry, importer: i.importer, imported: i.imported, chain: i.chain };
277
277
 
278
- // Transitive, from the ENTRY: a site page reaching app/ through any number of hops.
279
- if (i.entrySurface === 'site' && i.importedSurface === 'app' && !i.typeOnly) {
278
+ // Transitive, from the ENTRY: a site page reaching app/ through any number of hops. The finding
279
+ // is the edge that CROSSES — the first one in the chain to land on app/. Every edge below it is
280
+ // app/ importing app/, which is legal, and reporting those told the author to delete a query's
281
+ // own policy and repo imports ahead of the one import that was wrong.
282
+ if (
283
+ i.entrySurface === 'site' &&
284
+ i.importedSurface === 'app' &&
285
+ !i.typeOnly &&
286
+ !i.chain.slice(0, -1).some((file) => surfaceOf(file) === 'app')
287
+ ) {
280
288
  return {
281
289
  ...base,
282
290
  rule: 'site-imports-app',