fix(lint): flag a script that calls gsap before GSAP loads, and say so when a render fails on it (#7514)

* fix(lint): flag a script that calls gsap before GSAP loads, and say so when a render fails on it

* fix(lint): judge the first gsap call by when it runs, so a listener after a deferred GSAP passes

* fix(lint): keep the gsap timing helper's comment to two lines
This commit is contained in:
Miguel Ángel
2026-11-10 21:46:26 +00:00
committed by GitHub
parent 7afa05a782
commit 124591a9d5
5 changed files with 180 additions and 4 deletions
@@ -158,6 +158,31 @@ describe("recordSubTimelineWarning", () => {
expect(message).not.toContain("failed to load");
});
it("says GSAP was not loaded yet when a script reads timeline before GSAP runs", () => {
const session = makeSession({
subTimelineWaitOutcome: "script_failure",
pageErrors: ["runtime-error:TypeError: Cannot read properties of null (reading 'timeline')"],
pendingTimelineIds: ["main"],
});
recordSubTimelineWarning(session, 45_000);
expect(session.warnings[0].message).toContain(
"GSAP was not loaded yet when that script ran: load the GSAP script before the first script that uses gsap.",
);
});
it("adds no GSAP hint for a null read that is not GSAP's", () => {
const session = makeSession({
subTimelineWaitOutcome: "script_failure",
pageErrors: [
"runtime-error:TypeError: Cannot read properties of null (reading 'appendChild')",
],
});
recordSubTimelineWarning(session, 45_000);
expect(session.warnings[0].message).not.toContain("GSAP was not loaded");
});
it("names the missing script, not the error it caused, when both are present", () => {
const session = makeSession({
subTimelineWaitOutcome: "script_failure",
+9 -1
View File
@@ -2653,6 +2653,14 @@ export function recordSubTimelineWarning(session: CaptureSession, timeoutMs: num
const loadCauses = session.scriptLoadCauses ?? [];
const pending = session.pendingTimelineIds ?? [];
const pendingSuffix = pending.length > 0 ? ` (still unregistered: ${pending.join(", ")})` : "";
// The render page's gsap reads null until GSAP's script runs, so a too-early gsap.timeline() surfaces as this.
const gsapNotLoaded = sources.some((s) =>
/gsap is not defined|Cannot read properties of (?:null|undefined) \(reading '(?:timeline|registerPlugin)'\)/.test(
s,
),
)
? " GSAP was not loaded yet when that script ran: load the GSAP script before the first script that uses gsap."
: "";
const isolated = session.isolatedCompositions ?? [];
if (isolated.length > 0) {
recordCaptureWarnings(session, [
@@ -2676,7 +2684,7 @@ export function recordSubTimelineWarning(session: CaptureSession, timeoutMs: num
code: scriptFailure ? "sub_timeline_script_failure" : "sub_timeline_readiness_timeout",
message: threwThenTimedOut
? `A composition script threw before its timeline registered` +
`${pendingSuffix} (${sources.join(", ")}). Fix the error; a composition animated by ` +
`${pendingSuffix} (${sources.join(", ")}).${gsapNotLoaded} Fix the error; a composition animated by ` +
`CSS or rAF rather than a GSAP timeline must mark its host with data-no-timeline.`
: scriptFailure
? `A sub-composition timeline script failed to load${scriptLoadCauseSuffix(loadCauses)} ` +
+66
View File
@@ -1012,6 +1012,72 @@ describe("GSAP rules", () => {
expect(finding?.message).toContain("GSAP");
});
it.each([
["after the script that uses it", "", '<script src="./gsap.min.js"></script>'],
["with defer before it", '<script defer src="./gsap.min.js"></script>', ""],
])("reports gsap_loaded_after_use when the GSAP tag sits %s", async (_, before, after) => {
const html = `
<html><body>
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
${before}
<script>
const tl = gsap.timeline({ paused: true });
window.__timelines["main"] = tl;
</script>
${after}
</body></html>`;
const result = await lintHyperframeHtml(html);
const finding = result.findings.find((f) => f.code === "gsap_loaded_after_use");
expect(finding?.severity).toBe("error");
expect(result.findings.find((f) => f.code === "missing_gsap_script")).toBeUndefined();
});
it.each([
[
"a defer tag and a DOMContentLoaded listener",
'<head><script defer src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script></head>',
'<script>window.__timelines={};document.addEventListener("DOMContentLoaded",()=>{window.__timelines.main=gsap.timeline({paused:true});});</script>',
"",
],
[
"a later tag and a load listener",
"",
'<script>window.addEventListener("load", function () { window.__timelines = { main: gsap.timeline({ paused: true }) }; });</script>',
'<script src="./gsap.min.js"></script>',
],
])("does not report gsap_loaded_after_use for %s", async (_, head, body, after) => {
const html = `<html>${head}<body>
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
${body}
${after}
</body></html>`;
const result = await lintHyperframeHtml(html);
expect(result.findings.find((f) => f.code === "gsap_loaded_after_use")).toBeUndefined();
});
it("reports gsap_loaded_after_use for a function called on the spot before a later tag", async () => {
const html = `<html><body>
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
<script>(function () { window.__timelines = { main: gsap.timeline({ paused: true }) }; })();</script>
<script src="./gsap.min.js"></script>
</body></html>`;
const result = await lintHyperframeHtml(html);
expect(result.findings.find((f) => f.code === "gsap_loaded_after_use")?.severity).toBe("error");
});
it("does not report gsap_loaded_after_use when GSAP loads in the head first", async () => {
const html = `
<html><head><script src="./gsap.min.js"></script></head><body>
<div data-composition-id="main" data-width="1920" data-height="1080"></div>
<script>
const tl = gsap.timeline({ paused: true });
window.__timelines["main"] = tl;
</script>
</body></html>`;
const result = await lintHyperframeHtml(html);
expect(result.findings.find((f) => f.code === "gsap_loaded_after_use")).toBeUndefined();
});
it("does not report missing_gsap_script when GSAP CDN script is present", async () => {
const html = `
<html><body>
+34 -1
View File
@@ -1,5 +1,5 @@
import postcss from "postcss";
import { gsapCallOffset, containingCallOffset } from "../scriptPositions";
import { gsapCallOffset, containingCallOffset, gsapRunsWhenScriptRuns } from "../scriptPositions";
interface LintParsedGsap {
animations: Array<{
targetSelector: string;
@@ -1509,6 +1509,39 @@ export const gsapRules: LintRule<LintContext>[] = [
/\b_gsScope\b/.test(t),
);
if (usesGsap && hasGsapScript && !hasInlineGsap && !canInheritGsapFromHost) {
// A classic script runs where it sits, so GSAP must load earlier: a deferred, async or later tag is too late.
const classic = (s: { attrs: string }) => {
const tag = `<script ${s.attrs}>`;
return (
(readDecodedAttr(tag, "type") ?? "").toLowerCase() !== "module" &&
readDecodedAttr(tag, "defer") === null &&
readDecodedAttr(tag, "async") === null
);
};
// defer and async do nothing on an inline script; only a module waits. A use inside a listener runs later.
const firstUse = scripts.find(
(s) =>
!/\bsrc\s*=/.test(s.attrs) &&
(readDecodedAttr(`<script ${s.attrs}>`, "type") ?? "").toLowerCase() !== "module" &&
gsapRunsWhenScriptRuns(s),
);
const firstGsap = scripts.find(
(s) => classic(s) && isGsapCoreSrc(readAttr(`<script ${s.attrs}>`, "src") || ""),
);
if (firstUse && (!firstGsap || firstGsap.index > firstUse.index)) {
return [
{
code: "gsap_loaded_after_use",
severity: "error",
message:
"A script calls gsap before the GSAP script has run, so gsap is not there yet and its timeline never registers.",
fixHint:
"Move the GSAP <script src> above the first script that uses gsap, without defer or async; the <head> is safest.",
},
];
}
}
if (!usesGsap || hasGsapScript || hasInlineGsap || canInheritGsapFromHost) return [];
return [
{
+46 -2
View File
@@ -1,5 +1,5 @@
import { parse, type CallExpression } from "acorn";
import { simple } from "acorn-walk";
import { parse, type CallExpression, type Node } from "acorn";
import { ancestor, simple } from "acorn-walk";
import type { ExtractedBlock } from "./utils";
// Blocks belong to a single lint context. Weak keys release AST evidence after the pass.
@@ -41,6 +41,50 @@ export function gsapCallOffset(script: ExtractedBlock, method: string): number |
)?.start;
}
const GSAP_ENTRY = new Set(["to", "from", "fromTo", "timeline", "set", "registerPlugin"]);
const FUNCTION_TYPES = new Set([
"FunctionDeclaration",
"FunctionExpression",
"ArrowFunctionExpression",
]);
// A gsap call runs with the script at its top level or in a function called on the spot; a listener runs later.
// A script that does not parse returns false, so lint reports nothing it cannot prove.
export function gsapRunsWhenScriptRuns(script: ExtractedBlock): boolean {
let ast: Node;
try {
ast = parse(script.content, {
ecmaVersion: "latest",
sourceType: "script",
allowReturnOutsideFunction: true,
});
} catch {
return false;
}
let early = false;
ancestor(ast, {
CallExpression: (node, _state, ancestors) => {
const { callee } = node;
if (
early ||
callee.type !== "MemberExpression" ||
callee.computed ||
callee.object.type !== "Identifier" ||
callee.object.name !== "gsap" ||
callee.property.type !== "Identifier" ||
!GSAP_ENTRY.has(callee.property.name)
)
return;
early = ancestors.every((a, i) => {
if (!FUNCTION_TYPES.has(a.type)) return true;
const parent = ancestors[i - 1];
return parent?.type === "CallExpression" && (parent as CallExpression).callee === a;
});
},
});
return early;
}
/** The innermost call containing an already-detected token (for example repeat: -1). */
export function containingCallOffset(
script: ExtractedBlock,