Skip to content

Commit 57ec008

Browse files
refactor(core): settle the four remaining preview-vs-render divergences (#3097)
## Why #3094 fixed one way the mount and render paths disagreed, and added the gate that catches disagreement. It deliberately left the rest. Four divergences are still live. Each one means a composition assembles differently depending on whether it is being previewed or rendered — the same class of defect that shipped three catalog components unstyled, just with smaller blast radii. ## How Both paths now derive root discovery, scope identity, asset sources and order, hoisted links, variable carriers and nested-host enumeration from the shared module #3094 introduced. Each keeps its own I/O, which is where they genuinely differ. The compiler's local depth cap and root lookup and the runtime's three pre-filtered head parameters are gone; the runtime hands over the head node and lets the module decide what comes out of it. Four behaviour changes, each stated by what actually differs rather than by the edit: **Inline `<head>` scripts.** The compiler looped head scripts with a `src` branch and no `else`, so an inline one was silently discarded on render while the runtime ran it. That is losing code, not holding a convention — the runtime's answer wins. Head and content scripts now share one loop, head first, order preserved. A non-templated sub-composition with an inline head script went from **0 collected scripts to 1**, wrapped, body intact. **`<link>` hoisting.** Conditional on render, unconditional on mount, so a templated sub-composition's webfont link was dropped in video and kept in preview. Hoisting is the superset and matches what the author declared. A templated composition with a stylesheet link went from **no external links to that link**. The parity fixture that previously recorded this shape as a known exclusion now gates it. **Anonymous hosts.** With a host naming no id, the compiler fell back to the first declared composition and scoped to it; the mount left the content unflattened and injected its stylesheet into the host `<head>` **unscoped**, so a composition's CSS leaked into whatever mounted it. The compiler's answer wins. The injected rule went from a bare `.label { … }` to `[data-composition-id="scoped-text"] .label { … }`. **Scope ids.** The compiler splits the CSS scope id from the script composition id; they differ only when a host names an id the content does not declare, and there the scripts follow the declared id so their self-referencing queries resolve. The runtime used one for both. The split wins: a host naming `captions-comp` over content declaring `captions` now emits scripts bound to `captions` while its CSS still scopes to `captions-comp`. ## Test plan - [x] Unit tests added/updated - [x] Manual testing performed - [ ] Documentation updated (if applicable) Core 1694 passing, producer 574 passing, the parity contract now gates the two divergences it can observe (the other two carry no contract field, so they are gated by unit tests naming the exact before/after). Lint 0, `typecheck:runtime` and the runtime preview guards clean, package cycles unchanged. Characterization-first: both suites were run and recorded green before any decision moved, so a behavioural drift would surface as a red test rather than a silent difference. **One assertion changed, deliberately.** A runtime test asserted that an anonymous host's composition is *not* flattened, and documented that as intentional. That premise is now false. What the test actually cared about — the root and its content present under the host — still holds and is still asserted; the "not flattened" claim flipped, and the test now also asserts the scoping that was missing. ## Not covered The variable-carrier divergence and its `TODO(template-var-carriers)` are untouched by design, as is recursion on the mount path — a sub-composition containing its own `data-composition-src` is still silently dropped in live preview. Both are behaviour changes with their own units, and both are now one-line-ish changes because the shared module already reports what they need. `runtimeScopeCompositionId` no longer falls back to the authored scope id. This is a functional change beyond the four above, surfaced in review: for an anonymous host with authored variable defaults, the runtime previously stashed them under the declared id, and now does not. It removes a runtime-vs-compiler divergence in the correct direction — the runtime was doing work the compiler never did, and the compiler is authoritative for a shipped composition — but a caller relying on runtime-only variable exposure loses it. The three copies each of the flattened-root helper and the id assignment are left alone: they look mergeable and are not cheaply, and they touch the instancing contract the pixel harness guards. ## Worth knowing The parity test's compiler arms import core's **built dist** while the mount arm imports source, so core must be rebuilt before that lane means anything after a compiler change. Skipping it produces a phantom divergence that looks exactly like a real one.
1 parent b57dc13 commit 57ec008

7 files changed

Lines changed: 300 additions & 182 deletions

File tree

‎packages/core/src/compiler/compositionAssembly.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,15 +206,14 @@ describe("enumerateNestedCompositionHosts", () => {
206206
return host;
207207
};
208208

209-
it("enumerates nested hosts with their ancestry", () => {
209+
it("enumerates every nested host in document order", () => {
210210
const host = assembled(
211211
`<div data-composition-src="child-a.html"></div><div data-composition-src="child-b.html"></div>`,
212212
);
213213

214214
const { hosts, skipped } = enumerateNestedCompositionHosts(host, ["outer.html"]);
215215

216216
expect(hosts.map((entry) => entry.src)).toEqual(["child-a.html", "child-b.html"]);
217-
expect(hosts[0]?.ancestry).toEqual(["outer.html", "child-a.html"]);
218217
expect(hosts[0]?.host.getAttribute("data-composition-src")).toBe("child-a.html");
219218
expect(skipped).toEqual([]);
220219
});

‎packages/core/src/compiler/compositionAssembly.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,6 @@ export type NestedHostSkipReason = "circular composition reference" | "nesting d
205205
export interface NestedCompositionHost<TElement> {
206206
host: TElement;
207207
src: string;
208-
/**
209-
* The chain of `data-composition-src` values from the outermost composition
210-
* down to AND INCLUDING this host's own `src`. Pass it straight back into
211-
* `enumerateNestedCompositionHosts` when this host is itself assembled.
212-
*/
213-
ancestry: string[];
214208
}
215209

216210
export interface NestedCompositionHosts<TElement> {
@@ -243,7 +237,7 @@ export function enumerateNestedCompositionHosts<TElement extends AssemblyAttribu
243237
skipped.push({ src, reason: "nesting depth exceeded" });
244238
continue;
245239
}
246-
hosts.push({ host: nestedHost, src, ancestry: [...ancestry, src] });
240+
hosts.push({ host: nestedHost, src });
247241
}
248242

249243
return { hosts, skipped };

‎packages/core/src/compiler/inlineSubCompositions.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,61 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
286286
});
287287
});
288288

289+
it("collects an inline <head> script instead of discarding it", () => {
290+
// The <head> loop had a `src` branch and no else, so an inline <head>
291+
// script was silently dropped on render while the mount path executed it.
292+
const subCompWithHeadScript = `<!doctype html>
293+
<html><head>
294+
<script>window.__headScriptRan = true;</script>
295+
</head><body>
296+
<div data-composition-id="intro" data-width="1920" data-height="1080"><span>Hi</span></div>
297+
</body></html>`;
298+
299+
const document = makeHostDocument("intro");
300+
const host = document.querySelector('[data-composition-src="intro.html"]')!;
301+
302+
const result = inlineSubCompositions(document, [host], {
303+
resolveHtml: () => subCompWithHeadScript,
304+
parseHtml: (html) => parseHTML(html).document,
305+
});
306+
307+
expect(result.scripts.join("\n")).toContain("window.__headScriptRan = true;");
308+
expect(result.scriptItems).toContainEqual({
309+
kind: "inline",
310+
content: expect.stringContaining("window.__headScriptRan = true;"),
311+
});
312+
});
313+
314+
it("hoists a <link> from a TEMPLATED sub-composition's head", () => {
315+
// Hoisting used to be gated on the composition being non-templated, so a
316+
// templated composition's webfont link was kept in preview (the mount path
317+
// hoists unconditionally) and dropped from the render.
318+
const templatedSubCompWithLink = `<!doctype html>
319+
<html><head>
320+
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat">
321+
</head><body>
322+
<template id="intro-template">
323+
<div data-composition-id="intro" data-width="1920" data-height="1080"><span>Hi</span></div>
324+
</template>
325+
</body></html>`;
326+
327+
const document = makeHostDocument("intro");
328+
const host = document.querySelector('[data-composition-src="intro.html"]')!;
329+
330+
const result = inlineSubCompositions(document, [host], {
331+
resolveHtml: () => templatedSubCompWithLink,
332+
parseHtml: (html) => parseHTML(html).document,
333+
});
334+
335+
expect(result.externalLinks).toEqual([
336+
{
337+
href: "https://fonts.googleapis.com/css2?family=Montserrat",
338+
rel: "stylesheet",
339+
crossorigin: undefined,
340+
},
341+
]);
342+
});
343+
289344
it("deduplicates link hrefs across multiple sub-compositions", () => {
290345
const subComp = `<!doctype html>
291346
<html><head>

‎packages/core/src/compiler/inlineSubCompositions.ts‎

Lines changed: 56 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ import {
1515
rewriteInlineStyleAssetUrls,
1616
type AssetExists,
1717
} from "./rewriteSubCompPaths";
18-
import { queryByAttr } from "../utils/cssSelector";
1918
import {
2019
scopeCssToComposition,
2120
wrapInlineScriptWithErrorBoundary,
2221
wrapScopedCompositionScript,
2322
} from "./compositionScoping";
2423
import { checkSubCompositionUsability } from "@hyperframes/parsers/sub-composition-validity";
24+
import { enumerateNestedCompositionHosts, planCompositionAssembly } from "./compositionAssembly";
2525

2626
// ---------------------------------------------------------------------------
2727
// Public interface
@@ -141,8 +141,6 @@ function defaultBuildScopeSelector(compId: string): string {
141141
return `[data-composition-id="${escaped}"]`;
142142
}
143143

144-
const MAX_SUB_COMPOSITION_DEPTH = 20;
145-
146144
// ---------------------------------------------------------------------------
147145
// Core implementation
148146
// ---------------------------------------------------------------------------
@@ -244,33 +242,33 @@ export function inlineSubCompositions(
244242
continue;
245243
}
246244

247-
// Keep structural flattening tied to an exact mount-id match. A template
248-
// may intentionally use a different local id (for example, a
249-
// `captions-comp` host mounting a `captions` template); flattening that
250-
// fallback root changes the compiled DOM and can invalidate selectors and
251-
// regression goldens. Discover it separately so script timeline
252-
// registration can still map the authored id onto the runtime mount id.
253-
const innerRoot = compId
254-
? queryByAttr(contentDoc, "data-composition-id", compId)
255-
: contentDoc.querySelector("[data-composition-id]");
256-
const authoredCompositionRoot = innerRoot ?? contentDoc.querySelector("[data-composition-id]");
257-
const inferredCompId =
258-
authoredCompositionRoot?.getAttribute("data-composition-id")?.trim() || "";
259-
const authoredRootId = innerRoot?.getAttribute("id")?.trim() || null;
260-
const scopeCompId = compId || inferredCompId;
261-
const scriptCompositionId = inferredCompId || scopeCompId;
245+
// Which node is the composition root, which id its CSS scopes to, which
246+
// id its scripts scope to, where its assets come from and in what order —
247+
// every one of those is decided by the shared assembly module, so the mount
248+
// path in runtime/compositionLoader.ts decides them the same way.
249+
const plan = planCompositionAssembly<Element>({
250+
contentNode: contentDoc,
251+
head: compDoc.head,
252+
documentElement: compDoc.documentElement,
253+
hasTemplate: Boolean(contentRoot),
254+
compositionId: compId,
255+
});
256+
const innerRoot = plan.innerRoot;
257+
const authoredRootId = plan.authoredRootId;
258+
const scopeCompId = plan.authoredCompositionId || "";
259+
const scriptCompositionId = plan.scriptCompositionId || "";
262260
const runtimeScope = runtimeCompId ? buildScopeSelector(runtimeCompId) : "";
263261

264262
// Variable merging (bundler feature). Read declared defaults from the
265263
// document element (full-document sub-comps) AND the inner composition root
266264
// (template/fragment sub-comps store their schema on the root div, not a
267265
// synthetic <html>), then let per-instance host values override.
268266
if (readVariableDefaults && parseHostVariables && runtimeCompId) {
269-
const mergedVariables = {
270-
...readVariableDefaults(compDoc.documentElement),
271-
...(innerRoot ? readVariableDefaults(innerRoot) : {}),
272-
...parseHostVariables(hostEl),
273-
};
267+
const mergedVariables: Record<string, unknown> = {};
268+
for (const carrier of plan.variableDefaultCarriers) {
269+
Object.assign(mergedVariables, readVariableDefaults(carrier));
270+
}
271+
Object.assign(mergedVariables, parseHostVariables(hostEl));
274272
if (Object.keys(mergedVariables).length > 0) {
275273
variablesByComp[runtimeCompId] = mergedVariables;
276274
}
@@ -295,47 +293,35 @@ export function inlineSubCompositions(
295293
: css;
296294
};
297295

298-
// When a sub-composition is a full HTML document (no <template>), styles
299-
// and scripts in <head> are not part of contentDoc (which only has body
300-
// content). Extract them so backgrounds, positioning, fonts, and library
301-
// scripts (e.g. GSAP CDN) are not silently dropped.
302-
if (!contentRoot && compDoc.head) {
303-
for (const s of [...compDoc.head.querySelectorAll("style")]) {
304-
styles.push(scopeSubStyle(s.textContent || ""));
305-
}
306-
for (const s of [...compDoc.head.querySelectorAll("script")]) {
307-
const externalSrc = resolveSubAssetPath(s.getAttribute("src"));
308-
if (externalSrc) {
309-
if (!externalScriptSrcs.includes(externalSrc)) {
310-
externalScriptSrcs.push(externalSrc);
311-
}
312-
scriptItems.push({ kind: "external", src: externalSrc });
313-
}
314-
}
315-
for (const link of [
316-
...compDoc.head.querySelectorAll('link[rel="stylesheet"], link[rel="preconnect"]'),
317-
]) {
318-
const href = resolveSubAssetPath(link.getAttribute("href"));
319-
if (href && !seenLinkHrefs.has(href)) {
320-
seenLinkHrefs.add(href);
321-
const rel = (link.getAttribute("rel") || "").trim();
322-
const crossorigin = link.hasAttribute("crossorigin")
323-
? link.getAttribute("crossorigin") || ""
324-
: undefined;
325-
externalLinks.push({ href, rel, crossorigin });
326-
}
296+
// <link> hoisting is unconditional. A templated sub-composition's webfont
297+
// link is as load-bearing as a non-templated one's, and the mount path has
298+
// always hoisted both; gating this on `!contentRoot` dropped a templated
299+
// composition's font from the render while preview kept it.
300+
for (const link of plan.linkSources) {
301+
const href = resolveSubAssetPath(link.getAttribute("href"));
302+
if (href && !seenLinkHrefs.has(href)) {
303+
seenLinkHrefs.add(href);
304+
const rel = (link.getAttribute("rel") || "").trim();
305+
const crossorigin = link.hasAttribute("crossorigin")
306+
? link.getAttribute("crossorigin") || ""
307+
: undefined;
308+
externalLinks.push({ href, rel, crossorigin });
327309
}
328310
}
329311

330-
// Extract styles from content
331-
for (const s of [...contentDoc.querySelectorAll("style")]) {
332-
styles.push(scopeSubStyle(s.textContent || ""));
333-
s.remove();
312+
// Head-sourced assets come first: a non-templated sub-composition's <head>
313+
// carries its backgrounds, positioning and fonts, and a <head> library tag
314+
// (GSAP from a CDN) has to run before the content scripts calling into it.
315+
for (const styleEl of plan.styleSources) {
316+
styles.push(scopeSubStyle(styleEl.textContent || ""));
317+
styleEl.remove();
334318
}
335319

336-
// Extract scripts from content
337-
for (const s of [...contentDoc.querySelectorAll("script")]) {
338-
const externalSrc = resolveSubAssetPath(s.getAttribute("src"));
320+
// Head- and content-sourced scripts take the same branch. The head loop
321+
// used to handle only `src`, so an inline <head> script was silently
322+
// discarded on render while the mount path executed it.
323+
for (const scriptEl of plan.scriptSources) {
324+
const externalSrc = resolveSubAssetPath(scriptEl.getAttribute("src"));
339325
if (externalSrc) {
340326
if (!externalScriptSrcs.includes(externalSrc)) {
341327
externalScriptSrcs.push(externalSrc);
@@ -344,18 +330,18 @@ export function inlineSubCompositions(
344330
} else {
345331
const wrappedScript = scriptCompositionId
346332
? wrapScopedCompositionScript(
347-
s.textContent || "",
333+
scriptEl.textContent || "",
348334
scriptCompositionId,
349335
scriptErrorLabel,
350336
runtimeScope || undefined,
351337
runtimeCompId || scopeCompId || scriptCompositionId,
352338
authoredRootId,
353339
)
354-
: wrapInlineScriptWithErrorBoundary(s.textContent || "", scriptErrorLabel);
340+
: wrapInlineScriptWithErrorBoundary(scriptEl.textContent || "", scriptErrorLabel);
355341
scripts.push(wrappedScript);
356342
scriptItems.push({ kind: "inline", content: wrappedScript });
357343
}
358-
s.remove();
344+
scriptEl.remove();
359345
}
360346

361347
// Rewrite relative asset paths before inlining so ../foo.svg from
@@ -408,15 +394,15 @@ export function inlineSubCompositions(
408394
for (const child of [...innerRoot.querySelectorAll("style, script")]) child.remove();
409395
if (flattenInnerRoot) {
410396
const prepared = flattenInnerRoot(innerRoot);
411-
if (!compId && inferredCompId) {
397+
if (!compId && scopeCompId) {
412398
// Anonymous host: flattenInnerRoot strips data-composition-id,
413399
// assuming the host already carries the composition's identity.
414400
// When the host has none, nothing in the render DOM matches the
415401
// composition's own root-styling CSS or self-referencing scripts
416402
// (e.g. document.querySelector('[data-composition-id="X"]')).
417403
// Restore it on the wrapper so both keep resolving, same as
418404
// before flattening preserved it via outerHTML.
419-
prepared.setAttribute("data-composition-id", inferredCompId);
405+
prepared.setAttribute("data-composition-id", scopeCompId);
420406
}
421407
hostEl.innerHTML = prepared.outerHTML || "";
422408
} else {
@@ -441,18 +427,12 @@ export function inlineSubCompositions(
441427
hostEl.removeAttribute("data-composition-src");
442428

443429
const nestedAncestry = [...ancestry, src];
444-
for (const nestedHost of [...hostEl.querySelectorAll("[data-composition-src]")]) {
445-
const nestedSrc = nestedHost.getAttribute("data-composition-src");
446-
if (!nestedSrc) continue;
447-
if (nestedAncestry.includes(nestedSrc)) {
448-
onMissingComposition?.(nestedSrc, "circular composition reference");
449-
continue;
450-
}
451-
if (nestedAncestry.length >= MAX_SUB_COMPOSITION_DEPTH) {
452-
onMissingComposition?.(nestedSrc, "nesting depth exceeded");
453-
continue;
454-
}
455-
queue.push({ element: nestedHost, ancestry: nestedAncestry });
430+
const nested = enumerateNestedCompositionHosts(hostEl, nestedAncestry);
431+
for (const skipped of nested.skipped) {
432+
onMissingComposition?.(skipped.src, skipped.reason);
433+
}
434+
for (const nestedHost of nested.hosts) {
435+
queue.push({ element: nestedHost.host, ancestry: nestedAncestry });
456436
}
457437
}
458438

0 commit comments

Comments
 (0)