@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.
@@ -2459,92 +2459,7 @@ import { privateCacheRoot } from "@hyperframes/engine";
2459
2459
  import { suggestMatchingPreset } from "@hyperframes/core";
2460
2460
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
2461
2461
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
2462
-
2463
- // src/services/compositionSizeLimit.ts
2464
- import { statSync as statSync3 } from "node:fs";
2465
- var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
2466
- var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
2467
- var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2468
- var MAX_EXPANDED_COMPOSITION_BYTES = 4 * MAX_COMPOSITION_HTML_BYTES;
2469
- var MAX_COMPOSITION_MOUNTS = 1e4;
2470
- var CompositionTooLargeError = class extends Error {
2471
- constructor(message, publicMetadata) {
2472
- super(message);
2473
- this.publicMetadata = publicMetadata;
2474
- this.name = "CompositionTooLargeError";
2475
- }
2476
- publicMetadata;
2477
- code = COMPOSITION_TOO_LARGE;
2478
- // The producer server reads these off the error for the wire envelope.
2479
- owner = "user";
2480
- retryable = false;
2481
- };
2482
- var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
2483
- `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.`,
2484
- { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
2485
- );
2486
- var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
2487
- var REMOTE_SCRIPTS = "remote scripts";
2488
- var REMOTE_STYLESHEETS = "remote stylesheets";
2489
- function generatedTooLarge(file, bytes) {
2490
- if (file === "composition variables") {
2491
- return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
2492
- }
2493
- if (file === "variable media sources") {
2494
- return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
2495
- }
2496
- if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
2497
- return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
2498
- }
2499
- 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.`;
2500
- }
2501
- var CompositionExpansionBudget = class {
2502
- bytes = 0;
2503
- mounts = 0;
2504
- generated = 0;
2505
- /** `bytes` may be negative when a reserved upper bound is settled to the real size. */
2506
- chargeGenerated(file, bytes) {
2507
- this.generated += bytes;
2508
- if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
2509
- throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
2510
- bytes: this.generated,
2511
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
2512
- exceeded: "generated"
2513
- });
2514
- }
2515
- chargeGeneratedIfItFits(bytes) {
2516
- if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
2517
- this.generated += bytes;
2518
- return true;
2519
- }
2520
- charge(file, bytes) {
2521
- this.bytes += bytes;
2522
- this.mounts += 1;
2523
- if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
2524
- return;
2525
- }
2526
- throw new CompositionTooLargeError(
2527
- `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.`,
2528
- {
2529
- bytes: this.bytes,
2530
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
2531
- mounts: this.mounts,
2532
- exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
2533
- }
2534
- );
2535
- }
2536
- };
2537
- function assertCompositionFileSize(path, file) {
2538
- let bytes;
2539
- try {
2540
- const stats = statSync3(path);
2541
- if (!stats.isFile()) return;
2542
- bytes = stats.size;
2543
- } catch {
2544
- return;
2545
- }
2546
- if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
2547
- }
2462
+ import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
2548
2463
 
2549
2464
  // src/services/htmlCompiler.ts
2550
2465
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
@@ -2562,7 +2477,7 @@ import {
2562
2477
  stylesheetLinkMatches
2563
2478
  } from "@hyperframes/parsers/css-url-scans";
2564
2479
  import { createHash as createHash5 } from "node:crypto";
2565
- import { createReadStream as createReadStream2, existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5 } from "fs";
2480
+ import { createReadStream as createReadStream2, existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5, statSync as statSync5 } from "fs";
2566
2481
  import { join as join9, dirname as dirname7, resolve as resolve6, basename as basename3, relative as relative2, sep as sep3 } from "path";
2567
2482
  import { parseHTML as parseHTML5 } from "linkedom";
2568
2483
 
@@ -2640,6 +2555,13 @@ import {
2640
2555
  } from "@hyperframes/parsers/asset-resolution";
2641
2556
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
2642
2557
  import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
2558
+ import {
2559
+ assertCompositionFileSize,
2560
+ CompositionExpansionBudget,
2561
+ ENTRY_PAGE,
2562
+ REMOTE_SCRIPTS,
2563
+ REMOTE_STYLESHEETS
2564
+ } from "@hyperframes/core/compiler";
2643
2565
 
2644
2566
  // src/services/renderMediaCollector.ts
2645
2567
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -2834,7 +2756,7 @@ import {
2834
2756
 
2835
2757
  // src/services/animatedGifPrep.ts
2836
2758
  import { createHash as createHash3 } from "node:crypto";
2837
- import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync4 } from "node:fs";
2759
+ import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync3 } from "node:fs";
2838
2760
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolve4 } from "node:path";
2839
2761
  import { parseHTML as parseHTML3 } from "linkedom";
2840
2762
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -2893,7 +2815,7 @@ function resolveLocalImageSourcePath(src, options) {
2893
2815
  }
2894
2816
  function isUsableFile(path) {
2895
2817
  try {
2896
- const stat = statSync4(path);
2818
+ const stat = statSync3(path);
2897
2819
  return stat.isFile() && stat.size > 0;
2898
2820
  } catch {
2899
2821
  return false;
@@ -3158,7 +3080,7 @@ import {
3158
3080
  readFileSync as readFileSync4,
3159
3081
  readSync,
3160
3082
  rmSync as rmSync3,
3161
- statSync as statSync5,
3083
+ statSync as statSync4,
3162
3084
  writeFileSync as writeFileSync2
3163
3085
  } from "node:fs";
3164
3086
  import { dirname as dirname5, join as join7, resolve as resolve5 } from "node:path";
@@ -3402,7 +3324,7 @@ function resolveImageSource(src, options) {
3402
3324
  }
3403
3325
  function isUsableFile2(path) {
3404
3326
  try {
3405
- return statSync5(path).size > 0;
3327
+ return statSync4(path).size > 0;
3406
3328
  } catch {
3407
3329
  return false;
3408
3330
  }
@@ -3889,16 +3811,64 @@ function detectShaderTransitionUsage(html) {
3889
3811
  }
3890
3812
  return false;
3891
3813
  }
3892
- async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
3814
+ var MAX_REMOTE_ASSETS = 1e3;
3815
+ var ASSET_DOWNLOADS_AT_ONCE = 8;
3816
+ var AssetDownloads = class {
3817
+ reserved = /* @__PURE__ */ new Set();
3818
+ running = 0;
3819
+ queued = [];
3820
+ ended = new AbortController();
3821
+ signal;
3822
+ constructor(cancel) {
3823
+ this.signal = cancel ? AbortSignal.any([cancel, this.ended.signal]) : this.ended.signal;
3824
+ }
3825
+ /** Stops every download still running or queued: the compile that owns them has returned. */
3826
+ end() {
3827
+ this.ended.abort(new Error("The compile that started this download has ended"));
3828
+ }
3829
+ /** Throws before any of `urls` downloads when they would take the compile past the cap. */
3830
+ reserve(urls) {
3831
+ this.signal?.throwIfAborted();
3832
+ const fresh = new Set([...urls].filter((url) => !this.reserved.has(url)));
3833
+ if (this.reserved.size + fresh.size > MAX_REMOTE_ASSETS) {
3834
+ throw new Error(
3835
+ `The composition links more than ${MAX_REMOTE_ASSETS} remote media, image and font files; at most ${MAX_REMOTE_ASSETS} are downloaded at compile time`
3836
+ );
3837
+ }
3838
+ for (const url of fresh) this.reserved.add(url);
3839
+ }
3840
+ async download(url, destDir) {
3841
+ while (this.running >= ASSET_DOWNLOADS_AT_ONCE) {
3842
+ await new Promise((resolve10) => this.queued.push(resolve10));
3843
+ }
3844
+ if (this.signal?.aborted) {
3845
+ this.queued.shift()?.();
3846
+ this.signal.throwIfAborted();
3847
+ }
3848
+ this.running += 1;
3849
+ try {
3850
+ return await downloadToTemp(url, destDir, void 0, this.signal, void 0, {
3851
+ onTelemetry: logRemoteDownloadTelemetry
3852
+ });
3853
+ } finally {
3854
+ this.running -= 1;
3855
+ this.queued.shift()?.();
3856
+ }
3857
+ }
3858
+ };
3859
+ var downloadAsset = (url, destDir, assets) => assets ? assets.download(url, destDir) : downloadToTemp(url, destDir, void 0, void 0, void 0, {
3860
+ onTelemetry: logRemoteDownloadTelemetry
3861
+ });
3862
+ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, run, assetRoot) {
3893
3863
  let filePath = src;
3894
3864
  if (isHttpUrl(src)) {
3895
3865
  const remoteDir = join9(downloadDir, REMOTE_MEDIA_SUBDIR);
3896
3866
  if (!existsSync7(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
3867
+ run?.assets.reserve([src]);
3897
3868
  try {
3898
- filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
3899
- onTelemetry: logRemoteDownloadTelemetry
3900
- });
3901
- } catch {
3869
+ filePath = await downloadAsset(src, remoteDir, run?.assets);
3870
+ } catch (err) {
3871
+ if (run?.assets.signal?.aborted) throw err;
3902
3872
  return { duration: null, resolvedPath: src };
3903
3873
  }
3904
3874
  } else {
@@ -3926,13 +3896,17 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
3926
3896
  const probe = () => withMediaProbeSlot(async () => {
3927
3897
  try {
3928
3898
  await assertMediaPayload(filePath, elementIdentity);
3929
- const profile = await probeMediaProfile2(filePath);
3899
+ const signal = run?.assets.signal;
3900
+ const profile = await probeMediaProfile2(filePath, { signal });
3930
3901
  if (tagName === "video") {
3931
- return { profile, fileDuration: (await extractMediaMetadata(filePath)).durationSeconds };
3902
+ const { durationSeconds } = await extractMediaMetadata(filePath, { signal });
3903
+ return { profile, fileDuration: durationSeconds };
3932
3904
  }
3933
3905
  try {
3934
- return { profile, fileDuration: (await extractAudioMetadata(filePath)).durationSeconds };
3906
+ const { durationSeconds } = await extractAudioMetadata(filePath, { signal });
3907
+ return { profile, fileDuration: durationSeconds };
3935
3908
  } catch {
3909
+ if (signal?.aborted) throw signal.reason;
3936
3910
  return { profile, fileDuration: null };
3937
3911
  }
3938
3912
  } catch (error) {
@@ -3940,10 +3914,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
3940
3914
  }
3941
3915
  });
3942
3916
  const key = `${tagName}\0${filePath}`;
3943
- let probed = probes?.get(key);
3917
+ let probed = run?.probes.get(key);
3944
3918
  if (!probed) {
3945
3919
  probed = probe();
3946
- probes?.set(key, probed);
3920
+ run?.probes.set(key, probed);
3947
3921
  }
3948
3922
  const outcome = await probed;
3949
3923
  if ("error" in outcome) {
@@ -3982,12 +3956,13 @@ function markInferredVariableMediaDurations(html, unresolvedMedia) {
3982
3956
  }
3983
3957
  return changed ? document2.toString() : html;
3984
3958
  }
3985
- async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, probes, assetRoot) {
3959
+ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, run, assetRoot) {
3986
3960
  const { html: staticCompiled, unresolved } = compileTimingAttrs(html);
3987
3961
  const mediaUnresolved = unresolved.filter(
3988
3962
  (el) => (el.tagName === "video" || el.tagName === "audio") && el.src
3989
3963
  );
3990
3964
  const unresolvedCompositions = unresolved.filter((el) => el.tagName === "div");
3965
+ run?.assets.reserve(mediaUnresolved.map((el) => el.src).filter(isHttpUrl));
3991
3966
  const resolvedResults = await Promise.all(
3992
3967
  mediaUnresolved.map(
3993
3968
  (el) => resolveMediaDuration(
@@ -4001,7 +3976,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
4001
3976
  el.id,
4002
3977
  log,
4003
3978
  urlByAbsentLocalPath,
4004
- probes,
3979
+ run,
4005
3980
  assetRoot
4006
3981
  ).then(({ duration }) => ({ id: el.id, duration }))
4007
3982
  )
@@ -4013,8 +3988,10 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
4013
3988
  let compiledHtml = resolutions.length > 0 ? injectDurations(markedStaticHtml, resolutions) : markedStaticHtml;
4014
3989
  const preResolved = extractResolvedMedia(compiledHtml);
4015
3990
  const hiddenVideoIds = collectHiddenVideoIds(compiledHtml);
3991
+ const clampable = preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id));
3992
+ run?.assets.reserve(clampable.map((el) => el.src).filter(isHttpUrl));
4016
3993
  const clampResults = await Promise.all(
4017
- preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id)).map(async (el) => {
3994
+ clampable.map(async (el) => {
4018
3995
  const { duration: maxDuration } = await resolveMediaDuration(
4019
3996
  el.src,
4020
3997
  el.mediaStart,
@@ -4026,7 +4003,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
4026
4003
  el.id,
4027
4004
  log,
4028
4005
  void 0,
4029
- probes,
4006
+ run,
4030
4007
  assetRoot
4031
4008
  );
4032
4009
  return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src };
@@ -4049,7 +4026,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
4049
4026
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
4050
4027
  return { html: compiledHtml, unresolvedCompositions };
4051
4028
  }
4052
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
4029
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, run, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
4053
4030
  const subCompositions = /* @__PURE__ */ new Map();
4054
4031
  const { document: document2 } = parseHTML5(html);
4055
4032
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -4084,7 +4061,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
4084
4061
  downloadDir,
4085
4062
  void 0,
4086
4063
  urlByAbsentLocalPath,
4087
- probes,
4064
+ run,
4088
4065
  assetRoot
4089
4066
  );
4090
4067
  const nested = await parseSubCompositions(
@@ -4093,7 +4070,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
4093
4070
  downloadDir,
4094
4071
  item.nestedVisited,
4095
4072
  urlByAbsentLocalPath,
4096
- probes,
4073
+ run,
4097
4074
  assetRoot,
4098
4075
  outsideFiles,
4099
4076
  compiledSrcs
@@ -4151,13 +4128,28 @@ function promoteCssImportsToLinkTags(html) {
4151
4128
  return document2.toString();
4152
4129
  }
4153
4130
  var ProducerHostIdentityMap = class extends Map {
4154
- #document;
4155
4131
  #lateInstanceByCompositionId = /* @__PURE__ */ new Map();
4132
+ /** How many elements carry each composition id: the page once, then each mount's copy once. */
4133
+ #idCounts = /* @__PURE__ */ new Map();
4134
+ /** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */
4135
+ #uncounted;
4156
4136
  constructor(document2, initialHosts) {
4157
4137
  super(assignBundledRuntimeCompositionIds(initialHosts));
4158
- this.#document = document2;
4138
+ this.#uncounted = [document2];
4139
+ }
4140
+ #countUncopied() {
4141
+ for (const root of this.#uncounted.splice(0)) {
4142
+ for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) {
4143
+ this.#adjust(element.getAttribute("data-composition-id"), 1);
4144
+ }
4145
+ }
4146
+ }
4147
+ #adjust(id, by) {
4148
+ if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by);
4159
4149
  }
4160
4150
  get(host) {
4151
+ this.#countUncopied();
4152
+ this.#uncounted.push(host);
4161
4153
  const existing = super.get(host);
4162
4154
  if (existing) return existing;
4163
4155
  const authoredCompositionId = (host.getAttribute("data-hf-original-composition-id") || host.getAttribute("data-composition-id") || "").trim() || null;
@@ -4166,17 +4158,19 @@ var ProducerHostIdentityMap = class extends Map {
4166
4158
  this.set(host, identity2);
4167
4159
  return identity2;
4168
4160
  }
4161
+ const ownId = host.getAttribute("data-composition-id");
4162
+ const heldByOthers = (id) => (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0;
4169
4163
  let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
4170
4164
  let runtimeCompositionId;
4171
4165
  do {
4172
4166
  instanceIndex += 1;
4173
4167
  runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
4174
- } while (Array.from(this.#document.querySelectorAll("[data-composition-id]")).some(
4175
- (element) => element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId
4176
- ));
4168
+ } while (heldByOthers(runtimeCompositionId));
4177
4169
  this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
4178
4170
  host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
4179
4171
  host.setAttribute("data-composition-id", runtimeCompositionId);
4172
+ this.#adjust(ownId, -1);
4173
+ this.#adjust(runtimeCompositionId, 1);
4180
4174
  const identity = { authoredCompositionId, runtimeCompositionId };
4181
4175
  this.set(host, identity);
4182
4176
  return identity;
@@ -4234,6 +4228,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
4234
4228
  }
4235
4229
  function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
4236
4230
  const { document: document2 } = parseHTML5(html);
4231
+ budget.chargeElements(ENTRY_PAGE, document2.querySelectorAll("*").length);
4237
4232
  const head = document2.querySelector("head");
4238
4233
  const body = document2.querySelector("body");
4239
4234
  const hosts = Array.from(document2.querySelectorAll("[data-composition-src]"));
@@ -4291,6 +4286,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4291
4286
  return compHtml;
4292
4287
  },
4293
4288
  chargeEmitted: (srcPath, bytes) => budget.chargeGenerated(srcPath, bytes),
4289
+ chargeElements: (srcPath, count) => budget.chargeElements(srcPath, count),
4294
4290
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
4295
4291
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
4296
4292
  // against its own directory, project-root refs stay as authored.
@@ -4619,18 +4615,18 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
4619
4615
  };
4620
4616
  }
4621
4617
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
4622
- async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
4618
+ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, assets, extraRewrite) {
4619
+ assets?.reserve(urlSet);
4623
4620
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
4624
4621
  if (!existsSync7(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
4625
4622
  const urlToLocal = /* @__PURE__ */ new Map();
4626
4623
  await Promise.all(
4627
4624
  [...urlSet].map(async (url) => {
4628
4625
  try {
4629
- const localPath = await downloadToTemp(url, remoteDir, void 0, void 0, void 0, {
4630
- onTelemetry: logRemoteDownloadTelemetry
4631
- });
4626
+ const localPath = await downloadAsset(url, remoteDir, assets);
4632
4627
  urlToLocal.set(url, localPath);
4633
4628
  } catch (err) {
4629
+ if (assets?.signal?.aborted) throw err;
4634
4630
  const identity = safeDownloadUrlIdentity(url);
4635
4631
  defaultLogger.warn(`[Compiler] ${warnLabel}, using original URL as fallback.`, {
4636
4632
  urlFingerprint: identity.urlFingerprint,
@@ -4656,14 +4652,15 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
4656
4652
  defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
4657
4653
  return { html: result, remoteMediaAssets };
4658
4654
  }
4659
- async function localizeRemoteMediaSources(html, downloadDir) {
4655
+ async function localizeRemoteMediaSources(html, downloadDir, assets) {
4660
4656
  const urlSet = /* @__PURE__ */ new Set([...remoteSrcUrls(html, "media"), ...remoteSrcUrls(html, "source")]);
4661
4657
  const localized = await downloadAndRewriteUrls(
4662
4658
  urlSet,
4663
4659
  html,
4664
4660
  join9(downloadDir, REMOTE_MEDIA_SUBDIR),
4665
4661
  "Remote media download failed",
4666
- "Localized remote media source(s)"
4662
+ "Localized remote media source(s)",
4663
+ assets
4667
4664
  );
4668
4665
  return { ...localized, html: dropBindingOnLocalizedMedia(localized.html) };
4669
4666
  }
@@ -4679,17 +4676,18 @@ function dropBindingOnLocalizedMedia(html) {
4679
4676
  }
4680
4677
  return changed ? document2.toString() : html;
4681
4678
  }
4682
- async function localizeRemoteImageSources(html, downloadDir) {
4679
+ async function localizeRemoteImageSources(html, downloadDir, assets) {
4683
4680
  const urlSet = new Set(remoteSrcUrls(html, "img"));
4684
4681
  return downloadAndRewriteUrls(
4685
4682
  urlSet,
4686
4683
  html,
4687
4684
  join9(downloadDir, REMOTE_MEDIA_SUBDIR),
4688
4685
  "Remote image download failed",
4689
- "Localized remote image source(s)"
4686
+ "Localized remote image source(s)",
4687
+ assets
4690
4688
  );
4691
4689
  }
4692
- async function localizeRemoteBackgroundImages(html, downloadDir) {
4690
+ async function localizeRemoteBackgroundImages(html, downloadDir, assets) {
4693
4691
  const urlSet = /* @__PURE__ */ new Set();
4694
4692
  for (const { parts } of remoteBackgroundUrlMatches(html)) {
4695
4693
  if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
@@ -4700,6 +4698,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
4700
4698
  join9(downloadDir, REMOTE_MEDIA_SUBDIR),
4701
4699
  "Remote background-image download failed",
4702
4700
  "Localized remote background-image(s)",
4701
+ assets,
4703
4702
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
4704
4703
  // replaceAll; this handles the unquoted url(https://..) form.
4705
4704
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
@@ -4853,13 +4852,14 @@ function collectFontFaceUrls(html) {
4853
4852
  }
4854
4853
  return urlSet;
4855
4854
  }
4856
- function localizeFontFaceUrls(html, downloadDir) {
4855
+ function localizeFontFaceUrls(html, downloadDir, assets) {
4857
4856
  return downloadAndRewriteUrls(
4858
4857
  collectFontFaceUrls(html),
4859
4858
  html,
4860
4859
  join9(downloadDir, REMOTE_MEDIA_SUBDIR),
4861
4860
  "Remote font download failed",
4862
4861
  "Localized remote font face(s)",
4862
+ assets,
4863
4863
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
4864
4864
  );
4865
4865
  }
@@ -4877,16 +4877,24 @@ async function readLocalFont(absPath) {
4877
4877
  }
4878
4878
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
4879
4879
  }
4880
- async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
4881
- const absPath = localPath.startsWith("/") ? localPath : resolve6(projectDir, localPath);
4882
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
4883
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
4884
- return void 0;
4880
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log, downloadedPath, reserve) {
4881
+ const absPath = downloadedPath ?? (localPath.startsWith("/") ? localPath : resolve6(projectDir, localPath));
4882
+ if (downloadedPath === void 0) {
4883
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) {
4884
+ return void 0;
4885
+ }
4886
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
4887
+ return void 0;
4888
+ }
4889
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
4885
4890
  }
4886
- if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
4887
4891
  if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
4888
4892
  const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
4889
4893
  try {
4894
+ if (!reserve(Math.ceil(statSync5(absPath).size / 3) * 4 + 64)) {
4895
+ dataUriByAbsolutePath.set(absPath, void 0);
4896
+ return void 0;
4897
+ }
4890
4898
  const font = await readLocalFont(absPath);
4891
4899
  if (font.kind === "file-backed") {
4892
4900
  dataUriByAbsolutePath.set(absPath, void 0);
@@ -4910,9 +4918,26 @@ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsol
4910
4918
  }
4911
4919
  }
4912
4920
  var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
4913
- async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
4921
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger, downloadedFonts = /* @__PURE__ */ new Map()) {
4914
4922
  const dataUriByPath = /* @__PURE__ */ new Map();
4915
4923
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
4924
+ let warned = false;
4925
+ const keptFileBacked = (localPath) => {
4926
+ if (warned) return;
4927
+ warned = true;
4928
+ log.warn(
4929
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
4930
+ );
4931
+ };
4932
+ let reserved = 0;
4933
+ const reserveFor = (localPath) => (bytes) => {
4934
+ if (reserved + bytes > budget.generatedRoom) {
4935
+ keptFileBacked(localPath);
4936
+ return false;
4937
+ }
4938
+ reserved += bytes;
4939
+ return true;
4940
+ };
4916
4941
  for (const { parts: style } of styleBlockMatches(html)) {
4917
4942
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
4918
4943
  for (const { parts } of localFontFaceUrlMatches(face[1])) {
@@ -4920,24 +4945,26 @@ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = de
4920
4945
  if (!localPath || dataUriByPath.has(localPath)) continue;
4921
4946
  dataUriByPath.set(
4922
4947
  localPath,
4923
- await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
4948
+ await localFontDataUri(
4949
+ localPath,
4950
+ projectDir,
4951
+ assetRoot,
4952
+ dataUriByAbsolutePath,
4953
+ log,
4954
+ downloadedFonts.get(localPath),
4955
+ reserveFor(localPath)
4956
+ )
4924
4957
  );
4925
4958
  }
4926
4959
  }
4927
4960
  }
4928
4961
  if (![...dataUriByPath.values()].some(Boolean)) return html;
4929
- let warned = false;
4930
4962
  const embed = (source, localPath) => {
4931
4963
  const dataUri = dataUriByPath.get(localPath);
4932
4964
  if (!dataUri) return source;
4933
4965
  const inlined = `url("${dataUri}")`;
4934
4966
  if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
4935
- if (!warned) {
4936
- warned = true;
4937
- log.warn(
4938
- `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
4939
- );
4940
- }
4967
+ keptFileBacked(localPath);
4941
4968
  return source;
4942
4969
  };
4943
4970
  return replaceMatches(
@@ -5043,6 +5070,14 @@ function bindVariableMediaSources(html, variables, budget, log) {
5043
5070
  }
5044
5071
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename3(htmlPath);
5045
5072
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
5073
+ const assets = new AssetDownloads(options.abortSignal);
5074
+ try {
5075
+ return await compileWithAssets(projectDir, htmlPath, downloadDir, options, assets);
5076
+ } finally {
5077
+ assets.end();
5078
+ }
5079
+ }
5080
+ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, assets) {
5046
5081
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
5047
5082
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
5048
5083
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
@@ -5069,7 +5104,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5069
5104
  options.log
5070
5105
  );
5071
5106
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
5072
- const probes = /* @__PURE__ */ new Map();
5107
+ const run = { probes: /* @__PURE__ */ new Map(), assets };
5073
5108
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
5074
5109
  rawHtml,
5075
5110
  projectDir,
@@ -5077,7 +5112,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5077
5112
  downloadDir,
5078
5113
  options.log,
5079
5114
  options.urlByAbsentLocalPath,
5080
- probes,
5115
+ run,
5081
5116
  assetRoot
5082
5117
  );
5083
5118
  const { subCompositions } = await parseSubCompositions(
@@ -5086,7 +5121,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5086
5121
  downloadDir,
5087
5122
  void 0,
5088
5123
  options.urlByAbsentLocalPath,
5089
- probes,
5124
+ run,
5090
5125
  assetRoot,
5091
5126
  outsideFiles
5092
5127
  );
@@ -5139,11 +5174,12 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5139
5174
  );
5140
5175
  const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
5141
5176
  htmlWithDeferredScripts,
5142
- downloadDir
5177
+ downloadDir,
5178
+ run.assets
5143
5179
  );
5144
- const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir);
5145
- const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir);
5146
- const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir);
5180
+ const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir, run.assets);
5181
+ const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir, run.assets);
5182
+ const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir, run.assets);
5147
5183
  const {
5148
5184
  html: htmlWithJpegs,
5149
5185
  preparedAssets: preparedHeifAssets,
@@ -5180,7 +5216,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5180
5216
  projectDir,
5181
5217
  assetRoot,
5182
5218
  budget,
5183
- options.log
5219
+ options.log,
5220
+ remoteFontAssets
5184
5221
  );
5185
5222
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
5186
5223
  embeddedHtml,
@@ -5653,7 +5690,7 @@ function resolveEntryHtmlPath(input) {
5653
5690
  `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
5654
5691
  );
5655
5692
  }
5656
- assertCompositionFileSize(path, relative3(projectDir, path));
5693
+ assertCompositionFileSize2(path, relative3(projectDir, path));
5657
5694
  return readTextFile2(path);
5658
5695
  };
5659
5696
  const htmlPath = join10(projectDir, entryFile);
@@ -6955,13 +6992,19 @@ async function runExtractVideosStage(input) {
6955
6992
  const videoPath = resolveProjectRelativeSrc4(v.src, projectDir, compiledDir);
6956
6993
  if (!opensLocally(videoPath, assetRoots)) return null;
6957
6994
  try {
6958
- const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata4(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata4(videoPath), {
6959
- signal: abortSignal,
6960
- maxTransientRetries: extractionPolicy.maxTransientRetries,
6961
- onRetry: () => {
6962
- hdrProbeTransientRetries += 1;
6995
+ const attempted = extractionPolicy.maxTransientRetries === 0 ? {
6996
+ result: await extractMediaMetadata4(videoPath, { signal: abortSignal }),
6997
+ retries: 0
6998
+ } : await runVideoExtractionWithRetry2(
6999
+ () => extractMediaMetadata4(videoPath, { signal: abortSignal }),
7000
+ {
7001
+ signal: abortSignal,
7002
+ maxTransientRetries: extractionPolicy.maxTransientRetries,
7003
+ onRetry: () => {
7004
+ hdrProbeTransientRetries += 1;
7005
+ }
6963
7006
  }
6964
- });
7007
+ );
6965
7008
  const meta = attempted.result;
6966
7009
  if (isHdrColorSpace2(meta.colorSpace)) {
6967
7010
  nativeHdrVideoIds.add(v.id);
@@ -7156,7 +7199,7 @@ async function appendVideoAudioFromProbe(input) {
7156
7199
  videos.map(async (video) => {
7157
7200
  const readFrom = isHttpUrl3(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
7158
7201
  if (readFrom === null) return null;
7159
- const metadata = await extractMediaMetadata4(readFrom);
7202
+ const metadata = await extractMediaMetadata4(readFrom, { signal: input.signal });
7160
7203
  const window2 = await resolveFinalFrameExtractionWindow2(
7161
7204
  readFrom,
7162
7205
  video,