@hyperframes/producer 0.9.65 → 0.9.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6944,6 +6944,16 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6944
6944
  `Composition file "${file}" is ${megabytes(bytes)}, over the ${megabytes(MAX_COMPOSITION_HTML_BYTES)} limit for one composition HTML file. Keep large data such as images, fonts and JSON in separate asset files and reference them by path instead of inlining them.`,
6945
6945
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6946
6946
  );
6947
+ var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
6948
+ function generatedTooLarge(file, bytes) {
6949
+ if (file === "composition variables") {
6950
+ return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
6951
+ }
6952
+ if (file === "variable media sources") {
6953
+ return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
6954
+ }
6955
+ return `Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ${megabytes(bytes)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`;
6956
+ }
6947
6957
  var CompositionExpansionBudget = class {
6948
6958
  bytes = 0;
6949
6959
  mounts = 0;
@@ -6952,10 +6962,16 @@ var CompositionExpansionBudget = class {
6952
6962
  chargeGenerated(file, bytes) {
6953
6963
  this.generated += bytes;
6954
6964
  if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
6955
- throw new CompositionTooLargeError(
6956
- `Scripts and styles generated for sub-composition mounts, ending at "${file}", add up to ${megabytes(this.generated)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`,
6957
- { bytes: this.generated, limitBytes: MAX_EXPANDED_COMPOSITION_BYTES, exceeded: "generated" }
6958
- );
6965
+ throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
6966
+ bytes: this.generated,
6967
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
6968
+ exceeded: "generated"
6969
+ });
6970
+ }
6971
+ chargeGeneratedIfItFits(bytes) {
6972
+ if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
6973
+ this.generated += bytes;
6974
+ return true;
6959
6975
  }
6960
6976
  charge(file, bytes) {
6961
6977
  this.bytes += bytes;
@@ -8667,7 +8683,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8667
8683
  }
8668
8684
  return document2.toString();
8669
8685
  }
8670
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8686
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
8671
8687
  const { document: document2 } = parseHTML5(html);
8672
8688
  const head = document2.querySelector("head");
8673
8689
  const body = document2.querySelector("body");
@@ -8676,11 +8692,11 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8676
8692
  const emitted = emitRootCompositionVariableStyles(
8677
8693
  document2,
8678
8694
  {},
8679
- variableOverrides
8695
+ variableOverrides,
8696
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8680
8697
  );
8681
8698
  return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8682
8699
  }
8683
- const budget = new CompositionExpansionBudget();
8684
8700
  const readOnce = /* @__PURE__ */ new Map();
8685
8701
  const readMountHtml = (srcPath) => {
8686
8702
  const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
@@ -8715,6 +8731,10 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8715
8731
  hostIdentityMap: hostIdentityByElement,
8716
8732
  readVariableDefaults: readDeclaredDefaults,
8717
8733
  parseHostVariables: parseHostVariableValues,
8734
+ resolveFilePath: (srcPath) => {
8735
+ const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
8736
+ return file && relative2(projectDir, file).split(sep3).join("/");
8737
+ },
8718
8738
  resolveHtml: (srcPath) => {
8719
8739
  const compHtml = resolveMountHtml(srcPath);
8720
8740
  if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
@@ -8805,7 +8825,8 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8805
8825
  emitRootCompositionVariableStyles(
8806
8826
  document2,
8807
8827
  result.variablesByComp,
8808
- variableOverrides
8828
+ variableOverrides,
8829
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8809
8830
  );
8810
8831
  assignMediaRenderIds(document2);
8811
8832
  return { html: document2.toString(), variablesByComp: result.variablesByComp };
@@ -9230,10 +9251,6 @@ function localizeFontFaceUrls(html, downloadDir) {
9230
9251
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9231
9252
  );
9232
9253
  }
9233
- function urlOccurrenceRe(localPath) {
9234
- const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9235
- return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
9236
- }
9237
9254
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
9238
9255
  async function readLocalFont(absPath) {
9239
9256
  const chunks = [];
@@ -9248,59 +9265,83 @@ async function readLocalFont(absPath) {
9248
9265
  }
9249
9266
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9250
9267
  }
9251
- async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
9252
- const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
9253
- let result = html;
9254
- const embeddedPaths = /* @__PURE__ */ new Set();
9268
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9269
+ const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9270
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9271
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9272
+ return void 0;
9273
+ }
9274
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9275
+ if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
9276
+ const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9277
+ try {
9278
+ const font = await readLocalFont(absPath);
9279
+ if (font.kind === "file-backed") {
9280
+ dataUriByAbsolutePath.set(absPath, void 0);
9281
+ defaultLogger.debug(
9282
+ `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9283
+ );
9284
+ return void 0;
9285
+ }
9286
+ const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
9287
+ const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
9288
+ dataUriByAbsolutePath.set(absPath, dataUri);
9289
+ defaultLogger.debug(
9290
+ `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9291
+ );
9292
+ return dataUri;
9293
+ } catch (error) {
9294
+ defaultLogger.warn(
9295
+ `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9296
+ );
9297
+ return void 0;
9298
+ }
9299
+ }
9300
+ var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
9301
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
9302
+ const dataUriByPath = /* @__PURE__ */ new Map();
9255
9303
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
9256
- const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
9257
9304
  for (const { parts: style } of styleBlockMatches(html)) {
9258
9305
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
9259
- const block = face[1];
9260
- for (const { parts } of localFontFaceUrlMatches(block)) {
9306
+ for (const { parts } of localFontFaceUrlMatches(face[1])) {
9261
9307
  const localPath = parts[1];
9262
- if (!localPath || embeddedPaths.has(localPath)) continue;
9263
- const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9264
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
9265
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9266
- embeddedPaths.add(localPath);
9267
- continue;
9268
- }
9269
- if (isPrivateCompositionFile(projectDir, absPath)) continue;
9270
- const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9271
- try {
9272
- if (fileBackedAbsolutePaths.has(absPath)) {
9273
- embeddedPaths.add(localPath);
9274
- continue;
9275
- }
9276
- let dataUri = dataUriByAbsolutePath.get(absPath);
9277
- if (!dataUri) {
9278
- const font = await readLocalFont(absPath);
9279
- if (font.kind === "file-backed") {
9280
- fileBackedAbsolutePaths.add(absPath);
9281
- defaultLogger.debug(
9282
- `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9283
- );
9284
- embeddedPaths.add(localPath);
9285
- continue;
9286
- }
9287
- dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
9288
- dataUriByAbsolutePath.set(absPath, dataUri);
9289
- defaultLogger.debug(
9290
- `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9291
- );
9292
- }
9293
- result = result.replace(urlOccurrenceRe(localPath), `url("${dataUri}")`);
9294
- embeddedPaths.add(localPath);
9295
- } catch (error) {
9296
- defaultLogger.warn(
9297
- `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9298
- );
9299
- }
9308
+ if (!localPath || dataUriByPath.has(localPath)) continue;
9309
+ dataUriByPath.set(
9310
+ localPath,
9311
+ await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
9312
+ );
9300
9313
  }
9301
9314
  }
9302
9315
  }
9303
- return result;
9316
+ if (![...dataUriByPath.values()].some(Boolean)) return html;
9317
+ let warned = false;
9318
+ const embed = (source, localPath) => {
9319
+ const dataUri = dataUriByPath.get(localPath);
9320
+ if (!dataUri) return source;
9321
+ const inlined = `url("${dataUri}")`;
9322
+ if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
9323
+ if (!warned) {
9324
+ warned = true;
9325
+ log.warn(
9326
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9327
+ );
9328
+ }
9329
+ return source;
9330
+ };
9331
+ return replaceMatches(
9332
+ html,
9333
+ styleBlockMatches(html),
9334
+ (style, css) => replaceInner(
9335
+ style,
9336
+ css,
9337
+ "</style>".length,
9338
+ replaceMatches(
9339
+ css,
9340
+ fontFaceBlockMatches(css),
9341
+ (face, body) => replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed))
9342
+ )
9343
+ )
9344
+ );
9304
9345
  }
9305
9346
  function renderGsapDist() {
9306
9347
  try {
@@ -9326,32 +9367,42 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9326
9367
  return `${prefix}${gsapDist}${file}${suffix}`;
9327
9368
  });
9328
9369
  }
9329
- function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9370
+ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9330
9371
  if (!isPathInside(htmlPath, projectDir)) return html;
9331
9372
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9332
9373
  if (!entryPath.includes("/")) return html;
9333
9374
  const { document: document2 } = parseHTML5(html);
9334
9375
  const assetExists = projectAssetExists(projectDir);
9376
+ const charge = (bytes) => budget.chargeGenerated(entryPath, bytes);
9335
9377
  rewriteAssetPaths(
9336
9378
  document2.querySelectorAll("[src], [href], [srcset]"),
9337
9379
  entryPath,
9338
9380
  (el, attr) => el.getAttribute(attr),
9339
9381
  (el, attr, value) => el.setAttribute(attr, value),
9340
- assetExists
9382
+ assetExists,
9383
+ charge
9341
9384
  );
9342
9385
  rewriteInlineStyleAssetUrls(
9343
9386
  document2.querySelectorAll("[style]"),
9344
9387
  entryPath,
9345
9388
  (el) => el.getAttribute("style"),
9346
9389
  (el, value) => el.setAttribute("style", value),
9347
- assetExists
9390
+ assetExists,
9391
+ charge
9348
9392
  );
9349
9393
  for (const style of document2.querySelectorAll("style")) {
9350
- style.textContent = rewriteCssAssetUrls(style.textContent || "", entryPath, assetExists);
9394
+ style.textContent = rewriteCssAssetUrls(
9395
+ style.textContent || "",
9396
+ entryPath,
9397
+ assetExists,
9398
+ charge
9399
+ );
9351
9400
  }
9352
9401
  return document2.toString();
9353
9402
  }
9354
- function bindVariableMediaSources(html, variables) {
9403
+ var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
9404
+ var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
9405
+ function bindVariableMediaSources(html, variables, budget, log) {
9355
9406
  if (!html.includes("data-var-src")) return html;
9356
9407
  const { document: document2 } = parseHTML5(html);
9357
9408
  const declared = {};
@@ -9362,8 +9413,17 @@ function bindVariableMediaSources(html, variables) {
9362
9413
  let changed = false;
9363
9414
  for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
9364
9415
  if (el.closest("[data-variable-values]")) continue;
9365
- const src = boundMediaSrc(el, values);
9366
- if (src === null || el.getAttribute("src") === src) continue;
9416
+ const bound = boundMediaSrc(el, values);
9417
+ if (bound === null) continue;
9418
+ const src = bound.trim();
9419
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
9420
+ log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
9421
+ length: src.length
9422
+ });
9423
+ continue;
9424
+ }
9425
+ if (el.getAttribute("src") === src) continue;
9426
+ budget.chargeGenerated("variable media sources", src.length);
9367
9427
  el.setAttribute("src", src);
9368
9428
  changed = true;
9369
9429
  }
@@ -9383,10 +9443,18 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9383
9443
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9384
9444
  }
9385
9445
  assertCompositionFileSize(htmlPath, basename5(htmlPath));
9386
- const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9446
+ const budget = new CompositionExpansionBudget();
9447
+ const entryHtml = rebaseDirectEntryAssetPaths(
9448
+ readTextFile(htmlPath),
9449
+ projectDir,
9450
+ htmlPath,
9451
+ budget
9452
+ );
9387
9453
  const rawHtml = bindVariableMediaSources(
9388
9454
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9389
- options.variables ?? {}
9455
+ options.variables ?? {},
9456
+ budget,
9457
+ options.log
9390
9458
  );
9391
9459
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9392
9460
  const probes = /* @__PURE__ */ new Map();
@@ -9417,7 +9485,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9417
9485
  projectDir,
9418
9486
  options.variables ?? {},
9419
9487
  assetRoot,
9420
- outsideFiles
9488
+ outsideFiles,
9489
+ budget
9421
9490
  );
9422
9491
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9423
9492
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9496,6 +9565,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9496
9565
  htmlWithPreparedGifs,
9497
9566
  projectDir,
9498
9567
  assetRoot,
9568
+ budget,
9499
9569
  options.log
9500
9570
  );
9501
9571
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
@@ -6959,6 +6959,16 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6959
6959
  `Composition file "${file}" is ${megabytes(bytes)}, over the ${megabytes(MAX_COMPOSITION_HTML_BYTES)} limit for one composition HTML file. Keep large data such as images, fonts and JSON in separate asset files and reference them by path instead of inlining them.`,
6960
6960
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6961
6961
  );
6962
+ var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
6963
+ function generatedTooLarge(file, bytes) {
6964
+ if (file === "composition variables") {
6965
+ return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
6966
+ }
6967
+ if (file === "variable media sources") {
6968
+ return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
6969
+ }
6970
+ return `Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ${megabytes(bytes)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`;
6971
+ }
6962
6972
  var CompositionExpansionBudget = class {
6963
6973
  bytes = 0;
6964
6974
  mounts = 0;
@@ -6967,10 +6977,16 @@ var CompositionExpansionBudget = class {
6967
6977
  chargeGenerated(file, bytes) {
6968
6978
  this.generated += bytes;
6969
6979
  if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
6970
- throw new CompositionTooLargeError(
6971
- `Scripts and styles generated for sub-composition mounts, ending at "${file}", add up to ${megabytes(this.generated)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`,
6972
- { bytes: this.generated, limitBytes: MAX_EXPANDED_COMPOSITION_BYTES, exceeded: "generated" }
6973
- );
6980
+ throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
6981
+ bytes: this.generated,
6982
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
6983
+ exceeded: "generated"
6984
+ });
6985
+ }
6986
+ chargeGeneratedIfItFits(bytes) {
6987
+ if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
6988
+ this.generated += bytes;
6989
+ return true;
6974
6990
  }
6975
6991
  charge(file, bytes) {
6976
6992
  this.bytes += bytes;
@@ -8682,7 +8698,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8682
8698
  }
8683
8699
  return document2.toString();
8684
8700
  }
8685
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8701
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
8686
8702
  const { document: document2 } = parseHTML5(html);
8687
8703
  const head = document2.querySelector("head");
8688
8704
  const body = document2.querySelector("body");
@@ -8691,11 +8707,11 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8691
8707
  const emitted = emitRootCompositionVariableStyles(
8692
8708
  document2,
8693
8709
  {},
8694
- variableOverrides
8710
+ variableOverrides,
8711
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8695
8712
  );
8696
8713
  return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8697
8714
  }
8698
- const budget = new CompositionExpansionBudget();
8699
8715
  const readOnce = /* @__PURE__ */ new Map();
8700
8716
  const readMountHtml = (srcPath) => {
8701
8717
  const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
@@ -8730,6 +8746,10 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8730
8746
  hostIdentityMap: hostIdentityByElement,
8731
8747
  readVariableDefaults: readDeclaredDefaults,
8732
8748
  parseHostVariables: parseHostVariableValues,
8749
+ resolveFilePath: (srcPath) => {
8750
+ const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
8751
+ return file && relative2(projectDir, file).split(sep3).join("/");
8752
+ },
8733
8753
  resolveHtml: (srcPath) => {
8734
8754
  const compHtml = resolveMountHtml(srcPath);
8735
8755
  if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
@@ -8820,7 +8840,8 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8820
8840
  emitRootCompositionVariableStyles(
8821
8841
  document2,
8822
8842
  result.variablesByComp,
8823
- variableOverrides
8843
+ variableOverrides,
8844
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8824
8845
  );
8825
8846
  assignMediaRenderIds(document2);
8826
8847
  return { html: document2.toString(), variablesByComp: result.variablesByComp };
@@ -9242,10 +9263,6 @@ function localizeFontFaceUrls(html, downloadDir) {
9242
9263
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9243
9264
  );
9244
9265
  }
9245
- function urlOccurrenceRe(localPath) {
9246
- const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9247
- return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
9248
- }
9249
9266
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
9250
9267
  async function readLocalFont(absPath) {
9251
9268
  const chunks = [];
@@ -9260,59 +9277,83 @@ async function readLocalFont(absPath) {
9260
9277
  }
9261
9278
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9262
9279
  }
9263
- async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
9264
- const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
9265
- let result = html;
9266
- const embeddedPaths = /* @__PURE__ */ new Set();
9280
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9281
+ const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9282
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9283
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9284
+ return void 0;
9285
+ }
9286
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9287
+ if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
9288
+ const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9289
+ try {
9290
+ const font = await readLocalFont(absPath);
9291
+ if (font.kind === "file-backed") {
9292
+ dataUriByAbsolutePath.set(absPath, void 0);
9293
+ defaultLogger.debug(
9294
+ `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9295
+ );
9296
+ return void 0;
9297
+ }
9298
+ const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
9299
+ const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
9300
+ dataUriByAbsolutePath.set(absPath, dataUri);
9301
+ defaultLogger.debug(
9302
+ `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9303
+ );
9304
+ return dataUri;
9305
+ } catch (error) {
9306
+ defaultLogger.warn(
9307
+ `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9308
+ );
9309
+ return void 0;
9310
+ }
9311
+ }
9312
+ var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
9313
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
9314
+ const dataUriByPath = /* @__PURE__ */ new Map();
9267
9315
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
9268
- const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
9269
9316
  for (const { parts: style } of styleBlockMatches(html)) {
9270
9317
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
9271
- const block = face[1];
9272
- for (const { parts } of localFontFaceUrlMatches(block)) {
9318
+ for (const { parts } of localFontFaceUrlMatches(face[1])) {
9273
9319
  const localPath = parts[1];
9274
- if (!localPath || embeddedPaths.has(localPath)) continue;
9275
- const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9276
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
9277
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9278
- embeddedPaths.add(localPath);
9279
- continue;
9280
- }
9281
- if (isPrivateCompositionFile(projectDir, absPath)) continue;
9282
- const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9283
- try {
9284
- if (fileBackedAbsolutePaths.has(absPath)) {
9285
- embeddedPaths.add(localPath);
9286
- continue;
9287
- }
9288
- let dataUri = dataUriByAbsolutePath.get(absPath);
9289
- if (!dataUri) {
9290
- const font = await readLocalFont(absPath);
9291
- if (font.kind === "file-backed") {
9292
- fileBackedAbsolutePaths.add(absPath);
9293
- defaultLogger.debug(
9294
- `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9295
- );
9296
- embeddedPaths.add(localPath);
9297
- continue;
9298
- }
9299
- dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
9300
- dataUriByAbsolutePath.set(absPath, dataUri);
9301
- defaultLogger.debug(
9302
- `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9303
- );
9304
- }
9305
- result = result.replace(urlOccurrenceRe(localPath), `url("${dataUri}")`);
9306
- embeddedPaths.add(localPath);
9307
- } catch (error) {
9308
- defaultLogger.warn(
9309
- `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9310
- );
9311
- }
9320
+ if (!localPath || dataUriByPath.has(localPath)) continue;
9321
+ dataUriByPath.set(
9322
+ localPath,
9323
+ await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
9324
+ );
9312
9325
  }
9313
9326
  }
9314
9327
  }
9315
- return result;
9328
+ if (![...dataUriByPath.values()].some(Boolean)) return html;
9329
+ let warned = false;
9330
+ const embed = (source, localPath) => {
9331
+ const dataUri = dataUriByPath.get(localPath);
9332
+ if (!dataUri) return source;
9333
+ const inlined = `url("${dataUri}")`;
9334
+ if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
9335
+ if (!warned) {
9336
+ warned = true;
9337
+ log.warn(
9338
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9339
+ );
9340
+ }
9341
+ return source;
9342
+ };
9343
+ return replaceMatches(
9344
+ html,
9345
+ styleBlockMatches(html),
9346
+ (style, css) => replaceInner(
9347
+ style,
9348
+ css,
9349
+ "</style>".length,
9350
+ replaceMatches(
9351
+ css,
9352
+ fontFaceBlockMatches(css),
9353
+ (face, body) => replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed))
9354
+ )
9355
+ )
9356
+ );
9316
9357
  }
9317
9358
  function renderGsapDist() {
9318
9359
  try {
@@ -9338,32 +9379,42 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9338
9379
  return `${prefix}${gsapDist}${file}${suffix}`;
9339
9380
  });
9340
9381
  }
9341
- function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9382
+ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9342
9383
  if (!isPathInside(htmlPath, projectDir)) return html;
9343
9384
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9344
9385
  if (!entryPath.includes("/")) return html;
9345
9386
  const { document: document2 } = parseHTML5(html);
9346
9387
  const assetExists = projectAssetExists(projectDir);
9388
+ const charge = (bytes) => budget.chargeGenerated(entryPath, bytes);
9347
9389
  rewriteAssetPaths(
9348
9390
  document2.querySelectorAll("[src], [href], [srcset]"),
9349
9391
  entryPath,
9350
9392
  (el, attr) => el.getAttribute(attr),
9351
9393
  (el, attr, value) => el.setAttribute(attr, value),
9352
- assetExists
9394
+ assetExists,
9395
+ charge
9353
9396
  );
9354
9397
  rewriteInlineStyleAssetUrls(
9355
9398
  document2.querySelectorAll("[style]"),
9356
9399
  entryPath,
9357
9400
  (el) => el.getAttribute("style"),
9358
9401
  (el, value) => el.setAttribute("style", value),
9359
- assetExists
9402
+ assetExists,
9403
+ charge
9360
9404
  );
9361
9405
  for (const style of document2.querySelectorAll("style")) {
9362
- style.textContent = rewriteCssAssetUrls(style.textContent || "", entryPath, assetExists);
9406
+ style.textContent = rewriteCssAssetUrls(
9407
+ style.textContent || "",
9408
+ entryPath,
9409
+ assetExists,
9410
+ charge
9411
+ );
9363
9412
  }
9364
9413
  return document2.toString();
9365
9414
  }
9366
- function bindVariableMediaSources(html, variables) {
9415
+ var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
9416
+ var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
9417
+ function bindVariableMediaSources(html, variables, budget, log) {
9367
9418
  if (!html.includes("data-var-src")) return html;
9368
9419
  const { document: document2 } = parseHTML5(html);
9369
9420
  const declared = {};
@@ -9374,8 +9425,17 @@ function bindVariableMediaSources(html, variables) {
9374
9425
  let changed = false;
9375
9426
  for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
9376
9427
  if (el.closest("[data-variable-values]")) continue;
9377
- const src = boundMediaSrc(el, values);
9378
- if (src === null || el.getAttribute("src") === src) continue;
9428
+ const bound = boundMediaSrc(el, values);
9429
+ if (bound === null) continue;
9430
+ const src = bound.trim();
9431
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
9432
+ log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
9433
+ length: src.length
9434
+ });
9435
+ continue;
9436
+ }
9437
+ if (el.getAttribute("src") === src) continue;
9438
+ budget.chargeGenerated("variable media sources", src.length);
9379
9439
  el.setAttribute("src", src);
9380
9440
  changed = true;
9381
9441
  }
@@ -9395,10 +9455,18 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9395
9455
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9396
9456
  }
9397
9457
  assertCompositionFileSize(htmlPath, basename5(htmlPath));
9398
- const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9458
+ const budget = new CompositionExpansionBudget();
9459
+ const entryHtml = rebaseDirectEntryAssetPaths(
9460
+ readTextFile(htmlPath),
9461
+ projectDir,
9462
+ htmlPath,
9463
+ budget
9464
+ );
9399
9465
  const rawHtml = bindVariableMediaSources(
9400
9466
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9401
- options.variables ?? {}
9467
+ options.variables ?? {},
9468
+ budget,
9469
+ options.log
9402
9470
  );
9403
9471
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9404
9472
  const probes = /* @__PURE__ */ new Map();
@@ -9429,7 +9497,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9429
9497
  projectDir,
9430
9498
  options.variables ?? {},
9431
9499
  assetRoot,
9432
- outsideFiles
9500
+ outsideFiles,
9501
+ budget
9433
9502
  );
9434
9503
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9435
9504
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9508,6 +9577,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9508
9577
  htmlWithPreparedGifs,
9509
9578
  projectDir,
9510
9579
  assetRoot,
9580
+ budget,
9511
9581
  options.log
9512
9582
  );
9513
9583
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
@@ -16,6 +16,7 @@ export declare class CompositionExpansionBudget {
16
16
  private generated;
17
17
  /** `bytes` may be negative when a reserved upper bound is settled to the real size. */
18
18
  chargeGenerated(file: string, bytes: number): void;
19
+ chargeGeneratedIfItFits(bytes: number): boolean;
19
20
  charge(file: string, bytes: number): void;
20
21
  }
21
22
  /**