@hyperframes/producer 0.9.58 → 0.9.61

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.
Files changed (31) hide show
  1. package/dist/distributed.js +408 -153
  2. package/dist/hyperframe.manifest.json +1 -1
  3. package/dist/hyperframe.runtime.iife.js +64 -64
  4. package/dist/hyperframeLintWorker.js +9 -0
  5. package/dist/index.js +576 -185
  6. package/dist/public-server.js +531 -166
  7. package/dist/renderRequest.d.ts +3 -0
  8. package/dist/server.d.ts +2 -0
  9. package/dist/services/animatedGifPrep.d.ts +2 -2
  10. package/dist/services/compositionSizeLimit.d.ts +22 -0
  11. package/dist/services/distributed/plan.d.ts +6 -1
  12. package/dist/services/distributed/planV2.d.ts +1 -0
  13. package/dist/services/distributed/projectHash.d.ts +9 -4
  14. package/dist/services/distributed/renderConfigValidation.d.ts +0 -18
  15. package/dist/services/distributed/renderSpan.d.ts +1 -0
  16. package/dist/services/distributed/shared.d.ts +2 -0
  17. package/dist/services/fileServer.d.ts +1 -0
  18. package/dist/services/heifImagePrep.d.ts +1 -1
  19. package/dist/services/htmlCompiler.d.ts +5 -2
  20. package/dist/services/htmlTagScans.d.ts +1 -0
  21. package/dist/services/hyperframeLint.d.ts +8 -2
  22. package/dist/services/hyperframeLintWorker.d.ts +1 -0
  23. package/dist/services/render/outputDimensions.d.ts +6 -0
  24. package/dist/services/render/shared.d.ts +7 -0
  25. package/dist/services/render/stages/audioStage.d.ts +1 -0
  26. package/dist/services/render/stages/encodeStage.d.ts +26 -1
  27. package/dist/services/render/stages/probeStage.d.ts +11 -2
  28. package/dist/services/renderOrchestrator.d.ts +5 -0
  29. package/dist/utils/paths.d.ts +6 -2
  30. package/dist/verifyStaticPage.d.ts +1 -1
  31. package/package.json +7 -7
@@ -87,6 +87,7 @@ import { isSafePath } from "@hyperframes/core/safe-path";
87
87
  import {
88
88
  isCopiedOutsideFileType,
89
89
  isPrivateOutsideFile,
90
+ isUploadedOutsideFileType,
90
91
  leftOutWarning,
91
92
  linksOutside
92
93
  } from "@hyperframes/studio-server/outside-file";
@@ -108,15 +109,17 @@ function isPathInside(childPath, parentPath, options = {}) {
108
109
  function escapesAssetRoot(path, assetRoot) {
109
110
  return assetRoot !== void 0 && !isSafePath(assetRoot, path);
110
111
  }
111
- function outsideAssetRefusal(projectDir, path) {
112
+ function outsideAssetRefusal(projectDir, path, policy = {}) {
112
113
  if (!linksOutside(projectDir, path)) return null;
113
114
  if (isPrivateOutsideFile(projectDir, path)) return "blocklisted";
114
115
  const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
115
- return folder || isCopiedOutsideFileType(path) ? null : "file_type";
116
+ if (folder || isUploadedOutsideFileType(path)) return null;
117
+ if (!isCopiedOutsideFileType(path)) return "file_type";
118
+ return policy.includeScripts ? null : "script";
116
119
  }
117
120
  var leftOutOfRender = (file, reference, reason) => leftOutWarning(file, reference, reason, "render");
118
- function refusesOutsideLink(projectDir, path, warn) {
119
- const refusal = outsideAssetRefusal(projectDir, path);
121
+ function refusesOutsideLink(projectDir, path, warn, policy = {}) {
122
+ const refusal = outsideAssetRefusal(projectDir, path, policy);
120
123
  if (!refusal) return false;
121
124
  const file = nodeRelative(projectDir, path).split(sep).join("/");
122
125
  warn(leftOutOfRender(file, realFilePath(path), refusal));
@@ -146,7 +149,7 @@ import {
146
149
  mkdirSync as mkdirSync6,
147
150
  readdirSync as readdirSync3,
148
151
  rmSync as rmSync5,
149
- statSync as statSync6,
152
+ statSync as statSync7,
150
153
  writeFileSync as writeFileSync5,
151
154
  copyFileSync as copyFileSync5,
152
155
  appendFileSync
@@ -298,6 +301,10 @@ function stripPreloadNone(html) {
298
301
  return attr && attr.index < tagEnd ? [attr.index, attr.index + attr[0].length] : void 0;
299
302
  });
300
303
  }
304
+ function hasClosedMediaTag(text) {
305
+ const open2 = /<(?:video|audio)\b/i.exec(text);
306
+ return open2 !== null && text.includes(">", open2.index + open2[0].length);
307
+ }
301
308
  var REMOTE_SRC_TAGS = {
302
309
  media: { opener: "<(?:video|audio)\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
303
310
  source: { opener: "<source\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
@@ -1032,7 +1039,8 @@ function createFileServer(options) {
1032
1039
  compiledDir,
1033
1040
  port = 0,
1034
1041
  stripEmbeddedRuntime = true,
1035
- allowOutsideProjectAssets = false
1042
+ allowOutsideProjectAssets = false,
1043
+ includeOutsideScripts = false
1036
1044
  } = options;
1037
1045
  const preHeadScripts = [
1038
1046
  HF_EARLY_STUB,
@@ -1043,6 +1051,7 @@ function createFileServer(options) {
1043
1051
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
1044
1052
  const app = new Hono();
1045
1053
  const warnLeftOut = (line) => console.warn(`[FileServer] ${terminalText2(line)}`);
1054
+ const outsidePolicy = { includeScripts: includeOutsideScripts };
1046
1055
  let listeningPort = -1;
1047
1056
  app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
1048
1057
  await next();
@@ -1060,7 +1069,7 @@ function createFileServer(options) {
1060
1069
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
1061
1070
  if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
1062
1071
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
1063
- if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut)) continue;
1072
+ if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut, outsidePolicy)) continue;
1064
1073
  file = openRegularFile(candidate);
1065
1074
  if (file) break;
1066
1075
  }
@@ -2407,6 +2416,22 @@ import {
2407
2416
  resolvePlayableVideoDuration
2408
2417
  } from "@hyperframes/engine";
2409
2418
 
2419
+ // src/services/render/outputDimensions.ts
2420
+ function isExpectedOutputDimensions(value) {
2421
+ return typeof value === "object" && value !== null && "width" in value && "height" in value && typeof value.width === "number" && typeof value.height === "number" && Number.isSafeInteger(value.width) && Number.isSafeInteger(value.height) && value.width > 0 && value.height > 0;
2422
+ }
2423
+ var OutputDimensionsMismatchError = class extends Error {
2424
+ code = "OUTPUT_DIMENSIONS_MISMATCH";
2425
+ constructor() {
2426
+ super("Compiled output dimensions do not match the requested render dimensions.");
2427
+ }
2428
+ };
2429
+ function requireOutputDimensions(expected, width, height) {
2430
+ if (expected !== void 0 && (!isExpectedOutputDimensions(expected) || expected.width !== width || expected.height !== height)) {
2431
+ throw new OutputDimensionsMismatchError();
2432
+ }
2433
+ }
2434
+
2410
2435
  // src/services/render/stages/compileStage.ts
2411
2436
  import { existsSync as existsSync8, writeFileSync as writeFileSync3 } from "node:fs";
2412
2437
  import { join as join10, relative as relative3 } from "node:path";
@@ -2415,6 +2440,61 @@ import { suggestMatchingPreset } from "@hyperframes/core";
2415
2440
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
2416
2441
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
2417
2442
 
2443
+ // src/services/compositionSizeLimit.ts
2444
+ import { statSync as statSync3 } from "node:fs";
2445
+ var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
2446
+ var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
2447
+ var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2448
+ var MAX_EXPANDED_COMPOSITION_BYTES = 2 * MAX_COMPOSITION_HTML_BYTES;
2449
+ var MAX_COMPOSITION_MOUNTS = 1e4;
2450
+ var CompositionTooLargeError = class extends Error {
2451
+ constructor(message, publicMetadata) {
2452
+ super(message);
2453
+ this.publicMetadata = publicMetadata;
2454
+ this.name = "CompositionTooLargeError";
2455
+ }
2456
+ publicMetadata;
2457
+ code = COMPOSITION_TOO_LARGE;
2458
+ // The producer server reads these off the error for the wire envelope.
2459
+ owner = "user";
2460
+ retryable = false;
2461
+ };
2462
+ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
2463
+ `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.`,
2464
+ { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
2465
+ );
2466
+ var CompositionExpansionBudget = class {
2467
+ bytes = 0;
2468
+ mounts = 0;
2469
+ charge(file, bytes) {
2470
+ this.bytes += bytes;
2471
+ this.mounts += 1;
2472
+ if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
2473
+ return;
2474
+ }
2475
+ throw new CompositionTooLargeError(
2476
+ `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.`,
2477
+ {
2478
+ bytes: this.bytes,
2479
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
2480
+ mounts: this.mounts,
2481
+ exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
2482
+ }
2483
+ );
2484
+ }
2485
+ };
2486
+ function assertCompositionFileSize(path, file) {
2487
+ let bytes;
2488
+ try {
2489
+ const stats = statSync3(path);
2490
+ if (!stats.isFile()) return;
2491
+ bytes = stats.size;
2492
+ } catch {
2493
+ return;
2494
+ }
2495
+ if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
2496
+ }
2497
+
2418
2498
  // src/services/htmlCompiler.ts
2419
2499
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
2420
2500
  import {
@@ -2501,11 +2581,13 @@ import {
2501
2581
  import {
2502
2582
  isUnresolvedAssetPlaceholder,
2503
2583
  namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
2584
+ projectAssetExists,
2504
2585
  readProjectFile,
2505
2586
  readTextFile,
2506
2587
  resolveCompositionSrc
2507
2588
  } from "@hyperframes/parsers/asset-resolution";
2508
2589
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
2590
+ import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
2509
2591
 
2510
2592
  // src/services/renderMediaCollector.ts
2511
2593
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -2699,7 +2781,7 @@ import {
2699
2781
 
2700
2782
  // src/services/animatedGifPrep.ts
2701
2783
  import { createHash as createHash3 } from "node:crypto";
2702
- import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync3 } from "node:fs";
2784
+ import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync4 } from "node:fs";
2703
2785
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolve4 } from "node:path";
2704
2786
  import { parseHTML as parseHTML3 } from "linkedom";
2705
2787
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -2752,12 +2834,13 @@ function resolveLocalImageSourcePath(src, options) {
2752
2834
  isAbsolute2(basePath) ? basePath : resolve4(options.projectDir, projectRelative),
2753
2835
  resolve4(options.downloadDir, normalizedBase)
2754
2836
  ];
2755
- const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, options.assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
2837
+ const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
2838
+ const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
2756
2839
  return candidates.find((candidate) => allowed(candidate) && existsSync5(candidate)) ?? null;
2757
2840
  }
2758
2841
  function isUsableFile(path) {
2759
2842
  try {
2760
- const stat = statSync3(path);
2843
+ const stat = statSync4(path);
2761
2844
  return stat.isFile() && stat.size > 0;
2762
2845
  } catch {
2763
2846
  return false;
@@ -3022,7 +3105,7 @@ import {
3022
3105
  readFileSync as readFileSync4,
3023
3106
  readSync,
3024
3107
  rmSync as rmSync3,
3025
- statSync as statSync4,
3108
+ statSync as statSync5,
3026
3109
  writeFileSync as writeFileSync2
3027
3110
  } from "node:fs";
3028
3111
  import { dirname as dirname5, join as join7, resolve as resolve5 } from "node:path";
@@ -3266,7 +3349,7 @@ function resolveImageSource(src, options) {
3266
3349
  }
3267
3350
  function isUsableFile2(path) {
3268
3351
  try {
3269
- return statSync4(path).size > 0;
3352
+ return statSync5(path).size > 0;
3270
3353
  } catch {
3271
3354
  return false;
3272
3355
  }
@@ -3545,7 +3628,7 @@ Check that each file referenced by data-composition-src contains valid HTML with
3545
3628
  };
3546
3629
  function normalizeCompositionSrcs(html, projectDir) {
3547
3630
  return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
3548
- if (!value.includes("%") && !value.startsWith("/")) return whole;
3631
+ if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
3549
3632
  const file = resolveCompositionSrc(projectDir, value);
3550
3633
  if (file === null) return whole;
3551
3634
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
@@ -3561,68 +3644,94 @@ function resolveCompositionFile(projectDir, src, assetRoot) {
3561
3644
  const file = resolveCompositionPath(projectDir, src, assetRoot);
3562
3645
  return file !== null && COMPOSITION_FILE.test(file) ? file : null;
3563
3646
  }
3647
+ var OUTSIDE_COMPOSITION_NEEDS_FLAG = "it is outside the project, and any scripts in it would run; move it into the project, or pass --include-outside-files to hyperframes render, to include it";
3648
+ var runsOutsideMarkupUnasked = (projectDir, filePath, assetRoot, outsideFiles) => assetRoot === void 0 && !outsideFiles.includeScripts && linksOutside2(projectDir, filePath);
3649
+ function assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles) {
3650
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
3651
+ throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
3652
+ }
3653
+ }
3564
3654
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
3565
- function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
3655
+ var mountSrcsUnder = (root) => [...root.querySelectorAll("[data-composition-src]")].map((el) => el.getAttribute("data-composition-src")).filter((srcPath) => !!srcPath && !isUnresolvedAssetPlaceholder(srcPath));
3656
+ function compositionSrcsIn(html) {
3566
3657
  const { document: document2 } = parseHTML5(html);
3567
- const hosts = [...document2.querySelectorAll("[data-composition-src]")];
3568
- const problems = [];
3569
- for (const el of hosts) {
3570
- const srcPath = el.getAttribute("data-composition-src");
3571
- if (!srcPath) continue;
3572
- if (isUnresolvedAssetPlaceholder(srcPath)) continue;
3658
+ const templated = [];
3659
+ const templates = [...document2.querySelectorAll("template")];
3660
+ for (let template = templates.pop(); template; template = templates.pop()) {
3661
+ templated.push(...mountSrcsUnder(template.content));
3662
+ templates.push(...template.content.querySelectorAll("template"));
3663
+ }
3664
+ return { mounts: mountSrcsUnder(document2), templated };
3665
+ }
3666
+ function compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles) {
3667
+ if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
3668
+ return "it is outside the project in a private location";
3669
+ }
3670
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
3671
+ return OUTSIDE_COMPOSITION_NEEDS_FLAG;
3672
+ }
3673
+ if (isPrivateCompositionFile(projectDir, filePath)) {
3674
+ return "it is git metadata, an env file or a private tool record";
3675
+ }
3676
+ return COMPOSITION_FILE.test(filePath) ? null : NOT_A_COMPOSITION_FILE;
3677
+ }
3678
+ function readSubCompositionFile(filePath, srcPath) {
3679
+ assertCompositionFileSize(filePath, srcPath);
3680
+ const read = readProjectFile(filePath);
3681
+ if (read.kind === "missing") return { detail: "the file does not exist" };
3682
+ if (read.kind === "folder") return { detail: "it is a folder, not an HTML file" };
3683
+ const validity = checkSubCompositionUsability(read.text, parseSubCompHtmlForValidity);
3684
+ if (!validity.ok)
3685
+ return { detail: validity.detail ?? "the file is empty or could not be parsed" };
3686
+ return { bytes: Buffer.byteLength(read.text), ...compositionSrcsIn(read.text) };
3687
+ }
3688
+ function assertSubCompositionsUsable(html, projectDir, assetRoot, outsideFiles) {
3689
+ const budget = new CompositionExpansionBudget();
3690
+ const files = /* @__PURE__ */ new Map();
3691
+ const problems = /* @__PURE__ */ new Map();
3692
+ const report = (srcPath, detail) => problems.set(`${srcPath}\0${detail}`, { srcPath, detail });
3693
+ const chain = /* @__PURE__ */ new Set();
3694
+ const paths = /* @__PURE__ */ new Map();
3695
+ const resolveMount = (srcPath) => {
3573
3696
  const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
3574
- if (filePath === null) {
3575
- problems.push({ srcPath, detail: "it is outside the project folder" });
3576
- continue;
3577
- }
3578
- if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
3579
- problems.push({ srcPath, detail: "it is outside the project in a private location" });
3580
- continue;
3581
- }
3582
- if (isPrivateCompositionFile(projectDir, filePath)) {
3583
- problems.push({
3584
- srcPath,
3585
- detail: "it is git metadata, an env file or a private tool record"
3586
- });
3587
- continue;
3588
- }
3589
- if (!COMPOSITION_FILE.test(filePath)) {
3590
- problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
3591
- continue;
3592
- }
3593
- if (visited.has(filePath)) continue;
3594
- const read = readProjectFile(filePath);
3595
- if (read.kind === "missing") {
3596
- problems.push({ srcPath, detail: "the file does not exist" });
3597
- continue;
3598
- }
3599
- if (read.kind === "folder") {
3600
- problems.push({ srcPath, detail: "it is a folder, not an HTML file" });
3601
- continue;
3602
- }
3603
- const fileHtml = read.text;
3604
- const validity = checkSubCompositionUsability(fileHtml, parseSubCompHtmlForValidity);
3605
- if (!validity.ok) {
3606
- problems.push({
3607
- srcPath,
3608
- detail: validity.detail ?? "the file is empty or could not be parsed"
3609
- });
3610
- continue;
3611
- }
3612
- const nestedVisited = new Set(visited);
3613
- nestedVisited.add(filePath);
3614
- try {
3615
- assertSubCompositionsUsable(fileHtml, projectDir, assetRoot, nestedVisited);
3616
- } catch (err) {
3617
- if (err instanceof EmptyCompositionError) {
3618
- problems.push(...err.problems);
3619
- } else {
3620
- throw err;
3697
+ if (filePath === null) return { detail: "it is outside the project folder" };
3698
+ const detail = compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles);
3699
+ return detail ? { detail } : { filePath };
3700
+ };
3701
+ const walk = (srcPaths, quiet) => {
3702
+ for (const srcPath of srcPaths) {
3703
+ let resolved = paths.get(srcPath);
3704
+ if (!resolved) {
3705
+ resolved = resolveMount(srcPath);
3706
+ paths.set(srcPath, resolved);
3707
+ }
3708
+ if ("detail" in resolved) {
3709
+ if (!quiet) report(srcPath, resolved.detail);
3710
+ continue;
3711
+ }
3712
+ const { filePath } = resolved;
3713
+ if (chain.has(filePath)) continue;
3714
+ let file = files.get(filePath);
3715
+ if (!file) {
3716
+ file = readSubCompositionFile(filePath, srcPath);
3717
+ files.set(filePath, file);
3621
3718
  }
3719
+ if ("detail" in file) {
3720
+ if (!quiet) report(srcPath, file.detail);
3721
+ continue;
3722
+ }
3723
+ budget.charge(srcPath, file.bytes);
3724
+ chain.add(filePath);
3725
+ walk(file.mounts, quiet);
3726
+ walk(file.templated, true);
3727
+ chain.delete(filePath);
3622
3728
  }
3623
- }
3624
- if (problems.length > 0) {
3625
- throw new EmptyCompositionError(problems);
3729
+ };
3730
+ const entry = compositionSrcsIn(html);
3731
+ walk(entry.mounts, false);
3732
+ walk(entry.templated, true);
3733
+ if (problems.size > 0) {
3734
+ throw new EmptyCompositionError([...problems.values()]);
3626
3735
  }
3627
3736
  }
3628
3737
  var COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
@@ -3877,7 +3986,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
3877
3986
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
3878
3987
  return { html: compiledHtml, unresolvedCompositions };
3879
3988
  }
3880
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot) {
3989
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
3881
3990
  const subCompositions = /* @__PURE__ */ new Map();
3882
3991
  const { document: document2 } = parseHTML5(html);
3883
3992
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -3890,6 +3999,10 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
3890
3999
  if (visited.has(filePath)) {
3891
4000
  continue;
3892
4001
  }
4002
+ if (compiledSrcs.has(srcPath)) continue;
4003
+ compiledSrcs.add(srcPath);
4004
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
4005
+ assertCompositionFileSize(filePath, srcPath);
3893
4006
  const read = readProjectFile(filePath);
3894
4007
  if (read.kind !== "file") {
3895
4008
  continue;
@@ -3918,7 +4031,9 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
3918
4031
  item.nestedVisited,
3919
4032
  urlByAbsentLocalPath,
3920
4033
  probes,
3921
- assetRoot
4034
+ assetRoot,
4035
+ outsideFiles,
4036
+ compiledSrcs
3922
4037
  );
3923
4038
  return {
3924
4039
  srcPath: item.srcPath,
@@ -4054,7 +4169,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
4054
4169
  }
4055
4170
  return document2.toString();
4056
4171
  }
4057
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot) {
4172
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
4058
4173
  const { document: document2 } = parseHTML5(html);
4059
4174
  const head = document2.querySelector("head");
4060
4175
  const body = document2.querySelector("body");
@@ -4065,8 +4180,29 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4065
4180
  {},
4066
4181
  variableOverrides
4067
4182
  );
4068
- return emitted ? document2.toString() : html;
4183
+ return { html: emitted ? document2.toString() : html, variablesByComp: {} };
4069
4184
  }
4185
+ const budget = new CompositionExpansionBudget();
4186
+ const readOnce = /* @__PURE__ */ new Map();
4187
+ const readMountHtml = (srcPath) => {
4188
+ const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
4189
+ if (filePath) {
4190
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
4191
+ assertCompositionFileSize(filePath, srcPath);
4192
+ }
4193
+ const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
4194
+ return read?.kind === "file" ? rewriteUnresolvableGsapToCdn(
4195
+ normalizeCompositionSrcs(read.text, projectDir),
4196
+ projectDir,
4197
+ srcPath
4198
+ ) : null;
4199
+ };
4200
+ const resolveMountHtml = (srcPath) => {
4201
+ const compiled = subCompositions.get(srcPath);
4202
+ if (compiled) return compiled;
4203
+ if (!readOnce.has(srcPath)) readOnce.set(srcPath, readMountHtml(srcPath));
4204
+ return readOnce.get(srcPath) ?? null;
4205
+ };
4070
4206
  const hostIdentityByElement = new ProducerHostIdentityMap(
4071
4207
  document2,
4072
4208
  hosts
@@ -4082,20 +4218,14 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4082
4218
  readVariableDefaults: readDeclaredDefaults,
4083
4219
  parseHostVariables: parseHostVariableValues,
4084
4220
  resolveHtml: (srcPath) => {
4085
- let compHtml = subCompositions.get(srcPath) || null;
4086
- if (!compHtml) {
4087
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
4088
- const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
4089
- if (read?.kind === "file") {
4090
- compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
4091
- }
4092
- }
4221
+ const compHtml = resolveMountHtml(srcPath);
4222
+ if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
4093
4223
  return compHtml;
4094
4224
  },
4095
4225
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
4096
4226
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
4097
4227
  // against its own directory, project-root refs stay as authored.
4098
- assetExists: (path) => existsSync7(resolve6(projectDir, path)),
4228
+ assetExists: projectAssetExists(projectDir),
4099
4229
  // Preserve the authored root wrapper as a child of the host, matching
4100
4230
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
4101
4231
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -4179,7 +4309,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4179
4309
  variableOverrides
4180
4310
  );
4181
4311
  assignMediaRenderIds(document2);
4182
- return document2.toString();
4312
+ return { html: document2.toString(), variablesByComp: result.variablesByComp };
4183
4313
  }
4184
4314
  function ensureFullDocument(html) {
4185
4315
  const trimmed = html.trim();
@@ -4300,7 +4430,7 @@ ${safeText}
4300
4430
  }
4301
4431
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
4302
4432
  }
4303
- function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html") {
4433
+ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
4304
4434
  const absProjectDir = resolve6(projectDir);
4305
4435
  const externalAssets = /* @__PURE__ */ new Map();
4306
4436
  const leftOut = /* @__PURE__ */ new Set();
@@ -4313,7 +4443,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
4313
4443
  }
4314
4444
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
4315
4445
  if (!onShare && !existsSync7(absPath)) return null;
4316
- const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath);
4446
+ const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
4317
4447
  if (refusal) {
4318
4448
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
4319
4449
  leftOut.add(trimmed);
@@ -4699,7 +4829,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
4699
4829
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
4700
4830
  if (!entryPath.includes("/")) return html;
4701
4831
  const { document: document2 } = parseHTML5(html);
4702
- const assetExists = (path) => existsSync7(resolve6(projectDir, path));
4832
+ const assetExists = projectAssetExists(projectDir);
4703
4833
  rewriteAssetPaths(
4704
4834
  document2.querySelectorAll("[src], [href], [srcset]"),
4705
4835
  entryPath,
@@ -4740,18 +4870,23 @@ function bindVariableMediaSources(html, variables) {
4740
4870
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename3(htmlPath);
4741
4871
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
4742
4872
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
4873
+ const outsideFiles = { includeScripts: options.includeOutsideScripts };
4743
4874
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
4744
4875
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
4745
4876
  }
4877
+ if (isPathInside(htmlPath, projectDir) && runsOutsideMarkupUnasked(projectDir, htmlPath, assetRoot, outsideFiles)) {
4878
+ throw new Error(`Entry file ${htmlPath} ${OUTSIDE_COMPOSITION_NEEDS_FLAG}`);
4879
+ }
4746
4880
  if (!COMPOSITION_FILE.test(htmlPath)) {
4747
4881
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
4748
4882
  }
4883
+ assertCompositionFileSize(htmlPath, basename3(htmlPath));
4749
4884
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
4750
4885
  const rawHtml = bindVariableMediaSources(
4751
4886
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
4752
4887
  options.variables ?? {}
4753
4888
  );
4754
- assertSubCompositionsUsable(rawHtml, projectDir, assetRoot);
4889
+ assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
4755
4890
  const probes = /* @__PURE__ */ new Map();
4756
4891
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
4757
4892
  rawHtml,
@@ -4770,15 +4905,17 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4770
4905
  void 0,
4771
4906
  options.urlByAbsentLocalPath,
4772
4907
  probes,
4773
- assetRoot
4908
+ assetRoot,
4909
+ outsideFiles
4774
4910
  );
4775
4911
  const fullHtml = ensureFullDocument(compiledHtml);
4776
- const inlinedHtml = inlineSubCompositions(
4912
+ const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
4777
4913
  fullHtml,
4778
4914
  subCompositions,
4779
4915
  projectDir,
4780
4916
  options.variables ?? {},
4781
- assetRoot
4917
+ assetRoot,
4918
+ outsideFiles
4782
4919
  );
4783
4920
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
4784
4921
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -4832,7 +4969,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4832
4969
  cacheDir: options.animatedGifCacheDir,
4833
4970
  sourceAssets: remoteImageAssets,
4834
4971
  timeoutMs: options.ffmpegProcessTimeout,
4835
- assetRoot
4972
+ allowOutsideFiles: assetRoot === void 0
4836
4973
  });
4837
4974
  if (preparedHeifImages.length > 0) {
4838
4975
  defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
@@ -4848,7 +4985,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4848
4985
  cacheDir: options.animatedGifCacheDir,
4849
4986
  sourceAssets: gifSourceAssets,
4850
4987
  timeoutMs: options.ffmpegProcessTimeout,
4851
- assetRoot
4988
+ allowOutsideFiles: assetRoot === void 0
4852
4989
  });
4853
4990
  if (preparedGifs.length > 0) {
4854
4991
  defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
@@ -4863,7 +5000,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4863
5000
  embeddedHtml,
4864
5001
  projectDir,
4865
5002
  options.log,
4866
- entryFileName(projectDir, htmlPath)
5003
+ entryFileName(projectDir, htmlPath),
5004
+ { includeScripts: options.includeOutsideScripts }
4867
5005
  ) : { html: embeddedHtml, externalAssets: /* @__PURE__ */ new Map() };
4868
5006
  for (const [relPath, absPath] of remoteMediaAssets) {
4869
5007
  externalAssets.set(relPath, absPath);
@@ -4926,6 +5064,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4926
5064
  gradedCanvas,
4927
5065
  ...masterFxChain ? { masterFxChain } : {},
4928
5066
  unresolvedCompositions,
5067
+ variablesByComp,
4929
5068
  externalAssets,
4930
5069
  width,
4931
5070
  height,
@@ -5269,7 +5408,7 @@ async function resolveCompositionDurations(page, unresolved) {
5269
5408
  }
5270
5409
  return resolutions;
5271
5410
  }
5272
- async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot) {
5411
+ async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot, outsideFiles = {}) {
5273
5412
  if (resolutions.length === 0) return compiled;
5274
5413
  const html = injectDurations(compiled.html, resolutions);
5275
5414
  const { subCompositions } = await parseSubCompositions(
@@ -5279,7 +5418,8 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
5279
5418
  void 0,
5280
5419
  void 0,
5281
5420
  void 0,
5282
- assetRoot
5421
+ assetRoot,
5422
+ outsideFiles
5283
5423
  );
5284
5424
  const { videos, audios, images } = compiled;
5285
5425
  const remaining = compiled.unresolvedCompositions.filter(
@@ -5327,6 +5467,7 @@ function resolveEntryHtmlPath(input) {
5327
5467
  `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
5328
5468
  );
5329
5469
  }
5470
+ assertCompositionFileSize(path, relative3(projectDir, path));
5330
5471
  return readTextFile2(path);
5331
5472
  };
5332
5473
  const htmlPath = join10(projectDir, entryFile);
@@ -5388,7 +5529,8 @@ async function runCompileStage(input) {
5388
5529
  pageMotionBlur: input.pageMotionBlur,
5389
5530
  animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
5390
5531
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
5391
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
5532
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
5533
+ includeOutsideScripts: job.config.includeOutsideScripts
5392
5534
  });
5393
5535
  assertNotAborted();
5394
5536
  const compileOnlyMs = Date.now() - compileStart;
@@ -5474,6 +5616,8 @@ async function runCompileStage(input) {
5474
5616
  });
5475
5617
  const outputWidth = Math.round(width * deviceScaleFactor);
5476
5618
  const outputHeight = Math.round(height * deviceScaleFactor);
5619
+ requireOutputDimensions(job.config.expectedOutputDimensions, outputWidth, outputHeight);
5620
+ if (job.config.expectedOutputDimensions !== void 0) job.outputDimensionsChecked = true;
5477
5621
  if (deviceScaleFactor !== 1) {
5478
5622
  log.info("Scaling composition via deviceScaleFactor", {
5479
5623
  compositionWidth: width,
@@ -5568,23 +5712,50 @@ function hasAutoStartVideos(html) {
5568
5712
  const { document: document2 } = parseHTML6(html);
5569
5713
  return document2.querySelector("video[data-hf-auto-start]") !== null;
5570
5714
  }
5571
- function variableHasValue(element, variableId, variables) {
5715
+ var MAX_VARIABLE_SCOPE_STEPS = 1e6;
5716
+ function variableIdsOn(scan, element) {
5717
+ let ids = scan.ids.get(element);
5718
+ if (!ids) {
5719
+ ids = /* @__PURE__ */ new Set([
5720
+ ...Object.keys(parseHostVariableValues2(element)),
5721
+ ...Object.keys(readDeclaredDefaults2(element))
5722
+ ]);
5723
+ scan.ids.set(element, ids);
5724
+ }
5725
+ return ids;
5726
+ }
5727
+ function scopedVariablesFor(scan, element, variablesByComp) {
5728
+ for (let node = element; node; node = node.parentElement) {
5729
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return null;
5730
+ if (!node.hasAttribute("data-composition-id")) continue;
5731
+ const compId = node.getAttribute("data-composition-id")?.trim() ?? "";
5732
+ return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : void 0;
5733
+ }
5734
+ return void 0;
5735
+ }
5736
+ function variableHasValue(scan, element, variableId, variables, variablesByComp) {
5572
5737
  if (variables && Object.hasOwn(variables, variableId)) return true;
5738
+ const scoped = scopedVariablesFor(scan, element, variablesByComp);
5739
+ if (scoped === null) return true;
5740
+ if (scoped) return Object.hasOwn(scoped, variableId);
5573
5741
  for (let scope = element.parentElement; scope; scope = scope.parentElement) {
5574
- if (Object.hasOwn(parseHostVariableValues2(scope), variableId)) return true;
5575
- if (Object.hasOwn(readDeclaredDefaults2(scope), variableId)) return true;
5742
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return true;
5743
+ if (variableIdsOn(scan, scope).has(variableId)) return true;
5576
5744
  }
5577
- return Object.hasOwn(readDeclaredDefaults2(element.ownerDocument.documentElement), variableId);
5745
+ return variableIdsOn(scan, element.ownerDocument.documentElement).has(variableId);
5578
5746
  }
5579
- function hasVariableBoundMedia(html, variables) {
5747
+ function hasVariableBoundMedia(html, variables, variablesByComp = {}) {
5580
5748
  const { document: document2 } = parseHTML6(html);
5749
+ const scan = { ids: /* @__PURE__ */ new Map(), steps: 0 };
5581
5750
  return Array.from(
5582
5751
  document2.querySelectorAll(
5583
5752
  "img[data-var-src], audio[data-var-src], video[data-var-src], source[data-var-src]"
5584
5753
  )
5585
5754
  ).some((element) => {
5586
5755
  const variableId = element.getAttribute("data-var-src")?.trim();
5587
- return Boolean(variableId && variableHasValue(element, variableId, variables));
5756
+ return Boolean(
5757
+ variableId && variableHasValue(scan, element, variableId, variables, variablesByComp)
5758
+ );
5588
5759
  });
5589
5760
  }
5590
5761
  function authoredMediaStarts(html) {
@@ -5624,29 +5795,54 @@ function reconcileBrowserMediaEnd(existingEnd, projectedEnd, sourceChanged, dura
5624
5795
  if (sourceChanged && durationInferred) return projectedEnd;
5625
5796
  return existingEnd <= 0 ? projectedEnd : Math.min(existingEnd, projectedEnd);
5626
5797
  }
5798
+ var MAX_MEDIA_SELECTOR_WORK = 1e6;
5799
+ var SIBLING_COMBINATOR = /[~+]/;
5800
+ function managedMediaElements(document2) {
5801
+ const managed = [];
5802
+ const pending = [];
5803
+ for (const element of Array.from(document2.children)) pending.push({ element, inMedia: false });
5804
+ for (let next = pending.pop(); next; next = pending.pop()) {
5805
+ const name = next.element.tagName.toLowerCase();
5806
+ const isMedia = name === "video" || name === "audio";
5807
+ if (isMedia || next.inMedia && name === "source") managed.push(next.element);
5808
+ for (const child3 of Array.from(next.element.children)) {
5809
+ pending.push({ element: child3, inMedia: next.inMedia || isMedia });
5810
+ }
5811
+ }
5812
+ return managed;
5813
+ }
5627
5814
  function hasRuntimeMediaChanges(html) {
5628
5815
  const { document: document2 } = parseHTML6(html);
5629
5816
  const scriptBodies = [...document2.querySelectorAll("script")].map(
5630
5817
  (script) => script.textContent ?? ""
5631
5818
  );
5632
5819
  const insertedMedia = scriptBodies.some(
5633
- (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || /<(?:video|audio)\b[^>]*>/i.test(script)
5820
+ (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || hasClosedMediaTag(script)
5634
5821
  );
5635
5822
  if (insertedMedia) return true;
5636
- const isManagedMedia = (element) => {
5637
- const name = element.tagName.toLowerCase();
5638
- if (name === "video" || name === "audio") return true;
5639
- return name === "source" && element.closest("video, audio") !== null;
5640
- };
5823
+ const managed = managedMediaElements(document2);
5824
+ if (managed.length === 0) return false;
5825
+ const managedIds = new Set(managed.map((element) => element.getAttribute("id")).filter(Boolean));
5826
+ const selectors = /* @__PURE__ */ new Set();
5827
+ let selectorChars = 0;
5641
5828
  for (const script of scriptBodies) {
5642
5829
  for (const mutation of extractMediaSrcMutations(script)) {
5643
- try {
5644
- const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
5645
- const idTarget = id ? document2.getElementById(id) : null;
5646
- const targets = id ? idTarget ? [idTarget] : [] : [...document2.querySelectorAll(mutation.selector)];
5647
- if (targets.some(isManagedMedia)) return true;
5648
- } catch {
5830
+ const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
5831
+ if (id) {
5832
+ if (managedIds.has(id)) return true;
5833
+ continue;
5649
5834
  }
5835
+ if (selectors.has(mutation.selector)) continue;
5836
+ if (SIBLING_COMBINATOR.test(mutation.selector)) return true;
5837
+ selectors.add(mutation.selector);
5838
+ selectorChars += mutation.selector.length;
5839
+ if (selectorChars * managed.length > MAX_MEDIA_SELECTOR_WORK) return true;
5840
+ }
5841
+ }
5842
+ for (const selector of selectors) {
5843
+ try {
5844
+ if (managed.some((element) => element.matches(selector))) return true;
5845
+ } catch {
5650
5846
  }
5651
5847
  }
5652
5848
  return false;
@@ -5699,7 +5895,11 @@ async function runProbeStage(input) {
5699
5895
  compiled.html,
5700
5896
  composition.audios.length
5701
5897
  );
5702
- const hasVariableMedia = hasVariableBoundMedia(compiled.html, job.config.variables);
5898
+ const hasVariableMedia = hasVariableBoundMedia(
5899
+ compiled.html,
5900
+ job.config.variables,
5901
+ compiled.variablesByComp
5902
+ );
5703
5903
  const hasInsertedMedia = hasRuntimeMediaChanges(compiled.html);
5704
5904
  const needsBrowser = cfg.videoLayerPassthrough || input.measuresShownBoxes === true || probeRequiresBrowser({
5705
5905
  durationSeconds: composition.duration,
@@ -5730,7 +5930,8 @@ async function runProbeStage(input) {
5730
5930
  port: 0,
5731
5931
  preHeadScripts: [VIRTUAL_TIME_SHIM],
5732
5932
  fps: job.config.fps,
5733
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
5933
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
5934
+ includeOutsideScripts: job.config.includeOutsideScripts
5734
5935
  });
5735
5936
  assertNotAborted();
5736
5937
  const motionBlur = job.config.motionBlur;
@@ -5886,7 +6087,8 @@ async function runProbeStage(input) {
5886
6087
  resolutions,
5887
6088
  projectDir,
5888
6089
  join11(workDir, "downloads"),
5889
- job.config.allowOutsideProjectAssets ? void 0 : projectDir
6090
+ job.config.allowOutsideProjectAssets ? void 0 : projectDir,
6091
+ { includeScripts: job.config.includeOutsideScripts }
5890
6092
  );
5891
6093
  assertNotAborted();
5892
6094
  composition.videos = compiled.videos;
@@ -6772,7 +6974,8 @@ import {
6772
6974
  audioFailureDiagnostics,
6773
6975
  processCompositionAudio,
6774
6976
  removeScratch as removeScratch2,
6775
- collectScratchLeftovers
6977
+ collectScratchLeftovers,
6978
+ withFfmpegProgress
6776
6979
  } from "@hyperframes/engine";
6777
6980
 
6778
6981
  // src/services/render/audioDeliveryLimit.ts
@@ -6798,7 +7001,8 @@ import {
6798
7001
  removeScratch,
6799
7002
  renameWithRetry as renameWithRetry5,
6800
7003
  runFfmpeg as runFfmpeg5,
6801
- trackChildProcess
7004
+ trackChildProcess,
7005
+ withPublicOnlyProxy
6802
7006
  } from "@hyperframes/engine";
6803
7007
  import { redactKnownPaths, redactTelemetryString as redactTelemetryString3 } from "@hyperframes/core";
6804
7008
 
@@ -7240,7 +7444,17 @@ async function runFfprobeJson(args, signal) {
7240
7444
  if (!args.includes("--")) {
7241
7445
  throw new Error('[audioPadTrim] ffprobe args must terminate options with "--".');
7242
7446
  }
7447
+ const proxying = withPublicOnlyProxy(args, [args.indexOf("--") + 1]);
7448
+ const routed = proxying && await proxying;
7449
+ try {
7450
+ return await spawnFfprobeJson(routed?.args ?? args, routed?.env, signal);
7451
+ } finally {
7452
+ await routed?.close();
7453
+ }
7454
+ }
7455
+ async function spawnFfprobeJson(args, env, signal) {
7243
7456
  const proc = spawn(getFfprobeBinary(), args, {
7457
+ ...env && { env },
7244
7458
  stdio: ["ignore", "pipe", "pipe"],
7245
7459
  windowsHide: true
7246
7460
  });
@@ -7356,7 +7570,8 @@ function assertAudioNotInterrupted(failures) {
7356
7570
  }
7357
7571
  function runAudioStage(input) {
7358
7572
  return collectScratchLeftovers(
7359
- () => runAudioStageScoped(input),
7573
+ () => withFfmpegProgress(input.onFfmpegProgress ?? (() => {
7574
+ }), () => runAudioStageScoped(input)),
7360
7575
  (left) => {
7361
7576
  if (left.length > 0) input.log?.warn("[audio] scratch left behind", { count: left.length });
7362
7577
  }
@@ -7910,7 +8125,7 @@ import {
7910
8125
  readdirSync as readdirSync2,
7911
8126
  readFileSync as readFileSync6,
7912
8127
  rmSync as rmSync4,
7913
- statSync as statSync5,
8128
+ statSync as statSync6,
7914
8129
  writeFileSync as writeFileSync4
7915
8130
  } from "node:fs";
7916
8131
  import { readFile as readFile2 } from "node:fs/promises";
@@ -8039,7 +8254,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
8039
8254
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
8040
8255
  if (failure) return failure;
8041
8256
  }
8042
- const fileSize = existsSync13(outputPath) ? statSync5(outputPath).size : 0;
8257
+ const fileSize = existsSync13(outputPath) ? statSync6(outputPath).size : 0;
8043
8258
  return {
8044
8259
  success: true,
8045
8260
  outputPath,
@@ -8062,7 +8277,10 @@ function startEncodeProgress(job, stage, onProgress) {
8062
8277
  function resolveEngineConfig(input) {
8063
8278
  return input.engineConfig ?? input.job.config.producerConfig ?? resolveConfig();
8064
8279
  }
8065
- function videoEncoderOptions(input, engineCfg) {
8280
+ function overlapEncoderThreads(workerCount, cpuCount) {
8281
+ return Math.max(1, Math.floor(cpuCount) - Math.floor(workerCount));
8282
+ }
8283
+ function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
8066
8284
  const { job, preset } = input;
8067
8285
  return {
8068
8286
  fps: job.config.fps,
@@ -8082,7 +8300,8 @@ function videoEncoderOptions(input, engineCfg) {
8082
8300
  // keyframes that survive `-f concat -c copy` at assemble time. In-process
8083
8301
  // renders leave both undefined → preserves the existing open-GOP output.
8084
8302
  lockGopForChunkConcat: input.lockGopForChunkConcat === true,
8085
- gopSize: input.gopSize
8303
+ gopSize: input.gopSize,
8304
+ softwareEncoderThreads
8086
8305
  };
8087
8306
  }
8088
8307
  function canEncodeWhileCapturing(input, workerCount, cpuCount) {
@@ -8098,8 +8317,9 @@ async function readLandedFrame(workerPath, mergedPath) {
8098
8317
  }
8099
8318
  return readFile2(mergedPath);
8100
8319
  }
8101
- function encodeWhileCapturing(input, totalFrames) {
8320
+ function encodeWhileCapturing(input, totalFrames, captureBudget) {
8102
8321
  const engineCfg = resolveEngineConfig(input);
8322
+ const softwareEncoderThreads = captureBudget ? overlapEncoderThreads(captureBudget.workerCount, captureBudget.cpuCount) : void 0;
8103
8323
  const stop = new AbortController();
8104
8324
  const signal = input.abortSignal ? AbortSignal.any([input.abortSignal, stop.signal]) : stop.signal;
8105
8325
  const landed = /* @__PURE__ */ new Map();
@@ -8114,7 +8334,10 @@ function encodeWhileCapturing(input, totalFrames) {
8114
8334
  let reportFed = null;
8115
8335
  const encoder = spawnStreamingEncoder4(
8116
8336
  input.videoOnlyPath,
8117
- { ...videoEncoderOptions(input, engineCfg), imageFormat: "jpeg" },
8337
+ {
8338
+ ...videoEncoderOptions(input, engineCfg, softwareEncoderThreads),
8339
+ imageFormat: "jpeg"
8340
+ },
8118
8341
  signal,
8119
8342
  engineCfg
8120
8343
  );
@@ -8293,7 +8516,7 @@ function sampleDirectoryBytes(dir) {
8293
8516
  for (const name of entries) {
8294
8517
  const full = join18(current, name);
8295
8518
  try {
8296
- const st = statSync6(full);
8519
+ const st = statSync7(full);
8297
8520
  if (st.isDirectory()) {
8298
8521
  stack.push(full);
8299
8522
  } else if (st.isFile()) {
@@ -8374,7 +8597,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
8374
8597
  let rangeStart = null;
8375
8598
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
8376
8599
  const framePath = join18(framesDir, formatCaptureFrameName(frameIndex, frameExt));
8377
- const missing = !existsSync14(framePath) || statSync6(framePath).size <= 8;
8600
+ const missing = !existsSync14(framePath) || statSync7(framePath).size <= 8;
8378
8601
  if (missing && rangeStart === null) {
8379
8602
  rangeStart = frameIndex;
8380
8603
  } else if (!missing && rangeStart !== null) {
@@ -8977,8 +9200,10 @@ function buildSyntheticRenderJob(input) {
8977
9200
  producerConfig: input.producerConfig,
8978
9201
  variables: input.variables,
8979
9202
  strictVariables: input.strictVariables,
9203
+ expectedOutputDimensions: input.expectedOutputDimensions,
8980
9204
  pageMotionBlur: input.pageMotionBlur,
8981
- allowOutsideProjectAssets: input.allowOutsideProjectAssets
9205
+ allowOutsideProjectAssets: input.allowOutsideProjectAssets,
9206
+ includeOutsideScripts: input.includeOutsideScripts
8982
9207
  };
8983
9208
  return createRenderJob(renderConfig);
8984
9209
  }
@@ -10845,8 +11070,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
10845
11070
  producerConfig: cfg,
10846
11071
  variables: config.variables,
10847
11072
  strictVariables: config.strictVariables,
11073
+ expectedOutputDimensions: config.expectedOutputDimensions,
10848
11074
  pageMotionBlur: config.pageMotionBlur,
10849
- allowOutsideProjectAssets: options.allowOutsideProjectAssets === true
11075
+ allowOutsideProjectAssets: options.allowOutsideProjectAssets === true,
11076
+ includeOutsideScripts: options.includeOutsideScripts === true
10850
11077
  });
10851
11078
  const entryFile = config.entryFile ?? "index.html";
10852
11079
  const htmlPath = join27(projectDir, entryFile);
@@ -10867,7 +11094,9 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
10867
11094
  if (rel === "") return true;
10868
11095
  if (leavesRoot(rel)) return false;
10869
11096
  if (job.config.allowOutsideProjectAssets) {
10870
- if (refusesOutsideLink(projectDir, src, (line) => log.warn(`[Plan] ${line}`))) return false;
11097
+ const warn = (line) => log.warn(`[Plan] ${line}`);
11098
+ const policy = { includeScripts: job.config.includeOutsideScripts };
11099
+ if (refusesOutsideLink(projectDir, src, warn, policy)) return false;
10871
11100
  } else if (!isSafePath2(projectDir, src)) return false;
10872
11101
  const firstSegment = rel.split(sep4, 1)[0];
10873
11102
  return firstSegment === void 0 || !PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(firstSegment);
@@ -11312,6 +11541,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
11312
11541
  format: config.format,
11313
11542
  ffmpegVersion,
11314
11543
  producerVersion,
11544
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked },
11315
11545
  ...job.strictVariablesChecked === void 0 ? {} : { strictVariablesChecked: job.strictVariablesChecked }
11316
11546
  };
11317
11547
  }
@@ -11356,7 +11586,7 @@ import {
11356
11586
  readFileSync as readFileSync10,
11357
11587
  readdirSync as readdirSync7,
11358
11588
  rmSync as rmSync9,
11359
- statSync as statSync8,
11589
+ statSync as statSync9,
11360
11590
  writeFileSync as writeFileSync10
11361
11591
  } from "node:fs";
11362
11592
  import { tmpdir } from "node:os";
@@ -11375,7 +11605,7 @@ import {
11375
11605
  linkSync as linkSync2,
11376
11606
  mkdirSync as mkdirSync11,
11377
11607
  rmSync as rmSync8,
11378
- statSync as statSync7,
11608
+ statSync as statSync8,
11379
11609
  writeFileSync as writeFileSync9
11380
11610
  } from "node:fs";
11381
11611
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
@@ -11445,7 +11675,7 @@ var LocalPlanV2ArtifactPublisher = class {
11445
11675
  }
11446
11676
  async putBlob(blob) {
11447
11677
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
11448
- const sourceSize = statSync7(blob.sourcePath).size;
11678
+ const sourceSize = statSync8(blob.sourcePath).size;
11449
11679
  if (sourceSize !== blob.sizeBytes) {
11450
11680
  throw new PlanV2IntegrityError(
11451
11681
  `published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`
@@ -11759,7 +11989,7 @@ function publishBlobFor(absolutePath, digests) {
11759
11989
  return {
11760
11990
  sourcePath: absolutePath,
11761
11991
  sha256: planFileSha256(absolutePath, digests),
11762
- sizeBytes: statSync8(absolutePath).size
11992
+ sizeBytes: statSync9(absolutePath).size
11763
11993
  };
11764
11994
  }
11765
11995
  async function putBlobs(publisher, blobs) {
@@ -11938,7 +12168,10 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
11938
12168
  sliceChunkAudio: true,
11939
12169
  deferAudio: options.deferAudio
11940
12170
  });
11941
- options.onPlanned?.({ strictVariablesChecked: planned.strictVariablesChecked });
12171
+ options.onPlanned?.({
12172
+ strictVariablesChecked: planned.strictVariablesChecked,
12173
+ outputDimensionsChecked: planned.outputDimensionsChecked
12174
+ });
11942
12175
  return await publishExecutionPlan(stagingRoot, publisher, { digests, log: config.logger });
11943
12176
  } catch (error) {
11944
12177
  try {
@@ -12127,7 +12360,7 @@ function verifyBlob(planV2Dir, artifact) {
12127
12360
  if (!existsSync21(sourcePath)) {
12128
12361
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
12129
12362
  }
12130
- const stats = statSync8(sourcePath);
12363
+ const stats = statSync9(sourcePath);
12131
12364
  if (!stats.isFile() || stats.size !== artifact.sizeBytes) {
12132
12365
  throw new PlanV2IntegrityError(`artifact size mismatch for ${artifact.path}`);
12133
12366
  }
@@ -12220,7 +12453,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
12220
12453
  for (const artifact of required) {
12221
12454
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
12222
12455
  const path = join30(planDir, ...artifact.path.split("/"));
12223
- if (!existsSync21(path) || statSync8(path).size !== artifact.sizeBytes) {
12456
+ if (!existsSync21(path) || statSync9(path).size !== artifact.sizeBytes) {
12224
12457
  throw new PlanV2IntegrityError(
12225
12458
  `materialized artifact missing or truncated: ${artifact.path}`
12226
12459
  );
@@ -12249,7 +12482,7 @@ import {
12249
12482
  readFileSync as readFileSync11,
12250
12483
  readdirSync as readdirSync8,
12251
12484
  rmSync as rmSync10,
12252
- statSync as statSync9,
12485
+ statSync as statSync10,
12253
12486
  writeFileSync as writeFileSync11
12254
12487
  } from "node:fs";
12255
12488
  import { basename as basename6, dirname as dirname16, join as join31 } from "node:path";
@@ -12294,7 +12527,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
12294
12527
  outputPath,
12295
12528
  durationMs: Date.now() - start,
12296
12529
  framesEncoded: plan.totalFrames,
12297
- fileSize: statSync9(outputPath).size
12530
+ fileSize: statSync10(outputPath).size
12298
12531
  };
12299
12532
  }
12300
12533
  const format = plan.dimensions.format;
@@ -12341,7 +12574,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
12341
12574
  });
12342
12575
  }
12343
12576
  }
12344
- const fileSize = existsSync22(outputPath) ? statSync9(outputPath).size : 0;
12577
+ const fileSize = existsSync22(outputPath) ? statSync10(outputPath).size : 0;
12345
12578
  return {
12346
12579
  ...referenceBackgroundResult6(plan[REFERENCE_BACKGROUND_FIELD4]),
12347
12580
  outputPath,
@@ -12539,7 +12772,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
12539
12772
  mkdirSync13(outputPath, { recursive: true });
12540
12773
  let globalIdx = 0;
12541
12774
  for (const chunkDir of chunkPaths) {
12542
- if (!statSync9(chunkDir).isDirectory()) {
12775
+ if (!statSync10(chunkDir).isDirectory()) {
12543
12776
  throw new Error(
12544
12777
  `[assemble] png-sequence chunk must be a directory: ${chunkDir} (got a file)`
12545
12778
  );
@@ -12566,7 +12799,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
12566
12799
  let fileSize = 0;
12567
12800
  for (const name of readdirSync8(outputPath)) {
12568
12801
  try {
12569
- fileSize += statSync9(join31(outputPath, name)).size;
12802
+ fileSize += statSync10(join31(outputPath, name)).size;
12570
12803
  } catch {
12571
12804
  }
12572
12805
  }
@@ -13127,7 +13360,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
13127
13360
  const captureSession = session;
13128
13361
  session = null;
13129
13362
  verifyStarted = Date.now();
13130
- overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount2()) ? encodeWhileCapturing(encodeInput, framesInChunk) : null;
13363
+ overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount2()) ? encodeWhileCapturing(encodeInput, framesInChunk, {
13364
+ workerCount: chunkWorkerCount,
13365
+ cpuCount: usableCpuCount2()
13366
+ }) : null;
13131
13367
  await observeRenderStage(
13132
13368
  new RenderObservabilityRecorder({ pipelineStartMs: start, log }),
13133
13369
  "capture_chunk",
@@ -13363,6 +13599,12 @@ function validateDistributedRenderConfig(config) {
13363
13599
  `must be one of ${DISTRIBUTED_FPS2.join(", ")}; got ${String(config.fps)}`
13364
13600
  );
13365
13601
  }
13602
+ if (config.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(config.expectedOutputDimensions)) {
13603
+ throw new InvalidConfigError(
13604
+ "config.expectedOutputDimensions",
13605
+ "must contain positive integer width and height"
13606
+ );
13607
+ }
13366
13608
  validateIntDimension("config.width", config.width);
13367
13609
  validateIntDimension("config.height", config.height);
13368
13610
  if (config.pageMotionBlur !== void 0 && config.pageMotionBlur !== "off") {
@@ -13618,28 +13860,30 @@ function validateIntDimension(field, value) {
13618
13860
  }
13619
13861
 
13620
13862
  // src/services/distributed/projectHash.ts
13621
- import { closeSync as closeSync5, openSync as openSync5, readdirSync as readdirSync10, readSync as readSync4, realpathSync as realpathSync2, statSync as statSync10 } from "node:fs";
13863
+ import { closeSync as closeSync5, openSync as openSync5, readdirSync as readdirSync10, readSync as readSync4, realpathSync as realpathSync2, statSync as statSync11 } from "node:fs";
13622
13864
  import { createHash as createHash9 } from "node:crypto";
13623
- import { join as join34 } from "node:path";
13865
+ import { join as join34, sep as sep6 } from "node:path";
13624
13866
  import { isPrivateFileUnder as isPrivateFileUnder3, isStudioPrivatePath as isStudioPrivatePath3 } from "@hyperframes/core/safe-path";
13625
13867
  var SITE_ID_SCHEME = "site-v2\0";
13626
13868
  var READ_CHUNK_BYTES = 256 * 1024;
13627
13869
  var isPrivateSitePath = (relPath) => isStudioPrivatePath3(relPath);
13628
13870
  function statEntry(full, relPath) {
13629
13871
  try {
13630
- return statSync10(full);
13872
+ return statSync11(full);
13631
13873
  } catch (err) {
13632
13874
  throw new Error(`[listSiteFiles] cannot read ${relPath} (dangling symlink?)`, { cause: err });
13633
13875
  }
13634
13876
  }
13635
- function listSiteFiles(projectDir, onPrivate) {
13877
+ function listSiteFiles(projectDir, onPrivate, onOutside) {
13636
13878
  const files = [];
13637
- const ancestors = /* @__PURE__ */ new Set([realpathSync2(projectDir)]);
13879
+ const root = realpathSync2(projectDir);
13880
+ const ancestors = /* @__PURE__ */ new Set([root]);
13638
13881
  function visit(full, relPath) {
13639
13882
  if (isPrivateFileUnder3(projectDir, full, isStudioPrivatePath3)) return void onPrivate?.(relPath);
13640
13883
  const stat = statEntry(full, relPath);
13884
+ if (!stat.isFile() && !stat.isDirectory()) return;
13885
+ if (onOutside && outsideFolder(root, realpathSync2(full))) return void onOutside(relPath);
13641
13886
  if (stat.isFile()) return void files.push(relPath);
13642
- if (!stat.isDirectory()) return;
13643
13887
  const real = realpathSync2(full);
13644
13888
  if (ancestors.has(real)) return;
13645
13889
  ancestors.add(real);
@@ -13655,20 +13899,31 @@ function listSiteFiles(projectDir, onPrivate) {
13655
13899
  walk(projectDir, "");
13656
13900
  return files;
13657
13901
  }
13902
+ var outsideFolder = (root, real) => real !== root && !real.startsWith(root + sep6);
13658
13903
  var printablePath = (path) => [...path].map((ch) => {
13659
13904
  const code = ch.charCodeAt(0);
13660
13905
  const control = code < 32 && code !== 9 || code >= 127 && code <= 159;
13661
13906
  return control ? `\\x${code.toString(16).padStart(2, "0")}` : ch;
13662
13907
  }).join("");
13663
- function listSiteFilesForUpload(projectDir, onNotice) {
13908
+ function listSiteFilesForUpload(projectDir, onNotice, includeOutsideFiles = false) {
13664
13909
  const leftOut = [];
13665
- const files = listSiteFiles(projectDir, (path) => leftOut.push(path));
13910
+ const outside = [];
13911
+ const files = listSiteFiles(
13912
+ projectDir,
13913
+ (path) => leftOut.push(path),
13914
+ includeOutsideFiles ? void 0 : (path) => outside.push(path)
13915
+ );
13666
13916
  if (leftOut.length > 0) {
13667
13917
  const more = leftOut.length > 5 ? ` and ${leftOut.length - 5} more` : "";
13668
13918
  onNotice?.(
13669
13919
  `[deploySite] left out private files no composition loads (env, Git, credentials, tool state): ${leftOut.slice(0, 5).map(printablePath).join(", ")}${more}`
13670
13920
  );
13671
13921
  }
13922
+ if (outside.length > 0) {
13923
+ onNotice?.(
13924
+ `[deploySite] left out files linked in from outside the project: ${outside.map(printablePath).join(", ")}. Pass --include-outside-files (includeOutsideFiles in the SDK) to upload them.`
13925
+ );
13926
+ }
13672
13927
  return files;
13673
13928
  }
13674
13929
  function hashProjectDir(projectDir, files = listSiteFiles(projectDir)) {