@@ -2043,15 +2043,6 @@ function localizeFontFaceUrls(
20432043 ) ;
20442044}
20452045
2046- /**
2047- * Match one `url(<path>)` occurrence, with or without quotes, for a literal
2048- * path. Exported for tests: the suffix-collision it prevents is invisible in
2049- * ordinary projects and easy to reintroduce.
2050- */
2051- export function urlOccurrenceRe ( localPath : string ) : RegExp {
2052- const escaped = localPath . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, "\\$&" ) ;
2053- return new RegExp ( `url\\((["']?)${ escaped } \\1\\)` , "g" ) ;
2054- }
20552046// Base64 expands bytes by ~33%, then immutable HTML replacements retain more
20562047// string copies while compiling. Files up to and including 5 MiB remain inline;
20572048// the first byte above that stays file-backed. This conservative ceiling keeps
@@ -2075,81 +2066,107 @@ async function readLocalFont(absPath: string): Promise<LocalFontRead> {
20752066 return { kind : "inline" , buffer : Buffer . concat ( chunks , totalBytes ) } ;
20762067}
20772068
2078- // fallow-ignore-next-line complexity
2069+ /** The data URI a project font path embeds as, or undefined when it stays a file. */
2070+ async function localFontDataUri (
2071+ localPath : string ,
2072+ projectDir : string ,
2073+ assetRoot : string | undefined ,
2074+ dataUriByAbsolutePath : Map < string , string | undefined > ,
2075+ log : ProducerLogger ,
2076+ ) : Promise < string | undefined > {
2077+ const absPath = localPath . startsWith ( "/" ) ? localPath : resolve ( projectDir , localPath ) ;
2078+ if ( ! isPathInside ( absPath , projectDir ) || escapesAssetRoot ( absPath , assetRoot ) ) return undefined ;
2079+ // A project font that is a link leading outside obeys the same policy as the file server.
2080+ if ( refusesOutsideLink ( projectDir , absPath , ( line ) => log . warn ( `[Compiler] ${ line } ` ) ) ) {
2081+ return undefined ;
2082+ }
2083+ if ( isPrivateCompositionFile ( projectDir , absPath ) ) return undefined ;
2084+ if ( dataUriByAbsolutePath . has ( absPath ) ) return dataUriByAbsolutePath . get ( absPath ) ;
2085+ const ext = absPath . match ( / \. ( w o f f 2 ? | t t f | o t f | t t c ) $ / i) ?. [ 1 ] ?. toLowerCase ( ) ?? "ttf" ;
2086+ try {
2087+ const font = await readLocalFont ( absPath ) ;
2088+ if ( font . kind === "file-backed" ) {
2089+ dataUriByAbsolutePath . set ( absPath , undefined ) ;
2090+ defaultLogger . debug (
2091+ `[Compiler] Kept large local font file-backed: ${ localPath } (> ${ ( MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024 ) . toFixed ( 1 ) } MB)` ,
2092+ ) ;
2093+ return undefined ;
2094+ }
2095+ const { fontToDataUri } = await import ( "@hyperframes/core/fonts/embed" ) ;
2096+ const dataUri = await fontToDataUri ( font . buffer , ext , { compressToWoff2 : false } ) ;
2097+ dataUriByAbsolutePath . set ( absPath , dataUri ) ;
2098+ defaultLogger . debug (
2099+ `[Compiler] Embedded local font file: ${ localPath } (${ ( font . buffer . length / 1024 ) . toFixed ( 0 ) } KB → data URI)` ,
2100+ ) ;
2101+ return dataUri ;
2102+ } catch ( error ) {
2103+ // Keep the original path: a font that cannot be read must not fail the render, but say why
2104+ // it renders in a fallback typeface.
2105+ defaultLogger . warn (
2106+ `[Compiler] Could not embed local font ${ localPath } : ${
2107+ error instanceof Error ? error . message : String ( error )
2108+ } `,
2109+ ) ;
2110+ return undefined ;
2111+ }
2112+ }
2113+
2114+ /** `whole` with its `inner` text, which ends `tail` characters before its end, replaced. */
2115+ const replaceInner = ( whole : string , inner : string , tail : number , next : string ) =>
2116+ whole . slice ( 0 , whole . length - tail - inner . length ) + next + whole . slice ( whole . length - tail ) ;
2117+
2118+ /**
2119+ * Inline the project fonts that `<style>` `@font-face` sources name as data URIs. Every copy is
2120+ * charged to the render's budget, so a font named by many rules stops being inlined once the
2121+ * budget is spent and the rest keep loading it from its file.
2122+ */
20792123async function embedLocalFontFaces (
20802124 html : string ,
20812125 projectDir : string ,
20822126 assetRoot : string | undefined ,
2127+ budget : CompositionExpansionBudget ,
20832128 log : ProducerLogger = defaultLogger ,
20842129) : Promise < string > {
2085- const { fontToDataUri : toDataUri } = await import ( "@hyperframes/core/fonts/embed" ) ;
2086- let result = html ;
2087- const embeddedPaths = new Set < string > ( ) ;
2088- const dataUriByAbsolutePath = new Map < string , string > ( ) ;
2089- const fileBackedAbsolutePaths = new Set < string > ( ) ;
2090-
2130+ const dataUriByPath = new Map < string , string | undefined > ( ) ;
2131+ const dataUriByAbsolutePath = new Map < string , string | undefined > ( ) ;
20912132 for ( const { parts : style } of styleBlockMatches ( html ) ) {
20922133 for ( const { parts : face } of fontFaceBlockMatches ( style [ 1 ] ) ) {
2093- const block = face [ 1 ] ;
2094- for ( const { parts } of localFontFaceUrlMatches ( block ) ) {
2134+ for ( const { parts } of localFontFaceUrlMatches ( face [ 1 ] ) ) {
20952135 const localPath = parts [ 1 ] ;
2096- if ( ! localPath || embeddedPaths . has ( localPath ) ) continue ;
2097- const absPath = localPath . startsWith ( "/" ) ? localPath : resolve ( projectDir , localPath ) ;
2098- if ( ! isPathInside ( absPath , projectDir ) || escapesAssetRoot ( absPath , assetRoot ) ) continue ;
2099- // A project font that is a link leading outside obeys the same policy as the file server.
2100- if ( refusesOutsideLink ( projectDir , absPath , ( line ) => log . warn ( `[Compiler] ${ line } ` ) ) ) {
2101- embeddedPaths . add ( localPath ) ;
2102- continue ;
2103- }
2104- if ( isPrivateCompositionFile ( projectDir , absPath ) ) continue ;
2105- const ext = absPath . match ( / \. ( w o f f 2 ? | t t f | o t f | t t c ) $ / i) ?. [ 1 ] ?. toLowerCase ( ) ?? "ttf" ;
2106- try {
2107- if ( fileBackedAbsolutePaths . has ( absPath ) ) {
2108- embeddedPaths . add ( localPath ) ;
2109- continue ;
2110- }
2111- let dataUri = dataUriByAbsolutePath . get ( absPath ) ;
2112- if ( ! dataUri ) {
2113- const font = await readLocalFont ( absPath ) ;
2114- if ( font . kind === "file-backed" ) {
2115- fileBackedAbsolutePaths . add ( absPath ) ;
2116- defaultLogger . debug (
2117- `[Compiler] Kept large local font file-backed: ${ localPath } (> ${ ( MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024 ) . toFixed ( 1 ) } MB)` ,
2118- ) ;
2119- embeddedPaths . add ( localPath ) ;
2120- continue ;
2121- }
2122- dataUri = await toDataUri ( font . buffer , ext , { compressToWoff2 : false } ) ;
2123- dataUriByAbsolutePath . set ( absPath , dataUri ) ;
2124- defaultLogger . debug (
2125- `[Compiler] Embedded local font file: ${ localPath } (${ ( font . buffer . length / 1024 ) . toFixed ( 0 ) } KB → data URI)` ,
2126- ) ;
2127- }
2128- // Anchored on the `url(...)` occurrence, not a bare substring. A
2129- // plain replaceAll of `localPath` also rewrites that text anywhere
2130- // else it appears -- including inside a LONGER url whose tail
2131- // happens to match, e.g. embedding `fonts/x.ttf` would corrupt an
2132- // untouched `url("file:///abs/fonts/x.ttf")` into
2133- // `url("file:///abs/<data-uri>")`. Any two paths where one is a
2134- // suffix of the other collide the same way. Every sibling rewrite
2135- // in this file already anchors like this.
2136- result = result . replace ( urlOccurrenceRe ( localPath ) , `url("${ dataUri } ")` ) ;
2137- embeddedPaths . add ( localPath ) ;
2138- } catch ( error ) {
2139- // Keep the original path: a font that cannot be read must not fail
2140- // the render. Logged rather than silently swallowed -- a silent skip
2141- // here means the composition renders in a fallback typeface and
2142- // nothing says why.
2143- defaultLogger . warn (
2144- `[Compiler] Could not embed local font ${ localPath } : ${
2145- error instanceof Error ? error . message : String ( error )
2146- } `,
2147- ) ;
2148- }
2136+ if ( ! localPath || dataUriByPath . has ( localPath ) ) continue ;
2137+ dataUriByPath . set (
2138+ localPath ,
2139+ await localFontDataUri ( localPath , projectDir , assetRoot , dataUriByAbsolutePath , log ) ,
2140+ ) ;
21492141 }
21502142 }
21512143 }
2152- return result ;
2144+ if ( ! [ ...dataUriByPath . values ( ) ] . some ( Boolean ) ) return html ;
2145+
2146+ let warned = false ;
2147+ const embed = ( source : string , localPath : string ) => {
2148+ const dataUri = dataUriByPath . get ( localPath ) ;
2149+ if ( ! dataUri ) return source ;
2150+ const inlined = `url("${ dataUri } ")` ;
2151+ if ( budget . chargeGeneratedIfItFits ( inlined . length - source . length ) ) return inlined ;
2152+ if ( ! warned ) {
2153+ warned = true ;
2154+ log . warn (
2155+ `[Compiler] Kept local font ${ localPath } file-backed: the page reached its inline size limit` ,
2156+ ) ;
2157+ }
2158+ return source ;
2159+ } ;
2160+ return replaceMatches ( html , styleBlockMatches ( html ) , ( style , css ) =>
2161+ replaceInner (
2162+ style ,
2163+ css ,
2164+ "</style>" . length ,
2165+ replaceMatches ( css , fontFaceBlockMatches ( css ) , ( face , body ) =>
2166+ replaceInner ( face , body , 1 , replaceMatches ( body , localFontFaceUrlMatches ( body ) , embed ) ) ,
2167+ ) ,
2168+ ) ,
2169+ ) ;
21532170}
21542171
21552172/**
@@ -2518,6 +2535,7 @@ export async function compileForRender(
25182535 htmlWithPreparedGifs ,
25192536 projectDir ,
25202537 assetRoot ,
2538+ budget ,
25212539 options . log ,
25222540 ) ;
25232541
0 commit comments