@hyperframes/producer 0.9.72 → 0.9.74

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
@@ -7099,92 +7099,7 @@ import { privateCacheRoot } from "@hyperframes/engine";
7099
7099
  import { suggestMatchingPreset } from "@hyperframes/core";
7100
7100
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
7101
7101
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
7102
-
7103
- // src/services/compositionSizeLimit.ts
7104
- import { statSync as statSync6 } from "node:fs";
7105
- var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
7106
- var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
7107
- var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
7108
- var MAX_EXPANDED_COMPOSITION_BYTES = 4 * MAX_COMPOSITION_HTML_BYTES;
7109
- var MAX_COMPOSITION_MOUNTS = 1e4;
7110
- var CompositionTooLargeError = class extends Error {
7111
- constructor(message, publicMetadata) {
7112
- super(message);
7113
- this.publicMetadata = publicMetadata;
7114
- this.name = "CompositionTooLargeError";
7115
- }
7116
- publicMetadata;
7117
- code = COMPOSITION_TOO_LARGE;
7118
- // The producer server reads these off the error for the wire envelope.
7119
- owner = "user";
7120
- retryable = false;
7121
- };
7122
- var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
7123
- `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.`,
7124
- { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
7125
- );
7126
- var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
7127
- var REMOTE_SCRIPTS = "remote scripts";
7128
- var REMOTE_STYLESHEETS = "remote stylesheets";
7129
- function generatedTooLarge(file, bytes) {
7130
- if (file === "composition variables") {
7131
- return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
7132
- }
7133
- if (file === "variable media sources") {
7134
- return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
7135
- }
7136
- if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
7137
- return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
7138
- }
7139
- 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.`;
7140
- }
7141
- var CompositionExpansionBudget = class {
7142
- bytes = 0;
7143
- mounts = 0;
7144
- generated = 0;
7145
- /** `bytes` may be negative when a reserved upper bound is settled to the real size. */
7146
- chargeGenerated(file, bytes) {
7147
- this.generated += bytes;
7148
- if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
7149
- throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
7150
- bytes: this.generated,
7151
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
7152
- exceeded: "generated"
7153
- });
7154
- }
7155
- chargeGeneratedIfItFits(bytes) {
7156
- if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
7157
- this.generated += bytes;
7158
- return true;
7159
- }
7160
- charge(file, bytes) {
7161
- this.bytes += bytes;
7162
- this.mounts += 1;
7163
- if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
7164
- return;
7165
- }
7166
- throw new CompositionTooLargeError(
7167
- `Sub-composition mounts, ending at "${file}", add up to ${megabytes(this.bytes)} across ${this.mounts} mounts. One render inlines at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} of composition HTML in at most ${MAX_COMPOSITION_MOUNTS} mounts. Mount large or repeated scenes fewer times.`,
7168
- {
7169
- bytes: this.bytes,
7170
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
7171
- mounts: this.mounts,
7172
- exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
7173
- }
7174
- );
7175
- }
7176
- };
7177
- function assertCompositionFileSize(path, file) {
7178
- let bytes;
7179
- try {
7180
- const stats = statSync6(path);
7181
- if (!stats.isFile()) return;
7182
- bytes = stats.size;
7183
- } catch {
7184
- return;
7185
- }
7186
- if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
7187
- }
7102
+ import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7188
7103
 
7189
7104
  // src/services/htmlCompiler.ts
7190
7105
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
@@ -7202,7 +7117,7 @@ import {
7202
7117
  stylesheetLinkMatches
7203
7118
  } from "@hyperframes/parsers/css-url-scans";
7204
7119
  import { createHash as createHash6 } from "node:crypto";
7205
- import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7120
+ import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8, statSync as statSync8 } from "fs";
7206
7121
  import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7207
7122
  import { parseHTML as parseHTML5 } from "linkedom";
7208
7123
 
@@ -7280,6 +7195,13 @@ import {
7280
7195
  } from "@hyperframes/parsers/asset-resolution";
7281
7196
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7282
7197
  import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
7198
+ import {
7199
+ assertCompositionFileSize,
7200
+ CompositionExpansionBudget,
7201
+ ENTRY_PAGE,
7202
+ REMOTE_SCRIPTS,
7203
+ REMOTE_STYLESHEETS
7204
+ } from "@hyperframes/core/compiler";
7283
7205
 
7284
7206
  // src/services/renderMediaCollector.ts
7285
7207
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7474,7 +7396,7 @@ import {
7474
7396
 
7475
7397
  // src/services/animatedGifPrep.ts
7476
7398
  import { createHash as createHash4 } from "node:crypto";
7477
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7399
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7478
7400
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7479
7401
  import { parseHTML as parseHTML3 } from "linkedom";
7480
7402
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7533,7 +7455,7 @@ function resolveLocalImageSourcePath(src, options) {
7533
7455
  }
7534
7456
  function isUsableFile(path) {
7535
7457
  try {
7536
- const stat = statSync7(path);
7458
+ const stat = statSync6(path);
7537
7459
  return stat.isFile() && stat.size > 0;
7538
7460
  } catch {
7539
7461
  return false;
@@ -7798,7 +7720,7 @@ import {
7798
7720
  readFileSync as readFileSync7,
7799
7721
  readSync as readSync3,
7800
7722
  rmSync as rmSync10,
7801
- statSync as statSync8,
7723
+ statSync as statSync7,
7802
7724
  writeFileSync as writeFileSync3
7803
7725
  } from "node:fs";
7804
7726
  import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
@@ -8042,7 +7964,7 @@ function resolveImageSource(src, options) {
8042
7964
  }
8043
7965
  function isUsableFile2(path) {
8044
7966
  try {
8045
- return statSync8(path).size > 0;
7967
+ return statSync7(path).size > 0;
8046
7968
  } catch {
8047
7969
  return false;
8048
7970
  }
@@ -8529,16 +8451,64 @@ function detectShaderTransitionUsage(html) {
8529
8451
  }
8530
8452
  return false;
8531
8453
  }
8532
- async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
8454
+ var MAX_REMOTE_ASSETS = 1e3;
8455
+ var ASSET_DOWNLOADS_AT_ONCE = 8;
8456
+ var AssetDownloads = class {
8457
+ reserved = /* @__PURE__ */ new Set();
8458
+ running = 0;
8459
+ queued = [];
8460
+ ended = new AbortController();
8461
+ signal;
8462
+ constructor(cancel) {
8463
+ this.signal = cancel ? AbortSignal.any([cancel, this.ended.signal]) : this.ended.signal;
8464
+ }
8465
+ /** Stops every download still running or queued: the compile that owns them has returned. */
8466
+ end() {
8467
+ this.ended.abort(new Error("The compile that started this download has ended"));
8468
+ }
8469
+ /** Throws before any of `urls` downloads when they would take the compile past the cap. */
8470
+ reserve(urls) {
8471
+ this.signal?.throwIfAborted();
8472
+ const fresh = new Set([...urls].filter((url) => !this.reserved.has(url)));
8473
+ if (this.reserved.size + fresh.size > MAX_REMOTE_ASSETS) {
8474
+ throw new Error(
8475
+ `The composition links more than ${MAX_REMOTE_ASSETS} remote media, image and font files; at most ${MAX_REMOTE_ASSETS} are downloaded at compile time`
8476
+ );
8477
+ }
8478
+ for (const url of fresh) this.reserved.add(url);
8479
+ }
8480
+ async download(url, destDir) {
8481
+ while (this.running >= ASSET_DOWNLOADS_AT_ONCE) {
8482
+ await new Promise((resolve14) => this.queued.push(resolve14));
8483
+ }
8484
+ if (this.signal?.aborted) {
8485
+ this.queued.shift()?.();
8486
+ this.signal.throwIfAborted();
8487
+ }
8488
+ this.running += 1;
8489
+ try {
8490
+ return await downloadToTemp(url, destDir, void 0, this.signal, void 0, {
8491
+ onTelemetry: logRemoteDownloadTelemetry
8492
+ });
8493
+ } finally {
8494
+ this.running -= 1;
8495
+ this.queued.shift()?.();
8496
+ }
8497
+ }
8498
+ };
8499
+ var downloadAsset = (url, destDir, assets) => assets ? assets.download(url, destDir) : downloadToTemp(url, destDir, void 0, void 0, void 0, {
8500
+ onTelemetry: logRemoteDownloadTelemetry
8501
+ });
8502
+ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, run, assetRoot) {
8533
8503
  let filePath = src;
8534
8504
  if (isHttpUrl(src)) {
8535
8505
  const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8536
8506
  if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8507
+ run?.assets.reserve([src]);
8537
8508
  try {
8538
- filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8539
- onTelemetry: logRemoteDownloadTelemetry
8540
- });
8541
- } catch {
8509
+ filePath = await downloadAsset(src, remoteDir, run?.assets);
8510
+ } catch (err) {
8511
+ if (run?.assets.signal?.aborted) throw err;
8542
8512
  return { duration: null, resolvedPath: src };
8543
8513
  }
8544
8514
  } else {
@@ -8566,13 +8536,17 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8566
8536
  const probe = () => withMediaProbeSlot(async () => {
8567
8537
  try {
8568
8538
  await assertMediaPayload(filePath, elementIdentity);
8569
- const profile = await probeMediaProfile2(filePath);
8539
+ const signal = run?.assets.signal;
8540
+ const profile = await probeMediaProfile2(filePath, { signal });
8570
8541
  if (tagName === "video") {
8571
- return { profile, fileDuration: (await extractMediaMetadata(filePath)).durationSeconds };
8542
+ const { durationSeconds } = await extractMediaMetadata(filePath, { signal });
8543
+ return { profile, fileDuration: durationSeconds };
8572
8544
  }
8573
8545
  try {
8574
- return { profile, fileDuration: (await extractAudioMetadata(filePath)).durationSeconds };
8546
+ const { durationSeconds } = await extractAudioMetadata(filePath, { signal });
8547
+ return { profile, fileDuration: durationSeconds };
8575
8548
  } catch {
8549
+ if (signal?.aborted) throw signal.reason;
8576
8550
  return { profile, fileDuration: null };
8577
8551
  }
8578
8552
  } catch (error) {
@@ -8580,10 +8554,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8580
8554
  }
8581
8555
  });
8582
8556
  const key = `${tagName}\0${filePath}`;
8583
- let probed = probes?.get(key);
8557
+ let probed = run?.probes.get(key);
8584
8558
  if (!probed) {
8585
8559
  probed = probe();
8586
- probes?.set(key, probed);
8560
+ run?.probes.set(key, probed);
8587
8561
  }
8588
8562
  const outcome = await probed;
8589
8563
  if ("error" in outcome) {
@@ -8622,12 +8596,13 @@ function markInferredVariableMediaDurations(html, unresolvedMedia) {
8622
8596
  }
8623
8597
  return changed ? document2.toString() : html;
8624
8598
  }
8625
- async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, probes, assetRoot) {
8599
+ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, run, assetRoot) {
8626
8600
  const { html: staticCompiled, unresolved } = compileTimingAttrs(html);
8627
8601
  const mediaUnresolved = unresolved.filter(
8628
8602
  (el) => (el.tagName === "video" || el.tagName === "audio") && el.src
8629
8603
  );
8630
8604
  const unresolvedCompositions = unresolved.filter((el) => el.tagName === "div");
8605
+ run?.assets.reserve(mediaUnresolved.map((el) => el.src).filter(isHttpUrl));
8631
8606
  const resolvedResults = await Promise.all(
8632
8607
  mediaUnresolved.map(
8633
8608
  (el) => resolveMediaDuration(
@@ -8641,7 +8616,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8641
8616
  el.id,
8642
8617
  log,
8643
8618
  urlByAbsentLocalPath,
8644
- probes,
8619
+ run,
8645
8620
  assetRoot
8646
8621
  ).then(({ duration }) => ({ id: el.id, duration }))
8647
8622
  )
@@ -8653,8 +8628,10 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8653
8628
  let compiledHtml = resolutions.length > 0 ? injectDurations(markedStaticHtml, resolutions) : markedStaticHtml;
8654
8629
  const preResolved = extractResolvedMedia(compiledHtml);
8655
8630
  const hiddenVideoIds = collectHiddenVideoIds(compiledHtml);
8631
+ const clampable = preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id));
8632
+ run?.assets.reserve(clampable.map((el) => el.src).filter(isHttpUrl));
8656
8633
  const clampResults = await Promise.all(
8657
- preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id)).map(async (el) => {
8634
+ clampable.map(async (el) => {
8658
8635
  const { duration: maxDuration } = await resolveMediaDuration(
8659
8636
  el.src,
8660
8637
  el.mediaStart,
@@ -8666,7 +8643,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8666
8643
  el.id,
8667
8644
  log,
8668
8645
  void 0,
8669
- probes,
8646
+ run,
8670
8647
  assetRoot
8671
8648
  );
8672
8649
  return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src };
@@ -8689,7 +8666,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8689
8666
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
8690
8667
  return { html: compiledHtml, unresolvedCompositions };
8691
8668
  }
8692
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8669
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, run, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8693
8670
  const subCompositions = /* @__PURE__ */ new Map();
8694
8671
  const { document: document2 } = parseHTML5(html);
8695
8672
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -8724,7 +8701,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8724
8701
  downloadDir,
8725
8702
  void 0,
8726
8703
  urlByAbsentLocalPath,
8727
- probes,
8704
+ run,
8728
8705
  assetRoot
8729
8706
  );
8730
8707
  const nested = await parseSubCompositions(
@@ -8733,7 +8710,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8733
8710
  downloadDir,
8734
8711
  item.nestedVisited,
8735
8712
  urlByAbsentLocalPath,
8736
- probes,
8713
+ run,
8737
8714
  assetRoot,
8738
8715
  outsideFiles,
8739
8716
  compiledSrcs
@@ -8791,13 +8768,28 @@ function promoteCssImportsToLinkTags(html) {
8791
8768
  return document2.toString();
8792
8769
  }
8793
8770
  var ProducerHostIdentityMap = class extends Map {
8794
- #document;
8795
8771
  #lateInstanceByCompositionId = /* @__PURE__ */ new Map();
8772
+ /** How many elements carry each composition id: the page once, then each mount's copy once. */
8773
+ #idCounts = /* @__PURE__ */ new Map();
8774
+ /** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */
8775
+ #uncounted;
8796
8776
  constructor(document2, initialHosts) {
8797
8777
  super(assignBundledRuntimeCompositionIds(initialHosts));
8798
- this.#document = document2;
8778
+ this.#uncounted = [document2];
8779
+ }
8780
+ #countUncopied() {
8781
+ for (const root of this.#uncounted.splice(0)) {
8782
+ for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) {
8783
+ this.#adjust(element.getAttribute("data-composition-id"), 1);
8784
+ }
8785
+ }
8786
+ }
8787
+ #adjust(id, by) {
8788
+ if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by);
8799
8789
  }
8800
8790
  get(host) {
8791
+ this.#countUncopied();
8792
+ this.#uncounted.push(host);
8801
8793
  const existing = super.get(host);
8802
8794
  if (existing) return existing;
8803
8795
  const authoredCompositionId = (host.getAttribute("data-hf-original-composition-id") || host.getAttribute("data-composition-id") || "").trim() || null;
@@ -8806,17 +8798,19 @@ var ProducerHostIdentityMap = class extends Map {
8806
8798
  this.set(host, identity2);
8807
8799
  return identity2;
8808
8800
  }
8801
+ const ownId = host.getAttribute("data-composition-id");
8802
+ const heldByOthers = (id) => (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0;
8809
8803
  let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
8810
8804
  let runtimeCompositionId;
8811
8805
  do {
8812
8806
  instanceIndex += 1;
8813
8807
  runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
8814
- } while (Array.from(this.#document.querySelectorAll("[data-composition-id]")).some(
8815
- (element) => element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId
8816
- ));
8808
+ } while (heldByOthers(runtimeCompositionId));
8817
8809
  this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
8818
8810
  host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
8819
8811
  host.setAttribute("data-composition-id", runtimeCompositionId);
8812
+ this.#adjust(ownId, -1);
8813
+ this.#adjust(runtimeCompositionId, 1);
8820
8814
  const identity = { authoredCompositionId, runtimeCompositionId };
8821
8815
  this.set(host, identity);
8822
8816
  return identity;
@@ -8874,6 +8868,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8874
8868
  }
8875
8869
  function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
8876
8870
  const { document: document2 } = parseHTML5(html);
8871
+ budget.chargeElements(ENTRY_PAGE, document2.querySelectorAll("*").length);
8877
8872
  const head = document2.querySelector("head");
8878
8873
  const body = document2.querySelector("body");
8879
8874
  const hosts = Array.from(document2.querySelectorAll("[data-composition-src]"));
@@ -8931,6 +8926,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8931
8926
  return compHtml;
8932
8927
  },
8933
8928
  chargeEmitted: (srcPath, bytes) => budget.chargeGenerated(srcPath, bytes),
8929
+ chargeElements: (srcPath, count) => budget.chargeElements(srcPath, count),
8934
8930
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
8935
8931
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
8936
8932
  // against its own directory, project-root refs stay as authored.
@@ -9259,18 +9255,18 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9259
9255
  };
9260
9256
  }
9261
9257
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9262
- async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9258
+ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, assets, extraRewrite) {
9259
+ assets?.reserve(urlSet);
9263
9260
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9264
9261
  if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9265
9262
  const urlToLocal = /* @__PURE__ */ new Map();
9266
9263
  await Promise.all(
9267
9264
  [...urlSet].map(async (url) => {
9268
9265
  try {
9269
- const localPath = await downloadToTemp(url, remoteDir, void 0, void 0, void 0, {
9270
- onTelemetry: logRemoteDownloadTelemetry
9271
- });
9266
+ const localPath = await downloadAsset(url, remoteDir, assets);
9272
9267
  urlToLocal.set(url, localPath);
9273
9268
  } catch (err) {
9269
+ if (assets?.signal?.aborted) throw err;
9274
9270
  const identity = safeDownloadUrlIdentity(url);
9275
9271
  defaultLogger.warn(`[Compiler] ${warnLabel}, using original URL as fallback.`, {
9276
9272
  urlFingerprint: identity.urlFingerprint,
@@ -9296,14 +9292,15 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9296
9292
  defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
9297
9293
  return { html: result, remoteMediaAssets };
9298
9294
  }
9299
- async function localizeRemoteMediaSources(html, downloadDir) {
9295
+ async function localizeRemoteMediaSources(html, downloadDir, assets) {
9300
9296
  const urlSet = /* @__PURE__ */ new Set([...remoteSrcUrls(html, "media"), ...remoteSrcUrls(html, "source")]);
9301
9297
  const localized = await downloadAndRewriteUrls(
9302
9298
  urlSet,
9303
9299
  html,
9304
9300
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9305
9301
  "Remote media download failed",
9306
- "Localized remote media source(s)"
9302
+ "Localized remote media source(s)",
9303
+ assets
9307
9304
  );
9308
9305
  return { ...localized, html: dropBindingOnLocalizedMedia(localized.html) };
9309
9306
  }
@@ -9319,17 +9316,18 @@ function dropBindingOnLocalizedMedia(html) {
9319
9316
  }
9320
9317
  return changed ? document2.toString() : html;
9321
9318
  }
9322
- async function localizeRemoteImageSources(html, downloadDir) {
9319
+ async function localizeRemoteImageSources(html, downloadDir, assets) {
9323
9320
  const urlSet = new Set(remoteSrcUrls(html, "img"));
9324
9321
  return downloadAndRewriteUrls(
9325
9322
  urlSet,
9326
9323
  html,
9327
9324
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9328
9325
  "Remote image download failed",
9329
- "Localized remote image source(s)"
9326
+ "Localized remote image source(s)",
9327
+ assets
9330
9328
  );
9331
9329
  }
9332
- async function localizeRemoteBackgroundImages(html, downloadDir) {
9330
+ async function localizeRemoteBackgroundImages(html, downloadDir, assets) {
9333
9331
  const urlSet = /* @__PURE__ */ new Set();
9334
9332
  for (const { parts } of remoteBackgroundUrlMatches(html)) {
9335
9333
  if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
@@ -9340,6 +9338,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
9340
9338
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9341
9339
  "Remote background-image download failed",
9342
9340
  "Localized remote background-image(s)",
9341
+ assets,
9343
9342
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
9344
9343
  // replaceAll; this handles the unquoted url(https://..) form.
9345
9344
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
@@ -9496,13 +9495,14 @@ function collectFontFaceUrls(html) {
9496
9495
  async function localizeRemoteFontFaces(html, downloadDir) {
9497
9496
  return localizeFontFaceUrls(await inlineExternalFontStylesheets(html), downloadDir);
9498
9497
  }
9499
- function localizeFontFaceUrls(html, downloadDir) {
9498
+ function localizeFontFaceUrls(html, downloadDir, assets) {
9500
9499
  return downloadAndRewriteUrls(
9501
9500
  collectFontFaceUrls(html),
9502
9501
  html,
9503
9502
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9504
9503
  "Remote font download failed",
9505
9504
  "Localized remote font face(s)",
9505
+ assets,
9506
9506
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9507
9507
  );
9508
9508
  }
@@ -9520,16 +9520,24 @@ async function readLocalFont(absPath) {
9520
9520
  }
9521
9521
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9522
9522
  }
9523
- async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9524
- const absPath = localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath);
9525
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9526
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9527
- return void 0;
9523
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log, downloadedPath, reserve) {
9524
+ const absPath = downloadedPath ?? (localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath));
9525
+ if (downloadedPath === void 0) {
9526
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) {
9527
+ return void 0;
9528
+ }
9529
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9530
+ return void 0;
9531
+ }
9532
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9528
9533
  }
9529
- if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9530
9534
  if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
9531
9535
  const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9532
9536
  try {
9537
+ if (!reserve(Math.ceil(statSync8(absPath).size / 3) * 4 + 64)) {
9538
+ dataUriByAbsolutePath.set(absPath, void 0);
9539
+ return void 0;
9540
+ }
9533
9541
  const font = await readLocalFont(absPath);
9534
9542
  if (font.kind === "file-backed") {
9535
9543
  dataUriByAbsolutePath.set(absPath, void 0);
@@ -9553,9 +9561,26 @@ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsol
9553
9561
  }
9554
9562
  }
9555
9563
  var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
9556
- async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
9564
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger, downloadedFonts = /* @__PURE__ */ new Map()) {
9557
9565
  const dataUriByPath = /* @__PURE__ */ new Map();
9558
9566
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
9567
+ let warned = false;
9568
+ const keptFileBacked = (localPath) => {
9569
+ if (warned) return;
9570
+ warned = true;
9571
+ log.warn(
9572
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9573
+ );
9574
+ };
9575
+ let reserved = 0;
9576
+ const reserveFor = (localPath) => (bytes) => {
9577
+ if (reserved + bytes > budget.generatedRoom) {
9578
+ keptFileBacked(localPath);
9579
+ return false;
9580
+ }
9581
+ reserved += bytes;
9582
+ return true;
9583
+ };
9559
9584
  for (const { parts: style } of styleBlockMatches(html)) {
9560
9585
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
9561
9586
  for (const { parts } of localFontFaceUrlMatches(face[1])) {
@@ -9563,24 +9588,26 @@ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = de
9563
9588
  if (!localPath || dataUriByPath.has(localPath)) continue;
9564
9589
  dataUriByPath.set(
9565
9590
  localPath,
9566
- await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
9591
+ await localFontDataUri(
9592
+ localPath,
9593
+ projectDir,
9594
+ assetRoot,
9595
+ dataUriByAbsolutePath,
9596
+ log,
9597
+ downloadedFonts.get(localPath),
9598
+ reserveFor(localPath)
9599
+ )
9567
9600
  );
9568
9601
  }
9569
9602
  }
9570
9603
  }
9571
9604
  if (![...dataUriByPath.values()].some(Boolean)) return html;
9572
- let warned = false;
9573
9605
  const embed = (source, localPath) => {
9574
9606
  const dataUri = dataUriByPath.get(localPath);
9575
9607
  if (!dataUri) return source;
9576
9608
  const inlined = `url("${dataUri}")`;
9577
9609
  if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
9578
- if (!warned) {
9579
- warned = true;
9580
- log.warn(
9581
- `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9582
- );
9583
- }
9610
+ keptFileBacked(localPath);
9584
9611
  return source;
9585
9612
  };
9586
9613
  return replaceMatches(
@@ -9686,6 +9713,14 @@ function bindVariableMediaSources(html, variables, budget, log) {
9686
9713
  }
9687
9714
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative3(projectDir, htmlPath).split(sep4).join("/") : basename6(htmlPath);
9688
9715
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9716
+ const assets = new AssetDownloads(options.abortSignal);
9717
+ try {
9718
+ return await compileWithAssets(projectDir, htmlPath, downloadDir, options, assets);
9719
+ } finally {
9720
+ assets.end();
9721
+ }
9722
+ }
9723
+ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, assets) {
9689
9724
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9690
9725
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
9691
9726
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
@@ -9712,7 +9747,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9712
9747
  options.log
9713
9748
  );
9714
9749
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9715
- const probes = /* @__PURE__ */ new Map();
9750
+ const run = { probes: /* @__PURE__ */ new Map(), assets };
9716
9751
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
9717
9752
  rawHtml,
9718
9753
  projectDir,
@@ -9720,7 +9755,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9720
9755
  downloadDir,
9721
9756
  options.log,
9722
9757
  options.urlByAbsentLocalPath,
9723
- probes,
9758
+ run,
9724
9759
  assetRoot
9725
9760
  );
9726
9761
  const { subCompositions } = await parseSubCompositions(
@@ -9729,7 +9764,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9729
9764
  downloadDir,
9730
9765
  void 0,
9731
9766
  options.urlByAbsentLocalPath,
9732
- probes,
9767
+ run,
9733
9768
  assetRoot,
9734
9769
  outsideFiles
9735
9770
  );
@@ -9782,11 +9817,12 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9782
9817
  );
9783
9818
  const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
9784
9819
  htmlWithDeferredScripts,
9785
- downloadDir
9820
+ downloadDir,
9821
+ run.assets
9786
9822
  );
9787
- const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir);
9788
- const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir);
9789
- const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir);
9823
+ const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir, run.assets);
9824
+ const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir, run.assets);
9825
+ const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir, run.assets);
9790
9826
  const {
9791
9827
  html: htmlWithJpegs,
9792
9828
  preparedAssets: preparedHeifAssets,
@@ -9823,7 +9859,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9823
9859
  projectDir,
9824
9860
  assetRoot,
9825
9861
  budget,
9826
- options.log
9862
+ options.log,
9863
+ remoteFontAssets
9827
9864
  );
9828
9865
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
9829
9866
  embeddedHtml,
@@ -10296,7 +10333,7 @@ function resolveEntryHtmlPath(input) {
10296
10333
  `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10297
10334
  );
10298
10335
  }
10299
- assertCompositionFileSize(path, relative4(projectDir, path));
10336
+ assertCompositionFileSize2(path, relative4(projectDir, path));
10300
10337
  return readTextFile2(path);
10301
10338
  };
10302
10339
  const htmlPath = join22(projectDir, entryFile);
@@ -11598,13 +11635,19 @@ async function runExtractVideosStage(input) {
11598
11635
  const videoPath = resolveProjectRelativeSrc4(v.src, projectDir, compiledDir);
11599
11636
  if (!opensLocally(videoPath, assetRoots)) return null;
11600
11637
  try {
11601
- const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata4(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata4(videoPath), {
11602
- signal: abortSignal,
11603
- maxTransientRetries: extractionPolicy.maxTransientRetries,
11604
- onRetry: () => {
11605
- hdrProbeTransientRetries += 1;
11638
+ const attempted = extractionPolicy.maxTransientRetries === 0 ? {
11639
+ result: await extractMediaMetadata4(videoPath, { signal: abortSignal }),
11640
+ retries: 0
11641
+ } : await runVideoExtractionWithRetry2(
11642
+ () => extractMediaMetadata4(videoPath, { signal: abortSignal }),
11643
+ {
11644
+ signal: abortSignal,
11645
+ maxTransientRetries: extractionPolicy.maxTransientRetries,
11646
+ onRetry: () => {
11647
+ hdrProbeTransientRetries += 1;
11648
+ }
11606
11649
  }
11607
- });
11650
+ );
11608
11651
  const meta = attempted.result;
11609
11652
  if (isHdrColorSpace2(meta.colorSpace)) {
11610
11653
  nativeHdrVideoIds.add(v.id);
@@ -11799,7 +11842,7 @@ async function appendVideoAudioFromProbe(input) {
11799
11842
  videos.map(async (video) => {
11800
11843
  const readFrom = isHttpUrl3(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
11801
11844
  if (readFrom === null) return null;
11802
- const metadata = await extractMediaMetadata4(readFrom);
11845
+ const metadata = await extractMediaMetadata4(readFrom, { signal: input.signal });
11803
11846
  const window2 = await resolveFinalFrameExtractionWindow2(
11804
11847
  readFrom,
11805
11848
  video,