Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat: font resolution pipeline — compositions capture and embed their own fonts (#1255)
Miguel Ángel0bf15119f8e2
diff --git a/bun.lock b/bun.lockindex add7eec86f..be1a46f8c3 100644--- a/bun.lock+++ b/bun.lock@@ -22,7 +22,7 @@},"packages/aws-lambda": {"name": "@hyperframes/aws-lambda",- "version": "0.6.79",+ "version": "0.6.80","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.79",+ "version": "0.6.80","bin": {"hyperframes": "./dist/cli.js",},@@ -101,7 +101,7 @@},"packages/core": {"name": "@hyperframes/core",- "version": "0.6.79",+ "version": "0.6.80","dependencies": {"@babel/parser": "^7.27.0","@chenglou/pretext": "^0.0.5",@@ -130,7 +130,7 @@},"packages/engine": {"name": "@hyperframes/engine",- "version": "0.6.79",+ "version": "0.6.80","dependencies": {"@hono/node-server": "^1.13.0","@hyperframes/core": "workspace:^",@@ -168,7 +168,7 @@},"packages/player": {"name": "@hyperframes/player",- "version": "0.6.79",+ "version": "0.6.80","devDependencies": {"@types/bun": "^1.1.0","gsap": "^3.12.5",@@ -180,7 +180,7 @@},"packages/producer": {"name": "@hyperframes/producer",- "version": "0.6.79",+ "version": "0.6.80","dependencies": {"@fontsource/archivo-black": "^5.2.8","@fontsource/eb-garamond": "^5.2.7",@@ -201,6 +201,7 @@"postcss": "^8.4.0","puppeteer": "^24.0.0","puppeteer-core": "^24.39.1",+ "wawoff2": "^2.0.1",},"devDependencies": {"@fontsource/lato": "^5.2.7",@@ -220,7 +221,7 @@},"packages/shader-transitions": {"name": "@hyperframes/shader-transitions",- "version": "0.6.79",+ "version": "0.6.80","dependencies": {"html2canvas": "^1.4.1",},@@ -232,7 +233,7 @@},"packages/studio": {"name": "@hyperframes/studio",- "version": "0.6.79",+ "version": "0.6.80","dependencies": {"@codemirror/autocomplete": "^6.20.1","@codemirror/commands": "^6.10.3",@@ -1987,6 +1988,8 @@"walk-up-path": ["[email protected]", "", {}, "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A=="],+ "wawoff2": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "woff2_compress.js": "bin/woff2_compress.js", "woff2_decompress.js": "bin/woff2_decompress.js" } }, "sha512-r0CEmvpH63r4T15ebFqeOjGqU4+EgTx4I510NtK35EMciSdcTxCw3Byy3JnBonz7iyIFZ0AbVo0bbFpEVuhCYA=="],+"web-streams-polyfill": ["[email protected]", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],"webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],diff --git a/docs/plans/2026-06-07-001-fix-font-pinning-cross-platform-plan.md b/docs/plans/2026-06-07-001-fix-font-pinning-cross-platform-plan.mdnew file mode 100644index 0000000000..f28dac907c--- /dev/null+++ b/docs/plans/2026-06-07-001-fix-font-pinning-cross-platform-plan.md@@ -0,0 +1,290 @@+---+title: "fix: Pin fonts cross-platform — eliminate silent system-font fallback at render time"+status: active+type: fix+created: 2026-06-07+depth: Standard+origin: null+---++## Summary++System fonts (SF Mono, SF Pro, Menlo, Monaco, Consolas, Georgia, Verdana, etc.) silently fall back to generic families at render time because the deterministic font injector (`FONT_ALIASES`) has no mapping for them. The blank template and the `ensureFullDocument` CSS reset declare no `font-family` at all, so compositions start with browser defaults. Studio exposes macOS-only fonts (`COMMON_LOCAL_FONT_FAMILIES`) in its font picker with no warning that they break headless rendering. The fix expands `FONT_ALIASES` to cover all common system fonts across macOS/Windows/Linux, adds Inter + JetBrains Mono as defaults in templates and the CSS reset, upgrades the lint rule to catch unaliased system fonts, and annotates Studio's local font list so users see the render-time mapping.++---++## Problem Frame++When a composition author uses a system font like SF Mono or Menlo — either by typing it in CSS or selecting it in Studio's font picker — the deterministic font injector (`injectDeterministicFontFaces`) finds no match in `FONT_ALIASES`, passes the family name to Google Fonts, gets a 404 (it's not a Google Font), and silently leaves it unresolved. At render time in the Docker container, the font isn't installed, Chrome falls back to a generic monospace (DejaVu Sans Mono on Linux), and monospace alignment breaks because the metrics differ. The same pattern affects SF Pro, Menlo, Monaco, Consolas, Verdana, Tahoma, Calibri, Cambria, Georgia, Palatino, and other OS-bundled fonts.++A secondary issue: compositions scaffolded by `hyperframes init` or wrapped by `ensureFullDocument` have no default `font-family`, so any text element without an explicit font declaration renders in the browser's default serif (Times New Roman), which is never the intended look.++---++## Requirements++- R1. Every common system font across macOS, Windows, and Linux must map to a bundled canonical font in `FONT_ALIASES` so it renders deterministically+- R2. The blank template must declare `Inter` (sans-serif) and `JetBrains Mono` (monospace) as default fonts+- R3. The `ensureFullDocument` CSS reset must include a default `font-family` so wrapped fragments don't fall back to Times New Roman+- R4. The `TEXT_STYLES` constant must use `Inter` instead of `system-ui, -apple-system, sans-serif`+- R5. The lint rule `font_family_without_font_face` must warn about system fonts that aren't in `FONT_ALIASES` — not just fonts missing `@font-face`+- R6. The `PRODUCER_BUNDLED_FONTS` set in the lint rule must stay in sync with `FONT_ALIASES`+- R7. Studio's local font list must annotate fonts that are aliased to a bundled font at render time, so users know what they'll get+- R8. All existing tests must pass; new tests must cover the expanded alias map++---++## Key Technical Decisions++**KTD-1. Alias mapping strategy — map to metrically closest bundled font, not to a "safe generic".**+System sans-serif fonts (SF Pro, Calibri, Verdana, Segoe UI) map to Inter. System monospace fonts (SF Mono, Menlo, Monaco, Consolas, Lucida Console) map to JetBrains Mono. System serif fonts (Georgia, Palatino, Book Antiqua, Cambria) map to EB Garamond. This preserves the author's intent (category + approximate weight) while guaranteeing deterministic rendering. Rationale: mapping everything to Inter would destroy monospace alignment and serif aesthetics.++**KTD-2. Single source of truth for alias data — `FONT_ALIASES` in `deterministicFonts.ts` remains canonical; `PRODUCER_BUNDLED_FONTS` is generated from it.**+Today these two structures are manually kept in sync. Rather than continuing that, export the alias keys from the producer and import them in the lint rule. This eliminates drift permanently.++**KTD-3. Default font in templates — Inter for body, JetBrains Mono for code.**+These are already in `CANONICAL_FONTS` with embedded data URIs. No new font packages needed. The deterministic injector will auto-inject their `@font-face` rules when it sees them in the CSS.++**KTD-4. Studio annotation approach — add a `renderAlias` field to local font entries rather than removing them.**+Users may genuinely want to preview with their local SF Pro. The annotation tells them "renders as Inter in video output" so they can make an informed choice. Removing the fonts would break the Studio experience for macOS users who work locally.++---++## Scope Boundaries++### In Scope+- Expanding `FONT_ALIASES` with ~30 additional system font mappings+- Updating the blank template, `ensureFullDocument`, and `TEXT_STYLES` defaults+- Making `PRODUCER_BUNDLED_FONTS` derive from the canonical alias map+- Enhancing lint rules to catch system fonts+- Studio font catalog annotation+- Tests for all of the above++### Out of Scope (Non-Goals)+- Font subsetting (noted in the codebase as "not yet implemented" — separate concern)+- Adding new canonical fonts to the bundle (Inter, JetBrains Mono, EB Garamond already cover all needed categories)+- CJK system font aliases (Noto Sans JP is already bundled; CJK system fonts like PingFang, Hiragino, MS Gothic are a different problem with different solutions)+- Studio font picker UI redesign++### Deferred to Follow-Up Work+- Auto-generating `PRODUCER_BUNDLED_FONTS` at build time from the producer package export (would require a build-order dependency change)++---++## Implementation Units++### U1. Expand FONT_ALIASES with cross-platform system font mappings++**Goal:** Every common system font on macOS, Windows, and Linux resolves to a bundled canonical font.++**Requirements:** R1++**Dependencies:** None++**Files:**+- `packages/producer/src/services/deterministicFonts.ts`+- `packages/producer/src/services/deterministicFonts.test.ts`++**Approach:** Add entries to `FONT_ALIASES` for the following system fonts, grouped by target canonical:++*Maps to `inter` (sans-serif):*+- SF Pro, SF Pro Display, SF Pro Text, SF Pro Rounded+- Avenir, Avenir Next+- Lucida Grande, Lucida Sans, Lucida Sans Unicode+- Verdana, Tahoma, Trebuchet MS+- Calibri, Candara, Corbel+- Ubuntu (the system font, not the Google Font — same name, so the alias makes it deterministic)+- Noto Sans, DejaVu Sans, Liberation Sans+- Geneva, Optima++*Maps to `jetbrains-mono` (monospace):*+- SF Mono+- Menlo+- Monaco+- Consolas+- Lucida Console, Lucida Sans Typewriter+- Andale Mono+- DejaVu Sans Mono, Liberation Mono+- Ubuntu Mono (system variant)++*Maps to `eb-garamond` (serif):*+- Georgia+- Palatino, Palatino Linotype, Book Antiqua+- Cambria+- Times, Times New Roman+- DejaVu Serif, Liberation Serif++Export the `FONT_ALIASES` keys as a `Set<string>` named `FONT_ALIAS_KEYS` so the lint rule can import it.++**Patterns to follow:** Existing alias entries at lines 156-188 of `deterministicFonts.ts`. All keys are lowercase.++**Test scenarios:**+- Each new alias resolves to the expected canonical font key+- SF Mono resolves to jetbrains-mono+- SF Pro Display resolves to inter+- Menlo resolves to jetbrains-mono+- Consolas resolves to jetbrains-mono+- Georgia resolves to eb-garamond+- Times New Roman resolves to eb-garamond+- Verdana resolves to inter+- The existing aliases still resolve correctly (no regressions)++**Verification:** `bun run --cwd packages/producer test` passes. The exported `FONT_ALIAS_KEYS` set contains all new entries.++---++### U2. Update default fonts in templates and CSS reset++**Goal:** Compositions start with Inter and JetBrains Mono as default fonts, not browser defaults.++**Requirements:** R2, R3, R4++**Dependencies:** None (independent of U1 — the deterministic injector already handles Inter and JetBrains Mono)++**Files:**+- `packages/cli/src/templates/blank/index.html`+- `packages/core/src/templates/constants.ts`+- `packages/producer/src/services/htmlCompiler.ts`+- `packages/core/src/templates/base.test.ts`+- `packages/producer/src/services/htmlCompiler.test.ts`++**Approach:**++1. **Blank template** — add a `<style>` block with:+ ```+ body { font-family: "Inter", sans-serif; }+ code, pre, .monospace { font-family: "JetBrains Mono", monospace; }+ ```++2. **`TEXT_STYLES` constant** — change `font-family: system-ui, -apple-system, sans-serif` to `font-family: "Inter", sans-serif`.++3. **`ensureFullDocument` CSS reset** — add `font-family:"Inter",sans-serif` to the `body` rule. The deterministic injector will see the `Inter` declaration and inject its `@font-face`.++**Patterns to follow:** The existing CSS reset style in `ensureFullDocument` at line 710.++**Test scenarios:**+- `TEXT_STYLES` contains `"Inter"` and does not contain `system-ui` or `-apple-system`+- The blank template HTML contains `font-family: "Inter"` in a style block+- The blank template HTML contains `font-family: "JetBrains Mono"` for monospace+- `ensureFullDocument` output contains `font-family:"Inter"` in the body style+- Existing `base.test.ts` assertions still pass (update the font-family expectation)+- Fragment wrapping produces a document whose body has `font-family:"Inter",sans-serif`++**Verification:** `bun run --cwd packages/core test` and `bun run --cwd packages/producer test` pass.++---++### U3. Sync PRODUCER_BUNDLED_FONTS with FONT_ALIASES via import++**Goal:** Eliminate manual drift between the alias map in the producer and the lint rule's bundled-font list.++**Requirements:** R6++**Dependencies:** U1 (needs the exported `FONT_ALIAS_KEYS`)++**Files:**+- `packages/core/src/lint/rules/fonts.ts`+- `packages/producer/src/services/deterministicFonts.ts` (export already added in U1)++**Approach:** Replace the hardcoded `PRODUCER_BUNDLED_FONTS` set in `fonts.ts` with an import from the producer package. The producer already exports `FONT_ALIAS_KEYS` (added in U1). The lint rule imports it and uses it directly.++Check if `@hyperframes/producer` is already a dependency of `@hyperframes/core`. If not, consider exporting the alias keys from `@hyperframes/core` instead (since the lint rules live in core) by moving the canonical alias list to a shared location in core and importing it in both the producer and the lint rule.++If a circular dependency would result, export the alias key list as a plain JSON-serializable array from a shared file in core that both packages import, keeping `deterministicFonts.ts` as the runtime consumer and the lint rule as the build-time consumer.++**Test scenarios:**+- The lint rule's bundled font set matches the producer's alias keys exactly+- Adding a new alias in `deterministicFonts.ts` automatically makes the lint rule recognize it (verified by the import chain, not a separate test)+- Existing lint rule tests pass without modification (the recognized font set is a superset of the old one)++**Verification:** `bun run --cwd packages/core test` passes. Manually verify that `PRODUCER_BUNDLED_FONTS` is no longer a hardcoded set.++---++### U4. Enhance lint rule to warn about unaliased system fonts++**Goal:** The linter catches system-only fonts that will silently fall back at render time.++**Requirements:** R5++**Dependencies:** U3 (needs the synced bundled font set)++**Files:**+- `packages/core/src/lint/rules/fonts.ts`+- `packages/core/src/lint/rules/fonts.test.ts`++**Approach:** Add a new lint rule `system_font_will_alias` (severity: info) that fires when a composition uses a font family that exists in `FONT_ALIAS_KEYS` but is NOT the canonical name (i.e., it will be silently mapped). The message tells the user what it will render as: "Font 'SF Mono' will render as 'JetBrains Mono' in video output. Use 'JetBrains Mono' directly for consistent preview/render results."++This is distinct from the existing `font_family_without_font_face` rule (which warns about fonts that can't be resolved at all). The new rule covers fonts that CAN be resolved but will be substituted — an informational heads-up, not a warning.++Also add a `SYSTEM_FONT_FAMILIES` set (fonts that exist only as OS installations, not in Google Fonts) to distinguish them from Google Fonts in the `font_family_without_font_face` rule. A system font without an alias is a harder error than a Google Font without an alias (the Google Font can be fetched; the system font cannot).++**Patterns to follow:** Existing lint rules in `fonts.ts`.++**Test scenarios:**+- A composition using `font-family: "SF Mono", monospace` triggers `system_font_will_alias` with message mentioning JetBrains Mono+- A composition using `font-family: "Inter", sans-serif` does NOT trigger `system_font_will_alias` (Inter is the canonical name)+- A composition using `font-family: "Helvetica Neue", sans-serif` triggers `system_font_will_alias` with message mentioning Inter+- A composition using `font-family: "Comic Sans MS", sans-serif` with no `@font-face` triggers `font_family_without_font_face` (not aliased, not a Google Font)+- A composition using `font-family: "Roboto", sans-serif` does NOT trigger any font rule (Roboto is a canonical bundled font)++**Verification:** `bun run --cwd packages/core test` passes.++---++### U5. Annotate Studio font catalog with render-time aliases++**Goal:** Studio users see what their local fonts will render as in video output.++**Requirements:** R7++**Dependencies:** U1 (needs the alias map data)++**Files:**+- `packages/studio/src/components/editor/fontCatalog.ts`+- `packages/studio/src/components/editor/propertyPanelHelpers.ts`++**Approach:** Add a `RENDER_ALIAS_MAP` to `fontCatalog.ts` that maps local font family names to their render-time canonical names. This is a static map (not imported from the producer, to avoid a build dependency) that covers the `COMMON_LOCAL_FONT_FAMILIES` entries. The property panel helpers use this map to display "(renders as Inter)" or "(renders as JetBrains Mono)" next to local font names in the font picker dropdown.++Update `COMMON_LOCAL_FONT_FAMILIES` to remove entries that are already in the Google Fonts list or the canonical bundled font list (no point listing "Arial" as a "local font" when Inter is the canonical and Arial is already aliased). Keep only the genuinely local fonts (TT Norms Pro, SF Pro Display, SF Pro Text, Avenir, Avenir Next, Menlo, Monaco) and add the render alias annotation.++**Patterns to follow:** Existing `COMMON_LOCAL_FONT_FAMILIES` structure and `sortFontOptions` in `propertyPanelHelpers.ts`.++**Test scenarios:**+- `RENDER_ALIAS_MAP` maps "SF Pro Display" to "Inter"+- `RENDER_ALIAS_MAP` maps "Menlo" to "JetBrains Mono"+- `RENDER_ALIAS_MAP` maps "Monaco" to "JetBrains Mono"+- `COMMON_LOCAL_FONT_FAMILIES` no longer contains fonts that are in the Google or canonical bundled lists (Arial, Courier New, Helvetica Neue)+- Font picker helper produces annotation text for aliased local fonts++**Verification:** `bun run build` succeeds (Studio type-checks). Manual check: Studio font picker shows alias annotations.++---++## Open Questions++- **OQ-1.** Should the deterministic font injector log a warning when it resolves an alias (e.g., "SF Mono → JetBrains Mono")? Currently it silently substitutes. A warning would help debugging but could be noisy for compositions that intentionally use system font names. *Deferred to implementation — start silent, add opt-in verbose logging if needed.*++---++## System-Wide Impact++- **Existing compositions using system fonts** will now render with the aliased canonical font instead of an unpredictable fallback. This is a visual change but an intentional improvement — the previous behavior was already broken (wrong font rendered).+- **New compositions** will start with Inter instead of no font. This only affects compositions that had no explicit font-family declarations.+- **Lint output** will show new `system_font_will_alias` findings for compositions using aliased fonts. Severity is info, not warning — won't block CI.+- **Docker/CI rendering** is unaffected (system fonts were already falling back; now they fall back to the correct aliased font instead of a random generic).++---++## Sources & Research++- `packages/producer/src/services/deterministicFonts.ts` — canonical font injection engine with FONT_ALIASES and CANONICAL_FONTS+- `packages/core/src/lint/rules/fonts.ts` — lint rules with PRODUCER_BUNDLED_FONTS+- `packages/core/src/templates/constants.ts` — TEXT_STYLES with system-ui default+- `packages/cli/src/templates/blank/index.html` — blank template with no font declarations+- `packages/producer/src/services/htmlCompiler.ts` — ensureFullDocument CSS reset with no font-family+- `packages/studio/src/components/editor/fontCatalog.ts` — Studio font catalog with COMMON_LOCAL_FONT_FAMILIES+- `packages/producer/src/services/render/planValidation.ts` — system font validation for distributed rendering+- macOS system fonts: SF Pro, SF Mono, Menlo, Monaco, Avenir, Lucida Grande, Geneva, Optima, Palatino, Georgia, Courier+- Windows system fonts: Segoe UI (already aliased), Calibri, Cambria, Consolas, Candara, Corbel, Verdana, Tahoma, Trebuchet MS, Georgia, Palatino Linotype, Book Antiqua, Lucida Console, Lucida Sans Unicode+- Linux system fonts: DejaVu Sans/Serif/Mono, Liberation Sans/Serif/Mono, Noto Sans/Serif, Ubuntu (font family)diff --git a/docs/plans/2026-06-07-004-feat-font-resolution-pipeline-plan.md b/docs/plans/2026-06-07-004-feat-font-resolution-pipeline-plan.mdnew file mode 100644index 0000000000..f25c92e32e--- /dev/null+++ b/docs/plans/2026-06-07-004-feat-font-resolution-pipeline-plan.md@@ -0,0 +1,314 @@+---+title: "feat: Font resolution pipeline — make compositions self-contained by capturing local and remote fonts"+status: active+type: feat+created: 2026-06-07+depth: Standard+origin: null+---++## Summary++Compositions that reference system fonts (SF Mono, Menlo, TT Norms Pro) or fonts hosted on non-Google CDNs currently fall through the deterministic font injector and render with unpredictable fallbacks. The alias map from the prior PR mitigates this for known system fonts, but it's lossy (Inter ≠ SF Pro metrics) and always incomplete. This plan adds a font resolution pipeline that captures the *actual font files* and embeds them, making compositions portable without aliasing. The alias map becomes the fallback for distributed renders where local font access doesn't exist.++---++## Problem Frame++The deterministic font injector resolves fonts through two paths: bundled aliases (18 canonical fonts) and Google Fonts fetch. Anything outside those two paths is unresolved — the font silently falls back at render time. Three categories of fonts hit this gap:++1. **System fonts not in the alias map** — commercial or niche fonts like TT Norms Pro, Frutiger, Proxima Nova that are installed locally but don't exist in Google Fonts and aren't aliased+2. **Fonts hosted on non-Google CDNs** — `<link>` tags pointing to S3, Cloudflare, or custom font servers whose stylesheets are never fetched and inlined by the compiler+3. **Any new system font** — every time Apple, Microsoft, or a Linux distro ships a new system font, the alias map needs a manual update++A font resolution pipeline that captures font files from the local filesystem eliminates categories 1 and 3 entirely. Extending `localizeRemoteFontFaces` to handle external stylesheets (not just @font-face src URLs) eliminates category 2.++---++## Requirements++- R1. The compiler must locate and embed local system font files (ttf/otf/woff2) as data URIs when a font-family isn't resolved by the bundled or Google Fonts paths+- R2. System font location must work on macOS (system_profiler + directory scan), Windows (C:\Windows\Fonts), and Linux (fontconfig fc-match + directory scan)+- R3. Font files must be compressed to woff2 before embedding to keep composition size reasonable (ttf → woff2 is typically 60-70% smaller)+- R4. External `<link rel="stylesheet">` tags pointing to non-Google font CDNs must have their stylesheets fetched, @font-face rules extracted, and font URLs inlined as data URIs+- R5. The resolution order must be: existing @font-face → bundled alias → Google Fonts → local system font → alias fallback → actionable error+- R6. Studio must auto-import system fonts when selected in the picker so the font file is part of the project from composition time (not deferred to render time)+- R7. All existing tests must pass; new tests must cover system font resolution, woff2 conversion, external stylesheet inlining, and the resolution order+- R8. System font capture must be skipped in distributed/Lambda renders (no local filesystem) — the alias map serves as fallback there++---++## Key Technical Decisions++**KTD-1. System font locator lives in `@hyperframes/core` as a shared module.**+Both the compiler (producer) and the Studio API (core) need to locate font files. The Studio API's `GET /fonts` endpoint already scans OS font directories but only returns family names. The new module extends this to return file paths, keyed by normalized family name. The Studio API re-exports it; the producer imports it for the capture step.++**KTD-2. woff2 compression via the `wawoff2` npm package (WASM-based).**+System fonts are typically ttf/otf (500KB-2MB per weight). Embedding raw ttf as data URIs would bloat compositions. `wawoff2` is a WASM port of Google's woff2 reference implementation — works cross-platform without native binaries, supports Node.js and Bun. Alternative considered: shelling out to `woff2_compress` (faster but requires system installation, fails on Lambda). `wawoff2` is the right tradeoff — zero system requirements, ~10ms per font file.++**KTD-3. System font capture is a new Path 3 inside `buildFontFaceCss`, after Google Fonts, before unresolved.**+This ordering ensures bundled fonts (zero-latency, deterministic) and Google Fonts (cached, consistent) take priority. System font capture is the fallback for fonts that can't be found anywhere else. The capture step only runs when `allowSystemFontCapture` is true (set by the compiler but not by distributed render adapters).++**KTD-4. External stylesheet inlining extends `localizeRemoteFontFaces` rather than creating a new pipeline step.**+The function already downloads remote font URLs from @font-face blocks. Extending it to also fetch external `<link rel="stylesheet">` content, extract @font-face rules, and inline their font URLs is a natural extension that keeps font localization in one place. Google Fonts `<link>` tags are excluded (the deterministic injector already handles those).++**KTD-5. Studio auto-import uses the server-side font locator via `GET /fonts/file` API.**+The browser's `window.queryLocalFonts()` API already triggers auto-import for Local-source fonts. For System-source fonts (from `DEFAULT_FONT_FAMILIES`), a new API endpoint `GET /fonts/file?family=<name>` returns the font file binary, which the Studio can then import into the project. This bridges the gap where the browser API is unavailable (Safari, Firefox) or the font isn't in the browser's Local Font Access list.++---++## High-Level Technical Design++```mermaid+flowchart TD+ A[font-family declaration in HTML] --> B{Has @font-face?}+ B -- yes --> Z[Done — use existing]+ B -- no --> C{In FONT_ALIAS_MAP?}+ C -- yes --> D[Emit bundled data URI]+ D --> D1[Fill weight gaps from Google Fonts]+ C -- no --> E{On Google Fonts?}+ E -- yes --> F[Fetch + cache + embed as data URI]+ E -- no --> G{allowSystemFontCapture?}+ G -- yes --> H{Found on local filesystem?}+ H -- yes --> I[Read file → woff2 compress → embed as data URI]+ H -- no --> J{In FONT_ALIAS_MAP as alias?}+ G -- no --> J+ J -- yes --> K[Use aliased bundled font — fallback]+ J -- no --> L[Unresolved — actionable error]++ style I fill:#2d6a4f,color:#fff+ style G fill:#264653,color:#fff+ style L fill:#9b2226,color:#fff+```++---++## Scope Boundaries++### In Scope+- System font locator module (macOS, Windows, Linux)+- woff2 compression integration+- New resolution path in `buildFontFaceCss`+- External stylesheet font inlining in `localizeRemoteFontFaces`+- Studio font file API endpoint+- Studio auto-import for system fonts+- Tests for all of the above++### Out of Scope (Non-Goals)+- Font subsetting (embedding only the glyphs used — separate optimization concern)+- Variable font axis resolution (the capture step embeds the full file as-is)+- CJK font capture (Noto CJK fonts are 15-20MB; embedding them as data URIs is impractical)+- Redistributing commercially licensed fonts in CI artifacts (the capture happens on the author's machine; the composition is a rendering artifact)++### Deferred to Follow-Up Work+- Font file caching across compositions (currently each composition embeds independently)+- Consolidating the four diverging `GENERIC_FAMILIES` sets into one shared module+- Runtime validation that all FONT_ALIAS_MAP values are valid CANONICAL_FONTS keys++---++## Implementation Units++### U1. System font locator module++**Goal:** Create a shared module that locates a font file on the local filesystem given a family name, returning the file path and format.++**Requirements:** R1, R2++**Dependencies:** None++**Files:**+- `packages/core/src/fonts/systemFontLocator.ts` (create)+- `packages/core/src/fonts/systemFontLocator.test.ts` (create)+- `packages/core/package.json` (add subpath export `./fonts/system-locator`)++**Approach:** Extract and extend the directory scanning logic from `packages/core/src/studio-api/routes/fonts.ts`. The existing `fontDirectories()` and `collectFontsFromDir` scan directories and derive family names from filenames. The new module adds:++- A `locateSystemFont(family: string)` function that returns `{ path: string; format: "ttf" | "otf" | "woff2" | "woff" } | null`+- On macOS: first try `system_profiler SPFontsDataType -json` to get authoritative file paths (the JSON includes `path` per typeface), fall back to directory scan+- On Windows: scan `%WINDIR%\Fonts` matching by filename-derived family name+- On Linux: first try `fc-match "<family>" --format="%{file}"` (fontconfig), fall back to directory scan+- Match by normalized family name (case-insensitive, style-suffix-stripped)+- Prefer woff2 > otf > ttf when multiple formats exist for the same family+- Cache results in a module-level Map (same pattern as the Studio API's `cachedFonts`)++**Patterns to follow:** `fontDirectories()` and `collectFontsFromDir` in `packages/core/src/studio-api/routes/fonts.ts`. `normalizeFamilyName` in `deterministicFonts.ts`.++**Test scenarios:**+- `locateSystemFont("Inter")` returns null on a system without Inter installed (or returns a path if installed — test should handle both)+- `locateSystemFont("nonexistent-font-xyz")` returns null+- `locateSystemFont` normalizes case: `"SF MONO"` matches the same as `"SF Mono"`+- On macOS (CI), `locateSystemFont("Helvetica")` returns a valid path under `/System/Library/Fonts/`+- The format detection correctly identifies `.ttf`, `.otf`, and `.woff2` extensions+- Directory scan respects max depth of 2 (matching existing pattern)+- Cache returns the same result on repeated calls without re-scanning++**Verification:** `bun run --cwd packages/core test` passes. Module exports are accessible via `@hyperframes/core/fonts/system-locator`.++---++### U2. woff2 compression capability++**Goal:** Add the ability to compress ttf/otf font files to woff2 format for efficient data URI embedding.++**Requirements:** R3++**Dependencies:** None (independent of U1)++**Files:**+- `packages/producer/package.json` (add `wawoff2` dependency)+- `packages/producer/src/services/fontCompression.ts` (create)+- `packages/producer/src/services/fontCompression.test.ts` (create)++**Approach:** Add the `wawoff2` npm package (WASM-based woff2 compressor). Create a thin wrapper:++- `compressToWoff2(input: Buffer): Promise<Buffer>` — compress a ttf/otf buffer to woff2+- `fontToDataUri(input: Buffer, originalFormat: string): Promise<string>` — compress if needed, then base64 encode as `data:font/woff2;base64,...`+- If the input is already woff2, skip compression and just encode+- Handle compression failures gracefully — fall back to embedding the raw format (`data:font/truetype;base64,...` for ttf) with a console warning++**Patterns to follow:** `fontDataUri()` in `deterministicFonts.ts` for the data URI encoding pattern.++**Test scenarios:**+- `compressToWoff2` accepts a ttf Buffer and returns a smaller woff2 Buffer+- `fontToDataUri` with a ttf input returns a `data:font/woff2;base64,...` string+- `fontToDataUri` with a woff2 input returns a `data:font/woff2;base64,...` string without re-compression+- `fontToDataUri` with an otf input returns a compressed woff2 data URI+- Compression failure falls back to raw format data URI with a warning++**Verification:** `bun run --cwd packages/producer test` passes. `wawoff2` is listed in dependencies.++---++### U3. System font resolution in buildFontFaceCss++**Goal:** Add a new resolution path that locates and embeds local system fonts when the bundled and Google Fonts paths fail.++**Requirements:** R1, R5, R8++**Dependencies:** U1, U2++**Files:**+- `packages/producer/src/services/deterministicFonts.ts` (modify `buildFontFaceCss` and `injectDeterministicFontFaces`)+- `packages/producer/src/services/deterministicFonts.test.ts` (extend)++**Approach:** Add a Path 3 inside `buildFontFaceCss`, after the Google Fonts fetch (Path 2) returns empty:++1. Check `options.allowSystemFontCapture` — if false (distributed render), skip to unresolved+2. Call `locateSystemFont(originalCaseFamily)` from the system font locator+3. If found: read the font file, call `fontToDataUri` to compress and encode, emit a single `@font-face` rule with the data URI+4. If not found: fall through to unresolved (existing behavior)++Add `allowSystemFontCapture: boolean` to `InjectDeterministicFontFacesOptions`. Default to `true` in `compileForRender` (local renders). Set to `false` in distributed render adapters (`packages/producer/src/services/render/` and `packages/aws-lambda/`).++**Patterns to follow:** The Google Fonts fetch path in `buildFontFaceCss` (Path 2). The `buildFontFaceRule` helper for emitting @font-face CSS.++**Test scenarios:**+- With `allowSystemFontCapture: true` and a font that exists on the local system, the function emits a @font-face rule with a data URI+- With `allowSystemFontCapture: false`, the system font path is skipped even if the font exists locally+- A font already covered by @font-face is not re-captured+- A font in FONT_ALIAS_MAP is resolved via the alias, not via system capture+- A font available on Google Fonts is resolved via Google, not via system capture+- A font not found anywhere (not aliased, not on Google, not on system) is added to the unresolved list+- The emitted @font-face rule has `font-display: block` (matching existing rules)+- The resolution order is verified: alias → Google → system → unresolved++**Verification:** `bun run --cwd packages/producer test` passes. Render a composition referencing a local-only font and confirm the @font-face rule appears in the compiled output.++---++### U4. External stylesheet font inlining++**Goal:** Fetch non-Google external `<link rel="stylesheet">` content, extract @font-face rules, and inline their font URLs as data URIs.++**Requirements:** R4++**Dependencies:** None (independent of U1-U3)++**Files:**+- `packages/producer/src/services/htmlCompiler.ts` (modify `localizeRemoteFontFaces`)+- `packages/producer/src/services/htmlCompiler.test.ts` (extend)++**Approach:** Extend `localizeRemoteFontFaces` to also handle external stylesheet `<link>` tags:++1. Before the existing @font-face URL scan, find all `<link rel="stylesheet" href="https://...">` tags in the HTML+2. Exclude Google Fonts URLs (already handled by the deterministic injector)+3. Fetch each external stylesheet's CSS content+4. Extract @font-face blocks from the fetched CSS+5. For each @font-face block, download the woff2/ttf URLs referenced in `src: url(...)`+6. Rewrite the CSS with local paths (same as existing behavior for @font-face URLs)+7. Inject the fetched @font-face rules into the HTML as a `<style>` block, replacing the `<link>` tag+8. Handle fetch failures gracefully — keep the `<link>` tag if the stylesheet can't be fetched (network access at render time is the fallback)++**Patterns to follow:** The existing `downloadAndRewriteUrls` helper. The `REMOTE_FONTFACE_URL_RE` pattern for extracting URLs from @font-face blocks.++**Test scenarios:**+- A `<link>` tag pointing to a non-Google font CDN is fetched, its @font-face rules are extracted, and font URLs are inlined+- A `<link>` tag pointing to Google Fonts is left untouched (handled by deterministic injector)+- A `<link>` tag that fails to fetch is kept in the HTML with a console warning+- Multiple `<link>` tags are processed independently+- The `<link>` tag is replaced with a `<style>` block containing the inlined @font-face rules+- Non-font `<link>` tags (rel="icon", rel="preconnect") are not touched++**Verification:** `bun run --cwd packages/producer test` passes. A composition with a `<link>` tag to a non-Google font CDN produces inlined @font-face rules in the compiled output.++---++### U5. Studio font file API and auto-import++**Goal:** Add a server-side API endpoint that returns font file binary data, and wire Studio's font picker to auto-import system fonts on selection.++**Requirements:** R6++**Dependencies:** U1 (needs system font locator)++**Files:**+- `packages/core/src/studio-api/routes/fonts.ts` (add `GET /fonts/file` route)+- `packages/studio/src/components/editor/propertyPanelFont.tsx` (modify `commitFamily` for System-source fonts)+- `packages/studio/src/components/editor/propertyPanelHelpers.ts` (no change expected)++**Approach:**++Server side: Add `GET /fonts/file?family=<name>` route that:+1. Calls `locateSystemFont(family)` from the shared locator module+2. If found: reads the file and returns it with appropriate Content-Type (`font/ttf`, `font/otf`, `font/woff2`) and Content-Disposition header+3. If not found: returns 404++Client side: In `commitFamily`, when `option.source === "System"` and the font is not a CSS generic (sans-serif, monospace, etc.):+1. Fetch `GET /fonts/file?family=<family>`+2. If the response is OK: create a File object from the blob, pass to `onImportFonts([file])`, inject the @font-face stylesheet+3. If 404 or error: fall through to existing behavior (just commit the font-family name)++This means system fonts selected in Studio become project-embedded files — the composition is self-contained before it ever reaches the compiler.++**Patterns to follow:** The existing `GET /fonts` and `GET /fonts/google` routes. The `importLocalFont` function in `propertyPanelFont.tsx` for the client-side import flow.++**Test scenarios:**+- `GET /fonts/file?family=Helvetica` returns a font file with correct Content-Type on macOS+- `GET /fonts/file?family=nonexistent` returns 404+- `GET /fonts/file` without a family parameter returns 400+- Studio: selecting a System-source font triggers a fetch to `/fonts/file` and imports the result+- Studio: selecting a System-source font that returns 404 falls through to commit the name directly+- Studio: selecting a CSS generic (sans-serif) does not trigger the font file fetch++**Verification:** `bun run build` succeeds. Studio font picker auto-imports system fonts on selection (manual verification).++---++## Risks & Dependencies++- **woff2 compression adds ~2MB to the producer package** (WASM binary). Acceptable for a build-time tool.+- **System font file paths vary by OS and version.** The locator uses multiple strategies (system_profiler, fontconfig, directory scan) to maximize coverage, but some fonts in unusual locations may not be found.+- **Font licensing** — system fonts like SF Pro are licensed for use on Apple platforms. Embedding them in a video composition (a static artifact rendered on the author's machine) is standard fair use, but the capture step should not redistribute font files to other machines. The `allowSystemFontCapture: false` flag in distributed renders prevents this.+- **Large font files** — some fonts (especially CJK families) are 15-20MB. CJK fonts are explicitly out of scope; a size cap (e.g., 5MB per font file) should be enforced to prevent accidentally embedding oversized files.++---++## Sources & Research++- `packages/core/src/studio-api/routes/fonts.ts` — existing OS font directory scanning+- `packages/cli/src/capture/fontMetadataExtractor.ts` — fontkit-based font metadata extraction+- `packages/producer/src/services/deterministicFonts.ts` — `injectDeterministicFontFaces` and `buildFontFaceCss` resolution pipeline+- `packages/producer/src/services/htmlCompiler.ts` — `localizeRemoteFontFaces`, `promoteCssImportsToLinkTags`, `compileForRender` font operation sequence+- `packages/studio/src/components/editor/propertyPanelFont.tsx` — Studio font picker with Local/System/Google sources+- `wawoff2` npm package — WASM-based woff2 compression, cross-platform, no native dependenciesdiff --git a/packages/cli/src/templates/blank/index.html b/packages/cli/src/templates/blank/index.htmlindex d9cd0d48b0..8ce4ea8cdd 100644--- a/packages/cli/src/templates/blank/index.html+++ b/packages/cli/src/templates/blank/index.html@@ -18,6 +18,14 @@overflow: hidden;background: #000;}+ body {+ font-family: "Inter", sans-serif;+ }+ code,+ pre,+ .monospace {+ font-family: "JetBrains Mono", monospace;+ }</style></head><body>diff --git a/packages/core/package.json b/packages/core/package.jsonindex ca8f8bfb6d..2df0bdf909 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -74,6 +74,14 @@"import": "./src/parsers/springEase.ts","types": "./src/parsers/springEase.ts"},+ "./fonts/aliases": {+ "import": "./src/fonts/aliases.ts",+ "types": "./src/fonts/aliases.ts"+ },+ "./fonts/system-locator": {+ "import": "./src/fonts/systemFontLocator.ts",+ "types": "./src/fonts/systemFontLocator.ts"+ },"./schemas/registry.json": "./schemas/registry.json","./schemas/registry-item.json": "./schemas/registry-item.json"},@@ -137,6 +145,14 @@"import": "./dist/parsers/springEase.js","types": "./dist/parsers/springEase.d.ts"},+ "./fonts/aliases": {+ "import": "./dist/fonts/aliases.js",+ "types": "./dist/fonts/aliases.d.ts"+ },+ "./fonts/system-locator": {+ "import": "./dist/fonts/systemFontLocator.js",+ "types": "./dist/fonts/systemFontLocator.d.ts"+ },"./schemas/registry.json": "./schemas/registry.json","./schemas/registry-item.json": "./schemas/registry-item.json"},diff --git a/packages/core/src/fonts/aliases.ts b/packages/core/src/fonts/aliases.tsnew file mode 100644index 0000000000..9328f0dc5a--- /dev/null+++ b/packages/core/src/fonts/aliases.ts@@ -0,0 +1,129 @@+/**+ * Single source of truth for the deterministic font alias map. Both the+ * producer's @font-face injector and the core lint rules import from here,+ * eliminating manual drift between the two.+ *+ * Keys are lowercase font family names. Values are canonical font slugs+ * matching CANONICAL_FONTS keys in the producer's deterministicFonts module.+ */+export const FONT_ALIAS_MAP = {+ // ── Canonical bundled fonts (self-referencing) ────────────────────────+ inter: "inter",+ montserrat: "montserrat",+ outfit: "outfit",+ nunito: "nunito",+ oswald: "oswald",+ "league gothic": "league-gothic",+ "archivo black": "archivo-black",+ "space mono": "space-mono",+ "ibm plex mono": "ibm-plex-mono",+ "jetbrains mono": "jetbrains-mono",+ "eb garamond": "eb-garamond",+ "playfair display": "playfair-display",+ "source code pro": "source-code-pro",+ "noto sans jp": "noto-sans-jp",+ roboto: "roboto",+ "open sans": "open-sans",+ lato: "lato",+ poppins: "poppins",++ // ── Common aliases → nearest canonical ────────────────────────────────+ "helvetica neue": "inter",+ helvetica: "inter",+ arial: "inter",+ "helvetica bold": "inter",+ futura: "montserrat",+ "din alternate": "montserrat",+ "arial black": "montserrat",+ "bebas neue": "league-gothic",+ "courier new": "jetbrains-mono",+ courier: "jetbrains-mono",+ garamond: "eb-garamond",+ "noto sans japanese": "noto-sans-jp",+ "segoe ui": "roboto",++ // ── macOS sans-serif system fonts → inter ─────────────────────────────+ "sf pro": "inter",+ "sf pro display": "inter",+ "sf pro text": "inter",+ "sf pro rounded": "inter",+ avenir: "inter",+ "avenir next": "inter",+ "lucida grande": "inter",+ geneva: "inter",+ optima: "inter",++ // ── Windows sans-serif system fonts → inter ───────────────────────────+ verdana: "inter",+ tahoma: "inter",+ "trebuchet ms": "inter",+ calibri: "inter",+ candara: "inter",+ corbel: "inter",+ "lucida sans": "inter",+ "lucida sans unicode": "inter",++ // ── Linux sans-serif system fonts → inter ─────────────────────────────+ "noto sans": "inter",+ "dejavu sans": "inter",+ "liberation sans": "inter",++ // ── Monospace system fonts → jetbrains-mono ───────────────────────────+ "sf mono": "jetbrains-mono",+ menlo: "jetbrains-mono",+ monaco: "jetbrains-mono",+ consolas: "jetbrains-mono",+ "lucida console": "jetbrains-mono",+ "lucida sans typewriter": "jetbrains-mono",+ "andale mono": "jetbrains-mono",+ "dejavu sans mono": "jetbrains-mono",+ "liberation mono": "jetbrains-mono",++ // ── Serif system fonts → eb-garamond ──────────────────────────────────+ georgia: "eb-garamond",+ palatino: "eb-garamond",+ "palatino linotype": "eb-garamond",+ "book antiqua": "eb-garamond",+ cambria: "eb-garamond",+ times: "eb-garamond",+ "times new roman": "eb-garamond",+ "dejavu serif": "eb-garamond",+ "liberation serif": "eb-garamond",+} satisfies Readonly<Record<string, string>>;++export const FONT_ALIAS_KEYS: ReadonlySet<string> = new Set(Object.keys(FONT_ALIAS_MAP));++/**+ * Human-readable display names for canonical font slugs. Used by the lint+ * rule to tell authors what their aliased font will render as.+ */+export const CANONICAL_FONT_DISPLAY_NAMES: Readonly<Record<string, string>> = {+ inter: "Inter",+ montserrat: "Montserrat",+ outfit: "Outfit",+ nunito: "Nunito",+ oswald: "Oswald",+ "league-gothic": "League Gothic",+ "archivo-black": "Archivo Black",+ "space-mono": "Space Mono",+ "ibm-plex-mono": "IBM Plex Mono",+ "jetbrains-mono": "JetBrains Mono",+ "eb-garamond": "EB Garamond",+ "playfair-display": "Playfair Display",+ "source-code-pro": "Source Code Pro",+ "noto-sans-jp": "Noto Sans JP",+ roboto: "Roboto",+ "open-sans": "Open Sans",+ lato: "Lato",+ poppins: "Poppins",+};++/**+ * Resolve a font alias to its canonical display name, or undefined if the+ * alias is not in the map.+ */+export function resolveAliasDisplayName(alias: string): string | undefined {+ const slug = (FONT_ALIAS_MAP as Record<string, string>)[alias.toLowerCase()];+ if (!slug) return undefined;+ return CANONICAL_FONT_DISPLAY_NAMES[slug];+}diff --git a/packages/core/src/fonts/systemFontLocator.test.ts b/packages/core/src/fonts/systemFontLocator.test.tsnew file mode 100644index 0000000000..374a23dc4a--- /dev/null+++ b/packages/core/src/fonts/systemFontLocator.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, beforeAll } from "vitest";+import {+ locateSystemFont,+ clearSystemFontCache,+ SYSTEM_FONT_SIZE_LIMIT,+} from "./systemFontLocator";++describe("systemFontLocator", { timeout: 15_000 }, () => {+ beforeAll(() => {+ clearSystemFontCache();+ });++ it("returns null for nonexistent fonts", () => {+ const result = locateSystemFont("nonexistent-font-xyz-12345");+ expect(result).toBeNull();+ });++ it("normalizes case when looking up fonts", () => {+ const lower = locateSystemFont("helvetica");+ const upper = locateSystemFont("HELVETICA");+ if (lower === null) {+ expect(upper).toBeNull();+ } else {+ expect(upper).not.toBeNull();+ expect(upper!.path).toBe(lower.path);+ }+ });++ it("returns a valid format field when a font is found", () => {+ const result =+ locateSystemFont("Helvetica") ?? locateSystemFont("Arial") ?? locateSystemFont("DejaVu Sans");+ if (result) {+ expect(["ttf", "otf", "woff2", "woff", "ttc"]).toContain(result.format);+ expect(result.path).toBeTruthy();+ }+ });++ it("caches results across calls", () => {+ const first = locateSystemFont("nonexistent-font-xyz-12345");+ const second = locateSystemFont("nonexistent-font-xyz-12345");+ expect(first).toBeNull();+ expect(second).toBeNull();+ });++ it("clearSystemFontCache resets the cache", () => {+ locateSystemFont("nonexistent-font-xyz-12345");+ clearSystemFontCache();+ const result = locateSystemFont("nonexistent-font-xyz-12345");+ expect(result).toBeNull();+ });++ it("exports SYSTEM_FONT_SIZE_LIMIT as 5MB", () => {+ expect(SYSTEM_FONT_SIZE_LIMIT).toBe(5 * 1024 * 1024);+ });++ it("strips quotes from family name input", () => {+ const result = locateSystemFont('"nonexistent-font-xyz-12345"');+ expect(result).toBeNull();+ });++ it("returns null for empty string", () => {+ expect(locateSystemFont("")).toBeNull();+ expect(locateSystemFont(" ")).toBeNull();+ });++ if (process.platform === "darwin") {+ it("finds Helvetica on macOS", () => {+ const result = locateSystemFont("Helvetica");+ expect(result).not.toBeNull();+ expect(result!.path).toMatch(/\.(ttf|ttc|otf)$/i);+ });++ it("finds Courier on macOS", () => {+ const result = locateSystemFont("Courier");+ expect(result).not.toBeNull();+ });+ }+});diff --git a/packages/core/src/fonts/systemFontLocator.ts b/packages/core/src/fonts/systemFontLocator.tsnew file mode 100644index 0000000000..341f08c8c1--- /dev/null+++ b/packages/core/src/fonts/systemFontLocator.ts@@ -0,0 +1,410 @@+import { execFileSync } from "node:child_process";+import { existsSync, lstatSync, readdirSync, realpathSync } from "node:fs";+import { homedir, platform } from "node:os";+import { join, resolve } from "node:path";++export const SYSTEM_FONT_SIZE_LIMIT = 5 * 1024 * 1024;++export type FontFileFormat = "ttf" | "otf" | "woff2" | "woff" | "ttc";++export interface LocatedFont {+ path: string;+ format: FontFileFormat;+}++export const FONT_EXT_RE = /\.(otf|ttf|ttc|woff2?)$/i;++const FORMAT_PRIORITY: Record<FontFileFormat, number> = {+ woff2: 0,+ otf: 1,+ ttf: 2,+ woff: 3,+ ttc: 4,+};++const STYLE_SUFFIXES = new Set([+ "black",+ "bold",+ "book",+ "condensed",+ "demi",+ "demibold",+ "display",+ "extra",+ "extrabold",+ "hairline",+ "heavy",+ "italic",+ "light",+ "medium",+ "normal",+ "regular",+ "roman",+ "semibold",+ "thin",+ "ultra",+ "ultralight",+]);++const REGULAR_TOKENS = new Set(["regular", "roman", "normal", "book"]);++const cache = new Map<string, LocatedFont | null>();++let allowedDirsCache: string[] | null = null;++function getAllowedFontDirs(): string[] {+ if (allowedDirsCache) return allowedDirsCache;+ allowedDirsCache = fontDirectories()+ .filter((d) => existsSync(d))+ .map((d) => {+ try {+ return realpathSync(d);+ } catch {+ return resolve(d);+ }+ });+ return allowedDirsCache;+}++function isPathBounded(filePath: string): boolean {+ try {+ const real = realpathSync(filePath);+ const allowed = getAllowedFontDirs();+ return allowed.some((dir) => real.startsWith(dir + "/") || real.startsWith(dir + "\\"));+ } catch {+ return false;+ }+}++function isRegularFile(filePath: string): boolean {+ try {+ const lst = lstatSync(filePath);+ if (lst.isSymbolicLink())+ return isPathBounded(filePath) && lstatSync(realpathSync(filePath)).isFile();+ return lst.isFile();+ } catch {+ return false;+ }+}++function normalizeName(name: string): string {+ return name+ .trim()+ .replace(/^['"]|['"]$/g, "")+ .trim()+ .toLowerCase();+}++function extensionToFormat(ext: string): FontFileFormat {+ const lower = ext.toLowerCase().replace(/^\./, "");+ if (lower === "woff2") return "woff2";+ if (lower === "woff") return "woff";+ if (lower === "otf") return "otf";+ if (lower === "ttc") return "ttc";+ return "ttf";+}++export function toFamilyName(fileName: string): string | null {+ const withoutExt = fileName.replace(FONT_EXT_RE, "");+ if (!withoutExt || withoutExt.startsWith(".")) return null;+ const spaced = withoutExt+ .replace(/[_-]+/g, " ")+ .replace(/([a-z])([A-Z])/g, "$1 $2")+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")+ .replace(/\s+/g, " ")+ .trim();+ const words = spaced.split(" ").filter(Boolean);+ while (words.length > 1 && STYLE_SUFFIXES.has((words.at(-1) ?? "").toLowerCase())) {+ words.pop();+ }+ const family = words.join(" ").trim();+ return family.length >= 2 ? family : null;+}++function isRegularWeight(fileName: string): boolean {+ const lower = fileName.toLowerCase();+ if (REGULAR_TOKENS.has(lower.replace(FONT_EXT_RE, "").split(/[-_ ]/).pop() ?? "")) return true;+ return !lower.includes("bold") && !lower.includes("italic") && !lower.includes("light");+}++export function fontDirectories(): string[] {+ const home = homedir();+ if (platform() === "darwin") {+ return [+ join(home, "Library", "Fonts"),+ "/Library/Fonts",+ "/System/Library/Fonts",+ "/System/Library/Fonts/Supplemental",+ ];+ }+ if (platform() === "win32") {+ return [+ join(process.env.WINDIR || "C:\\Windows", "Fonts"),+ join(+ process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"),+ "Microsoft",+ "Windows",+ "Fonts",+ ),+ ];+ }+ return [+ join(home, ".fonts"),+ join(home, ".local", "share", "fonts"),+ "/usr/local/share/fonts",+ "/usr/share/fonts",+ ];+}++export interface FontFileEntry {+ path: string;+ fileName: string;+ family: string;+}++/**+ * Iterates font files in a directory (up to `depth` 2) and yields each file's+ * path, filename, and derived family name. Shared by the font listing route+ * and the per-family locator to avoid duplicating the directory scan loop.+ */+export function collectFontFileEntries(dir: string, depth = 0): FontFileEntry[] {+ if (!existsSync(dir) || depth > 2) return [];+ const entries: FontFileEntry[] = [];++ try {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const fullPath = join(dir, entry.name);+ if (entry.isDirectory()) {+ entries.push(...collectFontFileEntries(fullPath, depth + 1));+ continue;+ }+ if (!FONT_EXT_RE.test(entry.name)) continue;+ if (!isRegularFile(fullPath)) continue;+ const family = toFamilyName(entry.name);+ if (family) entries.push({ path: fullPath, fileName: entry.name, family });+ }+ } catch {+ // Directory read failed — skip+ }++ return entries;+}++interface FontCandidate {+ path: string;+ format: FontFileFormat;+ isRegular: boolean;+}++function collectCandidatesFromDir(dir: string, targetFamily: string, depth = 0): FontCandidate[] {+ return collectFontFileEntries(dir, depth)+ .filter((e) => normalizeName(e.family) === targetFamily)+ .map((e) => {+ const ext = e.fileName.match(FONT_EXT_RE)?.[1] ?? "ttf";+ return {+ path: e.path,+ format: extensionToFormat(ext),+ isRegular: isRegularWeight(e.fileName),+ };+ });+}++function pickBestCandidate(candidates: FontCandidate[]): LocatedFont | null {+ if (candidates.length === 0) return null;+ candidates.sort((a, b) => {+ if (a.isRegular !== b.isRegular) return a.isRegular ? -1 : 1;+ return (FORMAT_PRIORITY[a.format] ?? 9) - (FORMAT_PRIORITY[b.format] ?? 9);+ });+ const best = candidates[0]!;+ return { path: best.path, format: best.format };+}++type SystemProfilerEntry = {+ family: string;+ path: string;+ format: FontFileFormat;+ isRegular: boolean;+};++let profilerCache: Map<string, SystemProfilerEntry[]> | null = null;++// fallow-ignore-next-line complexity+function getSystemProfilerIndex(): Map<string, SystemProfilerEntry[]> {+ if (profilerCache) return profilerCache;+ profilerCache = new Map();+ if (platform() !== "darwin") return profilerCache;++ try {+ const raw = execFileSync("system_profiler", ["SPFontsDataType", "-json"], {+ encoding: "utf8",+ maxBuffer: 12 * 1024 * 1024,+ timeout: 5000,+ });+ const parsed = JSON.parse(raw);+ if (!parsed?.SPFontsDataType || !Array.isArray(parsed.SPFontsDataType)) return profilerCache;++ for (const fontEntry of parsed.SPFontsDataType) {+ if (!fontEntry?.typefaces || !Array.isArray(fontEntry.typefaces)) continue;+ for (const typeface of fontEntry.typefaces) {+ if (!typeface) continue;+ const family = typeface.family ?? typeface.fullname ?? typeface._name;+ if (typeof family !== "string") continue;+ const filePath = typeface.path;+ if (typeof filePath !== "string" || !FONT_EXT_RE.test(filePath)) continue;+ const normalized = normalizeName(family);+ const ext = filePath.match(FONT_EXT_RE)?.[1] ?? "ttf";+ const entry: SystemProfilerEntry = {+ family: normalized,+ path: filePath,+ format: extensionToFormat(ext),+ isRegular: isRegularWeight(filePath),+ };+ const list = profilerCache.get(normalized) ?? [];+ list.push(entry);+ profilerCache.set(normalized, list);+ }+ }+ } catch {+ // system_profiler unavailable+ }++ return profilerCache;+}++function locateViaSystemProfiler(targetFamily: string): LocatedFont | null {+ const index = getSystemProfilerIndex();+ const entries = index.get(targetFamily);+ if (!entries || entries.length === 0) return null;++ const candidates: FontCandidate[] = entries+ .filter((e) => isRegularFile(e.path) && isPathBounded(e.path))+ .map((e) => ({ path: e.path, format: e.format, isRegular: e.isRegular }));++ return pickBestCandidate(candidates);+}++// fallow-ignore-next-line complexity+function locateViaFcMatch(targetFamily: string): LocatedFont | null {+ if (platform() !== "linux") return null;+ try {+ const result = execFileSync("fc-match", [targetFamily, "--format=%{file}"], {+ encoding: "utf8",+ timeout: 3000,+ }).trim();+ if (!result || !isRegularFile(result) || !isPathBounded(result)) return null;+ const fileName = result.split("/").pop() ?? "";+ const derivedFamily = toFamilyName(fileName);+ if (!derivedFamily || normalizeName(derivedFamily) !== targetFamily) return null;+ const ext = fileName.match(FONT_EXT_RE)?.[1] ?? "ttf";+ return { path: result, format: extensionToFormat(ext) };+ } catch {+ return null;+ }+}++export function locateSystemFont(family: string): LocatedFont | null {+ const normalized = normalizeName(family);+ if (!normalized) return null;++ const cached = cache.get(normalized);+ if (cached !== undefined) return cached;++ let result: LocatedFont | null = null;++ result = locateViaSystemProfiler(normalized);++ if (!result) {+ result = locateViaFcMatch(normalized);+ }++ if (!result) {+ const allCandidates: FontCandidate[] = [];+ for (const dir of fontDirectories()) {+ allCandidates.push(...collectCandidatesFromDir(dir, normalized));+ }+ result = pickBestCandidate(allCandidates);+ }++ cache.set(normalized, result);+ return result;+}++export interface LocatedFontVariant extends LocatedFont {+ weight: string;+ style: "normal" | "italic";+}++const WEIGHT_TOKENS: Record<string, string> = {+ thin: "100",+ hairline: "100",+ ultralight: "200",+ extralight: "200",+ light: "300",+ regular: "400",+ normal: "400",+ book: "400",+ roman: "400",+ medium: "500",+ demibold: "600",+ semibold: "600",+ bold: "700",+ extrabold: "800",+ ultrabold: "800",+ heavy: "800",+ black: "900",+ ultrablack: "950",+};++const WEIGHT_TOKENS_SORTED = Object.entries(WEIGHT_TOKENS).sort(([a], [b]) => b.length - a.length);++function inferWeightAndStyle(fileName: string): { weight: string; style: "normal" | "italic" } {+ const lower = fileName.toLowerCase().replace(FONT_EXT_RE, "");+ const style = lower.includes("italic") || lower.includes("oblique") ? "italic" : "normal";+ for (const [token, weight] of WEIGHT_TOKENS_SORTED) {+ if (lower.includes(token)) return { weight, style };+ }+ return { weight: "400", style };+}++export function locateSystemFontVariants(family: string): LocatedFontVariant[] {+ const normalized = normalizeName(family);+ if (!normalized) return [];++ const variants: LocatedFontVariant[] = [];++ const profilerIndex = getSystemProfilerIndex();+ const profilerEntries = profilerIndex.get(normalized);+ if (profilerEntries && profilerEntries.length > 0) {+ for (const e of profilerEntries) {+ if (!isRegularFile(e.path) || !isPathBounded(e.path)) continue;+ const { weight, style } = inferWeightAndStyle(e.path);+ variants.push({ path: e.path, format: e.format, weight, style });+ }+ if (variants.length > 0) return dedupeVariants(variants);+ }++ const allCandidates: FontCandidate[] = [];+ for (const dir of fontDirectories()) {+ allCandidates.push(...collectCandidatesFromDir(dir, normalized));+ }+ for (const c of allCandidates) {+ const { weight, style } = inferWeightAndStyle(c.path);+ variants.push({ path: c.path, format: c.format, weight, style });+ }+ return dedupeVariants(variants);+}++function dedupeVariants(variants: LocatedFontVariant[]): LocatedFontVariant[] {+ const seen = new Map<string, LocatedFontVariant>();+ for (const v of variants) {+ const key = `${v.weight}:${v.style}`;+ if (!seen.has(key)) seen.set(key, v);+ }+ return Array.from(seen.values());+}++export function clearSystemFontCache(): void {+ cache.clear();+ profilerCache = null;+ allowedDirsCache = null;+}diff --git a/packages/core/src/lint/rules/fonts.test.ts b/packages/core/src/lint/rules/fonts.test.tsindex 4bd21b2f98..a93433ffd0 100644--- a/packages/core/src/lint/rules/fonts.test.ts+++ b/packages/core/src/lint/rules/fonts.test.ts@@ -34,6 +34,84 @@ describe("font rules", () => {});});+ describe("system_font_will_alias", () => {+ it("flags SF Mono as aliased to JetBrains Mono", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>code { font-family: 'SF Mono', monospace; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(1);+ expect(findings[0]!.severity).toBe("info");+ expect(findings[0]!.message).toContain("JetBrains Mono");+ });++ it("flags Helvetica Neue as aliased to Inter", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>body { font-family: 'Helvetica Neue', sans-serif; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(1);+ expect(findings[0]!.message).toContain("Inter");+ });++ it("does not flag canonical font names", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>body { font-family: 'Inter', sans-serif; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(0);+ });++ it("does not flag Roboto (canonical name)", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>body { font-family: 'Roboto', sans-serif; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(0);+ });++ it("does not flag unknown fonts (handled by font_family_without_font_face)", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>body { font-family: 'Comic Sans MS', sans-serif; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(0);+ });++ it("does not flag aliased fonts that have explicit @font-face", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>+ @font-face { font-family: 'Menlo'; src: url('../fonts/menlo.woff2'); }+ code { font-family: 'Menlo', monospace; }+ </style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(0);+ });++ it("handles case-insensitive font names", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>body { font-family: 'VERDANA', sans-serif; }</style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(1);+ expect(findings[0]!.message).toContain("Inter");+ });++ it("reports multiple aliased fonts in one finding", async () => {+ const html = `<div data-composition-id="test" data-width="1920" data-height="1080">+ <style>+ body { font-family: 'Verdana', sans-serif; }+ code { font-family: 'Consolas', monospace; }+ </style>+ </div>`;+ const findings = await findByCode(html, "system_font_will_alias");+ expect(findings).toHaveLength(1);+ expect(findings[0]!.message).toContain("Inter");+ expect(findings[0]!.message).toContain("JetBrains Mono");+ });+ });+describe("font_family_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">diff --git a/packages/core/src/lint/rules/fonts.ts b/packages/core/src/lint/rules/fonts.tsindex 05a5e0db2b..33ae5e8164 100644--- a/packages/core/src/lint/rules/fonts.ts+++ b/packages/core/src/lint/rules/fonts.ts@@ -1,3 +1,4 @@+import { FONT_ALIAS_KEYS, resolveAliasDisplayName } from "../../fonts/aliases";import type { LintContext, HyperframeLintFinding } from "../context";const GENERIC_FAMILIES = new Set([@@ -20,43 +21,6 @@ const GENERIC_FAMILIES = new Set(["revert",]);-// Fonts pre-bundled as data URIs in the producer (deterministicFonts.ts FONT_ALIASES).-// These render correctly without @font-face — the producer injects them automatically.-// Must match the keys in packages/producer/src/services/deterministicFonts.ts exactly.-const PRODUCER_BUNDLED_FONTS = new Set([- "inter",- "helvetica neue",- "helvetica",- "arial",- "helvetica bold",- "montserrat",- "futura",- "din alternate",- "arial black",- "outfit",- "nunito",- "oswald",- "bebas neue",- "league gothic",- "archivo black",- "space mono",- "ibm plex mono",- "jetbrains mono",- "courier new",- "courier",- "eb garamond",- "garamond",- "playfair display",- "source code pro",- "noto sans jp",- "noto sans japanese",- "roboto",- "open sans",- "lato",- "poppins",- "segoe ui",-]);-function extractFontFaceFamilies(styles: Array<{ content: string }>): Set<string> {const families = new Set<string>();const fontFaceRe = /@font-face\s*\{[^}]*\}/gi;@@ -98,6 +62,18 @@ function extractUsedFontFamilies(styles: Array<{ content: string }>): string[] {return used;}+function collectAliasedFonts(used: string[], declared: Set<string>): string[] {+ const aliased: string[] = [];+ for (const name of used) {+ if (declared.has(name)) continue;+ const displayName = resolveAliasDisplayName(name);+ if (!displayName) continue;+ if (displayName.toLowerCase() === name) continue;+ aliased.push(`'${name}' → ${displayName}`);+ }+ return aliased;+}+export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [// google_fonts_import({ styles, source }) => {@@ -123,15 +99,36 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [return findings;},+ // system_font_will_alias — inform when a font will be silently substituted+ ({ styles, options }) => {+ const declared = extractFontFaceFamilies(styles);+ const used = extractUsedFontFamilies(styles);+ const aliased = collectAliasedFonts(used, declared);+ if (aliased.length === 0) return [];+ // In distributed / Lambda renders system-font capture is disabled, so+ // the alias substitution does NOT happen — elevate to a warning.+ const severity = options.distributed ? ("warning" as const) : ("info" as const);+ return [+ {+ code: "system_font_will_alias",+ severity,+ message:+ `Font ${aliased.length === 1 ? "family" : "families"} will be substituted at render time: ${aliased.join(", ")}. ` ++ (options.distributed+ ? "In distributed/Lambda rendering system-font capture is disabled — these fonts will fall back to OS defaults. Embed explicit @font-face declarations instead."+ : "The renderer maps these to bundled fonts for cross-platform consistency. " ++ "Use the target font name directly for consistent preview and render results."),+ },+ ];+ },+// font_family_without_font_face({ styles }) => {const findings: HyperframeLintFinding[] = [];const declared = extractFontFaceFamilies(styles);const used = extractUsedFontFamilies(styles);- const undeclared = used.filter(- (name) => !declared.has(name) && !PRODUCER_BUNDLED_FONTS.has(name),- );+ const undeclared = used.filter((name) => !declared.has(name) && !FONT_ALIAS_KEYS.has(name));if (undeclared.length === 0) return findings;findings.push({diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.tsindex e468a348e0..8911566f93 100644--- a/packages/core/src/lint/types.ts+++ b/packages/core/src/lint/types.ts@@ -23,6 +23,14 @@ export type HyperframeLinterOptions = {filePath?: string;isSubComposition?: boolean;externalStyles?: Array<{ href: string; content: string }>;+ /**+ * Set to `true` when linting compositions destined for distributed / Lambda+ * rendering, where system-font capture (`allowSystemFontCapture`) is+ * disabled. When `true`, the `system_font_will_alias` rule is elevated from+ * `"info"` to `"warning"` because the alias substitution will NOT happen at+ * render time — the font will silently fall back to whatever the OS provides.+ */+ distributed?: boolean;};// A rule is a function: receives parsed context, returns zero or more findings.diff --git a/packages/core/src/studio-api/routes/fonts.ts b/packages/core/src/studio-api/routes/fonts.tsindex 256a6acc91..9514bab593 100644--- a/packages/core/src/studio-api/routes/fonts.ts+++ b/packages/core/src/studio-api/routes/fonts.ts@@ -1,40 +1,20 @@import { execFileSync } from "node:child_process";-import { existsSync, readdirSync, statSync } from "node:fs";-import { homedir, platform } from "node:os";-import { join } from "node:path";+import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";+import { platform } from "node:os";import type { Hono } from "hono";+import {+ collectFontFileEntries,+ fontDirectories,+ locateSystemFont,+ SYSTEM_FONT_SIZE_LIMIT,+} from "../../fonts/systemFontLocator";-const FONT_EXT_RE = /\.(otf|ttf|ttc|woff2?)$/i;const MAX_FONT_RESULTS = 2000;const GOOGLE_FONTS_METADATA_URL = "https://fonts.google.com/metadata/fonts";const GOOGLE_FONTS_FETCH_TIMEOUT_MS = 3000;let cachedFonts: string[] | null = null;let cachedGoogleFonts: string[] | null = null;-const STYLE_SUFFIXES = new Set([- "black",- "bold",- "book",- "condensed",- "demi",- "demibold",- "display",- "extra",- "extrabold",- "hairline",- "heavy",- "italic",- "light",- "medium",- "normal",- "regular",- "roman",- "semibold",- "thin",- "ultra",- "ultralight",-]);-const GOOGLE_FONT_FALLBACKS = ["Inter","Roboto",@@ -62,46 +42,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null;}-function fontDirectories(): string[] {- const home = homedir();- if (platform() === "darwin") {- return [- join(home, "Library", "Fonts"),- "/Library/Fonts",- "/System/Library/Fonts",- "/System/Library/Fonts/Supplemental",- ];- }- if (platform() === "win32") {- return [join(process.env.WINDIR || "C:\\Windows", "Fonts")];- }- return [- join(home, ".fonts"),- join(home, ".local", "share", "fonts"),- "/usr/local/share/fonts",- "/usr/share/fonts",- ];-}--function toFamilyName(fileName: string): string | null {- const withoutExt = fileName.replace(FONT_EXT_RE, "");- if (!withoutExt || withoutExt.startsWith(".")) return null;-- const spaced = withoutExt- .replace(/[_-]+/g, " ")- .replace(/([a-z])([A-Z])/g, "$1 $2")- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")- .replace(/\s+/g, " ")- .trim();- const words = spaced.split(" ").filter(Boolean);- while (words.length > 1 && STYLE_SUFFIXES.has((words.at(-1) ?? "").toLowerCase())) {- words.pop();- }-- const family = words.join(" ").trim();- return family.length >= 2 ? family : null;-}-function collectMacSystemProfilerFonts(): string[] {if (platform() !== "darwin") return [];@@ -143,27 +83,8 @@ function collectMacSystemProfilerFonts(): string[] {return fonts;}-function collectFontsFromDir(dir: string, depth = 0): string[] {- if (!existsSync(dir) || depth > 2) return [];- const fonts: string[] = [];-- for (const entry of readdirSync(dir, { withFileTypes: true })) {- const fullPath = join(dir, entry.name);- if (entry.isDirectory()) {- fonts.push(...collectFontsFromDir(fullPath, depth + 1));- continue;- }- if (!entry.isFile() || !FONT_EXT_RE.test(entry.name)) continue;- try {- if (!statSync(fullPath).isFile()) continue;- } catch {- continue;- }- const family = toFamilyName(entry.name);- if (family) fonts.push(family);- }-- return fonts;+function collectFontsFromDir(dir: string): string[] {+ return collectFontFileEntries(dir).map((e) => e.family);}function listInstalledFontFamilies(): string[] {@@ -244,4 +165,50 @@ async function listGoogleFontFamilies(): Promise<string[]> {export function registerFontRoutes(api: Hono): void {api.get("/fonts", (c) => c.json({ fonts: listInstalledFontFamilies() }));api.get("/fonts/google", async (c) => c.json({ fonts: await listGoogleFontFamilies() }));++ // fallow-ignore-next-line complexity+ api.get("/fonts/file", (c) => {+ const family = c.req.query("family");+ if (!family) return c.json({ error: "family parameter required" }, 400);++ const located = locateSystemFont(family);+ if (!located) return c.json({ error: "font not found" }, 404);++ let fd: number;+ try {+ fd = openSync(located.path, constants.O_RDONLY | constants.O_NOFOLLOW);+ } catch {+ return c.json({ error: "font file not accessible" }, 404);+ }+ try {+ const stat = fstatSync(fd);+ if (stat.size > SYSTEM_FONT_SIZE_LIMIT) {+ return c.json({ error: "font file too large" }, 413);+ }+ const buffer = Buffer.alloc(stat.size);+ readSync(fd, buffer, 0, stat.size, 0);+ const mimeType =+ located.format === "otf"+ ? "font/otf"+ : located.format === "woff2"+ ? "font/woff2"+ : located.format === "woff"+ ? "font/woff"+ : located.format === "ttc"+ ? "font/collection"+ : "font/ttf";++ const fileName = `${family.replace(/[^a-zA-Z0-9 -]/g, "")}.${located.format}`;+ return new Response(buffer, {+ headers: {+ "Content-Type": mimeType,+ "Content-Disposition": `attachment; filename="${fileName}"`,+ },+ });+ } catch {+ return c.json({ error: "failed to read font file" }, 500);+ } finally {+ closeSync(fd);+ }+ });}diff --git a/packages/core/src/templates/base.test.ts b/packages/core/src/templates/base.test.tsindex ec1b6b9fc9..a6dd8dc1d3 100644--- a/packages/core/src/templates/base.test.ts+++ b/packages/core/src/templates/base.test.ts@@ -100,6 +100,7 @@ describe("constants", () => {});it("TEXT_STYLES includes font and alignment", () => {+ expect(TEXT_STYLES).toContain('font-family: "Inter"');expect(TEXT_STYLES).toContain("font-size: 48px");expect(TEXT_STYLES).toContain("font-weight: bold");expect(TEXT_STYLES).toContain("color: white");diff --git a/packages/core/src/templates/constants.ts b/packages/core/src/templates/constants.tsindex eabb04fbb1..787d4b1391 100644--- a/packages/core/src/templates/constants.ts+++ b/packages/core/src/templates/constants.ts@@ -7,6 +7,6 @@ export const ELEMENT_BASE_STYLES = `position: absolute; visibility: hidden;`;export const MEDIA_STYLES = `width: 100%; height: 100%; object-fit: contain;`;-export const TEXT_STYLES = `display: flex; align-items: center; justify-content: center; font-family: system-ui, -apple-system, sans-serif; font-size: 48px; font-weight: bold; color: white; text-shadow: 2px 2px 4px rgba(0,0,0,0.8); width: 100%; height: 100%;`;+export const TEXT_STYLES = `display: flex; align-items: center; justify-content: center; font-family: "Inter", sans-serif; font-size: 48px; font-weight: bold; color: white; text-shadow: 2px 2px 4px rgba(0,0,0,0.8); width: 100%; height: 100%;`;export const ZOOM_CONTAINER_STYLES = `position: absolute; inset: 0; transform-origin: 0 0;`;diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.tsindex 5c16e9b1dc..ef26a6a009 100644--- a/packages/engine/src/index.ts+++ b/packages/engine/src/index.ts@@ -188,7 +188,7 @@ export {type KeyframeAnalysis,} from "./utils/ffprobe.js";-export { downloadToTemp, isHttpUrl } from "./utils/urlDownloader.js";+export { assertPublicHttpsUrl, downloadToTemp, isHttpUrl } from "./utils/urlDownloader.js";export {runFfmpeg,formatFfmpegError,diff --git a/packages/producer/build.mjs b/packages/producer/build.mjsindex b2f4d4fb89..7b4cacbf6c 100644--- a/packages/producer/build.mjs+++ b/packages/producer/build.mjs@@ -42,7 +42,7 @@ await Promise.all([platform: "node",target: "node22",format: "esm",- external: ["puppeteer", "esbuild", "postcss"],+ external: ["puppeteer", "esbuild", "postcss", "wawoff2"],plugins: [workspaceAliasPlugin],minify: false,sourcemap: true,@@ -54,7 +54,7 @@ await Promise.all([platform: "node",target: "node22",format: "esm",- external: ["puppeteer", "esbuild", "postcss"],+ external: ["puppeteer", "esbuild", "postcss", "wawoff2"],plugins: [workspaceAliasPlugin],minify: false,sourcemap: true,@@ -70,7 +70,7 @@ await Promise.all([platform: "node",target: "node22",format: "esm",- external: ["puppeteer", "esbuild", "postcss"],+ external: ["puppeteer", "esbuild", "postcss", "wawoff2"],plugins: [workspaceAliasPlugin],minify: false,sourcemap: true,@@ -86,7 +86,7 @@ await Promise.all([platform: "node",target: "node22",format: "esm",- external: ["puppeteer", "esbuild", "postcss"],+ external: ["puppeteer", "esbuild", "postcss", "wawoff2"],plugins: [workspaceAliasPlugin],minify: false,sourcemap: true,@@ -103,7 +103,7 @@ await Promise.all([platform: "node",target: "node22",format: "esm",- external: ["puppeteer", "esbuild", "postcss"],+ external: ["puppeteer", "esbuild", "postcss", "wawoff2"],plugins: [workspaceAliasPlugin],minify: false,sourcemap: true,diff --git a/packages/producer/package.json b/packages/producer/package.jsonindex de992e0a5a..2b1edf373a 100644--- a/packages/producer/package.json+++ b/packages/producer/package.json@@ -74,7 +74,8 @@"linkedom": "^0.18.12","postcss": "^8.4.0","puppeteer": "^24.0.0",- "puppeteer-core": "^24.39.1"+ "puppeteer-core": "^24.39.1",+ "wawoff2": "^2.0.1"},"devDependencies": {"@fontsource/lato": "^5.2.7",diff --git a/packages/producer/src/services/deterministicFonts-systemCapture.test.ts b/packages/producer/src/services/deterministicFonts-systemCapture.test.tsnew file mode 100644index 0000000000..e04117d576--- /dev/null+++ b/packages/producer/src/services/deterministicFonts-systemCapture.test.ts@@ -0,0 +1,112 @@+/**+ * Tests for the system font capture path (Path 3) in `buildFontFaceCss`.+ *+ * When a font family is not in FONT_ALIASES and not served by Google Fonts,+ * the resolver can locate it on the local filesystem, compress to woff2,+ * and embed it as a data URI. This path is controlled by the+ * `allowSystemFontCapture` option.+ *+ * Tests inject `fetchImpl` to simulate Google Fonts returning 400 (family+ * not served) so the resolver falls through to the system font path.+ */++import { describe, expect, it } from "bun:test";+import { existsSync } from "node:fs";+import { injectDeterministicFontFaces } from "./deterministicFonts.js";++// A font family that is NOT in FONT_ALIASES but exists on macOS as+// /System/Library/Fonts/Supplemental/Impact.ttf. When Google Fonts+// returns 400 for it, the system font locator should find it locally.+const SYSTEM_ONLY_FONT = "Impact";+const SYSTEM_ONLY_FONT_PATH = "/System/Library/Fonts/Supplemental/Impact.ttf";++function makeHtml(fontFamily: string): string {+ return `<!doctype html>+<html><head><style>+ body { font-family: "${fontFamily}", sans-serif; }+</style></head>+<body><h1>test</h1></body>+</html>`;+}++/** Google Fonts returns 400 for families it doesn't serve. */+function makeHttp400Fetch(): typeof fetch {+ return (async () =>+ new Response("", { status: 400, statusText: "Bad Request" })) as unknown as typeof fetch;+}++describe("system font capture — allowSystemFontCapture option", () => {+ it("does not attempt system font capture when allowSystemFontCapture is false", async () => {+ const html = makeHtml("NotARealFontFamilyForTest");+ const result = await injectDeterministicFontFaces(html, {+ fetchImpl: makeHttp400Fetch(),+ allowSystemFontCapture: false,+ });+ // No @font-face injected — the font is unresolved.+ expect(result.includes("data-hyperframes-deterministic-fonts")).toBe(false);+ });++ it("defaults allowSystemFontCapture to true when omitted", async () => {+ // Even without an explicit `allowSystemFontCapture`, the default is+ // `true` (`options.allowSystemFontCapture !== false`). We test this+ // with a non-existent font — the locator won't find it, so no+ // @font-face is injected, but importantly we verify it doesn't throw.+ const html = makeHtml("ZZZDefinitelyNotInstalledAnywhere");+ const result = await injectDeterministicFontFaces(html, {+ fetchImpl: makeHttp400Fetch(),+ // allowSystemFontCapture intentionally omitted+ });+ expect(result.includes("data-hyperframes-deterministic-fonts")).toBe(false);+ }, 15_000); // The system font locator runs system_profiler on macOS which can take >5s.+});++describe("system font capture — integration (macOS only)", () => {+ const hasFontLocally = existsSync(SYSTEM_ONLY_FONT_PATH);++ it("embeds a local system font when Google Fonts returns 400", async () => {+ if (!hasFontLocally) {+ console.warn(`Skipping: ${SYSTEM_ONLY_FONT_PATH} not available`);+ return;+ }++ const html = makeHtml(SYSTEM_ONLY_FONT);+ const result = await injectDeterministicFontFaces(html, {+ fetchImpl: makeHttp400Fetch(),+ allowSystemFontCapture: true,+ });++ // The system font was found and embedded as a data URI.+ expect(result).toContain("data-hyperframes-deterministic-fonts");+ expect(result).toContain(`font-family: "${SYSTEM_ONLY_FONT}"`);+ expect(result).toContain("data:font/woff2;base64,");+ });++ it("skips system font capture when allowSystemFontCapture is false even if font exists locally", async () => {+ if (!hasFontLocally) {+ console.warn(`Skipping: ${SYSTEM_ONLY_FONT_PATH} not available`);+ return;+ }++ const html = makeHtml(SYSTEM_ONLY_FONT);+ const result = await injectDeterministicFontFaces(html, {+ fetchImpl: makeHttp400Fetch(),+ allowSystemFontCapture: false,+ });++ // System font capture disabled — font stays unresolved.+ expect(result.includes("data-hyperframes-deterministic-fonts")).toBe(false);+ });++ it("still resolves alias-mapped fonts via embedded bundle regardless of allowSystemFontCapture", async () => {+ // "Inter" is in FONT_ALIASES → resolved via embedded bundle, not system font capture.+ const html = makeHtml("Inter");+ const result = await injectDeterministicFontFaces(html, {+ fetchImpl: makeHttp400Fetch(),+ allowSystemFontCapture: false,+ });++ // Even with system font capture disabled, Inter resolves via the alias map.+ expect(result).toContain("data-hyperframes-deterministic-fonts");+ expect(result).toContain('font-family: "Inter"');+ });+});diff --git a/packages/producer/src/services/deterministicFonts.test.ts b/packages/producer/src/services/deterministicFonts.test.tsnew file mode 100644index 0000000000..3dabac055a--- /dev/null+++ b/packages/producer/src/services/deterministicFonts.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "bun:test";+import { FONT_ALIASES, FONT_ALIAS_KEYS } from "./deterministicFonts.js";++describe("FONT_ALIASES cross-platform coverage", () => {+ it("maps macOS sans-serif system fonts to inter", () => {+ expect(FONT_ALIASES["sf pro"]).toBe("inter");+ expect(FONT_ALIASES["sf pro display"]).toBe("inter");+ expect(FONT_ALIASES["sf pro text"]).toBe("inter");+ expect(FONT_ALIASES["sf pro rounded"]).toBe("inter");+ expect(FONT_ALIASES["avenir"]).toBe("inter");+ expect(FONT_ALIASES["avenir next"]).toBe("inter");+ expect(FONT_ALIASES["geneva"]).toBe("inter");+ expect(FONT_ALIASES["optima"]).toBe("inter");+ expect(FONT_ALIASES["lucida grande"]).toBe("inter");+ });++ it("maps Windows sans-serif system fonts to inter", () => {+ expect(FONT_ALIASES["calibri"]).toBe("inter");+ expect(FONT_ALIASES["candara"]).toBe("inter");+ expect(FONT_ALIASES["corbel"]).toBe("inter");+ expect(FONT_ALIASES["verdana"]).toBe("inter");+ expect(FONT_ALIASES["tahoma"]).toBe("inter");+ expect(FONT_ALIASES["trebuchet ms"]).toBe("inter");+ expect(FONT_ALIASES["lucida sans"]).toBe("inter");+ expect(FONT_ALIASES["lucida sans unicode"]).toBe("inter");+ });++ it("maps Linux sans-serif system fonts to inter", () => {+ expect(FONT_ALIASES["noto sans"]).toBe("inter");+ expect(FONT_ALIASES["dejavu sans"]).toBe("inter");+ expect(FONT_ALIASES["liberation sans"]).toBe("inter");+ });++ it("maps monospace system fonts to jetbrains-mono", () => {+ expect(FONT_ALIASES["sf mono"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["menlo"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["monaco"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["consolas"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["lucida console"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["lucida sans typewriter"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["andale mono"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["dejavu sans mono"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["liberation mono"]).toBe("jetbrains-mono");+ });++ it("maps serif system fonts to eb-garamond", () => {+ expect(FONT_ALIASES["georgia"]).toBe("eb-garamond");+ expect(FONT_ALIASES["palatino"]).toBe("eb-garamond");+ expect(FONT_ALIASES["palatino linotype"]).toBe("eb-garamond");+ expect(FONT_ALIASES["book antiqua"]).toBe("eb-garamond");+ expect(FONT_ALIASES["cambria"]).toBe("eb-garamond");+ expect(FONT_ALIASES["times"]).toBe("eb-garamond");+ expect(FONT_ALIASES["times new roman"]).toBe("eb-garamond");+ expect(FONT_ALIASES["dejavu serif"]).toBe("eb-garamond");+ expect(FONT_ALIASES["liberation serif"]).toBe("eb-garamond");+ });++ it("preserves all existing aliases", () => {+ expect(FONT_ALIASES["helvetica neue"]).toBe("inter");+ expect(FONT_ALIASES["arial"]).toBe("inter");+ expect(FONT_ALIASES["courier new"]).toBe("jetbrains-mono");+ expect(FONT_ALIASES["segoe ui"]).toBe("roboto");+ expect(FONT_ALIASES["futura"]).toBe("montserrat");+ expect(FONT_ALIASES["bebas neue"]).toBe("league-gothic");+ });++ it("exports FONT_ALIAS_KEYS containing all alias entries", () => {+ expect(FONT_ALIAS_KEYS).toBeInstanceOf(Set);+ expect(FONT_ALIAS_KEYS.has("sf mono")).toBe(true);+ expect(FONT_ALIAS_KEYS.has("menlo")).toBe(true);+ expect(FONT_ALIAS_KEYS.has("consolas")).toBe(true);+ expect(FONT_ALIAS_KEYS.has("inter")).toBe(true);+ expect(FONT_ALIAS_KEYS.size).toBe(Object.keys(FONT_ALIASES).length);+ });+});diff --git a/packages/producer/src/services/deterministicFonts.ts b/packages/producer/src/services/deterministicFonts.tsindex 27f2dbd397..61e2b4e6ed 100644--- a/packages/producer/src/services/deterministicFonts.ts+++ b/packages/producer/src/services/deterministicFonts.ts@@ -2,9 +2,16 @@ import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join } from "node:path";+import { defaultLogger } from "../logger.js";+import { FONT_ALIAS_MAP } from "@hyperframes/core/fonts/aliases";+import {+ locateSystemFontVariants,+ SYSTEM_FONT_SIZE_LIMIT,+} from "@hyperframes/core/fonts/system-locator";import { parseHTML } from "linkedom";import { EMBEDDED_FONT_DATA } from "./fontData.generated.js";+import { fontToDataUri } from "./fontCompression.js";type FontFaceSpec = {weight: string;@@ -153,39 +160,11 @@ const CANONICAL_FONTS: Record<string, CanonicalFontSpec> = {},};-const FONT_ALIASES: Record<string, keyof typeof CANONICAL_FONTS> = {- inter: "inter",- "helvetica neue": "inter",- helvetica: "inter",- arial: "inter",- "helvetica bold": "inter",- montserrat: "montserrat",- futura: "montserrat",- "din alternate": "montserrat",- "arial black": "montserrat",- outfit: "outfit",- nunito: "nunito",- oswald: "oswald",- "bebas neue": "league-gothic",- "league gothic": "league-gothic",- "archivo black": "archivo-black",- "space mono": "space-mono",- "ibm plex mono": "ibm-plex-mono",- "jetbrains mono": "jetbrains-mono",- "courier new": "jetbrains-mono",- courier: "jetbrains-mono",- "eb garamond": "eb-garamond",- garamond: "eb-garamond",- "playfair display": "playfair-display",- "source code pro": "source-code-pro",- "noto sans jp": "noto-sans-jp",- "noto sans japanese": "noto-sans-jp",- roboto: "roboto",- "open sans": "open-sans",- lato: "lato",- poppins: "poppins",- "segoe ui": "roboto",-};+// FONT_ALIASES derives from the shared alias map in @hyperframes/core.+// The cast is safe: every value in FONT_ALIAS_MAP is a valid CANONICAL_FONTS key.+export const FONT_ALIASES = FONT_ALIAS_MAP as Record<string, keyof typeof CANONICAL_FONTS>;++export { FONT_ALIAS_KEYS } from "@hyperframes/core/fonts/aliases";function normalizeFamilyName(family: string): string {return family@@ -322,7 +301,30 @@ async function buildFontFaceCss(continue;}- // Neither path resolved+ // Path 3: locate font on the local filesystem, compress, and embed.+ if (options.allowSystemFontCapture) {+ const variants = locateSystemFontVariants(originalCaseFamily);+ if (variants.length > 0) {+ let totalBytes = 0;+ for (const variant of variants) {+ const fontBuffer = readFileSync(variant.path);+ totalBytes += fontBuffer.length;+ const dataUri = await fontToDataUri(fontBuffer, variant.format);+ rules.push(buildFontFaceRule(originalCaseFamily, dataUri, variant.weight, variant.style));+ }+ if (totalBytes > SYSTEM_FONT_SIZE_LIMIT) {+ defaultLogger.warn(+ `[Compiler] System font "${originalCaseFamily}" is large (${(totalBytes / 1024 / 1024).toFixed(1)} MB total across ${variants.length} variant(s)) — embedding anyway. Consider font subsetting for production.`,+ );+ }+ defaultLogger.info(+ `[Compiler] Embedded system font "${originalCaseFamily}" — ${variants.length} variant(s), ${(totalBytes / 1024).toFixed(0)} KB total`,+ );+ continue;+ }+ }++ // No path resolvedunresolved.push(originalCaseFamily);}@@ -340,14 +342,14 @@ function warnUnresolvedFonts(unresolved: string[]): void {return acc;}, []).sort();- console.warn(+ defaultLogger.warn(`[Compiler] No deterministic font mapping for: ${unresolved.join(", ")}\n` +` Mapped fonts: ${mapped.join(", ")}\n` +` To fix, pick one:\n` +` 1. Use a mapped font name instead (see list above)\n` +` 2. Add a @font-face block in your HTML with a local or hosted font file\n` +` 3. Install the font locally on the render machine (Docker: add to Dockerfile)\n` +- ` 4. Add an alias to FONT_ALIASES in deterministicFonts.ts (for contributors)\n` ++ ` 4. Add an alias to FONT_ALIAS_MAP in packages/core/src/fonts/aliases.ts (for contributors)\n` +` Docs: https://hyperframes.heygen.com/docs/fonts`,);}@@ -442,6 +444,7 @@ export class FontFetchError extends Error {interface InternalFontFetchOptions {failClosedFontFetch: boolean;fetchImpl: typeof fetch;+ allowSystemFontCapture: boolean;}/**@@ -580,7 +583,7 @@ async function fetchGoogleFont(}if (faces.length > 0) {- console.log(+ defaultLogger.info(`[Compiler] Fetched ${faces.length} font face(s) for "${familyName}" from Google Fonts (cached to ${fontCacheDir(slug)})`,);}@@ -613,6 +616,14 @@ export interface InjectDeterministicFontFacesOptions {* network.*/fetchImpl?: typeof fetch;+ /**+ * When `true` (default for local renders), fonts that aren't resolved by+ * the bundled alias map or Google Fonts are located on the local filesystem,+ * compressed to woff2, and embedded as data URIs. Set to `false` for+ * distributed/Lambda renders where the host filesystem is not guaranteed+ * to contain the same fonts as the authoring machine.+ */+ allowSystemFontCapture?: boolean;}export async function injectDeterministicFontFaces(@@ -621,7 +632,12 @@ export async function injectDeterministicFontFaces(): Promise<string> {const failClosedFontFetch = options.failClosedFontFetch === true;const fetchImpl = options.fetchImpl ?? fetch;- const fetchOptions: InternalFontFetchOptions = { failClosedFontFetch, fetchImpl };+ const allowSystemFontCapture = options.allowSystemFontCapture !== false;+ const fetchOptions: InternalFontFetchOptions = {+ failClosedFontFetch,+ fetchImpl,+ allowSystemFontCapture,+ };const existingFaces = extractExistingFontFaces(html);const requestedFamilies = extractRequestedFontFamilies(html);@@ -638,6 +654,14 @@ export async function injectDeterministicFontFaces(}const { css, unresolved } = await buildFontFaceCss(pendingFamilies, fetchOptions);+ if (unresolved.length > 0 && options.failClosedFontFetch) {+ throw new FontFetchError(+ unresolved.join(", "),+ "",+ `[Compiler] Unresolved fonts in fail-closed mode: ${unresolved.join(", ")}. ` ++ `Distributed renders require all fonts to be resolvable.`,+ );+ }if (!css) {if (unresolved.length > 0) {warnUnresolvedFonts(unresolved);@@ -656,7 +680,7 @@ export async function injectDeterministicFontFaces(styleEl.textContent = css;head.insertBefore(styleEl, head.firstChild);- console.log(+ defaultLogger.info(`[Compiler] Injected deterministic @font-face rules for ${pendingFamilies.size - unresolved.length} requested font families`,);if (unresolved.length > 0) {diff --git a/packages/producer/src/services/distributed/plan.ts b/packages/producer/src/services/distributed/plan.tsindex a5688eb686..b97125dc14 100644--- a/packages/producer/src/services/distributed/plan.ts+++ b/packages/producer/src/services/distributed/plan.ts@@ -743,6 +743,9 @@ export async function plan(// Distributed renders fail closed on font-fetch errors so the planDir// is content-addressed against deterministic fonts only.failClosedFontFetch: config.failClosedFontFetch !== false,+ // Distributed renders must not capture host-specific system fonts —+ // the Lambda/worker filesystem won't have the same fonts installed.+ allowSystemFontCapture: false,});let compiled = compileResult.compiled;const composition = compileResult.composition;diff --git a/packages/producer/src/services/fontCompression.test.ts b/packages/producer/src/services/fontCompression.test.tsnew file mode 100644index 0000000000..92969481b1--- /dev/null+++ b/packages/producer/src/services/fontCompression.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from "bun:test";+import { existsSync, readFileSync } from "node:fs";+import { compressToWoff2, fontToDataUri } from "./fontCompression.js";++/**+ * Locate a system TTF font for real compression tests. macOS ships plenty+ * of .ttf files in /System/Library/Fonts/Supplemental; we pick the first+ * one found from a short list. Returns null on Linux CI or any environment+ * without the expected fonts — those tests are skipped gracefully.+ */+function findSystemTtf(): Buffer | null {+ const candidates = [+ "/System/Library/Fonts/Supplemental/Andale Mono.ttf",+ "/System/Library/Fonts/Supplemental/Courier New.ttf",+ "/System/Library/Fonts/Supplemental/Arial.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",+ ];+ for (const path of candidates) {+ if (existsSync(path)) return readFileSync(path);+ }+ return null;+}++describe("compressToWoff2", () => {+ it("compresses a TTF buffer to a smaller woff2 buffer", async () => {+ const ttf = findSystemTtf();+ if (!ttf) {+ console.warn("Skipping: no system TTF font available");+ return;+ }+ const woff2 = await compressToWoff2(ttf);+ expect(woff2).toBeInstanceOf(Buffer);+ expect(woff2.length).toBeGreaterThan(0);+ expect(woff2.length).toBeLessThan(ttf.length);+ });++ it("throws on invalid input", async () => {+ const garbage = Buffer.from("this is not a font file");+ await expect(compressToWoff2(garbage)).rejects.toThrow();+ });+});++describe("fontToDataUri", () => {+ it("skips compression for woff2 input and returns a data URI", async () => {+ const raw = Buffer.from("fake-woff2-bytes");+ const uri = await fontToDataUri(raw, "woff2");+ const expectedBase64 = raw.toString("base64");+ expect(uri).toBe(`data:font/woff2;base64,${expectedBase64}`);+ });++ it("compresses a TTF and returns a woff2 data URI", async () => {+ const ttf = findSystemTtf();+ if (!ttf) {+ console.warn("Skipping: no system TTF font available");+ return;+ }+ const uri = await fontToDataUri(ttf, "ttf");+ expect(uri).toMatch(/^data:font\/woff2;base64,/);+ const naiveLength = `data:font/ttf;base64,${ttf.toString("base64")}`.length;+ expect(uri.length).toBeLessThan(naiveLength);+ });++ it("falls back to raw ttf on compression failure", async () => {+ const garbage = Buffer.from("this is not a font file");+ const uri = await fontToDataUri(garbage, "ttf");+ expect(uri).toMatch(/^data:font\/ttf;base64,/);+ });++ it("falls back with correct MIME type for otf", async () => {+ const garbage = Buffer.from("not a font");+ const uri = await fontToDataUri(garbage, "otf");+ expect(uri).toMatch(/^data:font\/otf;base64,/);+ });++ it("falls back with correct MIME type for ttc", async () => {+ const garbage = Buffer.from("not a font");+ const uri = await fontToDataUri(garbage, "ttc");+ expect(uri).toMatch(/^data:font\/collection;base64,/);+ });+});diff --git a/packages/producer/src/services/fontCompression.ts b/packages/producer/src/services/fontCompression.tsnew file mode 100644index 0000000000..d6be0df43e--- /dev/null+++ b/packages/producer/src/services/fontCompression.ts@@ -0,0 +1,34 @@+// @ts-expect-error -- wawoff2 ships no type declarations; ambient .d.ts only visible to producer's own tsconfig+import wawoff2 from "wawoff2";++const { compress } = wawoff2 as {+ compress: (input: Buffer | Uint8Array) => Promise<Uint8Array>;+};++export async function compressToWoff2(input: Buffer): Promise<Buffer> {+ return Buffer.from(await compress(input));+}++const RAW_MIME_TYPES: Record<string, string> = {+ otf: "font/otf",+ ttc: "font/collection",+};++function rawMimeType(format: string): string {+ return RAW_MIME_TYPES[format] ?? "font/ttf";+}++export async function fontToDataUri(input: Buffer, originalFormat: string): Promise<string> {+ if (originalFormat === "woff2") {+ return `data:font/woff2;base64,${input.toString("base64")}`;+ }+ try {+ const compressed = await compressToWoff2(input);+ return `data:font/woff2;base64,${compressed.toString("base64")}`;+ } catch {+ console.warn(+ `[fontCompression] woff2 compression failed for ${originalFormat} font, embedding raw format`,+ );+ return `data:${rawMimeType(originalFormat)};base64,${input.toString("base64")}`;+ }+}diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.tsindex cb8c9bda8d..6b6ff7fa60 100644--- a/packages/producer/src/services/htmlCompiler.test.ts+++ b/packages/producer/src/services/htmlCompiler.test.ts@@ -797,6 +797,7 @@ describe("text-rendering rule injection", () => {const compiled = await compileForRender(projectDir, join(projectDir, "index.html"), projectDir);expect(compiled.html.replace(/\s+/g, "")).toContain("text-rendering:geometricPrecision");+ expect(compiled.html.replace(/\s+/g, "")).toContain('font-family:"Inter",sans-serif');});});@@ -1191,6 +1192,137 @@ body { background-image: url("${BG_URL}"); }expect(result).toBe(html);expect(remoteMediaAssets.size).toBe(0);});++ // ── External <link rel="stylesheet"> inlining ──++ it("leaves Google Fonts <link> tags untouched", async () => {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-gf-"));+ const html = `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700">+<link rel="stylesheet" href="https://fonts.gstatic.com/s/inter/inter.css">+<style>body { color: red; }</style>`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ // Google Fonts links should remain as-is — the deterministic font injector handles them+ expect(result).toContain("fonts.googleapis.com");+ expect(result).toContain("fonts.gstatic.com");+ expect(result).toBe(html);+ expect(remoteMediaAssets.size).toBe(0);+ });++ it("does not process non-stylesheet <link> tags (rel=icon, rel=preconnect)", async () => {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-nonss-"));+ const html = `<link rel="icon" href="https://cdn.example.com/favicon.ico">+<link rel="preconnect" href="https://cdn.example.com">+<link rel="dns-prefetch" href="https://cdn.example.com">`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ expect(result).toBe(html);+ expect(remoteMediaAssets.size).toBe(0);+ });++ it("inlines @font-face rules from external non-Google stylesheet and downloads font files", async () => {+ const EXTERNAL_FONT_URL = "https://cdn.example.com/fonts/custom.woff2";+ const STYLESHEET_URL = "https://cdn.example.com/fonts/style.css";+ const fakeCss = `+/* Reset styles */+body { margin: 0; }+@font-face {+ font-family: "CustomFont";+ src: url("${EXTERNAL_FONT_URL}") format("woff2");+ font-weight: 400;+}+h1 { font-size: 2rem; }`;++ const orig = globalThis.fetch;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (globalThis as any).fetch = async (url: string) => {+ if (url === STYLESHEET_URL) {+ return new Response(fakeCss, { status: 200 });+ }+ // Font file download+ return new Response(new Uint8Array(16), { status: 200 });+ };+ try {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-ext-"));+ const html = `<link rel="stylesheet" href="${STYLESHEET_URL}">+<style>body { color: red; }</style>`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ // The <link> tag should be replaced with an inline <style> containing the @font-face+ expect(result).not.toContain(`href="${STYLESHEET_URL}"`);+ expect(result).not.toContain("<link");+ expect(result).toContain("@font-face");+ expect(result).toContain("CustomFont");+ // The remote font URL should be rewritten to a local path+ expect(result).not.toContain(EXTERNAL_FONT_URL);+ expect(result).toContain("_remote_media/");+ expect(remoteMediaAssets.size).toBe(1);+ } finally {+ globalThis.fetch = orig;+ }+ });++ it("keeps <link> tag when external stylesheet fetch fails (graceful degradation)", async () => {+ const STYLESHEET_URL = "https://down.example.com/fonts.css";+ const orig = globalThis.fetch;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (globalThis as any).fetch = async () => new Response(null, { status: 503 });+ try {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-extfail-"));+ const html = `<link rel="stylesheet" href="${STYLESHEET_URL}">`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ // Original link tag preserved on failure+ expect(result).toContain(STYLESHEET_URL);+ expect(result).toContain("<link");+ expect(remoteMediaAssets.size).toBe(0);+ } finally {+ globalThis.fetch = orig;+ }+ });++ it("keeps <link> tag when external stylesheet has no @font-face rules", async () => {+ const STYLESHEET_URL = "https://cdn.example.com/reset.css";+ const orig = globalThis.fetch;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (globalThis as any).fetch = async () =>+ new Response("body { margin: 0; } h1 { color: blue; }", { status: 200 });+ try {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-noff-"));+ const html = `<link rel="stylesheet" href="${STYLESHEET_URL}">`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ // No @font-face → keep the original link tag (non-font CSS may be needed)+ expect(result).toContain(STYLESHEET_URL);+ expect(result).toContain("<link");+ expect(remoteMediaAssets.size).toBe(0);+ } finally {+ globalThis.fetch = orig;+ }+ });++ it("handles multiple external stylesheets, mixing Google and non-Google", async () => {+ const FONT_CDN_URL = "https://use.typekit.net/abc123.css";+ const FONT_FILE_URL = "https://use.typekit.net/af/font.woff2";+ const fontCss = `@font-face { font-family: "AdobeFont"; src: url("${FONT_FILE_URL}") format("woff2"); }`;++ const orig = globalThis.fetch;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (globalThis as any).fetch = async (url: string) => {+ if (url === FONT_CDN_URL) return new Response(fontCss, { status: 200 });+ return new Response(new Uint8Array(16), { status: 200 });+ };+ try {+ const dl = mkdtempSync(join(tmpdir(), "hf-ff-multi-"));+ const html = `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto">+<link rel="stylesheet" href="${FONT_CDN_URL}">`;+ const { html: result, remoteMediaAssets } = await localizeRemoteFontFaces(html, dl);+ // Google link untouched+ expect(result).toContain("fonts.googleapis.com");+ // Typekit link inlined — the <link> tag is replaced; the URL only appears in a CSS comment+ expect(result).not.toContain(`href="${FONT_CDN_URL}"`);+ expect(result).toContain("AdobeFont");+ expect(result).toContain("_remote_media/");+ expect(remoteMediaAssets.size).toBe(1);+ } finally {+ globalThis.fetch = orig;+ }+ });});describe("discoverAudioVolumeAutomationFromTimeline", () => {diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.tsindex 26309ff34b..e98f598a1e 100644--- a/packages/producer/src/services/htmlCompiler.ts+++ b/packages/producer/src/services/htmlCompiler.ts@@ -36,10 +36,11 @@ import {type AudioVolumeKeyframe,analyzeKeyframeIntervals,} from "@hyperframes/engine";-import { downloadToTemp, isHttpUrl } from "../utils/urlDownloader.js";+import { assertPublicHttpsUrl, downloadToTemp, isHttpUrl } from "../utils/urlDownloader.js";import type { Page } from "puppeteer-core";import { injectDeterministicFontFaces } from "./deterministicFonts.js";import { createStudioPositionSeekReapplyScript } from "@hyperframes/core/studio-api/manual-edits-render-script";+import { defaultLogger } from "../logger.js";export interface CompiledComposition {html: string;@@ -707,7 +708,7 @@ function ensureFullDocument(html: string): string {// Wrap fragment with a proper document including margin/padding reset.// Without this, Chrome applies default body { margin: 8px } which creates// visible white lines at the edges of rendered video.- return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset="UTF-8">\n <style>*{margin:0;padding:0;box-sizing:border-box;text-rendering:geometricPrecision}body{overflow:hidden;background:#000}</style>\n</head>\n<body style="margin:0;overflow:hidden">\n${html}\n</body>\n</html>`;+ return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset="UTF-8">\n <style>*{margin:0;padding:0;box-sizing:border-box;text-rendering:geometricPrecision}body{overflow:hidden;background:#000;font-family:"Inter",sans-serif}</style>\n</head>\n<body style="margin:0;overflow:hidden">\n${html}\n</body>\n</html>`;}/**@@ -780,9 +781,9 @@ export async function inlineExternalScripts(html: string): Promise<string> {}inlineScript.textContent = `/* inlined: ${src} */\n${safeText}\n`;el.replaceWith(inlineScript);- console.log(`[Compiler] Inlined CDN script: ${src}`);+ defaultLogger.info(`[Compiler] Inlined CDN script: ${src}`);} else {- console.warn(+ defaultLogger.warn(`[Compiler] WARNING: Failed to download CDN script: ${src} — ${download.reason}. ` +`The render may fail if this script is required (e.g. GSAP). ` +`Consider bundling it locally in your project.`,@@ -860,7 +861,7 @@ export function collectExternalAssets(}if (externalAssets.size > 0) {- console.log(+ defaultLogger.info(`[Compiler] Found ${externalAssets.size} asset(s) outside project directory — will copy to render output`,);}@@ -914,7 +915,7 @@ async function downloadAndRewriteUrls(const localPath = await downloadToTemp(url, remoteDir);urlToLocal.set(url, localPath);} catch (err) {- console.warn(+ defaultLogger.warn(`[Compiler] ${warnLabel} ${url} — using original URL as fallback. ${err instanceof Error ? err.message : String(err)}`,@@ -939,7 +940,7 @@ async function downloadAndRewriteUrls(if (extraRewrite) result = extraRewrite(result, url, relPath);}- console.log(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);+ defaultLogger.info(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);return { html: result, remoteMediaAssets };}@@ -1043,42 +1044,248 @@ const REMOTE_FONTFACE_URL_RE = /url\(["']?(https?:\/\/[^"')]+)["']?\)/gi;* to the next font in the stack (e.g. Arial). Downloading the font file* before render and rewriting to a local path eliminates the CORS race.*/-/** @internal exported for unit testing only */-export async function localizeRemoteFontFaces(- html: string,- downloadDir: string,-): Promise<{ html: string; remoteMediaAssets: Map<string, string> }> {- // Only scan inside <style> blocks to avoid false-positive matches in JS.+/** Returns true for URLs belonging to Google Fonts (handled by the deterministic font injector). */+function isGoogleFontsUrl(href: string): boolean {+ try {+ const host = new URL(href).hostname.toLowerCase();+ return host === "fonts.googleapis.com" || host === "fonts.gstatic.com";+ } catch {+ return /fonts\.googleapis\.com|fonts\.gstatic\.com/i.test(href);+ }+}++const MAX_STYLESHEET_BYTES = 2 * 1024 * 1024;++async function fetchExternalStylesheetCss(href: string): Promise<string | null> {+ try {+ assertPublicHttpsUrl(href);+ } catch {+ return null;+ }+ try {+ const response = await fetch(href, {+ signal: AbortSignal.timeout(15_000),+ });+ if (!response.ok) {+ defaultLogger.warn(+ `[Compiler] External stylesheet fetch failed for ${href} — HTTP ${response.status}`,+ );+ return null;+ }+ const contentLength = response.headers.get("content-length");+ if (contentLength && parseInt(contentLength, 10) > MAX_STYLESHEET_BYTES) {+ defaultLogger.warn(+ `[Compiler] External stylesheet too large (${contentLength} bytes): ${href}`,+ );+ return null;+ }+ const text = await response.text();+ if (text.length > MAX_STYLESHEET_BYTES) {+ defaultLogger.warn(+ `[Compiler] External stylesheet too large (${text.length} bytes): ${href}`,+ );+ return null;+ }+ return text;+ } catch (err) {+ defaultLogger.warn(+ `[Compiler] External stylesheet fetch failed for ${href} — ${+ err instanceof Error ? err.message : String(err)+ }`,+ );+ return null;+ }+}++/**+ * Extract all `@font-face { ... }` blocks from a CSS string, preserving the+ * full rule text (including the `@font-face` keyword and braces).+ *+ * Uses a depth-tracking scan instead of `[^}]*` so blocks with nested+ * descriptor values that happen to contain `}` (rare but valid in+ * `format(...)` hints with custom idents) are captured correctly.+ */+function extractFontFaceBlocks(css: string): string[] {+ const blocks: string[] = [];+ const atRule = /@font-face\s*/gi;+ let m: RegExpExecArray | null;+ while ((m = atRule.exec(css)) !== null) {+ const openIdx = css.indexOf("{", m.index + m[0].length);+ if (openIdx === -1) break;+ let depth = 1;+ let i = openIdx + 1;+ for (; i < css.length && depth > 0; i++) {+ if (css[i] === "{") depth++;+ else if (css[i] === "}") depth--;+ }+ if (depth === 0) {+ blocks.push(css.slice(m.index, i));+ atRule.lastIndex = i;+ }+ }+ return blocks;+}++/**+ * Find all external `<link rel="stylesheet">` tags pointing to non-Google+ * CDNs, fetch their CSS, and replace the `<link>` with an inline `<style>`+ * containing only the `@font-face` rules. This allows Phase 2 (the existing+ * inline scan) to pick up and localise the font file URLs.+ *+ * Google Fonts links are excluded because the deterministic font injector+ * handles those. If a fetch fails or the CSS has no `@font-face` blocks,+ * the original `<link>` tag is preserved (graceful degradation).+ */+// fallow-ignore-next-line complexity+async function inlineExternalFontStylesheets(html: string): Promise<string> {+ const linkRe = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;+ const hrefRe = /\bhref=["']([^"']+)["']/i;++ const linkMatches: { fullMatch: string; href: string }[] = [];+ let linkMatch: RegExpExecArray | null;+ while ((linkMatch = linkRe.exec(html)) !== null) {+ const tag = linkMatch[0];+ const hrefMatch = hrefRe.exec(tag);+ if (!hrefMatch?.[1]) continue;+ const href = hrefMatch[1];+ if (!/^https?:\/\//i.test(href)) continue;+ if (isGoogleFontsUrl(href)) continue;+ linkMatches.push({ fullMatch: tag, href });+ }++ if (linkMatches.length === 0) return html;++ const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;+ const fetches: { fullMatch: string; href: string; css: string | null }[] = [];+ for (let i = 0; i < linkMatches.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {+ const batch = linkMatches.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);+ const results = await Promise.all(+ batch.map(async ({ fullMatch, href }) => {+ const css = await fetchExternalStylesheetCss(href);+ return { fullMatch, href, css };+ }),+ );+ fetches.push(...results);+ }++ let result = html;+ for (const { fullMatch, href, css } of fetches) {+ if (css === null) continue;+ const fontFaceBlocks = extractFontFaceBlocks(css);+ if (fontFaceBlocks.length === 0) continue;+ const inlineStyle = `<style>/* Inlined from ${href} */\n${fontFaceBlocks.join("\n")}\n</style>`;+ result = result.replace(fullMatch, inlineStyle);+ defaultLogger.info(+ `[Compiler] Inlined ${fontFaceBlocks.length} @font-face rule(s) from external stylesheet: ${href}`,+ );+ }+ return result;+}++/**+ * Collect all remote `url(https://...)` references inside `@font-face` blocks+ * found in `<style>` tags.+ */+// fallow-ignore-next-line complexity+function collectFontFaceUrls(html: string): Set<string> {const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;- const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;const urlSet = new Set<string>();let styleMatch: RegExpExecArray | null;while ((styleMatch = styleBlockRe.exec(html)) !== null) {const cssText = styleMatch[1] ?? "";- const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);- let ffMatch: RegExpExecArray | null;- while ((ffMatch = ffRe.exec(cssText)) !== null) {- const block = ffMatch[1] ?? "";+ // Depth-tracking scanner to correctly handle @font-face blocks that+ // contain nested braces (e.g. unicode-range fallback rules).+ let i = 0;+ while (i < cssText.length) {+ const atIdx = cssText.indexOf("@font-face", i);+ if (atIdx === -1) break;+ const braceStart = cssText.indexOf("{", atIdx);+ if (braceStart === -1) break;+ let depth = 1;+ let j = braceStart + 1;+ while (j < cssText.length && depth > 0) {+ if (cssText[j] === "{") depth++;+ else if (cssText[j] === "}") depth--;+ j++;+ }+ const block = cssText.slice(braceStart + 1, j - 1);const urlRe = new RegExp(REMOTE_FONTFACE_URL_RE.source, REMOTE_FONTFACE_URL_RE.flags);let urlMatch: RegExpExecArray | null;while ((urlMatch = urlRe.exec(block)) !== null) {if (urlMatch[1]) urlSet.add(urlMatch[1]);}+ i = j;}}+ return urlSet;+}++/** @internal exported for unit testing only */+export async function localizeRemoteFontFaces(+ html: string,+ downloadDir: string,+): Promise<{ html: string; remoteMediaAssets: Map<string, string> }> {+ // Phase 1: Inline @font-face rules from external <link rel="stylesheet"> tags.+ const processed = await inlineExternalFontStylesheets(html);++ // Phase 2: Download font file URLs from all @font-face blocks (both+ // pre-existing inline blocks and the ones just inlined from external sheets).+ const urlSet = collectFontFaceUrls(processed);return downloadAndRewriteUrls(urlSet,- html,+ processed,join(downloadDir, REMOTE_MEDIA_SUBDIR),"Remote font download failed for","Localized remote font face(s)",- // Also rewrite unquoted url(https://...) CSS syntax.(h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`),);}+const LOCAL_FONTFACE_URL_RE = /url\(["']?(?!data:|https?:\/\/)([^"')]+)["']?\)/gi;++// fallow-ignore-next-line complexity+async function embedLocalFontFaces(html: string, projectDir: string): Promise<string> {+ const { fontToDataUri: toDataUri } = await import("./fontCompression.js");+ const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;+ const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;+ let result = html;+ const embedded = new Set<string>();++ let styleMatch: RegExpExecArray | null;+ while ((styleMatch = styleBlockRe.exec(html)) !== null) {+ const cssText = styleMatch[1] ?? "";+ const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);+ let ffMatch: RegExpExecArray | null;+ while ((ffMatch = ffRe.exec(cssText)) !== null) {+ const block = ffMatch[1] ?? "";+ const urlRe = new RegExp(LOCAL_FONTFACE_URL_RE.source, LOCAL_FONTFACE_URL_RE.flags);+ let urlMatch: RegExpExecArray | null;+ while ((urlMatch = urlRe.exec(block)) !== null) {+ const localPath = urlMatch[1];+ if (!localPath || embedded.has(localPath)) continue;+ const absPath = localPath.startsWith("/") ? localPath : resolve(projectDir, localPath);+ if (!isPathInside(absPath, projectDir)) continue;+ if (!existsSync(absPath)) continue;+ const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";+ try {+ const buffer = readFileSync(absPath);+ const dataUri = await toDataUri(buffer, ext);+ result = result.replaceAll(localPath, dataUri);+ embedded.add(localPath);+ defaultLogger.info(+ `[Compiler] Embedded local font file: ${localPath} (${(buffer.length / 1024).toFixed(0)} KB → data URI)`,+ );+ } catch {+ // File read or compression failed — keep the original path+ }+ }+ }+ }+ return result;+}+/*** Optional behavior toggles for {@link compileForRender}. All fields are* additive; omitting `options` preserves the in-process renderer's defaults.@@ -1093,6 +1300,13 @@ export interface CompileForRenderOptions {* `false` preserves the in-process behavior.*/failClosedFontFetch?: boolean;+ /**+ * When `true`, fonts not resolved by the bundled alias map or Google Fonts+ * are located on the local filesystem, compressed to woff2, and embedded.+ * Default `true` for local renders. Distributed callers pass `false` to+ * prevent host-specific font capture from leaking into the planDir.+ */+ allowSystemFontCapture?: boolean;}const GSAP_CDN_BASE = "https://cdn.jsdelivr.net/npm/[email protected]/dist/";@@ -1104,7 +1318,7 @@ function rewriteUnresolvableGsapToCdn(html: string, projectDir: string): stringif (/^https?:\/\//i.test(src)) return full;const absPath = resolve(projectDir, src);if (existsSync(absPath)) return full;- console.log(+ defaultLogger.info(`[Compiler] Rewriting missing gsap script to CDN: ${src} → ${GSAP_CDN_BASE}${file}`,);return `${prefix}${GSAP_CDN_BASE}${file}${suffix}`;@@ -1164,7 +1378,10 @@ export async function compileForRender(injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(promoteCssImportsToLinkTags(sanitizedHtml)),),- { failClosedFontFetch: options.failClosedFontFetch === true },+ {+ failClosedFontFetch: options.failClosedFontFetch === true,+ allowSystemFontCapture: options.allowSystemFontCapture,+ },);// Download CDN scripts and inline them AFTER coalescing. This order matters:@@ -1224,14 +1441,14 @@ export async function compileForRender(// Remote font URLs fail with a CORS rejection at render time (S3 does not// allow http://localhost:PORT as origin), causing Chrome to silently fall// back to the next font in the stack.- const { html, remoteMediaAssets: remoteFontAssets } = await localizeRemoteFontFaces(- htmlWithLocalImages,- downloadDir,- );+ const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } =+ await localizeRemoteFontFaces(htmlWithLocalImages, downloadDir);for (const [relPath, absPath] of remoteFontAssets) {externalAssets.set(relPath, absPath);}+ const html = await embedLocalFontFaces(htmlWithLocalizedFonts, projectDir);+// Parse main HTML elementsconst mainVideos = parseVideoElements(html);const mainAudios = parseAudioElements(html);@@ -1253,7 +1470,7 @@ export async function compileForRender(Promise.all([analyzeKeyframeIntervals(videoPath), extractMediaMetadata(videoPath)]).then(([analysis, metadata]) => {if (analysis.isProblematic) {- console.warn(+ defaultLogger.warn(`[Compiler] WARNING: Video "${video.id}" has sparse keyframes (max interval: ${analysis.maxIntervalSeconds}s). ` +`This causes seek failures and frame freezing. Re-encode with: ${reencode}`,);diff --git a/packages/producer/src/services/render/stages/compileStage.ts b/packages/producer/src/services/render/stages/compileStage.tsindex aafab2a9d2..cb194e6d7a 100644--- a/packages/producer/src/services/render/stages/compileStage.ts+++ b/packages/producer/src/services/render/stages/compileStage.ts@@ -78,6 +78,11 @@ export interface CompileStageInput {* leaves it `undefined` to preserve current behavior.*/failClosedFontFetch?: boolean;+ /**+ * When `true`, fonts not resolved by aliases or Google Fonts are located+ * on the local filesystem and embedded. Distributed renders pass `false`.+ */+ allowSystemFontCapture?: boolean;}export interface CompileStageResult {@@ -111,11 +116,13 @@ export async function runCompileStage(input: CompileStageInput): Promise<Compilelog,assertNotAborted,failClosedFontFetch,+ allowSystemFontCapture,} = input;const compileStart = Date.now();const compiled = await compileForRender(projectDir, htmlPath, join(workDir, "downloads"), {failClosedFontFetch: failClosedFontFetch === true,+ allowSystemFontCapture,});assertNotAborted();const compileOnlyMs = Date.now() - compileStart;diff --git a/packages/producer/src/utils/urlDownloader.ts b/packages/producer/src/utils/urlDownloader.tsindex 65d9ee6b12..4e757a44d0 100644--- a/packages/producer/src/utils/urlDownloader.ts+++ b/packages/producer/src/utils/urlDownloader.ts@@ -2,4 +2,4 @@* Re-exported from @hyperframes/engine.* @see engine/src/utils/urlDownloader.ts for implementation.*/-export { downloadToTemp, isHttpUrl } from "@hyperframes/engine";+export { assertPublicHttpsUrl, downloadToTemp, isHttpUrl } from "@hyperframes/engine";diff --git a/packages/studio/src/components/editor/fontCatalog.ts b/packages/studio/src/components/editor/fontCatalog.tsindex c8691fc314..fd343ab5d1 100644--- a/packages/studio/src/components/editor/fontCatalog.ts+++ b/packages/studio/src/components/editor/fontCatalog.ts@@ -111,15 +111,22 @@ export const COMMON_LOCAL_FONT_FAMILIES = ["SF Pro Text","Avenir","Avenir Next",- "Helvetica Neue",- "Arial",- "Georgia",- "Times New Roman","Menlo","Monaco",- "Courier New",] as const;+import { resolveAliasDisplayName } from "@hyperframes/core/fonts/aliases";++/**+ * Resolves the render-time canonical font for a local font family name.+ * Derived from the shared FONT_ALIAS_MAP — no hand-curation needed.+ */+export function renderAliasFor(family: string): string | undefined {+ const display = resolveAliasDisplayName(family);+ if (!display || display.toLowerCase() === family.toLowerCase()) return undefined;+ return display;+}+export function googleFontStylesheetUrl(family: string): string {const encodedFamily = encodeURIComponent(family.trim()).replace(/%20/g, "+");return `https://fonts.googleapis.com/css2?family=${encodedFamily}:wght@300;400;500;600;700;800;900&display=swap`;diff --git a/packages/studio/src/components/editor/propertyPanelFont.tsx b/packages/studio/src/components/editor/propertyPanelFont.tsxindex 5be380db19..a0fd50d7ab 100644--- a/packages/studio/src/components/editor/propertyPanelFont.tsx+++ b/packages/studio/src/components/editor/propertyPanelFont.tsx@@ -1,5 +1,9 @@import { useEffect, useMemo, useRef, useState } from "react";-import { googleFontStylesheetUrl, POPULAR_GOOGLE_FONT_FAMILIES } from "./fontCatalog";+import {+ googleFontStylesheetUrl,+ POPULAR_GOOGLE_FONT_FAMILIES,+ renderAliasFor,+} from "./fontCatalog";import { fontFamilyFromAssetPath, importedFontFaceCss, type ImportedFontAsset } from "./fontAssets";import {DEFAULT_FONT_FAMILIES,@@ -315,12 +319,32 @@ export function FontFamilyField({);};+ const importSystemFont = async (family: string): Promise<ImportedFontAsset | null> => {+ if (!onImportFonts) return null;+ const response = await fetch(`/api/fonts/file?family=${encodeURIComponent(family)}`);+ if (!response.ok) return null;+ const blob = await response.blob();+ const ext = response.headers.get("Content-Disposition")?.match(/\.(\w+)"?$/)?.[1] ?? "ttf";+ const file = new File([blob], `${family}.${ext}`, { type: blob.type || "font/ttf" });+ const imported = await onImportFonts([file]);+ return (+ imported.find((a) => a.family.toLowerCase() === family.toLowerCase()) ?? imported[0] ?? null+ );+ };+const commitFamily = async (option: FontOption) => {- if (option.source === "Local") {+ const needsImport =+ option.source === "Local" ||+ (option.source === "System" && !GENERIC_FONT_FAMILIES.has(option.family.toLowerCase()));++ if (needsImport) {setImportingFonts(true);setFontNotice(null);try {- const imported = await importLocalFont(option.family);+ const imported =+ option.source === "Local"+ ? await importLocalFont(option.family)+ : await importSystemFont(option.family);if (imported) {loadImportedFontStylesheet(imported);onCommit(buildFontFamilyValue(imported.family));@@ -328,13 +352,9 @@ export function FontFamilyField({setOpen(false);return;}- onCommit(buildFontFamilyValue(option.family));- setQuery("");- setOpen(false);} finally {setImportingFonts(false);}- return;}if (option.source === "Google") loadGoogleFontStylesheet(option.family);const imported = importedFonts.find(@@ -440,7 +460,14 @@ export function FontFamilyField({: "text-neutral-300 hover:bg-neutral-900 hover:text-neutral-100"}`}>- <span className="min-w-0 truncate font-medium">{option.family}</span>+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="truncate font-medium">{option.family}</span>+ {renderAliasFor(option.family) && (+ <span className="flex-shrink-0 text-[9px] text-neutral-500">+ → {renderAliasFor(option.family)}+ </span>+ )}+ </span><span className="flex-shrink-0 text-[9px] uppercase tracking-[0.14em] text-neutral-600">{option.source}</span>