fix: harden docs snippets, SVG sanitizer, lint regexes, GSAP writers and registry pins (#7512)

* fix(docs): escape catalog preview values and the install command's --vars argument

The catalog preview embeds variable values as JSON that cannot close a
script element or attribute, accepts value messages only from the page
that embeds it, and reads only declared ids with primitive values from
the link. The install command shell-quotes its --vars JSON and keeps
only variable-id keys with primitive values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(core): fold CSS line endings before decoding escapes in the SVG sanitizer

A browser folds CR LF, CR and form feed into one newline before it reads
CSS escapes, so the whitespace after a hex escape can be a CR LF pair.
The sanitizer now does the same, so an escaped function name split by a
line ending is checked under its real name. The media-use bundle is
regenerated from the source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(lint): match template ids and CSS rules in linear time

A getElementById template literal is matched against document ids with
an in-order indexOf scan instead of a regex of joined wildcards, so the
time no longer grows with the number of placeholders. The CSS rule
scanners only start a match at the beginning of a brace-free run, which
finds the same rules without rescanning long brace-less text. Lint
results on every HTML file in the repository are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(parsers): keep GSAP writer output inside its script element

String literals and quoted keys the GSAP writers emit now encode a
script closer or comment opener as \u003c, so a value can no longer end
the inline script that holds the timeline. Strings without those
sequences are written exactly as before. The writers also refuse a tween
method outside set, to, from and fromTo, and a motion path whose
coordinates or curviness are not numbers, since both are emitted as code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(scripts): confine registry asset hosting to files inside the item

The asset hosting script now refuses a manifest path that leaves the
item directory or reaches its file through a symlink, before anything is
read, staged, uploaded or removed. A repository test fails when the
registry tracks a symlink or a manifest path that leaves its item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(registry): pin the map blocks' d3 and atlas files to exact versions

The five map blocks load d3 7.9.2, the build the d3@7 range serves today,
with a subresource integrity hash, and fetch us-atlas 3.0.1 and
world-atlas 2.0.2, the files their ranges serve today. The bytes are
unchanged, so the blocks render the same. A repository test fails when a
registry item names an npm CDN package by range, tag or no version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(registry): pin map blocks to d3 7.9.0

7.9.0 has been the stable release since 2024; 7.9.1 and 7.9.2 were published days ago. Pin the
long-standing version, with its subresource integrity hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(registry): keep the map block PR source-only and formatted

Restore the generated catalog pages and payloads, which the catalog
publish job regenerates from the item sources. Name the us-atlas URL
in us-map-flow so the call fits on one line and formatting is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(scripts): check registry asset containment with one prefix test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(lint): scan simple CSS rules in linear time

The two CSS-rule scans in the gsap rules took a body that could cross
'{', so a closed style of many '{' with no '}' rescanned to its end from
every brace. A scanner now returns the same selector and body pairs and
remembers the next '}', so each scan is linear. Findings are identical
on every tracked HTML file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(core): label the form-feed sanitizer case as a guard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michael Wang
2026-11-10 20:01:29 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 84c7d02a19
commit 24508ce2da
22 changed files with 583 additions and 93 deletions
+29 -9
View File
@@ -1710,6 +1710,27 @@ export const CatalogDetail = ({
*/
const urlKey = `vars-${compositionId}`;
// >>> preview values
/** JSON that is also inert inside an inline `<script>` and a single-quoted attribute. */
function scriptJson(value) {
return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, function (c) {
return "\\u" + ("000" + c.charCodeAt(0).toString(16)).slice(-4);
});
}
/** The entries of a parsed query object that name a declared id and hold a primitive value. */
function declaredValues(parsed, ids) {
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
return Object.fromEntries(
Object.entries(parsed).filter(([id, value]) => {
if (!ids.has(id)) return false;
if (typeof value === "number") return Number.isFinite(value);
return typeof value === "string" || typeof value === "boolean";
}),
);
}
// <<< preview values
const readFromUrl = () => {
if (typeof window === "undefined") return {};
try {
@@ -1718,11 +1739,8 @@ export const CatalogDetail = ({
// `URLSearchParams` has already decoded this once. Decoding again turned
// a path full of percent-escapes into something that no longer parsed,
// and doubled the length of every link.
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
// Only ids this item declares; a stale link must not inject stray keys.
const declared = new Set(variables.map((v) => v.id));
return Object.fromEntries(Object.entries(parsed).filter(([id]) => declared.has(id)));
return declaredValues(JSON.parse(raw), new Set(variables.map((v) => v.id)));
} catch {
return {};
}
@@ -1815,12 +1833,13 @@ export const CatalogDetail = ({
"script>",
"</head><body><script>",
"(function(){",
` var PAYLOAD = ${JSON.stringify(previewSrc)};`,
` var PAYLOAD = ${scriptJson(previewSrc)};`,
// The frame mounts with whatever a shared link asked for, not the bare
// defaults. Posting the values afterwards is too late for anything the
// composition reads once at init — a path arrives, the mark is already
// drawn from the default one, and only a later edit corrects it.
` var INITIAL = ${JSON.stringify({ ...defaults, ...readFromUrl() })};`,
` var INITIAL = ${scriptJson({ ...defaults, ...readFromUrl() })};`,
` var scriptJson = ${scriptJson.toString()};`,
" var html = null, player = null, poll = null;",
// Two ways in, because a composition can be either shape. A top-level one
// reads overrides off `window.__hfVariables`; one mounted through
@@ -1828,13 +1847,13 @@ export const CatalogDetail = ({
// which the loader reads before the sub-composition runs — so that has to
// be in the markup, not assigned afterwards.
" function withValues(source, values) {",
" var json = JSON.stringify(values);",
" var json = scriptJson(values);",
" var attr = json.replace(/'/g, '&#39;');",
" var out = source.replace(/\\sdata-variable-values=(?:\"[^\"]*\"|'[^']*')/gi, '');",
" out = out.replace(/(data-composition-src=)/gi, \"data-variable-values='\" + attr + \"' $1\");",
" out = out.replace(/data-composition-src=/gi, function (m) { return \"data-variable-values='\" + attr + \"' \" + m; });",
" var tag = '<' + 'script>window.__hfVariables=' + json + ';<' + '/script>';",
" return /<head[^>]*>/i.test(out)",
" ? out.replace(/<head([^>]*)>/i, '<head$1>' + tag)",
" ? out.replace(/<head[^>]*>/i, function (m) { return m + tag; })",
" : tag + out;",
" }",
// The composition reads its variables once, at init, so a new value can
@@ -1870,6 +1889,7 @@ export const CatalogDetail = ({
" document.body.innerHTML = '<pre style=\"color:#f66;font:12px monospace;padding:12px\">preview unavailable: ' + e + '</pre>';",
" });",
" addEventListener('message', function (event) {",
" if (event.source !== parent || event.origin !== self.origin) return;",
" var values = event.data && event.data.hfVariables;",
" if (!values) return;",
" mount(values, player.currentTime || 0);",
+22 -6
View File
@@ -42,14 +42,30 @@ export const InstallCommand = ({ command, item }) => {
React.useEffect(() => {
if (!item) return;
// >>> vars argument
/**
* The ` --vars '<json>'` suffix for a query value, or "" when nothing usable is in it.
*
* Keeps variable-id keys with string, finite number or boolean values, and
* escapes `'` so the JSON stays one shell argument.
*/
function varsArgument(raw) {
if (!raw) return "";
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "";
const kept = Object.entries(parsed).filter(([id, value]) => {
if (!/^[A-Za-z_][\w-]*$/.test(id)) return false;
if (typeof value === "number") return Number.isFinite(value);
return typeof value === "string" || typeof value === "boolean";
});
if (kept.length === 0) return "";
return ` --vars '${JSON.stringify(Object.fromEntries(kept)).replace(/'/g, "'\\''")}'`;
}
// <<< vars argument
const read = () => {
try {
const raw = new URLSearchParams(window.location.search).get(`vars-${item}`);
if (!raw) return setTuned("");
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return setTuned("");
if (Object.keys(parsed).length === 0) return setTuned("");
setTuned(` --vars '${JSON.stringify(parsed)}'`);
setTuned(varsArgument(new URLSearchParams(window.location.search).get(`vars-${item}`)));
} catch {
// A hand-edited link should leave the plain command, not break it.
setTuned("");
+1 -1
View File
@@ -54,7 +54,7 @@
"player:perf": "bun run --filter @hyperframes/player perf",
"format:check": "oxfmt --check .",
"knip": "knip",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/motion-blur-nightly-report.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs registry/examples/path-traced-3d/source/path-traced-3d.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/registry-cdn-pins.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/motion-blur-nightly-report.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs registry/examples/path-traced-3d/source/path-traced-3d.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json",
"test:skills": "HYPERFRAMES_MEDIA_HOME_REQUIRED=1 node --import ./packages/cli/scripts/test-home.mjs --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'",
"generate:previews": "tsx scripts/generate-template-previews.ts",
File diff suppressed because one or more lines are too long
@@ -54,6 +54,21 @@ const HOSTILE_CASES: Array<[label: string, input: string, mustNotContain: string
`<svg><style>svg{background-image:image-set("https://evil.example/b" 1x)}</style></svg>`,
["evil.example"],
],
[
"CSS-escaped image-set() followed by CR LF in a style element",
`<svg><style>.a{background:image-se\\74\r\n('https://evil.example/b' 1x)}</style></svg>`,
["evil.example"],
],
[
"CSS-escaped image-set() followed by CR LF in style=",
`<svg><rect style="background:image-se\\74\r\n('https://evil.example/b' 1x)"/></svg>`,
["evil.example"],
],
[
"CSS-escaped url() followed by a form feed in a presentation attribute (guards the line-ending fold, not a base bypass)",
`<svg><rect fill="\\75\frl(https://evil.example/b)"/></svg>`,
["evil.example"],
],
[
"CSS-escaped image-set() in style=",
String.raw`<svg><rect style="background:\69mage-set('https://evil.example/b' 1x)"/></svg>`,
+4 -5
View File
@@ -287,13 +287,12 @@ function decodeCssEscape(hex: string | undefined, char: string | undefined): str
return invalid ? "�" : String.fromCodePoint(cp);
}
// A browser reads `\75 rl(` as `url(`, so every check runs on escape-decoded, lowercased text.
// Comments stay in: CSS never lets one join a function name or `@import`, only split tokens.
// A browser folds CR LF, CR and FF to one newline, then reads `\75 rl(` as `url(`, so every check
// runs on that decoded, lowercased text. Comments stay in: CSS never lets one join a function name.
function canonicalCss(text: string): string {
return text
.replace(/\\([0-9a-f]{1,6})[ \t\n\r\f]?|\\([\s\S])/gi, (_, hex, char) =>
decodeCssEscape(hex, char),
)
.replace(/\r\n?|\f/g, "\n")
.replace(/\\([0-9a-f]{1,6})[ \t\n]?|\\([\s\S])/gi, (_, hex, char) => decodeCssEscape(hex, char))
.toLowerCase();
}
+4 -4
View File
@@ -167,7 +167,7 @@ function climbsAboveRoot(fileDepth: number, path: string): boolean {
function extractCssSelectors(css: string): string[] {
const out: string[] = [];
const noComments = css.replace(/\/\*[\s\S]*?\*\//g, "");
const ruleHeader = /([^{}]+)\{/g;
const ruleHeader = /(?<![^{}])([^{}]+)\{/g;
let m: RegExpExecArray | null;
while ((m = ruleHeader.exec(noComments)) !== null) {
const header = (m[1] ?? "").trim();
@@ -209,7 +209,7 @@ function collectHeavyOverlayHooks(styles: ExtractedBlock[]): {
const ids = new Set<string>();
for (const style of styles) {
const noComments = style.content.replace(/\/\*[\s\S]*?\*\//g, "");
const ruleWithBody = /([^{}]+)\{([^{}]*)\}/g;
const ruleWithBody = /(?<![^{}])([^{}]+)\{([^{}]*)\}/g;
let m: RegExpExecArray | null;
while ((m = ruleWithBody.exec(noComments)) !== null) {
const header = (m[1] ?? "").trim();
@@ -556,7 +556,7 @@ function stylesheetCanvasZoomHits(
): CanvasZoomHit[] {
const hits: CanvasZoomHit[] = [];
for (const style of styles) {
const ruleWithBody = /([^{}]+)\{([^{}]*)\}/g;
const ruleWithBody = /(?<![^{}])([^{}]+)\{([^{}]*)\}/g;
const content = stripCssComments(style.content);
// At-rules and style attributes can restrict selector applicability.
const allowNewHits = style.attrs.trim() === "" && !content.includes("@");
@@ -787,7 +787,7 @@ function stackingContextSelectors(styles: readonly ExtractedBlock[]): Set<string
const selectors = new Set<string>();
for (const style of styles) {
const content = stripCssComments(style.content);
const rule = /([^{}]+)\{([^{}]*)\}/g;
const rule = /(?<![^{}])([^{}]+)\{([^{}]*)\}/g;
let match: RegExpExecArray | null;
while ((match = rule.exec(content)) !== null) {
if (!STACKING_CONTEXT_DECLARATION.test(match[2] ?? "")) continue;
+61
View File
@@ -3153,6 +3153,67 @@ describe("SVG draw-on rules", () => {
expect(finding).toBeUndefined();
});
it("svg_drawon_css_dasharray_conflict: resolves a template id with a literal segment to the matching element", async () => {
const html = `
<html><body>
<style>.wire-b { stroke-dasharray: 10 10; }</style>
<div data-composition-id="b" data-width="1920" data-height="1080">
<svg><path id="line-b" class="wire-b" d="M 0 0 L 100 100"/></svg>
</div>
<script>
window.__timelines = window.__timelines || {};
const tl = gsap.timeline({ paused: true });
const name = "b";
const target = document.getElementById(\`line-\${name}\`);
tl.set(target, { strokeDasharray: 141.4, strokeDashoffset: 141.4 }, 0);
window.__timelines["b"] = tl;
</script>
</body></html>`;
const result = await lintHyperframeHtml(html);
const finding = result.findings.find((f) => f.code === "svg_drawon_css_dasharray_conflict");
expect(finding).toBeDefined();
});
it("matches a many-placeholder template id against a long near-miss id in linear time", async () => {
const template = Array.from({ length: 40 }, () => "${x}").join("a") + "b";
const html = `
<html><body>
<div data-composition-id="c1" data-width="1920" data-height="1080">
<svg><path id="${"a".repeat(5000)}c" d="M 0 0 L 1 1"/></svg>
</div>
<script>
window.__timelines = window.__timelines || {};
const el = document.getElementById(\`${template}\`);
const tl = gsap.timeline({ paused: true });
tl.set(el, { strokeDasharray: 1 }, 0);
window.__timelines["c1"] = tl;
</script>
</body></html>`;
const started = performance.now();
await lintHyperframeHtml(html);
expect(performance.now() - started).toBeLessThan(2000);
});
it("scans a long style block with no braces in linear time", async () => {
const html = `<html><body>
<div data-composition-id="c1" data-width="1920" data-height="1080"></div>
<style>${"a ".repeat(40000)}</style>
</body></html>`;
const started = performance.now();
await lintHyperframeHtml(html);
expect(performance.now() - started).toBeLessThan(3000);
});
it("scans a closed style block of many unclosed rules in linear time", async () => {
const html = `<html><body>
<div data-composition-id="c1" data-width="1920" data-height="1080"></div>
<style>${"x{".repeat(40000)}</style>
</body></html>`;
const started = performance.now();
await lintHyperframeHtml(html);
expect(performance.now() - started).toBeLessThan(2000);
});
// ── gsap_timeline_set_initial_hide ─────────────────────────────────────────
it("gsap_timeline_set_initial_hide: warns on tl.set hidden state at position 0", async () => {
+47 -4
View File
@@ -420,10 +420,35 @@ function styleLooksFullFrameOverlay(style: string): boolean {
return coversFrame && styleHasOpaqueBackground(style);
}
// The `[selectorList, body]` pairs `/(?<![^{}])([^{}]+)\{([^}]+)\}/g` matches, found in linear
// time: a run of non-braces, then `{`, then everything up to the next `}`. The next `}` is cached,
// because rescanning for it from every `{` is quadratic on a style with many `{` and no `}`.
function styleRuleBodies(css: string): Array<[selectorList: string, body: string]> {
const out: Array<[string, string]> = [];
let start = 0;
let close = 0;
while (start < css.length) {
let brace = start;
while (brace < css.length && css[brace] !== "{" && css[brace] !== "}") brace++;
if (brace === css.length) break;
if (css[brace] === "{" && brace > start) {
if (close !== -1 && close <= brace) close = css.indexOf("}", brace + 1);
if (close === -1) break;
if (close > brace + 1) {
out.push([css.slice(start, brace), css.slice(brace + 1, close)]);
start = close + 1;
continue;
}
}
start = brace + 1;
}
return out;
}
function collectSimpleStyleRules(styles: LintContext["styles"]): Map<string, string> {
const rules = new Map<string, string>();
for (const style of styles) {
for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) {
for (const [selectorList, body] of styleRuleBodies(style.content)) {
if (!selectorList || !body) continue;
for (const selector of selectorList.split(",")) {
const token = selector.trim();
@@ -897,6 +922,25 @@ function expressionReachesMeasurement(expression: string, measuring: Set<string>
return false;
}
const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
// Whether `id` is `parts` in order with a gap of non-line-terminators between each pair, the
// language of `^a.*b.*c$`, checked with leftmost indexOf so time stays linear in the id.
function matchesTemplateParts(id: string, parts: string[]): boolean {
const first = parts[0] ?? "";
const last = parts[parts.length - 1] ?? "";
if (parts.length === 1) return id === first;
if (!id.startsWith(first)) return false;
let at = first.length;
for (const part of parts.slice(1, -1)) {
const found = id.indexOf(part, at);
if (found === -1 || LINE_TERMINATOR.test(id.slice(at, found))) return false;
at = found + part.length;
}
const end = id.length - last.length;
return end >= at && id.endsWith(last) && !LINE_TERMINATOR.test(id.slice(at, end));
}
// Resolve script-level element variables to the simple selector tokens they can
// denote: literal getElementById/querySelector lookups, template-literal ids
// matched against the document's actual ids, and script-assigned class names
@@ -923,9 +967,8 @@ function resolveScriptElementTokens(source: string, tags: OpenTag[]): Map<string
// A template with no literal segments (`getElementById(\`${name}\`)`) would
// match EVERY id in the document — treat it as unresolved instead.
if (staticParts.every((part) => part === "")) continue;
const idPattern = new RegExp(`^${staticParts.map(escapeRegExp).join(".*")}$`);
for (const id of documentIds) {
if (idPattern.test(id)) add(match[1] ?? "", `#${id}`);
if (matchesTemplateParts(id, staticParts)) add(match[1] ?? "", `#${id}`);
}
}
for (const match of source.matchAll(
@@ -2332,7 +2375,7 @@ export const gsapRules: LintRule<LintContext>[] = [
const multiDashTokens = new Set<string>();
for (const style of styles) {
for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) {
for (const [selectorList, body] of styleRuleBodies(style.content)) {
if (!selectorList || !body) continue;
const value = readStyleProperty(body, "stroke-dasharray");
if (!value || !isMultiComponentDasharray(value)) continue;
+26 -22
View File
@@ -25,6 +25,9 @@ import {
distributeArrayKeyframes,
authorsKeyframes,
plainPercentKey,
scriptJson,
tweenMethodCode,
assertMotionPathNumbers,
} from "./gsapSerialize";
export type {
@@ -1479,7 +1482,7 @@ function insertAfterAnchor(parsed: ParsedGsapAst, newStatement: AstNode): void {
/** Build the source for a single `tl.method(selector, vars, position)` call. */
function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation, "id">): string {
const selector = JSON.stringify(anim.targetSelector);
const selector = scriptJson(anim.targetSelector);
const props: Record<string, number | string> = { ...anim.properties };
if (anim.method !== "set" && anim.duration !== undefined) props.duration = anim.duration;
if (anim.ease) props.ease = anim.ease;
@@ -1521,7 +1524,7 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
if (anim.method === "set" && anim.global) {
return `gsap.set(${selector}, ${objCode});`;
}
return `${timelineVar}.${anim.method}(${selector}, ${objCode}, ${posCode});`;
return `${timelineVar}.${tweenMethodCode(anim.method)}(${selector}, ${objCode}, ${posCode});`;
}
export function updateAnimationInScript(
@@ -1679,10 +1682,10 @@ export function addAnimationWithKeyframesToScript(
return { script, id: "" };
}
const selector = JSON.stringify(targetSelector);
const selector = scriptJson(targetSelector);
const kfCode = buildKeyframeObjectCode(keyframes, easeEach ? { easeEach } : undefined);
const varEntries = [`keyframes: ${kfCode}`, `duration: ${valueToCode(duration)}`];
if (ease) varEntries.push(`ease: ${JSON.stringify(ease)}`);
if (ease) varEntries.push(`ease: ${scriptJson(ease)}`);
const posCode = valueToCode(position);
const stmtCode = `${parsed.timelineVar}.to(${selector}, { ${varEntries.join(", ")} }, ${posCode});`;
@@ -1810,9 +1813,9 @@ function insertInheritedStateSet(
}
const tlVar = parsed.timelineVar;
const props = Object.entries(properties)
.map(([k, v]) => `${k}: ${typeof v === "string" ? JSON.stringify(v) : v}`)
.map(([k, v]) => `${safeKey(k)}: ${typeof v === "string" ? scriptJson(v) : v}`)
.join(", ");
const code = `${tlVar}.set(${JSON.stringify(selector)}, { ${props} }, ${position});`;
const code = `${tlVar}.set(${scriptJson(selector)}, { ${props} }, ${position});`;
const newStatement = parseScript(code).program.body[0];
const anchor = findTimelineDeclarationPath(parsed.ast, tlVar);
if (anchor) {
@@ -2071,11 +2074,11 @@ function buildKeyframeObjectCode(
): string {
const entries = mergePercentageKeyframes(keyframes).map((kf) => {
const props = keyframePropsToCode(kf);
if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`);
if (kf.ease) props.push(`ease: ${scriptJson(kf.ease)}`);
if (kf.auto) props.push(`_auto: 1`);
return `${JSON.stringify(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`;
return `${scriptJson(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`;
});
if (options?.easeEach) entries.push(`easeEach: ${JSON.stringify(options.easeEach)}`);
if (options?.easeEach) entries.push(`easeEach: ${scriptJson(options.easeEach)}`);
return `{ ${entries.join(", ")} }`;
}
@@ -2124,7 +2127,7 @@ function buildKeyframeValueNode(
const entries = Object.entries(properties)
.filter(([k]) => k !== "ease")
.map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
if (effectiveEase) entries.push(`ease: ${JSON.stringify(effectiveEase)}`);
if (effectiveEase) entries.push(`ease: ${scriptJson(effectiveEase)}`);
return parseExpr(`{ ${entries.join(", ")} }`);
}
@@ -2134,7 +2137,7 @@ function setObjectExpressionEase(node: AstNode, ease: string): boolean {
const easeIdx = props.findIndex(
(property: AstNode) => isObjectProperty(property) && propKeyName(property) === "ease",
);
const easeNode = parseExpr(`({ ease: ${JSON.stringify(ease)} })`).properties[0];
const easeNode = parseExpr(`({ ease: ${scriptJson(ease)} })`).properties[0];
if (easeIdx >= 0) props[easeIdx] = easeNode;
else props.push(easeNode);
return true;
@@ -2235,7 +2238,7 @@ function convertArrayKeyframesToObjectNode(varsArg: AstNode, scope: ScopeBinding
el.properties = (el.properties ?? []).filter(
(property: AstNode) => !isObjectProperty(property) || propKeyName(property) !== "duration",
);
return `${JSON.stringify(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`;
return `${scriptJson(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`;
});
prop.value = parseExpr(`{ ${entries.join(", ")}, easeEach: "none" }`);
return prop.value;
@@ -2327,7 +2330,7 @@ export function addKeyframeToScript(
}
} else {
// Build the new property node with a quoted percentage key
const newProp = parseExpr(`{ ${JSON.stringify(pctKey)}: {} }`).properties[0];
const newProp = parseExpr(`{ ${scriptJson(pctKey)}: {} }`).properties[0];
newProp.value = newValueNode;
// Insert in sorted order by percentage
@@ -2513,7 +2516,7 @@ export function moveKeyframeInScript(
const kept = (kfNode.properties ?? []).filter((p: AstNode) => !pctProps.has(p));
kfNode.properties = [
...entries.map((e) => {
const p = parseExpr(`{ ${JSON.stringify(plainPercentKey(e.pct))}: {} }`).properties[0];
const p = parseExpr(`{ ${scriptJson(plainPercentKey(e.pct))}: {} }`).properties[0];
p.value = e.value;
return p;
}),
@@ -2555,7 +2558,7 @@ export function resizeKeyframedTweenInScript(
seen.add(match.prop);
// Replace only the key node; the value node (incl. _auto + per-keyframe ease)
// stays verbatim. easeEach is a sibling non-percentage prop, left untouched.
match.prop.key = parseExpr(`{ ${JSON.stringify(plainPercentKey(to))}: 0 }`).properties[0].key;
match.prop.key = parseExpr(`{ ${scriptJson(plainPercentKey(to))}: 0 }`).properties[0].key;
}
applyUpdatesToCall(loc.target.call, {
@@ -2672,7 +2675,7 @@ export function updateKeyframeInScript(
else props.push(node);
};
for (const [k, v] of Object.entries(properties)) upsert(k, valueToCode(v));
if (ease !== undefined) upsert("ease", JSON.stringify(ease));
if (ease !== undefined) upsert("ease", scriptJson(ease));
return recast.print(loc.parsed.ast).code;
}
match.prop.value = buildKeyframeValueNode(properties, ease);
@@ -2701,7 +2704,7 @@ function insertKeyframesProp(
): void {
const fromEntries = Object.entries(fromProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
const toEntries = Object.entries(toProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
const easeEntry = easeEach ? `, easeEach: ${JSON.stringify(easeEach)}` : "";
const easeEntry = easeEach ? `, easeEach: ${scriptJson(easeEach)}` : "";
const kfCode = `{ "0%": { ${fromEntries.join(", ")} }, "100%": { ${toEntries.join(", ")} }${easeEntry} }`;
const kfProp = parseExpr(`{ keyframes: {} }`).properties[0];
kfProp.value = parseExpr(kfCode);
@@ -2853,7 +2856,7 @@ export function materializeKeyframesInScript(
// Replace dynamic selector with resolved static string
if (resolvedSelector && loc.target.call.node.arguments[0]) {
loc.target.call.node.arguments[0] = parseExpr(JSON.stringify(resolvedSelector));
loc.target.call.node.arguments[0] = parseExpr(scriptJson(resolvedSelector));
}
const kfObjCode = buildKeyframeObjectCode(sortedKeyframes(keyframes), { easeEach });
@@ -2898,6 +2901,7 @@ function buildMotionPathObjectCode(config: {
segments: ArcPathSegment[];
autoRotate: boolean | number;
}): string {
assertMotionPathNumbers(config);
const { waypoints, segments, autoRotate } = config;
const hasExplicitControlPoints = segments.some((s) => s.cp1 && s.cp2);
// The simple `path` array supports only one scalar curviness for the whole
@@ -3230,11 +3234,11 @@ export function addMotionPathToScript(
segments: [{ curviness: 1 }],
autoRotate: false,
});
const selector = JSON.stringify(targetSelector);
const selector = scriptJson(targetSelector);
const varEntries = [
`motionPath: ${motionPathCode}`,
`duration: ${valueToCode(duration)}`,
`ease: ${JSON.stringify(ease)}`,
`ease: ${scriptJson(ease)}`,
];
const stmtCode = `${parsed.timelineVar}.to(${selector}, { ${varEntries.join(", ")} }, ${valueToCode(position)});`;
const newStatement = parseScript(stmtCode).program.body[0];
@@ -3432,7 +3436,7 @@ export function unrollDynamicAnimations(
typeof position === "number"
? String(position)
: typeof position === "string"
? JSON.stringify(position)
? scriptJson(position)
: "0";
// Find the enclosing loop (for/forEach) by walking up the AST path
@@ -3467,7 +3471,7 @@ export function unrollDynamicAnimations(
easeEach: el.easeEach,
});
calls.push(
`${loc.parsed.timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`,
`${loc.parsed.timelineVar}.to(${scriptJson(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${scriptJson(ease)} }, ${posCode});`,
);
}
+37 -4
View File
@@ -274,7 +274,7 @@ export function serializeGsapAnimations(
});
// fallow-ignore-next-line complexity
const lines = sorted.map((anim) => {
const selector = JSON.stringify(anim.targetSelector);
const selector = scriptJson(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;
@@ -288,7 +288,7 @@ export function serializeGsapAnimations(
propsStr = propsStr.slice(0, -2) + `, ${extrasStr} }`;
}
}
const posStr = JSON.stringify(anim.position);
const posStr = scriptJson(anim.position);
switch (anim.method) {
case "set":
// A global set is a base `gsap.set` — off the timeline, no position arg.
@@ -338,11 +338,25 @@ ${lines.join("\n")}${mediaSync}${postamble}
`;
}
/** `JSON.stringify` whose output cannot end, or open a comment in, the inline script it lands in. */
export function scriptJson(value: unknown): string {
return String(JSON.stringify(value)).replace(/<(\/script|!--)/gi, "\\u003c$1");
}
const TWEEN_METHODS: ReadonlySet<string> = new Set<GsapMethod>(["set", "to", "from", "fromTo"]);
/** The method name, checked against the four tween methods because it is emitted as code. */
export function tweenMethodCode(method: string): GsapMethod {
if (!TWEEN_METHODS.has(method))
throw new TypeError(`Unsupported tween method: ${scriptJson(method)}`);
return method as GsapMethod;
}
export function serializeValue(value: unknown): string {
if (typeof value === "string" && value.startsWith("__raw:")) {
return value.slice(6);
}
if (typeof value === "string") return JSON.stringify(value);
if (typeof value === "string") return scriptJson(value);
return String(value);
}
@@ -353,7 +367,7 @@ export function plainPercentKey(percentage: number): string {
}
export function safeJsKey(key: string): string {
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : scriptJson(key);
}
function serializeObject(obj: Record<string, number | string>): string {
@@ -603,6 +617,24 @@ export function resolveConversionProps(
// ── Arc path serialization helpers (shared by recast + acorn writers) ─────────
/** Rejects a motion path whose coordinates or curviness are not numbers, since they are emitted as code. */
export function assertMotionPathNumbers(config: {
waypoints: Array<{ x: number; y: number }>;
segments: ArcPathSegment[];
}): void {
const points = [
...config.waypoints,
...config.segments.flatMap((s) => [s.cp1, s.cp2].filter((p) => p !== undefined)),
];
const values = [
...points.flatMap((p): unknown[] => [p.x, p.y]),
...config.segments.map((s): unknown => s.curviness ?? 1),
];
if (values.some((v) => typeof v !== "number")) {
throw new TypeError("Motion path coordinates and curviness must be numbers");
}
}
function numericXY(props: Record<string, number | string>): { x: number; y: number } | null {
const vx = props.x;
const vy = props.y;
@@ -671,6 +703,7 @@ export function buildMotionPathObjectCode(config: {
segments: ArcPathSegment[];
autoRotate: boolean | number;
}): string {
assertMotionPathNumbers(config);
const { waypoints, segments, autoRotate } = config;
const arSuffix = autoRotateSuffix(autoRotate);
// GSAP's simple `path` array supports only ONE scalar `curviness` for the whole
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import * as acornWriter from "./gsapWriterAcorn.js";
import * as recastWriter from "./gsapParser.js";
import { parseGsapScript } from "./gsapParser.js";
import type { GsapAnimation } from "./gsapSerialize.js";
const SCRIPT = `var tl = gsap.timeline({ paused: true });
tl.to("#box", { opacity: 1, duration: 1 }, 0);`;
const CLOSER = "</script><script>window.hacked = 1</script><!--";
const writers = [
["acorn", acornWriter],
["recast", recastWriter],
] as const;
describe.each(writers)("%s writer output stays inside its script element", (_name, writer) => {
it("escapes a script closer or comment opener in strings and keys", () => {
const animation: Omit<GsapAnimation, "id"> = {
targetSelector: `#box[data-x="${CLOSER}"]`,
method: "to",
position: 1,
duration: 1,
ease: CLOSER,
properties: { text: CLOSER, [CLOSER]: 1 },
};
const { script } = writer.addAnimationToScript(SCRIPT, animation);
expect(script).not.toMatch(/<\/script|<!--/i);
const added = parseGsapScript(script).animations.find((a) => a.ease === CLOSER);
expect(added?.targetSelector).toBe(animation.targetSelector);
expect(added?.properties.text).toBe(CLOSER);
});
it("leaves strings without those sequences byte-for-byte as before", () => {
const { script } = writer.addAnimationToScript(SCRIPT, {
targetSelector: "#box",
method: "to",
position: 2,
duration: 1,
ease: "power2.out",
properties: { text: "a < b", x: 10 },
});
expect(script).toContain('"a < b"');
expect(script).toContain('"power2.out"');
});
it("refuses a tween method outside set, to, from and fromTo", () => {
const animation = {
targetSelector: "#box",
method: "to(window),tl.to" as GsapAnimation["method"],
position: 0,
duration: 1,
properties: { x: 1 },
};
expect(() => writer.addAnimationToScript(SCRIPT, animation)).toThrow(/tween method/);
});
it("refuses a motion path point that is not a number", () => {
const point = { x: "0}];window.hacked=1;[{" as unknown as number, y: 0 };
expect(() => writer.addMotionPathToScript(SCRIPT, "#box", 0, 1, point)).toThrow(/numbers/);
});
});
+24 -23
View File
@@ -21,6 +21,8 @@ import {
buildMotionPathObjectCode,
mergePercentageKeyframes,
plainPercentKey,
scriptJson,
tweenMethodCode,
} from "./gsapSerialize.js";
import {
parseGsapScriptAcornForWrite,
@@ -57,19 +59,19 @@ type Node = any;
// always number|string and use the shared serializeValue (recast parity).
function valueToCode(value: unknown): string {
if (typeof value === "string" && value.startsWith("__raw:")) return value.slice(6);
if (typeof value === "string") return JSON.stringify(value);
if (typeof value === "string") return scriptJson(value);
if (typeof value === "number") return Number.isNaN(value) ? "0" : String(value);
if (typeof value === "boolean") return String(value);
return JSON.stringify(value);
return scriptJson(value);
}
function safeKey(key: string): string {
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : scriptJson(key);
}
// fallow-ignore-next-line complexity
function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation, "id">): string {
const selector = JSON.stringify(anim.targetSelector);
const selector = scriptJson(anim.targetSelector);
const props: Record<string, number | string> = { ...anim.properties };
if (anim.method !== "set" && anim.duration !== undefined) props.duration = anim.duration;
if (anim.ease) props.ease = anim.ease;
@@ -99,7 +101,7 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
if (anim.method === "set" && anim.global) {
return `gsap.set(${selector}, ${objCode});`;
}
return `${timelineVar}.${anim.method}(${selector}, ${objCode}, ${posCode});`;
return `${timelineVar}.${tweenMethodCode(anim.method)}(${selector}, ${objCode}, ${posCode});`;
}
// ── AST node helpers ─────────────────────────────────────────────────────────
@@ -528,7 +530,7 @@ export function copyAnimationsInScript(
const parsed = parseGsapScriptAcornForWrite(script);
if (!parsed) return script;
const block = timelineBlock(parsed);
const target = JSON.stringify(toSelector);
const target = scriptJson(toSelector);
const ms = new MagicString(script);
const tweens: string[] = [];
for (const { animation, call } of parsed.located) {
@@ -1290,7 +1292,7 @@ function convertArrayKeyframesToObject(script: string, target: Node): string {
if (!timing) return script;
const entries = els.map((el, i) => {
const { duration: _duration, ...record } = records[i]!;
return `${JSON.stringify(plainPercentKey(timing.percentages[i]!))}: ${recordToCode(record)}`;
return `${scriptJson(plainPercentKey(timing.percentages[i]!))}: ${recordToCode(record)}`;
});
const ms = new MagicString(script);
ms.overwrite(
@@ -1426,10 +1428,10 @@ function insertNewKeyframe(
}
}
if (insertBeforeProp) {
ms.appendLeft(insertBeforeProp.start, `${JSON.stringify(pctKey)}: ${valueCode}, `);
ms.appendLeft(insertBeforeProp.start, `${scriptJson(pctKey)}: ${valueCode}, `);
} else {
const sep = allProps.length > 0 ? ", " : "";
ms.appendLeft(kfNode.end - 1, `${sep}${JSON.stringify(pctKey)}: ${valueCode}`);
ms.appendLeft(kfNode.end - 1, `${sep}${scriptJson(pctKey)}: ${valueCode}`);
}
}
@@ -1583,7 +1585,7 @@ export function moveKeyframeInScript(
.filter((p: Node) => !pctProps.has(p))
.map((p: Node) => src.slice(p.start, p.end));
const body = [
...entries.map((e) => `${JSON.stringify(plainPercentKey(e.pct))}: ${recordToCode(e.record)}`),
...entries.map((e) => `${scriptJson(plainPercentKey(e.pct))}: ${recordToCode(e.record)}`),
...kept,
].join(", ");
const ms = new MagicString(src);
@@ -1630,7 +1632,7 @@ export function resizeKeyframedTweenInScript(
const ms = new MagicString(src);
for (const { keyNode, to } of edits) {
ms.overwrite(keyNode.start, keyNode.end, JSON.stringify(plainPercentKey(to)));
ms.overwrite(keyNode.start, keyNode.end, scriptJson(plainPercentKey(to)));
}
overwritePosition(ms, target.call, newPosition);
// Resizing is an explicit duration-authoring gesture. Promote GSAP's implicit
@@ -1829,7 +1831,7 @@ function buildKeyframeObjectCode(
const props = Object.entries(kf.properties).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
if (kf.ease) props.push(`ease: ${valueToCode(kf.ease)}`);
if (kf.auto) props.push(`_auto: 1`);
return `${JSON.stringify(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`;
return `${scriptJson(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`;
});
if (easeEach) entries.push(`easeEach: ${valueToCode(easeEach)}`);
return `{ ${entries.join(", ")} }`;
@@ -1868,8 +1870,7 @@ export function materializeKeyframesFromScript(
if (resolvedSelector) {
const selectorArg = call.node.arguments[0];
if (selectorArg)
ms.overwrite(selectorArg.start, selectorArg.end, JSON.stringify(resolvedSelector));
if (selectorArg) ms.overwrite(selectorArg.start, selectorArg.end, scriptJson(resolvedSelector));
}
const kfProp = findPropertyNode(call.varsArg, "keyframes");
@@ -1933,7 +1934,7 @@ export function replaceTweenWithKeyframesInScript(
if (edit.ease) parts.push(`ease: ${valueToCode(edit.ease)}`);
if (animation.hasUnresolvedSelector || animation.targetSelector !== edit.targetSelector) {
const selectorArg = call.node.arguments[0];
ms.overwrite(selectorArg.start, selectorArg.end, JSON.stringify(edit.targetSelector));
ms.overwrite(selectorArg.start, selectorArg.end, scriptJson(edit.targetSelector));
}
convertMethodToTo(ms, animation, call, call.varsArg);
overwriteVarsArg(ms, call, `{ ${parts.join(", ")} }`);
@@ -1967,7 +1968,7 @@ export function addAnimationWithKeyframesToScript(
const kfObjCode = buildKeyframeObjectCode(sorted, easeEach);
const varParts = [`keyframes: ${kfObjCode}`, `duration: ${valueToCode(duration)}`];
if (ease) varParts.push(`ease: ${valueToCode(ease)}`);
const stmtCode = `${parsed.timelineVar}.to(${JSON.stringify(targetSelector)}, { ${varParts.join(", ")} }, ${valueToCode(position)});`;
const stmtCode = `${parsed.timelineVar}.to(${scriptJson(targetSelector)}, { ${varParts.join(", ")} }, ${valueToCode(position)});`;
const ms = new MagicString(script);
ms.appendLeft(insertionPoint, "\n" + stmtCode);
@@ -2190,7 +2191,7 @@ export function addLabelToScript(script: string, name: string, position: number)
if (insertionPoint === null) return script;
const ms = new MagicString(script);
const labelCode = `${parsed.timelineVar}.addLabel(${JSON.stringify(name)}, ${valueToCode(position)});`;
const labelCode = `${parsed.timelineVar}.addLabel(${scriptJson(name)}, ${valueToCode(position)});`;
ms.appendLeft(insertionPoint, "\n" + labelCode);
return ms.toString();
}
@@ -2516,7 +2517,7 @@ function updateAnimationSelectorInScript(
const selectorArg = target.call.node.arguments?.[0];
if (!selectorArg) return script;
const ms = new MagicString(script);
ms.overwrite(selectorArg.start, selectorArg.end, JSON.stringify(newSelector));
ms.overwrite(selectorArg.start, selectorArg.end, scriptJson(newSelector));
return ms.toString();
}
@@ -2535,7 +2536,7 @@ function insertInheritedStateSetInScript(
const props = Object.entries(properties)
.map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`)
.join(", ");
const code = `${parsed.timelineVar}.set(${JSON.stringify(selector)}, { ${props} }, ${position});`;
const code = `${parsed.timelineVar}.set(${scriptJson(selector)}, { ${props} }, ${position});`;
const ms = new MagicString(script);
const tlDecl = findTimelineDeclarationStatement(parsed.ast, parsed.timelineVar);
const firstLocated = parsed.located[0];
@@ -2975,11 +2976,11 @@ function buildUnrollReplacement(
const duration = typeof animation.duration === "number" ? animation.duration : 8;
const ease = typeof animation.ease === "string" ? animation.ease : "none";
const pos = animation.position ?? 0;
const posCode = typeof pos === "number" ? String(pos) : JSON.stringify(pos);
const posCode = typeof pos === "number" ? String(pos) : scriptJson(pos);
const calls = elements.map((el) => {
const sorted = [...el.keyframes].sort((a, b) => a.percentage - b.percentage);
const kfCode = buildKeyframeObjectCode(sorted, el.easeEach);
return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
return `${timelineVar}.to(${scriptJson(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
});
return calls.join("\n ");
}
@@ -2999,10 +3000,10 @@ function buildUnrollCallForElement(
const duration = typeof animation.duration === "number" ? animation.duration : 8;
const ease = typeof animation.ease === "string" ? animation.ease : "none";
const pos = animation.position ?? 0;
const posCode = typeof pos === "number" ? String(pos) : JSON.stringify(pos);
const posCode = typeof pos === "number" ? String(pos) : scriptJson(pos);
const sorted = [...el.keyframes].sort((a, b) => a.percentage - b.percentage);
const kfCode = buildKeyframeObjectCode(sorted, el.easeEach);
return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
return `${timelineVar}.to(${scriptJson(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
}
/** Sentinel: the unroll cannot safely reproduce the loop body — caller no-ops. */
+5 -1
View File
@@ -11,7 +11,11 @@
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/dist/topojson-client.min.js"></script>
<style>
* {
+6 -2
View File
@@ -11,7 +11,11 @@
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/dist/topojson-client.min.js"></script>
<style>
* {
@@ -165,7 +169,7 @@
<script>
(function () {
var US_TOPO_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json";
var US_TOPO_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3.0.1/states-10m.json";
var cities = [
{ name: "New York", lat: 40.7128, lon: -74.006, pop: 8300000 },
+7 -2
View File
@@ -11,7 +11,11 @@
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/dist/topojson-client.min.js"></script>
<style>
* {
@@ -238,7 +242,8 @@
}
/* --- Load topology and render states --- */
d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json").then(function (us) {
var US_TOPO_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3.0.1/states-10m.json";
d3.json(US_TOPO_URL).then(function (us) {
var states = topojson.feature(us, us.objects.states).features;
states.forEach(function (feature) {
+6 -2
View File
@@ -11,7 +11,11 @@
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/dist/topojson-client.min.js"></script>
<style>
* {
@@ -158,7 +162,7 @@
<script>
(function () {
const US_TOPO_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json";
const US_TOPO_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3.0.1/states-10m.json";
const stateData = {
"01": { name: "Alabama", abbr: "AL", density: 99.2 },
+6 -2
View File
@@ -11,7 +11,11 @@
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client@3.1.0/dist/topojson-client.min.js"></script>
<style>
* {
@@ -278,7 +282,7 @@
var tooltipEl = document.querySelector("#world-map .tooltip");
/* Fetch topology and render countries */
d3.json("https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json").then(
d3.json("https://cdn.jsdelivr.net/npm/world-atlas@2.0.2/countries-110m.json").then(
function (world) {
var countries = topojson.feature(world, world.objects.countries).features;
+98 -1
View File
@@ -14,6 +14,7 @@
*/
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
@@ -466,7 +467,11 @@ test("printing keeps two decimals and drops a negative zero", () => {
});
/** The component as a page renders it: React comes from the studio workspace, the hooks are the globals Mintlify supplies. */
async function renderDetail(slots: string[], wrapped = false): Promise<string> {
async function renderDetail(
slots: string[],
wrapped = false,
overrides: Record<string, unknown> = {},
): Promise<string> {
const requireFromStudio = createRequire(
join(dirname(fileURLToPath(import.meta.url)), "..", "packages", "studio", "package.json"),
);
@@ -510,6 +515,7 @@ async function renderDetail(slots: string[], wrapped = false): Promise<string> {
variables: [],
meta: { duration: 5, width: 1920, height: 1080 },
hasCode: true,
...overrides,
},
...children,
),
@@ -529,6 +535,97 @@ for (const wrapped of [false, true]) {
});
}
const previewValues = (() => {
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "docs", "snippets", "catalog-detail.jsx"),
"utf8",
);
const open = source.indexOf("// >>> preview values");
const close = source.indexOf("// <<< preview values");
assert.ok(open !== -1 && close > open, "the preview values markers are missing");
return new Function(`${source.slice(open, close)}\nreturn { scriptJson, declaredValues };`)() as {
scriptJson: (value: unknown) => string;
declaredValues: (parsed: unknown, ids: Set<string>) => Record<string, unknown>;
};
})();
test("preview values embed as JSON with no markup characters and read back unchanged", () => {
const value = { t: "</script><img src=x onerror=alert(1)>", a: "R&D", s: "\u2028\u2029", n: 2 };
const json = previewValues.scriptJson(value);
assert.ok(!/[<>&\u2028\u2029]/.test(json), json);
assert.deepEqual(JSON.parse(json), value);
assert.deepEqual(new Function(`return ${json};`)(), value);
assert.equal(previewValues.scriptJson({ a: "plain", n: 1.5 }), '{"a":"plain","n":1.5}');
});
test("a link's values keep only declared ids holding a string, finite number or boolean", () => {
const ids = new Set(["a", "b", "c", "d"]);
assert.deepEqual(
previewValues.declaredValues({ a: "x", b: 2, c: true, d: { nested: 1 }, e: "stray" }, ids),
{ a: "x", b: 2, c: true },
);
assert.deepEqual(previewValues.declaredValues(["a"], ids), {});
assert.deepEqual(previewValues.declaredValues(null, ids), {});
});
test("a link value that closes a script element stays inside the preview's bootstrap script", async () => {
const injected = "</script><script>window.hacked=1</script>";
const query = new URLSearchParams({ "vars-x": JSON.stringify({ label: injected }) });
Object.assign(globalThis, {
window: { location: { search: `?${query}` }, matchMedia: () => ({ matches: false }) },
});
try {
const html = await renderDetail(["install"], false, {
variables: [{ id: "label", type: "string", default: "hello" }],
});
const srcdoc = /srcDoc="([^"]*)"|srcdoc="([^"]*)"/.exec(html);
assert.ok(srcdoc, "the preview frame has a srcdoc");
const doc = (srcdoc[1] ?? srcdoc[2] ?? "")
.replace(/&quot;/g, '"')
.replace(/&#x27;/g, "'")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&amp;/g, "&");
assert.equal(doc.match(/<script/gi)?.length, 2, "only the player and bootstrap scripts");
assert.ok(!doc.includes("window.hacked=1</script>"));
assert.match(doc, /var INITIAL = \{"label":"\\u003c\/script\\u003e/);
const body = /<body><script>([\s\S]*)<\/script><\/body>/.exec(doc)?.[1] ?? "";
assert.doesNotThrow(() => new Function(body), "the bootstrap script still parses");
assert.match(body, /var scriptJson = function scriptJson\(value\)/);
} finally {
Reflect.deleteProperty(globalThis, "window");
}
});
const varsArgument = (() => {
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "docs", "snippets", "install-command.jsx"),
"utf8",
);
const open = source.indexOf("// >>> vars argument");
const close = source.indexOf("// <<< vars argument");
assert.ok(open !== -1 && close > open, "the vars argument markers are missing");
return new Function(`${source.slice(open, close)}\nreturn varsArgument;`)() as (
raw: string | null,
) => string;
})();
test("the install command's --vars suffix is one shell argument for any link value", () => {
const hostile = { label: "a'; echo injected; echo '`$(id)`|\n", n: 3 };
const suffix = varsArgument(JSON.stringify(hostile));
const argv = execFileSync("sh", ["-c", `printf '%s\\0'${suffix}`])
.toString()
.split("\0");
assert.deepEqual(argv.slice(0, -1), ["--vars", JSON.stringify(hostile)]);
});
test("the install command keeps only variable-id keys with primitive values", () => {
assert.equal(varsArgument('{"speed":2,"on":true}'), ` --vars '{"speed":2,"on":true}'`);
assert.equal(varsArgument('{"a b":1,"nested":{"x":1},"list":[1]}'), "");
assert.equal(varsArgument('["speed"]'), "");
assert.equal(varsArgument(null), "");
});
test("the tabs are Preview, Code, Snippet, Docs with Preview selected", async () => {
const html = await renderDetail(["install"]);
const tabs = [
+63 -1
View File
@@ -1,9 +1,10 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { test } from "node:test";
import { pathToFileURL } from "node:url";
@@ -69,3 +70,64 @@ test("source replacement between planning and staging aborts before manifest pub
fs.rmSync(f.root, { recursive: true, force: true });
}
});
test("a manifest path outside the item is refused before anything is staged or removed", async () => {
const f = await fixture();
try {
const outside = join(f.root, "registry/blocks/secret.png");
fs.writeFileSync(outside, "outside bytes");
fs.writeFileSync(
f.manifestPath,
JSON.stringify({ name: "test-item", files: [{ path: "../secret.png" }] }),
);
await assert.rejects(f.main(["test-item", "--no-upload"]), /outside the item/);
assert.equal(fs.readFileSync(outside, "utf8"), "outside bytes");
assert.equal(fs.existsSync(join(f.root, ".registry-assets-staging")), false);
} finally {
fs.rmSync(f.root, { recursive: true, force: true });
}
});
test("an asset that is a symlink is refused before its target is read", async () => {
const f = await fixture();
try {
const outside = join(f.root, "secret.txt");
fs.writeFileSync(outside, "outside bytes");
fs.rmSync(f.source);
fs.symlinkSync(outside, f.source);
const manifest = fs.readFileSync(f.manifestPath, "utf8");
await assert.rejects(f.main(["test-item", "--no-upload"]), /symlink/);
assert.equal(fs.readFileSync(f.manifestPath, "utf8"), manifest);
assert.equal(fs.readFileSync(outside, "utf8"), "outside bytes");
assert.equal(fs.existsSync(join(f.root, ".registry-assets-staging")), false);
} finally {
fs.rmSync(f.root, { recursive: true, force: true });
}
});
test("the registry tracks no symlinks and every manifest path stays inside its item", () => {
const listing = execFileSync("git", ["ls-files", "-s", "-z", "registry"], {
cwd: repoRoot,
encoding: "utf-8",
maxBuffer: 64 * 1024 * 1024,
});
const entries = listing.split("\0").filter(Boolean);
const symlinks = entries.filter((entry) => entry.startsWith("120000 "));
assert.deepEqual(symlinks, []);
const escaping = entries
.map((entry) => entry.slice(entry.indexOf("\t") + 1))
.filter((file) => file.endsWith("/registry-item.json") && fs.existsSync(join(repoRoot, file)))
.flatMap((file) => {
const itemDir = join(repoRoot, dirname(file));
const manifest = JSON.parse(fs.readFileSync(join(repoRoot, file), "utf8")) as {
files?: Array<{ path: string }>;
};
return (manifest.files ?? [])
.filter(({ path }) => {
const rel = relative(itemDir, resolve(itemDir, path));
return rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel);
})
.map(({ path }) => `${file}: ${path}`);
});
assert.deepEqual(escaping, []);
});
+17 -3
View File
@@ -41,12 +41,13 @@ import {
mkdirSync,
readdirSync,
readFileSync,
realpathSync,
rmSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { execFileSync } from "node:child_process";
import { dirname, extname, join, resolve } from "node:path";
import { dirname, extname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { runAsCommand } from "./entrypoint.ts";
// Import from source, like every other script here: bun workspace linking does
@@ -126,10 +127,23 @@ function needsHosting(file: FileTarget): boolean {
return file.url === undefined && HOSTED_EXTENSIONS.has(extname(file.path).toLowerCase());
}
/** The declared file's path, refused unless it is inside the item and reached without a symlink. */
function itemSource(itemName: string, itemDir: string, path: string): string {
const root = realpathSync(itemDir);
const source = resolve(root, path);
if (!source.startsWith(root + sep)) {
throw new Error(`${itemName}: files[] declares "${path}", which is outside the item.`);
}
if (realpathSync(source) !== source) {
throw new Error(`${itemName}: files[] declares "${path}", which goes through a symlink.`);
}
return source;
}
/** Point one file at the CDN, and say which bytes have to get there. */
function hostFile(itemName: string, itemDir: string, file: FileTarget): Plan {
const source = resolve(itemDir, file.path);
const fd = openSync(source, constants.O_RDONLY | constants.O_NONBLOCK);
const source = itemSource(itemName, itemDir, file.path);
const fd = openSync(source, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
let digest: string;
try {
if (!fstatSync(fd).isFile()) {
+42
View File
@@ -0,0 +1,42 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
/** Registry items load npm packages from a CDN only at an exact version, so the bytes cannot change under them. */
const ROOT = resolve(import.meta.dirname, "..");
const NPM_CDN =
/(?:cdn\.jsdelivr\.net\/npm|unpkg\.com)\/((?:@[^/@"'`\s]+\/)?[^/@"'`\s)]+)(@[^/"'`\s)]*)?/g;
const EXACT = /^@\d+\.\d+\.\d+(?:-[\w.]+)?$/;
function floatingCdnReferences(text: string): string[] {
return [...text.matchAll(NPM_CDN)]
.filter((match) => !EXACT.test(match[2] ?? ""))
.map((match) => match[0]);
}
test("a range, tag or missing version is reported", () => {
assert.deepEqual(
floatingCdnReferences(
`<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
fetch("https://unpkg.com/us-atlas/states-10m.json");
import x from "https://cdn.jsdelivr.net/npm/@scope/pkg@latest/+esm";
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>`,
),
["cdn.jsdelivr.net/npm/d3@7", "unpkg.com/us-atlas", "cdn.jsdelivr.net/npm/@scope/pkg@latest"],
);
});
test("every npm CDN reference in a registry item names an exact version", () => {
const files = execFileSync("git", ["ls-files", "-z", "registry"], {
cwd: ROOT,
encoding: "utf-8",
})
.split("\0")
.filter((file) => /\.(html|js|mjs|json)$/.test(file));
const floating = files.flatMap((file) =>
floatingCdnReferences(readFileSync(join(ROOT, file), "utf-8")).map((ref) => `${file}: ${ref}`),
);
assert.deepEqual(floating, []);
});