@opentf/afw 0.0.0-stage → 0.33.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/components/Link.d.ts +12 -0
  4. package/components/Link.jsx +54 -0
  5. package/core/context.d.ts +7 -0
  6. package/core/context.js +60 -0
  7. package/core/dev.js +27 -0
  8. package/core/errors.d.ts +14 -0
  9. package/core/errors.js +48 -0
  10. package/core/html.js +10 -0
  11. package/core/metadata.js +186 -0
  12. package/core/reactive.d.ts +5 -0
  13. package/core/reactive.js +190 -0
  14. package/core/render-context.js +11 -0
  15. package/core/signals.d.ts +8 -0
  16. package/core/signals.js +264 -0
  17. package/index.d.ts +5 -0
  18. package/index.js +13 -0
  19. package/jsx-runtime.d.ts +37 -0
  20. package/package.json +66 -4
  21. package/runtime/clipboard.d.ts +7 -0
  22. package/runtime/clipboard.js +47 -0
  23. package/runtime/code-block.d.ts +14 -0
  24. package/runtime/code-block.js +76 -0
  25. package/runtime/context.browser.js +163 -0
  26. package/runtime/context.d.ts +13 -0
  27. package/runtime/context.js +44 -0
  28. package/runtime/dom.browser.js +423 -0
  29. package/runtime/dom.d.ts +142 -0
  30. package/runtime/dom.js +670 -0
  31. package/runtime/error-boundary.browser.js +140 -0
  32. package/runtime/error-boundary.d.ts +19 -0
  33. package/runtime/error-boundary.js +123 -0
  34. package/runtime/events.browser.js +29 -0
  35. package/runtime/events.d.ts +1 -0
  36. package/runtime/events.js +17 -0
  37. package/runtime/head.js +29 -0
  38. package/runtime/hmr.js +199 -0
  39. package/runtime/hydrate.browser.js +144 -0
  40. package/runtime/hydrate.d.ts +179 -0
  41. package/runtime/hydrate.js +584 -0
  42. package/runtime/index.d.ts +14 -0
  43. package/runtime/index.js +24 -0
  44. package/runtime/lifecycle.d.ts +6 -0
  45. package/runtime/lifecycle.js +14 -0
  46. package/runtime/mount.d.ts +20 -0
  47. package/runtime/mount.js +88 -0
  48. package/runtime/portal.browser.js +85 -0
  49. package/runtime/portal.d.ts +12 -0
  50. package/runtime/portal.js +74 -0
  51. package/runtime/raw-html.d.ts +11 -0
  52. package/runtime/raw-html.js +55 -0
  53. package/runtime/resource.d.ts +9 -0
  54. package/runtime/resource.js +139 -0
  55. package/runtime/route-data.d.ts +15 -0
  56. package/runtime/route-data.js +64 -0
  57. package/runtime/router.d.ts +149 -0
  58. package/runtime/router.js +807 -0
  59. package/server/adapters/node.d.ts +28 -0
  60. package/server/adapters/node.js +74 -0
  61. package/server/api.d.ts +175 -0
  62. package/server/api.js +233 -0
  63. package/server/builtins.js +42 -0
  64. package/server/cookies.d.ts +44 -0
  65. package/server/cookies.js +122 -0
  66. package/server/head.js +9 -0
  67. package/server/index.d.ts +155 -0
  68. package/server/index.js +31 -0
  69. package/server/loader.js +201 -0
  70. package/server/middleware.js +119 -0
  71. package/server/render-context.js +30 -0
  72. package/server/render.js +175 -0
  73. package/server/ssg-runtime.js +297 -0
@@ -0,0 +1,584 @@
1
+ // Hydration primitives (Phase 2 — see docs/HYDRATION.md). The client *adopts* the
2
+ // server-rendered DOM instead of rebuilding it: it claims existing nodes and wires
3
+ // reactivity (bindText/bindAttr/events from dom.js) onto them. There is no separate
4
+ // "hydrate" binding logic — those helpers already operate on existing nodes; the only
5
+ // new work is *node acquisition*, which is what this module provides.
6
+ //
7
+ // Acquisition is a **cursor walk** (the decided approach, like Solid): the Hydrate
8
+ // codegen emits claim calls in the exact order the SSG backend emitted nodes, so a
9
+ // cursor over a parent's childNodes lines up 1:1 with the template. The server output
10
+ // carries no inter-element whitespace (ssg.rs concatenates with no padding), so the
11
+ // re-parsed DOM has text nodes only where the template does — the walk stays aligned.
12
+ //
13
+ // Markers (only where structure is variable): a dynamic text hole is delimited by
14
+ // `<!--$-->value<!--/-->` so it is findable even when the value is empty or adjacent
15
+ // to static text (which the HTML parser would otherwise merge into one text node).
16
+ // Static structure carries no markers and is claimed by position.
17
+
18
+ /** Comment markers bounding a dynamic text hole in server HTML. */
19
+ export const HOLE_START = "$";
20
+ export const HOLE_END = "/";
21
+
22
+ /** Comment markers bounding a variable structural region — a list or a conditional —
23
+ * in server HTML (docs/HYDRATION.md §3.1): `<!--[-->` opens, `<!--]-->` closes. A list
24
+ * holds one item root node per item; a conditional holds the currently rendered branch
25
+ * (or nothing). The closing marker becomes the reconcile/swap anchor on hydration. */
26
+ export const REGION_START = "[";
27
+ export const REGION_END = "]";
28
+
29
+ /** Markers bounding a *component's* light-DOM `{children}` slot (docs/HYDRATION.md §3.1,
30
+ * 2.1d) — distinct bytes from the list/conditional region markers so a component's own
31
+ * internal regions never collide with its slot. The slot's content is the *parent's* JSX
32
+ * (server-rendered here), so the parent finds this slot by its `<!--c[-->` marker within the
33
+ * host and adopts the children (its reactivity), while the component steps over the slot.
34
+ *
35
+ * Each marker is **labeled with the owning host's tag** — `<!--c[afw-card-8e61e2ff-->` — because
36
+ * slot regions nest: a component that forwards `{children}` into another component
37
+ * (`Card` → `<Link>{children}</Link>`) emits its markers *inside* that component's, and a
38
+ * forwarding parent adds a third pair at the same position. Unlabeled, a component's walk
39
+ * stopped at the first close it met (a nested one) and the parent's slot lookup had to guess
40
+ * by tree order — both wrong in the forwarding shape. The label makes each side's pair exact. */
41
+ export const SLOT_START = "c[";
42
+ export const SLOT_END = "c]";
43
+
44
+ /** The tag a slot marker is labeled with, or `null` if `node` isn't that kind of marker.
45
+ * `prefix` is {@link SLOT_START} or {@link SLOT_END}. */
46
+ function slotLabel(node, prefix) {
47
+ if (!node || node.nodeType !== COMMENT) return null;
48
+ const d = node.data;
49
+ return d.startsWith(prefix) ? d.slice(prefix.length) : null;
50
+ }
51
+
52
+ const ELEMENT = 1;
53
+ const TEXT = 3;
54
+ const COMMENT = 8;
55
+
56
+ /** Thrown when the server DOM doesn't match the template at a claim site. The
57
+ * component boundary catches this and recovers by rebuilding via CSR (never silent;
58
+ * see docs/HYDRATION.md §3.5). */
59
+ export class HydrationMismatch extends Error {
60
+ constructor(message) {
61
+ super(message);
62
+ this.name = "HydrationMismatch";
63
+ }
64
+ }
65
+
66
+ // ── the hydration flag ────────────────────────────────────────────────────────
67
+ // True during the initial hydration pass. A component's connectedCallback reads it
68
+ // to decide whether to *adopt* its server children or *build* a fresh subtree — the
69
+ // custom-element-as-island coordination (docs/HYDRATION.md §3.4).
70
+ //
71
+ // Why a flag and not the per-instance `this.firstChild` test: a server-rendered host
72
+ // and a client-`createElement`'d host that was handed call-site children both have a
73
+ // `firstChild`, so the structural test alone can't tell "adopt the server DOM" from
74
+ // "build and slot these children" (it mis-adopts on plain SPA navigation). The flag is
75
+ // the unambiguous signal — it is only ever set during the one-shot first-paint pass.
76
+ //
77
+ // Why it initializes from the DOM sentinel, not `false`: a custom element upgrades — and
78
+ // its `connectedCallback` runs the build-vs-adopt switch — the instant its class is
79
+ // `customElements.define`d. Framework components imported *eagerly* by the app entry
80
+ // (e.g. `<Link>` from `@opentf/afw`) are therefore defined and upgraded during the entry
81
+ // bundle's evaluation, **before** `mountApp` runs `beginHydration()`. If the flag were
82
+ // still `false` then, every server-rendered `<afw-link>` would take the *build* arm —
83
+ // re-wrapping the server subtree it should have adopted (a silent `<a><a>` double-build)
84
+ // — long before the router ever starts hydrating. So the flag is seeded synchronously
85
+ // at module load from the server sentinel (`[data-afw-hydrate]`, stamped only when the
86
+ // page shipped adoptable server markup): the deferred entry module evaluates after the
87
+ // HTML is parsed, so the sentinel is present, and this module is a transitive dependency
88
+ // of every component (via the runtime), so it evaluates before any component's `define`.
89
+ // `mountApp` still brackets the pass with `beginHydration`/`endHydration`, and clears the
90
+ // flag when it decides *not* to hydrate (no sentinel / empty root), so a CSR mount and
91
+ // every subsequent SPA navigation build fresh.
92
+ let _hydrating =
93
+ typeof document !== "undefined" &&
94
+ renderedForPath(document.querySelector("[data-afw-hydrate]"), globalThis.location?.pathname);
95
+
96
+ /**
97
+ * Whether `el` carries the hydrate sentinel for markup rendered at `pathname`. A
98
+ * prerender stamps the route it rendered (`data-afw-hydrate="/docs/x"`); a bare
99
+ * sentinel (SSR, which renders the requested URL) always matches. A host that
100
+ * answers one URL with another page's HTML — an SPA fallback over static output —
101
+ * gets a mismatch, so the client builds the requested route instead of adopting.
102
+ */
103
+ export function renderedForPath(el, pathname) {
104
+ if (!el?.hasAttribute?.("data-afw-hydrate")) return false;
105
+ const rendered = el.getAttribute("data-afw-hydrate");
106
+ return !rendered || canonicalPath(rendered) === canonicalPath(pathname ?? "/");
107
+ }
108
+
109
+ function canonicalPath(path) {
110
+ let decoded = path;
111
+ try {
112
+ decoded = decodeURI(path);
113
+ } catch {
114
+ // Malformed escapes compare literally.
115
+ }
116
+ return decoded.replace(/(.)\/+$/, "$1") || "/";
117
+ }
118
+
119
+ /** Is the client mid-hydration right now? */
120
+ export function isHydrating() {
121
+ return _hydrating;
122
+ }
123
+
124
+ /**
125
+ * Run `fn` with the hydration flag *cleared*, restoring the prior value (nesting-safe).
126
+ *
127
+ * The build/adopt decision hangs on one module-global flag, but the invariant it must
128
+ * encode is narrower: `isHydrating()` may be true only while the DOM being processed is
129
+ * the server's. The moment a component builds fresh DOM — because its view isn't
130
+ * adoptable (`RebuildIfServerChildren`), or its adopt hit a mismatch and it's recovering,
131
+ * or it's a nested build — that fresh subtree is *not* server-rendered. Its child custom
132
+ * elements upgrade synchronously during `appendChild` inside this build, and if they still
133
+ * saw `isHydrating()` true they'd try to *adopt* content their parent just `createElement`'d
134
+ * → a guaranteed `HydrationMismatch` cascade (a non-adoptable layout would tear the whole
135
+ * page's islands into rebuild-storms). Bracketing every build path with this makes the
136
+ * children build too, matching the DOM they're actually handed. Synchronous only — builds
137
+ * never await — so a plain global save/restore is correct even when builds nest.
138
+ */
139
+ export function runBuild(fn) {
140
+ const prev = _hydrating;
141
+ _hydrating = false;
142
+ try {
143
+ return fn();
144
+ } finally {
145
+ _hydrating = prev;
146
+ }
147
+ }
148
+
149
+ /** Run `fn` with the hydration flag set, restoring the prior value (nesting-safe).
150
+ * Synchronous only — for the async first-paint pass use {@link beginHydration} /
151
+ * {@link endHydration}, which span the route module's `import()`. */
152
+ export function runHydration(fn) {
153
+ const prev = _hydrating;
154
+ _hydrating = true;
155
+ try {
156
+ return fn();
157
+ } finally {
158
+ _hydrating = prev;
159
+ }
160
+ }
161
+
162
+ // Route modules are code-split (`() => import(...)`), so a route's custom elements are
163
+ // defined — and its server-rendered hosts upgrade synchronously — *during* the router's
164
+ // `await import()`, before the page `hydrate` factory runs. The flag therefore has to be
165
+ // set across that whole async region, which a synchronous `runHydration` can't do; the
166
+ // router brackets first paint with these instead. First-paint hydration is a single,
167
+ // sequential boot step (no concurrent navigation), so a plain module-global set is safe.
168
+
169
+ /** Begin the first-paint hydration pass; pair with {@link endHydration}. Set *before*
170
+ * the route module is imported so every server host upgrading at `customElements.define`
171
+ * observes it and adopts (docs/HYDRATION.md §3.4). */
172
+ export function beginHydration() {
173
+ _hydrating = true;
174
+ }
175
+
176
+ /** End the first-paint hydration pass — subsequent client navigations build fresh.
177
+ * Also flushes any {@link afterHydration} callbacks queued during the pass. */
178
+ export function endHydration() {
179
+ _hydrating = false;
180
+ if (_postHydration) {
181
+ const queued = _postHydration;
182
+ _postHydration = null;
183
+ for (const fn of queued) fn();
184
+ }
185
+ }
186
+
187
+ // Work that must wait until first-paint hydration has *finished*. The motivating case is
188
+ // `<Portal>`: it relocates its light-DOM children to a target (usually <body>) on connect,
189
+ // but during hydration the portal upgrades — and would move — *before* the owning component
190
+ // adopts those children in place. Moving first tears the slot out from under the parent's
191
+ // `hydrateSlot` walk, so the portaled content never gets its reactivity wired (dead bindings
192
+ // until a later CSR rebuild). Deferring the move until `endHydration` lets the parent adopt
193
+ // the server nodes where they sit, then relocate the now-live nodes. See runtime/portal.js.
194
+ let _postHydration = null;
195
+
196
+ /** Run `fn` after first-paint hydration completes (at {@link endHydration}); run it
197
+ * synchronously when not hydrating (a CSR build / SPA navigation). */
198
+ export function afterHydration(fn) {
199
+ if (_hydrating) (_postHydration ??= []).push(fn);
200
+ else fn();
201
+ }
202
+
203
+ // ── the serialized props payload (compiler-driven data hydration) ─────────────
204
+ // SSG/SSR embeds each island's rich props in a `<script type="application/json"
205
+ // id="__afw_h">`, keyed by the host's `data-h` id (see server/ssg-runtime.js). A
206
+ // hydrating component reads its props from here — real JS values (objects, arrays,
207
+ // numbers), not lossy string attributes — so it resumes with correct data, with no flash
208
+ // and no dependence on a parent walk re-applying props. Read once and cached.
209
+ let _payload; // undefined = not yet read; null = none present; else the parsed array
210
+
211
+ function hydrationPayload() {
212
+ if (_payload === undefined) {
213
+ const el = typeof document !== "undefined" ? document.getElementById("__afw_h") : null;
214
+ try {
215
+ _payload = el ? JSON.parse(el.textContent || "[]") : null;
216
+ } catch {
217
+ _payload = null;
218
+ }
219
+ }
220
+ return _payload;
221
+ }
222
+
223
+ /**
224
+ * The rich hydration props recorded for host `el` (keyed by its `data-h` id), or `null`
225
+ * when there is no payload for it — a client-`createElement`'d element on SPA navigation,
226
+ * or a plain CSR build. A hydrate-target component constructor reads this to initialize
227
+ * its prop signals, falling back to attributes/defaults when it returns `null`.
228
+ */
229
+ export function hydrationProps(el) {
230
+ if (!el || typeof el.getAttribute !== "function") return null;
231
+ const data = hydrationPayload();
232
+ const id = data ? el.getAttribute("data-h") : null;
233
+ if (id != null) {
234
+ const entry = data[+id];
235
+ if (entry != null) return entry;
236
+ }
237
+ // An island whose markup was rendered before the route render carries its own props
238
+ // instead of an id into the payload (`inlineHydrationProps`).
239
+ const inline = el.getAttribute("data-hp");
240
+ if (inline == null) return null;
241
+ try {
242
+ return JSON.parse(inline);
243
+ } catch {
244
+ return null;
245
+ }
246
+ }
247
+
248
+ /** Reset the cached payload (tests only — a fresh document between cases). */
249
+ export function __resetHydrationPayload() {
250
+ _payload = undefined;
251
+ }
252
+
253
+ // ── the cursor ────────────────────────────────────────────────────────────────
254
+
255
+ /** A walker over `parent`'s children, positioned at the next node to claim. */
256
+ export function cursor(parent) {
257
+ return { node: parent.firstChild };
258
+ }
259
+
260
+ /** Advance past the next node without claiming it (a static text node between
261
+ * dynamic siblings), returning it. The template only emits a skip for a static
262
+ * `ViewNode::Text`, which the server renders as a real text node; assert that so a
263
+ * cursor misalignment surfaces *here* (with a clear message) instead of downstream at
264
+ * an unrelated claim. Throws {@link HydrationMismatch} on a wrong/absent node. */
265
+ export function skipNode(cur) {
266
+ const n = cur.node;
267
+ if (!n || n.nodeType !== TEXT) {
268
+ throw new HydrationMismatch(`expected static text, found ${describe(n)}`);
269
+ }
270
+ cur.node = n.nextSibling;
271
+ return n;
272
+ }
273
+
274
+ /**
275
+ * Claim the next node as an element, optionally asserting its tag, and advance the
276
+ * cursor past it. Returns the element so the caller can claim its children with a
277
+ * fresh `cursor(el)`. A wrong/absent node throws {@link HydrationMismatch}.
278
+ */
279
+ export function claimElement(cur, tag) {
280
+ const el = cur.node;
281
+ if (!el || el.nodeType !== ELEMENT || (tag && el.tagName.toLowerCase() !== tag.toLowerCase())) {
282
+ throw new HydrationMismatch(`expected <${tag ?? "element"}>, found ${describe(el)}`);
283
+ }
284
+ cur.node = el.nextSibling;
285
+ return el;
286
+ }
287
+
288
+ /**
289
+ * Adopt a `<p>` holding a component (a *recoverable region*), advancing the cursor past
290
+ * its `<!--p]-->` end marker. The compiler cannot see a component's markup, and a block
291
+ * element in it (`<div>`) makes the HTML parser close the `<p>` early, moving the rest of
292
+ * the paragraph out after it. So:
293
+ *
294
+ * - intact (the component rendered inline markup, the common case): `adopt(el)` wires the
295
+ * served paragraph and the marker follows it directly. Nothing is rebuilt.
296
+ * - restructured: `adopt` throws {@link HydrationMismatch}, or nodes the parser moved out
297
+ * sit between the `<p>` and its marker. Everything from the `<p>` up to the marker is
298
+ * removed and `build()` puts a fresh paragraph in its place. One paragraph is rebuilt,
299
+ * not the whole view. (The build warned about it: see `ssgParagraph`.)
300
+ *
301
+ * Comments are never moved by the parser, so the marker always ends the region. Without
302
+ * one there is no boundary to recover inside, and the mismatch propagates as before.
303
+ */
304
+ export function hydrateParagraph(cur, adopt, build) {
305
+ const el = claimElement(cur, "p");
306
+ let intact = true;
307
+ try {
308
+ adopt(el);
309
+ } catch (e) {
310
+ if (!(e instanceof HydrationMismatch)) throw e;
311
+ intact = false;
312
+ }
313
+ let end = el.nextSibling;
314
+ if (intact && isParagraphEnd(end)) {
315
+ cur.node = end.nextSibling;
316
+ return el;
317
+ }
318
+ while (end && !isParagraphEnd(end)) end = end.nextSibling;
319
+ if (!end) throw new HydrationMismatch("expected a <!--p]--> paragraph end marker");
320
+ const parent = end.parentNode;
321
+ for (let n = el; n !== end; ) {
322
+ const next = n.nextSibling;
323
+ parent.removeChild(n);
324
+ n = next;
325
+ }
326
+ // A build, not an adoption: the components in the fresh paragraph must build their
327
+ // own markup rather than look for server nodes that were just removed.
328
+ const fresh = runBuild(build);
329
+ parent.insertBefore(fresh, end);
330
+ cur.node = end.nextSibling;
331
+ return fresh;
332
+ }
333
+
334
+ const isParagraphEnd = (n) => n?.nodeType === 8 && n.data === "p]";
335
+
336
+ /**
337
+ * Claim a dynamic text hole delimited by `<!--$-->…<!--/-->`, returning the text node
338
+ * to bind onto (created empty when the server rendered no value), and advance the
339
+ * cursor past the closing marker. Wire reactivity with `bindText(node, fn)` from
340
+ * dom.js — the binding logic is shared with CSR; only the node is adopted, not built.
341
+ *
342
+ * A text hole may hold a *node*, not text: `{expr}` whose value is a JSX element or an
343
+ * array of them (e.g. a code example stored in a data array and rendered `{ex.body}`).
344
+ * The compiler can't distinguish that statically, so it emits the text path for both; the
345
+ * SSG backend renders such a value's markup inline in the hole. That server content is
346
+ * left in place and recorded on the returned anchor: `bindText` (dom.js) adopts it when
347
+ * the value is the server's `{ __html }` stand-in or a `hydratableNode`, and removes it
348
+ * otherwise, so it never lingers beside a rebuilt copy.
349
+ */
350
+ export function claimText(cur) {
351
+ const start = cur.node;
352
+ if (!start || start.nodeType !== COMMENT || start.data !== HOLE_START) {
353
+ throw new HydrationMismatch(`expected a text-hole marker, found ${describe(start)}`);
354
+ }
355
+ let node = start.nextSibling;
356
+ const content = [];
357
+ while (node && !(node.nodeType === COMMENT && node.data === HOLE_END)) {
358
+ content.push(node);
359
+ node = node.nextSibling;
360
+ }
361
+ const end = node; // the `<!--/-->` marker (or null if the markup is malformed)
362
+ cur.node = end ? end.nextSibling : null;
363
+ if (content.length === 1 && content[0].nodeType === TEXT) return content[0];
364
+ // Empty or node-valued hole (JSX stored as a value): bind onto an empty anchor after
365
+ // the server content. The content stays in place for `bindText` to adopt when the
366
+ // value describes it, and is removed only if the value turns out to be something else.
367
+ const anchor = document.createTextNode("");
368
+ (start.parentNode || document).insertBefore(anchor, end);
369
+ if (content.length) anchor.__afwServerNodes = content;
370
+ return anchor;
371
+ }
372
+
373
+ /**
374
+ * Claim the text node of a **raw text** element (`<textarea>`, `<title>`, `<style>`,
375
+ * `<script>`) — the one place a text hole carries no `<!--$-->…<!--/-->` markers.
376
+ *
377
+ * The tokenizer does not parse markup inside these elements, so a marker comment written
378
+ * in there comes back as literal characters (it would be *visible* in a textarea, and the
379
+ * walk would be hunting for a comment node that is really text). The SSG backend
380
+ * therefore emits the content bare (`ssg::raw_text`), and everything written between the
381
+ * tags — however many static and dynamic pieces — arrives as a single text node. That
382
+ * node is the whole content, so it is claimed from the element rather than off a cursor;
383
+ * the compiler only emits this call for the one-hole shape, which `reparse_hazard` is
384
+ * what guarantees. A server-rendered empty value leaves no text node at all, so one is
385
+ * created to bind onto.
386
+ */
387
+ export function claimRawText(el) {
388
+ const node = el.firstChild;
389
+ if (node) {
390
+ if (node.nodeType !== TEXT) {
391
+ throw new HydrationMismatch(`expected raw text in <${el.tagName.toLowerCase()}>, found ${describe(node)}`);
392
+ }
393
+ return node;
394
+ }
395
+ const text = document.createTextNode("");
396
+ el.appendChild(text);
397
+ return text;
398
+ }
399
+
400
+ /**
401
+ * Adopt a **JSX-value hole** — a `{expr}` whose value is a JSX-value local (`const x =
402
+ * <T/>`), server-rendered in place between the text-hole markers `<!--$-->…<!--/-->`
403
+ * (docs/HYDRATION.md §3.1, 2.1e). Unlike {@link claimText} — which treats a node-valued
404
+ * hole as *stray* server content, strips it, and lets `bindText` rebuild it fresh (a flash,
405
+ * plus a rebuild cascade through any island the node contains) — this *adopts* the server
406
+ * subtree in place: `adoptFn(inner)` claims it off a cursor seeded just after the opening
407
+ * marker, advancing to the closing marker. A JSX-value local is a `const` bound to a literal,
408
+ * so the hole never reactively re-renders — there is no build/swap arm, only the one-shot
409
+ * adopt. Advances `cur` past `<!--/-->`. Throws {@link HydrationMismatch} on a wrong/absent
410
+ * marker.
411
+ */
412
+ export function hydrateHole(cur, adoptFn) {
413
+ const start = cur.node;
414
+ if (!start || start.nodeType !== COMMENT || start.data !== HOLE_START) {
415
+ throw new HydrationMismatch(`expected a text-hole marker, found ${describe(start)}`);
416
+ }
417
+ const inner = { node: start.nextSibling };
418
+ adoptFn(inner); // claims the JSX-value's subtree, advancing `inner` to the end marker
419
+ const end = inner.node;
420
+ if (!end || end.nodeType !== COMMENT || end.data !== HOLE_END) {
421
+ throw new HydrationMismatch(`expected a text-hole end marker, found ${describe(end)}`);
422
+ }
423
+ cur.node = end.nextSibling;
424
+ }
425
+
426
+ /** Claim the `<!--[-->` marker that opens a server-rendered region (list or conditional),
427
+ * advancing the cursor past it. Throws {@link HydrationMismatch} on a wrong/absent node. */
428
+ export function claimRegionStart(cur) {
429
+ const n = cur.node;
430
+ if (!n || n.nodeType !== COMMENT || n.data !== REGION_START) {
431
+ throw new HydrationMismatch(`expected a region start marker, found ${describe(n)}`);
432
+ }
433
+ cur.node = n.nextSibling;
434
+ return n;
435
+ }
436
+
437
+ /** Claim the `<!--]-->` marker that closes a region and return it — it becomes the
438
+ * reconcile/swap anchor (`hydrateList`/`hydrateChild` insert later nodes before it).
439
+ * Advances the cursor past it. Throws {@link HydrationMismatch} on a wrong/absent node. */
440
+ export function claimRegionEnd(cur) {
441
+ const n = cur.node;
442
+ if (!n || n.nodeType !== COMMENT || n.data !== REGION_END) {
443
+ throw new HydrationMismatch(`expected a region end marker, found ${describe(n)}`);
444
+ }
445
+ cur.node = n.nextSibling;
446
+ return n;
447
+ }
448
+
449
+ /** Step a component's own adopt walk past its `{children}` slot — claim the
450
+ * `<!--c[-->`…`<!--c]-->` markers and skip the slotted nodes (the parent owns their
451
+ * reactivity, wired separately by {@link hydrateSlot}), leaving them in place. Advances the
452
+ * cursor past the closing marker. Throws {@link HydrationMismatch} on a missing start marker.
453
+ *
454
+ * Returns the slotted nodes. Adoption never captures light-DOM children the way a CSR build
455
+ * does (they are already in place), but a JSX-value local's `build` fallback still closes over
456
+ * the children local — so codegen seeds that binding from this return value, giving a later
457
+ * reactive rebuild the real nodes to re-slot instead of a `ReferenceError`. */
458
+ export function skipSlot(cur) {
459
+ const start = cur.node;
460
+ const label = slotLabel(start, SLOT_START);
461
+ if (label === null) {
462
+ throw new HydrationMismatch(`expected a children-slot marker, found ${describe(start)}`);
463
+ }
464
+ // Match the close by label, counting depth: the slotted content may itself contain a
465
+ // region from the *same* component (a recursive or forwarding chain), and it very often
466
+ // contains regions from other components. Stopping at the first `<!--c]…-->` in sibling
467
+ // order — as this did before — left the cursor short of the slot and the next claim
468
+ // failed against the end marker (`expected <span>, found comment <!--c]-->`).
469
+ const slotted = [];
470
+ let depth = 0;
471
+ let n = start.nextSibling;
472
+ while (n) {
473
+ if (slotLabel(n, SLOT_END) === label) {
474
+ if (depth === 0) break;
475
+ depth--;
476
+ } else if (slotLabel(n, SLOT_START) === label) {
477
+ depth++;
478
+ }
479
+ slotted.push(n);
480
+ n = n.nextSibling;
481
+ }
482
+ cur.node = n ? n.nextSibling : null; // step past the `<!--c]…-->` end marker
483
+ return slotted;
484
+ }
485
+
486
+ /**
487
+ * The nodes sitting in `host`'s own `{children}` slot in the server DOM, or `null` when the
488
+ * host has no slot markers. Non-destructive — the nodes stay where they are.
489
+ *
490
+ * This is the rescue path for a component that *can't* adopt (a view shape the hydrate
491
+ * backend doesn't support yet, or an adopt walk that hit a mismatch and is recovering). Such
492
+ * a component rebuilds via CSR, and its build captures `this.childNodes` as the call-site
493
+ * children — but on a server-rendered host those children are the *rendered view*, not the
494
+ * slotted content. Clearing first and capturing after (what the generated code used to do)
495
+ * therefore didn't just rebuild the component, it **lost the page content inside it**. Pulling
496
+ * the slot region out first gives the rebuild the real children to re-slot: still a flash,
497
+ * but nothing disappears.
498
+ */
499
+ export function slotChildren(host) {
500
+ const start = findSlotStart(host);
501
+ if (!start) return null;
502
+ const label = slotLabel(start, SLOT_START);
503
+ const nodes = [];
504
+ let depth = 0;
505
+ for (let n = start.nextSibling; n; n = n.nextSibling) {
506
+ if (slotLabel(n, SLOT_END) === label) {
507
+ if (depth === 0) break;
508
+ depth--;
509
+ } else if (slotLabel(n, SLOT_START) === label) {
510
+ depth++;
511
+ }
512
+ nodes.push(n);
513
+ }
514
+ return nodes;
515
+ }
516
+
517
+ /**
518
+ * Adopt a component's slotted children — the *parent's* JSX, server-rendered inside the
519
+ * component host at its `{children}` slot. The parent owns their reactivity but the
520
+ * component decides where they sit, so the parent locates the slot by its `<!--c[-->` marker
521
+ * within `host` and adopts from the first slotted node via `adoptFn(cursor)`. Independent of
522
+ * when the component upgrades: the markers are static server DOM and adoption only *wires*
523
+ * (never moves) nodes, so it commutes with the component's own `skipSlot`. A missing marker
524
+ * (a rebuilt component, or no children) is a no-op.
525
+ */
526
+ export function hydrateSlot(host, adoptFn) {
527
+ const start = findSlotStart(host);
528
+ if (start) adoptFn({ node: start.nextSibling });
529
+ }
530
+
531
+ /**
532
+ * The `<!--c[…-->` marker that belongs to `host` itself — the one labeled with its tag.
533
+ *
534
+ * Position alone can't identify it. A component renders chrome around its slot, and any
535
+ * component nested in that chrome emits slot markers of its own that come *first* in tree
536
+ * order (`<DocsLayout>` framed: `<Navbar>`'s slotted `<Link>`s precede the prose slot). And a
537
+ * component that forwards `{children}` into another (`<Card>` → `<Link>{children}</Link>`)
538
+ * emits its own marker *inside* that component's host, so "the first marker not nested in
539
+ * another component" finds the wrong one too — that shape adopted the Card's children against
540
+ * Link's region (`expected a children-slot marker, found <span>`) and lost them.
541
+ *
542
+ * Matching the label to `host.tagName` settles both. The only remaining ambiguity is a
543
+ * component nested within itself (a recursive component that also takes children): the host's
544
+ * own marker always precedes any same-tag marker inside its slot content, so first-in-tree-order
545
+ * among label matches is correct — except for a same-tag host in the *chrome* before the slot,
546
+ * which the "no intervening component host" preference still resolves.
547
+ */
548
+ function findSlotStart(host) {
549
+ const tag = host.tagName ? host.tagName.toLowerCase() : "";
550
+ let fallback = null;
551
+ const walker = document.createTreeWalker(host, 128 /* NodeFilter.SHOW_COMMENT */);
552
+ let n;
553
+ while ((n = walker.nextNode())) {
554
+ const label = slotLabel(n, SLOT_START);
555
+ // An **unlabeled** marker (`<!--c[-->`, empty label) comes from an older compiler that
556
+ // predates the labeling. Treat it as matching any host and fall through to the positional
557
+ // heuristic below, rather than matching nothing: this runtime can be installed alongside a
558
+ // compiler that is a release behind (`@opentf/afw-cli` pins `@opentf/afw-compiler`), and a
559
+ // strict comparison would make `hydrateSlot` a silent no-op for every component — every
560
+ // slot's reactivity dead on first paint, with nothing logged. Skew should degrade to the
561
+ // old behavior, not to a worse one.
562
+ if (label === null || (label !== "" && label !== tag)) continue;
563
+ if (fallback === null) fallback = n;
564
+ let nested = false;
565
+ for (let p = n.parentNode; p && p !== host; p = p.parentNode) {
566
+ // A same-tag host inside the chrome would emit an identically labeled marker.
567
+ if (p.nodeType === ELEMENT && p.tagName.includes("-")) {
568
+ nested = true;
569
+ break;
570
+ }
571
+ }
572
+ if (!nested) return n;
573
+ }
574
+ return fallback;
575
+ }
576
+
577
+ /** A short human description of a node for mismatch messages. */
578
+ function describe(node) {
579
+ if (!node) return "nothing";
580
+ if (node.nodeType === ELEMENT) return `<${node.tagName.toLowerCase()}>`;
581
+ if (node.nodeType === TEXT) return `text "${(node.data || "").slice(0, 20)}"`;
582
+ if (node.nodeType === COMMENT) return `comment <!--${node.data}-->`;
583
+ return `node(${node.nodeType})`;
584
+ }
@@ -0,0 +1,14 @@
1
+ export * from "./dom.js";
2
+ export * from "./events.js";
3
+ export * from "./mount.js";
4
+ export * from "./hydrate.js";
5
+ export * from "./lifecycle.js";
6
+ export * from "./router.js";
7
+ export * from "./route-data.js";
8
+ export * from "./resource.js";
9
+ export * from "./context.js";
10
+ export * from "./error-boundary.js";
11
+ export * from "./portal.js";
12
+ export * from "./raw-html.js";
13
+ export * from "./code-block.js";
14
+ export * from "./clipboard.js";
@@ -0,0 +1,24 @@
1
+ // Built-in custom elements self-register on import. They're used in JSX as *tags*
2
+ // (`<Portal>` → `afw-internal-portal`), so their bindings are never referenced and a plain
3
+ // re-export would be tree-shaken away (the element never registers). Bare imports
4
+ // force the registration side effect to be retained.
5
+ import "./context.js";
6
+ import "./error-boundary.js";
7
+ import "./portal.js";
8
+ import "./raw-html.js";
9
+ import "./code-block.js";
10
+
11
+ export * from "./dom.js";
12
+ export * from "./events.js";
13
+ export * from "./mount.js";
14
+ export * from "./hydrate.js";
15
+ export * from "./lifecycle.js";
16
+ export * from "./router.js";
17
+ export * from "./route-data.js";
18
+ export * from "./resource.js";
19
+ export * from "./context.js";
20
+ export * from "./error-boundary.js";
21
+ export * from "./portal.js";
22
+ export * from "./raw-html.js";
23
+ export * from "./code-block.js";
24
+ export * from "./clipboard.js";
@@ -0,0 +1,6 @@
1
+ /** Compiler lifecycle macros; callbacks are wired to the component host. */
2
+ export function onMount(callback: () => void | (() => void)): void;
3
+ export function onCleanup(callback: () => void): void;
4
+ export function onResize(callback: (entry: ResizeObserverEntry) => void): void;
5
+ export function onMediaQuery(query: string, callback: (matches: boolean, event: MediaQueryListEvent | undefined) => void): void;
6
+ export function onVisibilityChange(callback: (visible: boolean, entry: IntersectionObserverEntry) => void): void;
@@ -0,0 +1,14 @@
1
+ // Lifecycle hooks. `onMount`/`onCleanup`/`onResize`/`onMediaQuery`/
2
+ // `onVisibilityChange` are compiler macros: the OpenTF compiler collects their
3
+ // callbacks and wires them into a component's connect/disconnect (Custom
4
+ // Element) or a page/layout factory's `__lifecycle` record — the DOM hooks
5
+ // desugar to ResizeObserver/IntersectionObserver/matchMedia setup with
6
+ // automatic teardown. These exports exist so the source-level `import {
7
+ // onMount } from "@opentf/afw"` resolves, and so calling them outside a
8
+ // compiled component (or during SSR) is a safe no-op rather than a crash.
9
+
10
+ export function onMount() {}
11
+ export function onCleanup() {}
12
+ export function onResize() {}
13
+ export function onMediaQuery() {}
14
+ export function onVisibilityChange() {}
@@ -0,0 +1,20 @@
1
+ /** Build a factory view and attach its reactive scope to the node's teardown. */
2
+ export function buildScopedView(view: any): any;
3
+ /**
4
+ * Mount a view into `target`. `view` is either a factory function returning a
5
+ * DOM node or an already-built node. Returns the mounted node.
6
+ *
7
+ * Page/layout factories may attach a `__lifecycle` record (`{ mounts, cleanups }`)
8
+ * built from `onMount`/`onCleanup`. After insertion we run the `onMount` callbacks,
9
+ * collecting any returned disposer into `cleanups` so a caller (e.g. the router)
10
+ * can tear the page down on navigation.
11
+ *
12
+ * A factory build runs inside a reactive `scope`, and the scope's disposer joins
13
+ * the cleanups: teardown (router navigation) stops every binding effect the page
14
+ * created, so a replaced page's subscriptions don't outlive it.
15
+ */
16
+ export function mount(view: any, target: any): any;
17
+ /** Run a node's `onMount` callbacks, collecting returned disposers as cleanups. */
18
+ export function runMount(node: any): void;
19
+ /** Run a node's collected `onCleanup`/disposer teardown (idempotent). */
20
+ export function runCleanup(node: any): void;