Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): GSAP tween editing in Design panel (#1102)
Miguel Ángelfb2e21090fc0
diff --git a/.fallowrc.jsonc b/.fallowrc.jsoncindex 55d1da9f25..6d92412e6d 100644--- a/.fallowrc.jsonc+++ b/.fallowrc.jsonc@@ -79,6 +79,11 @@"refreshDomEditSelection",],},+ // Exported for render.test.ts (exported-for-tests pattern).+ {+ "file": "packages/cli/src/commands/render.ts",+ "exports": ["resolveBrowserGpuForCli", "renderLocal"],+ },],"ignoreDependencies": [// Runtime/dynamic deps not visible to static analysis: tsup `external`,diff --git a/bun.lock b/bun.lockindex 2d52b7a44c..00c10ccdef 100644--- a/bun.lock+++ b/bun.lock@@ -22,7 +22,7 @@},"packages/aws-lambda": {"name": "@hyperframes/aws-lambda",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {"@aws-sdk/client-s3": "^3.700.0","@aws-sdk/client-sfn": "^3.700.0",@@ -54,7 +54,7 @@},"packages/cli": {"name": "@hyperframes/cli",- "version": "0.6.29",+ "version": "0.6.51","bin": {"hyperframes": "./dist/cli.js",},@@ -99,10 +99,12 @@},"packages/core": {"name": "@hyperframes/core",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {+ "@babel/parser": "^7.27.0","@chenglou/pretext": "^0.0.5","postcss": "^8.5.8",+ "recast": "^0.23.11",},"devDependencies": {"@types/jsdom": "^28.0.0",@@ -126,7 +128,7 @@},"packages/engine": {"name": "@hyperframes/engine",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {"@hono/node-server": "^1.13.0","@hyperframes/core": "workspace:^",@@ -144,7 +146,7 @@},"packages/player": {"name": "@hyperframes/player",- "version": "0.6.29",+ "version": "0.6.51","devDependencies": {"@types/bun": "^1.1.0","gsap": "^3.12.5",@@ -156,7 +158,7 @@},"packages/producer": {"name": "@hyperframes/producer",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {"@fontsource/archivo-black": "^5.2.8","@fontsource/eb-garamond": "^5.2.7",@@ -196,7 +198,7 @@},"packages/shader-transitions": {"name": "@hyperframes/shader-transitions",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {"html2canvas": "^1.4.1",},@@ -208,7 +210,7 @@},"packages/studio": {"name": "@hyperframes/studio",- "version": "0.6.29",+ "version": "0.6.51","dependencies": {"@codemirror/autocomplete": "^6.20.1","@codemirror/commands": "^6.10.3",@@ -1041,7 +1043,7 @@"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],- "ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],+ "ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="],"ast-v8-to-istanbul": ["[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "estree-walker": "^3.0.3", "js-tokens": "^10.0.0" } }, "sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g=="],@@ -1675,6 +1677,8 @@"readdirp": ["[email protected]", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],+ "recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],+"require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],"require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],@@ -1795,6 +1799,8 @@"tiny-inflate": ["[email protected]", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="],+ "tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],+"tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],"tinyexec": ["[email protected]", "", {}, "sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA=="],@@ -1951,6 +1957,8 @@"data-urls/whatwg-mimetype": ["[email protected]", "", {}, "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw=="],+ "degenerator/ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],+"dom-serializer/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],"escodegen/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],@@ -1997,6 +2005,8 @@"proxy-agent/lru-cache": ["[email protected]", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="],+ "recast/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],+"socks-proxy-agent/agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],"strip-literal/js-tokens": ["[email protected]", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.tsindex ea833113b1..73b74555e6 100644--- a/packages/cli/src/commands/lint.ts+++ b/packages/cli/src/commands/lint.ts@@ -38,7 +38,7 @@ export default defineCommand({async run({ args }) {try {const project = resolveProject(args.dir);- const lintResult = lintProject(project);+ const lintResult = await lintProject(project);if (args.json) {const allFindings = lintResult.results.flatMap((r) => r.result.findings);diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsindex 9ce9afc8b0..67b9ce44f3 100644--- a/packages/cli/src/commands/preview.ts+++ b/packages/cli/src/commands/preview.ts@@ -129,7 +129,7 @@ export default defineCommand({const indexPath = join(dir, "index.html");if (existsSync(indexPath)) {const project = { dir, name: projectName, indexPath };- const lintResult = lintProject(project);+ const lintResult = await lintProject(project);if (lintResult.totalErrors > 0 || lintResult.totalWarnings > 0) {console.log();for (const line of formatLintFindings(lintResult)) console.log(line);diff --git a/packages/cli/src/commands/publish.ts b/packages/cli/src/commands/publish.tsindex 132cc8edbe..182743fcc9 100644--- a/packages/cli/src/commands/publish.ts+++ b/packages/cli/src/commands/publish.ts@@ -38,7 +38,7 @@ export default defineCommand({const indexPath = join(dir, "index.html");if (existsSync(indexPath)) {- const lintResult = lintProject({ dir, name: projectName, indexPath });+ const lintResult = await lintProject({ dir, name: projectName, indexPath });if (lintResult.totalErrors > 0 || lintResult.totalWarnings > 0) {console.log();for (const line of formatLintFindings(lintResult)) console.log(line);diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.tsindex 86d0a7121f..d7de1c6c78 100644--- a/packages/cli/src/commands/render.ts+++ b/packages/cli/src/commands/render.ts@@ -479,7 +479,7 @@ export default defineCommand({// ── Pre-render lint ──────────────────────────────────────────────────{- const lintResult = lintProject(project);+ const lintResult = await lintProject(project);if (!quiet && (lintResult.totalErrors > 0 || lintResult.totalWarnings > 0)) {console.log("");for (const line of formatLintFindings(lintResult, { errorsFirst: true })) console.log(line);diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 8c7ae9b0cf..a3eed7efee 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -260,7 +260,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {async lint(html: string, opts?: { filePath?: string }) {const { lintHyperframeHtml } = await import("@hyperframes/core/lint");- return lintHyperframeHtml(html, opts);+ return await lintHyperframeHtml(html, opts);},runtimeUrl: "/api/runtime.js",diff --git a/packages/cli/src/utils/lintProject.test.ts b/packages/cli/src/utils/lintProject.test.tsindex 65def2039b..157063d954 100644--- a/packages/cli/src/utils/lintProject.test.ts+++ b/packages/cli/src/utils/lintProject.test.ts@@ -59,9 +59,9 @@ afterEach(() => {});describe("lintProject", () => {- it("returns zero errors/warnings for a clean project", () => {+ it("returns zero errors/warnings for a clean project", async () => {const project = makeProject(validHtml());- const { totalErrors, totalWarnings, results } = lintProject(project);+ const { totalErrors, totalWarnings, results } = await lintProject(project);expect(totalErrors).toBe(0);expect(totalWarnings).toBe(0);@@ -71,9 +71,9 @@ describe("lintProject", () => {expect(first?.file).toBe("index.html");});- it("detects errors in index.html", () => {+ it("detects errors in index.html", async () => {const project = makeProject(htmlWithMissingMediaId());- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);expect(totalErrors).toBeGreaterThan(0);const first = results[0];@@ -82,11 +82,11 @@ describe("lintProject", () => {expect(mediaFinding).toBeDefined();});- it("lints sub-compositions in compositions/ directory", () => {+ it("lints sub-compositions in compositions/ directory", async () => {const project = makeProject(validHtml(), {"captions.html": htmlWithMissingMediaId(),});- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);expect(results).toHaveLength(2);const second = results[1];@@ -97,7 +97,7 @@ describe("lintProject", () => {expect(subFindings.some((f) => f.code === "media_missing_id")).toBe(true);});- it("lints linked CSS next to sub-compositions", () => {+ it("lints linked CSS next to sub-compositions", async () => {const project = makeProject(validHtml(), {"scene.html": `<html><head><link rel="stylesheet" href="scene.css"></head><body><div id="scene" data-composition-id="scene" data-width="1920" data-height="1080" data-start="0" data-duration="2"></div>@@ -109,7 +109,7 @@ describe("lintProject", () => {'[data-composition-id="scene"] .title { opacity: 0; }',);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const subResult = results.find((result) => result.file === "compositions/scene.html");const finding = subResult?.result.findings.find((item) => item.code === "composition_self_attribute_selector",@@ -119,7 +119,7 @@ describe("lintProject", () => {expect(finding?.selector).toBe('[data-composition-id="scene"] .title');});- it("lints percent-encoded linked CSS filenames that exist decoded on disk", () => {+ it("lints percent-encoded linked CSS filenames that exist decoded on disk", async () => {const encodedFilename = "%E6%97%A5%E6%9C%AC%E8%AA%9E.css";const project = makeProject(validHtml(), {"scene.html": `<html><head><link rel="stylesheet" href="${encodedFilename}"></head><body>@@ -132,7 +132,7 @@ describe("lintProject", () => {'[data-composition-id="scene"] .title { opacity: 0; }',);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const subResult = results.find((result) => result.file === "compositions/scene.html");const finding = subResult?.result.findings.find((item) => item.code === "composition_self_attribute_selector",@@ -142,11 +142,11 @@ describe("lintProject", () => {expect(finding?.selector).toBe('[data-composition-id="scene"] .title');});- it("aggregates errors across index.html and sub-compositions", () => {+ it("aggregates errors across index.html and sub-compositions", async () => {const project = makeProject(htmlWithMissingMediaId(), {"overlay.html": htmlWithMissingMediaId(),});- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);expect(results).toHaveLength(2);const first = results[0];@@ -159,11 +159,11 @@ describe("lintProject", () => {expect(totalErrors).toBe(rootErrors + subErrors);});- it("aggregates warnings from sub-compositions", () => {+ it("aggregates warnings from sub-compositions", async () => {const project = makeProject(validHtml(), {"captions.html": htmlWithPreloadNone(),});- const { totalWarnings, results } = lintProject(project);+ const { totalWarnings, results } = await lintProject(project);expect(results).toHaveLength(2);expect(totalWarnings).toBeGreaterThan(0);@@ -173,22 +173,22 @@ describe("lintProject", () => {expect(preloadWarning).toBeDefined();});- it("handles project with no compositions/ directory", () => {+ it("handles project with no compositions/ directory", async () => {const project = makeProject(validHtml());// No compositions/ dir created- const { results } = lintProject(project);+ const { results } = await lintProject(project);expect(results).toHaveLength(1);});- it("ignores non-HTML files in compositions/", () => {+ it("ignores non-HTML files in compositions/", async () => {const project = makeProject(validHtml(), {"captions.html": validHtml("captions"),});// Add a non-HTML filewriteFileSync(join(project.dir, "compositions", "readme.txt"), "not html");- const { results } = lintProject(project);+ const { results } = await lintProject(project);expect(results).toHaveLength(2); // index.html + captions.html, not readme.txt});@@ -227,11 +227,11 @@ function validHtmlWithMaskImageUrl(url: string): string {}describe("audio_file_without_element", () => {- it("warns when audio file exists but no <audio> element", () => {+ it("warns when audio file exists but no <audio> element", async () => {const project = makeProject(validHtml());writeFileSync(join(project.dir, "music.mp3"), "fake");- const { totalWarnings, results } = lintProject(project);+ const { totalWarnings, results } = await lintProject(project);expect(totalWarnings).toBeGreaterThan(0);const first = results[0];@@ -242,11 +242,11 @@ describe("audio_file_without_element", () => {expect(finding?.message).toContain("music.mp3");});- it("does not warn when audio file exists and <audio> element is present", () => {+ it("does not warn when audio file exists and <audio> element is present", async () => {const project = makeProject(validHtmlWithAudio());writeFileSync(join(project.dir, "song.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -254,10 +254,10 @@ describe("audio_file_without_element", () => {expect(finding).toBeUndefined();});- it("does not warn when no audio files exist", () => {+ it("does not warn when no audio files exist", async () => {const project = makeProject(validHtml());- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -265,12 +265,12 @@ describe("audio_file_without_element", () => {expect(finding).toBeUndefined();});- it("detects multiple audio file extensions", () => {+ it("detects multiple audio file extensions", async () => {const project = makeProject(validHtml());writeFileSync(join(project.dir, "narration.wav"), "fake");writeFileSync(join(project.dir, "bgm.ogg"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -280,13 +280,13 @@ describe("audio_file_without_element", () => {expect(finding?.message).toContain("bgm.ogg");});- it("does not warn when <audio> element is in a sub-composition", () => {+ it("does not warn when <audio> element is in a sub-composition", async () => {const project = makeProject(validHtml(), {"captions.html": validHtmlWithAudio("captions"),});writeFileSync(join(project.dir, "song.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -296,11 +296,11 @@ describe("audio_file_without_element", () => {});describe("audio_src_not_found", () => {- it("errors when <audio> src references a file that does not exist", () => {+ it("errors when <audio> src references a file that does not exist", async () => {const project = makeProject(validHtmlWithAudio());// song.mp3 is referenced in validHtmlWithAudio but not on disk- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);expect(totalErrors).toBeGreaterThan(0);const first = results[0];@@ -311,11 +311,11 @@ describe("audio_src_not_found", () => {expect(finding?.message).toContain("song.mp3");});- it("does not error when <audio> src file exists", () => {+ it("does not error when <audio> src file exists", async () => {const project = makeProject(validHtmlWithAudio());writeFileSync(join(project.dir, "song.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -323,7 +323,7 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("does not error when <audio> src is an HTTP URL", () => {+ it("does not error when <audio> src is an HTTP URL", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><audio id="music" src="https://cdn.example.com/song.mp3" data-start="0" data-track-index="0" data-volume="1"></audio>@@ -332,7 +332,7 @@ describe("audio_src_not_found", () => {</body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -340,13 +340,13 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("detects missing src in sub-compositions", () => {+ it("detects missing src in sub-compositions", async () => {const project = makeProject(validHtml(), {"captions.html": validHtmlWithAudio("captions"),});// song.mp3 referenced in sub-comp but not on disk- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);expect(totalErrors).toBeGreaterThan(0);const first = results[0];@@ -355,7 +355,7 @@ describe("audio_src_not_found", () => {expect(finding).toBeDefined();});- it("resolves relative paths from project root", () => {+ it("resolves relative paths from project root", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><audio id="music" src="assets/bgm.mp3" data-start="0" data-track-index="0" data-volume="1"></audio>@@ -366,7 +366,7 @@ describe("audio_src_not_found", () => {mkdirSync(join(project.dir, "assets"), { recursive: true });writeFileSync(join(project.dir, "assets", "bgm.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -374,14 +374,14 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("does not error for percent-encoded non-Latin filenames that exist on disk", () => {+ it("does not error for percent-encoded non-Latin filenames that exist on disk", async () => {const encodedFilename ="%D9%87%D9%86%D8%A7%20%D9%85%D8%B1%D9%88%D8%A7%20-%20%D9%85%D8%A8%D8%A7%D8%B1%D9%83.mp4";const project = makeProject(validHtmlWithAudioSrc(`assets/${encodedFilename}`));mkdirSync(join(project.dir, "assets"), { recursive: true });writeFileSync(join(project.dir, "assets", decodeURIComponent(encodedFilename)), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -389,13 +389,13 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("does not error for malformed percent sequences that are literal filenames", () => {+ it("does not error for malformed percent sequences that are literal filenames", async () => {const filename = "100%-discount.mp4";const project = makeProject(validHtmlWithAudioSrc(`assets/${filename}`));mkdirSync(join(project.dir, "assets"), { recursive: true });writeFileSync(join(project.dir, "assets", filename), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -403,24 +403,24 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("does not treat decoded traversal as an existing file outside the project", () => {+ it("does not treat decoded traversal as an existing file outside the project", async () => {const project = makeProject(validHtmlWithAudioSrc("assets/foo/%2E%2E/%2E%2E/%2E%2E/etc/passwd"),);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "audio_src_not_found");expect(finding).toBeDefined();});- it("deduplicates missing files across compositions", () => {+ it("deduplicates missing files across compositions", async () => {const project = makeProject(validHtmlWithAudio(), {"captions.html": validHtmlWithAudio("captions"),});// Both reference song.mp3 which doesn't exist- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -431,7 +431,7 @@ describe("audio_src_not_found", () => {expect(occurrences).toBe(1);});- it("resolves sub-composition src relative to the sub-composition file (../assets/...)", () => {+ it("resolves sub-composition src relative to the sub-composition file (../assets/...)", async () => {// A sub-composition at compositions/captions.html referencing// ../assets/bgm.mp3 means {projectRoot}/assets/bgm.mp3 — the bundler// rewrites that path before serving, so the lint check has to mirror it.@@ -445,7 +445,7 @@ describe("audio_src_not_found", () => {mkdirSync(join(project.dir, "assets"), { recursive: true });writeFileSync(join(project.dir, "assets", "bgm.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -453,7 +453,7 @@ describe("audio_src_not_found", () => {expect(finding).toBeUndefined();});- it("flags sub-composition src that resolves to a missing file via ../", () => {+ it("flags sub-composition src that resolves to a missing file via ../", async () => {const subComp = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080"><audio id="music" src="../assets/missing.mp3" data-start="0" data-track-index="0" data-volume="1"></audio>@@ -463,7 +463,7 @@ describe("audio_src_not_found", () => {const project = makeProject(validHtml(), { "captions.html": subComp });// No assets/ directory at all.- const { results } = lintProject(project);+ const { results } = await lintProject(project);const first = results[0];expect(first).toBeDefined();@@ -476,7 +476,7 @@ describe("audio_src_not_found", () => {});describe("texture_mask_asset_not_found", () => {- it("errors when CSS mask-image references a missing local texture", () => {+ it("errors when CSS mask-image references a missing local texture", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><div class="hf-texture-text hf-texture-lava">TEXT</div>@@ -491,7 +491,7 @@ describe("texture_mask_asset_not_found", () => {</body></html>`;const project = makeProject(html);- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -502,7 +502,7 @@ describe("texture_mask_asset_not_found", () => {expect(finding?.message).toContain("masks/lava.png");});- it("does not error when the referenced texture mask exists", () => {+ it("does not error when the referenced texture mask exists", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><div class="hf-texture-text hf-texture-lava">TEXT</div>@@ -519,7 +519,7 @@ describe("texture_mask_asset_not_found", () => {mkdirSync(join(project.dir, "masks"), { recursive: true });writeFileSync(join(project.dir, "masks", "lava.png"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -527,7 +527,7 @@ describe("texture_mask_asset_not_found", () => {expect(finding).toBeUndefined();});- it("resolves mask-image URLs inside linked sub-composition stylesheets", () => {+ it("resolves mask-image URLs inside linked sub-composition stylesheets", async () => {const project = makeProject(validHtml(), {"scene.html": `<html><head><link rel="stylesheet" href="scene.css"></head><body><div data-composition-id="scene" data-width="1920" data-height="1080">@@ -543,7 +543,7 @@ describe("texture_mask_asset_not_found", () => {mkdirSync(join(project.dir, "compositions", "masks"), { recursive: true });writeFileSync(join(project.dir, "compositions", "masks", "lava.png"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -551,7 +551,7 @@ describe("texture_mask_asset_not_found", () => {expect(finding).toBeUndefined();});- it("checks mask-image URLs inside percent-encoded linked CSS filenames", () => {+ it("checks mask-image URLs inside percent-encoded linked CSS filenames", async () => {const encodedFilename = "%E6%97%A5%E6%9C%AC%E8%AA%9E.css";const project = makeProject(validHtml(), {"scene.html": `<html><head><link rel="stylesheet" href="${encodedFilename}"></head><body>@@ -566,7 +566,7 @@ describe("texture_mask_asset_not_found", () => {'.hf-texture-lava { mask-image: url("masks/missing.png"); }',);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -575,7 +575,7 @@ describe("texture_mask_asset_not_found", () => {expect(finding?.message).toContain("masks/missing.png");});- it("resolves root-absolute mask-image URLs from the project root", () => {+ it("resolves root-absolute mask-image URLs from the project root", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><div class="hf-texture-text hf-texture-lava">TEXT</div>@@ -594,7 +594,7 @@ describe("texture_mask_asset_not_found", () => {});writeFileSync(join(project.dir, "assets", "texture-mask-text", "masks", "lava.png"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -602,13 +602,13 @@ describe("texture_mask_asset_not_found", () => {expect(finding).toBeUndefined();});- it("does not error for percent-encoded non-Latin mask filenames that exist on disk", () => {+ it("does not error for percent-encoded non-Latin mask filenames that exist on disk", async () => {const encodedFilename = "%E6%97%A5%E6%9C%AC%E8%AA%9E.png";const project = makeProject(validHtmlWithMaskImageUrl(`assets/${encodedFilename}`));mkdirSync(join(project.dir, "assets"), { recursive: true });writeFileSync(join(project.dir, "assets", decodeURIComponent(encodedFilename)), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -616,12 +616,12 @@ describe("texture_mask_asset_not_found", () => {expect(finding).toBeUndefined();});- it("does not treat decoded mask traversal as an existing file outside the project", () => {+ it("does not treat decoded mask traversal as an existing file outside the project", async () => {const project = makeProject(validHtmlWithMaskImageUrl("assets/foo/%2E%2E/%2E%2E/%2E%2E/etc/passwd"),);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((item) => item.code === "texture_mask_asset_not_found",);@@ -631,13 +631,13 @@ describe("texture_mask_asset_not_found", () => {});describe("multiple_root_compositions", () => {- it("fires when two HTML files have data-composition-id", () => {+ it("fires when two HTML files have data-composition-id", async () => {const project = makeProject(validHtml());writeFileSync(join(project.dir, "scaffold.html"),'<div data-composition-id="scaffold" data-width="1920" data-height="1080" data-duration="10"></div>',);- const { totalErrors, results } = lintProject(project);+ const { totalErrors, results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "multiple_root_compositions",);@@ -647,19 +647,19 @@ describe("multiple_root_compositions", () => {expect(totalErrors).toBeGreaterThan(0);});- it("does NOT fire with a single root composition", () => {+ it("does NOT fire with a single root composition", async () => {const project = makeProject(validHtml());- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "multiple_root_compositions",);expect(finding).toBeUndefined();});- it("ignores HTML files without data-composition-id", () => {+ it("ignores HTML files without data-composition-id", async () => {const project = makeProject(validHtml());writeFileSync(join(project.dir, "readme.html"), "<html><body>Not a composition</body></html>");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "multiple_root_compositions",);@@ -668,7 +668,7 @@ describe("multiple_root_compositions", () => {});describe("duplicate_audio_track", () => {- it("detects overlapping audio with attributes in any order", () => {+ it("detects overlapping audio with attributes in any order", async () => {// The original scaffold bug: data-start BEFORE data-track-indexconst html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-duration="30">@@ -678,13 +678,13 @@ describe("duplicate_audio_track", () => {<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("does NOT fire for non-overlapping audio on the same track", () => {+ it("does NOT fire for non-overlapping audio on the same track", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-duration="20"><audio id="a" src="a.wav" data-track-index="0" data-start="0" data-duration="10">@@ -693,12 +693,12 @@ describe("duplicate_audio_track", () => {<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeUndefined();});- it("does NOT fire for audio on different tracks", () => {+ it("does NOT fire for audio on different tracks", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-duration="20"><audio id="a" src="a.wav" data-track-index="0" data-start="0" data-duration="20">@@ -707,22 +707,22 @@ describe("duplicate_audio_track", () => {<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeUndefined();});- it("deduplicates same audio found in root + sub-composition", () => {+ it("deduplicates same audio found in root + sub-composition", async () => {const project = makeProject(validHtmlWithAudio(), {"scene.html": validHtmlWithAudio("scene"),});writeFileSync(join(project.dir, "song.mp3"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeUndefined();});- it("detects overlap when data-duration is missing (Infinity fallback)", () => {+ it("detects overlap when data-duration is missing (Infinity fallback)", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-duration="30"><audio id="a" src="a.wav" data-track-index="0" data-start="0" data-duration="20">@@ -731,12 +731,12 @@ describe("duplicate_audio_track", () => {<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeDefined();});- it("formats Infinity end times as 'end' without crashing", () => {+ it("formats Infinity end times as 'end' without crashing", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-duration="30"><audio id="a" src="a.wav" data-track-index="0" data-start="0">@@ -745,14 +745,14 @@ describe("duplicate_audio_track", () => {<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;const project = makeProject(html);- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");expect(finding).toBeDefined();expect(finding?.message).toContain("end");expect(finding?.message).not.toContain("Infinity");});- it("finds audio across multiple HTML sources (g-flag regression)", () => {+ it("finds audio across multiple HTML sources (g-flag regression)", async () => {const project = makeProject(validHtmlWithAudio(), {"scene.html": `<html><body><div data-composition-id="scene" data-width="1920" data-height="1080">@@ -763,7 +763,7 @@ describe("duplicate_audio_track", () => {});writeFileSync(join(project.dir, "song.mp3"), "fake");writeFileSync(join(project.dir, "music.wav"), "fake");- const { results } = lintProject(project);+ const { results } = await lintProject(project);const finding = results[0]?.result.findings.find((f) => f.code === "duplicate_audio_track");// song.mp3@0 (from validHtmlWithAudio, no data-duration → Infinity) and music.wav@5-25 overlapexpect(finding).toBeDefined();@@ -771,39 +771,39 @@ describe("duplicate_audio_track", () => {});describe("shouldBlockRender", () => {- it("default: does not block on errors", () => {+ it("default: does not block on errors", async () => {expect(shouldBlockRender(false, false, 5, 0)).toBe(false);});- it("default: does not block on warnings", () => {+ it("default: does not block on warnings", async () => {expect(shouldBlockRender(false, false, 0, 3)).toBe(false);});- it("--strict: blocks on errors", () => {+ it("--strict: blocks on errors", async () => {expect(shouldBlockRender(true, false, 1, 0)).toBe(true);});- it("--strict: does not block on warnings only", () => {+ it("--strict: does not block on warnings only", async () => {expect(shouldBlockRender(true, false, 0, 5)).toBe(false);});- it("--strict-all: blocks on errors", () => {+ it("--strict-all: blocks on errors", async () => {expect(shouldBlockRender(true, true, 1, 0)).toBe(true);});- it("--strict-all: blocks on warnings", () => {+ it("--strict-all: blocks on warnings", async () => {expect(shouldBlockRender(true, true, 0, 1)).toBe(true);});- it("--strict-all: does not block when clean", () => {+ it("--strict-all: does not block when clean", async () => {expect(shouldBlockRender(true, true, 0, 0)).toBe(false);});- it("--strict-all alone: blocks on errors", () => {+ it("--strict-all alone: blocks on errors", async () => {expect(shouldBlockRender(false, true, 1, 0)).toBe(true);});- it("--strict-all alone: blocks on warnings", () => {+ it("--strict-all alone: blocks on warnings", async () => {expect(shouldBlockRender(false, true, 0, 1)).toBe(true);});});diff --git a/packages/cli/src/utils/lintProject.ts b/packages/cli/src/utils/lintProject.tsindex a3a8f8d5ab..d2b69c68bb 100644--- a/packages/cli/src/utils/lintProject.ts+++ b/packages/cli/src/utils/lintProject.ts@@ -179,7 +179,7 @@ function resolveCssAssetCandidates(* Lint the root index.html and all sub-compositions in the compositions/ directory.* Returns aggregated results across all files.*/-export function lintProject(project: ProjectDir): ProjectLintResult {+export async function lintProject(project: ProjectDir): Promise<ProjectLintResult> {const results: Array<{ file: string; result: HyperframeLintResult }> = [];let totalErrors = 0;let totalWarnings = 0;@@ -187,7 +187,7 @@ export function lintProject(project: ProjectDir): ProjectLintResult {// Lint root compositionconst rootHtml = readFileSync(project.indexPath, "utf-8");- const rootResult = lintHyperframeHtml(rootHtml, {+ const rootResult = await lintHyperframeHtml(rootHtml, {filePath: project.indexPath,externalStyles: collectExternalStyles(project.dir, rootHtml),});@@ -206,7 +206,7 @@ export function lintProject(project: ProjectDir): ProjectLintResult {const html = readFileSync(filePath, "utf-8");const compSrcPath = `compositions/${file}`;allHtmlSources.push({ html, compSrcPath });- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath,isSubComposition: true,externalStyles: collectExternalStyles(project.dir, html, compSrcPath),diff --git a/packages/core/package.json b/packages/core/package.jsonindex f0b17f3f36..9b954e86d2 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -58,6 +58,14 @@"import": "./src/registry/index.ts","types": "./src/registry/index.ts"},+ "./gsap-parser": {+ "import": "./src/parsers/gsapParser.ts",+ "types": "./src/parsers/gsapParser.ts"+ },+ "./gsap-constants": {+ "import": "./src/parsers/gsapConstants.ts",+ "types": "./src/parsers/gsapConstants.ts"+ },"./schemas/registry.json": "./schemas/registry.json","./schemas/registry-item.json": "./schemas/registry-item.json"},@@ -105,6 +113,14 @@"import": "./dist/registry/index.js","types": "./dist/registry/index.d.ts"},+ "./gsap-parser": {+ "import": "./dist/parsers/gsapParser.js",+ "types": "./dist/parsers/gsapParser.d.ts"+ },+ "./gsap-constants": {+ "import": "./dist/parsers/gsapConstants.js",+ "types": "./dist/parsers/gsapConstants.d.ts"+ },"./schemas/registry.json": "./schemas/registry.json","./schemas/registry-item.json": "./schemas/registry-item.json"},@@ -134,8 +150,10 @@"prepublishOnly": "echo skip"},"dependencies": {+ "@babel/parser": "^7.27.0","@chenglou/pretext": "^0.0.5",- "postcss": "^8.5.8"+ "postcss": "^8.5.8",+ "recast": "^0.23.11"},"devDependencies": {"@types/jsdom": "^28.0.0",diff --git a/packages/core/scripts/check-hyperframe-static.ts b/packages/core/scripts/check-hyperframe-static.tsindex 4c37d10dac..e61e1ec754 100644--- a/packages/core/scripts/check-hyperframe-static.ts+++ b/packages/core/scripts/check-hyperframe-static.ts@@ -35,7 +35,7 @@ function formatHumanOutput(result: HyperframeLintResult, resolvedPath: string):return lines.join("\n");}-function main() {+async function main() {const args = process.argv.slice(2);const normalizedArgs = args[0] === "--" ? args.slice(1) : args;const jsonOutput = normalizedArgs.includes("--json");@@ -55,7 +55,7 @@ function main() {}const html = fs.readFileSync(resolvedPath, "utf-8");- const result = lintHyperframeHtml(html, { filePath: resolvedPath });+ const result = await lintHyperframeHtml(html, { filePath: resolvedPath });if (jsonOutput) {console.log(JSON.stringify(result, null, 2));diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.tsindex de590c8505..121b89336e 100644--- a/packages/core/src/compiler/htmlBundler.ts+++ b/packages/core/src/compiler/htmlBundler.ts@@ -623,7 +623,7 @@ export async function bundleToSingleHtml(const rawHtml = readFileSync(indexPath, "utf-8");const compiled = await compileHtml(rawHtml, projectDir, options?.probeMediaDuration);- const staticGuard = validateHyperframeHtmlContract(compiled);+ const staticGuard = await validateHyperframeHtmlContract(compiled);if (!staticGuard.isValid) {console.warn(`[StaticGuard] Invalid HyperFrame contract: ${staticGuard.missingKeys.join("; ")}`,diff --git a/packages/core/src/compiler/staticGuard.ts b/packages/core/src/compiler/staticGuard.tsindex 372d538b1e..a5fd791a8f 100644--- a/packages/core/src/compiler/staticGuard.ts+++ b/packages/core/src/compiler/staticGuard.ts@@ -13,8 +13,10 @@ export type HyperframeStaticGuardResult = {failureReason: HyperframeStaticFailureReason | null;};-export function validateHyperframeHtmlContract(html: string): HyperframeStaticGuardResult {- const result = lintHyperframeHtml(html);+export async function validateHyperframeHtmlContract(+ html: string,+): Promise<HyperframeStaticGuardResult> {+ const result = await lintHyperframeHtml(html);const missingKeys = result.findings.filter((finding) => finding.severity === "error").map((finding) => finding.message);diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.tsindex 2e406b5c27..f4ce86d22a 100644--- a/packages/core/src/index.test.ts+++ b/packages/core/src/index.test.ts@@ -97,23 +97,14 @@ describe("@hyperframes/core public API exports", () => {});describe("parser exports", () => {- it("exports GSAP parser functions", () => {- expect(typeof core.parseGsapScript).toBe("function");- expect(typeof core.serializeGsapAnimations).toBe("function");- expect(typeof core.updateAnimationInScript).toBe("function");- expect(typeof core.addAnimationToScript).toBe("function");- expect(typeof core.removeAnimationFromScript).toBe("function");- expect(typeof core.getAnimationsForElement).toBe("function");- expect(typeof core.validateCompositionGsap).toBe("function");- expect(typeof core.keyframesToGsapAnimations).toBe("function");- expect(typeof core.gsapAnimationsToKeyframes).toBe("function");- });-- it("exports GSAP constants", () => {- expect(core.SUPPORTED_PROPS).toBeDefined();- expect(Array.isArray(core.SUPPORTED_PROPS)).toBe(true);- expect(core.SUPPORTED_EASES).toBeDefined();- expect(Array.isArray(core.SUPPORTED_EASES)).toBe(true);+ it("does NOT re-export GSAP parser functions from barrel (available via gsap-parser subpath)", () => {+ // GSAP parser uses recast (Node.js fs), so it's excluded from the barrel+ // to keep browser bundles clean. Use @hyperframes/core/gsap-parser instead.+ expect(typeof (core as Record<string, unknown>).parseGsapScript).toBe("undefined");+ });++ it("does NOT re-export GSAP constants from barrel (available via gsap-constants subpath)", () => {+ expect((core as Record<string, unknown>).SUPPORTED_PROPS).toBeUndefined();});it("exports HTML parser functions", () => {diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex db25cba0ea..d1a4900822 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -71,22 +71,19 @@ export {ZOOM_CONTAINER_STYLES,} from "./templates/constants";-// Parsers-export type { GsapAnimation, GsapMethod, ParsedGsap } from "./parsers/gsapParser";+// Parsers — recast-free GSAP helpers only. The AST parser (parseGsapScript and+// the script-mutation helpers) depends on recast/@babel/parser, which break in+// browser/SSR bundles; it is reachable only via the Node-only+// `@hyperframes/core/gsap-parser` subpath.+export type { GsapAnimation, GsapMethod, ParsedGsap } from "./parsers/gsapSerialize";export {- parseGsapScript,serializeGsapAnimations,- updateAnimationInScript,- addAnimationToScript,- removeAnimationFromScript,getAnimationsForElement,validateCompositionGsap,keyframesToGsapAnimations,gsapAnimationsToKeyframes,- SUPPORTED_PROPS,- SUPPORTED_EASES,-} from "./parsers/gsapParser";+} from "./parsers/gsapSerialize";export type { ParsedHtml, CompositionMetadata } from "./parsers/htmlParser";diff --git a/packages/core/src/lint/hyperframeLinter.test.ts b/packages/core/src/lint/hyperframeLinter.test.tsindex 7285dca304..4d11a64e05 100644--- a/packages/core/src/lint/hyperframeLinter.test.ts+++ b/packages/core/src/lint/hyperframeLinter.test.ts@@ -18,33 +18,33 @@ describe("lintHyperframeHtml — orchestrator", () => {</body></html>`;- it("reports no errors for a valid composition", () => {- const result = lintHyperframeHtml(validComposition);+ it("reports no errors for a valid composition", async () => {+ const result = await lintHyperframeHtml(validComposition);expect(result.ok).toBe(true);expect(result.errorCount).toBe(0);});- it("attaches filePath to findings when option is set", () => {+ it("attaches filePath to findings when option is set", async () => {const html = "<html><body><div></div></body></html>";- const result = lintHyperframeHtml(html, { filePath: "test.html" });+ const result = await lintHyperframeHtml(html, { filePath: "test.html" });for (const finding of result.findings) {expect(finding.file).toBe("test.html");}});- it("deduplicates identical findings", () => {+ it("deduplicates identical findings", async () => {const html = `<html><body><div id="root"></div><script>const tl = gsap.timeline();</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const codes = result.findings.map((f) => `${f.code}|${f.message}`);const uniqueCodes = [...new Set(codes)];expect(codes.length).toBe(uniqueCodes.length);});- it("strips <template> wrapper before linting composition files", () => {+ it("strips <template> wrapper before linting composition files", async () => {const html = `<template id="my-comp-template"><div data-composition-id="my-comp" data-width="1920" data-height="1080"style="position:relative;width:1920px;height:1080px;">@@ -57,7 +57,7 @@ describe("lintHyperframeHtml — orchestrator", () => {window.__timelines["my-comp"] = tl;</script></template>`;- const result = lintHyperframeHtml(html, { filePath: "compositions/my-comp.html" });+ const result = await lintHyperframeHtml(html, { filePath: "compositions/my-comp.html" });const missing = result.findings.filter((f) => f.code === "missing-composition-id" || f.code === "missing-dimensions",);diff --git a/packages/core/src/lint/hyperframeLinter.ts b/packages/core/src/lint/hyperframeLinter.tsindex ff76579ba2..fcab47fcc7 100644--- a/packages/core/src/lint/hyperframeLinter.ts+++ b/packages/core/src/lint/hyperframeLinter.ts@@ -21,16 +21,16 @@ const ALL_RULES = [...fontRules,];-export function lintHyperframeHtml(+export async function lintHyperframeHtml(html: string,options: HyperframeLinterOptions = {},-): HyperframeLintResult {+): Promise<HyperframeLintResult> {const ctx = buildLintContext(html, options);const findings: HyperframeLintFinding[] = [];const seen = new Set<string>();for (const rule of ALL_RULES) {- for (const finding of rule(ctx)) {+ for (const finding of await Promise.resolve(rule(ctx))) {const dedupeKey = [finding.code,finding.severity,diff --git a/packages/core/src/lint/rules/adapters.test.ts b/packages/core/src/lint/rules/adapters.test.tsindex 3fedd10284..938efc7842 100644--- a/packages/core/src/lint/rules/adapters.test.ts+++ b/packages/core/src/lint/rules/adapters.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("adapter rules", () => {- it("reports error when GSAP is used without a GSAP script tag", () => {+ it("reports error when GSAP is used without a GSAP script tag", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -13,14 +13,14 @@ describe("adapter rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("GSAP");});- it("does not report missing_gsap_script when GSAP CDN script is present", () => {+ it("does not report missing_gsap_script when GSAP CDN script is present", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -32,12 +32,12 @@ describe("adapter rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("reports error when Lottie container exists without a Lottie script tag", () => {+ it("reports error when Lottie container exists without a Lottie script tag", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -48,14 +48,14 @@ describe("adapter rules", () => {window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_lottie_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("Lottie");});- it("reports error when lottie.loadAnimation is used without a Lottie script tag", () => {+ it("reports error when lottie.loadAnimation is used without a Lottie script tag", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -65,13 +65,13 @@ describe("adapter rules", () => {lottie.loadAnimation({ container: document.getElementById('lottie'), path: 'anim.json' });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_lottie_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("does not report missing_lottie_script when Lottie CDN script is present", () => {+ it("does not report missing_lottie_script when Lottie CDN script is present", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -83,12 +83,12 @@ describe("adapter rules", () => {window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_lottie_script");expect(finding).toBeUndefined();});- it("reports error when Three.js is used without a Three.js script tag", () => {+ it("reports error when Three.js is used without a Three.js script tag", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -99,14 +99,14 @@ describe("adapter rules", () => {const renderer = new THREE.WebGLRenderer();</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_three_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("Three.js");});- it("does not report missing_three_script when Three.js CDN script is present", () => {+ it("does not report missing_three_script when Three.js CDN script is present", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -118,12 +118,12 @@ describe("adapter rules", () => {const renderer = new THREE.WebGLRenderer();</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_three_script");expect(finding).toBeUndefined();});- it("does not report any adapter errors for composition with no adapter usage", () => {+ it("does not report any adapter errors for composition with no adapter usage", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -134,7 +134,7 @@ describe("adapter rules", () => {window.__timelines["main"] = { totalDuration: function() { return 3; } };</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const adapterFindings = result.findings.filter((f) =>["missing_gsap_script", "missing_lottie_script", "missing_three_script"].includes(f.code),);diff --git a/packages/core/src/lint/rules/captions.test.ts b/packages/core/src/lint/rules/captions.test.tsindex 9ae3c02c3a..f43462e8c5 100644--- a/packages/core/src/lint/rules/captions.test.ts+++ b/packages/core/src/lint/rules/captions.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("caption rules", () => {- it("warns when caption exit has no hard kill tl.set", () => {+ it("warns when caption exit has no hard kill tl.set", async () => {const html = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080">@@ -20,13 +20,13 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_exit_missing_hard_kill");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("does not warn when caption exit has hard kill tl.set", () => {+ it("does not warn when caption exit has hard kill tl.set", async () => {const html = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080">@@ -45,12 +45,12 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_exit_missing_hard_kill");expect(finding).toBeUndefined();});- it("does not warn for generic GSAP opacity exits in non-caption loops", () => {+ it("does not warn for generic GSAP opacity exits in non-caption loops", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -67,12 +67,12 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_exit_missing_hard_kill");expect(finding).toBeUndefined();});- it("warns when caption group has nowrap without max-width", () => {+ it("warns when caption group has nowrap without max-width", async () => {const html = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080">@@ -90,13 +90,13 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_text_overflow_risk");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("does not warn when caption group has nowrap with max-width", () => {+ it("does not warn when caption group has nowrap with max-width", async () => {const html = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080">@@ -115,14 +115,14 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_text_overflow_risk" && f.severity === "warning",);expect(finding).toBeUndefined();});- it("warns when caption container uses position: relative", () => {+ it("warns when caption container uses position: relative", async () => {const html = `<html><body><div data-composition-id="captions" data-width="1920" data-height="1080">@@ -138,7 +138,7 @@ describe("caption rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "caption_container_relative_position");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");diff --git a/packages/core/src/lint/rules/composition.test.ts b/packages/core/src/lint/rules/composition.test.tsindex 69fe23ed31..8ede1c0d8e 100644--- a/packages/core/src/lint/rules/composition.test.ts+++ b/packages/core/src/lint/rules/composition.test.ts@@ -3,39 +3,41 @@ import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("composition rules", () => {describe("subcomposition guidance", () => {- it("warns when any HTML composition file is over 300 lines", () => {+ it("warns when any HTML composition file is over 300 lines", async () => {const html = Array.from({ length: 301 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, { filePath: "/project/compositions/scene.html" });+ const result = await lintHyperframeHtml(html, {+ filePath: "/project/compositions/scene.html",+ });const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("does not warn when an HTML composition file is exactly 300 lines", () => {+ it("does not warn when an HTML composition file is exactly 300 lines", async () => {const html = Array.from({ length: 300 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeUndefined();});- it("does not count a final trailing newline as an extra physical line", () => {+ it("does not count a final trailing newline as an extra physical line", async () => {const html =Array.from({ length: 300 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n") + "\n";- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeUndefined();});- it("does not count inline style block internals as structural lines", () => {+ it("does not count inline style block internals as structural lines", async () => {const style = `<style>\n${Array.from({ length: 320 }, (_, i) => `.rule-${i} { color: red; }`).join("\n")}\n</style>`;const html = `<!doctype html><html>@@ -45,29 +47,29 @@ describe("composition rules", () => {</body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeUndefined();});- it("does not warn for large registry source block files", () => {+ it("does not warn for large registry source block files", async () => {const html = Array.from({ length: 301 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/registry/blocks/data-chart/data-chart.html",});const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeUndefined();});- it("warns for large installed block composition files", () => {+ it("warns for large installed block composition files", async () => {const html = Array.from({ length: 301 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/data-chart.html",});const finding = result.findings.find((f) => f.code === "composition_file_too_large");@@ -75,26 +77,26 @@ describe("composition rules", () => {expect(finding?.severity).toBe("warning");});- it("does not warn for large registry-installed block composition files", () => {+ it("does not warn for large registry-installed block composition files", async () => {const html ="<!-- hyperframes-registry-item: data-chart -->\n" +Array.from({ length: 300 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/data-chart.html",});const finding = result.findings.find((f) => f.code === "composition_file_too_large");expect(finding).toBeUndefined();});- it("uses nested split copy for large sub-composition files", () => {+ it("uses nested split copy for large sub-composition files", async () => {const html = Array.from({ length: 301 }, (_, i) =>i === 0 ? "<html><body>" : `<!-- filler ${i} -->`,).join("\n");- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/scene.html",isSubComposition: true,});@@ -102,7 +104,7 @@ describe("composition rules", () => {expect(finding?.fixHint).toContain("Split this sub-composition further");});- it("warns when more than 3 timed elements share the same track", () => {+ it("warns when more than 3 timed elements share the same track", async () => {const html = `<!DOCTYPE html><html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0">@@ -113,14 +115,16 @@ describe("composition rules", () => {</div></body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/compositions/scene.html" });+ const result = await lintHyperframeHtml(html, {+ filePath: "/project/compositions/scene.html",+ });const finding = result.findings.find((f) => f.code === "timeline_track_too_dense");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");expect(finding?.message).toContain("Track 0 has 4 timed elements");});- it("does not warn when 3 timed elements share the same track", () => {+ it("does not warn when 3 timed elements share the same track", async () => {const html = `<!DOCTYPE html><html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0">@@ -130,12 +134,12 @@ describe("composition rules", () => {</div></body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "timeline_track_too_dense");expect(finding).toBeUndefined();});- it("does not warn when timed elements are split across tracks", () => {+ it("does not warn when timed elements are split across tracks", async () => {const html = `<!DOCTYPE html><html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0">@@ -146,12 +150,12 @@ describe("composition rules", () => {</div></body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "timeline_track_too_dense");expect(finding).toBeUndefined();});- it("does not count timed media or script/style tags as dense track elements", () => {+ it("does not count timed media or script/style tags as dense track elements", async () => {const html = `<!DOCTYPE html><html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0">@@ -163,12 +167,12 @@ describe("composition rules", () => {</div></body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "timeline_track_too_dense");expect(finding).toBeUndefined();});- it("does not count root composition or mounted sub-compositions as dense elements", () => {+ it("does not count root composition or mounted sub-compositions as dense elements", async () => {const html = `<!DOCTYPE html><html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-track-index="0">@@ -179,13 +183,13 @@ describe("composition rules", () => {</div></body></html>`;- const result = lintHyperframeHtml(html, { filePath: "/project/index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "/project/index.html" });const finding = result.findings.find((f) => f.code === "timeline_track_too_dense");expect(finding).toBeUndefined();});});- it("reports info for composition with external CDN script dependency", () => {+ it("reports info for composition with external CDN script dependency", async () => {const html = `<template id="rockets-template"><div data-composition-id="rockets" data-width="1920" data-height="1080"><div id="rocket-container"></div>@@ -197,7 +201,7 @@ describe("composition rules", () => {</script></div></template>`;- const result = lintHyperframeHtml(html, { filePath: "compositions/rockets.html" });+ const result = await lintHyperframeHtml(html, { filePath: "compositions/rockets.html" });const finding = result.findings.find((f) => f.code === "external_script_dependency" && f.message.includes("cdnjs.cloudflare.com"),);@@ -208,7 +212,7 @@ describe("composition rules", () => {expect(result.errorCount).toBe(0);});- it("does not report external_script_dependency for inline scripts", () => {+ it("does not report external_script_dependency for inline scripts", async () => {const html = `<html><body><div id="root" data-composition-id="main" data-width="1920" data-height="1080">@@ -219,11 +223,11 @@ describe("composition rules", () => {</script></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);expect(result.findings.find((f) => f.code === "external_script_dependency")).toBeUndefined();});- it("reports error when querySelector uses template literal variable", () => {+ it("reports error when querySelector uses template literal variable", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -237,13 +241,13 @@ describe("composition rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "template_literal_selector");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("reports error for querySelectorAll with template literal variable", () => {+ it("reports error for querySelectorAll with template literal variable", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -255,12 +259,12 @@ describe("composition rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "template_literal_selector");expect(finding).toBeDefined();});- it("does not report error for hardcoded querySelector strings", () => {+ it("does not report error for hardcoded querySelector strings", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080">@@ -273,12 +277,12 @@ describe("composition rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "template_literal_selector");expect(finding).toBeUndefined();});- it("reports error when a selector combines data attributes in one bracket", () => {+ it("reports error when a selector combines data attributes in one bracket", async () => {const html = `<template id="scene-template"><div data-composition-id="scene" data-start="0" data-width="1920" data-height="1080">@@ -294,7 +298,7 @@ describe("composition rules", () => {</script></div></template>`;- const result = lintHyperframeHtml(html, { filePath: "compositions/scene.html" });+ const result = await lintHyperframeHtml(html, { filePath: "compositions/scene.html" });const findings = result.findings.filter((f) => f.code === "split_data_attribute_selector");expect(findings.length).toBe(1);expect(findings[0]?.severity).toBe("error");@@ -302,7 +306,7 @@ describe("composition rules", () => {});describe("timed_element_missing_clip_class", () => {- it("flags element with data-start but no class='clip'", () => {+ it("flags element with data-start but no class='clip'", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -313,13 +317,13 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "timed_element_missing_clip_class");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("does not flag element that has class='clip'", () => {+ it("does not flag element that has class='clip'", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -330,12 +334,12 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "timed_element_missing_clip_class");expect(finding).toBeUndefined();});- it("does not flag audio or video elements", () => {+ it("does not flag audio or video elements", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -347,14 +351,14 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "timed_element_missing_clip_class");expect(finding).toBeUndefined();});});describe("overlapping_clips_same_track", () => {- it("flags overlapping clips on the same track", () => {+ it("flags overlapping clips on the same track", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -366,13 +370,13 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "overlapping_clips_same_track");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("does not flag clips on different tracks", () => {+ it("does not flag clips on different tracks", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -384,12 +388,12 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "overlapping_clips_same_track");expect(finding).toBeUndefined();});- it("does not flag sequential clips on the same track", () => {+ it("does not flag sequential clips on the same track", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -401,14 +405,14 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "overlapping_clips_same_track");expect(finding).toBeUndefined();});});describe("root_composition_missing_html_wrapper", () => {- it("flags bare composition div as error", () => {+ it("flags bare composition div as error", async () => {// Exact scenario from the screenshot — bare div with composition attributes, no HTML wrapperconst html = `<divid="comp-main"@@ -434,7 +438,7 @@ describe("composition rules", () => {window.__timelines["no-limits"] = tl;</script></div>`;- const result = lintHyperframeHtml(html, { filePath: "index.html" });+ const result = await lintHyperframeHtml(html, { filePath: "index.html" });const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);@@ -443,7 +447,7 @@ describe("composition rules", () => {expect(result.ok).toBe(false);});- it("does not flag properly wrapped HTML composition", () => {+ it("does not flag properly wrapped HTML composition", async () => {const html = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="10">@@ -454,14 +458,14 @@ describe("composition rules", () => {window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);expect(finding).toBeUndefined();});- it("does not flag composition starting with <html> (no doctype)", () => {+ it("does not flag composition starting with <html> (no doctype)", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="5"></div><script>@@ -469,44 +473,44 @@ describe("composition rules", () => {window.__timelines["main"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);expect(finding).toBeUndefined();});- it("does not flag sub-compositions", () => {+ it("does not flag sub-compositions", async () => {const html = `<div data-composition-id="sub" data-width="1920" data-height="1080"><script>window.__timelines = window.__timelines || {};window.__timelines["sub"] = gsap.timeline({ paused: true });</script></div>`;- const result = lintHyperframeHtml(html, { isSubComposition: true });+ const result = await lintHyperframeHtml(html, { isSubComposition: true });const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);expect(finding).toBeUndefined();});- it("does not flag HTML without composition attributes", () => {+ it("does not flag HTML without composition attributes", async () => {const html = `<div id="hello"><p>Not a composition</p></div>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);expect(finding).toBeUndefined();});- it("includes root tag snippet in finding", () => {+ it("includes root tag snippet in finding", async () => {const html = `<div data-composition-id="bare" data-width="1920" data-height="1080"><script>window.__timelines = window.__timelines || {};window.__timelines["bare"] = gsap.timeline({ paused: true });</script></div>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_composition_missing_html_wrapper",);@@ -516,7 +520,7 @@ describe("composition rules", () => {});describe("standalone_composition_wrapped_in_template", () => {- it("flags root index.html wrapped in template", () => {+ it("flags root index.html wrapped in template", async () => {const html = `<template id="main-template"><div data-composition-id="main" data-width="1920" data-height="1080"><script>@@ -525,7 +529,7 @@ describe("composition rules", () => {</script></div></template>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "standalone_composition_wrapped_in_template",);@@ -533,7 +537,7 @@ describe("composition rules", () => {expect(finding?.severity).toBe("warning");});- it("does not flag sub-compositions in template", () => {+ it("does not flag sub-compositions in template", async () => {const html = `<template id="sub-template"><div data-composition-id="sub" data-width="1920" data-height="1080"><script>@@ -542,7 +546,7 @@ describe("composition rules", () => {</script></div></template>`;- const result = lintHyperframeHtml(html, { isSubComposition: true });+ const result = await lintHyperframeHtml(html, { isSubComposition: true });const finding = result.findings.find((f) => f.code === "standalone_composition_wrapped_in_template",);@@ -551,7 +555,7 @@ describe("composition rules", () => {});describe("requestanimationframe_in_composition", () => {- it("flags requestAnimationFrame usage in script content", () => {+ it("flags requestAnimationFrame usage in script content", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -561,7 +565,7 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "requestanimationframe_in_composition",);@@ -569,7 +573,7 @@ describe("composition rules", () => {expect(finding?.severity).toBe("warning");});- it("does not flag requestAnimationFrame in comments", () => {+ it("does not flag requestAnimationFrame in comments", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -579,7 +583,7 @@ describe("composition rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "requestanimationframe_in_composition",);@@ -596,7 +600,7 @@ describe("composition rules", () => {// GSAP rules); these tests pin the removal so the rule does not silently// come back.- it("does not warn on a docs-compliant root with no data-duration", () => {+ it("does not warn on a docs-compliant root with no data-duration", async () => {// The documented authoring model: root composition without// data-duration, runtime derives it from the GSAP timeline.const html = `<!DOCTYPE html><html><body>@@ -608,14 +612,14 @@ describe("composition rules", () => {window.__timelines["docs"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_composition_missing_data_duration",);expect(finding).toBeUndefined();});- it("does not warn even on the original Infinity-risk shape (no media, looping timeline)", () => {+ it("does not warn even on the original Infinity-risk shape (no media, looping timeline)", async () => {// This was the canonical "warn" case under the old rule — root with no// data-duration, no media, GSAP timeline driven by repeat: -1. The// looping shape itself is now flagged by `gsap_infinite_repeat`; the@@ -632,7 +636,7 @@ describe("composition rules", () => {window.__timelines["loopy"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);// The deprecated rule must not fire.const removedFinding = result.findings.find((f) => f.code === "root_composition_missing_data_duration",@@ -647,81 +651,81 @@ describe("composition rules", () => {});describe("root_composition_missing_data_start", () => {- it("does not warn for template-wrapped sub-composition files", () => {+ it("does not warn for template-wrapped sub-composition files", async () => {const html = `<template id="foo-template"><div data-composition-id="foo" data-width="1920" data-height="1080"><div class="clip" data-start="0" data-duration="1"></div></div></template>`;- const result = lintHyperframeHtml(html, { isSubComposition: true });+ const result = await lintHyperframeHtml(html, { isSubComposition: true });const finding = result.findings.find((f) => f.code === "root_composition_missing_data_start");expect(finding).toBeUndefined();});});describe("invalid_variable_values_json", () => {- it("warns when data-variable-values is unparseable JSON", () => {+ it("warns when data-variable-values is unparseable JSON", async () => {const html = `<html><body><div data-composition-id="card-1" data-composition-src="card.html" data-variable-values='{not json'></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_variable_values_json");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("warns when data-variable-values is a JSON array (must be an object)", () => {+ it("warns when data-variable-values is a JSON array (must be an object)", async () => {const html = `<html><body><div data-composition-src="card.html" data-variable-values='[1,2,3]'></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_variable_values_json");expect(finding).toBeDefined();expect(finding?.message).toMatch(/must be a JSON object/);});- it("warns when data-variable-values is a JSON string (must be an object)", () => {+ it("warns when data-variable-values is a JSON string (must be an object)", async () => {const html = `<html><body><div data-composition-src="card.html" data-variable-values='"hello"'></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_variable_values_json");expect(finding).toBeDefined();});- it("does not warn for a valid JSON object", () => {+ it("does not warn for a valid JSON object", async () => {const html = `<html><body><div data-composition-src="card.html" data-variable-values='{"title":"Hello","count":3}'></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_variable_values_json");expect(finding).toBeUndefined();});- it("does not warn when data-variable-values is absent", () => {+ it("does not warn when data-variable-values is absent", async () => {const html = `<html><body><div data-composition-src="card.html"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_variable_values_json");expect(finding).toBeUndefined();});});describe("invalid_composition_variables_declaration", () => {- it("warns when data-composition-variables is unparseable JSON", () => {+ it("warns when data-composition-variables is unparseable JSON", async () => {const html = `<html data-composition-variables='[{not json'><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_composition_variables_declaration",);expect(finding).toBeDefined();});- it("warns when data-composition-variables is not an array", () => {+ it("warns when data-composition-variables is not an array", async () => {const html = `<html data-composition-variables='{"title":"Hello"}'><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_composition_variables_declaration",);@@ -729,9 +733,9 @@ describe("composition rules", () => {expect(finding?.message).toMatch(/array of variable declarations/);});- it("warns per-entry when an entry is missing required fields", () => {+ it("warns per-entry when an entry is missing required fields", async () => {const html = `<html data-composition-variables='[{"id":"ok","type":"string","label":"Ok","default":"x"},{"id":"bad"}]'><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const findings = result.findings.filter((f) => f.code === "invalid_composition_variables_declaration",);@@ -740,9 +744,9 @@ describe("composition rules", () => {expect(findings[0]?.message).toMatch(/type|label|default/);});- it("warns when a declaration uses an unknown type", () => {+ it("warns when a declaration uses an unknown type", async () => {const html = `<html data-composition-variables='[{"id":"x","type":"date","label":"X","default":"y"}]'><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_composition_variables_declaration",);@@ -750,22 +754,22 @@ describe("composition rules", () => {expect(finding?.message).toMatch(/type/);});- it("does not warn for a fully valid declarations array", () => {+ it("does not warn for a fully valid declarations array", async () => {const html = `<html data-composition-variables='[{"id":"title","type":"string","label":"Title","default":"Hello"},{"id":"count","type":"number","label":"Count","default":3},{"id":"theme","type":"enum","label":"Theme","default":"light","options":[{"value":"light","label":"Light"}]}]'><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_composition_variables_declaration",);expect(finding).toBeUndefined();});- it("does not warn when data-composition-variables is absent", () => {+ it("does not warn when data-composition-variables is absent", async () => {const html = `<html><body><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "invalid_composition_variables_declaration",);@@ -774,13 +778,13 @@ describe("composition rules", () => {});describe("invalid_capture_path", () => {- it("errors when an <img> src uses ../capture/", () => {+ it("errors when an <img> src uses ../capture/", async () => {const html = `<html><body><div data-composition-id="x"><img src="../capture/assets/logo.svg" alt="logo"></div></body></html>`;- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/scene.html",});const finding = result.findings.find((f) => f.code === "invalid_capture_path");@@ -788,7 +792,7 @@ describe("composition rules", () => {expect(finding?.severity).toBe("error");});- it("errors when a CSS url() uses ../capture/ (counts all occurrences)", () => {+ it("errors when a CSS url() uses ../capture/ (counts all occurrences)", async () => {const html = `<html><body><style>@font-face { font-family: 'Brand'; src: url('../capture/assets/fonts/Brand.woff2'); }@@ -796,7 +800,7 @@ describe("composition rules", () => {</style><div data-composition-id="x"></div></body></html>`;- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/scene.html",});const finding = result.findings.find((f) => f.code === "invalid_capture_path");@@ -804,14 +808,14 @@ describe("composition rules", () => {expect(finding?.message).toContain("2 asset path(s)");});- it("does not flag root-relative capture/ paths", () => {+ it("does not flag root-relative capture/ paths", async () => {const html = `<html><body><div data-composition-id="x"><img src="capture/assets/logo.svg" alt="logo"></div><style>.hero { background-image: url('capture/assets/hero.png'); }</style></body></html>`;- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {filePath: "/project/compositions/scene.html",});const finding = result.findings.find((f) => f.code === "invalid_capture_path");diff --git a/packages/core/src/lint/rules/core.test.ts b/packages/core/src/lint/rules/core.test.tsindex 778e8de164..cd5525648a 100644--- a/packages/core/src/lint/rules/core.test.ts+++ b/packages/core/src/lint/rules/core.test.ts@@ -2,31 +2,31 @@ import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("core rules", () => {- it("reports error when root is missing data-composition-id", () => {+ it("reports error when root is missing data-composition-id", async () => {const html = `<html><body><div id="root" data-width="1920" data-height="1080"></div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_missing_composition_id");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("reports error when root is missing data-width or data-height", () => {+ it("reports error when root is missing data-width or data-height", async () => {const html = `<html><body><div id="root" data-composition-id="c1"></div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "root_missing_dimensions");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("reports error when timeline registry is missing", () => {+ it("reports error when timeline registry is missing", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -34,12 +34,12 @@ describe("core rules", () => {const tl = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_timeline_registry");expect(finding).toBeDefined();});- it("reports error for composition host missing data-composition-id", () => {+ it("reports error for composition host missing data-composition-id", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -47,12 +47,12 @@ describe("core rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "host_missing_composition_id");expect(finding).toBeDefined();});- it("reports error when timeline registry is assigned without initializing", () => {+ it("reports error when timeline registry is assigned without initializing", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -64,14 +64,14 @@ describe("core rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "timeline_registry_missing_init");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("without initializing");});- it("does not flag timeline assignment when init guard is present", () => {+ it("does not flag timeline assignment when init guard is present", async () => {const validComposition = `<html><body>@@ -87,12 +87,12 @@ describe("core rules", () => {</script></body></html>`;- const result = lintHyperframeHtml(validComposition);+ const result = await lintHyperframeHtml(validComposition);const finding = result.findings.find((f) => f.code === "timeline_registry_missing_init");expect(finding).toBeUndefined();});- it("warns when a timeline-visible element has no stable id for Studio editing", () => {+ it("warns when a timeline-visible element has no stable id for Studio editing", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -100,7 +100,7 @@ describe("core rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "studio_missing_editable_id");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");@@ -108,7 +108,7 @@ describe("core rules", () => {expect(finding?.fixHint).toContain("stable, human-readable id");});- it("does not warn about the composition root or timeline elements with ids", () => {+ it("does not warn about the composition root or timeline elements with ids", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080" data-start="0">@@ -116,13 +116,13 @@ describe("core rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "studio_missing_editable_id");expect(finding).toBeUndefined();});describe("non_deterministic_code", () => {- it("detects Math.random() in script content", () => {+ it("detects Math.random() in script content", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -132,14 +132,14 @@ describe("core rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "non_deterministic_code");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("Math.random");});- it("detects Date.now() in script content", () => {+ it("detects Date.now() in script content", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -149,14 +149,14 @@ describe("core rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "non_deterministic_code");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("Date.now");});- it("does not flag non-deterministic calls inside single-line comments", () => {+ it("does not flag non-deterministic calls inside single-line comments", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080"></div>@@ -167,14 +167,14 @@ describe("core rules", () => {window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "non_deterministic_code");expect(finding).toBeUndefined();});});describe("composition_self_attribute_selector", () => {- it("warns when inline CSS targets the root composition id", () => {+ it("warns when inline CSS targets the root composition id", async () => {const html = `<html><body><div id="scene" data-composition-id="scene" data-width="1920" data-height="1080">@@ -186,7 +186,7 @@ describe("core rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const findings = result.findings.filter((f) => f.code === "composition_self_attribute_selector",);@@ -198,13 +198,13 @@ describe("core rules", () => {expect(findings[0]?.fixHint).not.toContain("#556");});- it("warns when external CSS targets the root composition id", () => {+ it("warns when external CSS targets the root composition id", async () => {const html = `<html><body><div id="scene" data-composition-id="scene" data-width="1920" data-height="1080"></div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html, {+ const result = await lintHyperframeHtml(html, {externalStyles: [{href: "scene.css",@@ -218,7 +218,7 @@ describe("core rules", () => {expect(finding?.selector).toBe('[data-composition-id="scene"] .title');});- it("does not warn when CSS targets a different composition id", () => {+ it("does not warn when CSS targets a different composition id", async () => {const html = `<html><body><div id="scene" data-composition-id="scene" data-width="1920" data-height="1080">@@ -226,7 +226,7 @@ describe("core rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "composition_self_attribute_selector");expect(finding).toBeUndefined();diff --git a/packages/core/src/lint/rules/fonts.test.ts b/packages/core/src/lint/rules/fonts.test.tsindex af35df87f0..4bd21b2f98 100644--- a/packages/core/src/lint/rules/fonts.test.ts+++ b/packages/core/src/lint/rules/fonts.test.ts@@ -1,82 +1,82 @@import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";-function findByCode(html: string, code: string, isSubComposition = true) {- const result = lintHyperframeHtml(html, { isSubComposition });+async function findByCode(html: string, code: string, isSubComposition = true) {+ const result = await lintHyperframeHtml(html, { isSubComposition });return result.findings.filter((f) => f.code === code);}describe("font rules", () => {describe("google_fonts_import", () => {- it("flags @import url with fonts.googleapis.com", () => {+ it("flags @import url with fonts.googleapis.com", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap');</style></div>`;- const findings = findByCode(html, "google_fonts_import");+ const findings = await findByCode(html, "google_fonts_import");expect(findings).toHaveLength(1);expect(findings[0]!.severity).toBe("warning");});- it("flags <link> to fonts.googleapis.com", () => {+ it("flags <link> to fonts.googleapis.com", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter"></div>`;- const findings = findByCode(html, "google_fonts_import");+ const findings = await findByCode(html, "google_fonts_import");expect(findings).toHaveLength(1);});- it("does not flag local @font-face usage", () => {+ it("does not flag local @font-face usage", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>@font-face { font-family: 'Inter'; src: url('../capture/assets/fonts/Inter.woff2'); }</style></div>`;- const findings = findByCode(html, "google_fonts_import");+ const findings = await findByCode(html, "google_fonts_import");expect(findings).toHaveLength(0);});});describe("font_family_without_font_face", () => {- it("flags font-family used without @font-face", () => {+ it("flags font-family used without @font-face", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>body { font-family: 'GT Walsheim', sans-serif; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(1);expect(findings[0]!.message).toContain("gt walsheim");});- it("does not flag when @font-face is declared", () => {+ it("does not flag when @font-face is declared", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>@font-face { font-family: 'GT Walsheim'; src: url('../fonts/gt.woff2'); }body { font-family: 'GT Walsheim', sans-serif; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(0);});- it("does not flag generic font families", () => {+ it("does not flag generic font families", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>body { font-family: monospace; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(0);});- it("reports multiple missing families in one finding", () => {+ it("reports multiple missing families in one finding", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>h1 { font-family: 'Aeonik', sans-serif; }code { font-family: 'Feature Deck', monospace; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(1);expect(findings[0]!.message).toContain("aeonik");expect(findings[0]!.message).toContain("feature deck");});- it("does not flag fonts the producer has pre-bundled", () => {+ it("does not flag fonts the producer has pre-bundled", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>body { font-family: 'Inter', sans-serif; }@@ -84,37 +84,37 @@ describe("font rules", () => {h1 { font-family: 'Roboto', sans-serif; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(0);});- it("still flags Google-Fonts-only fonts not pre-bundled", () => {+ it("still flags Google-Fonts-only fonts not pre-bundled", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>body { font-family: 'Geist', sans-serif; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(1);expect(findings[0]!.message).toContain("geist");});- it("is case-insensitive when matching @font-face to font-family", () => {+ it("is case-insensitive when matching @font-face to font-family", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>@font-face { font-family: 'Inter'; src: url('../fonts/inter.woff2'); }body { font-family: 'inter', sans-serif; }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(0);});- it("ignores font-family inside @font-face blocks", () => {+ it("ignores font-family inside @font-face blocks", async () => {const html = `<div data-composition-id="test" data-width="1920" data-height="1080"><style>@font-face { font-family: 'CustomFont'; src: url('../fonts/custom.woff2'); }</style></div>`;- const findings = findByCode(html, "font_family_without_font_face");+ const findings = await findByCode(html, "font_family_without_font_face");expect(findings).toHaveLength(0);});});diff --git a/packages/core/src/lint/rules/gsap.test.ts b/packages/core/src/lint/rules/gsap.test.tsindex 5dd6e2e5ee..921cc46934 100644--- a/packages/core/src/lint/rules/gsap.test.ts+++ b/packages/core/src/lint/rules/gsap.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("GSAP rules", () => {- it("does NOT error when GSAP animates opacity on a clip element (by id)", () => {+ it("does NOT error when GSAP animates opacity on a clip element (by id)", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -17,12 +17,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT error when GSAP targets a clip element with safe properties (by class)", () => {+ it("does NOT error when GSAP targets a clip element with safe properties (by class)", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -37,12 +37,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT flag GSAP targeting a child of a clip element", () => {+ it("does NOT flag GSAP targeting a child of a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -57,12 +57,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT flag GSAP targeting a nested selector like '#overlay .title'", () => {+ it("does NOT flag GSAP targeting a nested selector like '#overlay .title'", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -77,12 +77,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT error when GSAP targets a clip element with safe properties (class-only, no id)", () => {+ it("does NOT error when GSAP targets a clip element with safe properties (class-only, no id)", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -97,12 +97,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT error when GSAP animates opacity on a clip element", () => {+ it("does NOT error when GSAP animates opacity on a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -117,12 +117,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT error when GSAP animates transform props on a clip element", () => {+ it("does NOT error when GSAP animates transform props on a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -137,12 +137,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeUndefined();});- it("does NOT require a local GSAP script for sub-compositions", () => {+ it("does NOT require a local GSAP script for sub-compositions", async () => {const html = `<template id="intro-template"><div data-composition-id="intro" data-width="1920" data-height="1080"><div class="title">Hello</div>@@ -155,12 +155,12 @@ describe("GSAP rules", () => {</div></template>`;- const result = lintHyperframeHtml(html, { isSubComposition: true });+ const result = await lintHyperframeHtml(html, { isSubComposition: true });const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("does NOT require a local GSAP script when a template composition is linted in isolation", () => {+ it("does NOT require a local GSAP script when a template composition is linted in isolation", async () => {const html = `<template id="intro-template"><div data-composition-id="intro" data-width="1920" data-height="1080"><div class="title">Hello</div>@@ -173,12 +173,12 @@ describe("GSAP rules", () => {</div></template>`;- const result = lintHyperframeHtml(html, { filePath: "compositions/intro.html" });+ const result = await lintHyperframeHtml(html, { filePath: "compositions/intro.html" });const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("ERRORS when GSAP animates visibility on a clip element", () => {+ it("ERRORS when GSAP animates visibility on a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -193,7 +193,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");@@ -201,7 +201,7 @@ describe("GSAP rules", () => {expect(finding?.message).toContain("visibility");});- it("ERRORS when GSAP animates display on a clip element", () => {+ it("ERRORS when GSAP animates display on a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -216,7 +216,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");@@ -224,7 +224,7 @@ describe("GSAP rules", () => {expect(finding?.message).toContain("display");});- it("ERRORS when GSAP tween mixes safe properties with visibility on a clip element", () => {+ it("ERRORS when GSAP tween mixes safe properties with visibility on a clip element", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -239,14 +239,14 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_animates_clip_element");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("visibility");});- it("warns when tl.to animates x on an element with CSS translateX", () => {+ it("warns when tl.to animates x on an element with CSS translateX", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -262,7 +262,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");@@ -271,7 +271,7 @@ describe("GSAP rules", () => {expect(finding?.fixHint).toMatch(/xPercent/);});- it("warns when tl.to animates scale on an element with CSS scale transform", () => {+ it("warns when tl.to animates scale on an element with CSS scale transform", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -287,14 +287,14 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");expect(finding?.selector).toBe("#hero");});- it("does NOT warn when tl.to targets element without CSS transform", () => {+ it("does NOT warn when tl.to targets element without CSS transform", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -310,12 +310,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const conflict = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(conflict).toBeUndefined();});- it("does NOT warn when tl.fromTo targets element WITH CSS transform (author owns both ends)", () => {+ it("does NOT warn when tl.fromTo targets element WITH CSS transform (author owns both ends)", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -331,12 +331,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const conflict = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(conflict).toBeUndefined();});- it("emits one warning when a combined CSS transform conflicts with multiple GSAP properties", () => {+ it("emits one warning when a combined CSS transform conflicts with multiple GSAP properties", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -352,7 +352,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const conflicts = result.findings.filter((f) => f.code === "gsap_css_transform_conflict");expect(conflicts).toHaveLength(1);expect(conflicts[0]?.message).toMatch(/x\/scale|scale\/x/);@@ -360,7 +360,7 @@ describe("GSAP rules", () => {// --- Inline style transform detection tests ---- it("warns when inline style transform: translateX conflicts with GSAP x", () => {+ it("warns when inline style transform: translateX conflicts with GSAP x", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -373,13 +373,13 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeDefined();expect(finding?.selector).toBe("#centered");});- it("warns when inline style transform: scale conflicts with GSAP scale", () => {+ it("warns when inline style transform: scale conflicts with GSAP scale", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -392,13 +392,13 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeDefined();expect(finding?.selector).toBe("#box");});- it("does not false-positive on inline transform: rotate when GSAP uses rotation", () => {+ it("does not false-positive on inline transform: rotate when GSAP uses rotation", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -411,13 +411,13 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);// rotation doesn't conflict with rotate() — GSAP handles rotation separatelyconst finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeUndefined();});- it("detects conflict via class selector when element has multiple classes", () => {+ it("detects conflict via class selector when element has multiple classes", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -430,12 +430,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_css_transform_conflict");expect(finding).toBeDefined();});- it("handles both style block and inline style on same selector without crash", () => {+ it("handles both style block and inline style on same selector without crash", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -451,12 +451,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const conflicts = result.findings.filter((f) => f.code === "gsap_css_transform_conflict");expect(conflicts.length).toBeGreaterThanOrEqual(1);});- it("reports error when GSAP is used without a GSAP script tag", () => {+ it("reports error when GSAP is used without a GSAP script tag", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -467,14 +467,14 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("GSAP");});- it("does not report missing_gsap_script when GSAP CDN script is present", () => {+ it("does not report missing_gsap_script when GSAP CDN script is present", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -486,12 +486,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("does not report missing_gsap_script when GSAP is bundled inline", () => {+ it("does not report missing_gsap_script when GSAP is bundled inline", async () => {// Simulate a large inline GSAP bundle (>5KB) with GreenSock markerconst fakeGsapLib = "/* GreenSock GSAP */" + " ".repeat(6000);const html = `@@ -505,12 +505,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("does not report missing_gsap_script when producer inlined CDN script", () => {+ it("does not report missing_gsap_script when producer inlined CDN script", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -524,12 +524,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeUndefined();});- it("still reports missing_gsap_script for small inline scripts that use but don't bundle GSAP", () => {+ it("still reports missing_gsap_script for small inline scripts that use but don't bundle GSAP", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -540,13 +540,13 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "missing_gsap_script");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("errors on repeat: -1 (infinite repeat breaks capture engine)", () => {+ it("errors on repeat: -1 (infinite repeat breaks capture engine)", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -558,14 +558,14 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_infinite_repeat");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("repeat: -1");});- it("does not error on finite repeat values", () => {+ it("does not error on finite repeat values", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -577,12 +577,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_infinite_repeat");expect(finding).toBeUndefined();});- it("does not error on repeat: -1 inside JavaScript comments", () => {+ it("does not error on repeat: -1 inside JavaScript comments", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -598,12 +598,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_infinite_repeat");expect(finding).toBeUndefined();});- it("does NOT report overlapping_gsap_tweens when an object-target tween is interleaved (regression)", () => {+ it("does NOT report overlapping_gsap_tweens when an object-target tween is interleaved (regression)", async () => {// Regression: a non-DOM-targeting tween like `tl.to({ _: 0 }, …)` (used to// anchor timeline duration) was matched by the regex but skipped by the// parser, drifting the index and making the second tween "see" the first@@ -624,12 +624,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "overlapping_gsap_tweens");expect(finding).toBeUndefined();});- it("warns when an opacity exit ends at a clip start boundary without a hard kill", () => {+ it("warns when an opacity exit ends at a clip start boundary without a hard kill", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080" data-start="0" data-duration="6">@@ -648,7 +648,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_exit_missing_hard_kill");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");@@ -656,7 +656,7 @@ describe("GSAP rules", () => {expect(finding?.message).toContain("3.00s");});- it("does not warn when a boundary exit has a matching hard kill", () => {+ it("does not warn when a boundary exit has a matching hard kill", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080" data-start="0" data-duration="6">@@ -676,12 +676,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_exit_missing_hard_kill");expect(finding).toBeUndefined();});- it("does not match sub-composition exits against root clip boundaries", () => {+ it("does not match sub-composition exits against root clip boundaries", async () => {const html = `<html><body><div data-composition-id="root" data-width="1920" data-height="1080" data-start="0" data-duration="6">@@ -701,12 +701,12 @@ describe("GSAP rules", () => {window.__timelines["sub"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_exit_missing_hard_kill");expect(finding).toBeUndefined();});- it("uses the authored hidden property in hard-kill fix hints", () => {+ it("uses the authored hidden property in hard-kill fix hints", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080" data-start="0" data-duration="6">@@ -725,12 +725,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_exit_missing_hard_kill");expect(finding?.fixHint).toContain("{ autoAlpha: 0 }");});- it("does not false-positive on repeat: -10 (invalid GSAP but not infinite)", () => {+ it("does not false-positive on repeat: -10 (invalid GSAP but not infinite)", async () => {const html = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080"></div>@@ -742,12 +742,12 @@ describe("GSAP rules", () => {window.__timelines["main"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_infinite_repeat");expect(finding).toBeUndefined();});- it("errors when CSS opacity:0 + gsap.from({opacity:0}) — invisible forever", () => {+ it("errors when CSS opacity:0 + gsap.from({opacity:0}) — invisible forever", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -760,14 +760,14 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_from_opacity_noop");expect(finding).toBeDefined();expect(finding!.severity).toBe("error");expect(finding!.selector).toBe("#title");});- it("errors when style block has opacity:0 + gsap.from({opacity:0})", () => {+ it("errors when style block has opacity:0 + gsap.from({opacity:0})", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -783,12 +783,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_from_opacity_noop");expect(finding).toBeDefined();});- it("does NOT error when gsap.from({opacity:0}) and CSS has no opacity:0", () => {+ it("does NOT error when gsap.from({opacity:0}) and CSS has no opacity:0", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -801,12 +801,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_from_opacity_noop");expect(finding).toBeUndefined();});- it("does NOT error when gsap.fromTo({opacity:0}, {opacity:1}) — destination overrides CSS", () => {+ it("does NOT error when gsap.fromTo({opacity:0}, {opacity:1}) — destination overrides CSS", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -819,12 +819,12 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_from_opacity_noop");expect(finding).toBeUndefined();});- it("does NOT error when gsap.to() uses opacity:0 (exit animation)", () => {+ it("does NOT error when gsap.to() uses opacity:0 (exit animation)", async () => {const html = `<html><body><div data-composition-id="c1" data-width="1920" data-height="1080">@@ -837,7 +837,7 @@ describe("GSAP rules", () => {window.__timelines["c1"] = tl;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "gsap_from_opacity_noop");expect(finding).toBeUndefined();});diff --git a/packages/core/src/lint/rules/gsap.ts b/packages/core/src/lint/rules/gsap.tsindex 7c28aaa4f5..5c02adbf27 100644--- a/packages/core/src/lint/rules/gsap.ts+++ b/packages/core/src/lint/rules/gsap.ts@@ -1,5 +1,22 @@-import { parseGsapScript } from "../../parsers/gsapParser";-import type { LintContext, HyperframeLintFinding } from "../context";+interface LintParsedGsap {+ animations: Array<{+ targetSelector: string;+ position: number | string;+ properties: Record<string, number | string>;+ }>;+ timelineVar: string;+}++// The recast-based GSAP parser lives behind the Node-only+// `@hyperframes/core/gsap-parser` subpath. The linter runs server-side only+// (CLI + studio-api `/lint` route), so loading it via dynamic import keeps+// recast out of any browser/SSR-traced static graph.+async function loadParseGsapScript(): Promise<(script: string) => LintParsedGsap> {+ const mod = await import("../../parsers/gsapParser.js");+ return mod.parseGsapScript as unknown as (script: string) => LintParsedGsap;+}+import type { LintContext } from "../context";+import type { HyperframeLintFinding, LintRule } from "../types";import type { OpenTag } from "../utils";import { readAttr, truncateSnippet, WINDOW_TIMELINE_ASSIGN_PATTERN } from "../utils";@@ -108,8 +125,9 @@ function readRegisteredTimelineCompositionId(script: string): string | null {return match?.[1] || null;}-function extractGsapWindows(script: string): GsapWindow[] {+async function extractGsapWindows(script: string): Promise<GsapWindow[]> {if (!/gsap\.timeline/.test(script)) return [];+ const parseGsapScript = await loadParseGsapScript();const parsed = parseGsapScript(script);if (parsed.animations.length === 0) return [];@@ -135,6 +153,9 @@ function extractGsapWindows(script: string): GsapWindow[] {const animation = parsed.animations[index];index += 1;if (!animation) continue;+ // Skip animations with string positions (e.g. "+=1", "<") — their absolute+ // timing depends on runtime evaluation and can't be statically linted.+ if (typeof animation.position !== "number") continue;windows.push({targetSelector: animation.targetSelector,position: animation.position,@@ -433,9 +454,9 @@ function cssTransformToGsapProps(cssTransform: string): string | null {// ── GSAP rules ─────────────────────────────────────────────────────────────-export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [+export const gsapRules: LintRule<LintContext>[] = [// overlapping_gsap_tweens + gsap_animates_clip_element + unscoped_gsap_selector- ({ source, tags, scripts, rootCompositionId }) => {+ async ({ source, tags, scripts, rootCompositionId }) => {const findings: HyperframeLintFinding[] = [];// Build clip element selector map@@ -463,7 +484,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [for (const script of scripts) {const localTimelineCompId = readRegisteredTimelineCompositionId(script.content);- const gsapWindows = extractGsapWindows(script.content);+ const gsapWindows = await extractGsapWindows(script.content);const clipStartBoundaries =clipStartBoundariesByComposition.get(localTimelineCompId || rootCompositionId || "") ?? [];@@ -564,7 +585,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [},// gsap_css_transform_conflict- ({ styles, scripts, tags }) => {+ async ({ styles, scripts, tags }) => {const findings: HyperframeLintFinding[] = [];const cssTranslateSelectors = new Map<string, string>();const cssScaleSelectors = new Map<string, string>();@@ -610,7 +631,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [for (const script of scripts) {if (!/gsap\.timeline/.test(script.content)) continue;- const windows = extractGsapWindows(script.content);+ const windows = await extractGsapWindows(script.content);type Conflict = { cssTransform: string; props: Set<string>; raw: string };const conflicts = new Map<string, Conflict>();@@ -845,7 +866,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [},// gsap_from_opacity_noop — CSS opacity:0 + gsap.from({opacity:0}) = invisible forever- ({ styles, scripts, tags }) => {+ async ({ styles, scripts, tags }) => {const findings: HyperframeLintFinding[] = [];const cssOpacityZeroSelectors = new Set<string>();@@ -872,7 +893,7 @@ export const gsapRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [for (const script of scripts) {if (!/gsap\.timeline/.test(script.content)) continue;- const windows = extractGsapWindows(script.content);+ const windows = await extractGsapWindows(script.content);for (const win of windows) {if (win.method !== "from") continue;diff --git a/packages/core/src/lint/rules/media.test.ts b/packages/core/src/lint/rules/media.test.tsindex 64d1e78172..68efbed88e 100644--- a/packages/core/src/lint/rules/media.test.ts+++ b/packages/core/src/lint/rules/media.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { lintHyperframeHtml } from "../hyperframeLinter.js";describe("media rules", () => {- it("reports error for duplicate media ids", () => {+ it("reports error for duplicate media ids", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -11,14 +11,14 @@ describe("media rules", () => {</div><script>window.__timelines = {};</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "duplicate_media_id");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.elementId).toBe("v1");});- it("reports error for audio with data-start but no id", () => {+ it("reports error for audio with data-start but no id", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -26,14 +26,14 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_missing_id");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("SILENT");});- it("reports error for video with data-start but no id", () => {+ it("reports error for video with data-start but no id", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -41,14 +41,14 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_missing_id");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.message).toContain("FROZEN");});- it("does not flag media elements that have id", () => {+ it("does not flag media elements that have id", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -57,12 +57,12 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_missing_id");expect(finding).toBeUndefined();});- it("reports warning for media with preload=none", () => {+ it("reports warning for media with preload=none", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -70,13 +70,13 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_preload_none");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("reports error for media with id but no src", () => {+ it("reports error for media with id but no src", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -84,13 +84,13 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_missing_src");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("reports error for media with src but no data-start", () => {+ it("reports error for media with src but no data-start", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -98,14 +98,14 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "media_missing_data_start");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.elementId).toBe("demo-video");});- it("allows audible video clips to omit muted when data-has-audio is true", () => {+ it("allows audible video clips to omit muted when data-has-audio is true", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -113,14 +113,14 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);expect(result.findings.find((f) => f.code === "video_missing_muted")).toBeUndefined();expect(result.findings.find((f) => f.code === "video_muted_with_declared_audio"),).toBeUndefined();});- it("reports error for videos that declare audio while muted", () => {+ it("reports error for videos that declare audio while muted", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -128,14 +128,14 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "video_muted_with_declared_audio");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.elementId).toBe("demo-video");});- it("does NOT flag <video> as nested in a void element with data-start (regression)", () => {+ it("does NOT flag <video> as nested in a void element with data-start (regression)", async () => {// Regression: void elements like <img> have no closing tag, so the previous// implementation kept them on the parent stack indefinitely and flagged any// later <video> with data-start as "nested" inside them.@@ -147,12 +147,12 @@ describe("media rules", () => {</div><script>window.__timelines = window.__timelines || {}; window.__timelines["c1"] = gsap.timeline({ paused: true });</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "video_nested_in_timed_element");expect(finding).toBeUndefined();});- it("reports imperative play() control on managed media ids", () => {+ it("reports imperative play() control on managed media ids", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -163,14 +163,14 @@ describe("media rules", () => {video.play();</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "imperative_media_control");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");expect(finding?.elementId).toBe("demo-video");});- it("reports imperative currentTime writes on query-selected managed media", () => {+ it("reports imperative currentTime writes on query-selected managed media", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -181,13 +181,13 @@ describe("media rules", () => {demo.currentTime = 1.5;</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "imperative_media_control");expect(finding).toBeDefined();expect(finding?.severity).toBe("error");});- it("reports imperative muted/play control on class-selected media without ids", () => {+ it("reports imperative muted/play control on class-selected media without ids", async () => {const html = `<template id="scene-template"><div data-composition-id="scene" data-width="1920" data-height="1080">@@ -198,14 +198,14 @@ describe("media rules", () => {</script></div></template>`;- const result = lintHyperframeHtml(html, { filePath: "compositions/scene.html" });+ const result = await lintHyperframeHtml(html, { filePath: "compositions/scene.html" });const imperativeFindings = result.findings.filter((f) => f.code === "imperative_media_control");expect(imperativeFindings.length).toBe(2);expect(imperativeFindings.some((f) => f.snippet === "vid.muted =")).toBe(true);expect(imperativeFindings.some((f) => f.snippet === "vid.play(")).toBe(true);});- it("does not flag play() on non-media elements", () => {+ it("does not flag play() on non-media elements", async () => {const html = `<html><body><div id="root" data-composition-id="c1" data-width="1920" data-height="1080">@@ -216,7 +216,7 @@ describe("media rules", () => {panel.play?.();</script></body></html>`;- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((f) => f.code === "imperative_media_control");expect(finding).toBeUndefined();});diff --git a/packages/core/src/lint/rules/textures.test.ts b/packages/core/src/lint/rules/textures.test.tsindex b2b1b6b1ce..c9505fa10a 100644--- a/packages/core/src/lint/rules/textures.test.ts+++ b/packages/core/src/lint/rules/textures.test.ts@@ -24,21 +24,21 @@ const textureCss = ``;describe("texture rules", () => {- it("does not warn for a valid texture mask text usage", () => {+ it("does not warn for a valid texture mask text usage", async () => {const html = baseHtml('<div class="shadow"><div class="hf-texture-text hf-texture-lava">TEXT</div></div>',`${textureCss}.shadow { filter: drop-shadow(1px 2px 1px rgba(0,0,0,.48)); }`,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);expect(result.findings.filter((finding) => finding.code.startsWith("texture_"))).toEqual([]);});- it("warns when a material class is used without hf-texture-text", () => {+ it("warns when a material class is used without hf-texture-text", async () => {const html = baseHtml('<div class="hf-texture-lava">TEXT</div>', textureCss);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_class_missing_base");expect(finding).toBeDefined();@@ -46,98 +46,98 @@ describe("texture rules", () => {expect(finding?.fixHint).toContain("hf-texture-text");});- it("warns when hf-texture-text has no material class or custom mask image", () => {+ it("warns when hf-texture-text has no material class or custom mask image", async () => {const html = baseHtml('<div class="hf-texture-text">TEXT</div>', textureCss);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_text_missing_mask");expect(finding).toBeDefined();expect(finding?.severity).toBe("warning");});- it("allows hf-texture-text with an inline custom mask image", () => {+ it("allows hf-texture-text with an inline custom mask image", async () => {const html = baseHtml('<div class="hf-texture-text" style="-webkit-mask-image:url(custom.png); mask-image:url(custom.png)">TEXT</div>',textureCss,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_text_missing_mask");expect(finding).toBeUndefined();});- it("warns when a texture material class is not defined by local CSS", () => {+ it("warns when a texture material class is not defined by local CSS", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-marbel">TEXT</div>', textureCss);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_class_unknown");expect(finding).toBeDefined();expect(finding?.message).toContain("hf-texture-marbel");});- it("warns when drop-shadow is applied inline to the textured text element", () => {+ it("warns when drop-shadow is applied inline to the textured text element", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-lava" style="filter: drop-shadow(1px 2px 1px black)">TEXT</div>',textureCss,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_drop_shadow_on_text");expect(finding).toBeDefined();expect(finding?.fixHint).toContain("wrapper");});- it("warns when drop-shadow is applied by CSS directly to hf-texture-text", () => {+ it("warns when drop-shadow is applied by CSS directly to hf-texture-text", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-lava">TEXT</div>',`${textureCss}.hf-texture-text { filter: drop-shadow(1px 2px 1px black); }`,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_drop_shadow_on_text");expect(finding).toBeDefined();expect(finding?.selector).toBe(".hf-texture-text");});- it("warns when drop-shadow targets a material class before the mask rule is declared", () => {+ it("warns when drop-shadow targets a material class before the mask rule is declared", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-lava">TEXT</div>',`.hf-texture-lava { filter: drop-shadow(1px 2px 1px black); }${textureCss}`,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_drop_shadow_on_text");expect(finding).toBeDefined();expect(finding?.selector).toBe(".hf-texture-lava");});- it("warns when drop-shadow targets another class on the textured text element", () => {+ it("warns when drop-shadow targets another class on the textured text element", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-lava headline">TEXT</div>',`${textureCss}.headline { filter: drop-shadow(1px 2px 1px black); }`,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_drop_shadow_on_text");expect(finding).toBeDefined();expect(finding?.selector).toBe(".headline");});- it("does not warn when another-class drop-shadow selector needs an unmatched ancestor", () => {+ it("does not warn when another-class drop-shadow selector needs an unmatched ancestor", async () => {const html = baseHtml('<div class="hf-texture-text hf-texture-lava headline">TEXT</div>',`${textureCss}.card .headline { filter: drop-shadow(1px 2px 1px black); }`,);- const result = lintHyperframeHtml(html);+ const result = await lintHyperframeHtml(html);const finding = result.findings.find((item) => item.code === "texture_drop_shadow_on_text");expect(finding).toBeUndefined();diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.tsindex 69dfeb7585..e468a348e0 100644--- a/packages/core/src/lint/types.ts+++ b/packages/core/src/lint/types.ts@@ -25,6 +25,8 @@ export type HyperframeLinterOptions = {externalStyles?: Array<{ href: string; content: string }>;};-// A rule is a pure function: receives parsed context, returns zero or more findings.-// Rule modules should receive a LintContext (defined in ./context) as the type parameter.-export type LintRule<TContext> = (ctx: TContext) => HyperframeLintFinding[];+// A rule is a function: receives parsed context, returns zero or more findings.+// Rules may be async (e.g. when lazy-loading heavy dependencies like recast).+export type LintRule<TContext> = (+ ctx: TContext,+) => HyperframeLintFinding[] | Promise<HyperframeLintFinding[]>;diff --git a/packages/core/src/parsers/gsapConstants.ts b/packages/core/src/parsers/gsapConstants.tsnew file mode 100644index 0000000000..340892ebdd--- /dev/null+++ b/packages/core/src/parsers/gsapConstants.ts@@ -0,0 +1,48 @@+/**+ * GSAP property and ease constants.+ *+ * Extracted into a standalone module so browser code can import them+ * without pulling in gsapParser (which depends on recast / @babel/parser).+ */++export const SUPPORTED_PROPS = [+ "opacity",+ "visibility",+ "x",+ "y",+ "scale",+ "scaleX",+ "scaleY",+ "rotation",+ "autoAlpha",+ "width",+ "height",+];++export const SUPPORTED_EASES = [+ "none",+ "power1.in",+ "power1.out",+ "power1.inOut",+ "power2.in",+ "power2.out",+ "power2.inOut",+ "power3.in",+ "power3.out",+ "power3.inOut",+ "power4.in",+ "power4.out",+ "power4.inOut",+ "back.in",+ "back.out",+ "back.inOut",+ "elastic.in",+ "elastic.out",+ "elastic.inOut",+ "bounce.in",+ "bounce.out",+ "bounce.inOut",+ "expo.in",+ "expo.out",+ "expo.inOut",+];diff --git a/packages/core/src/parsers/gsapParser.stress.test.ts b/packages/core/src/parsers/gsapParser.stress.test.tsnew file mode 100644index 0000000000..81e01c2fbd--- /dev/null+++ b/packages/core/src/parsers/gsapParser.stress.test.ts@@ -0,0 +1,952 @@+import { describe, it, expect } from "vitest";+import {+ parseGsapScript,+ serializeGsapAnimations,+ updateAnimationInScript,+ addAnimationToScript,+ removeAnimationFromScript,+} from "./gsapParser.js";+import type { ParsedGsap } from "./gsapParser.js";++// ── Helpers ────────────────────────────────────────────────────────────────++/** Assert a parse completed without crashing and returned the safe-default shape. */+function expectSafeDefault(result: ParsedGsap) {+ expect(result).toBeDefined();+ expect(Array.isArray(result.animations)).toBe(true);+ expect(typeof result.timelineVar).toBe("string");+}++/** Parse, serialize, re-parse, and assert structural equality of the animation IR. */+function assertRoundTrip(script: string) {+ const parsed1 = parseGsapScript(script);+ expect(parsed1.animations.length).toBeGreaterThan(0);++ const serialized = serializeGsapAnimations(parsed1.animations, parsed1.timelineVar, {+ preamble: parsed1.preamble,+ postamble: parsed1.postamble,+ });+ const parsed2 = parseGsapScript(serialized);++ expect(parsed2.animations.length).toBe(parsed1.animations.length);+ for (let i = 0; i < parsed1.animations.length; i++) {+ const a = parsed1.animations[i];+ const b = parsed2.animations[i];+ expect(b.targetSelector).toBe(a.targetSelector);+ expect(b.method).toBe(a.method);+ expect(b.position).toEqual(a.position);+ expect(b.duration).toEqual(a.duration);+ expect(b.ease).toEqual(a.ease);+ // Properties: numeric values must match; __raw values may re-serialize differently+ for (const [key, val] of Object.entries(a.properties)) {+ if (typeof val === "number") {+ expect(b.properties[key]).toBe(val);+ } else if (typeof val === "string" && val.startsWith("__raw:")) {+ // Raw values survive in some form — just confirm the key exists+ expect(b.properties).toHaveProperty(key);+ }+ }+ // Extras survive+ if (a.extras) {+ expect(b.extras).toBeDefined();+ for (const key of Object.keys(a.extras)) {+ expect(b.extras).toHaveProperty(key);+ }+ }+ }+}++// ── 1. Malformed Scripts ───────────────────────────────────────────────────++describe("1. Malformed scripts", () => {+ const cases = [+ {+ name: "unclosed brace",+ script: "const tl = gsap.timeline({ paused: true }); tl.to('#a', { x: 1",+ },+ {+ name: "unclosed parenthesis",+ script: "const tl = gsap.timeline({ paused: true }); tl.to('#a', { x: 1 }, 0",+ },+ { name: "random garbage", script: "@@@ not javascript at all ~~~" },+ { name: "partial assignment", script: "const tl =" },+ {+ name: "missing semicolons everywhere",+ script:+ "const tl = gsap.timeline({ paused: true })\ntl.to('#a', { x: 1 }, 0)\ntl.to('#b', { y: 2 }, 1)",+ },+ {+ name: "double commas",+ script: 'const tl = gsap.timeline({ paused: true }); tl.to("#a",, { x: 1 }, 0);',+ },+ { name: "HTML mixed in", script: "<div>hello</div>\nconst tl = gsap.timeline();" },+ { name: "only opening brace", script: "{" },+ { name: "only closing brace", script: "}" },+ { name: "null byte", script: "const tl = gsap.timeline();\x00 tl.to('#a', { x: 1 }, 0);" },+ ];++ for (const { name, script } of cases) {+ it(`does not crash on: ${name}`, () => {+ const result = parseGsapScript(script);+ expectSafeDefault(result);+ });++ it(`mutation functions are safe on: ${name}`, () => {+ // Some malformed scripts might parse as valid but empty — mutation safety+ // still applies (either noop or a valid transform)+ expect(() => updateAnimationInScript(script, "id", { duration: 1 })).not.toThrow();+ expect(() =>+ addAnimationToScript(script, {+ targetSelector: "#el",+ method: "to",+ position: 0,+ properties: { opacity: 1 },+ duration: 1,+ }),+ ).not.toThrow();+ expect(() => removeAnimationFromScript(script, "id")).not.toThrow();+ });+ }++ it("missing semicolons still parse tweens (ASI)", () => {+ const script = `+ const tl = gsap.timeline({ paused: true })+ tl.to("#a", { x: 100, duration: 0.5 }, 0)+ tl.to("#b", { y: 200, duration: 1 }, 1)+ `;+ const result = parseGsapScript(script);+ // Babel handles ASI — these should parse fine+ expect(result.animations.length).toBe(2);+ });+});++// ── 2. Empty / Minimal Scripts ─────────────────────────────────────────────++describe("2. Empty / minimal scripts", () => {+ it("empty string", () => {+ const result = parseGsapScript("");+ expectSafeDefault(result);+ expect(result.animations).toHaveLength(0);+ });++ it("whitespace only", () => {+ const result = parseGsapScript(" \n\t\n ");+ expectSafeDefault(result);+ expect(result.animations).toHaveLength(0);+ });++ it("window.__timelines = {} with no tweens", () => {+ const script = "window.__timelines = {};";+ const result = parseGsapScript(script);+ expectSafeDefault(result);+ expect(result.animations).toHaveLength(0);+ });++ it("timeline declaration with no tween calls", () => {+ const script = "const tl = gsap.timeline({ paused: true });";+ const result = parseGsapScript(script);+ expect(result.timelineVar).toBe("tl");+ expect(result.animations).toHaveLength(0);+ });++ it("only comments", () => {+ const script = "// this is a comment\n/* block comment */";+ const result = parseGsapScript(script);+ expectSafeDefault(result);+ expect(result.animations).toHaveLength(0);+ });++ it("tween with only selector and empty vars object", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", {}, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(Object.keys(result.animations[0].properties)).toHaveLength(0);+ expect(result.animations[0].duration).toBeUndefined();+ });+});++// ── 3. Extreme Values ──────────────────────────────────────────────────────++describe("3. Extreme values", () => {+ it("very large numbers", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 1e10, y: 99999999, duration: 1000000 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties.x).toBe(1e10);+ expect(result.animations[0].properties.y).toBe(99999999);+ expect(result.animations[0].duration).toBe(1000000);+ });++ it("very small numbers", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 0.001, duration: 0.0001 }, 0.00001);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties.opacity).toBe(0.001);+ expect(result.animations[0].duration).toBe(0.0001);+ expect(result.animations[0].position).toBeCloseTo(0.00001);+ });++ it("negative position", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1 }, -5);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].position).toBe(-5);+ });++ it("zero duration", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 0 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].duration).toBe(0);+ });++ it("NaN-producing division by zero is handled", () => {+ const script = `+ const ZERO = 0;+ const BAD = 100 / ZERO;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: BAD, y: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Division by zero returns undefined from resolveNode, so BAD is unresolvable+ // x should be __raw: or undefined, y should be 50+ expect(result.animations[0].properties.y).toBe(50);+ // BAD was never bound (division by zero returns undefined), so the reference is raw+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ });++ it("Infinity literal", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: Infinity, y: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Infinity is an Identifier, not a NumericLiteral — should be __raw+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ expect(result.animations[0].properties.y).toBe(50);+ });+});++// ── 4. Unicode in Selectors ────────────────────────────────────────────────++describe("4. Unicode in selectors", () => {+ it("Japanese characters in selector", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#日本語", { x: 100, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].targetSelector).toBe("#日本語");+ });++ it("emoji in selector", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#rocket-🚀", { opacity: 1, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].targetSelector).toBe("#rocket-🚀");+ });++ it("Arabic and Cyrillic selectors", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#عربي", { x: 50, duration: 1 }, 0);+ tl.to("#кириллица", { y: 100, duration: 1 }, 1);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(2);+ expect(result.animations[0].targetSelector).toBe("#عربي");+ expect(result.animations[1].targetSelector).toBe("#кириллица");+ });++ it("class selector with unicode", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".コンポーネント", { scale: 2, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].targetSelector).toBe(".コンポーネント");+ });+});++// ── 5. Deeply Nested Objects ───────────────────────────────────────────────++describe("5. Deeply nested objects", () => {+ it("complex stagger object preserved in extras", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: { amount: 1, grid: [3, 3], from: "center", axis: "x" } }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].extras).toBeDefined();+ expect(result.animations[0].extras!.stagger).toBeDefined();+ // stagger should be __raw: containing the nested object source+ const stagger = String(result.animations[0].extras!.stagger);+ expect(stagger.startsWith("__raw:")).toBe(true);+ expect(stagger).toContain("amount");+ expect(stagger).toContain("grid");+ expect(stagger).toContain("center");+ });++ it("complex stagger survives round-trip serialization", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: { amount: 1, grid: [3, 3], from: "center", axis: "x" } }, 0);+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });+ expect(serialized).toContain("stagger:");+ expect(serialized).toContain("amount");+ expect(serialized).toContain("grid");+ });++ it("nested ease config object (non-string ease)", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1, ease: "back.out(1.7)" }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].ease).toBe("back.out(1.7)");+ });+});++// ── 6. Chained Method Calls ────────────────────────────────────────────────++describe("6. Chained method calls", () => {+ it("chained tl.to().to().from() — only top-level calls detected", () => {+ // Chaining like tl.to(...).to(...) means the second .to() is called on the+ // return value of the first .to(), which is the timeline itself. However,+ // the parser checks `callee.object.name === timelineVar`, so chained calls+ // where the callee.object is a CallExpression (not an Identifier) are skipped.+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#a", { x: 100, duration: 0.5 }, 0).to("#b", { y: 200, duration: 0.5 }, 1).from("#c", { scale: 0, duration: 1 }, 2);+ `;+ const result = parseGsapScript(script);+ // Only the first call in the chain has `tl` as the callee object directly+ // The rest are chained on the return value — parser may or may not catch them+ expect(result.animations.length).toBeGreaterThanOrEqual(1);+ expect(result.animations[0].targetSelector).toBe("#a");+ expect(result.animations[0].properties.x).toBe(100);+ });++ it("separate statements all parse", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#a", { x: 100, duration: 0.5 }, 0);+ tl.to("#b", { y: 200, duration: 0.5 }, 1);+ tl.from("#c", { scale: 0, duration: 1 }, 2);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(3);+ });+});++// ── 7. Template Literals in Values ─────────────────────────────────────────++describe("7. Template literals in values", () => {+ it("template literal with no expressions resolves to string", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 50, duration: 1, ease: \`power2.out\` }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].ease).toBe("power2.out");+ });++ it("template literal with expression becomes __raw", () => {+ const script = `+ const val = 100;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: \`\${val}px\`, y: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Template literal with expressions is not resolvable+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ expect(result.animations[0].properties.y).toBe(50);+ });+});++// ── 8. Multiple Scripts in One HTML ────────────────────────────────────────++describe("8. Multiple timelines", () => {+ it("two gsap.timeline() calls sets multipleTimelines flag", () => {+ const script = `+ const tl1 = gsap.timeline({ paused: true });+ tl1.to("#a", { x: 100, duration: 1 }, 0);+ const tl2 = gsap.timeline({ paused: true });+ tl2.to("#b", { y: 200, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.multipleTimelines).toBe(true);+ // Parser only tracks the first timeline variable+ expect(result.timelineVar).toBe("tl1");+ // Only tl1 tweens are captured+ expect(result.animations.every((a) => a.targetSelector === "#a")).toBe(true);+ });++ it("two scripts concatenated with same variable name", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#first", { opacity: 1, duration: 0.5 }, 0);+ // Second block re-uses tl but creates a new timeline+ const tl2 = gsap.timeline({ paused: true });+ tl.to("#second", { opacity: 0.5, duration: 1 }, 1);+ `;+ const result = parseGsapScript(script);+ // Both .to() calls use "tl" as the callee object, so both are captured+ expect(result.multipleTimelines).toBe(true);+ const selectors = result.animations.map((a) => a.targetSelector);+ expect(selectors).toContain("#first");+ expect(selectors).toContain("#second");+ });+});++// ── 9. Comments Everywhere ─────────────────────────────────────────────────++describe("9. Comments everywhere", () => {+ it("inline comments inside tween args", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { /* fade in */ opacity: 1 /*, y: 200*/, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties.opacity).toBe(1);+ // y: 200 is commented out, should not appear+ expect(result.animations[0].properties).not.toHaveProperty("y");+ });++ it("line comments between tween calls", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ // First animation+ tl.set("#el", { opacity: 0 }, 0);+ // Second animation+ tl.to("#el", { opacity: 1, duration: 1 }, 0.5);+ // Done+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(2);+ });++ it("comment inside selector string (not really a comment)", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el /* not a comment */", { x: 100, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].targetSelector).toBe("#el /* not a comment */");+ });+});++// ── 10. Arrow Functions as Values ──────────────────────────────────────────++describe("10. Arrow functions as values", () => {+ it("arrow function property becomes __raw", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: (i) => i * 50, opacity: 1, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Arrow function is not resolvable+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ // Resolvable values still work+ expect(result.animations[0].properties.opacity).toBe(1);+ });++ it("arrow function in stagger becomes __raw extra", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: (i) => i * 0.1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].extras).toBeDefined();+ const stagger = String(result.animations[0].extras!.stagger);+ expect(stagger.startsWith("__raw:")).toBe(true);+ });++ it("arrow function round-trips via serialization", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: (i) => i * 50, opacity: 1, duration: 1 }, 0);+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });+ // The raw arrow function should be emitted without quotes+ expect(serialized).toContain("(i) => i * 50");+ expect(serialized).not.toContain('"(i) => i * 50"');+ });+});++// ── 11. Spread Operator ────────────────────────────────────────────────────++describe("11. Spread operator", () => {+ it("spread in vars object does not crash — spread properties are skipped", () => {+ const script = `+ const baseVars = { opacity: 0, x: -50 };+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { ...baseVars, y: 100, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Spread properties are SpreadElement, not ObjectProperty — they're skipped+ // Only explicitly written properties are captured+ expect(result.animations[0].properties.y).toBe(100);+ expect(result.animations[0].duration).toBe(1);+ });+});++// ── 12. Conditional Expressions ────────────────────────────────────────────++describe("12. Conditional expressions", () => {+ it("ternary expression becomes __raw", () => {+ const script = `+ const condition = true;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: condition ? 100 : 200, y: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // ConditionalExpression is not handled by resolveNode+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ expect(result.animations[0].properties.y).toBe(50);+ });++ it("conditional in position argument defaults to 0", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1 }, someCondition ? 0 : 2);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // Position can't be resolved — falls back to 0+ expect(result.animations[0].position).toBe(0);+ });+});++// ── 13. Round-Trip Stability ───────────────────────────────────────────────++describe("13. Round-trip stability", () => {+ it("basic .to() round-trips", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, x: 50, duration: 0.5, ease: "power2.out" }, 0);+ `);+ });++ it("basic .from() round-trips", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.from("#el", { opacity: 0, y: -100, duration: 1, ease: "back.out" }, 0.5);+ `);+ });++ it("basic .set() round-trips", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.set("#el", { opacity: 0, scale: 0.5 }, 0);+ `);+ });++ it("basic .fromTo() round-trips", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.fromTo("#el", { opacity: 0 }, { opacity: 1, duration: 1, ease: "power1.inOut" }, 2);+ `);+ });++ it("stagger extra round-trips", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: 0.1 }, 0);+ `);+ });++ it("yoyo + repeat extras round-trip", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1, yoyo: true, repeat: 3, repeatDelay: 0.2 }, 0);+ `);+ });++ it("multiple tweens round-trip with ordering preserved", () => {+ assertRoundTrip(`+ const tl = gsap.timeline({ paused: true });+ tl.set("#el1", { opacity: 0 }, 0);+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);+ tl.to("#el2", { x: 100, duration: 1 }, 1);+ tl.from("#el3", { y: -50, duration: 0.3 }, 2);+ `);+ });++ it("string position round-trips", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: 1, duration: 0.5 }, "+=1");+ tl.to("#el2", { x: 100, duration: 1 }, "<");+ `;+ const parsed1 = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed1.animations, parsed1.timelineVar, {+ preamble: parsed1.preamble,+ postamble: parsed1.postamble,+ });+ const parsed2 = parseGsapScript(serialized);+ expect(parsed2.animations[0].position).toBe("+=1");+ expect(parsed2.animations[1].position).toBe("<");+ });++ it("double round-trip: parse -> serialize -> parse -> serialize -> parse gives stable IR", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.set("#a", { opacity: 0 }, 0);+ tl.to("#a", { opacity: 1, x: 100, duration: 0.5, ease: "power2.out" }, 0.5);+ tl.to("#b", { y: -50, scale: 1.5, duration: 1, stagger: 0.1 }, 1);+ `;+ const parsed1 = parseGsapScript(script);+ const ser1 = serializeGsapAnimations(parsed1.animations, parsed1.timelineVar, {+ preamble: parsed1.preamble,+ postamble: parsed1.postamble,+ });+ const parsed2 = parseGsapScript(ser1);+ const ser2 = serializeGsapAnimations(parsed2.animations, parsed2.timelineVar, {+ preamble: parsed2.preamble,+ postamble: parsed2.postamble,+ });+ const parsed3 = parseGsapScript(ser2);++ // Third parse should match second parse exactly+ expect(parsed3.animations.length).toBe(parsed2.animations.length);+ for (let i = 0; i < parsed2.animations.length; i++) {+ expect(parsed3.animations[i].targetSelector).toBe(parsed2.animations[i].targetSelector);+ expect(parsed3.animations[i].method).toBe(parsed2.animations[i].method);+ expect(parsed3.animations[i].position).toEqual(parsed2.animations[i].position);+ expect(parsed3.animations[i].properties).toEqual(parsed2.animations[i].properties);+ }+ });+});++// ── 14. ID Collision ───────────────────────────────────────────────────────++describe("14. ID collision", () => {+ it("three tweens with same selector, method, position get disambiguated", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 0, duration: 0.3 }, 0);+ tl.to("#el", { x: 100, duration: 0.5 }, 0);+ tl.to("#el", { y: 50, duration: 0.7 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(3);+ const ids = result.animations.map((a) => a.id);+ // All IDs must be unique+ expect(new Set(ids).size).toBe(3);+ expect(ids[0]).toBe("#el-to-0");+ expect(ids[1]).toBe("#el-to-0-2");+ expect(ids[2]).toBe("#el-to-0-3");+ });++ it("disambiguated IDs are stable across parses", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 0 }, 0);+ tl.to("#el", { x: 100 }, 0);+ `;+ const r1 = parseGsapScript(script);+ const r2 = parseGsapScript(script);+ expect(r1.animations[0].id).toBe(r2.animations[0].id);+ expect(r1.animations[1].id).toBe(r2.animations[1].id);+ });++ it("mutation by ID targets the correct animation among collisions", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 0, duration: 0.3 }, 0);+ tl.to("#el", { opacity: 1, duration: 0.5 }, 0);+ `;+ const parsed = parseGsapScript(script);+ const secondId = parsed.animations[1].id; // "#el-to-0-2"+ const updated = updateAnimationInScript(script, secondId, { duration: 2 });+ const reparsed = parseGsapScript(updated);+ // The second animation should have updated duration+ expect(reparsed.animations[1].duration).toBe(2);+ // The first should be untouched+ expect(reparsed.animations[0].duration).toBe(0.3);+ });+});++// ── 15. Very Long Scripts ──────────────────────────────────────────────────++describe("15. Very long scripts (50+ tweens)", () => {+ it("parses 50 sequential tweens", () => {+ const tweens = Array.from(+ { length: 50 },+ (_, i) =>+ `tl.to("#el${i}", { x: ${i * 10}, opacity: ${(i % 10) / 10}, duration: 0.5 }, ${i * 0.5});`,+ ).join("\n ");+ const script = `+ const tl = gsap.timeline({ paused: true });+ ${tweens}+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(50);+ // Spot check first and last+ expect(result.animations[0].targetSelector).toBe("#el0");+ expect(result.animations[0].properties.x).toBe(0);+ expect(result.animations[49].targetSelector).toBe("#el49");+ expect(result.animations[49].properties.x).toBe(490);+ });++ it("parses 100 tweens targeting the same element", () => {+ const tweens = Array.from(+ { length: 100 },+ (_, i) => `tl.to("#el", { x: ${i}, duration: 0.1 }, ${i * 0.1});`,+ ).join("\n ");+ const script = `+ const tl = gsap.timeline({ paused: true });+ ${tweens}+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(100);+ // All IDs must be unique despite same selector+ const ids = result.animations.map((a) => a.id);+ expect(new Set(ids).size).toBe(100);+ });++ it("round-trips 50 tweens", () => {+ const tweens = Array.from(+ { length: 50 },+ (_, i) => `tl.to("#el${i}", { x: ${i * 10}, duration: 0.5 }, ${i * 0.5});`,+ ).join("\n ");+ const script = `+ const tl = gsap.timeline({ paused: true });+ ${tweens}+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });+ const reparsed = parseGsapScript(serialized);+ expect(reparsed.animations.length).toBe(50);+ for (let i = 0; i < 50; i++) {+ expect(reparsed.animations[i].targetSelector).toBe(parsed.animations[i].targetSelector);+ expect(reparsed.animations[i].properties.x).toBe(parsed.animations[i].properties.x);+ }+ });+});++// ── Additional Edge Cases ──────────────────────────────────────────────────++describe("Additional edge cases", () => {+ it("selector with special CSS characters", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#my-element_v2.class", { x: 100, duration: 1 }, 0);+ tl.to(".parent > .child", { y: 50, duration: 0.5 }, 0);+ tl.to("[data-anim='fade']", { opacity: 1, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(3);+ expect(result.animations[0].targetSelector).toBe("#my-element_v2.class");+ expect(result.animations[1].targetSelector).toBe(".parent > .child");+ expect(result.animations[2].targetSelector).toBe("[data-anim='fade']");+ });++ it("string concatenation in property value", () => {+ const script = `+ const prefix = "100";+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: prefix + "px", y: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].properties.x).toBe("100px");+ expect(result.animations[0].properties.y).toBe(50);+ });++ it("arithmetic in position argument", () => {+ const script = `+ const START = 2;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1 }, START + 0.5);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].position).toBe(2.5);+ });++ it("var declaration for timeline", () => {+ const script = `+ var tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.timelineVar).toBe("tl");+ expect(result.animations).toHaveLength(1);+ });++ it("assignment expression for timeline (no declaration keyword)", () => {+ const script = `+ window.tl = gsap.timeline({ paused: true });+ `;+ const result = parseGsapScript(script);+ // Window member expression is not a bare Identifier, so timelineVar may not be found+ // The parser checks for Identifier left in assignment expressions+ // window.tl is a MemberExpression, not Identifier — should not set timelineVar+ expectSafeDefault(result);+ });++ it("non-GSAP method calls on the timeline are ignored", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, duration: 0.5 }, 0);+ tl.play();+ tl.pause();+ tl.reverse();+ tl.seek(2);+ `;+ const result = parseGsapScript(script);+ // Only .to() is a tween method — play/pause/reverse/seek are not in GSAP_METHODS+ expect(result.animations).toHaveLength(1);+ });++ it("tween with only one argument (selector only) is skipped", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el");+ tl.to("#el2", { opacity: 1, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ // First tween has < 2 args — should be skipped+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].targetSelector).toBe("#el2");+ });++ it("non-string selector (variable reference) is skipped", () => {+ const script = `+ const el = document.querySelector("#el");+ const tl = gsap.timeline({ paused: true });+ tl.to(el, { opacity: 1, duration: 0.5 }, 0);+ tl.to("#el2", { x: 100, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ // First tween has a variable reference as selector, not a string literal — skipped+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].targetSelector).toBe("#el2");+ });++ it("boolean values in vars are not included in properties", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, immediateRender: false, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].properties.opacity).toBe(1);+ // immediateRender is in EXTRAS_KEYS, should be in extras+ expect(result.animations[0].extras).toBeDefined();+ expect(result.animations[0].extras!.immediateRender).toBeDefined();+ // Should not be in properties+ expect(result.animations[0].properties).not.toHaveProperty("immediateRender");+ });++ it("callbacks (onComplete etc.) are dropped", () => {+ // Note: validation would flag these, but the parser just drops them+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, duration: 1, onComplete: function() { console.log("done"); } }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties).not.toHaveProperty("onComplete");+ expect(result.animations[0].extras).toBeUndefined();+ });++ it("delay is not included in properties (BUILTIN_VAR_KEYS)", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { opacity: 1, duration: 0.5, delay: 0.2 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].properties).not.toHaveProperty("delay");+ expect(result.animations[0].properties).not.toHaveProperty("duration");+ });++ it("percentage string values in properties survive", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { width: "50%", opacity: 1, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ expect(result.animations[0].properties.width).toBe("50%");+ expect(result.animations[0].properties.opacity).toBe(1);+ });++ it("scope resolution: binary expression with one unresolvable side", () => {+ const script = `+ const BASE = 100;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: BASE + unknownVar, y: BASE * 2, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);+ // BASE + unknownVar: left is 100, right is undefined => result is undefined => __raw+ const xVal = result.animations[0].properties.x;+ expect(typeof xVal === "string" && xVal.startsWith("__raw:")).toBe(true);+ // BASE * 2: both resolved => 200+ expect(result.animations[0].properties.y).toBe(200);+ });++ it("negative position in ID generation", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el", { x: 100, duration: 1 }, -2.5);+ `;+ const result = parseGsapScript(script);+ // ID uses Math.round(position * 1000) for numeric positions+ expect(result.animations[0].id).toBe("#el-to--2500");+ });++ it("fromTo with no position arg defaults to 0", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.fromTo("#el", { opacity: 0 }, { opacity: 1, duration: 1 });+ `;+ const result = parseGsapScript(script);+ expect(result.animations).toHaveLength(1);+ // For fromTo, position is args[3] which is undefined => defaults to 0+ expect(result.animations[0].position).toBe(0);+ });+});diff --git a/packages/core/src/parsers/gsapParser.test.ts b/packages/core/src/parsers/gsapParser.test.tsindex 3dae45caf0..cbdddeb5f7 100644--- a/packages/core/src/parsers/gsapParser.test.ts+++ b/packages/core/src/parsers/gsapParser.test.ts@@ -8,6 +8,9 @@ import {validateCompositionGsap,getAnimationsForElement,keyframesToGsapAnimations,+ addAnimationToScript,+ removeAnimationFromScript,+ updateAnimationInScript,} from "./gsapParser.js";import type { GsapAnimation } from "./gsapParser.js";import type { Keyframe } from "../core.types";@@ -79,9 +82,7 @@ describe("parseGsapScript", () => {expect(anim.position).toBe(2);});- it("parseObjectLiteral does not match negative numbers (known limitation)", () => {- // The regex in parseObjectLiteral only matches [\d.]+, not negative numbers.- // Negative values like x: -100 won't be parsed by the object literal parser.+ it("parses negative numbers in property values", () => {const script = `const tl = gsap.timeline({ paused: true });tl.fromTo("#el5", { opacity: 0, x: -100 }, { opacity: 1, x: 0, duration: 1 }, 0);@@ -92,8 +93,7 @@ describe("parseGsapScript", () => {const anim = result.animations[0];expect(anim.fromProperties).toBeDefined();expect(anim.fromProperties?.opacity).toBe(0);- // -100 is not parseable by the regex, so x won't be in fromProperties- expect(anim.fromProperties?.x).toBeUndefined();+ expect(anim.fromProperties?.x).toBe(-100);});it("handles an empty script", () => {@@ -142,7 +142,7 @@ describe("parseGsapScript", () => {expect(result.animations[2].method).toBe("to");});- it("filters out unsupported properties from animations", () => {+ it("extracts all GSAP properties including non-standard ones", () => {const script = `const tl = gsap.timeline({ paused: true });tl.to("#el1", { opacity: 1, backgroundColor: "red", x: 50, duration: 0.5 }, 0);@@ -151,8 +151,7 @@ describe("parseGsapScript", () => {expect(result.animations[0].properties.opacity).toBe(1);expect(result.animations[0].properties.x).toBe(50);- // backgroundColor is not in SUPPORTED_PROPS, so it's filtered out- expect(result.animations[0].properties.backgroundColor).toBeUndefined();+ expect(result.animations[0].properties.backgroundColor).toBe("red");});it("extracts ease from properties", () => {@@ -175,6 +174,197 @@ describe("parseGsapScript", () => {expect(result.timelineVar).toBe("timeline");expect(result.animations).toHaveLength(1);});++ it("preserves string position values like '+=1' and '<'", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: 1, duration: 0.5 }, "+=1");+ tl.to("#el2", { x: 100, duration: 1 }, "<");+ tl.to("#el3", { y: 50, duration: 0.3 }, "-=0.5");+ `;+ const result = parseGsapScript(script);++ expect(result.animations).toHaveLength(3);+ expect(result.animations[0].position).toBe("+=1");+ expect(result.animations[1].position).toBe("<");+ expect(result.animations[2].position).toBe("-=0.5");+ });++ it("resolves variable references from const declarations in the same script", () => {+ const script = `+ const FADE = 0.8;+ const OFFSET = -60;+ const MY_EASE = "power3.out";+ const tl = gsap.timeline({ paused: true });+ tl.from("#el1", { y: OFFSET, opacity: 0, duration: FADE, ease: MY_EASE }, 0);+ `;+ const result = parseGsapScript(script);++ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties.y).toBe(-60);+ expect(result.animations[0].properties.opacity).toBe(0);+ expect(result.animations[0].duration).toBe(0.8);+ expect(result.animations[0].ease).toBe("power3.out");+ });++ it("resolves computed expressions from scope bindings", () => {+ const script = `+ const BASE = 100;+ const HALF = BASE / 2;+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { x: HALF, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);++ expect(result.animations[0].properties.x).toBe(50);+ });++ it("preserves unresolvable references as __raw: prefixed strings", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: someUndefinedVar, x: 50, duration: 1 }, 0);+ `;+ const result = parseGsapScript(script);++ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].properties.x).toBe(50);+ expect(result.animations[0].properties.opacity).toBe("__raw:someUndefinedVar");+ });++ it("generates stable content-based IDs", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);+ tl.to("#el2", { x: 100, duration: 1 }, 1);+ `;+ const result1 = parseGsapScript(script);+ const result2 = parseGsapScript(script);++ // IDs are deterministic across parses+ expect(result1.animations[0].id).toBe(result2.animations[0].id);+ expect(result1.animations[1].id).toBe(result2.animations[1].id);++ // IDs encode selector, method, and position+ expect(result1.animations[0].id).toBe("#el1-to-0");+ expect(result1.animations[1].id).toBe("#el2-to-1000");+ });++ it("disambiguates colliding IDs with a suffix", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: 0, duration: 0.3 }, 0);+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);+ `;+ const result = parseGsapScript(script);++ expect(result.animations[0].id).toBe("#el1-to-0");+ expect(result.animations[1].id).toBe("#el1-to-0-2");+ });++ it("uses string position in ID for relative positions", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: 1, duration: 0.5 }, "+=1");+ `;+ const result = parseGsapScript(script);++ expect(result.animations[0].id).toBe("#el1-to-+=1");+ });+});++describe("stagger/yoyo/repeat round-trip", () => {+ it("preserves stagger as extras on parse", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: 0.1 }, 0);+ `;+ const result = parseGsapScript(script);++ expect(result.animations).toHaveLength(1);+ expect(result.animations[0].extras).toBeDefined();+ expect(result.animations[0].extras!.stagger).toBe("__raw:0.1");+ expect(result.animations[0].properties.opacity).toBe(1);+ // stagger should NOT appear in properties+ expect(result.animations[0].properties).not.toHaveProperty("stagger");+ });++ it("preserves complex stagger object on round-trip", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, duration: 0.5, stagger: { each: 0.15, from: "start" } }, 0);+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });++ expect(serialized).toContain("stagger: {");+ expect(serialized).toContain("each: 0.15");+ expect(serialized).toContain('from: "start"');+ });++ it("preserves yoyo and repeat on round-trip", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { x: 100, duration: 1, yoyo: true, repeat: 3, repeatDelay: 0.2 }, 0);+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });++ expect(serialized).toContain("yoyo: true");+ expect(serialized).toContain("repeat: 3");+ expect(serialized).toContain("repeatDelay: 0.2");+ });++ it("survives a full parse-edit-serialize round-trip with stagger intact", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to(".items", { opacity: 1, x: 50, duration: 0.5, stagger: 0.1, ease: "power2.out" }, 0);+ `;+ const parsed = parseGsapScript(script);+ const animId = parsed.animations[0].id;+ // Simulate an edit — change opacity to 0.5+ const updatedScript = updateAnimationInScript(script, animId, {+ properties: { opacity: 0.5, x: 50 },+ });+ // stagger should still be in the output+ expect(updatedScript).toContain("stagger: 0.1");+ expect(updatedScript).toContain("opacity: 0.5");+ });+});++describe("unresolvable value round-trip", () => {+ it("preserves unresolvable property values through serialize", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { opacity: someFn(), x: 50, duration: 1 }, 0);+ `;+ const parsed = parseGsapScript(script);+ const serialized = serializeGsapAnimations(parsed.animations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ });++ // The raw expression should survive — emitted without quotes+ expect(serialized).toContain("opacity: someFn()");+ expect(serialized).toContain("x: 50");+ });++ it("preserves complex unresolvable expressions", () => {+ const script = `+ const tl = gsap.timeline({ paused: true });+ tl.to("#el1", { x: getOffset() + 10, y: 200, duration: 1 }, 0);+ `;+ const parsed = parseGsapScript(script);++ // x is unresolvable (function call in expression), y is resolvable+ expect(parsed.animations[0].properties.y).toBe(200);+ expect(String(parsed.animations[0].properties.x)).toMatch(/^__raw:/);+ });});describe("gsapAnimationsToKeyframes", () => {@@ -244,7 +434,7 @@ describe("gsapAnimationsToKeyframes", () => {targetSelector: "#el1",method: "set",position: 5,- properties: { x: 0, y: 0, scale: 1 },+ properties: { x: 0, y: 0 },},{id: "anim-2",@@ -258,7 +448,6 @@ describe("gsapAnimationsToKeyframes", () => {const keyframes = gsapAnimationsToKeyframes(animations, 5, { skipBaseSet: true });- // The set at position 5 (time=0) with x=0, y=0, scale=1 (base values) should be skippedexpect(keyframes).toHaveLength(1);expect(keyframes[0].id).toBe("anim-2");});@@ -527,6 +716,83 @@ describe("getAnimationsForElement", () => {});});+describe("mutation functions parse-fail safety", () => {+ const garbage = "this is not valid javascript @@@ {{{{";++ it("updateAnimationInScript returns original script on parse failure", () => {+ const result = updateAnimationInScript(garbage, "anim-1", { duration: 2 });+ expect(result).toBe(garbage);+ });++ it("addAnimationToScript returns original script on parse failure", () => {+ const result = addAnimationToScript(garbage, {+ targetSelector: "#el1",+ method: "to",+ position: 0,+ properties: { opacity: 1 },+ duration: 1,+ });+ expect(result.script).toBe(garbage);+ expect(result.id).toBe("");+ });++ it("removeAnimationFromScript returns original script on parse failure", () => {+ const result = removeAnimationFromScript(garbage, "anim-1");+ expect(result).toBe(garbage);+ });+});++describe("serializeGsapAnimations quote escaping", () => {+ it("escapes quotes and backslashes in string property values", () => {+ const animations: GsapAnimation[] = [+ {+ id: "anim-1",+ targetSelector: "#el1",+ method: "to",+ position: 0,+ properties: { content: 'say "hello"' },+ duration: 1,+ },+ ];++ const result = serializeGsapAnimations(animations);+ // JSON.stringify produces escaped quotes+ expect(result).toContain('content: "say \\"hello\\""');+ });++ it("escapes backslashes in string property values", () => {+ const animations: GsapAnimation[] = [+ {+ id: "anim-1",+ targetSelector: "#el1",+ method: "to",+ position: 0,+ properties: { path: "C:\\Users\\test" },+ duration: 1,+ },+ ];++ const result = serializeGsapAnimations(animations);+ expect(result).toContain('path: "C:\\\\Users\\\\test"');+ });++ it("serializes string position values correctly", () => {+ const animations: GsapAnimation[] = [+ {+ id: "anim-1",+ targetSelector: "#el1",+ method: "to",+ position: "+=1",+ properties: { opacity: 1 },+ duration: 0.5,+ },+ ];++ const result = serializeGsapAnimations(animations);+ expect(result).toContain('"+=1"');+ });+});+describe("SUPPORTED_PROPS", () => {it("includes expected properties", () => {expect(SUPPORTED_PROPS).toContain("opacity");diff --git a/packages/core/src/parsers/gsapParser.ts b/packages/core/src/parsers/gsapParser.tsindex c8db6a4cbf..1a8eb1c7b0 100644--- a/packages/core/src/parsers/gsapParser.ts+++ b/packages/core/src/parsers/gsapParser.ts@@ -1,299 +1,395 @@-import type { Keyframe, KeyframeProperties, ValidationResult } from "../core.types";+/**+ * Node-only GSAP AST parser. Depends on recast / @babel/parser, which compile+ * to CommonJS that calls `require("fs")` — so this module must never be in the+ * static import graph of isomorphic/browser code. It is reachable only via the+ * `@hyperframes/core/gsap-parser` subpath (studio-api mutations + the linter).+ *+ * Recast-free helpers (serialization, keyframe conversion, validation, types)+ * live in `./gsapSerialize` and are re-exported here so this subpath exposes the+ * full surface for tests and server-side consumers.+ */+import * as recast from "recast";+import { parse as babelParse } from "@babel/parser";+import {+ type GsapAnimation,+ type GsapMethod,+ type ParsedGsap,+ serializeGsapAnimations,+} from "./gsapSerialize";++export type { GsapAnimation, GsapMethod, ParsedGsap } from "./gsapSerialize";+export {+ serializeGsapAnimations,+ getAnimationsForElement,+ validateCompositionGsap,+ keyframesToGsapAnimations,+ gsapAnimationsToKeyframes,+ SUPPORTED_PROPS,+ SUPPORTED_EASES,+} from "./gsapSerialize";-export type GsapMethod = "set" | "to" | "from" | "fromTo";+const GSAP_METHODS = new Set<string>(["set", "to", "from", "fromTo"]);-export interface GsapAnimation {- id: string;- targetSelector: string;- method: GsapMethod;- position: number;- properties: Record<string, number | string>;- fromProperties?: Record<string, number | string>;- duration?: number;- ease?: string;-}+// ── Recast AST Helpers ──────────────────────────────────────────────────────++type ScopeBindings = ReadonlyMap<string, number | string | boolean>;-export interface ParsedGsap {- animations: GsapAnimation[];- timelineVar: string;- preamble: string;- postamble: string;+function parseScript(script: string) {+ return recast.parse(script, {+ parser: {+ parse(source: string) {+ return babelParse(source, { sourceType: "script", plugins: [], tokens: true });+ },+ },+ });}-const GSAP_METHODS = new Set<string>(["set", "to", "from", "fromTo"]);+function collectScopeBindings(ast: any): ScopeBindings {+ const bindings = new Map<string, number | string | boolean>();+ recast.types.visit(ast, {+ visitVariableDeclarator(path: any) {+ const name = path.node.id?.name;+ const init = path.node.init;+ if (name && init) {+ const val = resolveNode(init, bindings);+ if (val !== undefined) bindings.set(name, val);+ }+ this.traverse(path);+ },+ });+ return bindings;+}-export const SUPPORTED_PROPS = [- "opacity",- "visibility",- "x",- "y",- "scale",- "scaleX",- "scaleY",- "rotation",- "autoAlpha",- "width",- "height",-];--export const SUPPORTED_EASES = [- "none",- "power1.in",- "power1.out",- "power1.inOut",- "power2.in",- "power2.out",- "power2.inOut",- "power3.in",- "power3.out",- "power3.inOut",- "power4.in",- "power4.out",- "power4.inOut",- "back.in",- "back.out",- "back.inOut",- "elastic.in",- "elastic.out",- "elastic.inOut",- "bounce.in",- "bounce.out",- "bounce.inOut",- "expo.in",- "expo.out",- "expo.inOut",-];--function parseObjectLiteral(str: string): Record<string, number | string> {- const result: Record<string, number | string> = {};-- const cleaned = str.replace(/^\{|\}$/g, "").trim();- if (!cleaned) return result;-- const propRegex = /(\w+)\s*:\s*("[^"]*"|'[^']*'|[\d.]+|[a-zA-Z_][\w.]*)/g;- let match;-- while ((match = propRegex.exec(cleaned)) !== null) {- const key = match[1] ?? "";- let value: string | number = match[2] ?? "";-- if (typeof value === "string") {- if (- (value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))- ) {- value = value.slice(1, -1);- } else if (!isNaN(Number(value))) {- value = Number(value);+function resolveNode(+ node: any,+ scope: ReadonlyMap<string, number | string | boolean>,+): number | string | boolean | undefined {+ if (!node) return undefined;+ if (node.type === "NumericLiteral" || (node.type === "Literal" && typeof node.value === "number"))+ return node.value;+ if (node.type === "StringLiteral" || (node.type === "Literal" && typeof node.value === "string"))+ return node.value;+ if (+ node.type === "BooleanLiteral" ||+ (node.type === "Literal" && typeof node.value === "boolean")+ )+ return node.value;+ if (node.type === "UnaryExpression" && node.operator === "-" && node.argument) {+ const val = resolveNode(node.argument, scope);+ return typeof val === "number" ? -val : undefined;+ }+ if (node.type === "BinaryExpression") {+ const left = resolveNode(node.left, scope);+ const right = resolveNode(node.right, scope);+ if (typeof left === "number" && typeof right === "number") {+ switch (node.operator) {+ case "+":+ return left + right;+ case "-":+ return left - right;+ case "*":+ return left * right;+ case "/":+ return right !== 0 ? left / right : undefined;}}-- result[key] = value;+ if (typeof left === "string" && node.operator === "+") return left + String(right ?? "");+ if (typeof right === "string" && node.operator === "+") return String(left ?? "") + right;}+ if (node.type === "Identifier" && scope.has(node.name)) {+ return scope.get(node.name);+ }+ if (node.type === "TemplateLiteral" && node.expressions?.length === 0) {+ return node.quasis?.[0]?.value?.cooked ?? undefined;+ }+ return undefined;+}- return result;+function extractLiteralValue(node: any, scope: ScopeBindings): unknown {+ return resolveNode(node, scope);}-function findMatchingBrace(str: string, startIndex: number): number {- let depth = 0;- for (let i = startIndex; i < str.length; i++) {- if (str[i] === "{") depth++;- else if (str[i] === "}") {- depth--;- if (depth === 0) return i;+function objectExpressionToRecord(node: any, scope: ScopeBindings): Record<string, unknown> {+ const result: Record<string, unknown> = {};+ if (node?.type !== "ObjectExpression") return result;+ for (const prop of node.properties ?? []) {+ if (prop.type !== "ObjectProperty" && prop.type !== "Property") continue;+ const key = prop.key?.name ?? prop.key?.value;+ if (!key) continue;+ const resolved = resolveNode(prop.value, scope);+ if (resolved !== undefined) {+ result[key] = resolved;+ } else {+ // Preserve unresolvable values as raw source text so they survive round-trips+ result[key] = `__raw:${recast.print(prop.value).code}`;}}- return -1;+ return result;}-export function parseGsapScript(script: string): ParsedGsap {- const animations: GsapAnimation[] = [];- let idCounter = 0;-- const timelineMatch = script.match(/(?:const|let|var)\s+(\w+)\s*=\s*gsap\.timeline/);- const timelineVar = timelineMatch ? (timelineMatch[1] ?? "tl") : "tl";+// ── Timeline Variable Detection ─────────────────────────────────────────────- const preambleMatch = script.match(- new RegExp(- `^[\\s\\S]*?(?:const|let|var)\\s+${timelineVar}\\s*=\\s*gsap\\.timeline\\s*\\([^)]*\\)\\s*;?`,- ),+function isGsapTimelineCall(node: any): boolean {+ return (+ node?.type === "CallExpression" &&+ node.callee?.type === "MemberExpression" &&+ node.callee.object?.name === "gsap" &&+ node.callee.property?.name === "timeline");- const preamble = preambleMatch- ? preambleMatch[0]- : `const ${timelineVar} = gsap.timeline({ paused: true });`;-- const methodPattern = new RegExp(- `${timelineVar}\\.(set|to|from|fromTo)\\s*\\(([^)]+(?:\\{[^}]*\\}[^)]*)+)\\)`,- "g",- );-- let match;- while ((match = methodPattern.exec(script)) !== null) {- const rawMethod = match[1];- if (!rawMethod || !GSAP_METHODS.has(rawMethod)) continue;- const method: GsapMethod = rawMethod as GsapMethod;- const argsStr = match[2] ?? "";-- const animation = parseGsapCall(method, argsStr, ++idCounter);- if (animation) {- animations.push(animation);- }- }-- const lastAnimIdx = script.lastIndexOf(`${timelineVar}.`);- let postamble = "";- if (lastAnimIdx !== -1) {- const afterLastAnim = script.slice(lastAnimIdx);- const endOfCall = afterLastAnim.indexOf(";");- if (endOfCall !== -1) {- postamble = script.slice(lastAnimIdx + endOfCall + 1).trim();- }- }-- return { animations, timelineVar, preamble, postamble };}-function parseGsapCall(method: GsapMethod, argsStr: string, idNum: number): GsapAnimation | null {- const selectorMatch = argsStr.match(/^\s*["']([^"']+)["']\s*,/);- if (!selectorMatch) return null;-- const targetSelector = selectorMatch[1] ?? "";- const afterSelector = argsStr.slice(selectorMatch[0].length);-- let properties: Record<string, number | string> = {};- let fromProperties: Record<string, number | string> | undefined;- let position = 0;-- if (method === "fromTo") {- const firstBrace = afterSelector.indexOf("{");- const firstEnd = findMatchingBrace(afterSelector, firstBrace);- if (firstBrace === -1 || firstEnd === -1) return null;+interface TimelineDetection {+ timelineVar: string | null;+ timelineCount: number;+}- fromProperties = parseObjectLiteral(afterSelector.slice(firstBrace, firstEnd + 1));+function findTimelineVar(ast: any): TimelineDetection {+ let timelineVar: string | null = null;+ let timelineCount = 0;+ recast.types.visit(ast, {+ visitVariableDeclarator(path: any) {+ if (isGsapTimelineCall(path.node.init)) {+ timelineCount += 1;+ if (!timelineVar) timelineVar = path.node.id?.name ?? null;+ }+ this.traverse(path);+ },+ visitAssignmentExpression(path: any) {+ if (isGsapTimelineCall(path.node.right)) {+ timelineCount += 1;+ if (!timelineVar) {+ const left = path.node.left;+ if (left?.type === "Identifier") timelineVar = left.name;+ }+ }+ this.traverse(path);+ },+ });+ return { timelineVar, timelineCount };+}- const secondPart = afterSelector.slice(firstEnd + 1);- const secondBrace = secondPart.indexOf("{");- const secondEnd = findMatchingBrace(secondPart, secondBrace);- if (secondBrace === -1 || secondEnd === -1) return null;+// ── Find All Tween Calls ────────────────────────────────────────────────────- properties = parseObjectLiteral(secondPart.slice(secondBrace, secondEnd + 1));+interface TweenCallInfo {+ path: any;+ node: any;+ method: GsapMethod;+ selector: string;+ varsArg: any;+ fromArg?: any;+ positionArg?: any;+}- const afterProps = secondPart.slice(secondEnd + 1);- const posMatch = afterProps.match(/,\s*([\d.]+)/);- if (posMatch) position = parseFloat(posMatch[1] ?? "");- } else {- const braceStart = afterSelector.indexOf("{");- const braceEnd = findMatchingBrace(afterSelector, braceStart);+function findAllTweenCalls(ast: any, timelineVar: string): TweenCallInfo[] {+ const results: TweenCallInfo[] = [];+ recast.types.visit(ast, {+ visitCallExpression(path: any) {+ const node = path.node;+ const callee = node.callee;+ if (+ callee?.type === "MemberExpression" &&+ callee.object?.type === "Identifier" &&+ callee.object.name === timelineVar &&+ callee.property?.type === "Identifier"+ ) {+ const method = callee.property.name;+ if (!GSAP_METHODS.has(method)) {+ this.traverse(path);+ return;+ }+ const args = node.arguments;+ if (args.length < 2) {+ this.traverse(path);+ return;+ }+ const selectorArg = args[0];+ const selectorValue =+ selectorArg.type === "StringLiteral" || selectorArg.type === "Literal"+ ? String(selectorArg.value)+ : null;+ if (!selectorValue) {+ this.traverse(path);+ return;+ }- if (braceStart !== -1 && braceEnd !== -1) {- properties = parseObjectLiteral(afterSelector.slice(braceStart, braceEnd + 1));+ if (method === "fromTo") {+ results.push({+ path,+ node,+ method: "fromTo",+ selector: selectorValue,+ fromArg: args[1],+ varsArg: args[2],+ positionArg: args[3],+ });+ } else {+ results.push({+ path,+ node,+ method: method as GsapMethod,+ selector: selectorValue,+ varsArg: args[1],+ positionArg: args[2],+ });+ }+ }+ this.traverse(path);+ },+ });+ return results;+}- const afterProps = afterSelector.slice(braceEnd + 1);- const posMatch = afterProps.match(/,\s*([\d.]+)/);- if (posMatch) position = parseFloat(posMatch[1] ?? "");+/** Keys that are stored on dedicated GsapAnimation fields (not in properties/extras). */+const BUILTIN_VAR_KEYS = new Set(["duration", "ease", "delay"]);++/** Keys that are never preserved (callbacks / advanced patterns). */+const DROPPED_VAR_KEYS = new Set(["keyframes", "onComplete", "onStart", "onUpdate", "onRepeat"]);++/** Keys that belong in `extras` — non-editable GSAP config that must survive round-trips. */+const EXTRAS_KEYS = new Set([+ "stagger",+ "yoyo",+ "repeat",+ "repeatDelay",+ "snap",+ "overwrite",+ "immediateRender",+]);++/**+ * Extract raw source text for a property in an ObjectExpression AST node.+ * Returns the printed source of the value node, suitable for verbatim re-emission.+ */+function extractRawPropertySource(varsArgNode: any, key: string): string | undefined {+ if (varsArgNode?.type !== "ObjectExpression") return undefined;+ for (const prop of varsArgNode.properties ?? []) {+ if (prop.type !== "ObjectProperty" && prop.type !== "Property") continue;+ const propKey = prop.key?.name ?? prop.key?.value;+ if (propKey === key) {+ return recast.print(prop.value).code;}}+ return undefined;+}- const duration = typeof properties.duration === "number" ? properties.duration : undefined;- const ease = typeof properties.ease === "string" ? properties.ease : undefined;+function tweenCallToAnimation(+ call: TweenCallInfo,+ scope: ScopeBindings,+): Omit<GsapAnimation, "id"> {+ const vars = objectExpressionToRecord(call.varsArg, scope);+ const properties: Record<string, number | string> = {};+ const extras: Record<string, unknown> = {};++ for (const [key, val] of Object.entries(vars)) {+ if (BUILTIN_VAR_KEYS.has(key)) continue;+ if (DROPPED_VAR_KEYS.has(key)) continue;++ if (EXTRAS_KEYS.has(key)) {+ // For extras, prefer the raw AST source so complex objects like+ // `stagger: { each: 0.15, from: "start" }` survive verbatim.+ const rawSource = extractRawPropertySource(call.varsArg, key);+ if (rawSource !== undefined) {+ extras[key] = `__raw:${rawSource}`;+ } else if (val !== undefined) {+ extras[key] = val;+ }+ continue;+ }- const filteredProps: Record<string, number | string> = {};- for (const [key, value] of Object.entries(properties)) {- if (SUPPORTED_PROPS.includes(key)) {- filteredProps[key] = value;+ if (typeof val === "number" || typeof val === "string") {+ properties[key] = val;}}- let filteredFromProps: Record<string, number | string> | undefined;- if (fromProperties) {- filteredFromProps = {};- for (const [key, value] of Object.entries(fromProperties)) {- if (SUPPORTED_PROPS.includes(key)) {- filteredFromProps[key] = value;+ let fromProperties: Record<string, number | string> | undefined;+ if (call.method === "fromTo" && call.fromArg) {+ fromProperties = {};+ const fromVars = objectExpressionToRecord(call.fromArg, scope);+ for (const [key, val] of Object.entries(fromVars)) {+ if (typeof val === "number" || typeof val === "string") {+ fromProperties[key] = val;}}}- return {- id: `anim-${idNum}`,- targetSelector,- method,+ const posVal = call.positionArg ? extractLiteralValue(call.positionArg, scope) : 0;+ const position: number | string =+ typeof posVal === "number" ? posVal : typeof posVal === "string" ? posVal : 0;+ const duration = typeof vars.duration === "number" ? vars.duration : undefined;+ const ease = typeof vars.ease === "string" ? vars.ease : undefined;++ const anim: Omit<GsapAnimation, "id"> = {+ targetSelector: call.selector,+ method: call.method,position,- properties: filteredProps,- fromProperties: filteredFromProps,+ properties,+ fromProperties,duration,ease,};+ if (Object.keys(extras).length > 0) anim.extras = extras;+ return anim;}-export function serializeGsapAnimations(- animations: GsapAnimation[],- timelineVar = "tl",- options?: { includeMediaSync?: boolean },-): string {- const sorted = [...animations].sort((a, b) => a.position - b.position);-- const lines = sorted.map((anim) => {- const selector = `"${anim.targetSelector}"`;-- const props: Record<string, number | string> = { ...anim.properties };- if (anim.duration !== undefined) props.duration = anim.duration;- if (anim.ease) props.ease = anim.ease;-- const propsStr = serializeObject(props);-- switch (anim.method) {- case "set":- return ` ${timelineVar}.set(${selector}, ${propsStr}, ${anim.position});`;- case "to":- return ` ${timelineVar}.to(${selector}, ${propsStr}, ${anim.position});`;- case "from":- return ` ${timelineVar}.from(${selector}, ${propsStr}, ${anim.position});`;- case "fromTo": {- const fromStr = serializeObject(anim.fromProperties || {});- return ` ${timelineVar}.fromTo(${selector}, ${fromStr}, ${propsStr}, ${anim.position});`;+// ── Stable ID Generation ───────────────────────────────────────────────────++function assignStableIds(anims: Omit<GsapAnimation, "id">[]): GsapAnimation[] {+ const counts = new Map<string, number>();+ return anims.map((anim) => {+ const posKey =+ typeof anim.position === "number"+ ? String(Math.round(anim.position * 1000))+ : String(anim.position);+ const base = `${anim.targetSelector}-${anim.method}-${posKey}`;+ const count = (counts.get(base) ?? 0) + 1;+ counts.set(base, count);+ const id = count === 1 ? base : `${base}-${count}`;+ return { ...anim, id };+ });+}++// ── Public API ──────────────────────────────────────────────────────────────++export function parseGsapScript(script: string): ParsedGsap {+ try {+ const ast = parseScript(script);+ const scope = collectScopeBindings(ast);+ const detection = findTimelineVar(ast);+ const timelineVar = detection.timelineVar ?? "tl";+ const calls = findAllTweenCalls(ast, timelineVar);+ const animations = assignStableIds(calls.map((call) => tweenCallToAnimation(call, scope)));++ const timelineMatch = script.match(+ new RegExp(+ `^[\\s\\S]*?(?:const|let|var)\\s+${timelineVar}\\s*=\\s*gsap\\.timeline\\s*\\([^)]*\\)\\s*;?`,+ ),+ );+ const preamble =+ timelineMatch?.[0] ?? `const ${timelineVar} = gsap.timeline({ paused: true });`;++ const lastCallIdx = script.lastIndexOf(`${timelineVar}.`);+ let postamble = "";+ if (lastCallIdx !== -1) {+ const afterLast = script.slice(lastCallIdx);+ const endOfCall = afterLast.indexOf(";");+ if (endOfCall !== -1) {+ postamble = script.slice(lastCallIdx + endOfCall + 1).trim();}}- });- let mediaSync = "";- if (options?.includeMediaSync) {- mediaSync = `- // Sync media playback- ${timelineVar}.eventCallback("onUpdate", function() {- const time = ${timelineVar}.time();- document.querySelectorAll("video[data-start], audio[data-start]").forEach(function(media) {- const start = parseFloat(media.dataset.start);- const end = parseFloat(media.dataset.end) || Infinity;- const mediaTime = time - start;- if (time >= start && time < end) {- if (Math.abs(media.currentTime - mediaTime) > 0.1) {- media.currentTime = mediaTime;- }- if (media.paused && !${timelineVar}.paused()) {- media.play().catch(function() {});- }- } else if (!media.paused) {- media.pause();- }- });- });`;+ const result: ParsedGsap = { animations, timelineVar, preamble, postamble };+ if (detection.timelineCount > 1) result.multipleTimelines = true;+ if (detection.timelineCount > 0 && detection.timelineVar === null)+ result.unsupportedTimelinePattern = true;+ return result;+ } catch {+ return { animations: [], timelineVar: "tl", preamble: "", postamble: "" };}-- return `- const ${timelineVar} = gsap.timeline({ paused: true });-${lines.join("\n")}${mediaSync}- `;}-function serializeObject(obj: Record<string, number | string>): string {- const entries = Object.entries(obj).map(([key, value]) => {- if (typeof value === "string") {- return `${key}: "${value}"`;- }- return `${key}: ${value}`;- });- return `{ ${entries.join(", ")} }`;+/** Returns true when the parse result is a failure fallback (no animations, no preamble). */+function isParseFailure(parsed: ParsedGsap): boolean {+ return parsed.animations.length === 0 && !parsed.preamble;}export function updateAnimationInScript(@@ -302,15 +398,14 @@ export function updateAnimationInScript(updates: Partial<GsapAnimation>,): string {const parsed = parseGsapScript(script);-- const updated = parsed.animations.map((anim) => {- if (anim.id === animationId) {- return { ...anim, ...updates };- }- return anim;+ if (isParseFailure(parsed)) return script;+ const updated = parsed.animations.map((anim) =>+ anim.id === animationId ? { ...anim, ...updates } : anim,+ );+ return serializeGsapAnimations(updated, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,});-- return serializeGsapAnimations(updated, parsed.timelineVar);}export function addAnimationToScript(@@ -318,203 +413,25 @@ export function addAnimationToScript(animation: Omit<GsapAnimation, "id">,): { script: string; id: string } {const parsed = parseGsapScript(script);-+ if (isParseFailure(parsed)) return { script, id: "" };const id = `anim-${Date.now()}`;const newAnim: GsapAnimation = { ...animation, id };-- parsed.animations.push(newAnim);-+ const allAnimations = [...parsed.animations, newAnim];return {- script: serializeGsapAnimations(parsed.animations, parsed.timelineVar),+ script: serializeGsapAnimations(allAnimations, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,+ }),id,};}export function removeAnimationFromScript(script: string, animationId: string): string {const parsed = parseGsapScript(script);+ if (isParseFailure(parsed)) return script;const filtered = parsed.animations.filter((a) => a.id !== animationId);- return serializeGsapAnimations(filtered, parsed.timelineVar);-}--export function getAnimationsForElement(- animations: GsapAnimation[],- elementId: string,-): GsapAnimation[] {- const selector = `#${elementId}`;- return animations.filter((a) => a.targetSelector === selector);-}--const FORBIDDEN_GSAP_PATTERNS: Array<{ pattern: RegExp; message: string }> = [- { pattern: /\.call\s*\(/, message: "call() method not allowed" },- {- pattern: /\.add\s*\(\s*function/,- message: "add(function) not allowed",- },- {- pattern: /\.add\s*\(\s*\(/,- message: "add() with arrow function not allowed",- },- { pattern: /onComplete\s*:/, message: "onComplete callback not allowed" },- { pattern: /onStart\s*:/, message: "onStart callback not allowed" },- { pattern: /onUpdate\s*:/, message: "onUpdate callback not allowed" },- {- pattern: /onRepeat\s*:/,- message: "onRepeat callback not allowed",- },- {- pattern: /onReverseComplete\s*:/,- message: "onReverseComplete callback not allowed",- },- {- pattern: /repeat\s*:\s*-1/,- message: "Infinite repeat (repeat: -1) not allowed",- },- {- pattern: /Math\.random\s*\(/,- message: "Random values (Math.random) not allowed",- },- {- pattern: /Date\.now\s*\(/,- message: "Date-dependent values (Date.now) not allowed",- },- { pattern: /new\s+Date\s*\(/, message: "Date constructor not allowed" },- { pattern: /setTimeout\s*\(/, message: "setTimeout not allowed" },- { pattern: /setInterval\s*\(/, message: "setInterval not allowed" },- {- pattern: /requestAnimationFrame\s*\(/,- message: "requestAnimationFrame not allowed",- },-];--export function validateCompositionGsap(script: string): ValidationResult {- const errors: string[] = [];- const warnings: string[] = [];-- for (const { pattern, message } of FORBIDDEN_GSAP_PATTERNS) {- if (pattern.test(script)) {- errors.push(message);- }- }-- if (/yoyo\s*:\s*true/.test(script)) {- warnings.push("yoyo animations may behave unexpectedly when scrubbing");- }-- if (/stagger\s*:/.test(script)) {- warnings.push("stagger animations may not serialize correctly");- }-- return {- valid: errors.length === 0,- errors,- warnings,- };-}--export function keyframesToGsapAnimations(- elementId: string,- keyframes: Keyframe[],- elementStartTime: number,- base?: { x?: number; y?: number; scale?: number },-): GsapAnimation[] {- const sorted = [...keyframes].sort((a, b) => a.time - b.time);- const animations: GsapAnimation[] = [];- const baseX = base?.x ?? 0;- const baseY = base?.y ?? 0;- const baseScale = base?.scale ?? 1;-- sorted.forEach((kf, i) => {- const absoluteTime = elementStartTime + kf.time;- const isFirst = i === 0;-- const prevKf = i > 0 ? sorted[i - 1] : null;- const duration = prevKf ? kf.time - prevKf.time : undefined;- const position = prevKf ? elementStartTime + prevKf.time : absoluteTime;-- const properties: Record<string, number | string> = {};- for (const [key, value] of Object.entries(kf.properties)) {- if (typeof value !== "number") continue;- if (key === "x") properties.x = baseX + value;- else if (key === "y") properties.y = baseY + value;- else if (key === "scale") properties.scale = baseScale * value;- else properties[key] = value;- }-- animations.push({- id: `${elementId}-kf-${kf.id}`,- targetSelector: `#${elementId}`,- method: isFirst ? "set" : "to",- position,- properties,- duration: isFirst ? undefined : duration,- ease: kf.ease,- });+ return serializeGsapAnimations(filtered, parsed.timelineVar, {+ preamble: parsed.preamble,+ postamble: parsed.postamble,});-- return animations;-}--export function gsapAnimationsToKeyframes(- animations: GsapAnimation[],- elementStartTime: number,- options?: {- baseX?: number;- baseY?: number;- baseScale?: number;- clampTimeToZero?: boolean;- skipBaseSet?: boolean;- },-): Keyframe[] {- const validMethods: GsapMethod[] = ["set", "to", "from", "fromTo"];- const baseX = options?.baseX ?? 0;- const baseY = options?.baseY ?? 0;- const baseScale = options?.baseScale ?? 1;- const clampTimeToZero = options?.clampTimeToZero ?? true;- const skipBaseSet = options?.skipBaseSet ?? false;- const baseTimeEpsilon = 0.001;- const baseValueEpsilon = 0.00001;-- return animations- .filter((a) => validMethods.includes(a.method))- .map((a) => {- const relativeTimeRaw = a.position - elementStartTime;- const time = clampTimeToZero ? Math.max(0, relativeTimeRaw) : relativeTimeRaw;-- const properties: Partial<KeyframeProperties> = {};-- for (const [key, value] of Object.entries(a.properties)) {- if (SUPPORTED_PROPS.includes(key) && typeof value === "number") {- if (key === "x") {- (properties as Record<string, number>).x = value - baseX;- } else if (key === "y") {- (properties as Record<string, number>).y = value - baseY;- } else if (key === "scale") {- (properties as Record<string, number>).scale =- baseScale !== 0 ? value / baseScale : value;- } else {- (properties as Record<string, number>)[key] = value;- }- }- }-- if (skipBaseSet && a.method === "set" && Math.abs(time) <= baseTimeEpsilon) {- const propKeys = Object.keys(properties);- const isOnlyBaseProps = propKeys.every((k) => k === "x" || k === "y" || k === "scale");- if (isOnlyBaseProps && propKeys.length > 0) {- const hasNonBaseOffset =- (properties.x !== undefined && Math.abs(properties.x) > baseValueEpsilon) ||- (properties.y !== undefined && Math.abs(properties.y) > baseValueEpsilon) ||- (properties.scale !== undefined && Math.abs(properties.scale - 1) > baseValueEpsilon);- if (!hasNonBaseOffset) {- return null;- }- }- }-- const kf: Keyframe = { id: a.id, time, properties };- if (a.ease !== undefined) kf.ease = a.ease;- return kf;- })- .filter((kf): kf is Keyframe => kf !== null)- .sort((a, b) => a.time - b.time);}diff --git a/packages/core/src/parsers/gsapSerialize.ts b/packages/core/src/parsers/gsapSerialize.tsnew file mode 100644index 0000000000..bf6c7c2244--- /dev/null+++ b/packages/core/src/parsers/gsapSerialize.ts@@ -0,0 +1,287 @@+/**+ * Recast-free GSAP helpers: serialization, keyframe<->animation conversion,+ * validation, and shared types.+ *+ * This module MUST NOT import recast / @babel/parser. It is part of the+ * isomorphic core layer that the barrel and browser code depend on. AST+ * parsing of GSAP source lives in the Node-only `./gsapParser` module.+ */+import type { Keyframe, KeyframeProperties, ValidationResult } from "../core.types";++export type GsapMethod = "set" | "to" | "from" | "fromTo";++export interface GsapAnimation {+ id: string;+ targetSelector: string;+ method: GsapMethod;+ position: number | string;+ properties: Record<string, number | string>;+ fromProperties?: Record<string, number | string>;+ duration?: number;+ ease?: string;+ /** Non-editable GSAP config (stagger, yoyo, repeat, etc.) preserved for round-trips. */+ extras?: Record<string, unknown>;+}++export interface ParsedGsap {+ animations: GsapAnimation[];+ timelineVar: string;+ preamble: string;+ postamble: string;+ multipleTimelines?: boolean;+ unsupportedTimelinePattern?: boolean;+}++export { SUPPORTED_PROPS, SUPPORTED_EASES } from "./gsapConstants";++// ── Serialization ───────────────────────────────────────────────────────────++export function serializeGsapAnimations(+ animations: GsapAnimation[],+ timelineVar = "tl",+ options?: { includeMediaSync?: boolean; preamble?: string; postamble?: string },+): string {+ const sorted = [...animations].sort((a, b) => {+ const aNum = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;+ const bNum = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;+ return aNum - bNum;+ });+ const lines = sorted.map((anim) => {+ const selector = `"${anim.targetSelector}"`;+ const props: Record<string, number | string> = { ...anim.properties };+ if (anim.duration !== undefined) props.duration = anim.duration;+ if (anim.ease) props.ease = anim.ease;+ let propsStr = serializeObject(props);+ if (anim.extras && Object.keys(anim.extras).length > 0) {+ const extrasStr = serializeExtras(anim.extras);+ if (Object.keys(props).length === 0) {+ propsStr = `{ ${extrasStr} }`;+ } else {+ // Insert extras before the closing brace+ propsStr = propsStr.slice(0, -2) + `, ${extrasStr} }`;+ }+ }+ const posStr = typeof anim.position === "string" ? `"${anim.position}"` : anim.position;+ switch (anim.method) {+ case "set":+ return ` ${timelineVar}.set(${selector}, ${propsStr}, ${posStr});`;+ case "to":+ return ` ${timelineVar}.to(${selector}, ${propsStr}, ${posStr});`;+ case "from":+ return ` ${timelineVar}.from(${selector}, ${propsStr}, ${posStr});`;+ case "fromTo": {+ const fromStr = serializeObject(anim.fromProperties || {});+ return ` ${timelineVar}.fromTo(${selector}, ${fromStr}, ${propsStr}, ${posStr});`;+ }+ }+ });++ let mediaSync = "";+ if (options?.includeMediaSync) {+ mediaSync = `+ ${timelineVar}.eventCallback("onUpdate", function() {+ const time = ${timelineVar}.time();+ document.querySelectorAll("video[data-start], audio[data-start]").forEach(function(media) {+ const start = parseFloat(media.dataset.start);+ const end = parseFloat(media.dataset.end) || Infinity;+ const mediaTime = time - start;+ if (time >= start && time < end) {+ if (Math.abs(media.currentTime - mediaTime) > 0.1) {+ media.currentTime = mediaTime;+ }+ if (media.paused && !${timelineVar}.paused()) {+ media.play().catch(function() {});+ }+ } else if (!media.paused) {+ media.pause();+ }+ });+ });`;+ }++ const preamble = options?.preamble || `const ${timelineVar} = gsap.timeline({ paused: true });`;+ const postamble = options?.postamble ? `\n ${options.postamble}` : "";++ return `+ ${preamble}+${lines.join("\n")}${mediaSync}${postamble}+ `;+}++function serializeValue(value: unknown): string {+ if (typeof value === "string" && value.startsWith("__raw:")) {+ return value.slice(6);+ }+ if (typeof value === "string") return JSON.stringify(value);+ return String(value);+}++function serializeObject(obj: Record<string, number | string>): string {+ const entries = Object.entries(obj).map(([key, value]) => {+ const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);+ return `${safeKey}: ${serializeValue(value)}`;+ });+ return `{ ${entries.join(", ")} }`;+}++function serializeExtras(extras: Record<string, unknown>): string {+ return Object.entries(extras)+ .map(([key, value]) => {+ const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);+ return `${safeKey}: ${serializeValue(value)}`;+ })+ .join(", ");+}++// ── Element filtering ─────────────────────────────────────────────────────────++export function getAnimationsForElement(+ animations: GsapAnimation[],+ elementId: string,+): GsapAnimation[] {+ const selector = `#${elementId}`;+ return animations.filter((a) => a.targetSelector === selector);+}++// ── Validation (regex-based, no AST needed) ─────────────────────────────────++const FORBIDDEN_GSAP_PATTERNS: Array<{ pattern: RegExp; message: string }> = [+ { pattern: /\.call\s*\(/, message: "call() method not allowed" },+ { pattern: /\.add\s*\(/, message: "add() method not allowed" },+ { pattern: /\.addLabel\s*\(/, message: "addLabel() method not allowed" },+ { pattern: /\.addPause\s*\(/, message: "addPause() method not allowed" },+ { pattern: /gsap\.registerPlugin\s*\(/, message: "registerPlugin() not allowed" },+ { pattern: /gsap\.registerEffect\s*\(/, message: "registerEffect() not allowed" },+ { pattern: /ScrollTrigger/, message: "ScrollTrigger not allowed" },+ { pattern: /MotionPathPlugin/, message: "MotionPathPlugin not allowed" },+ { pattern: /onComplete\s*:/, message: "onComplete callback not allowed" },+ { pattern: /onUpdate\s*:/, message: "onUpdate callback not allowed" },+ { pattern: /onStart\s*:/, message: "onStart callback not allowed" },+ { pattern: /onRepeat\s*:/, message: "onRepeat callback not allowed" },+ { pattern: /onReverseComplete\s*:/, message: "onReverseComplete callback not allowed" },+ { pattern: /repeat\s*:\s*-1/, message: "Infinite repeat (repeat: -1) not allowed" },+ { pattern: /Math\.random\s*\(/, message: "Random values (Math.random) not allowed" },+ { pattern: /Date\.now\s*\(/, message: "Date-dependent values (Date.now) not allowed" },+ { pattern: /new\s+Date\s*\(/, message: "Date constructor not allowed" },+ { pattern: /setTimeout\s*\(/, message: "setTimeout not allowed" },+ { pattern: /setInterval\s*\(/, message: "setInterval not allowed" },+ { pattern: /requestAnimationFrame\s*\(/, message: "requestAnimationFrame not allowed" },+];++export function validateCompositionGsap(script: string): ValidationResult {+ const errors: string[] = [];+ const warnings: string[] = [];+ for (const { pattern, message } of FORBIDDEN_GSAP_PATTERNS) {+ if (pattern.test(script)) errors.push(message);+ }+ if (/yoyo\s*:\s*true/.test(script)) {+ warnings.push("yoyo animations may behave unexpectedly when scrubbing");+ }+ if (/stagger\s*:/.test(script)) {+ warnings.push("stagger animations may not serialize correctly");+ }+ return { valid: errors.length === 0, errors, warnings };+}++// ── Keyframe Conversion Helpers ─────────────────────────────────────────────++export function keyframesToGsapAnimations(+ elementId: string,+ keyframes: Keyframe[],+ elementStartTime: number,+ base?: { x?: number; y?: number; scale?: number },+): GsapAnimation[] {+ const sorted = [...keyframes].sort((a, b) => a.time - b.time);+ const animations: GsapAnimation[] = [];+ const baseX = base?.x ?? 0;+ const baseY = base?.y ?? 0;+ const baseScale = base?.scale ?? 1;++ sorted.forEach((kf, i) => {+ const absoluteTime = elementStartTime + kf.time;+ const isFirst = i === 0;+ const prevKf = i > 0 ? sorted[i - 1] : null;+ const duration = prevKf ? kf.time - prevKf.time : undefined;+ const position = prevKf ? elementStartTime + prevKf.time : absoluteTime;++ const properties: Record<string, number | string> = {};+ for (const [key, value] of Object.entries(kf.properties)) {+ if (typeof value !== "number") continue;+ if (key === "x") properties.x = baseX + value;+ else if (key === "y") properties.y = baseY + value;+ else if (key === "scale") properties.scale = baseScale * value;+ else properties[key] = value;+ }++ animations.push({+ id: `${elementId}-kf-${kf.id}`,+ targetSelector: `#${elementId}`,+ method: isFirst ? "set" : "to",+ position,+ properties,+ duration: isFirst ? undefined : duration,+ ease: kf.ease,+ });+ });++ return animations;+}++export function gsapAnimationsToKeyframes(+ animations: GsapAnimation[],+ elementStartTime: number,+ options?: {+ baseX?: number;+ baseY?: number;+ baseScale?: number;+ clampTimeToZero?: boolean;+ skipBaseSet?: boolean;+ },+): Keyframe[] {+ const validMethods: GsapMethod[] = ["set", "to", "from", "fromTo"];+ const baseX = options?.baseX ?? 0;+ const baseY = options?.baseY ?? 0;+ const baseScale = options?.baseScale ?? 1;+ const clampTimeToZero = options?.clampTimeToZero ?? true;+ const skipBaseSet = options?.skipBaseSet ?? false;+ const baseTimeEpsilon = 0.001;+ const baseValueEpsilon = 0.00001;++ return animations+ .filter((a) => validMethods.includes(a.method) && typeof a.position === "number")+ .map((a) => {+ const relativeTimeRaw = (a.position as number) - elementStartTime;+ const time = clampTimeToZero ? Math.max(0, relativeTimeRaw) : relativeTimeRaw;++ const properties: Partial<KeyframeProperties> = {};+ for (const [key, value] of Object.entries(a.properties)) {+ if (typeof value !== "number") continue;+ if (key === "x") properties.x = value - baseX;+ else if (key === "y") properties.y = value - baseY;+ else if (key === "scale") {+ properties.scale = baseScale !== 0 ? value / baseScale : value;+ } else {+ (properties as Record<string, number>)[key] = value;+ }+ }++ if (+ skipBaseSet &&+ a.method === "set" &&+ time < baseTimeEpsilon &&+ Object.values(properties).every(+ (v) => typeof v === "number" && Math.abs(v) < baseValueEpsilon,+ )+ ) {+ return null;+ }++ return {+ id: a.id.replace(/^.*-kf-/, ""),+ time,+ properties: properties as KeyframeProperties,+ ease: a.ease,+ };+ })+ .filter((kf): kf is NonNullable<typeof kf> => kf !== null) as Keyframe[];+}diff --git a/packages/core/src/parsers/htmlParser.ts b/packages/core/src/parsers/htmlParser.tsindex 23fae3a2bb..92864e04ed 100644--- a/packages/core/src/parsers/htmlParser.ts+++ b/packages/core/src/parsers/htmlParser.ts@@ -10,12 +10,7 @@ import type {StageZoomKeyframe,CompositionVariable,} from "../core.types";-import {- parseGsapScript,- validateCompositionGsap,- gsapAnimationsToKeyframes,- getAnimationsForElement,-} from "./gsapParser";+import { validateCompositionGsap } from "./gsapSerialize";import type { ValidationResult } from "../core.types";const MEDIA_TYPES = new Set<string>(["video", "image", "audio"]);@@ -375,24 +370,6 @@ export function parseHtml(html: string): ParsedHtml {}}- // Extract x/y positions and scale from GSAP script- if (gsapScript) {- const positionMap = extractPositionsFromGsap(gsapScript);- for (const element of elements) {- const pos = positionMap.get(element.id);- if (pos) {- if (pos.x !== undefined) element.x = pos.x;- if (pos.y !== undefined) element.y = pos.y;- if (- pos.scale !== undefined &&- (element.type === "video" || element.type === "image" || element.type === "composition")- ) {- (element as TimelineMediaElement | TimelineCompositionElement).scale = pos.scale;- }- }- }- }-// Normalize keyframes (clamp negative time, convert absolute -> relative if detected)for (const element of elements) {const elementKeyframes = keyframes[element.id];@@ -428,32 +405,6 @@ export function parseHtml(html: string): ParsedHtml {const resolution = parseResolutionFromHtml(doc) ?? parseResolutionFromCss(doc, allStyles);- // Extract keyframes from GSAP animations for elements that don't have data-keyframes- if (gsapScript) {- const parsed = parseGsapScript(gsapScript);- for (const element of elements) {- // Only extract from GSAP if we don't have explicit data-keyframes- if (keyframes[element.id]) continue;-- const elementAnimations = getAnimationsForElement(parsed.animations, element.id);- if (elementAnimations.length > 0) {- const elementKeyframes = gsapAnimationsToKeyframes(elementAnimations, element.startTime, {- baseX: element.x ?? 0,- baseY: element.y ?? 0,- baseScale:- element.type === "video" || element.type === "image" || element.type === "composition"- ? ((element as TimelineMediaElement | TimelineCompositionElement).scale ?? 1)- : 1,- clampTimeToZero: true,- skipBaseSet: true,- });- if (elementKeyframes.length > 0) {- keyframes[element.id] = elementKeyframes;- }- }- }- }-// Parse stage zoom keyframes from zoom containerconst stageZoomKeyframes = parseStageZoomKeyframes(doc);@@ -501,52 +452,6 @@ function parseStageZoomKeyframes(doc: Document): StageZoomKeyframe[] {return [];}-/**- * Extract x/y positions and scale from GSAP set() calls at position 0- * Returns a map of elementId -> { x, y, scale }- */-function extractPositionsFromGsap(- script: string,-): Map<string, { x?: number; y?: number; scale?: number }> {- const positionMap = new Map<string, { x?: number; y?: number; scale?: number }>();-- try {- const parsed = parseGsapScript(script);-- // Look for set() calls at position 0 with x/y/scale properties- for (const anim of parsed.animations) {- if (anim.method === "set" && anim.position === 0) {- // Extract element ID from selector (e.g., "#element-1" -> "element-1")- const selectorMatch = anim.targetSelector.match(/^#(.+)$/);- if (!selectorMatch) continue;-- const elementId = selectorMatch[1] ?? "";- const x = typeof anim.properties.x === "number" ? anim.properties.x : undefined;- const y = typeof anim.properties.y === "number" ? anim.properties.y : undefined;- const scale = typeof anim.properties.scale === "number" ? anim.properties.scale : undefined;-- // Only add to map if x, y, or scale is defined and non-default- if (- (x !== undefined && x !== 0) ||- (y !== undefined && y !== 0) ||- (scale !== undefined && scale !== 1)- ) {- const existing = positionMap.get(elementId) || {};- positionMap.set(elementId, {- x: x !== undefined ? x : existing.x,- y: y !== undefined ? y : existing.y,- scale: scale !== undefined ? scale : existing.scale,- });- }- }- }- } catch {- // skip GSAP position parsing failure- }-- return positionMap;-}-function normalizeKeyframes(keyframes: Keyframe[],baseX: number,diff --git a/packages/core/src/studio-api/helpers/sourceMutation.test.ts b/packages/core/src/studio-api/helpers/sourceMutation.test.tsindex 305b934888..5d1e1eb949 100644--- a/packages/core/src/studio-api/helpers/sourceMutation.test.ts+++ b/packages/core/src/studio-api/helpers/sourceMutation.test.ts@@ -70,6 +70,44 @@ describe("patchElementInHtml", () => {expect(result).toContain('data-hf-studio-path-offset="true"');});+ it("does not double data- prefix when property already has it", () => {+ const result = patchElementInHtml(FIXTURE, { id: "hero" }, [+ { type: "attribute", property: "data-hf-studio-path-offset", value: "true" },+ ]);++ expect(result).toContain('data-hf-studio-path-offset="true"');+ expect(result).not.toContain("data-data-hf-studio-path-offset");+ });++ it("does not double data- prefix for any studio attribute", () => {+ const attrs = [+ "data-hf-studio-path-offset",+ "data-hf-studio-original-translate",+ "data-hf-studio-original-inline-translate",+ "data-hf-studio-box-size",+ "data-hf-studio-rotation",+ ];+ for (const attr of attrs) {+ const result = patchElementInHtml(FIXTURE, { id: "hero" }, [+ { type: "attribute", property: attr, value: "true" },+ ]);+ expect(result).toContain(`${attr}="true"`);+ expect(result).not.toContain(`data-${attr}`);+ }+ });++ it("removes attribute with data- prefix already present", () => {+ const withAttr = patchElementInHtml(FIXTURE, { id: "hero" }, [+ { type: "attribute", property: "data-hf-studio-path-offset", value: "true" },+ ]);+ expect(withAttr).toContain('data-hf-studio-path-offset="true"');++ const removed = patchElementInHtml(withAttr, { id: "hero" }, [+ { type: "attribute", property: "data-hf-studio-path-offset", value: null },+ ]);+ expect(removed).not.toContain("hf-studio-path-offset");+ });+it("patches html attribute", () => {const result = patchElementInHtml(FIXTURE, { id: "hero" }, [{ type: "html-attribute", property: "title", value: "greeting" },diff --git a/packages/core/src/studio-api/helpers/sourceMutation.ts b/packages/core/src/studio-api/helpers/sourceMutation.tsindex 2b7e22b95a..6c00041e7a 100644--- a/packages/core/src/studio-api/helpers/sourceMutation.ts+++ b/packages/core/src/studio-api/helpers/sourceMutation.ts@@ -176,10 +176,13 @@ export function patchElementInHtml(}break;case "attribute":- if (op.value != null) {- htmlEl.setAttribute(`data-${op.property}`, op.value);- } else {- htmlEl.removeAttribute(`data-${op.property}`);+ {+ const fullAttr = op.property.startsWith("data-") ? op.property : `data-${op.property}`;+ if (op.value != null) {+ htmlEl.setAttribute(fullAttr, op.value);+ } else {+ htmlEl.removeAttribute(fullAttr);+ }}break;case "html-attribute":diff --git a/packages/core/src/studio-api/routes/files.ts b/packages/core/src/studio-api/routes/files.tsindex 9663b68c12..14f8505f83 100644--- a/packages/core/src/studio-api/routes/files.ts+++ b/packages/core/src/studio-api/routes/files.ts@@ -23,6 +23,7 @@ import {probeElementInSource,type PatchOperation,} from "../helpers/sourceMutation.js";+import { parseHTML } from "linkedom";// ── Shared helpers ──────────────────────────────────────────────────────────@@ -182,6 +183,42 @@ function updateReferences(projectDir: string, oldPath: string, newPath: string):return updatedCount;}+// ── GSAP script extraction ──────────────────────────────────────────────────++/**+ * Parse an HTML string with linkedom, locate the inline `<script>` that+ * contains GSAP timeline code, and return both its text content and a+ * function that replaces that script block and serialises back to HTML.+ */+function extractGsapScriptBlock(+ html: string,+): { scriptText: string; replaceScript: (newText: string) => string } | null {+ const { document } = parseHTML(html);+ const scripts = document.querySelectorAll("script:not([src])");+ for (const script of scripts) {+ const content = script.textContent || "";+ if (+ content.includes("gsap.timeline") ||+ content.includes(".set(") ||+ content.includes(".to(")+ ) {+ return {+ scriptText: content,+ replaceScript(newText: string): string {+ script.textContent = newText;+ return document.toString();+ },+ };+ }+ }+ return null;+}++/** Lazy-load gsapParser to avoid pulling recast into every file-route import. */+async function loadGsapParser() {+ return import("../../parsers/gsapParser.js");+}+// ── Route registration ──────────────────────────────────────────────────────export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {@@ -458,4 +495,150 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {return c.json({ ok: true, files: uploaded, skipped, invalid }, 201);},);++ // ── GSAP Animations (parse) ──++ api.get("/projects/:id/gsap-animations/*", async (c) => {+ const res = await resolveProjectPath(c, adapter, (id) => `/projects/${id}/gsap-animations/`, {+ mustExist: true,+ });+ if ("error" in res) return res.error;++ const html = readFileSync(res.absPath, "utf-8");+ const block = extractGsapScriptBlock(html);+ if (!block) {+ return c.json({+ animations: [],+ timelineVar: "tl",+ preamble: "",+ postamble: "",+ });+ }++ const { parseGsapScript } = await loadGsapParser();+ const parsed = parseGsapScript(block.scriptText);+ return c.json(parsed);+ });++ // ── GSAP Mutations ──++ type GsapMutationRequest =+ | {+ type: "update-property";+ animationId: string;+ property: string;+ value: number | string;+ }+ | {+ type: "update-meta";+ animationId: string;+ updates: { duration?: number; ease?: string; position?: number };+ }+ | {+ type: "add";+ targetSelector: string;+ method: "to" | "from" | "set";+ position: number;+ duration?: number;+ ease?: string;+ properties: Record<string, number | string>;+ }+ | { type: "delete"; animationId: string }+ | {+ type: "add-property";+ animationId: string;+ property: string;+ defaultValue: number | string;+ }+ | { type: "remove-property"; animationId: string; property: string };++ api.post("/projects/:id/gsap-mutations/*", async (c) => {+ const res = await resolveProjectPath(c, adapter, (id) => `/projects/${id}/gsap-mutations/`, {+ mustExist: true,+ });+ if ("error" in res) return res.error;++ const body = (await c.req.json().catch(() => null)) as GsapMutationRequest | null;+ if (!body || !body.type) {+ return c.json({ error: "mutation type required" }, 400);+ }++ const html = readFileSync(res.absPath, "utf-8");+ const block = extractGsapScriptBlock(html);+ if (!block) {+ return c.json({ error: "no GSAP script found in file" }, 400);+ }++ const {+ parseGsapScript,+ updateAnimationInScript,+ addAnimationToScript,+ removeAnimationFromScript,+ } = await loadGsapParser();++ let newScript: string;++ switch (body.type) {+ case "update-property": {+ const parsed = parseGsapScript(block.scriptText);+ const anim = parsed.animations.find((a) => a.id === body.animationId);+ if (!anim) return c.json({ error: "animation not found" }, 404);+ newScript = updateAnimationInScript(block.scriptText, body.animationId, {+ properties: { ...anim.properties, [body.property]: body.value },+ });+ break;+ }+ case "update-meta": {+ newScript = updateAnimationInScript(block.scriptText, body.animationId, body.updates);+ break;+ }+ case "add": {+ const result = addAnimationToScript(block.scriptText, {+ targetSelector: body.targetSelector,+ method: body.method,+ position: body.position,+ duration: body.duration,+ ease: body.ease,+ properties: body.properties,+ });+ newScript = result.script;+ break;+ }+ case "delete": {+ newScript = removeAnimationFromScript(block.scriptText, body.animationId);+ break;+ }+ case "add-property": {+ const parsed = parseGsapScript(block.scriptText);+ const anim = parsed.animations.find((a) => a.id === body.animationId);+ if (!anim) return c.json({ error: "animation not found" }, 404);+ newScript = updateAnimationInScript(block.scriptText, body.animationId, {+ properties: { ...anim.properties, [body.property]: body.defaultValue },+ });+ break;+ }+ case "remove-property": {+ const parsed = parseGsapScript(block.scriptText);+ const anim = parsed.animations.find((a) => a.id === body.animationId);+ if (!anim) return c.json({ error: "animation not found" }, 404);+ const filtered = { ...anim.properties };+ delete filtered[body.property];+ newScript = updateAnimationInScript(block.scriptText, body.animationId, {+ properties: filtered,+ });+ break;+ }+ default:+ return c.json({ error: `unknown mutation type: ${(body as { type: string }).type}` }, 400);+ }++ const newHtml = block.replaceScript(newScript);+ if (newHtml !== html) {+ writeFileSync(res.absPath, newHtml, "utf-8");+ }++ // Re-parse the mutated script so the UI gets fresh state+ const freshParsed = parseGsapScript(newScript);+ return c.json({ ok: true, parsed: freshParsed, before: html, after: newHtml });+ });}diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.tsindex 358f70e993..ea471bd8a3 100644--- a/packages/producer/src/server.ts+++ b/packages/producer/src/server.ts@@ -288,7 +288,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandlereturn c.json({ success: false, requestId, error: preparedResult.error }, 400);}- const result = runHyperframeLint(preparedResult.prepared);+ const result = await runHyperframeLint(preparedResult.prepared);log.info("lint completed", {requestId,entryFile: preparedResult.prepared.entryFile,diff --git a/packages/producer/src/services/hyperframeLint.ts b/packages/producer/src/services/hyperframeLint.tsindex c1c7a9c220..426bced4e6 100644--- a/packages/producer/src/services/hyperframeLint.ts+++ b/packages/producer/src/services/hyperframeLint.ts@@ -113,6 +113,8 @@ export function prepareHyperframeLintBody(return { error: "Missing lint source: provide projectDir, files, or html" };}-export function runHyperframeLint(prepared: PreparedHyperframeLintInput): HyperframeLintResult {+export async function runHyperframeLint(+ prepared: PreparedHyperframeLintInput,+): Promise<HyperframeLintResult> {return lintHyperframeHtml(prepared.html, { filePath: prepared.entryFile });}diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanel.tsxindex f009e6426c..49639ccd8e 100644--- a/packages/studio/src/components/StudioRightPanel.tsx+++ b/packages/studio/src/components/StudioRightPanel.tsx@@ -78,6 +78,15 @@ export function StudioRightPanel({handleAskAgent,handleDomMotionCommit,handleDomMotionClear,+ selectedGsapAnimations,+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ handleGsapUpdateProperty,+ handleGsapUpdateMeta,+ handleGsapDeleteAnimation,+ handleGsapAddAnimation,+ handleGsapAddProperty,+ handleGsapRemoveProperty,} = useDomEditContext();const { assets, fontAssets, projectDir, handleImportFiles, handleImportFonts } =@@ -198,6 +207,15 @@ export function StudioRightPanel({onImportAssets={handleImportFiles}fontAssets={fontAssets}onImportFonts={handleImportFonts}+ gsapAnimations={selectedGsapAnimations}+ gsapMultipleTimelines={gsapMultipleTimelines}+ gsapUnsupportedTimelinePattern={gsapUnsupportedTimelinePattern}+ onUpdateGsapProperty={handleGsapUpdateProperty}+ onUpdateGsapMeta={handleGsapUpdateMeta}+ onDeleteGsapAnimation={handleGsapDeleteAnimation}+ onAddGsapProperty={handleGsapAddProperty}+ onRemoveGsapProperty={handleGsapRemoveProperty}+ onAddGsapAnimation={handleGsapAddAnimation}/>) : motionPanelActive ? (<MotionPaneldiff --git a/packages/studio/src/components/editor/AnimationCard.tsx b/packages/studio/src/components/editor/AnimationCard.tsxnew file mode 100644index 0000000000..117a726bdd--- /dev/null+++ b/packages/studio/src/components/editor/AnimationCard.tsx@@ -0,0 +1,325 @@+import { memo, useCallback, useMemo, useState } from "react";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { SUPPORTED_EASES, SUPPORTED_PROPS } from "@hyperframes/core/gsap-constants";+import { RESPONSIVE_GRID } from "./propertyPanelHelpers";+import { MetricField, SelectField } from "./propertyPanelPrimitives";+import { controlPointsForGsapEase } from "./studioMotion";+import {+ EASE_LABELS,+ METHOD_LABELS,+ METHOD_TOOLTIPS,+ PROP_LABELS,+ PROP_TOOLTIPS,+ PROP_UNITS,+} from "./gsapAnimationConstants";+import { EaseCurveSection } from "./EaseCurveSection";++const PERCENT_PROPS = new Set(["opacity", "autoAlpha"]);+function isPercentProp(prop: string): boolean {+ return PERCENT_PROPS.has(prop);+}++function buildTweenSummary(animation: GsapAnimation): string {+ const easeName = animation.ease ?? "none";+ const ease = EASE_LABELS[easeName] ?? easeName;+ const props = Object.entries(animation.properties);+ const target = animation.targetSelector;+ const dur = animation.duration ?? 0;+ const pos = animation.position;+ const propDescs = props.map(([p, v]) => {+ const label = (PROP_LABELS[p] ?? p).toLowerCase();+ const unit = PROP_UNITS[p] ?? "";+ return `${label} to ${v}${unit}`;+ });+ const propText = propDescs.length > 0 ? propDescs.join(", ") : "no properties yet";+ if (animation.method === "set") return `At ${pos}s, instantly set ${target}'s ${propText}.`;+ if (animation.method === "from")+ return `Starting at ${pos}s, over ${dur}s, ${target} enters from ${propText} using a ${ease.toLowerCase()} curve.`;+ return `Starting at ${pos}s, over ${dur}s, animate ${target}'s ${propText} using a ${ease.toLowerCase()} curve.`;+}++function parseNumericOrString(raw: string): number | string {+ const num = Number(raw);+ return Number.isFinite(num) ? num : raw;+}++interface AnimationCardProps {+ animation: GsapAnimation;+ defaultExpanded: boolean;+ onUpdateProperty: (animationId: string, property: string, value: number | string) => void;+ onUpdateMeta: (+ animationId: string,+ updates: { duration?: number; ease?: string; position?: number },+ ) => void;+ onDeleteAnimation: (animationId: string) => void;+ onAddProperty: (animationId: string, property: string) => void;+ onRemoveProperty: (animationId: string, property: string) => void;+ onLivePreview?: (property: string, value: number | string) => void;+ onLivePreviewEnd?: () => void;+}++// fallow-ignore-next-line complexity+export const AnimationCard = memo(function AnimationCard({+ animation,+ defaultExpanded,+ onUpdateProperty,+ onUpdateMeta,+ onDeleteAnimation,+ onAddProperty,+ onRemoveProperty,+ onLivePreview,+ onLivePreviewEnd,+}: AnimationCardProps) {+ const [expanded, setExpanded] = useState(defaultExpanded);+ const [addingProp, setAddingProp] = useState(false);++ const usedProps = useMemo(+ () => new Set(Object.keys(animation.properties)),+ [animation.properties],+ );+ const availableProps = useMemo(+ () => SUPPORTED_PROPS.filter((p) => !usedProps.has(p)),+ [usedProps],+ );++ const commitProperty = useCallback(+ (prop: string, raw: string) => {+ const value = parseNumericOrString(raw);+ onUpdateProperty(animation.id, prop, value);+ onLivePreviewEnd?.();+ },+ [animation.id, onUpdateProperty, onLivePreviewEnd],+ );++ const scrubProperty = useCallback(+ (prop: string, raw: string) => {+ onLivePreview?.(prop, parseNumericOrString(raw));+ },+ [onLivePreview],+ );++ const commitDuration = useCallback(+ (raw: string) => {+ const num = Number(raw);+ if (Number.isFinite(num) && num >= 0)+ onUpdateMeta(animation.id, { duration: Math.max(0, num) });+ },+ [animation.id, onUpdateMeta],+ );++ const commitPosition = useCallback(+ (raw: string) => {+ const num = Number(raw);+ if (Number.isFinite(num) && num >= 0)+ onUpdateMeta(animation.id, { position: Math.max(0, num) });+ },+ [animation.id, onUpdateMeta],+ );++ const [copied, setCopied] = useState(false);++ const methodLabel = METHOD_LABELS[animation.method] ?? animation.method;+ const easeName = animation.ease ?? "none";+ const easeLabel = easeName.startsWith("custom(")+ ? "Custom curve"+ : (EASE_LABELS[easeName] ?? easeName);+ const endTime =+ typeof animation.position === "number"+ ? animation.position + (animation.duration ?? 0)+ : animation.position;++ const summary = useMemo(() => buildTweenSummary(animation), [animation]);++ return (+ <div className="border-b border-neutral-800 pb-3">+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="flex w-full items-center gap-2 py-1.5"+ >+ <span+ className="rounded bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-400"+ title={METHOD_TOOLTIPS[animation.method]}+ >+ {methodLabel}+ </span>+ <span className="text-[11px] font-medium text-neutral-400" title="When this effect plays">+ {typeof animation.position === "number" ? `${animation.position}s` : animation.position} –{" "}+ {typeof endTime === "number" ? `${endTime.toFixed(1)}s` : endTime}+ </span>+ <span className="ml-auto text-[10px] text-neutral-500" title={easeName}>+ {easeLabel}+ </span>+ <svg+ width="10"+ height="10"+ viewBox="0 0 10 10"+ fill="currentColor"+ className={`flex-shrink-0 text-neutral-500 transition-transform ${expanded ? "" : "-rotate-90"}`}+ >+ <path d="M2 3l3 4 3-4z" />+ </svg>+ </button>++ {expanded && (+ <div className="pt-2">+ <div className="space-y-3">+ <div className="flex items-start gap-2">+ <p className="flex-1 text-[10px] leading-relaxed text-neutral-400 italic">+ {summary}+ </p>+ <button+ type="button"+ onClick={() => {+ void navigator.clipboard.writeText(summary);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ }}+ className="flex-shrink-0 rounded px-1.5 py-0.5 text-[9px] font-medium text-neutral-500 transition-colors hover:bg-neutral-800 hover:text-neutral-300"+ title="Copy description to clipboard — paste into agent prompts"+ >+ {copied ? "Copied" : "Copy"}+ </button>+ </div>+ <div className={RESPONSIVE_GRID}>+ {animation.method !== "set" && (+ <MetricField+ label="Length"+ value={String(Math.max(0, animation.duration ?? 0))}+ suffix="s"+ tooltip="How long this effect lasts"+ onCommit={commitDuration}+ />+ )}+ <MetricField+ label="Starts at"+ value={+ typeof animation.position === "string"+ ? animation.position+ : String(Math.max(0, animation.position))+ }+ suffix={typeof animation.position === "number" ? "s" : undefined}+ tooltip="When this effect begins on the timeline"+ onCommit={commitPosition}+ />+ </div>++ {animation.method !== "set" && (+ <>+ <SelectField+ label="Speed"+ value={+ animation.ease?.startsWith("custom(") ? "custom" : (animation.ease ?? "none")+ }+ options={[...SUPPORTED_EASES, "custom"]}+ onChange={(next) => {+ if (next === "custom") {+ const points = controlPointsForGsapEase(animation.ease ?? "power2.out");+ const path = `M0,0 C${points.x1},${points.y1} ${points.x2},${points.y2} 1,1`;+ onUpdateMeta(animation.id, { ease: `custom(${path})` });+ } else {+ onUpdateMeta(animation.id, { ease: next });+ }+ }}+ />+ <EaseCurveSection+ ease={animation.ease ?? "none"}+ duration={animation.duration}+ onCustomEaseCommit={(customEase) =>+ onUpdateMeta(animation.id, { ease: customEase })+ }+ />+ </>+ )}++ {Object.keys(animation.properties).length > 0 && (+ <div className="space-y-1.5">+ {Object.entries(animation.properties).map(([prop, val]) => (+ <div key={prop} className="flex items-center gap-1">+ <div className="min-w-0 flex-1">+ <MetricField+ label={PROP_LABELS[prop] ?? prop}+ value={+ isPercentProp(prop) ? String(Math.round(Number(val) * 100)) : String(val)+ }+ suffix={PROP_UNITS[prop]}+ tooltip={PROP_TOOLTIPS[prop]}+ scrub+ liveCommit+ onCommit={(raw) => {+ const adjusted = isPercentProp(prop) ? String(Number(raw) / 100) : raw;+ scrubProperty(prop, adjusted);+ commitProperty(prop, adjusted);+ }}+ />+ </div>+ <button+ type="button"+ onClick={() => onRemoveProperty(animation.id, prop)}+ className="flex-shrink-0 rounded p-0.5 text-neutral-600 transition-colors hover:bg-neutral-800 hover:text-red-400"+ title={`Remove ${PROP_LABELS[prop] ?? prop}`}+ >+ <svg+ width="12"+ height="12"+ viewBox="0 0 12 12"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ >+ <path d="M3 3l6 6M9 3l-6 6" />+ </svg>+ </button>+ </div>+ ))}+ </div>+ )}++ <div className="flex items-center gap-2 pt-1">+ {addingProp && availableProps.length > 0 ? (+ <select+ autoFocus+ className="min-w-0 rounded-lg border border-neutral-700 bg-neutral-900 px-2 py-1 text-[11px] text-neutral-100 outline-none"+ defaultValue=""+ onChange={(e) => {+ if (e.target.value) onAddProperty(animation.id, e.target.value);+ setAddingProp(false);+ }}+ onBlur={() => setAddingProp(false)}+ >+ <option value="" disabled>+ Choose effect…+ </option>+ {availableProps.map((p) => (+ <option key={p} value={p}>+ {PROP_LABELS[p] ?? p}+ </option>+ ))}+ </select>+ ) : (+ availableProps.length > 0 && (+ <button+ type="button"+ onClick={() => setAddingProp(true)}+ className="text-[11px] font-medium text-neutral-400 transition-colors hover:text-neutral-200"+ title="Add another animated property to this effect"+ >+ + Effect+ </button>+ )+ )}+ <button+ type="button"+ onClick={() => onDeleteAnimation(animation.id)}+ className="ml-auto text-[11px] font-medium text-red-400 transition-colors hover:text-red-300"+ title="Remove this animation"+ >+ Remove+ </button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+});diff --git a/packages/studio/src/components/editor/EaseCurveSection.tsx b/packages/studio/src/components/editor/EaseCurveSection.tsxnew file mode 100644index 0000000000..07995c3369--- /dev/null+++ b/packages/studio/src/components/editor/EaseCurveSection.tsx@@ -0,0 +1,213 @@+import { useCallback, useRef, useState } from "react";+import { EASE_CURVES, EASE_LABELS, parseCustomEaseFromString } from "./gsapAnimationConstants";++function round2(n: number): number {+ return Math.round(n * 100) / 100;+}++export function EaseCurveSection({+ ease,+ duration,+ onCustomEaseCommit,+}: {+ ease: string;+ duration?: number;+ onCustomEaseCommit: (ease: string) => void;+}) {+ const isCustom = ease.startsWith("custom(");+ const curveFromPreset = EASE_CURVES[ease];+ const customPoints = isCustom ? parseCustomEaseFromString(ease) : null;+ const curve: [number, number, number, number] | null =+ isCustom && customPoints+ ? [customPoints.x1, customPoints.y1, customPoints.x2, customPoints.y2]+ : (curveFromPreset ?? null);++ const [draft, setDraft] = useState<[number, number, number, number] | null>(null);+ const [progress, setProgress] = useState<number | null>(null);+ const draggingRef = useRef<"p1" | "p2" | null>(null);+ const svgRef = useRef<SVGSVGElement | null>(null);+ const rafRef = useRef<number>(0);++ const play = useCallback(() => {+ const start = performance.now();+ const dur = 1000;+ const tick = (now: number) => {+ const t = Math.min((now - start) / dur, 1);+ setProgress(t);+ if (t < 1) rafRef.current = requestAnimationFrame(tick);+ else setTimeout(() => setProgress(null), 400);+ };+ cancelAnimationFrame(rafRef.current);+ rafRef.current = requestAnimationFrame(tick);+ }, []);++ const active = draft ?? curve;+ if (!active) return null;+ const [x1, y1, x2, y2] = active;++ const w = 200;+ const h = 100;+ const pad = 14;+ const gw = w - pad * 2;+ const gh = h - pad * 2;++ const toSvg = (px: number, py: number) => ({+ x: pad + gw * px,+ y: h - pad - gh * py,+ });++ const curvePath = `M${pad},${h - pad} C${toSvg(x1, y1).x},${toSvg(x1, y1).y} ${toSvg(x2, y2).x},${toSvg(x2, y2).y} ${w - pad},${pad}`;++ let dotX = pad;+ let dotY = h - pad;+ if (progress !== null) {+ const t = progress;+ const mt = 1 - t;+ dotX = pad + gw * (mt * mt * mt * 0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t);+ dotY =+ h - pad - gh * (mt * mt * mt * 0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t);+ }++ const handlePointerDown = (handle: "p1" | "p2", e: React.PointerEvent) => {+ e.preventDefault();+ e.stopPropagation();+ draggingRef.current = handle;+ (e.target as SVGElement).setPointerCapture(e.pointerId);+ if (!draft) setDraft([x1, y1, x2, y2]);+ };++ const handlePointerMove = (e: React.PointerEvent<SVGSVGElement>) => {+ if (!draggingRef.current || !svgRef.current) return;+ e.preventDefault();+ const rect = svgRef.current.getBoundingClientRect();+ const sx = ((e.clientX - rect.left) / rect.width) * w;+ const sy = ((e.clientY - rect.top) / rect.height) * h;+ const px = Math.max(0, Math.min(1, (sx - pad) / gw));+ const py = Math.max(-1, Math.min(2, (h - pad - sy) / gh));+ const prev = draft ?? [x1, y1, x2, y2];+ const next: [number, number, number, number] =+ draggingRef.current === "p1"+ ? [round2(px), round2(py), prev[2], prev[3]]+ : [prev[0], prev[1], round2(px), round2(py)];+ setDraft(next);+ };++ const handlePointerUp = () => {+ if (!draggingRef.current || !draft) return;+ draggingRef.current = null;+ const path = `M0,0 C${draft[0]},${draft[1]} ${draft[2]},${draft[3]} 1,1`;+ onCustomEaseCommit(`custom(${path})`);+ setDraft(null);+ };++ const p1 = toSvg(x1, y1);+ const p2 = toSvg(x2, y2);+ const start = toSvg(0, 0);+ const end = toSvg(1, 1);+ const label = isCustom ? "Custom curve" : (EASE_LABELS[ease] ?? ease);++ return (+ <div className="rounded-lg bg-neutral-900/50 p-2">+ <div className="mb-1.5 flex items-center justify-between">+ <span className="text-[10px] font-medium text-neutral-500">Speed curve</span>+ <button+ type="button"+ onClick={play}+ className="rounded px-1.5 py-0.5 text-[10px] font-medium text-emerald-400 transition-colors hover:bg-emerald-500/10"+ >+ {progress !== null ? "Playing…" : "Preview"}+ </button>+ </div>+ <div className="overflow-hidden rounded pt-[72px] -mt-[72px]">+ <svg+ ref={svgRef}+ width="100%"+ height={h}+ viewBox={`0 0 ${w} ${h}`}+ preserveAspectRatio="none"+ style={{ overflow: "visible" }}+ className="touch-none select-none"+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ onPointerCancel={handlePointerUp}+ >+ <line+ x1={pad}+ y1={h - pad}+ x2={w - pad}+ y2={h - pad}+ stroke="white"+ strokeOpacity="0.06"+ strokeWidth="0.5"+ />+ <line+ x1={pad}+ y1={pad}+ x2={pad}+ y2={h - pad}+ stroke="white"+ strokeOpacity="0.06"+ strokeWidth="0.5"+ />+ <line+ x1={start.x}+ y1={start.y}+ x2={p1.x}+ y2={p1.y}+ stroke="rgba(52,211,153,0.25)"+ strokeWidth="1"+ />+ <line+ x1={end.x}+ y1={end.y}+ x2={p2.x}+ y2={p2.y}+ stroke="rgba(52,211,153,0.25)"+ strokeWidth="1"+ />+ <path d={curvePath} fill="none" stroke="#34d399" strokeWidth="2" strokeLinecap="round" />+ {progress !== null && <circle cx={dotX} cy={dotY} r="4" fill="#34d399" />}+ <circle+ cx={p1.x}+ cy={p1.y}+ r="5"+ fill="#0a0a1a"+ stroke="#34d399"+ strokeWidth="2"+ className="cursor-grab active:cursor-grabbing"+ onPointerDown={(e) => handlePointerDown("p1", e)}+ />+ <circle+ cx={p2.x}+ cy={p2.y}+ r="5"+ fill="#0a0a1a"+ stroke="#34d399"+ strokeWidth="2"+ className="cursor-grab active:cursor-grabbing"+ onPointerDown={(e) => handlePointerDown("p2", e)}+ />+ {duration != null && duration > 0 && (+ <>+ <text x={pad} y={h - 1} textAnchor="start" className="fill-neutral-600 text-[8px]">+ 0s+ </text>+ <text+ x={pad + gw / 2}+ y={h - 1}+ textAnchor="middle"+ className="fill-neutral-600 text-[8px]"+ >+ {(duration / 2).toFixed(1)}s+ </text>+ <text x={w - pad} y={h - 1} textAnchor="end" className="fill-neutral-600 text-[8px]">+ {duration}s+ </text>+ </>+ )}+ </svg>+ </div>+ <p className="mt-1 text-center text-[10px] text-neutral-500">{label}</p>+ </div>+ );+}diff --git a/packages/studio/src/components/editor/GsapAnimationSection.tsx b/packages/studio/src/components/editor/GsapAnimationSection.tsxnew file mode 100644index 0000000000..42b70a956a--- /dev/null+++ b/packages/studio/src/components/editor/GsapAnimationSection.tsx@@ -0,0 +1,112 @@+import { memo, useState } from "react";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { Film } from "../../icons/SystemIcons";+import { Section } from "./propertyPanelPrimitives";+import { ADD_METHODS, ADD_METHOD_LABELS, METHOD_TOOLTIPS } from "./gsapAnimationConstants";+import { AnimationCard } from "./AnimationCard";++interface GsapAnimationSectionProps {+ animations: GsapAnimation[];+ multipleTimelines?: boolean;+ unsupportedTimelinePattern?: boolean;+ onUpdateProperty: (animationId: string, property: string, value: number | string) => void;+ onUpdateMeta: (+ animationId: string,+ updates: { duration?: number; ease?: string; position?: number },+ ) => void;+ onDeleteAnimation: (animationId: string) => void;+ onAddProperty: (animationId: string, property: string) => void;+ onRemoveProperty: (animationId: string, property: string) => void;+ onAddAnimation: (method: "to" | "from" | "set") => void;+ onLivePreview?: (property: string, value: number | string) => void;+ onLivePreviewEnd?: () => void;+}++export const GsapAnimationSection = memo(function GsapAnimationSection({+ animations,+ multipleTimelines,+ unsupportedTimelinePattern,+ onUpdateProperty,+ onUpdateMeta,+ onDeleteAnimation,+ onAddProperty,+ onRemoveProperty,+ onAddAnimation,+ onLivePreview,+ onLivePreviewEnd,+}: GsapAnimationSectionProps) {+ const [addMenuOpen, setAddMenuOpen] = useState(false);++ return (+ <Section title="Animation" icon={<Film size={15} />}>+ {multipleTimelines && (+ <p className="mb-2 rounded-lg bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-400">+ This file has multiple GSAP timelines. Animation editing is disabled to prevent data loss+ — consolidate into a single timeline to enable editing.+ </p>+ )}+ {unsupportedTimelinePattern && (+ <p className="mb-2 rounded-lg bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-400">+ This composition uses a timeline assignment pattern (window.__timelines[...]) that the+ editor doesn't support. Use a variable declaration (const tl = gsap.timeline()) to+ enable editing.+ </p>+ )}+ {multipleTimelines || unsupportedTimelinePattern ? null : (+ <div className="space-y-2">+ {animations.map((anim, index) => (+ <AnimationCard+ key={anim.id}+ animation={anim}+ defaultExpanded={index === 0}+ onUpdateProperty={onUpdateProperty}+ onUpdateMeta={onUpdateMeta}+ onDeleteAnimation={onDeleteAnimation}+ onAddProperty={onAddProperty}+ onRemoveProperty={onRemoveProperty}+ onLivePreview={onLivePreview}+ onLivePreviewEnd={onLivePreviewEnd}+ />+ ))}++ <div className="relative pt-1">+ {addMenuOpen ? (+ <div className="flex gap-1.5">+ {ADD_METHODS.map((method) => (+ <button+ key={method}+ type="button"+ title={METHOD_TOOLTIPS[method]}+ onClick={() => {+ onAddAnimation(method);+ setAddMenuOpen(false);+ }}+ className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 py-1.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white"+ >+ {ADD_METHOD_LABELS[method] ?? method}+ </button>+ ))}+ <button+ type="button"+ onClick={() => setAddMenuOpen(false)}+ className="px-1.5 text-[11px] text-neutral-500 hover:text-neutral-300"+ >+ Cancel+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => setAddMenuOpen(true)}+ className="text-[11px] font-medium text-neutral-400 transition-colors hover:text-neutral-200"+ title="Add a new animation effect to this element"+ >+ + Add effect+ </button>+ )}+ </div>+ </div>+ )}+ </Section>+ );+});diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsxindex c8a8d14fe7..9c65e9b1e8 100644--- a/packages/studio/src/components/editor/PropertyPanel.tsx+++ b/packages/studio/src/components/editor/PropertyPanel.tsx@@ -1,12 +1,7 @@import { memo } from "react";import { Clock, Eye, Layers, MessageSquare, Move, X } from "../../icons/SystemIcons";import { type DomEditSelection } from "./domEditing";-import {- readStudioBoxSize,- readStudioPathOffset,- readStudioRotation,- readGsapTranslateFromTransform,-} from "./manualEdits";+import { readStudioBoxSize, readStudioPathOffset, readStudioRotation } from "./manualEdits";import type { ImportedFontAsset } from "./fontAssets";import {EMPTY_STYLES,@@ -18,12 +13,13 @@ import {import { MetricField, Section } from "./propertyPanelPrimitives";import { isMediaElement, MediaSection } from "./propertyPanelMediaSection";import { TextSection, StyleSections } from "./propertyPanelSections";+import { GsapAnimationSection } from "./GsapAnimationSection";+import { STUDIO_GSAP_PANEL_ENABLED } from "./manualEditingAvailability";// Re-export helpers that external consumers import from this moduleexport {buildStrokeStyleUpdates,buildStrokeWidthStyleUpdates,- clampPanelNumber,getCssFilterFunctionPx,getClipPathInsetPx,inferBoxShadowPreset,@@ -54,6 +50,18 @@ interface PropertyPanelProps {onImportAssets?: (files: FileList) => Promise<string[]>;fontAssets?: ImportedFontAsset[];onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ gsapAnimations?: import("@hyperframes/core/gsap-parser").GsapAnimation[];+ gsapMultipleTimelines?: boolean;+ gsapUnsupportedTimelinePattern?: boolean;+ onUpdateGsapProperty?: (animId: string, prop: string, value: number | string) => void;+ onUpdateGsapMeta?: (+ animId: string,+ updates: { duration?: number; ease?: string; position?: number },+ ) => void;+ onDeleteGsapAnimation?: (animId: string) => void;+ onAddGsapProperty?: (animId: string, prop: string) => void;+ onRemoveGsapProperty?: (animId: string, prop: string) => void;+ onAddGsapAnimation?: (method: "to" | "from" | "set") => void;}/* ------------------------------------------------------------------ */@@ -146,6 +154,15 @@ export const PropertyPanel = memo(function PropertyPanel({onImportAssets,fontAssets = [],onImportFonts,+ gsapAnimations = [],+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ onUpdateGsapProperty,+ onUpdateGsapMeta,+ onDeleteGsapAnimation,+ onAddGsapProperty,+ onRemoveGsapProperty,+ onAddGsapAnimation,}: PropertyPanelProps) {const styles = element?.computedStyles ?? EMPTY_STYLES;@@ -186,11 +203,6 @@ export const PropertyPanel = memo(function PropertyPanel({const sourceLabel = element.id ? `#${element.id}` : element.selector;const showEditableSections = element.capabilities.canEditStyles;const manualOffset = readStudioPathOffset(element.element);- const gsapTranslate = readGsapTranslateFromTransform(element.element);- const visualOffset = {- x: manualOffset.x + gsapTranslate.x,- y: manualOffset.y + gsapTranslate.y,- };const manualSize = readStudioBoxSize(element.element);const resolvedWidth =manualSize.width > 0@@ -204,11 +216,10 @@ export const PropertyPanel = memo(function PropertyPanel({const commitManualOffset = (axis: "x" | "y", nextValue: string) => {const parsed = parsePxMetricValue(nextValue);if (parsed == null) return;- const currentRaw = readStudioPathOffset(element.element);- const currentGsap = readGsapTranslateFromTransform(element.element);+ const current = readStudioPathOffset(element.element);onSetManualOffset(element, {- x: axis === "x" ? parsed - currentGsap.x : currentRaw.x,- y: axis === "y" ? parsed - currentGsap.y : currentRaw.y,+ x: axis === "x" ? parsed : current.x,+ y: axis === "y" ? parsed : current.y,});};@@ -300,14 +311,14 @@ export const PropertyPanel = memo(function PropertyPanel({<div className={RESPONSIVE_GRID}><MetricFieldlabel="X"- value={formatPxMetricValue(visualOffset.x)}+ value={formatPxMetricValue(manualOffset.x)}disabled={manualOffsetEditingDisabled}scrubonCommit={(next) => commitManualOffset("x", next)}/><MetricFieldlabel="Y"- value={formatPxMetricValue(visualOffset.y)}+ value={formatPxMetricValue(manualOffset.y)}disabled={manualOffsetEditingDisabled}scrubonCommit={(next) => commitManualOffset("y", next)}@@ -342,6 +353,25 @@ export const PropertyPanel = memo(function PropertyPanel({</div></Section>+ {STUDIO_GSAP_PANEL_ENABLED &&+ onUpdateGsapProperty &&+ onUpdateGsapMeta &&+ onDeleteGsapAnimation &&+ onAddGsapProperty &&+ onAddGsapAnimation && (+ <GsapAnimationSection+ animations={gsapAnimations}+ multipleTimelines={gsapMultipleTimelines}+ unsupportedTimelinePattern={gsapUnsupportedTimelinePattern}+ onUpdateProperty={onUpdateGsapProperty}+ onUpdateMeta={onUpdateGsapMeta}+ onDeleteAnimation={onDeleteGsapAnimation}+ onAddProperty={onAddGsapProperty}+ onRemoveProperty={onRemoveGsapProperty ?? (() => {})}+ onAddAnimation={onAddGsapAnimation}+ />+ )}+{showEditableSections && (<StyleSectionsprojectId={projectId}diff --git a/packages/studio/src/components/editor/domEditingTypes.ts b/packages/studio/src/components/editor/domEditingTypes.tsindex 52446ed899..96f69ff8c8 100644--- a/packages/studio/src/components/editor/domEditingTypes.ts+++ b/packages/studio/src/components/editor/domEditingTypes.ts@@ -1,4 +1,5 @@import type { PatchTarget } from "../../utils/sourcePatcher";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";export const CURATED_STYLE_PROPERTIES = ["position",@@ -86,6 +87,7 @@ export interface DomEditSelection extends PatchTarget {computedStyles: Record<string, string>;textFields: DomEditTextField[];capabilities: DomEditCapabilities;+ gsapAnimations?: GsapAnimation[];}export interface DomEditLayerItem {diff --git a/packages/studio/src/components/editor/gsapAnimationConstants.ts b/packages/studio/src/components/editor/gsapAnimationConstants.tsnew file mode 100644index 0000000000..8a5e3af9e2--- /dev/null+++ b/packages/studio/src/components/editor/gsapAnimationConstants.ts@@ -0,0 +1,130 @@+import { controlPointsForGsapEase } from "./studioMotion";++export const METHOD_LABELS: Record<string, string> = {+ set: "Set",+ to: "Animate",+ from: "Animate In",+ fromTo: "Animate",+};++export const METHOD_TOOLTIPS: Record<string, string> = {+ set: "Instantly snap to these values — no transition",+ to: "Smoothly animate the element to these target values",+ from: "Element starts at these values and transitions to its normal state",+ fromTo: "Animate from one state to another",+};++export const PROP_LABELS: Record<string, string> = {+ x: "Move X",+ y: "Move Y",+ width: "Width",+ height: "Height",+ rotation: "Rotate",+ opacity: "Opacity",+ scale: "Scale",+ scaleX: "Scale X",+ scaleY: "Scale Y",+ autoAlpha: "Visibility",+ visibility: "Visible",+ scaleX_alias: "Stretch X",+};++export const PROP_UNITS: Record<string, string> = {+ x: "px",+ y: "px",+ width: "px",+ height: "px",+ rotation: "°",+ opacity: "%",+ scale: "×",+ scaleX: "×",+ scaleY: "×",+ autoAlpha: "%",+ visibility: "",+};++export const PROP_TOOLTIPS: Record<string, string> = {+ x: "Move left/right (negative = left, positive = right)",+ y: "Move up/down (negative = up, positive = down)",+ opacity: "How visible (0 = invisible, 1 = fully visible)",+ scale: "Size multiplier (1 = normal, 2 = double, 0.5 = half)",+ scaleX: "Horizontal stretch (1 = normal)",+ scaleY: "Vertical stretch (1 = normal)",+ rotation: "Spin angle (360 = full rotation)",+ width: "Element width",+ height: "Element height",+ autoAlpha: "Like opacity but hides element completely at 0",+ visibility: "Show or hide the element",+};++export const EASE_LABELS: Record<string, string> = {+ none: "Constant speed",+ "power1.out": "Gentle slowdown",+ "power2.out": "Smooth slowdown",+ "power3.out": "Snappy slowdown",+ "power4.out": "Sharp slowdown",+ "power1.in": "Gentle speedup",+ "power2.in": "Smooth speedup",+ "power3.in": "Strong speedup",+ "power4.in": "Sharp speedup",+ "power1.inOut": "Gentle ease",+ "power2.inOut": "Smooth ease",+ "power3.inOut": "Strong ease",+ "power4.inOut": "Sharp ease",+ "back.out": "Overshoot & settle",+ "back.in": "Pull back & go",+ "back.inOut": "Pull & overshoot",+ "elastic.out": "Springy bounce",+ "elastic.in": "Wind up spring",+ "elastic.inOut": "Full spring",+ "bounce.out": "Drop & bounce",+ "bounce.in": "Reverse bounce",+ "bounce.inOut": "Double bounce",+ "expo.out": "Very snappy stop",+ "expo.in": "Very slow start",+ "expo.inOut": "Dramatic ease",+};++export const EASE_CURVES: Record<string, [number, number, number, number]> = {+ none: [0, 0, 1, 1],+ "power1.out": [0, 0, 0.58, 1],+ "power2.out": [0.16, 1, 0.3, 1],+ "power3.out": [0.08, 0.82, 0.17, 1],+ "power4.out": [0.06, 0.73, 0.09, 1],+ "power1.in": [0.42, 0, 1, 1],+ "power2.in": [0.55, 0.06, 0.68, 0.19],+ "power3.in": [0.6, 0.04, 0.98, 0.34],+ "power4.in": [0.7, 0, 0.84, 0],+ "power1.inOut": [0.42, 0, 0.58, 1],+ "power2.inOut": [0.45, 0.05, 0.55, 0.95],+ "power3.inOut": [0.65, 0.05, 0.35, 1],+ "power4.inOut": [0.76, 0, 0.24, 1],+ "back.out": [0.34, 1.56, 0.64, 1],+ "back.in": [0.36, 0, 0.66, -0.56],+ "back.inOut": [0.68, -0.55, 0.27, 1.55],+ "expo.out": [0.16, 1, 0.3, 1],+ "expo.in": [0.7, 0, 0.84, 0],+ "expo.inOut": [0.87, 0, 0.13, 1],+};++export function parseCustomEaseFromString(ease: string): {+ x1: number;+ y1: number;+ x2: number;+ y2: number;+} {+ const match = ease.match(/^custom\((.+)\)$/);+ if (!match) return controlPointsForGsapEase("power2.out");+ const data = match[1];+ const nums = data.match(/[\d.]+/g)?.map(Number);+ if (!nums || nums.length < 6) return controlPointsForGsapEase("power2.out");+ return { x1: nums[2], y1: nums[3], x2: nums[4], y2: nums[5] };+}++export const ADD_METHODS = ["to", "from", "set"] as const;++export const ADD_METHOD_LABELS: Record<string, string> = {+ to: "Animate",+ from: "Animate In",+ set: "Set Instantly",+};diff --git a/packages/studio/src/components/editor/manualEditingAvailability.ts b/packages/studio/src/components/editor/manualEditingAvailability.tsindex 98057a44a2..6845956a6e 100644--- a/packages/studio/src/components/editor/manualEditingAvailability.ts+++ b/packages/studio/src/components/editor/manualEditingAvailability.ts@@ -65,6 +65,12 @@ export const STUDIO_BLOCKS_PANEL_ENABLED = resolveStudioBooleanEnvFlag(true,);+export const STUDIO_GSAP_PANEL_ENABLED = resolveStudioBooleanEnvFlag(+ env,+ ["VITE_STUDIO_ENABLE_GSAP_PANEL", "VITE_STUDIO_GSAP_PANEL_ENABLED"],+ false,+);+export const STUDIO_PREVIEW_SELECTION_ENABLED = STUDIO_INSPECTOR_PANELS_ENABLED;export const STUDIO_MANUAL_EDITING_DISABLED_TITLE = "Manual editing is temporarily disabled";diff --git a/packages/studio/src/components/editor/manualEdits.test.ts b/packages/studio/src/components/editor/manualEdits.test.tsindex 8492ef746c..12a37192d4 100644--- a/packages/studio/src/components/editor/manualEdits.test.ts+++ b/packages/studio/src/components/editor/manualEdits.test.ts@@ -516,3 +516,104 @@ describe("studio manual edits", () => {expect(frames).toHaveLength(0);});});++describe("applyStudioPathOffset sets correct attribute name", () => {+ it("sets data-hf-studio-path-offset without double data- prefix", () => {+ const window = new Window();+ const el = window.document.createElement("div");+ window.document.body.append(el);++ applyStudioPathOffset(el, { x: 100, y: 50 });++ expect(el.getAttribute("data-hf-studio-path-offset")).toBe("true");+ expect(el.getAttribute("data-data-hf-studio-path-offset")).toBeNull();+ });++ it("stores offset in CSS vars alongside the attribute marker", () => {+ const window = new Window();+ const el = window.document.createElement("div");+ window.document.body.append(el);++ applyStudioPathOffset(el, { x: 50, y: 25 });++ expect(el.getAttribute("data-hf-studio-path-offset")).toBe("true");+ expect(el.style.getPropertyValue(STUDIO_OFFSET_X_PROP)).toBe("50px");+ expect(el.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)).toBe("25px");+ expect(el.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);+ });++ it("corrects offset applied on top of legacy double-prefix element", () => {+ const window = new Window();+ const el = window.document.createElement("div");+ el.setAttribute("data-data-hf-studio-path-offset", "true");+ el.style.setProperty(STUDIO_OFFSET_X_PROP, "200px");+ el.style.setProperty(STUDIO_OFFSET_Y_PROP, "-30px");+ window.document.body.append(el);++ applyStudioPathOffset(el, { x: 200, y: -30 });++ expect(el.getAttribute("data-hf-studio-path-offset")).toBe("true");+ expect(readStudioPathOffset(el)).toEqual({ x: 200, y: -30 });+ expect(el.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);+ });+});++describe("applyStudioPathOffset strips GSAP double-counted translate", () => {+ it("strips GSAP transform translate when applying offset", () => {+ const window = new Window();+ const element = window.document.createElement("div");+ window.document.body.append(element);++ // Simulate GSAP having baked translate into the transform matrix+ element.style.setProperty("transform", "matrix(1, 0, 0, 1, 200, 0)");++ applyStudioPathOffset(element, { x: 200, y: 0 });++ // The transform translate should be stripped (GSAP's 200px removed)+ const transform = element.style.getPropertyValue("transform");+ if (transform && transform !== "none") {+ const m = new window.DOMMatrix(transform);+ expect(m.m41).toBe(0);+ expect(m.m42).toBe(0);+ }+ // The offset should be stored in CSS vars+ expect(readStudioPathOffset(element).x).toBe(200);+ });++ it("subtracts only the studio offset from GSAP transform, preserving animation values", () => {+ const window = new Window();+ const element = window.document.createElement("div");+ window.document.body.append(element);++ // GSAP has scale + baked translate (offset 50) + animation contribution (-70)+ // Total m42 = 50 + (-70) = -20+ element.style.setProperty("transform", "matrix(0.5, 0, 0, 0.5, 0, -20)");++ applyStudioPathOffset(element, { x: 0, y: 50 });++ const transform = element.style.getPropertyValue("transform");+ if (transform && transform !== "none") {+ const m = new window.DOMMatrix(transform);+ expect(m.a).toBeCloseTo(0.5);+ expect(m.d).toBeCloseTo(0.5);+ // Only the studio offset (50) is subtracted, animation contribution (-70) preserved+ expect(m.m41).toBe(0);+ expect(m.m42).toBe(-70);+ }+ expect(readStudioPathOffset(element).y).toBe(50);+ });++ it("offset survives repeated applyStudioPathOffset calls without drift", () => {+ const window = new Window();+ const element = window.document.createElement("div");+ window.document.body.append(element);++ // Apply offset 3 times with same value (simulates reapply hook firing multiple times)+ applyStudioPathOffset(element, { x: 100, y: -20 });+ applyStudioPathOffset(element, { x: 100, y: -20 });+ applyStudioPathOffset(element, { x: 100, y: -20 });++ expect(readStudioPathOffset(element).x).toBe(100);+ expect(readStudioPathOffset(element).y).toBe(-20);+ });+});diff --git a/packages/studio/src/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.tsindex fd69969d5a..05e6a81b0a 100644--- a/packages/studio/src/components/editor/manualEdits.ts+++ b/packages/studio/src/components/editor/manualEdits.ts@@ -3,9 +3,7 @@ export {STUDIO_OFFSET_X_PROP,STUDIO_OFFSET_Y_PROP,STUDIO_WIDTH_PROP,- STUDIO_HEIGHT_PROP,STUDIO_ROTATION_PROP,- type StudioManualEditSeekWindow,type StudioBoxSizeSnapshot,type StudioRotationSnapshot,type StudioPathOffsetSnapshot,@@ -20,7 +18,6 @@ export {readStudioPathOffset,readStudioBoxSize,readStudioRotation,- readGsapTranslateFromTransform,applyStudioPathOffset,applyStudioPathOffsetDraft,applyStudioBoxSize,@@ -28,8 +25,6 @@ export {applyStudioRotation,applyStudioRotationDraft,reapplyPositionEditsAfterSeek,- buildMotionPatches,- buildClearMotionPatches,} from "./manualEditsDom";export {@@ -51,7 +46,6 @@ import {STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP,} from "./manualEditsTypes";import { finiteNumber } from "./manualEditsParsing";-import { isStudioManualEditGestureActive } from "./manualEditsDom";/* ── Seek/play reapply wrappers ───────────────────────────────────── */function markWrapped(fn: (...args: unknown[]) => unknown): void {@@ -262,6 +256,28 @@ export function installStudioManualEditSeekReapply(win: Window, apply: () => voiwrapApplyAfterFunction(studioWin, timeline, "pause") || wrappedNamedTimelinePause;}+ // Auto-wrap timelines registered AFTER this install runs. GSAP compositions+ // register via `window.__timelines[id] = tl` which may happen after the+ // Studio hook runs. The Proxy intercepts new registrations and wraps+ // seek/play/pause immediately, closing the gap that causes translate doubling.+ if (studioWin.__timelines && !(studioWin.__timelines as Record<string, unknown>).__proxied) {+ const original = studioWin.__timelines;+ studioWin.__timelines = new Proxy(original, {+ set(target, prop, value) {+ target[prop as string] = value;+ if (typeof value === "object" && value !== null) {+ const tl = value as Record<string, unknown>;+ wrapSeekReapplyFunction(studioWin, tl, "seek");+ wrapPlayReapplyFunction(studioWin, tl, "play");+ wrapApplyAfterFunction(studioWin, tl, "pause");+ studioWin.__hfStudioManualEditsApply?.();+ }+ return true;+ },+ });+ (studioWin.__timelines as Record<string, unknown>).__proxied = true;+ }+if (isStudioManualEditPlaybackActive(studioWin)) {startStudioManualEditPlaybackReapply(studioWin);}@@ -280,6 +296,3 @@ export function installStudioManualEditSeekReapply(win: Window, apply: () => voiwrappedNamedTimelinePause);}--// Re-export for internal use (seek hooks need this)-export { isStudioManualEditGestureActive };diff --git a/packages/studio/src/components/editor/manualEditsDom.ts b/packages/studio/src/components/editor/manualEditsDom.tsindex f2cc838063..b08a8c5678 100644--- a/packages/studio/src/components/editor/manualEditsDom.ts+++ b/packages/studio/src/components/editor/manualEditsDom.ts@@ -48,7 +48,7 @@ export function endStudioManualEditGesture(element: HTMLElement, token?: string)element.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);}-export function isStudioManualEditGestureActive(element: HTMLElement): boolean {+function isStudioManualEditGestureActive(element: HTMLElement): boolean {return element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);}@@ -213,26 +213,15 @@ function writeStudioPathOffsetVars(// GSAP 3.x reads the resolved CSS `translate` individual property at initialization and bakes it// into element.style.transform (as a matrix) on every seek. When the studio's reapply hook also-// writes `translate`, both properties compose additively, doubling the visual offset. This helper-// zeroes out only the translate component (m41/m42) so the `translate` prop isn't double-counted.+// writes `translate`, both properties compose additively, doubling the visual offset.+//+// This helper subtracts only the baked studio offset from m41/m42, preserving any GSAP animation+// contribution (e.g. a tween animating y: -20). The studio offset is read from the CSS custom+// properties which tell us exactly how much was baked from the CSS translate.function isIdentityAfterTranslateStrip(m: DOMMatrix): boolean {return m.is2D && m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1;}-export function readGsapTranslateFromTransform(element: HTMLElement): { x: number; y: number } {- const transform = element.style.getPropertyValue("transform");- if (!transform || transform === "none") return { x: 0, y: 0 };- const DOMMatrixCtor = (element.ownerDocument.defaultView as (Window & typeof globalThis) | null)- ?.DOMMatrix;- if (!DOMMatrixCtor) return { x: 0, y: 0 };- try {- const m = new DOMMatrixCtor(transform);- return { x: m.m41, y: m.m42 };- } catch {- return { x: 0, y: 0 };- }-}-function stripGsapTranslateFromTransform(element: HTMLElement): void {const transform = element.style.getPropertyValue("transform");if (!transform || transform === "none") return;@@ -242,9 +231,11 @@ function stripGsapTranslateFromTransform(element: HTMLElement): void {try {const m = new DOMMatrixCtor(transform);if (m.m41 === 0 && m.m42 === 0) return;- m.m41 = 0;- m.m42 = 0;- if (isIdentityAfterTranslateStrip(m)) {+ const offsetX = readPxCustomProperty(element, STUDIO_OFFSET_X_PROP);+ const offsetY = readPxCustomProperty(element, STUDIO_OFFSET_Y_PROP);+ m.m41 -= offsetX;+ m.m42 -= offsetY;+ if (Math.abs(m.m41) < 0.01 && Math.abs(m.m42) < 0.01 && isIdentityAfterTranslateStrip(m)) {element.style.removeProperty("transform");} else {element.style.setProperty("transform", m.toString());@@ -493,9 +484,19 @@ export {function queryStudioElements(doc: Document, attr: string): HTMLElement[] {const ctor = doc.defaultView?.HTMLElement;if (!ctor) return [];- return Array.from(doc.querySelectorAll(`[${attr}="true"]`)).filter(+ const elements = Array.from(doc.querySelectorAll(`[${attr}="true"]`)).filter((el): el is HTMLElement => el instanceof ctor,);+ // Handle legacy HTML files where attributes were persisted with a double data- prefix+ const legacyAttr = `data-${attr}`;+ for (const el of doc.querySelectorAll(`[${legacyAttr}="true"]`)) {+ if (el instanceof ctor && !el.hasAttribute(attr)) {+ el.setAttribute(attr, "true");+ el.removeAttribute(legacyAttr);+ elements.push(el);+ }+ }+ return elements;}function reapplyPathOffsets(doc: Document): void {diff --git a/packages/studio/src/components/editor/manualOffsetDrag.test.ts b/packages/studio/src/components/editor/manualOffsetDrag.test.tsindex 48f9abffd0..2d833d04d6 100644--- a/packages/studio/src/components/editor/manualOffsetDrag.test.ts+++ b/packages/studio/src/components/editor/manualOffsetDrag.test.ts@@ -1,8 +1,10 @@import { Window } from "happy-dom";import { describe, expect, it } from "vitest";import {+ applyManualOffsetDragCommit,applyManualOffsetDragMatrix,createManualOffsetDragMember,+ endManualOffsetDragMembers,invertManualOffsetDragMatrix,measureManualOffsetDragScreenToOffsetMatrix,resolveManualOffsetForPointerDelta,@@ -140,8 +142,8 @@ describe("measureManualOffsetDragScreenToOffsetMatrix", () => {});});-describe("createManualOffsetDragMember GSAP translate compensation", () => {- it("folds GSAP translate from element.style.transform into initialOffset", () => {+describe("createManualOffsetDragMember uses raw CSS var offset", () => {+ it("ignores GSAP transform — initialOffset comes from CSS vars only", () => {const window = new Window();const element = window.document.createElement("div");window.document.body.append(element);@@ -164,14 +166,18 @@ describe("createManualOffsetDragMember GSAP translate compensation", () => {expect(result.ok).toBe(true);if (!result.ok) return;expect(result.member.initialOffset.x).toBe(0);- expect(result.member.initialOffset.y).toBe(-20);+ expect(result.member.initialOffset.y).toBe(0);});- it("leaves initialOffset unchanged when no GSAP transform is present", () => {+ it("reads only the CSS var offset, not GSAP transform", () => {const window = new Window();const element = window.document.createElement("div");window.document.body.append(element);+ element.style.setProperty(STUDIO_OFFSET_X_PROP, "30px");+ element.style.setProperty(STUDIO_OFFSET_Y_PROP, "10px");+ element.style.setProperty("transform", "translate(50px, -15px)");+element.getBoundingClientRect = () => {const offsetX = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;const offsetY = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;@@ -187,35 +193,42 @@ describe("createManualOffsetDragMember GSAP translate compensation", () => {expect(result.ok).toBe(true);if (!result.ok) return;- expect(result.member.initialOffset.x).toBe(0);- expect(result.member.initialOffset.y).toBe(0);+ expect(result.member.initialOffset.x).toBe(30);+ expect(result.member.initialOffset.y).toBe(10);});- it("combines existing manual offset with GSAP translate", () => {+ it("does not accumulate drift across multiple drag cycles", () => {const window = new Window();const element = window.document.createElement("div");window.document.body.append(element);- element.style.setProperty(STUDIO_OFFSET_X_PROP, "30px");- element.style.setProperty(STUDIO_OFFSET_Y_PROP, "10px");- element.style.setProperty("transform", "translate(50px, -15px)");-element.getBoundingClientRect = () => {const offsetX = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;const offsetY = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;return new window.DOMRect(10 + offsetX, 20 + offsetY, 100, 50);};- const result = createManualOffsetDragMember({- key: "test",- selection: { element } as never,- element,- rect: { left: 10, top: 20, width: 100, height: 50, editScaleX: 1, editScaleY: 1 },- });-- expect(result.ok).toBe(true);- if (!result.ok) return;- expect(result.member.initialOffset.x).toBe(80);- expect(result.member.initialOffset.y).toBe(-5);+ // Simulate GSAP baking a translate into transform each cycle+ for (let cycle = 0; cycle < 3; cycle++) {+ element.style.setProperty("transform", `translate(${50 * (cycle + 1)}px, 0px)`);++ const result = createManualOffsetDragMember({+ key: "test",+ selection: { element } as never,+ element,+ rect: { left: 10, top: 20, width: 100, height: 50, editScaleX: 1, editScaleY: 1 },+ });++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ // initialOffset should always be the CSS var value, never inflated by GSAP transform+ const currentRawX =+ Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;+ expect(result.member.initialOffset.x).toBe(currentRawX);++ // Simulate drag commit: apply a small offset+ applyManualOffsetDragCommit(result.member, 10, 0);+ endManualOffsetDragMembers([result.member]);+ }});});diff --git a/packages/studio/src/components/editor/manualOffsetDrag.ts b/packages/studio/src/components/editor/manualOffsetDrag.tsindex bc5827ed3c..67aae33979 100644--- a/packages/studio/src/components/editor/manualOffsetDrag.ts+++ b/packages/studio/src/components/editor/manualOffsetDrag.ts@@ -5,7 +5,6 @@ import {beginStudioManualEditGesture,captureStudioPathOffset,endStudioManualEditGesture,- readGsapTranslateFromTransform,readStudioPathOffset,restoreStudioPathOffset,type StudioPathOffsetSnapshot,@@ -232,12 +231,7 @@ export function createManualOffsetDragMember(input: {element: HTMLElement;rect: ManualOffsetDragRect;}): ManualOffsetDragMemberResult {- const rawOffset = readStudioPathOffset(input.element);- const gsapTranslate = readGsapTranslateFromTransform(input.element);- const initialOffset = {- x: rawOffset.x + gsapTranslate.x,- y: rawOffset.y + gsapTranslate.y,- };+ const initialOffset = readStudioPathOffset(input.element);const initialPathOffset = captureStudioPathOffset(input.element);const gestureToken = beginStudioManualEditGesture(input.element);const measured = measureManualOffsetDragScreenToOffsetMatrix(input.element, initialOffset);diff --git a/packages/studio/src/components/editor/propertyPanelPrimitives.tsx b/packages/studio/src/components/editor/propertyPanelPrimitives.tsxindex dc069ec082..449bad38e6 100644--- a/packages/studio/src/components/editor/propertyPanelPrimitives.tsx+++ b/packages/studio/src/components/editor/propertyPanelPrimitives.tsx@@ -103,6 +103,8 @@ export function MetricField({disabled,liveCommit,scrub,+ suffix,+ tooltip,onCommit,}: {label: string;@@ -110,6 +112,8 @@ export function MetricField({disabled?: boolean;liveCommit?: boolean;scrub?: boolean;+ suffix?: string;+ tooltip?: string;onCommit: (nextValue: string) => void;}) {const scrubRef = useRef<{ startX: number; startValue: number; pointerId: number } | null>(null);@@ -151,7 +155,7 @@ export function MetricField({: ({ className: "flex-shrink-0 text-[11px] font-medium text-neutral-500" } as const);return (- <div className={FIELD}>+ <div className={FIELD} title={tooltip}><div className="flex min-w-0 items-center gap-3"><span {...scrubProps}>{label}</span><CommitField@@ -160,6 +164,7 @@ export function MetricField({liveCommit={liveCommit}onCommit={onCommit}/>+ {suffix && <span className="flex-shrink-0 text-[10px] text-neutral-600">{suffix}</span>}</div></div>);diff --git a/packages/studio/src/contexts/DomEditContext.tsx b/packages/studio/src/contexts/DomEditContext.tsxindex 5160b26104..3774738126 100644--- a/packages/studio/src/contexts/DomEditContext.tsx+++ b/packages/studio/src/contexts/DomEditContext.tsx@@ -53,6 +53,15 @@ export function DomEditProvider({setAgentModalOpen,setAgentPromptSelectionContext,setAgentModalAnchorPoint,+ selectedGsapAnimations,+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ handleGsapUpdateProperty,+ handleGsapUpdateMeta,+ handleGsapDeleteAnimation,+ handleGsapAddAnimation,+ handleGsapAddProperty,+ handleGsapRemoveProperty,},children,}: {@@ -101,6 +110,15 @@ export function DomEditProvider({setAgentModalOpen,setAgentPromptSelectionContext,setAgentModalAnchorPoint,+ selectedGsapAnimations,+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ handleGsapUpdateProperty,+ handleGsapUpdateMeta,+ handleGsapDeleteAnimation,+ handleGsapAddAnimation,+ handleGsapAddProperty,+ handleGsapRemoveProperty,}),[domEditSelection,@@ -143,6 +161,15 @@ export function DomEditProvider({setAgentModalOpen,setAgentPromptSelectionContext,setAgentModalAnchorPoint,+ selectedGsapAnimations,+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ handleGsapUpdateProperty,+ handleGsapUpdateMeta,+ handleGsapDeleteAnimation,+ handleGsapAddAnimation,+ handleGsapAddProperty,+ handleGsapRemoveProperty,],);return <DomEditContext value={stable}>{children}</DomEditContext>;diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.tsindex 517f732bd8..11d71c9e43 100644--- a/packages/studio/src/hooks/useDomEditSession.ts+++ b/packages/studio/src/hooks/useDomEditSession.ts@@ -1,7 +1,11 @@import { useCallback, useEffect, useRef } from "react";import type { TimelineElement } from "../player";-import { STUDIO_INSPECTOR_PANELS_ENABLED } from "../components/editor/manualEditingAvailability";+import {+ STUDIO_INSPECTOR_PANELS_ENABLED,+ STUDIO_GSAP_PANEL_ENABLED,+} from "../components/editor/manualEditingAvailability";import { findElementForSelection, type DomEditSelection } from "../components/editor/domEditing";+import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";import type { ImportedFontAsset } from "../components/editor/fontAssets";import type { EditHistoryKind } from "../utils/editHistory";import type { RightPanelTab } from "../utils/studioHelpers";@@ -11,6 +15,8 @@ import { useAskAgentModal } from "./useAskAgentModal";import { useDomSelection } from "./useDomSelection";import { usePreviewInteraction } from "./usePreviewInteraction";import { useDomEditCommits } from "./useDomEditCommits";+import { useGsapScriptCommits } from "./useGsapScriptCommits";+import { useGsapAnimationsForElement, useGsapCacheVersion } from "./useGsapTweenCache";// ── Types ──@@ -185,6 +191,37 @@ export function useDomEditSession({onClickToSource,});+ // ── GSAP script editing ──++ const { version: gsapCacheVersion, bump: bumpGsapCache } = useGsapCacheVersion();++ const {+ animations: selectedGsapAnimations,+ multipleTimelines: gsapMultipleTimelines,+ unsupportedTimelinePattern: gsapUnsupportedTimelinePattern,+ } = useGsapAnimationsForElement(+ STUDIO_GSAP_PANEL_ENABLED ? (projectId ?? null) : null,+ domEditSelection?.sourceFile || activeCompPath || "index.html",+ domEditSelection?.id ?? null,+ gsapCacheVersion,+ );++ const {+ updateGsapProperty,+ updateGsapMeta,+ deleteGsapAnimation,+ addGsapAnimation,+ addGsapProperty,+ removeGsapProperty,+ } = useGsapScriptCommits({+ projectIdRef,+ activeCompPath,+ editHistory,+ domEditSaveTimestampRef,+ reloadPreview,+ onCacheInvalidate: bumpGsapCache,+ });+// ── Commit handlers (delegated to useDomEditCommits) ──const {@@ -224,7 +261,53 @@ export function useDomEditSession({buildDomSelectionFromTarget,});- // ── Effects ──+ const handleGsapUpdateProperty = useCallback(+ (animId: string, prop: string, value: number | string) => {+ if (!domEditSelection) return;+ updateGsapProperty(domEditSelection, animId, prop, value);+ },+ [domEditSelection, updateGsapProperty],+ );++ const handleGsapUpdateMeta = useCallback(+ (animId: string, updates: { duration?: number; ease?: string; position?: number }) => {+ if (!domEditSelection) return;+ updateGsapMeta(domEditSelection, animId, updates);+ },+ [domEditSelection, updateGsapMeta],+ );++ const handleGsapDeleteAnimation = useCallback(+ (animId: string) => {+ if (!domEditSelection) return;+ deleteGsapAnimation(domEditSelection, animId);+ },+ [domEditSelection, deleteGsapAnimation],+ );++ const handleGsapAddAnimation = useCallback(+ (method: "to" | "from" | "set") => {+ if (!domEditSelection) return;+ addGsapAnimation(domEditSelection, method, currentTime);+ },+ [domEditSelection, addGsapAnimation, currentTime],+ );++ const handleGsapAddProperty = useCallback(+ (animId: string, prop: string) => {+ if (!domEditSelection) return;+ addGsapProperty(domEditSelection, animId, prop);+ },+ [domEditSelection, addGsapProperty],+ );++ const handleGsapRemoveProperty = useCallback(+ (animId: string, prop: string) => {+ if (!domEditSelection) return;+ removeGsapProperty(domEditSelection, animId, prop);+ },+ [domEditSelection, removeGsapProperty],+ );// Sync selection from preview document on load / refresh// eslint-disable-next-line no-restricted-syntax@@ -243,6 +326,8 @@ export function useDomEditSession({}if (!doc) return;+ reapplyPositionEditsAfterSeek(doc);+const nextElement = findElementForSelection(doc, currentSelection, activeCompPath);if (!nextElement) {applyDomSelection(null, { revealPanel: false });@@ -345,5 +430,16 @@ export function useDomEditSession({setAgentModalOpen,setAgentPromptSelectionContext,setAgentModalAnchorPoint,++ // GSAP script editing+ selectedGsapAnimations,+ gsapMultipleTimelines,+ gsapUnsupportedTimelinePattern,+ handleGsapUpdateProperty,+ handleGsapUpdateMeta,+ handleGsapDeleteAnimation,+ handleGsapAddAnimation,+ handleGsapAddProperty,+ handleGsapRemoveProperty,};}diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.tsindex c58670be0e..0eba293ce6 100644--- a/packages/studio/src/hooks/useDomSelection.ts+++ b/packages/studio/src/hooks/useDomSelection.ts@@ -16,6 +16,7 @@ import {resolveDomEditSelection,type DomEditSelection,} from "../components/editor/domEditing";+import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";// ── Types ──@@ -218,6 +219,11 @@ export function useDomSelection({) => {const iframe = previewIframeRef.current;if (!iframe || captionEditMode) return null;+ try {+ if (iframe.contentDocument) reapplyPositionEditsAfterSeek(iframe.contentDocument);+ } catch {+ /* cross-origin guard */+ }const target = getPreviewTargetFromPointer(iframe, clientX, clientY, activeCompPath);if (!target) return null;return buildDomSelectionFromTarget(target, {@@ -245,6 +251,8 @@ export function useDomSelection({}if (!doc) return null;+ reapplyPositionEditsAfterSeek(doc);+const targetElement = findElementForTimelineElement(doc, element, {activeCompositionPath: activeCompPath,compIdToSrc,diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.tsnew file mode 100644index 0000000000..d2d206c028--- /dev/null+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts@@ -0,0 +1,303 @@+import { useCallback, useEffect, useRef } from "react";+import type { ParsedGsap } from "@hyperframes/core/gsap-parser";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import type { EditHistoryKind } from "../utils/editHistory";++const PROPERTY_DEFAULTS: Record<string, number> = {+ opacity: 1,+ x: 0,+ y: 0,+ scale: 1,+ scaleX: 1,+ scaleY: 1,+ rotation: 0,+ width: 100,+ height: 100,+};++/**+ * Ensures the element has an id so it can be targeted by a GSAP selector.+ * If the element already has an id or a CSS selector, returns those.+ * Otherwise mints a unique id and sets it on the live element.+ */+function ensureElementAddressable(selection: DomEditSelection): {+ selector: string;+ autoId?: string;+} {+ if (selection.id) return { selector: `#${selection.id}` };+ if (selection.selector) return { selector: selection.selector };++ const el = selection.element;+ const doc = el.ownerDocument;+ const tag = el.tagName.toLowerCase();+ let id = tag;+ let n = 1;+ while (doc.getElementById(id)) {+ n += 1;+ id = `${tag}-${n}`;+ }+ el.setAttribute("id", id);+ return { selector: `#${id}`, autoId: id };+}++interface MutationResult {+ ok: boolean;+ parsed?: ParsedGsap;+ before?: string;+ after?: string;+}++async function mutateGsapScript(+ projectId: string,+ sourceFile: string,+ mutation: Record<string, unknown>,+): Promise<MutationResult | null> {+ try {+ const res = await fetch(+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(sourceFile)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(mutation),+ },+ );+ if (!res.ok) return null;+ return (await res.json()) as MutationResult;+ } catch {+ return null;+ }+}++interface GsapScriptCommitsParams {+ projectIdRef: React.MutableRefObject<string | null>;+ activeCompPath: string | null;+ editHistory: {+ recordEdit: (entry: {+ label: string;+ kind: EditHistoryKind;+ coalesceKey?: string;+ files: Record<string, { before: string; after: string }>;+ }) => Promise<void>;+ };+ domEditSaveTimestampRef: React.MutableRefObject<number>;+ reloadPreview: () => void;+ onCacheInvalidate: () => void;+}++const DEBOUNCE_MS = 150;++// fallow-ignore-next-line complexity unit-size+export function useGsapScriptCommits({+ projectIdRef,+ activeCompPath,+ editHistory,+ domEditSaveTimestampRef,+ reloadPreview,+ onCacheInvalidate,+}: GsapScriptCommitsParams) {+ const pendingPropertyEditRef = useRef<{+ selection: DomEditSelection;+ animationId: string;+ property: string;+ value: number | string;+ } | null>(null);+ const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ /** Send a mutation and record the edit in undo history. */+ const commitMutation = useCallback(+ async (+ selection: DomEditSelection,+ mutation: Record<string, unknown>,+ options: { label: string; coalesceKey?: string; softReload?: boolean },+ ) => {+ const pid = projectIdRef.current;+ if (!pid) return;+ const targetPath = selection.sourceFile || activeCompPath || "index.html";++ const result = await mutateGsapScript(pid, targetPath, mutation);+ if (!result?.ok) return;++ domEditSaveTimestampRef.current = Date.now();++ if (result.before != null && result.after != null) {+ await editHistory.recordEdit({+ label: options.label,+ kind: "manual",+ coalesceKey: options.coalesceKey,+ files: { [targetPath]: { before: result.before, after: result.after } },+ });+ }++ onCacheInvalidate();++ if (!options.softReload) {+ reloadPreview();+ }+ },+ [+ projectIdRef,+ activeCompPath,+ editHistory,+ domEditSaveTimestampRef,+ reloadPreview,+ onCacheInvalidate,+ ],+ );++ const flushPendingPropertyEdit = useCallback(() => {+ const pending = pendingPropertyEditRef.current;+ if (!pending) return;+ pendingPropertyEditRef.current = null;+ const { selection, animationId, property, value } = pending;+ void commitMutation(+ selection,+ { type: "update-property", animationId, property, value },+ {+ label: `Edit GSAP ${property}`,+ coalesceKey: `gsap:${animationId}:${property}`,+ },+ );+ }, [commitMutation]);++ const updateGsapProperty = useCallback(+ (+ selection: DomEditSelection,+ animationId: string,+ property: string,+ value: number | string,+ ) => {+ pendingPropertyEditRef.current = { selection, animationId, property, value };+ if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);+ debounceTimerRef.current = setTimeout(flushPendingPropertyEdit, DEBOUNCE_MS);+ },+ [flushPendingPropertyEdit],+ );++ useEffect(() => {+ return () => {+ if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);+ flushPendingPropertyEdit();+ };+ }, [flushPendingPropertyEdit]);++ const updateGsapMeta = useCallback(+ (+ selection: DomEditSelection,+ animationId: string,+ updates: { duration?: number; ease?: string; position?: number },+ ) => {+ void commitMutation(+ selection,+ { type: "update-meta", animationId, updates },+ {+ label: "Edit GSAP animation",+ coalesceKey: `gsap:${animationId}:meta`,+ },+ );+ },+ [commitMutation],+ );++ const deleteGsapAnimation = useCallback(+ (selection: DomEditSelection, animationId: string) => {+ void commitMutation(+ selection,+ { type: "delete", animationId },+ { label: "Delete GSAP animation" },+ );+ },+ [commitMutation],+ );++ const addGsapAnimation = useCallback(+ async (selection: DomEditSelection, method: "to" | "from" | "set", currentTime?: number) => {+ const { selector, autoId } = ensureElementAddressable(selection);++ if (autoId) {+ const pid = projectIdRef.current;+ const targetPath = selection.sourceFile || activeCompPath || "index.html";+ if (!pid) return;+ const res = await fetch(+ `/api/projects/${encodeURIComponent(pid)}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ target: {+ id: selection.id,+ selector: selection.selector,+ selectorIndex: selection.selectorIndex,+ },+ operations: [{ type: "html-attribute", property: "id", value: autoId }],+ }),+ },+ );+ if (!res.ok) return;+ const data = (await res.json()) as { changed?: boolean };+ if (!data.changed) return;+ }++ const start = currentTime ?? (Number.parseFloat(selection.dataAttributes.start ?? "0") || 0);+ const defaults: Record<string, Record<string, number>> = {+ from: { opacity: 0 },+ to: { opacity: 1 },+ set: { opacity: 1 },+ };++ await commitMutation(+ selection,+ {+ type: "add",+ targetSelector: selector,+ method,+ position: start,+ duration: method === "set" ? undefined : 0.5,+ ease: method === "set" ? undefined : "power2.out",+ properties: defaults[method] ?? { opacity: 1 },+ },+ { label: `Add GSAP ${method} animation` },+ );+ },+ [commitMutation, projectIdRef, activeCompPath],+ );++ const addGsapProperty = useCallback(+ (selection: DomEditSelection, animationId: string, property: string) => {+ let defaultValue = PROPERTY_DEFAULTS[property] ?? 0;+ const el = selection.element;+ if (property === "width" || property === "height") {+ const rect = el.getBoundingClientRect();+ defaultValue = Math.round(property === "width" ? rect.width : rect.height);+ } else if (property === "opacity" || property === "autoAlpha") {+ const cs = el.ownerDocument.defaultView?.getComputedStyle(el);+ defaultValue = cs ? Number.parseFloat(cs.opacity) || 1 : 1;+ }+ void commitMutation(+ selection,+ { type: "add-property", animationId, property, defaultValue },+ { label: `Add GSAP ${property}` },+ );+ },+ [commitMutation],+ );++ const removeGsapProperty = useCallback(+ (selection: DomEditSelection, animationId: string, property: string) => {+ void commitMutation(+ selection,+ { type: "remove-property", animationId, property },+ { label: `Remove GSAP ${property}` },+ );+ },+ [commitMutation],+ );++ return {+ updateGsapProperty,+ updateGsapMeta,+ deleteGsapAnimation,+ addGsapAnimation,+ addGsapProperty,+ removeGsapProperty,+ };+}diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.tsnew file mode 100644index 0000000000..f26d21717d--- /dev/null+++ b/packages/studio/src/hooks/useGsapTweenCache.ts@@ -0,0 +1,80 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";++function getAnimationsForElement(animations: GsapAnimation[], elementId: string): GsapAnimation[] {+ return animations.filter((a) => a.targetSelector === `#${elementId}`);+}++async function fetchParsedAnimations(+ projectId: string,+ sourceFile: string,+): Promise<ParsedGsap | null> {+ try {+ const res = await fetch(+ `/api/projects/${encodeURIComponent(projectId)}/gsap-animations/${encodeURIComponent(sourceFile)}`,+ );+ return res.ok ? ((await res.json()) as ParsedGsap) : null;+ } catch {+ return null;+ }+}++export function useGsapAnimationsForElement(+ projectId: string | null,+ sourceFile: string,+ elementId: string | null,+ version: number,+): {+ animations: GsapAnimation[];+ multipleTimelines: boolean;+ unsupportedTimelinePattern: boolean;+} {+ const [allAnimations, setAllAnimations] = useState<GsapAnimation[]>([]);+ const [multipleTimelines, setMultipleTimelines] = useState(false);+ const [unsupportedTimelinePattern, setUnsupportedTimelinePattern] = useState(false);+ const lastFetchKeyRef = useRef("");++ useEffect(() => {+ const fetchKey = `${projectId}:${sourceFile}:${version}`;+ if (fetchKey === lastFetchKeyRef.current) return;+ lastFetchKeyRef.current = fetchKey;++ if (!projectId) {+ setAllAnimations([]);+ setMultipleTimelines(false);+ setUnsupportedTimelinePattern(false);+ return;+ }++ let cancelled = false;+ fetchParsedAnimations(projectId, sourceFile).then((parsed) => {+ if (cancelled) return;+ if (!parsed) {+ setAllAnimations([]);+ setMultipleTimelines(false);+ setUnsupportedTimelinePattern(false);+ return;+ }+ setAllAnimations(parsed.animations);+ setMultipleTimelines(parsed.multipleTimelines === true);+ setUnsupportedTimelinePattern(parsed.unsupportedTimelinePattern === true);+ });++ return () => {+ cancelled = true;+ };+ }, [projectId, sourceFile, version]);++ const animations = useMemo(+ () => (elementId ? getAnimationsForElement(allAnimations, elementId) : []),+ [allAnimations, elementId],+ );++ return { animations, multipleTimelines, unsupportedTimelinePattern };+}++export function useGsapCacheVersion() {+ const [version, setVersion] = useState(0);+ const bump = useCallback(() => setVersion((v) => v + 1), []);+ return { version, bump };+}diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.tsindex eab2d755d4..2ebe73a676 100644--- a/packages/studio/src/hooks/usePreviewPersistence.ts+++ b/packages/studio/src/hooks/usePreviewPersistence.ts@@ -102,6 +102,7 @@ export function usePreviewPersistence({}if (d) reapplyPositionEditsAfterSeek(d);};+const install = () => {reapply();if (iframe.contentWindow) installStudioManualEditSeekReapply(iframe.contentWindow, reapply);diff --git a/packages/studio/tests/e2e/helpers.sh b/packages/studio/tests/e2e/helpers.shnew file mode 100644index 0000000000..d1eefbc1b4--- /dev/null+++ b/packages/studio/tests/e2e/helpers.sh@@ -0,0 +1,88 @@+#!/bin/bash+# E2E test helpers for agent-browser that work reliably with React components.+# Uses JS-based clicks (element.click()) instead of pointer events to avoid+# stale ref issues after iframe reloads.++# Click a button by its exact text content+click_button() {+ local text="$1"+ agent-browser eval --stdin <<EVALEOF+(function() {+ var btns = document.querySelectorAll('button');+ for (var i = 0; i < btns.length; i++) {+ if (btns[i].textContent.trim() === '${text}') {+ btns[i].click();+ return 'clicked: ${text}';+ }+ }+ return 'not found: ${text}';+})()+EVALEOF+}++# Click a button whose text contains a substring+click_button_contains() {+ local text="$1"+ agent-browser eval --stdin <<EVALEOF+(function() {+ var btns = document.querySelectorAll('button');+ for (var i = 0; i < btns.length; i++) {+ if (btns[i].textContent.includes('${text}')) {+ btns[i].click();+ return 'clicked: ' + btns[i].textContent.trim().substring(0, 60);+ }+ }+ return 'not found: ${text}';+})()+EVALEOF+}++# Set an input value by label text and commit via Enter+set_input() {+ local label="$1"+ local value="$2"+ agent-browser eval --stdin <<EVALEOF+(function() {+ var labels = document.querySelectorAll('label, span');+ for (var i = 0; i < labels.length; i++) {+ if (labels[i].textContent.trim() === '${label}') {+ var input = labels[i].closest('[class]')?.querySelector('input');+ if (!input) continue;+ var nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;+ nativeSetter.call(input, '${value}');+ input.dispatchEvent(new Event('input', {bubbles: true}));+ input.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter', code: 'Enter', bubbles: true}));+ return 'set ${label} = ${value}';+ }+ }+ return 'not found: ${label}';+})()+EVALEOF+}++# Select from a combobox/select by label and option value+select_option() {+ local label="$1"+ local value="$2"+ agent-browser eval --stdin <<EVALEOF+(function() {+ var selects = document.querySelectorAll('select');+ for (var i = 0; i < selects.length; i++) {+ var lbl = selects[i].closest('[class]')?.querySelector('label, span');+ if (lbl && lbl.textContent.trim() === '${label}') {+ selects[i].value = '${value}';+ selects[i].dispatchEvent(new Event('change', {bubbles: true}));+ return 'selected ${label} = ${value}';+ }+ }+ return 'not found: ${label}';+})()+EVALEOF+}++# Wait for text to appear in the page+wait_for_text() {+ local text="$1"+ local timeout="${2:-10000}"+ agent-browser wait --text "${text}" --timeout "${timeout}" 2>/dev/null || echo "timeout waiting for: ${text}"+}diff --git a/packages/studio/vite.adapter.ts b/packages/studio/vite.adapter.tsindex 9d095d0ce5..f227e3baff 100644--- a/packages/studio/vite.adapter.ts+++ b/packages/studio/vite.adapter.ts@@ -184,7 +184,7 @@ export function createViteAdapter(dataDir: string, server: ViteDevServer): Studiasync lint(html: string, opts?: { filePath?: string }) {const mod = await server.ssrLoadModule("@hyperframes/core/lint");- return mod.lintHyperframeHtml(html, opts);+ return await mod.lintHyperframeHtml(html, opts);},runtimeUrl: "/api/runtime.js",diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.tsindex 85a8c5e4bc..57713807f4 100644--- a/packages/studio/vite.config.ts+++ b/packages/studio/vite.config.ts@@ -181,4 +181,13 @@ export default defineConfig({server: {port: 5190,},+ ssr: {+ // recast / @babel/parser are CommonJS and call `require("fs")`. They are+ // reachable only server-side via the Node-only `@hyperframes/core/gsap-parser`+ // subpath (studio-api GSAP mutations + the linter), which the dev server loads+ // through Vite SSR. Externalizing them makes SSR load the native Node modules+ // instead of esbuild-transforming the `require` into a shim that throws+ // "Dynamic require of fs is not supported". Browser bundles never reach them.+ external: ["recast", "@babel/parser", "ast-types"],+ },});