Skip to content

Write HTML. Render video. Built for agents.

31.2 KB
Raw Blame
import { getSvgSelectorAliasesScript } from "../generated/svg-selector-aliases-inline";
import postcss, { type AtRule, type Node, type Rule } from "postcss";
import { escapeCssIdentifier, replaceSelectorIdTokens } from "./selectorIdTokens";
import { SCENE_PARTS_META } from "../sceneParts";

const AUTHORED_ROOT_ID_ATTR = "data-hf-authored-id";
const INNER_ROOT_ATTR = "data-hf-inner-root";

function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function escapeCssAttributeValue(value: string): string {
  return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

function getAuthoredRootIdSelectorForms(authoredRootId: string): string[] {
  const trimmed = authoredRootId.trim();
  if (!trimmed) return [];
  return Array.from(new Set([trimmed, escapeCssIdentifier(trimmed)])).filter(Boolean);
}

function replaceAuthoredRootIdSelectors(
  selector: string,
  authoredRootId: string,
  replacement: string,
): string {
  const forms = getAuthoredRootIdSelectorForms(authoredRootId);
  return replaceSelectorIdTokens(selector, forms, () => replacement);
}

function normalizeAuthoredRootIdSelector(selector: string, authoredRootId?: string | null): string {
  const trimmed = authoredRootId?.trim();
  if (!trimmed) return selector;
  return replaceAuthoredRootIdSelectors(
    selector,
    trimmed,
    `[${AUTHORED_ROOT_ID_ATTR}="${escapeCssAttributeValue(trimmed)}"]`,
  );
}

/** The composition's own box: the host when it renders content directly, or the
 *  flattened inner root when one is preserved below the host. Used both for a
 *  bare composition-root selector and for remapped document-level selectors.
 *  Relies on `:has()` (Chrome 105 / Safari 15.4 / Firefox 121) — an existing
 *  baseline for the bare-root case, noted here for new callers. */
function compositionBoxSelector(scope: string): string {
  return `${scope}:not(:has([${INNER_ROOT_ATTR}])), ${scope} > [${INNER_ROOT_ATTR}]`;
}

function scopeSelector(
  selector: string,
  scope: string,
  compositionId: string,
  authoredRootId?: string | null,
  compoundAuthoredRoot?: boolean,
  scopeRootSelectors?: boolean,
): string {
  const selectorWithoutAuthoredRootId = normalizeAuthoredRootIdSelector(selector, authoredRootId);
  const selectorWithoutRootTiming = normalizeCompositionRootSelector(
    selectorWithoutAuthoredRootId,
    scope,
    compositionId,
  );
  const trimmed = selectorWithoutRootTiming.trim();
  if (!trimmed) return selector;
  if (trimmed === "*") return selector;
  if (/^(html|body|:root)$/i.test(trimmed)) {
    // A mounted/inlined sub-comp's document-level selectors must not style the
    // PARENT (a sub-comp `body { width/height/overflow }` would clobber the host
    // <body> and clip the preview/render). Remap to the comp's own box. A
    // top-level compile (scopeRootSelectors falsy) legitimately owns the document.
    //
    // Coverage is intentionally BARE-only: compound forms (`body.dark`,
    // `body[data-theme]`, `body:hover`, `html body`, `:root .x`) fall through to
    // general scoping below. That is byte-identical to pre-fix behavior — those
    // selectors never matched the parent <body> (it has no data-composition-id),
    // so there was no clobber to fix. The bare forms are the ones that actually
    // caused the parent-body clobber, which is what this remap targets.
    return scopeRootSelectors ? compositionBoxSelector(scope) : selector;
  }
  // Authored-root patterns must follow the renamed instance, not require a nested root.
  const compositionIdPattern = new RegExp(
    `\\[\\s*data-composition-id\\s*[\\^\\*\\$]?=\\s*(["'])${escapeRegExp(compositionId)}\\1\\s*\\]`,
    "g",
  );
  if (compositionIdPattern.test(trimmed)) {
    const isRootBoxSelector = trimmed.replace(compositionIdPattern, "").trim() === "";
    if (isRootBoxSelector) {
      // A bare root selector styles the composition's own box (flex/grid/
      // position/padding). When flattenInnerRoot preserves the authored root
      // as a wrapper below `scope` (see prepareFlattenedInnerRoot), that
      // wrapper is the element real children are laid out in, not `scope`
      // itself, so the box styling must land there instead. It must land on
      // exactly one of the two: applying it to both compounds any additive
      // property (padding, margin, non-zero transform) since the wrapper
      // sits nested inside the host and would inherit the effect twice.
      return compositionBoxSelector(scope);
    }
    return selectorWithoutRootTiming.replace(compositionIdPattern, scope);
  }
  const leading = selectorWithoutRootTiming.match(/^\s*/)?.[0] ?? "";
  const trailing = selectorWithoutRootTiming.match(/\s*$/)?.[0] ?? "";
  if (compoundAuthoredRoot) {
    const authoredRootAttr = authoredRootId
      ? `[${AUTHORED_ROOT_ID_ATTR}="${escapeCssAttributeValue(authoredRootId)}"]`
      : null;
    if (authoredRootAttr && trimmed.startsWith(authoredRootAttr)) {
      const rest = trimmed.slice(authoredRootAttr.length);
      return `${leading}${scope}${authoredRootAttr}${rest}${trailing}`;
    }
  }
  return `${leading}${scope} ${trimmed}${trailing}`;
}

function normalizeCompositionRootSelector(
  selector: string,
  scope: string,
  compositionId: string,
): string {
  const quotedCompId = escapeRegExp(compositionId);
  const compAttr = String.raw`\[\s*data-composition-id\s*=\s*(?:"${quotedCompId}"|'${quotedCompId}')\s*\]`;
  const timingAttr = String.raw`\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`;
  return selector
    .replace(new RegExp(`${compAttr}(?:${timingAttr})+`, "g"), scope)
    .replace(new RegExp(`(?:${timingAttr})+${compAttr}`, "g"), scope);
}

const GLOBAL_AT_RULES = new Set(["keyframes", "-webkit-keyframes", "font-face"]);

function isAtRuleNode(node: Node["parent"]): node is AtRule {
  return node?.type === "atrule";
}

function isInsideGlobalAtRule(rule: Rule): boolean {
  let current: Node["parent"] = rule.parent;
  while (current) {
    if (isAtRuleNode(current) && GLOBAL_AT_RULES.has(current.name.toLowerCase())) {
      return true;
    }
    current = current.parent;
  }
  return false;
}

/**
 * A Rule nested inside another Rule (CSS Nesting Module Level 1) already
 * inherits scope from its parent's `&` prefix at match time — re-applying
 * the composition scope to the nested selector produces
 * `<scope> <scope> .child`, which matches nothing when the composition
 * root only appears once in the DOM. Only top-level rules get scoped;
 * their nested descendants inherit the scope naturally via CSS nesting.
 * See #2721 for the reproducer that motivated this.
 */
function isNestedInsideAnotherRule(rule: Rule): boolean {
  let current: Node["parent"] = rule.parent;
  while (current) {
    if (current.type === "rule") return true;
    current = current.parent;
  }
  return false;
}

type ScopeOptions = { compoundAuthoredRoot?: boolean; scopeRootSelectors?: boolean };

export function scopeCssToComposition(
  css: string,
  compositionId: string,
  scopeSelectorOverride?: string,
  authoredRootId?: string | null,
  options?: ScopeOptions,
): string {
  const trimmedCompositionId = compositionId.trim();
  if (!css || !trimmedCompositionId) return css;
  const scope =
    scopeSelectorOverride ||
    `[data-composition-id="${escapeCssAttributeValue(trimmedCompositionId)}"]`;
  const root = parseCss(css);
  return root ? scopeParsedCss(root, scope, trimmedCompositionId, authoredRootId, options) : "";
}

function parseCss(css: string): postcss.Root | null {
  try {
    return postcss.parse(css);
  } catch {
    return null;
  }
}

function forEachScopedRule(root: postcss.Root, visit: (rule: Rule) => void): void {
  root.walkRules((rule) => {
    if (isInsideGlobalAtRule(rule)) return;
    if (isNestedInsideAnotherRule(rule)) return;
    visit(rule);
  });
}

function scopeParsedCss(
  root: postcss.Root,
  scope: string,
  compositionId: string,
  authoredRootId: string | null | undefined,
  options: ScopeOptions | undefined,
): string {
  forEachScopedRule(root, (rule) => {
    rule.selectors = rule.selectors.map((selector) =>
      scopeSelector(
        selector,
        scope,
        compositionId,
        authoredRootId,
        options?.compoundAuthoredRoot,
        options?.scopeRootSelectors,
      ),
    );
  });
  return root.toResult({ map: false }).css;
}

// Shaped like every scope it stands in for, so each selector test treats the two alike; its only `[` is
// its first character, so no occurrence of it overlaps another or the text around it.
const PLACEHOLDER_ID = "hf-scope-placeholder";
const PLACEHOLDER_SCOPE = `[data-composition-id="${PLACEHOLDER_ID}"]`;
// No quote, bracket, backslash, space or `$` (a String.replace pattern): such a scope lands verbatim.
const PLAIN_ID = /^[\w.:-]+$/;
const PLAIN_SCOPE = /^\[data-composition-id="([\w.:-]+)"\]$/;

/** `scopeCssToComposition` for sheets mounted many times: each sheet is scoped once around a
 * placeholder scope, which each mount's own scope then replaces. */
export function createCompositionCssScoper(): typeof scopeCssToComposition {
  const templates = new Map<string, string | null>();
  return (css, compositionId, scopeSelectorOverride, authoredRootId, options) => {
    const trimmedId = compositionId.trim();
    const scope = scopeSelectorOverride ?? "";
    const scopeId = PLAIN_SCOPE.exec(scope)?.[1];
    if (
      !scopeId ||
      scopeId === trimmedId ||
      !PLAIN_ID.test(trimmedId) ||
      trimmedId === PLACEHOLDER_ID
    )
      return scopeCssToComposition(
        css,
        compositionId,
        scopeSelectorOverride,
        authoredRootId,
        options,
      );
    const key = JSON.stringify([
      trimmedId,
      authoredRootId ?? null,
      Boolean(options?.compoundAuthoredRoot),
      Boolean(options?.scopeRootSelectors),
      css,
    ]);
    let template = templates.get(key);
    if (template === undefined) {
      template = scopeTemplate(css, trimmedId, authoredRootId, options);
      templates.set(key, template);
    }
    return template === null
      ? scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options)
      : template.split(PLACEHOLDER_SCOPE).join(scope);
  };
}

/** Null when the placeholder is already in the sheet, or a selector keeps its raw text (it holds a comment). */
function scopeTemplate(
  css: string,
  compositionId: string,
  authoredRootId: string | null | undefined,
  options: ScopeOptions | undefined,
): string | null {
  if (css.includes(PLACEHOLDER_SCOPE)) return null;
  if (!css) return css;
  const root = parseCss(css);
  if (!root) return "";
  let rawSelector = false;
  forEachScopedRule(root, (rule) => {
    rawSelector ||= Boolean(rule.raws.selector);
  });
  return rawSelector
    ? null
    : scopeParsedCss(root, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
}

function isFontFaceAtRule(node: { type: string; name?: string }): node is AtRule {
  return node.type === "atrule" && (node as AtRule).name.toLowerCase() === "font-face";
}

function fontFaceKey(atRule: AtRule): string {
  const decls: string[] = [];
  atRule.walkDecls((decl) => {
    // Collapse whitespace outside quoted strings only: "A  B" and "A B" name different families.
    const value = decl.value.replace(
      /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\s+/g,
      (_m, str) => str ?? " ",
    );
    decls.push(
      `${decl.prop.trim().toLowerCase()}:${value.trim()}${decl.important ? "!important" : ""}`,
    );
  });
  return decls.join(";");
}

/** Drops repeats of an identical `@font-face` across the given style texts, keeping the last copy:
 * the last matching rule is the one the browser uses, so a rule in between never gains precedence. */
export const dedupeFontFaceRules = (styleTexts: string[]): string[] => dropFontFaces(styleTexts);

export function hoistFontFaceRules(styleTexts: string[]): { styles: string[]; faces: string[] } {
  const faces: string[] = [];
  return { styles: dropFontFaces(styleTexts, faces), faces };
}

function dropFontFaces(styleTexts: string[], hoisted?: string[]): string[] {
  const seen = new Set<string>();
  return [...styleTexts]
    .reverse()
    .map((css) => {
      if (!css || !/@font-face/i.test(css)) return css;
      let root: postcss.Root;
      try {
        root = postcss.parse(css);
      } catch {
        return css; // unparseable text ships as authored and takes no part
      }
      let changed = false;
      for (const node of [...(root.nodes ?? [])].reverse()) {
        if (!isFontFaceAtRule(node)) continue;
        const key = fontFaceKey(node);
        if (!seen.has(key)) {
          seen.add(key);
          if (!hoisted) continue;
          hoisted.unshift(node.toString());
        }
        node.remove();
        changed = true;
      }
      return changed ? root.toResult({ map: false }).css : css;
    })
    .reverse();
}

/**
 * Serialize a value as a JS literal safe to emit inside a `<script>` element.
 *
 * `<script>` is a RAW TEXT element: HTML serialization does not escape its
 * content, and the tokenizer ends the element at the first `</script` — in any
 * string, comment or regex context. `JSON.stringify` escapes `"` and `\` but
 * neither `<` nor `/`, so any dynamic literal carrying `</script>` would close
 * the element early and have the remainder parsed as markup. Rewriting every
 * `<` to `<` removes the only byte that can start a closing tag, and is
 * transparent to both `JSON.parse` and the JS string grammar, so the value the
 * runtime reads is unchanged.
 *
 * Every dynamic literal in an emitted script body must go through here: a
 * per-value guard on this surface has already been missed once, since the
 * composition id reaches the emitted script through four separate literals.
 */
function jsonScriptLiteral(value: unknown): string {
  return JSON.stringify(value).replace(/</g, "\\u003c");
}

const SCOPED_HYPERFRAMES_EXPRESSION = `!__hfBaseHyperframes
    ? __hfBaseHyperframes
    : Object.assign({}, __hfBaseHyperframes, {
        assetUrl: function(path) {
          var page = window.document.baseURI;
          return new URL(path, __hfCompositionSrc ? new URL(__hfCompositionSrc, page) : page).href;
        },
        getVariables: function() {
          var byComp = window.__hfVariablesByComp;
          var scoped = byComp && __hfTimelineCompId ? byComp[__hfTimelineCompId] : null;
          return scoped ? Object.assign({}, scoped) : {};
        },
      })`;

export function scopedModulePrelude(
  timelineCompositionId: string,
  compositionSrc?: string | null,
): string {
  return `const __hyperframes = (function(__hfBaseHyperframes, __hfTimelineCompId, __hfCompositionSrc) {
  return ${SCOPED_HYPERFRAMES_EXPRESSION};
})(window.__hyperframes, ${jsonScriptLiteral(timelineCompositionId)}, ${jsonScriptLiteral(compositionSrc?.trim() || null)});
${wrapScopedCompositionScript("", timelineCompositionId)}
`;
}

export function wrapScopedCompositionScript(
  source: string,
  compositionId: string,
  errorLabel = "[HyperFrames] composition script error:",
  scopeSelectorOverride?: string,
  timelineCompositionId = compositionId,
  authoredRootId?: string | null,
  compositionSrc?: string | null,
): string {
  const compositionIdLiteral = jsonScriptLiteral(compositionId);
  const timelineCompositionIdLiteral = jsonScriptLiteral(timelineCompositionId);
  const errorLabelLiteral = jsonScriptLiteral(errorLabel);
  const escapedCompositionId = escapeRegExp(compositionId);
  const authoredRootIdLiteral = jsonScriptLiteral(authoredRootId?.trim() || null);
  const scopeSelectorLiteral = jsonScriptLiteral(scopeSelectorOverride ?? null);
  const rootSelectorPatternLiteral = jsonScriptLiteral(
    String.raw`\[\s*data-composition-id\s*=\s*(?:"${escapedCompositionId}"|'${escapedCompositionId}')\s*\]`,
  );
  const timingSelectorPatternLiteral = jsonScriptLiteral(
    String.raw`\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`,
  );
  const aliasInstallerOutsideAuthoredStrictness = `(function(){ ${getSvgSelectorAliasesScript()} })();`;
  return `(function(){
  ${aliasInstallerOutsideAuthoredStrictness}
  var __hfCompId = ${compositionIdLiteral};
  var __hfTimelineCompId = ${timelineCompositionIdLiteral};
  var __hfErrorLabel = ${errorLabelLiteral};
  var __hfAuthoredRootId = ${authoredRootIdLiteral};
  var __hfCompositionSrc = ${jsonScriptLiteral(compositionSrc?.trim() || null)};
  var __hfAuthoredRootAttr = ${jsonScriptLiteral(AUTHORED_ROOT_ID_ATTR)};
  var __hfEscapeAttr = function(value) {
    return (value + "").replace(/\\\\/g, "\\\\\\\\").replace(/"/g, "\\\\\\"");
  };
  var __hfRootSelector = ${scopeSelectorLiteral} || (__hfCompId
    ? '[data-composition-id="' + __hfEscapeAttr(__hfCompId) + '"]'
    : "");
  var __hfRoot = null;
  var __hfRootSelectorPattern = ${rootSelectorPatternLiteral};
  var __hfTimingSelectorPattern = ${timingSelectorPatternLiteral};
  var __hfAuthoredRootSelector = __hfAuthoredRootId
    ? "[" + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(__hfAuthoredRootId) + '"]'
    : "";
  var __hfAuthoredRootEntries = __hfAuthoredRootSelector
    ? [{ id: __hfAuthoredRootId, replacement: __hfAuthoredRootSelector }]
    : [];
  var __hfNormalizeSelector = function(selector) {
    if (!__hfCompId || typeof selector !== "string") return selector;
    var normalized = selector
      .replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelector)
      .replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelector);
    return window.__hfSvgSelectorAliases.rewrite(normalized, __hfAuthoredRootEntries);
  };
  var __hfFindRoot = function() {
    if (!__hfRoot && __hfRootSelector) {
      __hfRoot = window.document.querySelector(__hfRootSelector);
    }
    return __hfRoot;
  };
  var __hfContains = function(node) {
    var root = __hfFindRoot();
    return !root || node === root || root.contains(node);
  };
  var __hfQueryAll = function(selector) {
    var root = __hfFindRoot();
    if (!root || typeof selector !== "string") {
      return window.document.querySelectorAll(selector);
    }
    return Array.prototype.filter.call(window.document.querySelectorAll(__hfNormalizeSelector(selector)), function(node) {
      return __hfContains(node);
    });
  };
  var __hfQueryOne = function(selector) {
    var matches = __hfQueryAll(selector);
    return matches[0] || null;
  };
  var __hfGetElementById = function(id) {
    var found = window.document.getElementById(id);
    if (found && __hfContains(found)) return found;
    var root = __hfFindRoot();
    if (!root) return found || null;
    var idValue = id + "";
    if (__hfAuthoredRootId && __hfAuthoredRootId === idValue && root.getAttribute && root.getAttribute(__hfAuthoredRootAttr) === idValue) {
      return root;
    }
    if (root.id === idValue) return root;
    if (typeof root.querySelector !== "function") return null;
    try {
      var authoredRootMatch = root.querySelector('[' + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(idValue) + '"]');
      if (authoredRootMatch) return authoredRootMatch;
    } catch {}
    if (typeof CSS !== "undefined" && CSS && typeof CSS.escape === "function") {
      try {
        return root.querySelector("#" + CSS.escape(idValue)) || null;
      } catch {}
    }
    try {
      return root.querySelector('[id="' + __hfEscapeAttr(idValue) + '"]') || null;
    } catch {}
    return null;
  };
  var __hfScopedDocument = typeof Proxy === "function"
    ? new Proxy(window.document, {
        get: function(target, prop, receiver) {
          if (prop === "querySelector") return __hfQueryOne;
          if (prop === "querySelectorAll") return __hfQueryAll;
          if (prop === "getElementById") return __hfGetElementById;
          var value = Reflect.get(target, prop, target);
          return typeof value === "function" ? value.bind(target) : value;
        },
      })
    : window.document;
  var __hfTimelineRegistryProxy = null;
  var __hfGetTimelineRegistry = function() {
    window.__timelines = window.__timelines || {};
    if (!__hfCompId || __hfCompId === __hfTimelineCompId || typeof Proxy !== "function") {
      return window.__timelines;
    }
    if (!__hfTimelineRegistryProxy) {
      __hfTimelineRegistryProxy = new Proxy(window.__timelines, {
        get: function(target, prop, receiver) {
          if (prop !== __hfCompId) {
            return Reflect.get(target, prop, target);
          }
          var runtimeValue = Reflect.get(target, __hfTimelineCompId, target);
          return runtimeValue === undefined ? Reflect.get(target, prop, target) : runtimeValue;
        },
        set: function(target, prop, value, receiver) {
          if (prop !== __hfCompId) {
            return Reflect.set(target, prop, value, target);
          }
          // The authored node remains in the compiled DOM when its local id
          // differs from the runtime mount id, so readiness legitimately sees
          // both compositions. Publish the same timeline under both identities,
          // unless another mount of the same file already owns the authored one.
          var authoredValue = Reflect.get(target, __hfCompId, target);
          var ownsAuthored =
            authoredValue === undefined ||
            authoredValue === Reflect.get(target, __hfTimelineCompId, target);
          var runtimeSet = Reflect.set(target, __hfTimelineCompId, value, target);
          if (!ownsAuthored) return runtimeSet;
          return Reflect.set(target, __hfCompId, value, target) && runtimeSet;
        },
      });
    }
    return __hfTimelineRegistryProxy;
  };
  var __hfScopedWindow = typeof Proxy === "function"
    ? new Proxy(window, {
        get: function(target, prop, receiver) {
          if (prop === "__timelines") return __hfGetTimelineRegistry();
          // Inside a sub-composition, __hyperframes is passed as a bare script
          // param bound to the SCOPED variant (per-comp getVariables). But
          // authors routinely write the documented window.__hyperframes.
          // getVariables() form, which would otherwise fall through to the host
          // page's base __hyperframes and return the WRONG (or empty) variables
          // for this instance. Route it to the scoped variant too so both
          // spellings resolve to this composition's own variables.
          // (__hfScopedHyperframes is a hoisted var assigned below, before any
          // sub-comp script -- the only code that reads this -- runs.)
          if (prop === "__hyperframes") return __hfScopedHyperframes;
          // Native window methods must stay bound to the real window. Handed
          // back unbound, "this" at call time is this Proxy and Chrome rejects
          // it with "Illegal invocation", which broke window.addEventListener,
          // setTimeout, matchMedia and getComputedStyle inside every
          // sub-composition -- including the window.addEventListener("hf-seek",
          // ...) form the Three.js and TypeGPU adapters document. The sibling
          // document and gsap proxies here already bind.
          //
          // Only bind non-constructors. Function.prototype.bind drops static
          // members, so binding a class exposed on window (window.Texts and
          // friends) would silently strip its statics. Built-in methods have
          // no .prototype; classes and constructor functions do.
          var value = Reflect.get(target, prop, target);
          return typeof value === "function" && value.prototype === undefined
            ? value.bind(target)
            : value;
        },
        set: function(target, prop, value, receiver) {
          if (prop === "__timelines") {
            // Common authoring boilerplate assigns the registry back to
            // itself (window.__timelines = window.__timelines || {}). The
            // getter above returns our proxy; do not replace the canonical
            // registry with that proxy or later wrappers will stack proxies.
            if (value === __hfTimelineRegistryProxy) return true;
            target.__timelines = value || {};
            __hfTimelineRegistryProxy = null;
            return true;
          }
          return Reflect.set(target, prop, value, target);
        },
      })
    : window;
  var __hfResolveGsapTarget = function(target) {
    if (typeof target === "string") return __hfQueryAll(target);
    if (!Array.isArray(target)) return target;
    return target.reduce(function(resolved, item) {
      if (typeof item === "string") {
        return resolved.concat(Array.prototype.slice.call(__hfQueryAll(item)));
      }
      resolved.push(item);
      return resolved;
    }, []);

  };
  var __hfScopeTimeline = function(timeline) {
    if (!timeline || timeline.__hfScopedCompositionRoot === __hfFindRoot()) return timeline;
    ["to", "from", "fromTo", "set"].forEach(function(method) {
      var original = timeline[method];
      if (typeof original !== "function") return;
      timeline[method] = function(target) {
        var args = Array.prototype.slice.call(arguments);
        args[0] = __hfResolveGsapTarget(target);
        return original.apply(timeline, args);
      };
    });
    try {
      Object.defineProperty(timeline, "__hfScopedCompositionRoot", {
        value: __hfFindRoot(),
        configurable: true,
      });
    } catch {
      // Best-effort: timelines coming from user code may have a frozen target
      // or a non-extensible defineProperty path. Swallow — the scoped root
      // is an enrichment, not a correctness invariant for playback.
    }
    return timeline;
  };
  var __hfBaseGsap = typeof gsap === "undefined" ? window.gsap : gsap;
  var __hfScopedGsap = !__hfBaseGsap || typeof Proxy !== "function"
    ? __hfBaseGsap
    : new Proxy(__hfBaseGsap, {
        get: function(target, prop, receiver) {
          if (prop === "timeline") {
            return function() {
              return __hfScopeTimeline(target.timeline.apply(target, arguments));
            };
          }
          if (prop === "to" || prop === "from" || prop === "fromTo" || prop === "set") {
            return function(firstArg) {
              var args = Array.prototype.slice.call(arguments);
              args[0] = __hfResolveGsapTarget(firstArg);
              return target[prop].apply(target, args);
            };
          }
          if (prop === "utils" && target.utils && typeof Proxy === "function") {
            return new Proxy(target.utils, {
              get: function(utilsTarget, utilsProp, utilsReceiver) {
                if (utilsProp === "toArray") {
                  return function(firstArg) {
                    var args = Array.prototype.slice.call(arguments);
                    args[0] = __hfResolveGsapTarget(firstArg);
                    return utilsTarget.toArray.apply(utilsTarget, args);
                  };
                }
                if (utilsProp === "selector") {
                  return function(base) {
                    var baseEl = typeof base === "string" ? __hfQueryOne(base) : base;
                    var root = baseEl || __hfFindRoot();
                    return function(selector) {
                      if (!root || typeof selector !== "string") return [];
                      return Array.prototype.filter.call(
                        window.document.querySelectorAll(__hfNormalizeSelector(selector)),
                        function(node) {
                          return node === root || (typeof root.contains === "function" && root.contains(node));
                        },
                      );
                    };
                  };
                }
                var value = Reflect.get(utilsTarget, utilsProp, utilsTarget);
                return typeof value === "function" ? value.bind(utilsTarget) : value;
              },
            });
          }
          var value = Reflect.get(target, prop, target);
          return typeof value === "function" ? value.bind(target) : value;
        },
      });
  var __hfBaseHyperframes = window.__hyperframes;
  var __hfScopedHyperframes = ${SCOPED_HYPERFRAMES_EXPRESSION};
  var __hfRun = function() {
    var report = window.__hfScriptState;
    if (typeof report === "function") report("start", __hfCompositionSrc || "index.html");
    try {
      (function(document, gsap, window, __hyperframes) {
${source.replace(/<\/(script)/gi, "<\\/$1")}
      }).call(window, __hfScopedDocument, __hfScopedGsap, __hfScopedWindow, __hfScopedHyperframes);
    } catch (_err) {
      console.error(__hfErrorLabel, __hfCompId, _err);
    } finally {
      if (typeof report === "function") report("finish", __hfCompositionSrc || "index.html");
    }
  };
  // What the script started on the global gsap timeline, by any route, for a scene swap to revert.
  // Only a page with a scene manifest can swap; elsewhere the first script stores null and none records.
  var __hfRecordAnimations = function(run) {
    if (window.__hfSceneAnimations === undefined) {
      window.__hfSceneAnimations = window.document.querySelector(${jsonScriptLiteral(`meta[name="${SCENE_PARTS_META}"]`)})
        ? {}
        : null;
    }
    var byComp = window.__hfSceneAnimations;
    var globalTimeline = __hfBaseGsap && __hfBaseGsap.globalTimeline;
    if (!byComp || !globalTimeline || !__hfTimelineCompId) return run();
    var before = globalTimeline.getChildren(false);
    // A set completes as it is made and would leave the timeline before the diff below.
    var autoRemove = globalTimeline.autoRemoveChildren;
    globalTimeline.autoRemoveChildren = false;
    run();
    globalTimeline.autoRemoveChildren = autoRemove;
    var recorded = (byComp[__hfTimelineCompId] = byComp[__hfTimelineCompId] || []);
    globalTimeline.getChildren(false).forEach(function(animation) {
      if (before.indexOf(animation) >= 0) return;
      recorded.push(animation);
      // Dropped as the timeline drops a finished tween (it keeps a paused one); moved back, a tween re-adds itself.
      if (autoRemove && !animation.getChildren && animation.totalProgress() === 1) globalTimeline.remove(animation);
    });
  };
  __hfFindRoot();
  __hfRecordAnimations(__hfRun);
})();`;
}

export function wrapInlineScriptWithErrorBoundary(source: string, errorLabel: string): string {
  return `(function(){ try { Function(${jsonScriptLiteral(source)}).call(window); } catch (_err) { console.error(${jsonScriptLiteral(errorLabel)}, _err); } })();`;
}

/**
 * Build the statement that populates `window.__hfVariablesByComp` — the table
 * the scoped `getVariables` above reads. Returns `null` when there are no
 * per-instance values.
 *
 * The WRITER lives next to the READER (the scoped `getVariables` in
 * `wrapScopedCompositionScript`) on purpose: every compile path that wraps the
 * reader MUST also emit this writer before the sub-comp scripts run. The
 * render compiler (`htmlCompiler`) inlined the reader scripts but never emitted
 * the writer while the preview bundler (`htmlBundler`) did, so
 * `getVariables()` returned `{}` only during render — parametrized sub-comps
 * silently shipped blank/default text in the final MP4 while snapshot QA passed
 * (issue #2064). Both callers now share this one builder so they can't drift.
 *
 * Values, keys and composition ids are all attacker-reachable, so the whole
 * table goes through `jsonScriptLiteral` — see there for why.
 */
export function buildVariablesByCompScript(
  variablesByComp: Record<string, Record<string, unknown>>,
): string | null {
  if (!variablesByComp || Object.keys(variablesByComp).length === 0) return null;
  const json = jsonScriptLiteral(variablesByComp);
  return `window.__hfVariablesByComp = Object.assign({}, window.__hfVariablesByComp || {}, ${json});`;
}