fix(parsers): bound canvas scaffold dimension extraction (#7873)

* fix(parsers): bound canvas scaffold dimension extraction

* chore(parsers): raise packed size budget for linear scaffold scanners

The bounded scanners replace three regexes with a small amount of
procedural code; @hyperframes/parsers packs to 210414 bytes (+1.2%).

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:
James Russo
2026-11-16 00:00:41 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 0f23f40f8b
commit b856a1d63f
6 changed files with 216 additions and 66 deletions
+13 -13
View File
@@ -57,9 +57,10 @@ import {
type CanvasResolution,
} from "@hyperframes/core";
import {
HTML_BODY_CSS_HEIGHT_FIRST_RE,
HTML_BODY_CSS_WIDTH_FIRST_RE,
VIEWPORT_META_SIZE_RE,
matchHtmlBodyCssHeightFirst,
matchHtmlBodyCssWidthFirst,
matchViewportMetaSize,
replaceCanvasScaffoldSize,
} from "@hyperframes/parsers";
import { decodableAudioStream } from "@hyperframes/parsers/media-streams";
import { cliSourced } from "../utils/sourceTag.js";
@@ -633,20 +634,19 @@ function applyCanvasSize(
}
}
// Inline `html, body { ... }` CSS: handle width-before-height and
// height-before-width orderings. Hand-authored templates can use either.
// Groups 1 and 3 are the text before each dimension, 2 and 4 the digits.
if (HTML_BODY_CSS_WIDTH_FIRST_RE.test(html)) {
html = html.replace(HTML_BODY_CSS_WIDTH_FIRST_RE, `$1${width}px$3${height}px`);
const widthFirst = matchHtmlBodyCssWidthFirst(html);
if (widthFirst) {
html = replaceCanvasScaffoldSize(html, widthFirst, width, height);
changed = true;
}
if (HTML_BODY_CSS_HEIGHT_FIRST_RE.test(html)) {
html = html.replace(HTML_BODY_CSS_HEIGHT_FIRST_RE, `$1${height}px$3${width}px`);
const heightFirst = matchHtmlBodyCssHeightFirst(html);
if (heightFirst) {
html = replaceCanvasScaffoldSize(html, heightFirst, height, width);
changed = true;
}
if (VIEWPORT_META_SIZE_RE.test(html)) {
html = html.replace(VIEWPORT_META_SIZE_RE, `$1${width}$3${height}`);
const viewport = matchViewportMetaSize(html);
if (viewport) {
html = replaceCanvasScaffoldSize(html, viewport, width, height);
changed = true;
}
+6 -6
View File
@@ -11,9 +11,9 @@ import { styleRoot } from "../styleRoots";
import selectorParser from "postcss-selector-parser";
import { GLSL_SCRIPT_TYPES } from "../shaderDomains";
import {
HTML_BODY_CSS_WIDTH_FIRST_RE,
HTML_BODY_CSS_HEIGHT_FIRST_RE,
VIEWPORT_META_SIZE_RE,
matchHtmlBodyCssWidthFirst,
matchHtmlBodyCssHeightFirst,
matchViewportMetaSize,
} from "@hyperframes/parsers/composition";
import {
readAttr,
@@ -378,12 +378,12 @@ type ScaffoldSize = { width: string; height: string };
// Groups 1 and 3 are prefix text for applyResolutionPreset's in-place
// replace; lint only reads the digit groups (2 and 4).
function readHtmlBodyCssSize(source: string): ScaffoldSize | null {
const widthFirst = source.match(HTML_BODY_CSS_WIDTH_FIRST_RE);
const widthFirst = matchHtmlBodyCssWidthFirst(source);
if (widthFirst) {
const [, , width = "", , height = ""] = widthFirst;
return { width, height };
}
const heightFirst = source.match(HTML_BODY_CSS_HEIGHT_FIRST_RE);
const heightFirst = matchHtmlBodyCssHeightFirst(source);
if (heightFirst) {
const [, , height = "", , width = ""] = heightFirst;
return { width, height };
@@ -392,7 +392,7 @@ function readHtmlBodyCssSize(source: string): ScaffoldSize | null {
}
function readViewportMetaSize(source: string): ScaffoldSize | null {
const match = source.match(VIEWPORT_META_SIZE_RE);
const match = matchViewportMetaSize(source);
if (!match) return null;
const [, , width = "", , height = ""] = match;
return { width, height };
@@ -1,53 +1,91 @@
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
import {
HTML_BODY_CSS_HEIGHT_FIRST_RE,
HTML_BODY_CSS_WIDTH_FIRST_RE,
VIEWPORT_META_SIZE_RE,
matchHtmlBodyCssHeightFirst,
matchHtmlBodyCssWidthFirst,
matchViewportMetaSize,
replaceCanvasScaffoldSize,
} from "./canvasScaffoldPatterns.js";
// Both callers key off group numbers: @hyperframes/lint's
// root_dimensions_mismatch reads the digits, @hyperframes/cli's
// applyResolutionPreset substitutes `$1<new>$3<new>` to keep the text around
// them. Pin the layout here so neither can renumber against the other.
const CASES = [
{
name: "HTML_BODY_CSS_WIDTH_FIRST_RE",
re: HTML_BODY_CSS_WIDTH_FIRST_RE,
match: matchHtmlBodyCssWidthFirst,
source: "html, body { margin: 0; width: 1920px; height: 1080px; overflow: hidden; }",
digits: ["1920", "1080"],
replacement: "$13840px$32160px",
replaced: "html, body { margin: 0; width: 3840px; height: 2160px; overflow: hidden; }",
target: [3840, 2160],
result: "html, body { margin: 0; width: 3840px; height: 2160px; overflow: hidden; }",
},
{
name: "HTML_BODY_CSS_HEIGHT_FIRST_RE",
re: HTML_BODY_CSS_HEIGHT_FIRST_RE,
match: matchHtmlBodyCssHeightFirst,
source: "html, body { margin: 0; height: 1080px; width: 1920px; overflow: hidden; }",
digits: ["1080", "1920"],
replacement: "$12160px$33840px",
replaced: "html, body { margin: 0; height: 2160px; width: 3840px; overflow: hidden; }",
target: [2160, 3840],
result: "html, body { margin: 0; height: 2160px; width: 3840px; overflow: hidden; }",
},
{
name: "VIEWPORT_META_SIZE_RE",
re: VIEWPORT_META_SIZE_RE,
match: matchViewportMetaSize,
source: '<meta name="viewport" content="width=1920, height=1080" />',
digits: ["1920", "1080"],
replacement: "$13840$32160",
replaced: '<meta name="viewport" content="width=3840, height=2160" />',
target: [3840, 2160],
result: '<meta name="viewport" content="width=3840, height=2160" />',
},
];
describe("canvas scaffold patterns", () => {
it.each(CASES)("$name exposes the two dimensions as groups 2 and 4", ({ re, source, digits }) => {
const match = source.match(re);
expect(match).not.toBeNull();
expect(match?.slice(1)).toHaveLength(4);
expect([match?.[2], match?.[4]]).toEqual(digits);
});
describe("canvas scaffold extraction", () => {
it.each(CASES)(
"$name replaces both dimensions in place, leaving the rest untouched",
({ re, source, replacement, replaced }) => {
expect(source.replace(re, replacement)).toBe(replaced);
"reads and replaces dimensions in $source",
({ match, source, digits, target, result }) => {
const found = match(source);
expect(found).not.toBeNull();
expect([found?.[2], found?.[4]]).toEqual(digits);
if (found)
expect(replaceCanvasScaffoldSize(source, found, target[0], target[1])).toBe(result);
},
);
it("preserves case, offsets and surrounding text", () => {
const source = "before} HTML , BODY { WIDTH: 10PX; HEIGHT: 20PX;}after";
const found = matchHtmlBodyCssWidthFirst(source);
expect(found).not.toBeNull();
if (found)
expect(replaceCanvasScaffoldSize(source, found, 30, 40)).toBe(
"before} HTML , BODY { WIDTH: 30PX; HEIGHT: 40PX;}after",
);
});
it("does not join dimensions across braces or tags", () => {
expect(matchHtmlBodyCssWidthFirst("html,body{width:1px}height:2px")).toBeNull();
expect(
matchViewportMetaSize('<meta name="viewport"><meta content="width=1,height=2">'),
).toBeNull();
});
it("finds a later complete block after an incomplete block", () => {
const found = matchHtmlBodyCssWidthFirst("html,body{width:1px}html,body{width:3px;height:4px}");
expect([found?.[2], found?.[4]]).toEqual(["3", "4"]);
});
it.each(["width", "height", "viewport"])(
"bounds malformed %s input in a killable process",
(kind) => {
// A separate process guarantees a regression cannot hang the test runner.
const modulePath = resolve(__dirname, "canvasScaffoldPatterns.ts");
const result = spawnSync(
"bun",
[
"--eval",
`
const m = await import(${JSON.stringify(modulePath)});
const kind = ${JSON.stringify(kind)};
const source = kind === 'viewport'
? ('<meta name="viewport" '.repeat(30000) + 'content="width=1,height=x')
: ('html,body{'.repeat(30000) + (kind + ':1px;').repeat(30000));
const match = kind === 'viewport' ? m.matchViewportMetaSize
: kind === 'width' ? m.matchHtmlBodyCssWidthFirst : m.matchHtmlBodyCssHeightFirst;
if (match(source) !== null) process.exit(2);
`,
],
{ timeout: 2000, encoding: "utf8" },
);
expect(result.error).toBeUndefined();
expect(result.status, result.stderr).toBe(0);
},
);
});
+125 -13
View File
@@ -1,16 +1,128 @@
/**
* Where a scaffolded project's canvas resolution lives besides the root's own
* data-width/data-height: the html/body CSS size and the meta viewport content.
*/
/** Linear-time readers for the canvas dimensions in scaffold CSS and metadata. */
export type CanvasScaffoldMatch = [string, string, string, string, string] & { index: number };
/** html/body CSS, width first. Groups 1/3 are the surrounding text, 2/4 the digits. */
export const HTML_BODY_CSS_WIDTH_FIRST_RE =
/(html\s*,\s*body\s*\{[^}]*?width:\s*)(\d+)px([^}]*?height:\s*)(\d+)px/i;
function capture(
source: string,
start: number,
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): CanvasScaffoldMatch {
const match: [string, string, string, string, string] = [
source.slice(start, secondEnd),
source.slice(start, firstStart),
source.slice(firstStart, firstEnd),
source.slice(firstEnd, secondStart),
source.slice(secondStart, secondEnd),
];
return Object.assign(match, { index: start });
}
/** Same block, height authored first. */
export const HTML_BODY_CSS_HEIGHT_FIRST_RE =
/(html\s*,\s*body\s*\{[^}]*?height:\s*)(\d+)px([^}]*?width:\s*)(\d+)px/i;
function findDimensionPair(
source: string,
first: "width" | "height",
): [number, number, number, number] | null {
const dimensions = /(width|height):\s*(\d+)px/gi;
let firstValue: { start: number; end: number } | undefined;
let token: RegExpExecArray | null;
while ((token = dimensions.exec(source))) {
if (!token[2]) continue;
const start = token.index + token[0].length - token[2].length - 2;
const end = start + token[2].length;
if (token[1]?.toLowerCase() === first) {
firstValue ??= { start, end };
} else if (firstValue) {
return [firstValue.start, firstValue.end, start, end];
}
}
return null;
}
/** Viewport meta content. Shared by lint (reads groups 2/4) and cli (replaces via 1/3). */
export const VIEWPORT_META_SIZE_RE =
/(<meta[^>]*name=["']viewport["'][^>]*content=["']width=)(\d+)(,\s*height=)(\d+)/i;
/** Scan each disjoint brace-delimited region once, never retry its suffix. */
function matchBody(source: string, first: "width" | "height"): CanvasScaffoldMatch | null {
let start = 0;
while (start < source.length) {
const close = source.indexOf("}", start);
const end = close < 0 ? source.length : close;
const region = source.slice(start, end);
const header = /html\s*,\s*body\s*\{/i.exec(region);
if (header) {
const contentStart = start + header.index + header[0].length;
const pair = findDimensionPair(source.slice(contentStart, end), first);
if (pair) {
return capture(
source,
start + header.index,
contentStart + pair[0],
contentStart + pair[1],
contentStart + pair[2],
contentStart + pair[3],
);
}
}
start = end + 1;
}
return null;
}
export function matchHtmlBodyCssWidthFirst(source: string): CanvasScaffoldMatch | null {
return matchBody(source, "width");
}
export function matchHtmlBodyCssHeightFirst(source: string): CanvasScaffoldMatch | null {
return matchBody(source, "height");
}
/** Scan each tag-sized region once, including malformed unterminated tags. */
export function matchViewportMetaSize(source: string): CanvasScaffoldMatch | null {
let start = 0;
while (start < source.length) {
const close = source.indexOf(">", start);
const end = close < 0 ? source.length : close;
const region = source.slice(start, end);
const meta = region.search(/<meta/i);
if (meta >= 0) {
const names = /name=["']viewport["']/gi;
names.lastIndex = meta + 5;
const name = names.exec(region);
if (name) {
const content = /content=["']width=(\d+)(,\s*height=)(\d+)/gi;
content.lastIndex = name.index + name[0].length;
const size = content.exec(region);
if (size && size[1] && size[2] && size[3]) {
const firstStart = start + size.index + 15;
const firstEnd = firstStart + size[1].length;
const secondStart = firstEnd + size[2].length;
return capture(
source,
start + meta,
firstStart,
firstEnd,
secondStart,
secondStart + size[3].length,
);
}
}
}
start = end + 1;
}
return null;
}
/** Replace only the captured digits; preserve whitespace, units and surrounding text. */
export function replaceCanvasScaffoldSize(
source: string,
match: CanvasScaffoldMatch,
first: number,
second: number,
): string {
return (
source.slice(0, match.index) +
match[1] +
first +
match[3] +
second +
source.slice(match.index + match[0].length)
);
}
@@ -58,7 +58,7 @@ import {
} from "@hyperframes/core";
import { HF_AUDIO_GROUP_TAG } from "@hyperframes/core/audio-groups";
import type { CompileForRenderOptions } from "./htmlCompiler.js";
import { HTML_BODY_CSS_HEIGHT_FIRST_RE, HTML_BODY_CSS_WIDTH_FIRST_RE } from "@hyperframes/parsers";
import { matchHtmlBodyCssHeightFirst, matchHtmlBodyCssWidthFirst } from "@hyperframes/parsers";
import {
type EngineConfig,
extractMediaMetadata,
@@ -1766,8 +1766,8 @@ function detectRootBodySizeMismatch(
// Groups 1 and 3 are prefix text for applyResolutionPreset's in-place
// replace; this read-only comparison only needs the digit groups (2 and 4).
const widthFirst = html.match(HTML_BODY_CSS_WIDTH_FIRST_RE);
const heightFirst = widthFirst ? undefined : html.match(HTML_BODY_CSS_HEIGHT_FIRST_RE);
const widthFirst = matchHtmlBodyCssWidthFirst(html);
const heightFirst = widthFirst ? undefined : matchHtmlBodyCssHeightFirst(html);
const [cssWidth, cssHeight] = widthFirst
? [Number(widthFirst[2]), Number(widthFirst[4])]
: heightFirst
+1 -1
View File
@@ -28,7 +28,7 @@
"unpacked": 737342
},
"@hyperframes/parsers": {
"packed": 208000,
"packed": 212000,
"unpacked": 900000
},
"@hyperframes/player": {