@hyperframes/producer 0.9.30 → 0.9.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  // src/services/renderOrchestrator.ts
10
10
  import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
11
11
  import {
12
- existsSync as existsSync21,
12
+ existsSync as existsSync22,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync12,
@@ -67,7 +67,7 @@ import {
67
67
  referenceBackgroundResult,
68
68
  createReferenceBackgroundRecorder
69
69
  } from "@hyperframes/engine";
70
- import { join as join30, dirname as dirname13, resolve as resolve8 } from "path";
70
+ import { join as join31, dirname as dirname13, resolve as resolve8 } from "path";
71
71
  import { totalmem as totalmem2 } from "node:os";
72
72
  import { randomUUID } from "crypto";
73
73
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -980,6 +980,33 @@ function resolveDeliveryEncoderOptions(config) {
980
980
  return { maxBitrate, bufferSize, ...gop };
981
981
  }
982
982
 
983
+ // src/services/render/chromaSubsampling.ts
984
+ function validateChromaSubsamplingConfig(config) {
985
+ if (config.chromaSubsampling !== "444") return;
986
+ const format = config.format ?? "mp4";
987
+ if (format !== "mp4") {
988
+ throw new Error(
989
+ `[Render] chromaSubsampling "444" supports format "mp4" only (got "${format}"). WebM, MOV and GIF use their own pixel formats, and HLS targets broad playback. Use --format mp4, or drop --chroma-subsampling 444.`
990
+ );
991
+ }
992
+ if (config.hdrMode === "force-hdr") {
993
+ throw new Error(
994
+ `[Render] chromaSubsampling "444" is SDR only; HDR output stays 10-bit 4:2:0 H.265. Drop --hdr, or drop --chroma-subsampling 444.`
995
+ );
996
+ }
997
+ if (config.useGpu === true) {
998
+ throw new Error(
999
+ `[Render] chromaSubsampling "444" requires the software encoder (libx264); GPU encoders do not reliably support 4:4:4. Re-run without --gpu.`
1000
+ );
1001
+ }
1002
+ }
1003
+ function assertChromaSubsamplingSdr(config, hasHdrContent) {
1004
+ if (config.chromaSubsampling !== "444" || !hasHdrContent) return;
1005
+ throw new Error(
1006
+ `[Render] chromaSubsampling "444" is SDR only, but this composition has HDR sources. Re-run with --sdr (hdrMode "force-sdr"), or drop --chroma-subsampling 444.`
1007
+ );
1008
+ }
1009
+
983
1010
  // src/services/render/shared.ts
984
1011
  import {
985
1012
  copyFileSync,
@@ -995,6 +1022,9 @@ import {
995
1022
  CANVAS_DIMENSIONS,
996
1023
  checkOutputResolutionCompatibility
997
1024
  } from "@hyperframes/core";
1025
+ import {
1026
+ mediaIdPathSegment
1027
+ } from "@hyperframes/engine";
998
1028
 
999
1029
  // src/utils/paths.ts
1000
1030
  import {
@@ -1089,6 +1119,10 @@ function writeCompiledArtifacts(compiled, workDir, includeSummary) {
1089
1119
  writeFileSync(join3(compileDir, "index.html"), compiled.html, "utf-8");
1090
1120
  for (const [srcPath, html] of compiled.subCompositions) {
1091
1121
  const outPath = join3(compileDir, srcPath);
1122
+ if (!isPathInside2(outPath, compileDir)) {
1123
+ console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
1124
+ continue;
1125
+ }
1092
1126
  mkdirSync(dirname2(outPath), { recursive: true });
1093
1127
  writeFileSync(outPath, html, "utf-8");
1094
1128
  }
@@ -1350,7 +1384,7 @@ function materializeExtractedFramesForCompiledDir(extracted, compiledDir, option
1350
1384
  for (const ext of extracted) {
1351
1385
  const resolvedOut = pathModule.resolve(ext.outputDir);
1352
1386
  if (isPathInside2(resolvedOut, resolvedCompiledDir, { pathModule })) continue;
1353
- const linkPath = pathModule.join(compiledFrameRoot, ext.videoId);
1387
+ const linkPath = pathModule.join(compiledFrameRoot, mediaIdPathSegment(ext.videoId));
1354
1388
  if (!fileSystem.existsSync(linkPath)) {
1355
1389
  fileSystem.mkdirSync(pathModule.dirname(linkPath), { recursive: true });
1356
1390
  stageExtractedFrameDir(
@@ -5425,6 +5459,7 @@ import { dirname as dirname5, join as join11 } from "node:path";
5425
5459
  import {
5426
5460
  createFrameLookupTable,
5427
5461
  extractVideoFramesRange,
5462
+ mediaIdPathSegment as mediaIdPathSegment2,
5428
5463
  runVideoExtractionWithRetry
5429
5464
  } from "@hyperframes/engine";
5430
5465
  function contiguousRuns(sortedIndexes) {
@@ -5465,7 +5500,7 @@ async function extractDeferredFrames(input) {
5465
5500
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5466
5501
  return Promise.all(
5467
5502
  deferred.map(async (video) => {
5468
- const outputDir = join11(input.outputRoot, video.videoId);
5503
+ const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
5469
5504
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5470
5505
  if (indexes.length === 0) {
5471
5506
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -6340,8 +6375,8 @@ function countAuthoredTimedClips(html) {
6340
6375
  }
6341
6376
 
6342
6377
  // src/services/render/stages/compileStage.ts
6343
- import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6344
- import { join as join18 } from "node:path";
6378
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
6379
+ import { join as join19 } from "node:path";
6345
6380
  import { suggestMatchingPreset } from "@hyperframes/core";
6346
6381
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6347
6382
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
@@ -6349,9 +6384,23 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
6349
6384
  // src/services/htmlCompiler.ts
6350
6385
  import { decodedUrlPath as decodedUrlPath2 } from "@hyperframes/parsers/asset-paths";
6351
6386
  import { createHash as createHash6 } from "node:crypto";
6352
- import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync7 } from "fs";
6353
- import { join as join17, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep2 } from "path";
6387
+ import { createReadStream as createReadStream2, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6388
+ import { join as join18, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep2 } from "path";
6354
6389
  import { parseHTML as parseHTML5 } from "linkedom";
6390
+
6391
+ // src/services/bundledScripts.ts
6392
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
6393
+ import { join as join15 } from "node:path";
6394
+ import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
6395
+ var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
6396
+ function bundledScript(url) {
6397
+ const dir = process.env[GSAP_VENDOR_DIR_ENV];
6398
+ if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
6399
+ const file = join15(dir, "gsap.min.js");
6400
+ return existsSync9(file) ? readFileSync5(file) : null;
6401
+ }
6402
+
6403
+ // src/services/htmlCompiler.ts
6355
6404
  import {
6356
6405
  COMPOSITION_SOURCE_URL,
6357
6406
  compileTimingAttrs,
@@ -6373,7 +6422,7 @@ import {
6373
6422
  import { MAX_AUDIO_GAIN } from "@hyperframes/core/audio-gain";
6374
6423
  import { readPlaybackRate } from "@hyperframes/parsers/media-duration";
6375
6424
  import { resolveRateSpec } from "@hyperframes/core/speed-ramp";
6376
- import { gsapCdnDist, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
6425
+ import { gsapCdnDist as gsapCdnDist2, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
6377
6426
  import {
6378
6427
  assignBundledRuntimeCompositionIds,
6379
6428
  assignMediaRenderIds,
@@ -6596,8 +6645,8 @@ import {
6596
6645
 
6597
6646
  // src/services/animatedGifPrep.ts
6598
6647
  import { createHash as createHash4 } from "node:crypto";
6599
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync5, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6600
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join15, resolve as resolve5 } from "node:path";
6648
+ import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6649
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
6601
6650
  import { parseHTML as parseHTML3 } from "linkedom";
6602
6651
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
6603
6652
  import { DEFAULT_VP9_CPU_USED, runFfmpeg as runFfmpeg2, renameWithRetry as renameWithRetry3 } from "@hyperframes/engine";
@@ -6635,14 +6684,14 @@ function resolveLocalImageSourcePath(src, options) {
6635
6684
  const { basePath } = splitUrlSuffix(trimmed);
6636
6685
  const normalizedBase = normalizeRelPath(basePath);
6637
6686
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
6638
- if (mapped && existsSync9(mapped)) return mapped;
6687
+ if (mapped && existsSync10(mapped)) return mapped;
6639
6688
  if (isHttpUrl(trimmed)) return null;
6640
6689
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
6641
6690
  const candidates = [
6642
6691
  isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
6643
6692
  resolve5(options.downloadDir, normalizedBase)
6644
6693
  ];
6645
- return candidates.find((candidate) => existsSync9(candidate)) ?? null;
6694
+ return candidates.find((candidate) => existsSync10(candidate)) ?? null;
6646
6695
  }
6647
6696
  function isUsableFile(path) {
6648
6697
  try {
@@ -6753,10 +6802,10 @@ async function runAnimatedGifTranscode(request) {
6753
6802
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
6754
6803
  }
6755
6804
  async function ensurePreparedWebm(input) {
6756
- if (!existsSync9(dirname6(input.cachePath))) {
6805
+ if (!existsSync10(dirname6(input.cachePath))) {
6757
6806
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
6758
6807
  }
6759
- if (!existsSync9(dirname6(input.outputPath))) {
6808
+ if (!existsSync10(dirname6(input.outputPath))) {
6760
6809
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
6761
6810
  }
6762
6811
  if (!isUsableFile(input.cachePath)) {
@@ -6840,7 +6889,7 @@ function replaceImageWithVideo(input) {
6840
6889
  return video;
6841
6890
  }
6842
6891
  async function prepareAnimatedGifInputs(html, options) {
6843
- const outputDir = options.outputDir ?? join15(options.downloadDir, PREPARED_GIF_SUBDIR);
6892
+ const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_GIF_SUBDIR);
6844
6893
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
6845
6894
  const cacheDir = options.cacheDir ?? outputDir;
6846
6895
  const { document: document2 } = parseHTML3(html);
@@ -6854,7 +6903,7 @@ async function prepareAnimatedGifInputs(html, options) {
6854
6903
  if (!hasGifExtension(src)) continue;
6855
6904
  const sourcePath = resolveLocalImageSourcePath(src, options);
6856
6905
  if (!sourcePath) continue;
6857
- const bytes = readFileSync5(sourcePath);
6906
+ const bytes = readFileSync6(sourcePath);
6858
6907
  const metadata = parseAnimatedGifMetadata(bytes);
6859
6908
  if (!metadata?.animated) continue;
6860
6909
  const loopOverride = readLoopOverride(img);
@@ -6867,8 +6916,8 @@ async function prepareAnimatedGifInputs(html, options) {
6867
6916
  );
6868
6917
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
6869
6918
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
6870
- const cachePath = join15(cacheDir, filename);
6871
- const outputPath = join15(outputDir, filename);
6919
+ const cachePath = join16(cacheDir, filename);
6920
+ const outputPath = join16(outputDir, filename);
6872
6921
  const outputSrc = `${outputSrcPrefix}/${filename}`;
6873
6922
  await ensurePreparedWebm({
6874
6923
  sourcePath,
@@ -6907,13 +6956,13 @@ import {
6907
6956
  copyFileSync as copyFileSync3,
6908
6957
  mkdirSync as mkdirSync8,
6909
6958
  openSync as openSync4,
6910
- readFileSync as readFileSync6,
6959
+ readFileSync as readFileSync7,
6911
6960
  readSync as readSync3,
6912
6961
  rmSync as rmSync10,
6913
6962
  statSync as statSync7,
6914
6963
  writeFileSync as writeFileSync4
6915
6964
  } from "node:fs";
6916
- import { dirname as dirname7, join as join16, resolve as resolve6 } from "node:path";
6965
+ import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
6917
6966
  import { parseHTML as parseHTML4 } from "linkedom";
6918
6967
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe } from "@hyperframes/engine";
6919
6968
 
@@ -7091,7 +7140,7 @@ function primaryGrid(probed) {
7091
7140
  async function convertHeifToJpeg(request) {
7092
7141
  const probed = await probeJson(request.inputPath, true);
7093
7142
  const grid = primaryGrid(probed);
7094
- const rotation = readHeifPrimaryRotation(readFileSync6(request.inputPath));
7143
+ const rotation = readHeifPrimaryRotation(readFileSync7(request.inputPath));
7095
7144
  const filters = [];
7096
7145
  let inputs = [];
7097
7146
  let size = probed.streams?.[0];
@@ -7149,7 +7198,7 @@ function resolveImageSource(src, options) {
7149
7198
  const path = resolveLocalImageSourcePath(src, options);
7150
7199
  const head = path ? readHead(path) : null;
7151
7200
  if (!path || !head || !isHeifBytes(head)) return null;
7152
- return { path, bytes: readFileSync6(path), label: `"${splitUrlSuffix(src).basePath}"` };
7201
+ return { path, bytes: readFileSync7(path), label: `"${splitUrlSuffix(src).basePath}"` };
7153
7202
  }
7154
7203
  function isUsableFile2(path) {
7155
7204
  try {
@@ -7187,7 +7236,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
7187
7236
  }
7188
7237
  }
7189
7238
  async function prepareHeifImageInputs(html, options) {
7190
- const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_HEIF_SUBDIR);
7239
+ const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_HEIF_SUBDIR);
7191
7240
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
7192
7241
  const cacheDir = options.cacheDir ?? outputDir;
7193
7242
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -7208,7 +7257,7 @@ async function prepareHeifImageInputs(html, options) {
7208
7257
  await Promise.all(
7209
7258
  [...unique].map(
7210
7259
  ([filename, source]) => withMediaProbeSlot(
7211
- () => ensurePreparedJpeg(source, join16(cacheDir, filename), join16(outputDir, filename), options)
7260
+ () => ensurePreparedJpeg(source, join17(cacheDir, filename), join17(outputDir, filename), options)
7212
7261
  ).catch((error) => {
7213
7262
  if (!options.onFailure) throw error;
7214
7263
  failed.add(filename);
@@ -7220,8 +7269,8 @@ async function prepareHeifImageInputs(html, options) {
7220
7269
  if (failed.has(filename)) continue;
7221
7270
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7222
7271
  img.setAttribute("src", outputSrc);
7223
- preparedAssets.set(outputSrc, join16(outputDir, filename));
7224
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join16(outputDir, filename) });
7272
+ preparedAssets.set(outputSrc, join17(outputDir, filename));
7273
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join17(outputDir, filename) });
7225
7274
  }
7226
7275
  return { html: document2.toString(), preparedAssets, preparedImages };
7227
7276
  }
@@ -7231,7 +7280,7 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7231
7280
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7232
7281
 
7233
7282
  // src/services/assetMediaType.ts
7234
- import { existsSync as existsSync10 } from "node:fs";
7283
+ import { existsSync as existsSync11 } from "node:fs";
7235
7284
  import {
7236
7285
  fingerprintElementId,
7237
7286
  isNotMediaPayload,
@@ -7304,7 +7353,7 @@ async function preflightCompositionAssetMediaTypes(input) {
7304
7353
  input.projectDir,
7305
7354
  input.compiledDir
7306
7355
  );
7307
- if (!existsSync10(resolvedPath)) continue;
7356
+ if (!existsSync11(resolvedPath)) continue;
7308
7357
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
7309
7358
  }
7310
7359
  const mismatches = [];
@@ -7557,8 +7606,8 @@ function detectShaderTransitionUsage(html) {
7557
7606
  async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes) {
7558
7607
  let filePath = src;
7559
7608
  if (isHttpUrl(src)) {
7560
- const remoteDir = join17(downloadDir, REMOTE_MEDIA_SUBDIR);
7561
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7609
+ const remoteDir = join18(downloadDir, REMOTE_MEDIA_SUBDIR);
7610
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7562
7611
  try {
7563
7612
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
7564
7613
  onTelemetry: logRemoteDownloadTelemetry
@@ -7568,10 +7617,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
7568
7617
  }
7569
7618
  } else {
7570
7619
  filePath = decodedUrlPath2(src);
7571
- if (!filePath.startsWith("/")) filePath = join17(baseDir, filePath);
7620
+ if (!filePath.startsWith("/")) filePath = join18(baseDir, filePath);
7572
7621
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
7573
7622
  }
7574
- if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
7623
+ if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
7575
7624
  return { duration: null, resolvedPath: filePath };
7576
7625
  }
7577
7626
  const withSrcContext = (error) => {
@@ -7920,7 +7969,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
7920
7969
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
7921
7970
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
7922
7971
  // against its own directory, project-root refs stay as authored.
7923
- assetExists: (path) => existsSync11(resolve7(projectDir, path)),
7972
+ assetExists: (path) => existsSync12(resolve7(projectDir, path)),
7924
7973
  // Preserve the authored root wrapper as a child of the host, matching
7925
7974
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
7926
7975
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8065,12 +8114,17 @@ async function inlineExternalScripts(html) {
8065
8114
  if (externalScripts.length === 0) return html;
8066
8115
  const downloads = await Promise.allSettled(
8067
8116
  externalScripts.map(async ({ el, src }) => {
8117
+ const integrity = el.getAttribute("integrity") || "";
8118
+ const bundled = bundledScript(src);
8119
+ if (bundled && matchesScriptIntegrity(bundled, integrity)) {
8120
+ return { src, text: new TextDecoder().decode(bundled) };
8121
+ }
8068
8122
  const response = await fetch(src, {
8069
8123
  signal: AbortSignal.timeout(15e3)
8070
8124
  });
8071
8125
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
8072
8126
  const bytes = new Uint8Array(await response.arrayBuffer());
8073
- if (!matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "")) {
8127
+ if (!matchesScriptIntegrity(bytes, integrity)) {
8074
8128
  throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
8075
8129
  }
8076
8130
  return { src, text: new TextDecoder().decode(bytes) };
@@ -8111,7 +8165,7 @@ function collectExternalAssets(html, projectDir) {
8111
8165
  if (isPathInside2(absPath, absProjectDir)) {
8112
8166
  return null;
8113
8167
  }
8114
- if (!existsSync11(absPath)) return null;
8168
+ if (!existsSync12(absPath)) return null;
8115
8169
  const safeKey = toExternalAssetKey(absPath);
8116
8170
  externalAssets.set(safeKey, absPath);
8117
8171
  return safeKey;
@@ -8161,7 +8215,7 @@ var REMOTE_SOURCE_TAG_RE = /<source\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+)["
8161
8215
  var REMOTE_IMG_TAG_RE = /<img\b[^>]*?(?<![\w-])src\s*=\s*["'](https?:\/\/[^"']+)["'][^>]*>/gi;
8162
8216
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
8163
8217
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
8164
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8218
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8165
8219
  const urlToLocal = /* @__PURE__ */ new Map();
8166
8220
  await Promise.all(
8167
8221
  [...urlSet].map(async (url) => {
@@ -8208,7 +8262,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
8208
8262
  return downloadAndRewriteUrls(
8209
8263
  urlSet,
8210
8264
  html,
8211
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8265
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8212
8266
  "Remote media download failed",
8213
8267
  "Localized remote media source(s)"
8214
8268
  );
@@ -8223,7 +8277,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
8223
8277
  return downloadAndRewriteUrls(
8224
8278
  urlSet,
8225
8279
  html,
8226
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8280
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8227
8281
  "Remote image download failed",
8228
8282
  "Localized remote image source(s)"
8229
8283
  );
@@ -8239,7 +8293,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
8239
8293
  return downloadAndRewriteUrls(
8240
8294
  urlSet,
8241
8295
  html,
8242
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8296
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8243
8297
  "Remote background-image download failed",
8244
8298
  "Localized remote background-image(s)",
8245
8299
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -8344,13 +8398,13 @@ function projectStylesheetFontFamilies(html, projectDir) {
8344
8398
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
8345
8399
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
8346
8400
  const sheet = resolve7(projectDir, decodedUrlPath2(href).replace(/^(?:\.?\/)+/, ""));
8347
- if (!isPathInside2(sheet, projectDir) || !existsSync11(sheet)) continue;
8348
- for (const face of extractFontFaceBlocks(readFileSync7(sheet, "utf8"))) {
8401
+ if (!isPathInside2(sheet, projectDir) || !existsSync12(sheet)) continue;
8402
+ for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
8349
8403
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
8350
8404
  const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
8351
8405
  const path = decodedUrlPath2(url);
8352
8406
  const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname8(sheet), path);
8353
- return isPathInside2(file, projectDir) && existsSync11(file);
8407
+ return isPathInside2(file, projectDir) && existsSync12(file);
8354
8408
  });
8355
8409
  if (family && shipsFile) families.push(family);
8356
8410
  }
@@ -8394,7 +8448,7 @@ function localizeFontFaceUrls(html, downloadDir) {
8394
8448
  return downloadAndRewriteUrls(
8395
8449
  collectFontFaceUrls(html),
8396
8450
  html,
8397
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8451
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8398
8452
  "Remote font download failed",
8399
8453
  "Localized remote font face(s)",
8400
8454
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -8478,7 +8532,7 @@ async function embedLocalFontFaces(html, projectDir) {
8478
8532
  }
8479
8533
  function renderGsapDist() {
8480
8534
  try {
8481
- return gsapCdnDist(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
8535
+ return gsapCdnDist2(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
8482
8536
  } catch (cause) {
8483
8537
  throw new Error(
8484
8538
  "Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment",
@@ -8488,7 +8542,7 @@ function renderGsapDist() {
8488
8542
  }
8489
8543
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
8490
8544
  let gsapDist;
8491
- const exists = (path) => existsSync11(resolve7(projectDir, path));
8545
+ const exists = (path) => existsSync12(resolve7(projectDir, path));
8492
8546
  return html.replace(
8493
8547
  /(<script\b[^>]*\bsrc=["'])([^"']*gsap[^"']*\/dist\/([^"']+))(["'][^>]*>)/gi,
8494
8548
  (full, prefix, src, file, suffix) => {
@@ -8505,7 +8559,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
8505
8559
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
8506
8560
  if (!entryPath.includes("/")) return html;
8507
8561
  const { document: document2 } = parseHTML5(html);
8508
- const assetExists = (path) => existsSync11(resolve7(projectDir, path));
8562
+ const assetExists = (path) => existsSync12(resolve7(projectDir, path));
8509
8563
  rewriteAssetPaths(
8510
8564
  document2.querySelectorAll("[src], [href], [srcset]"),
8511
8565
  entryPath,
@@ -9071,11 +9125,11 @@ function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height,
9071
9125
  }
9072
9126
  function resolveEntryHtmlPath(input) {
9073
9127
  const { projectDir, workDir, entryFile, log } = input;
9074
- const htmlPath = join18(projectDir, entryFile);
9128
+ const htmlPath = join19(projectDir, entryFile);
9075
9129
  const rawEntry = readTextFile2(htmlPath);
9076
9130
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
9077
- const projectIndexPath = join18(projectDir, "index.html");
9078
- if (!existsSync12(projectIndexPath)) {
9131
+ const projectIndexPath = join19(projectDir, "index.html");
9132
+ if (!existsSync13(projectIndexPath)) {
9079
9133
  throw new Error(
9080
9134
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
9081
9135
  );
@@ -9090,11 +9144,19 @@ function resolveEntryHtmlPath(input) {
9090
9144
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
9091
9145
  );
9092
9146
  }
9093
- const wrapperPath = join18(workDir, "standalone-entry.html");
9147
+ const wrapperPath = join19(workDir, "standalone-entry.html");
9094
9148
  writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
9095
9149
  log.info("Extracted standalone entry from index.html host context", { entryFile });
9096
9150
  return wrapperPath;
9097
9151
  }
9152
+ function applyChroma444Gate(cfg, chromaSubsampling, gate, log) {
9153
+ if (!cfg.useDrawElement || chromaSubsampling !== "444") return gate;
9154
+ cfg.useDrawElement = false;
9155
+ log.info(
9156
+ "[Render] Fast capture: chromaSubsampling 444 captures lossless PNG frames, so disabling drawElementImage for this render. Capture uses the platform's baseline route."
9157
+ );
9158
+ return "chroma_444";
9159
+ }
9098
9160
  async function runCompileStage(input) {
9099
9161
  const {
9100
9162
  projectDir,
@@ -9111,7 +9173,7 @@ async function runCompileStage(input) {
9111
9173
  } = input;
9112
9174
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log });
9113
9175
  const compileStart = Date.now();
9114
- const compiled = await compileForRender(projectDir, htmlPath, join18(workDir, "downloads"), {
9176
+ const compiled = await compileForRender(projectDir, htmlPath, join19(workDir, "downloads"), {
9115
9177
  log,
9116
9178
  failClosedFontFetch: failClosedFontFetch === true,
9117
9179
  allowSystemFontCapture,
@@ -9119,7 +9181,7 @@ async function runCompileStage(input) {
9119
9181
  variables: input.variables,
9120
9182
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
9121
9183
  pageMotionBlur: input.pageMotionBlur,
9122
- animatedGifCacheDir: cfg.extractCacheDir ? join18(cfg.extractCacheDir, "animated-gif") : void 0,
9184
+ animatedGifCacheDir: cfg.extractCacheDir ? join19(cfg.extractCacheDir, "animated-gif") : void 0,
9123
9185
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout
9124
9186
  });
9125
9187
  assertNotAborted();
@@ -9146,6 +9208,7 @@ async function runCompileStage(input) {
9146
9208
  "[Render] Fast capture: composition uses shader transitions, so disabling drawElementImage so page-side compositing stays available."
9147
9209
  );
9148
9210
  }
9211
+ deCompileGate = applyChroma444Gate(cfg, job.config.chromaSubsampling, deCompileGate, log);
9149
9212
  if (!cfg.useDrawElement && cfg.pageSideCompositingAutoDisabled) {
9150
9213
  cfg.enablePageSideCompositing = true;
9151
9214
  cfg.pageSideCompositingAutoDisabled = false;
@@ -9176,7 +9239,7 @@ async function runCompileStage(input) {
9176
9239
  };
9177
9240
  await preflightCompositionAssetMediaTypes({
9178
9241
  projectDir,
9179
- compiledDir: join18(workDir, "compiled"),
9242
+ compiledDir: join19(workDir, "compiled"),
9180
9243
  composition,
9181
9244
  signal: abortSignal
9182
9245
  });
@@ -9222,7 +9285,7 @@ async function runCompileStage(input) {
9222
9285
 
9223
9286
  // src/services/render/stages/probeStage.ts
9224
9287
  import { createHash as createHash7 } from "node:crypto";
9225
- import { basename as basename6, join as join19 } from "node:path";
9288
+ import { basename as basename6, join as join20 } from "node:path";
9226
9289
  import { parseHTML as parseHTML6 } from "linkedom";
9227
9290
  import {
9228
9291
  closeCaptureSession as closeCaptureSession4,
@@ -9257,11 +9320,19 @@ function isActionableProbeFailure(line) {
9257
9320
 
9258
9321
  // src/services/render/captureImageFormat.ts
9259
9322
  function resolveCaptureImageFormat(input) {
9260
- return input.needsAlpha || input.motionBlur ? "png" : "jpeg";
9323
+ return input.needsAlpha || input.motionBlur || input.chromaSubsampling === "444" ? "png" : "jpeg";
9261
9324
  }
9262
9325
  function resolveCaptureJpegQuality(quality) {
9263
9326
  return quality === "draft" ? 80 : 100;
9264
9327
  }
9328
+ function resolveCaptureSurface(input, quality) {
9329
+ const format = resolveCaptureImageFormat(input);
9330
+ return {
9331
+ format,
9332
+ quality: format === "png" ? void 0 : resolveCaptureJpegQuality(quality),
9333
+ transparent: input.needsAlpha
9334
+ };
9335
+ }
9265
9336
 
9266
9337
  // src/services/render/stages/probeStage.ts
9267
9338
  var FRAME_BOUNDARY_EPSILON = 1e-3;
@@ -9431,22 +9502,22 @@ async function runProbeStage(input) {
9431
9502
  });
9432
9503
  fileServer = await createFileServer({
9433
9504
  projectDir,
9434
- compiledDir: join19(workDir, "compiled"),
9505
+ compiledDir: join20(workDir, "compiled"),
9435
9506
  port: 0,
9436
9507
  preHeadScripts: [VIRTUAL_TIME_SHIM],
9437
9508
  fps: job.config.fps
9438
9509
  });
9439
9510
  assertNotAborted();
9440
9511
  const motionBlur = job.config.motionBlur;
9441
- const captureFormat = resolveCaptureImageFormat({ needsAlpha, motionBlur });
9442
9512
  const captureOpts = {
9443
9513
  recordReferenceBackground: input.recordReferenceBackground,
9444
9514
  width,
9445
9515
  height,
9446
9516
  fps: job.config.fps,
9447
- format: captureFormat,
9448
- transparent: needsAlpha,
9449
- quality: captureFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
9517
+ ...resolveCaptureSurface(
9518
+ { needsAlpha, motionBlur, chromaSubsampling: job.config.chromaSubsampling },
9519
+ job.config.quality
9520
+ ),
9450
9521
  variables: job.config.variables,
9451
9522
  deviceScaleFactor,
9452
9523
  motionBlur,
@@ -9461,7 +9532,7 @@ async function runProbeStage(input) {
9461
9532
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
9462
9533
  probeSession = await createCaptureSession4(
9463
9534
  fileServer.url,
9464
- join19(workDir, "probe"),
9535
+ join20(workDir, "probe"),
9465
9536
  captureOpts,
9466
9537
  null,
9467
9538
  probeCfg
@@ -9546,7 +9617,7 @@ async function runProbeStage(input) {
9546
9617
  });
9547
9618
  probeSession = await createCaptureSession4(
9548
9619
  fileServer.url,
9549
- join19(workDir, "probe-screenshot"),
9620
+ join20(workDir, "probe-screenshot"),
9550
9621
  captureOpts,
9551
9622
  null,
9552
9623
  { ...probeCfg, forceScreenshot: true }
@@ -9584,7 +9655,7 @@ async function runProbeStage(input) {
9584
9655
  compiled,
9585
9656
  resolutions,
9586
9657
  projectDir,
9587
- join19(workDir, "downloads")
9658
+ join20(workDir, "downloads")
9588
9659
  );
9589
9660
  assertNotAborted();
9590
9661
  composition.videos = compiled.videos;
@@ -9775,7 +9846,7 @@ async function runProbeStage(input) {
9775
9846
  }
9776
9847
  await preflightCompositionAssetMediaTypes({
9777
9848
  projectDir,
9778
- compiledDir: join19(workDir, "compiled"),
9849
+ compiledDir: join20(workDir, "compiled"),
9779
9850
  composition,
9780
9851
  signal: abortSignal
9781
9852
  });
@@ -9941,8 +10012,8 @@ function validateDistributedDuration(input) {
9941
10012
  }
9942
10013
 
9943
10014
  // src/services/render/stages/extractVideosStage.ts
9944
- import { existsSync as existsSync13 } from "node:fs";
9945
- import { join as join20 } from "node:path";
10015
+ import { existsSync as existsSync14 } from "node:fs";
10016
+ import { join as join21 } from "node:path";
9946
10017
  import {
9947
10018
  classifyVideoExtractionError,
9948
10019
  createFrameLookupTable as createFrameLookupTable3,
@@ -10216,7 +10287,7 @@ async function runExtractVideosStage(input) {
10216
10287
  const probeFailures = await Promise.all(
10217
10288
  composition.videos.map(async (v) => {
10218
10289
  const videoPath = resolveProjectRelativeSrc3(v.src, projectDir, compiledDir);
10219
- if (!existsSync13(videoPath)) return null;
10290
+ if (!existsSync14(videoPath)) return null;
10220
10291
  try {
10221
10292
  const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata3(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata3(videoPath), {
10222
10293
  signal: abortSignal,
@@ -10254,7 +10325,7 @@ async function runExtractVideosStage(input) {
10254
10325
  const probed = await Promise.all(
10255
10326
  composition.images.map(async (img) => {
10256
10327
  const imgPath = resolveProjectRelativeSrc3(img.src, projectDir, compiledDir);
10257
- if (!existsSync13(imgPath)) return null;
10328
+ if (!existsSync14(imgPath)) return null;
10258
10329
  const colorSpace = await probeColorSpaceSafely(imgPath, log);
10259
10330
  if (isHdrColorSpace2(colorSpace)) {
10260
10331
  nativeHdrImageIds.add(img.id);
@@ -10288,14 +10359,14 @@ async function runExtractVideosStage(input) {
10288
10359
  // because short boundary counts can differ by one frame.
10289
10360
  {
10290
10361
  fps: job.config.fps,
10291
- outputDir: join20(compiledDir, "__hyperframes_video_frames"),
10362
+ outputDir: join21(compiledDir, "__hyperframes_video_frames"),
10292
10363
  format: job.config.videoFrameFormat ?? "auto",
10293
10364
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
10294
10365
  timelineEnd: composition.duration,
10295
10366
  maxTransientRetries: extractionPolicy.maxTransientRetries,
10296
10367
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
10297
10368
  deferRangeExtraction,
10298
- contentKeyedDirs: [join20(compiledDir, REMOTE_MEDIA_SUBDIR)],
10369
+ contentKeyedDirs: [join21(compiledDir, REMOTE_MEDIA_SUBDIR)],
10299
10370
  urlByAbsentLocalPath,
10300
10371
  onProgress: ({ planned = 0, done = 0 }) => {
10301
10372
  framesPlanned += planned;
@@ -10374,7 +10445,7 @@ async function appendVideoAudioFromProbe(input) {
10374
10445
  videos.map(async (video) => {
10375
10446
  const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc3(video.src, projectDir, compiledDir);
10376
10447
  const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
10377
- if (!isHttpUrl2(readFrom) && !existsSync13(readFrom)) return null;
10448
+ if (!isHttpUrl2(readFrom) && !existsSync14(readFrom)) return null;
10378
10449
  const metadata = await extractMediaMetadata3(readFrom);
10379
10450
  const window2 = await resolveFinalFrameExtractionWindow2(
10380
10451
  readFrom,
@@ -10394,7 +10465,7 @@ async function appendVideoAudioFromProbe(input) {
10394
10465
  }
10395
10466
 
10396
10467
  // src/services/render/videoLayerPassthroughPlan.ts
10397
- import { existsSync as existsSync14 } from "node:fs";
10468
+ import { existsSync as existsSync15 } from "node:fs";
10398
10469
  import {
10399
10470
  buildVideoLayerInput,
10400
10471
  isHttpUrl as isHttpUrl3,
@@ -10462,7 +10533,7 @@ async function planVideoLayerPassthrough(input) {
10462
10533
  const { video } = q;
10463
10534
  if (isHttpUrl3(video.src)) return { reason: "remote_source" };
10464
10535
  const path = resolveProjectRelativeSrc4(video.src, input.projectDir, input.compiledDir);
10465
- if (!existsSync14(path)) return { reason: "source_missing" };
10536
+ if (!existsSync15(path)) return { reason: "source_missing" };
10466
10537
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
10467
10538
  if ("reason" in layout) return layout;
10468
10539
  const layer = await buildVideoLayerInput(
@@ -10477,8 +10548,8 @@ async function planVideoLayerPassthrough(input) {
10477
10548
  }
10478
10549
 
10479
10550
  // src/services/render/stages/audioStage.ts
10480
- import { existsSync as existsSync16 } from "node:fs";
10481
- import { join as join23 } from "node:path";
10551
+ import { existsSync as existsSync17 } from "node:fs";
10552
+ import { join as join24 } from "node:path";
10482
10553
  import {
10483
10554
  MIXED_AUDIO_FILENAME,
10484
10555
  audioFailureDiagnostics,
@@ -10488,8 +10559,8 @@ import {
10488
10559
  } from "@hyperframes/engine";
10489
10560
 
10490
10561
  // src/services/render/audioDeliveryLimit.ts
10491
- import { existsSync as existsSync15 } from "node:fs";
10492
- import { dirname as dirname10, join as join22 } from "node:path";
10562
+ import { existsSync as existsSync16 } from "node:fs";
10563
+ import { dirname as dirname10, join as join23 } from "node:path";
10493
10564
  import {
10494
10565
  applyAudioFxChain,
10495
10566
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -10499,7 +10570,7 @@ import {
10499
10570
 
10500
10571
  // src/services/render/audioPadTrim.ts
10501
10572
  import { spawn } from "node:child_process";
10502
- import { dirname as dirname9, join as join21 } from "node:path";
10573
+ import { dirname as dirname9, join as join22 } from "node:path";
10503
10574
  import {
10504
10575
  DEFAULT_CONFIG,
10505
10576
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -10779,7 +10850,7 @@ async function constrainAacTruePeak(input) {
10779
10850
  }
10780
10851
  async function cutSource(input, scratchDir, attenuationDb) {
10781
10852
  if (!input.sourcePath || !input.rewriteSource) return true;
10782
- const cutPath = join21(scratchDir, "source.wav");
10853
+ const cutPath = join22(scratchDir, "source.wav");
10783
10854
  try {
10784
10855
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
10785
10856
  if (!result.success) throw new Error(result.error);
@@ -10794,7 +10865,7 @@ async function enforceAacTruePeak(input) {
10794
10865
  let scratchDir;
10795
10866
  try {
10796
10867
  scratchDir = createStagingDir3(dirname9(input.audioPath), ".true-peak-");
10797
- const correctedPath = join21(scratchDir, "audio.m4a");
10868
+ const correctedPath = join22(scratchDir, "audio.m4a");
10798
10869
  const measurements = [];
10799
10870
  let attenuationDb = 0;
10800
10871
  let sourcePeakDbfs;
@@ -10997,14 +11068,14 @@ async function limitDeliveryPeaks(input, deps = {
10997
11068
  applyChain: applyAudioFxChain,
10998
11069
  encode: encodeAac2,
10999
11070
  rename: renameWithRetry6,
11000
- sourceExists: existsSync15
11071
+ sourceExists: existsSync16
11001
11072
  }) {
11002
11073
  const { audioPath, sourcePath, signal, timeoutMs } = input;
11003
11074
  if (!deps.sourceExists(sourcePath)) return { success: true };
11004
11075
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
11005
11076
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
11006
11077
  const alternating = ["a", "b"].map(
11007
- (k) => join22(dirname10(sourcePath), `audio-source-limited-${k}.wav`)
11078
+ (k) => join23(dirname10(sourcePath), `audio-source-limited-${k}.wav`)
11008
11079
  );
11009
11080
  let encodedFrom;
11010
11081
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -11076,7 +11147,7 @@ function runAudioStage(input) {
11076
11147
  }
11077
11148
  async function runAudioStageScoped(input) {
11078
11149
  const stageStart = Date.now();
11079
- const pcmSourcePath = join23(input.workDir, "audio-source.wav");
11150
+ const pcmSourcePath = join24(input.workDir, "audio-source.wav");
11080
11151
  const duration = input.totalFrames * input.fps.den / input.fps.num;
11081
11152
  let deliverySourcePath;
11082
11153
  try {
@@ -11092,7 +11163,7 @@ async function runAudioStageScoped(input) {
11092
11163
  );
11093
11164
  audioLoweredDb = guard.loweredDb;
11094
11165
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
11095
- if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
11166
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
11096
11167
  deliverySourcePath = pcmSourcePath;
11097
11168
  }
11098
11169
  }
@@ -11141,7 +11212,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11141
11212
  assertNotAborted,
11142
11213
  log
11143
11214
  } = input;
11144
- const audioOutputPath = join23(workDir, MIXED_AUDIO_FILENAME);
11215
+ const audioOutputPath = join24(workDir, MIXED_AUDIO_FILENAME);
11145
11216
  let hasAudio = false;
11146
11217
  let audioError;
11147
11218
  let audioFailures;
@@ -11152,7 +11223,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11152
11223
  audioResult = await processCompositionAudio(
11153
11224
  audios,
11154
11225
  projectDir,
11155
- join23(workDir, "audio-work"),
11226
+ join24(workDir, "audio-work"),
11156
11227
  audioOutputPath,
11157
11228
  duration,
11158
11229
  abortSignal,
@@ -11220,8 +11291,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11220
11291
  }
11221
11292
 
11222
11293
  // src/services/render/stages/captureStage.ts
11223
- import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11224
- import { join as join24 } from "node:path";
11294
+ import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11295
+ import { join as join25 } from "node:path";
11225
11296
  import {
11226
11297
  classifyCaptureFailure as classifyCaptureFailure2,
11227
11298
  frameFileExtension,
@@ -11291,16 +11362,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
11291
11362
  }
11292
11363
  function measureCaptureFrameBytes(workDir, framesDir) {
11293
11364
  let total = sampleDirectoryBytes(framesDir);
11294
- if (!existsSync17(workDir)) return total;
11365
+ if (!existsSync18(workDir)) return total;
11295
11366
  for (const attempt of readdirSync4(workDir)) {
11296
11367
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
11297
- total += sampleDirectoryBytes(join24(workDir, attempt));
11368
+ total += sampleDirectoryBytes(join25(workDir, attempt));
11298
11369
  continue;
11299
11370
  }
11300
11371
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
11301
- const attemptDir = join24(workDir, attempt);
11372
+ const attemptDir = join25(workDir, attempt);
11302
11373
  for (const name of readdirSync4(attemptDir)) {
11303
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join24(attemptDir, name));
11374
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join25(attemptDir, name));
11304
11375
  }
11305
11376
  }
11306
11377
  return total;
@@ -11598,8 +11669,8 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
11598
11669
  }
11599
11670
 
11600
11671
  // src/services/render/stages/captureHdrStage.ts
11601
- import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
11602
- import { join as join28 } from "node:path";
11672
+ import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
11673
+ import { join as join29 } from "node:path";
11603
11674
  import {
11604
11675
  closeCaptureSession as closeCaptureSession7,
11605
11676
  cloneCaptureWarnings as cloneCaptureWarnings2,
@@ -11671,7 +11742,7 @@ function createHdrImageTransferCache(options = {}) {
11671
11742
  }
11672
11743
 
11673
11744
  // src/services/render/stages/captureHdrSequentialLoop.ts
11674
- import { join as join25 } from "node:path";
11745
+ import { join as join26 } from "node:path";
11675
11746
  import {
11676
11747
  TRANSITIONS,
11677
11748
  crossfade
@@ -11796,7 +11867,7 @@ async function runSequentialLayeredFrameLoop(input) {
11796
11867
  );
11797
11868
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
11798
11869
  writeFileExclusiveSync(
11799
- join25(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
11870
+ join26(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
11800
11871
  normalCanvas
11801
11872
  );
11802
11873
  }
@@ -11828,7 +11899,7 @@ async function runSequentialLayeredFrameLoop(input) {
11828
11899
  }
11829
11900
 
11830
11901
  // src/services/render/stages/captureHdrHybridLoop.ts
11831
- import { join as join27 } from "node:path";
11902
+ import { join as join28 } from "node:path";
11832
11903
  import {
11833
11904
  TRANSITIONS as TRANSITIONS2,
11834
11905
  closeCaptureSession as closeCaptureSession6,
@@ -11842,9 +11913,9 @@ import {
11842
11913
  // src/services/shaderTransitionWorkerPool.ts
11843
11914
  import { Worker } from "node:worker_threads";
11844
11915
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
11845
- import { dirname as dirname11, join as join26 } from "node:path";
11916
+ import { dirname as dirname11, join as join27 } from "node:path";
11846
11917
  import { createRequire } from "node:module";
11847
- import { existsSync as existsSync18 } from "node:fs";
11918
+ import { existsSync as existsSync19 } from "node:fs";
11848
11919
  import { cpus as cpus2 } from "node:os";
11849
11920
  function resolveWorkerEntry(explicit) {
11850
11921
  if (explicit && explicit.length > 0) {
@@ -11856,9 +11927,9 @@ function resolveWorkerEntry(explicit) {
11856
11927
  return { path: override, isTs };
11857
11928
  }
11858
11929
  const moduleDir = dirname11(fileURLToPath3(import.meta.url));
11859
- const jsPath = join26(moduleDir, "shaderTransitionWorker.js");
11860
- if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
11861
- const tsPath = join26(moduleDir, "shaderTransitionWorker.ts");
11930
+ const jsPath = join27(moduleDir, "shaderTransitionWorker.js");
11931
+ if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
11932
+ const tsPath = join27(moduleDir, "shaderTransitionWorker.ts");
11862
11933
  return { path: tsPath, isTs: true };
11863
11934
  }
11864
11935
  function buildExecArgv(entryIsTs) {
@@ -12226,7 +12297,7 @@ async function runHybridLayeredFrameLoop(input) {
12226
12297
  );
12227
12298
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
12228
12299
  writeFileExclusiveSync(
12229
- join27(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12300
+ join28(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12230
12301
  canvas
12231
12302
  );
12232
12303
  }
@@ -12417,8 +12488,8 @@ async function runCaptureHdrStage(input) {
12417
12488
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
12418
12489
  }
12419
12490
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
12420
- const debugDumpDir = debugDumpEnabled ? join28(framesDir, "debug-composite") : null;
12421
- if (debugDumpDir && !existsSync19(debugDumpDir)) {
12491
+ const debugDumpDir = debugDumpEnabled ? join29(framesDir, "debug-composite") : null;
12492
+ if (debugDumpDir && !existsSync20(debugDumpDir)) {
12422
12493
  mkdirSync10(debugDumpDir, { recursive: true });
12423
12494
  }
12424
12495
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -12575,16 +12646,16 @@ async function runCaptureHdrStage(input) {
12575
12646
  // src/services/render/stages/encodeStage.ts
12576
12647
  import {
12577
12648
  copyFileSync as copyFileSync4,
12578
- existsSync as existsSync20,
12649
+ existsSync as existsSync21,
12579
12650
  mkdirSync as mkdirSync11,
12580
12651
  readdirSync as readdirSync5,
12581
- readFileSync as readFileSync8,
12652
+ readFileSync as readFileSync9,
12582
12653
  rmSync as rmSync11,
12583
12654
  statSync as statSync8,
12584
12655
  writeFileSync as writeFileSync6
12585
12656
  } from "node:fs";
12586
12657
  import { readFile as readFile2 } from "node:fs/promises";
12587
- import { dirname as dirname12, join as join29 } from "node:path";
12658
+ import { dirname as dirname12, join as join30 } from "node:path";
12588
12659
  import {
12589
12660
  encodeFramesChunkedConcat,
12590
12661
  encodeFramesFromDir,
@@ -12672,7 +12743,7 @@ async function reencodeWithClearedWholeFrames(argsInput, run, startTime) {
12672
12743
  const error = formatFfmpegError(result.exitCode, result.stderr);
12673
12744
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
12674
12745
  }
12675
- const gif = readFileSync8(outputPath);
12746
+ const gif = readFileSync9(outputPath);
12676
12747
  if (!clearGifFramesBeforeNext(gif)) {
12677
12748
  const error = "[FFmpeg] GIF output could not be parsed to clear its frames";
12678
12749
  return gifEncodeFailure(startTime, outputPath, error);
@@ -12705,11 +12776,11 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
12705
12776
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
12706
12777
  }
12707
12778
  }
12708
- if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync8(outputPath)) !== false) {
12779
+ if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync9(outputPath)) !== false) {
12709
12780
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
12710
12781
  if (failure) return failure;
12711
12782
  }
12712
- const fileSize = existsSync20(outputPath) ? statSync8(outputPath).size : 0;
12783
+ const fileSize = existsSync21(outputPath) ? statSync8(outputPath).size : 0;
12713
12784
  return {
12714
12785
  success: true,
12715
12786
  outputPath,
@@ -12795,7 +12866,7 @@ function encodeWhileCapturing(input, totalFrames) {
12795
12866
  await new Promise((resolve13) => wake = resolve13);
12796
12867
  }
12797
12868
  if (signal.aborted) return;
12798
- const mergedPath = join29(input.framesDir, formatCaptureFrameName(next, "jpg"));
12869
+ const mergedPath = join30(input.framesDir, formatCaptureFrameName(next, "jpg"));
12799
12870
  const frame = await readLandedFrame(landed.get(next), mergedPath);
12800
12871
  landed.delete(next);
12801
12872
  if (!await stream.writeFrame(frame)) {
@@ -12870,7 +12941,7 @@ async function runEncodeStage(input) {
12870
12941
  const stage5Start = Date.now();
12871
12942
  if (isPngSequence) {
12872
12943
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
12873
- if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
12944
+ if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
12874
12945
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
12875
12946
  if (captured.length === 0) {
12876
12947
  throw new Error(
@@ -12878,11 +12949,11 @@ async function runEncodeStage(input) {
12878
12949
  );
12879
12950
  }
12880
12951
  captured.forEach((name, i) => {
12881
- const dst = join29(outputPath, formatExportFrameName(i, "png"));
12882
- copyFileSync4(join29(framesDir, name), dst);
12952
+ const dst = join30(outputPath, formatExportFrameName(i, "png"));
12953
+ copyFileSync4(join30(framesDir, name), dst);
12883
12954
  });
12884
- if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
12885
- copyFileSync4(audioOutputPath, join29(outputPath, MIXED_AUDIO_FILENAME2));
12955
+ if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
12956
+ copyFileSync4(audioOutputPath, join30(outputPath, MIXED_AUDIO_FILENAME2));
12886
12957
  log.info(
12887
12958
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
12888
12959
  );
@@ -12902,7 +12973,7 @@ async function runEncodeStage(input) {
12902
12973
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
12903
12974
  fps: job.config.fps,
12904
12975
  loop,
12905
- palettePath: join29(dirname12(videoOnlyPath), "gif-palette.png"),
12976
+ palettePath: join30(dirname12(videoOnlyPath), "gif-palette.png"),
12906
12977
  preserveAlpha: needsAlpha,
12907
12978
  signal: abortSignal,
12908
12979
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -13113,7 +13184,7 @@ function sampleDirectoryBytes(dir) {
13113
13184
  continue;
13114
13185
  }
13115
13186
  for (const name of entries) {
13116
- const full = join30(current, name);
13187
+ const full = join31(current, name);
13117
13188
  try {
13118
13189
  const st = statSync9(full);
13119
13190
  if (st.isDirectory()) {
@@ -13269,8 +13340,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
13269
13340
  const ranges = [];
13270
13341
  let rangeStart = null;
13271
13342
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13272
- const framePath = join30(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13273
- const missing = !existsSync21(framePath) || statSync9(framePath).size <= 8;
13343
+ const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13344
+ const missing = !existsSync22(framePath) || statSync9(framePath).size <= 8;
13274
13345
  if (missing && rangeStart === null) {
13275
13346
  rangeStart = frameIndex;
13276
13347
  } else if (!missing && rangeStart !== null) {
@@ -13286,7 +13357,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
13286
13357
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
13287
13358
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
13288
13359
  const batches = [];
13289
- const outputDirFor = (batchIndex, workerId) => join30(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
13360
+ const outputDirFor = (batchIndex, workerId) => join31(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
13290
13361
  if (stride > 1) {
13291
13362
  const spans = /* @__PURE__ */ new Map();
13292
13363
  for (const range of ranges) {
@@ -13346,8 +13417,8 @@ function getNextRetryWorkerCount(currentWorkers) {
13346
13417
  return Math.max(1, Math.floor(currentWorkers / 2));
13347
13418
  }
13348
13419
  function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
13349
- if (platform2 === "win32" || platform2 === "darwin") return join30(systemTempDir, "hf-render-");
13350
- return join30(dirname13(outputPath), `work-${jobId}-`);
13420
+ if (platform2 === "win32" || platform2 === "darwin") return join31(systemTempDir, "hf-render-");
13421
+ return join31(dirname13(outputPath), `work-${jobId}-`);
13351
13422
  }
13352
13423
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
13353
13424
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -13360,13 +13431,20 @@ function resetCaptureAttemptProgress(job) {
13360
13431
  job.framesRendered = 0;
13361
13432
  }
13362
13433
  var FIRST_FRAME_STALL_MS = 3e5;
13434
+ var FIRST_FRAME_STARTUP_FACTOR = 2;
13435
+ var FIRST_FRAME_STALL_CEILING_MS = 9e5;
13363
13436
  var TAIL_STALL_MS = FIRST_FRAME_STALL_MS;
13364
- function frameStallRule(job, totalFrames) {
13437
+ function firstFrameWindowMs(probeStartupMs) {
13438
+ const fromStartup = (probeStartupMs ?? 0) * FIRST_FRAME_STARTUP_FACTOR;
13439
+ if (!Number.isFinite(fromStartup)) return FIRST_FRAME_STALL_MS;
13440
+ return Math.max(FIRST_FRAME_STALL_MS, Math.min(FIRST_FRAME_STALL_CEILING_MS, fromStartup));
13441
+ }
13442
+ function frameStallRule(job, totalFrames, probeStartupMs) {
13365
13443
  const noProgressMs = resolveCaptureStallTimeoutMs();
13366
13444
  return {
13367
13445
  progress: () => job.framesRendered ?? 0,
13368
13446
  noProgressMs,
13369
- firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
13447
+ firstProgressMs: Math.max(firstFrameWindowMs(probeStartupMs), noProgressMs),
13370
13448
  complete: () => (job.framesRendered ?? 0) >= totalFrames,
13371
13449
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
13372
13450
  detail: () => describeWorkerPhases(job),
@@ -13394,8 +13472,8 @@ The composition is too large for the available memory. To reduce memory pressure
13394
13472
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
13395
13473
  let captured = 0;
13396
13474
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13397
- const framePath = join30(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13398
- if (existsSync21(framePath)) captured++;
13475
+ const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13476
+ if (existsSync22(framePath)) captured++;
13399
13477
  }
13400
13478
  return captured;
13401
13479
  }
@@ -13420,7 +13498,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
13420
13498
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
13421
13499
  });
13422
13500
  pendingTransientRetry = false;
13423
- const attemptWorkDir = join30(options.workDir, `capture-attempt-${attempt}`);
13501
+ const attemptWorkDir = join31(options.workDir, `capture-attempt-${attempt}`);
13424
13502
  const batches = missingRanges ? buildMissingFrameRetryBatches(
13425
13503
  missingRanges,
13426
13504
  currentWorkers,
@@ -14053,18 +14131,19 @@ function deVerifyFallbackTelemetry(err) {
14053
14131
  }
14054
14132
  function resolveRenderDebugDir() {
14055
14133
  const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname13(fileURLToPath4(import.meta.url)), "../..");
14056
- return join30(producerRoot, ".debug");
14134
+ return join31(producerRoot, ".debug");
14057
14135
  }
14058
14136
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
14059
14137
  validateHlsRenderConfig(job.config);
14060
14138
  validateDeliveryEncoderConfig(job.config);
14139
+ validateChromaSubsamplingConfig(job.config);
14061
14140
  const debugDir = resolveRenderDebugDir();
14062
14141
  const outputDir = dirname13(outputPath);
14063
- if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
14064
- const workDir = job.config.debug ? join30(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14142
+ if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
14143
+ const workDir = job.config.debug ? join31(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14065
14144
  const pipelineStart = Date.now();
14066
14145
  const baseLog = job.config.logger ?? defaultLogger;
14067
- const logPath = job.config.debug ? join30(workDir, "render.log") : null;
14146
+ const logPath = job.config.debug ? join31(workDir, "render.log") : null;
14068
14147
  const execution = new RenderExecutionContext({
14069
14148
  request: { renderJobId: job.id, projectDir, outputPath },
14070
14149
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -14126,7 +14205,7 @@ async function executeRenderPipeline(input) {
14126
14205
  imageDecodeFailures: 0
14127
14206
  };
14128
14207
  let hdrPerf;
14129
- const perfOutputPath = join30(workDir, "perf-summary.json");
14208
+ const perfOutputPath = join31(workDir, "perf-summary.json");
14130
14209
  const cfg = { ...job.config.producerConfig ?? resolveConfig2() };
14131
14210
  const observability = new RenderObservabilityRecorder({
14132
14211
  pipelineStartMs: pipelineStart,
@@ -14202,7 +14281,7 @@ async function executeRenderPipeline(input) {
14202
14281
  job.startedAt = /* @__PURE__ */ new Date();
14203
14282
  assertNotAborted();
14204
14283
  assertConfiguredFfmpegBinariesExist();
14205
- if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
14284
+ if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
14206
14285
  if (job.config.debug) {
14207
14286
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
14208
14287
  }
@@ -14231,8 +14310,8 @@ async function executeRenderPipeline(input) {
14231
14310
  requestedWorkers: job.config.workers ?? "auto"
14232
14311
  });
14233
14312
  const entryFile = job.config.entryFile || "index.html";
14234
- const htmlPath = join30(projectDir, entryFile);
14235
- if (!existsSync21(htmlPath)) {
14313
+ const htmlPath = join31(projectDir, entryFile);
14314
+ if (!existsSync22(htmlPath)) {
14236
14315
  throw new Error(`Entry file not found: ${htmlPath}`);
14237
14316
  }
14238
14317
  assertNotAborted();
@@ -14408,7 +14487,7 @@ async function executeRenderPipeline(input) {
14408
14487
  canvas: { width, height },
14409
14488
  page: probeSession.page,
14410
14489
  projectDir,
14411
- compiledDir: join30(workDir, "compiled")
14490
+ compiledDir: join31(workDir, "compiled")
14412
14491
  });
14413
14492
  if (videoLayerPlan.videoId === void 0) {
14414
14493
  log.info(`[Render] Video layer passthrough off: ${videoLayerPlan.reason}`);
@@ -14426,7 +14505,7 @@ async function executeRenderPipeline(input) {
14426
14505
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
14427
14506
  code: "extract_video"
14428
14507
  });
14429
- const compiledDir = join30(workDir, "compiled");
14508
+ const compiledDir = join31(workDir, "compiled");
14430
14509
  const segmentsCapture = (layeredOrEffectRoute) => shouldSegmentCapture({
14431
14510
  env: process.env,
14432
14511
  durationSeconds: probeResult.duration,
@@ -14557,7 +14636,7 @@ async function executeRenderPipeline(input) {
14557
14636
  try {
14558
14637
  fileServer = await createFileServer({
14559
14638
  projectDir,
14560
- compiledDir: join30(workDir, "compiled"),
14639
+ compiledDir: join31(workDir, "compiled"),
14561
14640
  port: 0,
14562
14641
  preHeadScripts: [VIRTUAL_TIME_SHIM],
14563
14642
  fps: job.config.fps
@@ -14575,8 +14654,8 @@ async function executeRenderPipeline(input) {
14575
14654
  if (!activeFileServer) {
14576
14655
  throw new Error("File server failed to initialize before frame capture");
14577
14656
  }
14578
- const framesDir = join30(workDir, "captured-frames");
14579
- if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
14657
+ const framesDir = join31(workDir, "captured-frames");
14658
+ if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
14580
14659
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
14581
14660
  code: "start_browsers"
14582
14661
  });
@@ -14595,18 +14674,28 @@ async function executeRenderPipeline(input) {
14595
14674
  forceScreenshot: captureForceScreenshot
14596
14675
  });
14597
14676
  const videoCaptureBeyondViewport = resolveVideoCaptureBeyondViewport(composition.videos.length);
14598
- const captureImageFormat = resolveCaptureImageFormat({
14599
- needsAlpha,
14600
- motionBlur: job.config.motionBlur
14601
- });
14677
+ const captureSurface = resolveCaptureSurface(
14678
+ {
14679
+ needsAlpha,
14680
+ motionBlur: job.config.motionBlur,
14681
+ chromaSubsampling: job.config.chromaSubsampling
14682
+ },
14683
+ job.config.quality
14684
+ );
14685
+ if (job.config.chromaSubsampling === "444") {
14686
+ log.info("[Render] Capture: png (chromaSubsampling 444, lossless)");
14687
+ }
14602
14688
  const captureOptions = {
14603
14689
  width,
14604
14690
  height,
14605
14691
  fps: job.config.fps,
14606
- format: videoLayer ? "png" : captureImageFormat,
14607
- transparent: needsAlpha || videoLayer !== void 0,
14608
- ...videoLayer ? { hiddenElementIds: [videoLayer.videoId] } : {},
14609
- quality: captureImageFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
14692
+ ...captureSurface,
14693
+ ...videoLayer ? {
14694
+ format: "png",
14695
+ quality: void 0,
14696
+ transparent: true,
14697
+ hiddenElementIds: [videoLayer.videoId]
14698
+ } : {},
14610
14699
  variables: job.config.variables,
14611
14700
  deviceScaleFactor,
14612
14701
  motionBlur: job.config.motionBlur,
@@ -14713,6 +14802,7 @@ async function executeRenderPipeline(input) {
14713
14802
  );
14714
14803
  const nativeHdrIds = /* @__PURE__ */ new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
14715
14804
  const hasHdrContent = Boolean(effectiveHdr && nativeHdrIds.size > 0);
14805
+ assertChromaSubsamplingSdr(job.config, hasHdrContent);
14716
14806
  if (hasHdrContent) assertOutputScaleSupported(deviceScaleFactor, "hdr_layered");
14717
14807
  routePageMotionBlur = pageMotionBlurForRoute({ hasHdrContent, useLayeredComposite: false });
14718
14808
  const deSingleMinFrames = resolveDeSingleMinFrames(process.env);
@@ -15140,7 +15230,7 @@ async function executeRenderPipeline(input) {
15140
15230
  hls: ".mp4"
15141
15231
  };
15142
15232
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
15143
- const videoOnlyPath = join30(workDir, `video-only${videoExt}`);
15233
+ const videoOnlyPath = join31(workDir, `video-only${videoExt}`);
15144
15234
  const usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15145
15235
  if (usePageSideCompositingForTransitions) {
15146
15236
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -15295,7 +15385,9 @@ async function executeRenderPipeline(input) {
15295
15385
  usePageSideCompositing: capturePlan.usePageSideCompositing,
15296
15386
  hasHdrContent: capturePlan.hasHdrContent,
15297
15387
  hasShaderTransitions: compiled.hasShaderTransitions,
15298
- isPngSequence
15388
+ isPngSequence,
15389
+ captureImageFormat: captureOptions.format ?? "jpeg",
15390
+ chromaSubsampling: job.config.chromaSubsampling ?? "420"
15299
15391
  });
15300
15392
  const encoderHdr = hasHdrContent ? effectiveHdr : void 0;
15301
15393
  const presetFormat = outputFormat === "webm" || outputFormat === "mov" ? outputFormat : "mp4";
@@ -15303,7 +15395,8 @@ async function executeRenderPipeline(input) {
15303
15395
  job.config.quality,
15304
15396
  presetFormat,
15305
15397
  encoderHdr,
15306
- job.config.proresProfile
15398
+ job.config.proresProfile,
15399
+ job.config.chromaSubsampling
15307
15400
  );
15308
15401
  if (job.config.crf != null && job.config.videoBitrate) {
15309
15402
  log.warn(
@@ -15385,7 +15478,7 @@ async function executeRenderPipeline(input) {
15385
15478
  onProgress
15386
15479
  });
15387
15480
  },
15388
- { stall: frameStallRule(job, totalFrames) }
15481
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15389
15482
  );
15390
15483
  lastBrowserConsole = hdrRes.lastBrowserConsole;
15391
15484
  layeredCaptureWarnings.push(...hdrRes.warnings);
@@ -15426,7 +15519,7 @@ async function executeRenderPipeline(input) {
15426
15519
  pageMotionBlur: job.config.pageMotionBlur,
15427
15520
  captureQuality: captureOptions.quality
15428
15521
  });
15429
- const segmentDir = segmentDirFor(join30(projectDir, "renders"), segmentPlanHash);
15522
+ const segmentDir = segmentDirFor(join31(projectDir, "renders"), segmentPlanHash);
15430
15523
  let completedSegments = /* @__PURE__ */ new Set();
15431
15524
  if (job.config.resumeSegments === true) {
15432
15525
  const existing = readSegmentManifest(segmentDir);
@@ -15837,7 +15930,7 @@ async function executeRenderPipeline(input) {
15837
15930
  interleaveFrames: overlap !== null,
15838
15931
  openAttempt
15839
15932
  }),
15840
- { stall: frameStallRule(job, totalFrames) }
15933
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15841
15934
  );
15842
15935
  let captureRes;
15843
15936
  try {
@@ -15967,7 +16060,7 @@ async function executeRenderPipeline(input) {
15967
16060
  })
15968
16061
  );
15969
16062
  const totalElapsed = Date.now() - pipelineStart;
15970
- const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
16063
+ const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
15971
16064
  recordTransientRetryObservability();
15972
16065
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
15973
16066
  const observabilitySummary = observability.summary({
@@ -16048,8 +16141,8 @@ async function executeRenderPipeline(input) {
16048
16141
  }
16049
16142
  }
16050
16143
  if (job.config.debug) {
16051
- if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
16052
- const debugOutput = join30(workDir, `output${videoExt}`);
16144
+ if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
16145
+ const debugOutput = join31(workDir, `output${videoExt}`);
16053
16146
  copyFileSync5(stagedOutputPath, debugOutput);
16054
16147
  }
16055
16148
  }
@@ -16163,15 +16256,15 @@ import {
16163
16256
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD4,
16164
16257
  referenceBackgroundResult as referenceBackgroundResult6
16165
16258
  } from "@hyperframes/engine";
16166
- import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync14, rmSync as rmSync18 } from "node:fs";
16167
- import { join as join44 } from "node:path";
16259
+ import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync18 } from "node:fs";
16260
+ import { join as join45 } from "node:path";
16168
16261
  import { tmpdir as tmpdir4 } from "node:os";
16169
16262
 
16170
16263
  // src/services/distributed/mp4Stitch.ts
16171
16264
  import { createReadStream as createReadStream3, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
16172
16265
  import { open } from "node:fs/promises";
16173
16266
  import { renameWithRetry as renameWithRetry7 } from "@hyperframes/engine";
16174
- import { basename as basename7, dirname as dirname14, join as join31 } from "node:path";
16267
+ import { basename as basename7, dirname as dirname14, join as join32 } from "node:path";
16175
16268
  import { finished, pipeline } from "node:stream/promises";
16176
16269
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
16177
16270
  function boxAt(src, off, at, limit) {
@@ -16538,13 +16631,13 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
16538
16631
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
16539
16632
  mkdirSync13(dirname14(outputPath), { recursive: true });
16540
16633
  const workDir = createStagingDir4(dirname14(outputPath), `${basename7(outputPath)}.stitch-`);
16541
- const out = createWriteStream(join31(workDir, "out.mp4"));
16634
+ const out = createWriteStream(join32(workDir, "out.mp4"));
16542
16635
  try {
16543
16636
  out.write(header);
16544
16637
  for (const [i, path] of sourcePaths.entries()) await copyPayload(path, layouts[i], i, out);
16545
16638
  out.end();
16546
16639
  await finished(out);
16547
- renameWithRetry7(join31(workDir, "out.mp4"), outputPath);
16640
+ renameWithRetry7(join32(workDir, "out.mp4"), outputPath);
16548
16641
  } finally {
16549
16642
  out.destroy();
16550
16643
  rmSync13(workDir, { recursive: true, force: true });
@@ -16561,13 +16654,13 @@ import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframe
16561
16654
  import {
16562
16655
  copyFileSync as copyFileSync6,
16563
16656
  cpSync as cpSync2,
16564
- existsSync as existsSync26,
16657
+ existsSync as existsSync27,
16565
16658
  linkSync,
16566
16659
  mkdirSync as mkdirSync16,
16567
16660
  rmSync as rmSync14,
16568
16661
  writeFileSync as writeFileSync10
16569
16662
  } from "node:fs";
16570
- import { extname as extname6, isAbsolute as isAbsolute3, join as join39, relative as relative5, sep as sep3 } from "node:path";
16663
+ import { extname as extname6, isAbsolute as isAbsolute3, join as join40, relative as relative5, sep as sep3 } from "node:path";
16571
16664
  import {
16572
16665
  fpsToNumber as fpsToNumber9,
16573
16666
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -16583,7 +16676,7 @@ import {
16583
16676
  } from "@hyperframes/engine";
16584
16677
 
16585
16678
  // src/services/distributed/planFrameCost.ts
16586
- import { join as join34 } from "node:path";
16679
+ import { join as join35 } from "node:path";
16587
16680
  import {
16588
16681
  closeCaptureSession as closeCaptureSession9,
16589
16682
  createCaptureSession as createCaptureSession9,
@@ -16592,17 +16685,18 @@ import {
16592
16685
  } from "@hyperframes/engine";
16593
16686
 
16594
16687
  // src/services/distributed/chunkFrames.ts
16595
- import { existsSync as existsSync23, readdirSync as readdirSync7 } from "node:fs";
16596
- import { extname as extname4, join as join33 } from "node:path";
16688
+ import { existsSync as existsSync24, readdirSync as readdirSync7 } from "node:fs";
16689
+ import { extname as extname4, join as join34 } from "node:path";
16597
16690
  import {
16598
16691
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
16599
- createVideoFrameInjector as createVideoFrameInjector3
16692
+ createVideoFrameInjector as createVideoFrameInjector3,
16693
+ mediaIdPathSegment as mediaIdPathSegment3
16600
16694
  } from "@hyperframes/engine";
16601
16695
 
16602
16696
  // src/services/distributed/shared.ts
16603
16697
  import { execFile as execFileCallback } from "node:child_process";
16604
- import { dirname as dirname15, join as join32 } from "node:path";
16605
- import { existsSync as existsSync22, readFileSync as readFileSync9 } from "node:fs";
16698
+ import { dirname as dirname15, join as join33 } from "node:path";
16699
+ import { existsSync as existsSync23, readFileSync as readFileSync10 } from "node:fs";
16606
16700
  import { fileURLToPath as fileURLToPath5 } from "node:url";
16607
16701
  import { promisify as promisify2 } from "node:util";
16608
16702
  import {
@@ -16617,8 +16711,8 @@ function isPlanAudioArtifactPath(path) {
16617
16711
  }
16618
16712
  function resolvePlanAudioPath(planDir) {
16619
16713
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
16620
- const candidate = join32(planDir, name);
16621
- if (existsSync22(candidate)) return candidate;
16714
+ const candidate = join33(planDir, name);
16715
+ if (existsSync23(candidate)) return candidate;
16622
16716
  }
16623
16717
  return null;
16624
16718
  }
@@ -16878,10 +16972,10 @@ function readProducerVersion() {
16878
16972
  const startDir = dirname15(fileURLToPath5(import.meta.url));
16879
16973
  let current = startDir;
16880
16974
  for (let i = 0; i < 10; i++) {
16881
- const candidate = join32(current, "package.json");
16882
- if (existsSync22(candidate)) {
16975
+ const candidate = join33(current, "package.json");
16976
+ if (existsSync23(candidate)) {
16883
16977
  try {
16884
- const pkg = JSON.parse(readFileSync9(candidate, "utf-8"));
16978
+ const pkg = JSON.parse(readFileSync10(candidate, "utf-8"));
16885
16979
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
16886
16980
  cachedProducerVersion = pkg.version;
16887
16981
  return pkg.version;
@@ -16933,8 +17027,8 @@ function frameNumberFromFileName(name) {
16933
17027
  function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v1") {
16934
17028
  const result = [];
16935
17029
  for (const v of videos) {
16936
- const outputDir = join33(planDir, "video-frames", v.videoId);
16937
- if (!existsSync23(outputDir)) {
17030
+ const outputDir = join34(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
17031
+ if (!existsSync24(outputDir)) {
16938
17032
  throw new Error(
16939
17033
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
16940
17034
  );
@@ -16952,7 +17046,7 @@ function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v
16952
17046
  if (!frameName) continue;
16953
17047
  const frameNumber = indexMode === "sparse-v2" ? frameNumberFromFileName(frameName) : null;
16954
17048
  const frameIndex = frameNumber === null ? i : frameNumber - 1;
16955
- framePaths.set(frameIndex, join33(outputDir, frameName));
17049
+ framePaths.set(frameIndex, join34(outputDir, frameName));
16956
17050
  }
16957
17051
  result.push({
16958
17052
  videoId: v.videoId,
@@ -17032,8 +17126,8 @@ async function extractDeferredVideoFramesForChunk(input) {
17032
17126
  sourceOf: (video) => {
17033
17127
  const range = planned.get(video.videoId).deferredRange;
17034
17128
  const remoteUrl = remoteSources[range.sourcePath];
17035
- const sourcePath = remoteUrl ?? join33(input.planDir, ...range.sourcePath.split("/"));
17036
- if (remoteUrl === void 0 && !existsSync23(sourcePath)) {
17129
+ const sourcePath = remoteUrl ?? join34(input.planDir, ...range.sourcePath.split("/"));
17130
+ if (remoteUrl === void 0 && !existsSync24(sourcePath)) {
17037
17131
  throw new RenderChunkValidationError(
17038
17132
  MISSING_PLAN_ARTIFACT,
17039
17133
  `[renderChunk] planDir is missing the source for video ${JSON.stringify(video.videoId)}: ${range.sourcePath}`
@@ -17063,12 +17157,12 @@ async function measurePlanSecondsPerFrame(input) {
17063
17157
  planVideos,
17064
17158
  frames: sampled,
17065
17159
  fps: fpsRatio,
17066
- outputRoot: join34(workDir, "frame-cost-video-frames"),
17160
+ outputRoot: join35(workDir, "frame-cost-video-frames"),
17067
17161
  cfg: input.cfg
17068
17162
  })
17069
17163
  ];
17070
17164
  const lookup = extracted.length > 0 ? createFrameLookupTable4(planVideos.videos, extracted, resolveRenderFpsConfig(fpsRatio).value) : null;
17071
- const compiledDir = join34(planDir, "compiled");
17165
+ const compiledDir = join35(planDir, "compiled");
17072
17166
  const fileServer = await createFileServer({
17073
17167
  projectDir: compiledDir,
17074
17168
  compiledDir,
@@ -17080,7 +17174,7 @@ async function measurePlanSecondsPerFrame(input) {
17080
17174
  try {
17081
17175
  session = await createCaptureSession9(
17082
17176
  fileServer.url,
17083
- join34(workDir, "frame-cost"),
17177
+ join35(workDir, "frame-cost"),
17084
17178
  buildChunkCaptureOptions({
17085
17179
  dimensions: { ...input, fpsNum: fps, fpsDen: 1 },
17086
17180
  encoder: input,
@@ -17177,7 +17271,7 @@ function buildWeightedChunkSlices(weights, chunkCount, minFrames, maxFrames) {
17177
17271
  }
17178
17272
 
17179
17273
  // src/services/render/planReferenceBackground.ts
17180
- import { join as join35 } from "node:path";
17274
+ import { join as join36 } from "node:path";
17181
17275
  import {
17182
17276
  closeCaptureSession as closeCaptureSession10,
17183
17277
  createCaptureSession as createCaptureSession10,
@@ -17190,14 +17284,14 @@ async function readPlanReferenceBackground(input) {
17190
17284
  try {
17191
17285
  server = await createFileServer({
17192
17286
  projectDir: input.projectDir,
17193
- compiledDir: join35(input.workDir, "compiled"),
17287
+ compiledDir: join36(input.workDir, "compiled"),
17194
17288
  port: 0,
17195
17289
  preHeadScripts: [VIRTUAL_TIME_SHIM],
17196
17290
  fps: input.options.fps
17197
17291
  });
17198
17292
  session = await createCaptureSession10(
17199
17293
  server.url,
17200
- join35(input.workDir, "reference"),
17294
+ join36(input.workDir, "reference"),
17201
17295
  {
17202
17296
  ...input.options,
17203
17297
  requiresWebGpu: false
@@ -17233,8 +17327,8 @@ async function readPlanReferenceBackground(input) {
17233
17327
  }
17234
17328
 
17235
17329
  // src/services/render/stages/freezePlan.ts
17236
- import { existsSync as existsSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync10, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
17237
- import { join as join36, relative as relative3, resolve as resolve9 } from "node:path";
17330
+ import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
17331
+ import { join as join37, relative as relative3, resolve as resolve9 } from "node:path";
17238
17332
  import {
17239
17333
  REFERENCE_BACKGROUND_FIELD,
17240
17334
  referenceBackgroundResult as referenceBackgroundResult3
@@ -17427,7 +17521,7 @@ function planFileSha256(absolutePath, digests) {
17427
17521
  return sha256;
17428
17522
  }
17429
17523
  async function prehashPlanFiles(dir, digests) {
17430
- if (!existsSync24(dir)) return;
17524
+ if (!existsSync25(dir)) return;
17431
17525
  for (const { absolutePath } of listPlanFiles(dir)) {
17432
17526
  if (!digests.has(absolutePath)) digests.set(absolutePath, await sha256FileAsync(absolutePath));
17433
17527
  }
@@ -17452,7 +17546,7 @@ function listPlanFiles(planDir) {
17452
17546
  function walk(dir) {
17453
17547
  const entries = readdirSync8(dir, { withFileTypes: true });
17454
17548
  for (const entry of entries) {
17455
- const full = join36(dir, entry.name);
17549
+ const full = join37(dir, entry.name);
17456
17550
  if (entry.isDirectory()) {
17457
17551
  walk(full);
17458
17552
  } else if (entry.isFile()) {
@@ -17473,7 +17567,7 @@ function collectPlanAssetShas(planDir, digests) {
17473
17567
  const assets = [];
17474
17568
  for (const file of files) {
17475
17569
  if (file.planRelativePath === COMPILED_INDEX_RELATIVE_PATH) {
17476
- compositionHtml = readFileSync10(file.absolutePath);
17570
+ compositionHtml = readFileSync11(file.absolutePath);
17477
17571
  continue;
17478
17572
  }
17479
17573
  if (HASH_EXCLUDED_PLAN_FILES.has(file.planRelativePath)) continue;
@@ -17493,23 +17587,23 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
17493
17587
  function writePlanRemoteFiles(planDir, files) {
17494
17588
  if (files.length === 0) return;
17495
17589
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
17496
- writeFileSync8(join36(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
17590
+ writeFileSync8(join37(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
17497
17591
  }
17498
17592
  function readPlanRemoteFiles(planDir) {
17499
- const path = join36(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
17500
- return existsSync24(path) ? JSON.parse(readFileSync10(path, "utf-8")) : [];
17593
+ const path = join37(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
17594
+ return existsSync25(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
17501
17595
  }
17502
17596
  function recomputePlanHashFromPlanDir(planDir, digests) {
17503
- const planJsonPath = join36(planDir, "plan.json");
17504
- const encoderJsonPath = join36(planDir, "meta", "encoder.json");
17505
- if (!existsSync24(planJsonPath)) {
17597
+ const planJsonPath = join37(planDir, "plan.json");
17598
+ const encoderJsonPath = join37(planDir, "meta", "encoder.json");
17599
+ if (!existsSync25(planJsonPath)) {
17506
17600
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
17507
17601
  }
17508
- if (!existsSync24(encoderJsonPath)) {
17602
+ if (!existsSync25(encoderJsonPath)) {
17509
17603
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
17510
17604
  }
17511
- const planJson = JSON.parse(readFileSync10(planJsonPath, "utf-8"));
17512
- const encoderConfigCanonicalJson = readFileSync10(encoderJsonPath, "utf-8");
17605
+ const planJson = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
17606
+ const encoderConfigCanonicalJson = readFileSync11(encoderJsonPath, "utf-8");
17513
17607
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
17514
17608
  return computePlanHash({
17515
17609
  compositionHtml,
@@ -17535,21 +17629,21 @@ async function freezePlan(input) {
17535
17629
  hasAudio,
17536
17630
  digests
17537
17631
  } = input;
17538
- if (!existsSync24(planDir)) {
17632
+ if (!existsSync25(planDir)) {
17539
17633
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
17540
17634
  }
17541
- const metaDir = join36(planDir, "meta");
17542
- if (!existsSync24(metaDir)) mkdirSync14(metaDir, { recursive: true });
17635
+ const metaDir = join37(planDir, "meta");
17636
+ if (!existsSync25(metaDir)) mkdirSync14(metaDir, { recursive: true });
17543
17637
  writeFileSync8(
17544
- join36(metaDir, "composition.json"),
17638
+ join37(metaDir, "composition.json"),
17545
17639
  `${JSON.stringify(composition, null, 2)}
17546
17640
  `,
17547
17641
  "utf-8"
17548
17642
  );
17549
17643
  const encoderForCanonical = stripUndefined(encoder);
17550
17644
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
17551
- writeFileSync8(join36(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
17552
- writeFileSync8(join36(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
17645
+ writeFileSync8(join37(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
17646
+ writeFileSync8(join37(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
17553
17647
  `, "utf-8");
17554
17648
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
17555
17649
  const planHash = computePlanHash({
@@ -17574,7 +17668,7 @@ async function freezePlan(input) {
17574
17668
  duration: durationSeconds,
17575
17669
  hasAudio
17576
17670
  };
17577
- const planJsonPath = join36(planDir, "plan.json");
17671
+ const planJsonPath = join37(planDir, "plan.json");
17578
17672
  writeFileSync8(planJsonPath, `${JSON.stringify(planJson, null, 2)}
17579
17673
  `, "utf-8");
17580
17674
  return { planJsonPath, planHash };
@@ -17616,9 +17710,9 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
17616
17710
  }
17617
17711
 
17618
17712
  // src/services/distributed/chunkAudio.ts
17619
- import { closeSync as closeSync6, existsSync as existsSync25, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync11 } from "node:fs";
17713
+ import { closeSync as closeSync6, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
17620
17714
  import { writeFileSync as writeFileSync9, writeSync } from "node:fs";
17621
- import { join as join37 } from "node:path";
17715
+ import { join as join38 } from "node:path";
17622
17716
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
17623
17717
  function audioCutForChunk(grid, chunks, index, fps) {
17624
17718
  const firstPacketAt = (frame) => Math.min(
@@ -17704,9 +17798,9 @@ async function writeChunkAudioSlices(input) {
17704
17798
  offset += track.sizes[offsets.length - 1];
17705
17799
  }
17706
17800
  });
17707
- const bytes = readFileSync11(input.audioPath);
17801
+ const bytes = readFileSync12(input.audioPath);
17708
17802
  const layout = { sizeBytes: bytes.length, payloadStart, payloadEnd, partStarts: {} };
17709
- mkdirSync15(join37(input.planDir, SLICE_DIR), { recursive: true });
17803
+ mkdirSync15(join38(input.planDir, SLICE_DIR), { recursive: true });
17710
17804
  input.chunks.forEach((_, index) => {
17711
17805
  const cut = audioCutForChunk(grid, input.chunks, index, input.fps);
17712
17806
  if (!cut) return;
@@ -17714,17 +17808,17 @@ async function writeChunkAudioSlices(input) {
17714
17808
  const start = offsets[cut.firstPacket];
17715
17809
  layout.partStarts[index] = start;
17716
17810
  const end = offsets[last] + track.sizes[last];
17717
- writeFileSync9(join37(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
17811
+ writeFileSync9(join38(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
17718
17812
  });
17719
17813
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
17720
- writeFileSync9(join37(input.planDir, SLICE_FRAME), Buffer.concat(frame));
17721
- writeFileSync9(join37(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
17814
+ writeFileSync9(join38(input.planDir, SLICE_FRAME), Buffer.concat(frame));
17815
+ writeFileSync9(join38(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
17722
17816
  }
17723
17817
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
17724
- const layoutPath = join37(planDir, SLICE_LAYOUT);
17725
- if (!existsSync25(layoutPath)) return resolvePlanAudioPath(planDir);
17726
- const layout = JSON.parse(readFileSync11(layoutPath, "utf-8"));
17727
- const frame = readFileSync11(join37(planDir, SLICE_FRAME));
17818
+ const layoutPath = join38(planDir, SLICE_LAYOUT);
17819
+ if (!existsSync26(layoutPath)) return resolvePlanAudioPath(planDir);
17820
+ const layout = JSON.parse(readFileSync12(layoutPath, "utf-8"));
17821
+ const frame = readFileSync12(join38(planDir, SLICE_FRAME));
17728
17822
  const fd = openSync6(scratchPath, "w");
17729
17823
  try {
17730
17824
  writeSync(fd, frame, 0, layout.payloadStart, 0);
@@ -17737,7 +17831,7 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
17737
17831
  );
17738
17832
  const start = layout.partStarts[chunkIndex];
17739
17833
  if (start !== void 0) {
17740
- const part = readFileSync11(join37(planDir, chunkAudioSlicePath(chunkIndex)));
17834
+ const part = readFileSync12(join38(planDir, chunkAudioSlicePath(chunkIndex)));
17741
17835
  writeSync(fd, part, 0, part.length, start);
17742
17836
  }
17743
17837
  ftruncateSync(fd, layout.sizeBytes);
@@ -17793,7 +17887,7 @@ async function muxChunkWithAudio(input) {
17793
17887
  // src/services/distributed/planSize.ts
17794
17888
  import { createHash as createHash9 } from "node:crypto";
17795
17889
  import { lstatSync as lstatSync2, readdirSync as readdirSync9 } from "node:fs";
17796
- import { extname as extname5, join as join38, relative as relative4 } from "node:path";
17890
+ import { extname as extname5, join as join39, relative as relative4 } from "node:path";
17797
17891
  var MAX_TOP_COMPONENTS = 10;
17798
17892
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
17799
17893
  ".aac",
@@ -17905,7 +17999,7 @@ function walkRegularFiles(dir, visit) {
17905
17999
  return;
17906
18000
  }
17907
18001
  for (const entry of entries) {
17908
- const full = join38(dir, entry.name);
18002
+ const full = join39(dir, entry.name);
17909
18003
  if (entry.isDirectory()) {
17910
18004
  walkRegularFiles(full, visit);
17911
18005
  } else if (entry.isFile()) {
@@ -18121,13 +18215,13 @@ function assertPositiveInteger2(name, value) {
18121
18215
  }
18122
18216
  var FREEZE_OWNED_PLAN_FILES = [
18123
18217
  "plan.json",
18124
- join39("meta", "composition.json"),
18125
- join39("meta", "encoder.json"),
18126
- join39("meta", "chunks.json")
18218
+ join40("meta", "composition.json"),
18219
+ join40("meta", "encoder.json"),
18220
+ join40("meta", "chunks.json")
18127
18221
  ];
18128
18222
  function removeFreezeOwnedPlanFiles(planDir) {
18129
18223
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
18130
- rmSync14(join39(planDir, relativePath), { force: true });
18224
+ rmSync14(join40(planDir, relativePath), { force: true });
18131
18225
  }
18132
18226
  }
18133
18227
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -18282,19 +18376,19 @@ function createVideoSourceShipper(input) {
18282
18376
  const known = shipped.get(srcPath);
18283
18377
  if (known) return known;
18284
18378
  const stagedRel = pathInside(input.workVideoFramesDir, srcPath);
18285
- const current = stagedRel === null ? srcPath : join39(input.planDir, "video-frames", stagedRel);
18379
+ const current = stagedRel === null ? srcPath : join40(input.planDir, "video-frames", stagedRel);
18286
18380
  let result = null;
18287
18381
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
18288
18382
  const rel = pathInside(root, srcPath);
18289
- if (rel !== null && (existsSync26(join39(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
18383
+ if (rel !== null && (existsSync27(join40(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
18290
18384
  result = ["compiled", ...rel.split(sep3)].join("/");
18291
18385
  break;
18292
18386
  }
18293
18387
  }
18294
18388
  if (result === null) {
18295
18389
  result = `video-sources/${shipped.size}${extname6(current)}`;
18296
- const destination = join39(input.planDir, ...result.split("/"));
18297
- mkdirSync16(join39(input.planDir, "video-sources"), { recursive: true });
18390
+ const destination = join40(input.planDir, ...result.split("/"));
18391
+ mkdirSync16(join40(input.planDir, "video-sources"), { recursive: true });
18298
18392
  try {
18299
18393
  linkSync(current, destination);
18300
18394
  } catch {
@@ -18314,7 +18408,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
18314
18408
  useGpu: false,
18315
18409
  browserGpuMode: "software"
18316
18410
  });
18317
- if (!existsSync26(planDir)) mkdirSync16(planDir, { recursive: true });
18411
+ if (!existsSync27(planDir)) mkdirSync16(planDir, { recursive: true });
18318
18412
  const log = config.logger ?? defaultLogger;
18319
18413
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
18320
18414
  const abortSignal = config.abortSignal;
@@ -18344,14 +18438,14 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
18344
18438
  pageMotionBlur: config.pageMotionBlur
18345
18439
  });
18346
18440
  const entryFile = config.entryFile ?? "index.html";
18347
- const htmlPath = join39(projectDir, entryFile);
18348
- if (!existsSync26(htmlPath)) {
18441
+ const htmlPath = join40(projectDir, entryFile);
18442
+ if (!existsSync27(htmlPath)) {
18349
18443
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
18350
18444
  }
18351
- const workDir = join39(planDir, ".plan-work");
18445
+ const workDir = join40(planDir, ".plan-work");
18352
18446
  rmSync14(workDir, { recursive: true, force: true });
18353
18447
  mkdirSync16(workDir, { recursive: true });
18354
- const compiledDir = join39(workDir, "compiled");
18448
+ const compiledDir = join40(workDir, "compiled");
18355
18449
  mkdirSync16(compiledDir, { recursive: true });
18356
18450
  let stageStarted = Date.now();
18357
18451
  cpSync2(projectDir, compiledDir, {
@@ -18365,10 +18459,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
18365
18459
  }
18366
18460
  });
18367
18461
  logPlanStage(log, "copy", stageStarted);
18368
- const finalCompiledDir = join39(planDir, "compiled");
18462
+ const finalCompiledDir = join40(planDir, "compiled");
18369
18463
  const needsAlpha = outputNeedsAlpha(config.format);
18370
18464
  const remoteFiles = Object.entries(options.remoteFiles ?? {});
18371
- const remoteLocalPath = (rel) => join39(projectDir, ...rel.split("/"));
18465
+ const remoteLocalPath = (rel) => join40(projectDir, ...rel.split("/"));
18372
18466
  for (const [, file] of remoteFiles) {
18373
18467
  declareContentAddressedUrl(file.url, file.sha256);
18374
18468
  if (file.probeFactsUrl) declareProbeFactsUrl(file.url, file.probeFactsUrl);
@@ -18571,17 +18665,17 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18571
18665
  let stageStarted = Date.now();
18572
18666
  const extractResult = await extractPlanVideos(c, options.deferVideoExtraction);
18573
18667
  logPlanStage(log, "extract", stageStarted);
18574
- const stagedVideoFrames = join39(compiledDir, "__hyperframes_video_frames");
18575
- const videoFramesDst = join39(planDir, "video-frames");
18576
- if (existsSync26(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
18577
- const videoSourcesDir = join39(planDir, "video-sources");
18668
+ const stagedVideoFrames = join40(compiledDir, "__hyperframes_video_frames");
18669
+ const videoFramesDst = join40(planDir, "video-frames");
18670
+ if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
18671
+ const videoSourcesDir = join40(planDir, "video-sources");
18578
18672
  rmSync14(videoSourcesDir, { recursive: true, force: true });
18579
- if (existsSync26(stagedVideoFrames)) {
18673
+ if (existsSync27(stagedVideoFrames)) {
18580
18674
  renameWithRetry8(stagedVideoFrames, videoFramesDst);
18581
18675
  } else {
18582
18676
  mkdirSync16(videoFramesDst, { recursive: true });
18583
18677
  }
18584
- if (existsSync26(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
18678
+ if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
18585
18679
  renameWithRetry8(compiledDir, finalCompiledDir);
18586
18680
  const shipVideoSource = createVideoSourceShipper({
18587
18681
  planDir,
@@ -18611,7 +18705,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18611
18705
  };
18612
18706
  })
18613
18707
  });
18614
- mkdirSync16(join39(planDir, "meta"), { recursive: true });
18708
+ mkdirSync16(join40(planDir, "meta"), { recursive: true });
18615
18709
  writePlanRemoteFiles(
18616
18710
  planDir,
18617
18711
  remoteFiles.map(([rel, { sha256, sizeBytes }]) => ({
@@ -18621,7 +18715,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18621
18715
  }))
18622
18716
  );
18623
18717
  writeFileSync10(
18624
- join39(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
18718
+ join40(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
18625
18719
  JSON.stringify(planVideosJson, null, 2),
18626
18720
  "utf-8"
18627
18721
  );
@@ -18701,11 +18795,11 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18701
18795
  if (audioResult?.audioError) {
18702
18796
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
18703
18797
  }
18704
- const planAudioPath = join39(planDir, PLAN_AUDIO_RELATIVE_PATH);
18705
- if (audioResult?.hasAudio && existsSync26(audioResult.audioOutputPath)) {
18798
+ const planAudioPath = join40(planDir, PLAN_AUDIO_RELATIVE_PATH);
18799
+ if (audioResult?.hasAudio && existsSync27(audioResult.audioOutputPath)) {
18706
18800
  renameWithRetry8(audioResult.audioOutputPath, planAudioPath);
18707
18801
  }
18708
- if (chunksCarryAudio && existsSync26(planAudioPath)) {
18802
+ if (chunksCarryAudio && existsSync27(planAudioPath)) {
18709
18803
  if (options.sliceChunkAudio) {
18710
18804
  stageStarted = Date.now();
18711
18805
  await writeChunkAudioSlices({
@@ -18823,9 +18917,9 @@ async function plan(projectDir, config, planDir, options = {}) {
18823
18917
 
18824
18918
  // src/services/distributed/renderChunk.ts
18825
18919
  import { randomBytes } from "node:crypto";
18826
- import { existsSync as existsSync29, mkdirSync as mkdirSync19, readFileSync as readFileSync13, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
18920
+ import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
18827
18921
  import { cpus as cpus3 } from "node:os";
18828
- import { join as join43 } from "node:path";
18922
+ import { join as join44 } from "node:path";
18829
18923
  import {
18830
18924
  assertSwiftShader,
18831
18925
  BROWSER_GPU_NOT_SOFTWARE as BROWSER_GPU_NOT_SOFTWARE4,
@@ -18850,24 +18944,28 @@ import {
18850
18944
  } from "@hyperframes/engine";
18851
18945
  import {
18852
18946
  copyFileSync as copyFileSync8,
18853
- existsSync as existsSync28,
18947
+ existsSync as existsSync29,
18854
18948
  lstatSync as lstatSync3,
18855
18949
  mkdirSync as mkdirSync18,
18856
- readFileSync as readFileSync12,
18950
+ readFileSync as readFileSync13,
18857
18951
  readdirSync as readdirSync10,
18858
18952
  rmSync as rmSync16,
18859
18953
  statSync as statSync11,
18860
18954
  writeFileSync as writeFileSync12
18861
18955
  } from "node:fs";
18862
18956
  import { tmpdir as tmpdir3 } from "node:os";
18863
- import { dirname as dirname17, isAbsolute as isAbsolute4, join as join42, relative as relative6, resolve as resolve10, sep as sep4 } from "node:path";
18957
+ import { dirname as dirname17, isAbsolute as isAbsolute4, join as join43, relative as relative6, resolve as resolve10, sep as sep4 } from "node:path";
18864
18958
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
18865
- import { createFrameLookupTable as createFrameLookupTable5, renameWithRetry as renameWithRetry10 } from "@hyperframes/engine";
18959
+ import {
18960
+ createFrameLookupTable as createFrameLookupTable5,
18961
+ mediaIdPathSegment as mediaIdPathSegment4,
18962
+ renameWithRetry as renameWithRetry10
18963
+ } from "@hyperframes/engine";
18866
18964
 
18867
18965
  // src/services/distributed/planV2Publisher.ts
18868
18966
  import {
18869
18967
  copyFileSync as copyFileSync7,
18870
- existsSync as existsSync27,
18968
+ existsSync as existsSync28,
18871
18969
  linkSync as linkSync2,
18872
18970
  mkdirSync as mkdirSync17,
18873
18971
  rmSync as rmSync15,
@@ -18875,7 +18973,7 @@ import {
18875
18973
  writeFileSync as writeFileSync11
18876
18974
  } from "node:fs";
18877
18975
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
18878
- import { dirname as dirname16, join as join41 } from "node:path";
18976
+ import { dirname as dirname16, join as join42 } from "node:path";
18879
18977
 
18880
18978
  // src/services/distributed/planV2Errors.ts
18881
18979
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -18890,7 +18988,7 @@ var PlanV2IntegrityError = class extends Error {
18890
18988
  };
18891
18989
 
18892
18990
  // src/services/distributed/planV2Layout.ts
18893
- import { join as join40 } from "node:path";
18991
+ import { join as join41 } from "node:path";
18894
18992
  var SHA256_PATTERN = /^[0-9a-f]{64}$/;
18895
18993
  function assertPlanV2Sha256(value, field) {
18896
18994
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
@@ -18900,7 +18998,7 @@ function assertPlanV2Sha256(value, field) {
18900
18998
  }
18901
18999
  function planV2BlobPath(root, sha256) {
18902
19000
  const digest = assertPlanV2Sha256(sha256, "artifact sha256");
18903
- return join40(root, "artifacts", "sha256", digest.slice(0, 2), digest);
19001
+ return join41(root, "artifacts", "sha256", digest.slice(0, 2), digest);
18904
19002
  }
18905
19003
 
18906
19004
  // src/services/distributed/planV2Publisher.ts
@@ -18936,7 +19034,7 @@ var LocalPlanV2ArtifactPublisher = class {
18936
19034
  #linkFile;
18937
19035
  #committed = false;
18938
19036
  constructor(destinationDir, options = {}) {
18939
- if (existsSync27(destinationDir)) {
19037
+ if (existsSync28(destinationDir)) {
18940
19038
  throw new PlanV2IntegrityError(`output directory already exists: ${destinationDir}`);
18941
19039
  }
18942
19040
  this.destinationDir = destinationDir;
@@ -18953,10 +19051,10 @@ var LocalPlanV2ArtifactPublisher = class {
18953
19051
  );
18954
19052
  }
18955
19053
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
18956
- if (existsSync27(destinationPath)) return;
19054
+ if (existsSync28(destinationPath)) return;
18957
19055
  mkdirSync17(dirname16(destinationPath), { recursive: true });
18958
19056
  const stagingDir = createStagingDir5(dirname16(destinationPath), ".plan-v2-blob-");
18959
- const temporaryPath = join41(stagingDir, "blob");
19057
+ const temporaryPath = join42(stagingDir, "blob");
18960
19058
  try {
18961
19059
  try {
18962
19060
  this.#linkFile(blob.sourcePath, temporaryPath);
@@ -18971,13 +19069,13 @@ var LocalPlanV2ArtifactPublisher = class {
18971
19069
  }
18972
19070
  async commitManifest(manifestBytes) {
18973
19071
  for (const digest of new Set(manifestDigests(manifestBytes))) {
18974
- if (!existsSync27(planV2BlobPath(this.temporaryDir, digest))) {
19072
+ if (!existsSync28(planV2BlobPath(this.temporaryDir, digest))) {
18975
19073
  throw new PlanV2IntegrityError(
18976
19074
  `cannot commit manifest before referenced blob is durable: ${digest}`
18977
19075
  );
18978
19076
  }
18979
19077
  }
18980
- writeFileSync11(join41(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
19078
+ writeFileSync11(join42(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
18981
19079
  renameWithRetry9(this.temporaryDir, this.destinationDir);
18982
19080
  this.#committed = true;
18983
19081
  }
@@ -19003,7 +19101,7 @@ function isNonNegativeIntegerArray(value) {
19003
19101
  return Array.isArray(value) && value.every((item) => typeof item === "number" && Number.isInteger(item) && item >= 0);
19004
19102
  }
19005
19103
  function readJsonFile(path, label) {
19006
- const contents = readFileSync12(path, "utf-8");
19104
+ const contents = readFileSync13(path, "utf-8");
19007
19105
  try {
19008
19106
  const parsed = JSON.parse(contents);
19009
19107
  return parsed;
@@ -19023,7 +19121,7 @@ function listFiles(root) {
19023
19121
  const rootResolved = resolve10(root);
19024
19122
  function walk(dir) {
19025
19123
  for (const entry of readdirSync10(dir, { withFileTypes: true })) {
19026
- const absolutePath = join42(dir, entry.name);
19124
+ const absolutePath = join43(dir, entry.name);
19027
19125
  if (entry.isDirectory()) {
19028
19126
  walk(absolutePath);
19029
19127
  } else if (entry.isFile()) {
@@ -19050,13 +19148,13 @@ function assertValidExtractionCacheCompleteSentinel(path) {
19050
19148
  }
19051
19149
  }
19052
19150
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
19053
- const videoRoot = join42(executionPlanDir, "video-frames");
19054
- if (!existsSync28(videoRoot)) return;
19151
+ const videoRoot = join43(executionPlanDir, "video-frames");
19152
+ if (!existsSync29(videoRoot)) return;
19055
19153
  for (const videoEntry of readdirSync10(videoRoot, { withFileTypes: true })) {
19056
19154
  if (!videoEntry.isDirectory()) continue;
19057
- const videoDir = join42(videoRoot, videoEntry.name);
19155
+ const videoDir = join43(videoRoot, videoEntry.name);
19058
19156
  if (readdirSync10(videoDir).includes(EXTRACTION_CACHE_COMPLETE_SENTINEL)) {
19059
- const sentinelPath = join42(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
19157
+ const sentinelPath = join43(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
19060
19158
  assertValidExtractionCacheCompleteSentinel(sentinelPath);
19061
19159
  }
19062
19160
  }
@@ -19067,7 +19165,7 @@ function isExtractionCacheCompleteSentinelPath(path) {
19067
19165
  }
19068
19166
  function resolveExtractedVideoOutputDir(planDir, videoId) {
19069
19167
  const videoRoot = resolve10(planDir, "video-frames");
19070
- const outputDir = resolve10(videoRoot, videoId);
19168
+ const outputDir = resolve10(videoRoot, mediaIdPathSegment4(videoId));
19071
19169
  if (outputDir === videoRoot || !outputDir.startsWith(`${videoRoot}${sep4}`)) {
19072
19170
  throw new PlanV2IntegrityError(`unsafe extracted video id: ${JSON.stringify(videoId)}`);
19073
19171
  }
@@ -19103,7 +19201,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
19103
19201
  if (video.deferredRange) {
19104
19202
  const framePaths2 = /* @__PURE__ */ new Map();
19105
19203
  for (let index = 0; index < video.totalFrames; index++) {
19106
- framePaths2.set(index, join42(outputDir, String(index)));
19204
+ framePaths2.set(index, join43(outputDir, String(index)));
19107
19205
  }
19108
19206
  return { ...video, outputDir, framePaths: framePaths2, ownedByLookup: false };
19109
19207
  }
@@ -19111,7 +19209,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
19111
19209
  const framePaths = /* @__PURE__ */ new Map();
19112
19210
  for (const frameName of frameNames) {
19113
19211
  if (frameName === EXTRACTION_CACHE_COMPLETE_SENTINEL) {
19114
- assertValidExtractionCacheCompleteSentinel(join42(outputDir, frameName));
19212
+ assertValidExtractionCacheCompleteSentinel(join43(outputDir, frameName));
19115
19213
  continue;
19116
19214
  }
19117
19215
  const match = /(\d+)(?=\.[^.]+$)/.exec(frameName);
@@ -19130,7 +19228,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
19130
19228
  `duplicate extracted frame index ${frameIndex} in ${outputDir}`
19131
19229
  );
19132
19230
  }
19133
- framePaths.set(frameIndex, join42(outputDir, frameName));
19231
+ framePaths.set(frameIndex, join43(outputDir, frameName));
19134
19232
  }
19135
19233
  return {
19136
19234
  ...video,
@@ -19151,8 +19249,8 @@ function parsePlanVideosJson2(value) {
19151
19249
  }
19152
19250
  }
19153
19251
  function materializeExtractedVideoDirectories(planDir) {
19154
- const videosPath = join42(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19155
- if (!existsSync28(videosPath)) return;
19252
+ const videosPath = join43(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19253
+ if (!existsSync29(videosPath)) return;
19156
19254
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
19157
19255
  for (const video of videos.extracted) {
19158
19256
  mkdirSync18(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
@@ -19185,13 +19283,13 @@ function parseChunkSlices(value) {
19185
19283
  });
19186
19284
  }
19187
19285
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
19188
- const videoRoot = join42(executionPlanDir, "video-frames");
19189
- const hasExtractedFrames = existsSync28(videoRoot) && listFiles(videoRoot).length > 0;
19190
- const videosPath = join42(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19191
- if (!existsSync28(videosPath)) {
19286
+ const videoRoot = join43(executionPlanDir, "video-frames");
19287
+ const hasExtractedFrames = existsSync29(videoRoot) && listFiles(videoRoot).length > 0;
19288
+ const videosPath = join43(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19289
+ if (!existsSync29(videosPath)) {
19192
19290
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
19193
19291
  }
19194
- const chunksPath = join42(executionPlanDir, "meta", "chunks.json");
19292
+ const chunksPath = join43(executionPlanDir, "meta", "chunks.json");
19195
19293
  const videos = readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH);
19196
19294
  const chunks = readJsonFile(chunksPath, "meta/chunks.json");
19197
19295
  const parsedVideos = parsePlanVideosJson2(videos);
@@ -19245,10 +19343,10 @@ function computeManifestHash(manifest) {
19245
19343
  return sha256Hex(`${PLAN_V2_HASH_PREFIX}${canonicalJsonStringify(manifestPayload(manifest))}`);
19246
19344
  }
19247
19345
  function writeBlob(sourcePath, destinationPath) {
19248
- if (existsSync28(destinationPath)) return;
19346
+ if (existsSync29(destinationPath)) return;
19249
19347
  mkdirSync18(dirname17(destinationPath), { recursive: true });
19250
19348
  const temporaryDir = createStagingDir6(dirname17(destinationPath), ".plan-v2-blob-");
19251
- const temporaryPath = join42(temporaryDir, "blob");
19349
+ const temporaryPath = join43(temporaryDir, "blob");
19252
19350
  try {
19253
19351
  copyFileSync8(sourcePath, temporaryPath);
19254
19352
  renameWithRetry10(temporaryPath, destinationPath);
@@ -19284,8 +19382,8 @@ async function putTasks(tasks) {
19284
19382
  if (failure) throw failure.reason;
19285
19383
  }
19286
19384
  function buildPlanV2Publication(executionPlanDir, digests) {
19287
- const executionPlanPath = join42(executionPlanDir, "plan.json");
19288
- if (!existsSync28(executionPlanPath)) {
19385
+ const executionPlanPath = join43(executionPlanDir, "plan.json");
19386
+ if (!existsSync29(executionPlanPath)) {
19289
19387
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
19290
19388
  }
19291
19389
  const executionPlanValue = readJsonFile(executionPlanPath, "execution plan.json");
@@ -19312,7 +19410,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
19312
19410
  }
19313
19411
  validateExtractionCacheCompleteSentinels(executionPlanDir);
19314
19412
  const videoDependencyPlan = buildVideoChunkDependencies(executionPlanDir, dimensions);
19315
- const encoder = readJsonFile(join42(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
19413
+ const encoder = readJsonFile(join43(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
19316
19414
  const files = listFiles(executionPlanDir);
19317
19415
  const chunkAudio = !isRecord3(encoder) || encoder.chunksCarryAudio !== true ? "none" : files.some((file) => chunkAudioSliceTarget(file.path) !== null) ? "sliced" : "whole";
19318
19416
  for (const file of files) {
@@ -19365,7 +19463,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
19365
19463
  };
19366
19464
  }
19367
19465
  function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
19368
- if (existsSync28(planV2Dir)) {
19466
+ if (existsSync29(planV2Dir)) {
19369
19467
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
19370
19468
  }
19371
19469
  const publication = buildPlanV2Publication(executionPlanDir);
@@ -19379,7 +19477,7 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
19379
19477
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
19380
19478
  }
19381
19479
  writeFileSync12(
19382
- join42(tempDir, "plan.json"),
19480
+ join43(tempDir, "plan.json"),
19383
19481
  canonicalJsonStringify(publication.manifest),
19384
19482
  "utf-8"
19385
19483
  );
@@ -19431,7 +19529,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
19431
19529
  // artifactTargets ships every compiled/ file to all chunks, so each is in the manifest.
19432
19530
  whileAudioMixes: () => putBlobs(
19433
19531
  publisher,
19434
- listFiles(join42(stagingRoot, "compiled")).map(
19532
+ listFiles(join43(stagingRoot, "compiled")).map(
19435
19533
  (file) => publishBlobFor(file.absolutePath, digests)
19436
19534
  )
19437
19535
  ),
@@ -19451,7 +19549,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
19451
19549
  }
19452
19550
  }
19453
19551
  async function planV2(projectDir, config, planV2Dir) {
19454
- if (existsSync28(planV2Dir)) {
19552
+ if (existsSync29(planV2Dir)) {
19455
19553
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
19456
19554
  }
19457
19555
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
@@ -19468,7 +19566,7 @@ function resultFromManifest(planV2Dir, manifest) {
19468
19566
  isRecord3(executionPlan) ? executionPlan[REFERENCE_BACKGROUND_FIELD3] : void 0
19469
19567
  ),
19470
19568
  planDir: planV2Dir,
19471
- manifestPath: join42(planV2Dir, "plan.json"),
19569
+ manifestPath: join43(planV2Dir, "plan.json"),
19472
19570
  planProtocol: PLAN_PROTOCOL_V2,
19473
19571
  planHash: manifest.planHash,
19474
19572
  sourcePlanV1Hash: getPlanV2ExecutionPlanHash(manifest),
@@ -19604,8 +19702,8 @@ function parsePlanV2Manifest(value) {
19604
19702
  return parsed;
19605
19703
  }
19606
19704
  function readPlanV2Manifest(planV2Dir) {
19607
- const manifestPath = join42(planV2Dir, "plan.json");
19608
- if (!existsSync28(manifestPath)) {
19705
+ const manifestPath = join43(planV2Dir, "plan.json");
19706
+ if (!existsSync29(manifestPath)) {
19609
19707
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
19610
19708
  }
19611
19709
  const value = readJsonFile(manifestPath, "v2 manifest");
@@ -19624,7 +19722,7 @@ function listPlanV2ArtifactsForTarget(manifest, target) {
19624
19722
  }
19625
19723
  function verifyBlob(planV2Dir, artifact) {
19626
19724
  const sourcePath = planV2BlobPath(planV2Dir, artifact.sha256);
19627
- if (!existsSync28(sourcePath)) {
19725
+ if (!existsSync29(sourcePath)) {
19628
19726
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
19629
19727
  }
19630
19728
  const stats = statSync11(sourcePath);
@@ -19637,7 +19735,7 @@ function verifyBlob(planV2Dir, artifact) {
19637
19735
  return sourcePath;
19638
19736
  }
19639
19737
  function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}) {
19640
- if (existsSync28(destinationDir)) {
19738
+ if (existsSync29(destinationDir)) {
19641
19739
  throw new PlanV2IntegrityError(`materialization destination already exists: ${destinationDir}`);
19642
19740
  }
19643
19741
  const manifest = readPlanV2Manifest(planV2Dir);
@@ -19653,13 +19751,13 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
19653
19751
  const tempDir = createStagingDir6(dirname17(destinationDir), ".plan-v2-materialize-");
19654
19752
  try {
19655
19753
  for (const { artifact, sourcePath } of verified) {
19656
- const destinationPath = join42(tempDir, ...artifact.path.split("/"));
19754
+ const destinationPath = join43(tempDir, ...artifact.path.split("/"));
19657
19755
  mkdirSync18(dirname17(destinationPath), { recursive: true });
19658
19756
  copyFileSync8(sourcePath, destinationPath);
19659
19757
  }
19660
19758
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
19661
19759
  writeFileSync12(
19662
- join42(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
19760
+ join43(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
19663
19761
  canonicalJsonStringify({
19664
19762
  manifest,
19665
19763
  target,
@@ -19682,7 +19780,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
19682
19780
  // Join the artifact's OWN name, not the current constant: a plan written
19683
19781
  // before the container change carries the legacy name, and materializing it
19684
19782
  // under the new one would point at a file that was never written.
19685
- audioPath: target.role === "assembler" ? audioArtifact ? join42(destinationDir, audioArtifact.path) : null : null
19783
+ audioPath: target.role === "assembler" ? audioArtifact ? join43(destinationDir, audioArtifact.path) : null : null
19686
19784
  };
19687
19785
  }
19688
19786
  function assertRemoteSources(remoteSources, artifacts) {
@@ -19701,8 +19799,8 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
19701
19799
  return readValidatedPlanV2Materialization(planDir, expectedTarget)?.manifest ?? null;
19702
19800
  }
19703
19801
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
19704
- const markerPath = join42(planDir, PLAN_V2_MATERIALIZATION_MARKER);
19705
- if (!existsSync28(markerPath)) return null;
19802
+ const markerPath = join43(planDir, PLAN_V2_MATERIALIZATION_MARKER);
19803
+ if (!existsSync29(markerPath)) return null;
19706
19804
  const marker = readJsonFile(markerPath, "materialization marker");
19707
19805
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
19708
19806
  throw new PlanV2IntegrityError("malformed materialization marker");
@@ -19719,8 +19817,8 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
19719
19817
  assertRemoteSources(remoteSources, required);
19720
19818
  for (const artifact of required) {
19721
19819
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
19722
- const path = join42(planDir, ...artifact.path.split("/"));
19723
- if (!existsSync28(path) || statSync11(path).size !== artifact.sizeBytes) {
19820
+ const path = join43(planDir, ...artifact.path.split("/"));
19821
+ if (!existsSync29(path) || statSync11(path).size !== artifact.sizeBytes) {
19724
19822
  throw new PlanV2IntegrityError(
19725
19823
  `materialized artifact missing or truncated: ${artifact.path}`
19726
19824
  );
@@ -19848,10 +19946,10 @@ async function beginFrameSessionNeedsScreenshotFallback(session, probe = probeBe
19848
19946
  return !await probe(session.page, timeoutMs, probeTick, session.beginFrameIntervalMs);
19849
19947
  }
19850
19948
  function hashChunkOutput(outputPath, kind) {
19851
- if (kind === "file") return sha256Hex(readFileSync13(outputPath));
19949
+ if (kind === "file") return sha256Hex(readFileSync14(outputPath));
19852
19950
  const entries = readdirSync11(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
19853
19951
  const lines = entries.map(
19854
- (name) => `${name}\0${sha256Hex(readFileSync13(join43(outputPath, name)))}`
19952
+ (name) => `${name}\0${sha256Hex(readFileSync14(join44(outputPath, name)))}`
19855
19953
  );
19856
19954
  return sha256Hex(lines.join("\0"));
19857
19955
  }
@@ -19868,16 +19966,16 @@ function resolveLockedVp9CpuUsed(lockedEncoder) {
19868
19966
  async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19869
19967
  const start = Date.now();
19870
19968
  const log = defaultLogger;
19871
- const planJsonPath = join43(planDir, "plan.json");
19872
- const encoderJsonPath = join43(planDir, "meta", "encoder.json");
19873
- const chunksJsonPath = join43(planDir, "meta", "chunks.json");
19874
- if (!existsSync29(planJsonPath)) {
19969
+ const planJsonPath = join44(planDir, "plan.json");
19970
+ const encoderJsonPath = join44(planDir, "meta", "encoder.json");
19971
+ const chunksJsonPath = join44(planDir, "meta", "chunks.json");
19972
+ if (!existsSync30(planJsonPath)) {
19875
19973
  throw new RenderChunkValidationError(
19876
19974
  MISSING_PLAN_ARTIFACT,
19877
19975
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
19878
19976
  );
19879
19977
  }
19880
- const plan2 = JSON.parse(readFileSync13(planJsonPath, "utf-8"));
19978
+ const plan2 = JSON.parse(readFileSync14(planJsonPath, "utf-8"));
19881
19979
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.chunk);
19882
19980
  const planHashStarted = Date.now();
19883
19981
  const v2Materialization = readValidatedPlanV2Materialization(planDir, {
@@ -19887,20 +19985,20 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19887
19985
  const v2Manifest = v2Materialization?.manifest ?? null;
19888
19986
  const remoteSources = v2Materialization?.remoteSources ?? {};
19889
19987
  for (const required of [encoderJsonPath, chunksJsonPath]) {
19890
- if (!existsSync29(required)) {
19988
+ if (!existsSync30(required)) {
19891
19989
  throw new RenderChunkValidationError(
19892
19990
  MISSING_PLAN_ARTIFACT,
19893
19991
  `[renderChunk] planDir is missing required artifact: ${required}`
19894
19992
  );
19895
19993
  }
19896
19994
  }
19897
- const encoder = JSON.parse(readFileSync13(encoderJsonPath, "utf-8"));
19898
- const chunks = JSON.parse(readFileSync13(chunksJsonPath, "utf-8"));
19899
- const videosJsonPath = join43(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19995
+ const encoder = JSON.parse(readFileSync14(encoderJsonPath, "utf-8"));
19996
+ const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
19997
+ const videosJsonPath = join44(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19900
19998
  let planVideos = null;
19901
- if (existsSync29(videosJsonPath)) {
19999
+ if (existsSync30(videosJsonPath)) {
19902
20000
  try {
19903
- planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync13(videosJsonPath, "utf-8")));
20001
+ planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync14(videosJsonPath, "utf-8")));
19904
20002
  } catch (err) {
19905
20003
  if (err instanceof RenderChunkValidationError) throw err;
19906
20004
  throw new RenderChunkValidationError(
@@ -19928,8 +20026,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19928
20026
  }
19929
20027
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
19930
20028
  const framesInChunk = range.endFrame - range.startFrame;
19931
- const compiledDir = join43(planDir, "compiled");
19932
- if (!existsSync29(compiledDir)) {
20029
+ const compiledDir = join44(planDir, "compiled");
20030
+ if (!existsSync30(compiledDir)) {
19933
20031
  throw new RenderChunkValidationError(
19934
20032
  MISSING_PLAN_ARTIFACT,
19935
20033
  `[renderChunk] planDir missing compiled/ directory: ${compiledDir}`
@@ -19987,7 +20085,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19987
20085
  };
19988
20086
  const workDir = `${outputChunkPath}.work.${process.pid}.${randomBytes(4).toString("hex")}`;
19989
20087
  mkdirSync19(workDir, { recursive: true });
19990
- const framesDir = join43(workDir, "captured-frames");
20088
+ const framesDir = join44(workDir, "captured-frames");
19991
20089
  mkdirSync19(framesDir, { recursive: true });
19992
20090
  const videoFramesDir = `${workDir}.video-frames`;
19993
20091
  const chunkFrameNumbers = Array.from({ length: framesInChunk }, (_, i) => range.startFrame + i);
@@ -20012,7 +20110,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20012
20110
  dimensions: plan2.dimensions,
20013
20111
  encoder,
20014
20112
  videoCount: planVideos?.videos.length ?? 0,
20015
- html: readFileSync13(join43(compiledDir, "index.html"), "utf-8"),
20113
+ html: readFileSync14(join44(compiledDir, "index.html"), "utf-8"),
20016
20114
  // The plan ships a deferred source only to chunks that show it; don't wait on the rest.
20017
20115
  skipReadinessVideoIds: deferredVideos.filter(
20018
20116
  (video) => !shownFrames.get(video.videoId)?.size || remoteVideoIds.has(video.videoId)
@@ -20180,10 +20278,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20180
20278
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
20181
20279
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
20182
20280
  if (isPngSequence) {
20183
- if (!existsSync29(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
20281
+ if (!existsSync30(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
20184
20282
  } else {
20185
- const outDir = join43(outputChunkPath, "..");
20186
- if (!existsSync29(outDir)) mkdirSync19(outDir, { recursive: true });
20283
+ const outDir = join44(outputChunkPath, "..");
20284
+ if (!existsSync30(outDir)) mkdirSync19(outDir, { recursive: true });
20187
20285
  }
20188
20286
  const encodeInput = {
20189
20287
  job,
@@ -20290,7 +20388,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20290
20388
  openAttempt,
20291
20389
  verifyFirstSession: forceScreenshot || !verifyInWorker ? void 0 : verifyFirstWorker
20292
20390
  }),
20293
- { stall: frameStallRule(job, framesInChunk) }
20391
+ { stall: frameStallRule(job, framesInChunk, void 0) }
20294
20392
  ).catch(async (captureError) => {
20295
20393
  await overlap.current?.abort();
20296
20394
  overlap.current = null;
@@ -20456,10 +20554,10 @@ async function renderSpan(projectDir, config, span, outputPath) {
20456
20554
  if (config.cfr === true) {
20457
20555
  throw new RenderSpanUnsupportedError("--start/--end cannot be combined with a cfr re-encode.");
20458
20556
  }
20459
- const workDir = mkdtempSync(join44(tmpdir4(), "hf-render-span-"));
20557
+ const workDir = mkdtempSync(join45(tmpdir4(), "hf-render-span-"));
20460
20558
  try {
20461
- const planDir = join44(workDir, "plan");
20462
- const partsDir = join44(workDir, "parts");
20559
+ const planDir = join45(workDir, "plan");
20560
+ const partsDir = join45(workDir, "parts");
20463
20561
  mkdirSync20(partsDir, { recursive: true });
20464
20562
  const planned = await plan(
20465
20563
  projectDir,
@@ -20474,7 +20572,7 @@ async function renderSpan(projectDir, config, span, outputPath) {
20474
20572
  planned.totalFrames
20475
20573
  );
20476
20574
  const slices = JSON.parse(
20477
- readFileSync14(join44(planDir, "meta", "chunks.json"), "utf-8")
20575
+ readFileSync15(join45(planDir, "meta", "chunks.json"), "utf-8")
20478
20576
  );
20479
20577
  const parts = [];
20480
20578
  for (const slice of slices) {
@@ -20484,7 +20582,7 @@ async function renderSpan(projectDir, config, span, outputPath) {
20484
20582
  };
20485
20583
  if (range.endFrame <= range.startFrame) continue;
20486
20584
  throwIfAborted(config.abortSignal);
20487
- const part = join44(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`);
20585
+ const part = join45(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`);
20488
20586
  await renderChunk(planDir, slice.index, part, { frameRange: range });
20489
20587
  parts.push(part);
20490
20588
  }
@@ -20722,6 +20820,13 @@ function validateDistributedRenderConfig(config) {
20722
20820
  `distributed mode supports only ${ALLOWED_HDR_MODES.join(", ")}; got ${String(config.hdrMode)}`
20723
20821
  );
20724
20822
  }
20823
+ const chromaSubsampling = config.chromaSubsampling;
20824
+ if (chromaSubsampling !== void 0 && chromaSubsampling !== "420") {
20825
+ throw new InvalidConfigError(
20826
+ "config.chromaSubsampling",
20827
+ `distributed mode encodes 4:2:0 only; got ${String(chromaSubsampling)}`
20828
+ );
20829
+ }
20725
20830
  if (config.variables !== void 0) {
20726
20831
  validateVariablesPayload(config.variables);
20727
20832
  }
@@ -20905,6 +21010,7 @@ function assertRequestOptionScalars(options) {
20905
21010
  assertOptionalEnum(options, "proresProfile", PRORES_PROFILE_NAMES2);
20906
21011
  assertOptionalEnum(options, "strictness", ["strict", "best-effort"]);
20907
21012
  assertOptionalEnum(options, "hdrMode", ["auto", "force-hdr", "force-sdr"]);
21013
+ assertOptionalEnum(options, "chromaSubsampling", ["420", "444"]);
20908
21014
  assertOptionalEnum(options, "pageMotionBlur", ["off"]);
20909
21015
  if (options.videoFrameFormat !== void 0 && !isVideoFrameFormat2(options.videoFrameFormat)) {
20910
21016
  throw new Error("Render request videoFrameFormat is invalid");
@@ -20993,6 +21099,11 @@ function distributedConfigFromRequest(request, runtime = {}) {
20993
21099
  if (options.hdrMode === "force-hdr") {
20994
21100
  throw new Error("Distributed render does not support force-hdr");
20995
21101
  }
21102
+ if (options.chromaSubsampling === "444") {
21103
+ throw new Error(
21104
+ "Distributed render does not support chromaSubsampling 444: chunk workers and the assemble encode 4:2:0"
21105
+ );
21106
+ }
20996
21107
  return {
20997
21108
  fps: distributedFps(options.fps),
20998
21109
  width: distributed.width,
@@ -21100,7 +21211,7 @@ import {
21100
21211
 
21101
21212
  // src/server.ts
21102
21213
  import {
21103
- existsSync as existsSync32,
21214
+ existsSync as existsSync33,
21104
21215
  mkdirSync as mkdirSync21,
21105
21216
  statSync as statSync13,
21106
21217
  mkdtempSync as mkdtempSync2,
@@ -21108,7 +21219,7 @@ import {
21108
21219
  rmSync as rmSync19,
21109
21220
  createReadStream as createReadStream5
21110
21221
  } from "node:fs";
21111
- import { resolve as resolve12, dirname as dirname19, join as join47 } from "node:path";
21222
+ import { resolve as resolve12, dirname as dirname19, join as join48 } from "node:path";
21112
21223
  import { tmpdir as tmpdir5 } from "node:os";
21113
21224
  import { parseArgs } from "node:util";
21114
21225
  import crypto from "node:crypto";
@@ -21123,15 +21234,15 @@ import {
21123
21234
 
21124
21235
  // src/services/hyperframeLint.ts
21125
21236
  import {
21126
- existsSync as existsSync30,
21127
- readFileSync as readFileSync15,
21237
+ existsSync as existsSync31,
21238
+ readFileSync as readFileSync16,
21128
21239
  statSync as statSync12,
21129
21240
  openSync as openSync7,
21130
21241
  fstatSync as fstatSync3,
21131
21242
  closeSync as closeSync7,
21132
21243
  constants as constants3
21133
21244
  } from "node:fs";
21134
- import { resolve as resolve11, join as join45, relative as relative7, isAbsolute as isAbsolute5, sep as sep5 } from "node:path";
21245
+ import { resolve as resolve11, join as join46, relative as relative7, isAbsolute as isAbsolute5, sep as sep5 } from "node:path";
21135
21246
  import { lintHyperframeHtml } from "@hyperframes/lint";
21136
21247
  function isStringRecord(value) {
21137
21248
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -21170,14 +21281,14 @@ function readEntryHtml(filePath) {
21170
21281
  }
21171
21282
  try {
21172
21283
  if (!fstatSync3(fd).isFile()) return null;
21173
- return readFileSync15(fd, "utf-8");
21284
+ return readFileSync16(fd, "utf-8");
21174
21285
  } finally {
21175
21286
  closeSync7(fd);
21176
21287
  }
21177
21288
  }
21178
21289
  function readProjectEntryFile(projectDir, preferredEntryFile) {
21179
21290
  const absProjectDir = resolve11(projectDir);
21180
- if (!existsSync30(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
21291
+ if (!existsSync31(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
21181
21292
  return { error: `Project directory not found: ${absProjectDir}` };
21182
21293
  }
21183
21294
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -21199,7 +21310,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
21199
21310
  }
21200
21311
  }
21201
21312
  return {
21202
- error: `No HTML entry file found in project directory: ${join45(absProjectDir, preferredEntryFile || "index.html")}`
21313
+ error: `No HTML entry file found in project directory: ${join46(absProjectDir, preferredEntryFile || "index.html")}`
21203
21314
  };
21204
21315
  }
21205
21316
  function prepareHyperframeLintBody(body) {
@@ -21245,8 +21356,8 @@ async function runHyperframeLint(prepared) {
21245
21356
  // src/services/healthWorker.ts
21246
21357
  import { Worker as Worker2 } from "node:worker_threads";
21247
21358
  import { fileURLToPath as fileURLToPath6 } from "node:url";
21248
- import { dirname as dirname18, join as join46 } from "node:path";
21249
- import { existsSync as existsSync31 } from "node:fs";
21359
+ import { dirname as dirname18, join as join47 } from "node:path";
21360
+ import { existsSync as existsSync32 } from "node:fs";
21250
21361
  var DEFAULT_HEALTH_PORT = 9848;
21251
21362
  async function startHealthWorker(options = {}) {
21252
21363
  const log = options.logger ?? defaultLogger2();
@@ -21321,9 +21432,9 @@ function defaultLogger2() {
21321
21432
  }
21322
21433
  function resolveWorkerEntry2() {
21323
21434
  const here = dirname18(fileURLToPath6(import.meta.url));
21324
- const candidates = [join46(here, "healthWorkerThread.js"), join46(here, "healthWorkerThread.ts")];
21435
+ const candidates = [join47(here, "healthWorkerThread.js"), join47(here, "healthWorkerThread.ts")];
21325
21436
  for (const candidate of candidates) {
21326
- if (existsSync31(candidate)) return candidate;
21437
+ if (existsSync32(candidate)) return candidate;
21327
21438
  }
21328
21439
  return void 0;
21329
21440
  }
@@ -21399,7 +21510,15 @@ function parseRenderOptions(body) {
21399
21510
  const format = parseServerFormat(body.format);
21400
21511
  const outputDynamicRange = parseServerOutputDynamicRange(body.outputDynamicRange) ?? fromRenderHdrMode(parseLegacyServerHdrMode(body.hdrMode));
21401
21512
  const encoder = parseEncoderOptions(body, format ?? "mp4");
21402
- const { crf, videoBitrate, videoFrameFormat, keyframeIntervalSeconds, maxBitrate, bufferSize } = encoder.ok ? encoder.options : {};
21513
+ const {
21514
+ crf,
21515
+ videoBitrate,
21516
+ videoFrameFormat,
21517
+ keyframeIntervalSeconds,
21518
+ maxBitrate,
21519
+ bufferSize,
21520
+ chromaSubsampling
21521
+ } = encoder.ok ? encoder.options : {};
21403
21522
  const { variables, outputResolution, outputResolutionAspectAgnostic } = parseRenderOverrides(body);
21404
21523
  return {
21405
21524
  outputPath,
@@ -21412,6 +21531,7 @@ function parseRenderOptions(body) {
21412
21531
  keyframeIntervalSeconds,
21413
21532
  maxBitrate,
21414
21533
  bufferSize,
21534
+ chromaSubsampling,
21415
21535
  useGpu,
21416
21536
  debug,
21417
21537
  forceScreenshot,
@@ -21451,6 +21571,7 @@ function buildRenderJobConfig(input, outputPath, log) {
21451
21571
  keyframeIntervalSeconds: input.keyframeIntervalSeconds,
21452
21572
  maxBitrate: input.maxBitrate,
21453
21573
  bufferSize: input.bufferSize,
21574
+ chromaSubsampling: input.chromaSubsampling,
21454
21575
  useGpu: input.useGpu,
21455
21576
  debug: input.debug,
21456
21577
  strictness: input.strictness,
@@ -21469,15 +21590,28 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log) {
21469
21590
  const { input, cleanupProjectDir } = prepared;
21470
21591
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
21471
21592
  const outputDir = dirname19(absoluteOutputPath);
21472
- if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
21593
+ if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
21473
21594
  return { input, cleanupProjectDir, absoluteOutputPath };
21474
21595
  }
21596
+ function prepareRenderJob(prepared, rendersDir, log) {
21597
+ try {
21598
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
21599
+ const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
21600
+ return { ...output, job };
21601
+ } catch (error) {
21602
+ cleanupTempDir(prepared.cleanupProjectDir, log);
21603
+ return { error: error instanceof Error ? error.message : String(error) };
21604
+ }
21605
+ }
21475
21606
  function validateRenderOverrides(body) {
21476
21607
  const encoder = parseEncoderOptions(body, parseServerFormat(body.format) ?? "mp4");
21477
21608
  if (!encoder.ok) return encoder.error;
21478
21609
  if (body.maxRenderMs !== void 0 && (typeof body.maxRenderMs !== "number" || !Number.isInteger(body.maxRenderMs) || body.maxRenderMs < 0)) {
21479
21610
  return "maxRenderMs must be a non-negative integer number of milliseconds";
21480
21611
  }
21612
+ if (typeof body.workers === "number" && (!Number.isInteger(body.workers) || body.workers < 1)) {
21613
+ return "workers must be a positive integer";
21614
+ }
21481
21615
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
21482
21616
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
21483
21617
  }
@@ -21492,6 +21626,9 @@ function validateRenderOverrides(body) {
21492
21626
  if (outputDynamicRange !== void 0 && legacyHdrMode !== void 0 && outputDynamicRange !== fromRenderHdrMode(legacyHdrMode)) {
21493
21627
  return "outputDynamicRange and legacy hdrMode must describe the same output policy";
21494
21628
  }
21629
+ if (body.chromaSubsampling === "444" && outputDynamicRange === "hdr") {
21630
+ return 'chromaSubsampling "444" is SDR only, not outputDynamicRange "hdr"';
21631
+ }
21495
21632
  return validateOutputResolutionOverride(body);
21496
21633
  }
21497
21634
  function validateOutputResolutionOverride(body) {
@@ -21510,11 +21647,11 @@ function prepareProjectDirectory(projectDir, options) {
21510
21647
  const candidate = nonEmptyString(projectDir);
21511
21648
  if (!candidate) return null;
21512
21649
  const absProjectDir = resolve12(candidate);
21513
- if (!existsSync32(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
21650
+ if (!existsSync33(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
21514
21651
  return { error: `Project directory not found: ${absProjectDir}` };
21515
21652
  }
21516
21653
  const entry = options.entryFile || "index.html";
21517
- if (!existsSync32(resolve12(absProjectDir, entry))) {
21654
+ if (!existsSync33(resolve12(absProjectDir, entry))) {
21518
21655
  return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
21519
21656
  }
21520
21657
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -21535,8 +21672,8 @@ async function resolveInlineRenderHtml(body) {
21535
21672
  }
21536
21673
  function materializeInlineProject(html, options) {
21537
21674
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir5();
21538
- const tempProjectDir = mkdtempSync2(join47(tempRoot, "producer-project-"));
21539
- writeFileSync14(join47(tempProjectDir, "index.html"), html, "utf-8");
21675
+ const tempProjectDir = mkdtempSync2(join48(tempRoot, "producer-project-"));
21676
+ writeFileSync14(join48(tempProjectDir, "index.html"), html, "utf-8");
21540
21677
  return {
21541
21678
  prepared: {
21542
21679
  input: { projectDir: tempProjectDir, ...options },
@@ -21606,7 +21743,7 @@ function cleanupTempDir(dir, log) {
21606
21743
  }
21607
21744
  }
21608
21745
  function outputFileSize(path) {
21609
- return existsSync32(path) ? statSync13(path).size : 0;
21746
+ return existsSync33(path) ? statSync13(path).size : 0;
21610
21747
  }
21611
21748
  function createBlockingProgressReporter(log, requestId) {
21612
21749
  let lastLoggedPct = -10;
@@ -21755,11 +21892,11 @@ function createRenderHandlers(options = {}) {
21755
21892
  if ("error" in preparedResult) {
21756
21893
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
21757
21894
  }
21758
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
21759
- preparedResult.prepared,
21760
- rendersDir,
21761
- log
21762
- );
21895
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
21896
+ if ("error" in preparedJob) {
21897
+ return c.json({ success: false, requestId, error: preparedJob.error }, 400);
21898
+ }
21899
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
21763
21900
  const release = await renderSemaphore.acquire();
21764
21901
  log.info("render started", {
21765
21902
  requestId,
@@ -21767,7 +21904,6 @@ function createRenderHandlers(options = {}) {
21767
21904
  fps: input.fps,
21768
21905
  quality: input.quality
21769
21906
  });
21770
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
21771
21907
  try {
21772
21908
  await executeRenderJob(
21773
21909
  job,
@@ -21835,13 +21971,20 @@ function createRenderHandlers(options = {}) {
21835
21971
  const t0 = Date.now();
21836
21972
  const prepared = await prepareSseRenderRequest(c, stream, requestId);
21837
21973
  if (!prepared) return;
21838
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
21839
- prepared,
21840
- rendersDir,
21841
- log
21842
- );
21974
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log);
21975
+ if ("error" in preparedJob) {
21976
+ await stream.writeSSE({
21977
+ data: JSON.stringify({
21978
+ type: "error",
21979
+ requestId,
21980
+ error: preparedJob.error,
21981
+ stage: "validation"
21982
+ })
21983
+ });
21984
+ return;
21985
+ }
21986
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
21843
21987
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
21844
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
21845
21988
  const abortController = new AbortController();
21846
21989
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
21847
21990
  c.req.raw.signal.addEventListener("abort", onRequestAbort, { once: true });
@@ -21885,7 +22028,8 @@ function createRenderHandlers(options = {}) {
21885
22028
  videoDurationSeconds: job.duration ?? null,
21886
22029
  outcome: job.outcome ?? "completed",
21887
22030
  warnings: job.warnings,
21888
- perf: job.perfSummary ?? null
22031
+ perf: job.perfSummary ?? null,
22032
+ producerVersion: readProducerVersion()
21889
22033
  })
21890
22034
  });
21891
22035
  } catch (error) {
@@ -21910,7 +22054,7 @@ function createRenderHandlers(options = {}) {
21910
22054
  if (!artifact) {
21911
22055
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
21912
22056
  }
21913
- if (!existsSync32(artifact.path)) {
22057
+ if (!existsSync33(artifact.path)) {
21914
22058
  store.delete(token);
21915
22059
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
21916
22060
  }
@@ -21930,9 +22074,26 @@ function createRenderHandlers(options = {}) {
21930
22074
  });
21931
22075
  return { render, renderStream, lint, health, outputs, queue };
21932
22076
  }
22077
+ function isCrossOriginBrowserRequest(c) {
22078
+ const fetchSite = c.req.header("sec-fetch-site");
22079
+ if (fetchSite) return fetchSite !== "same-origin" && fetchSite !== "none";
22080
+ const origin = c.req.header("origin");
22081
+ if (!origin) return false;
22082
+ try {
22083
+ return new URL(origin).host !== c.req.header("host");
22084
+ } catch {
22085
+ return true;
22086
+ }
22087
+ }
21933
22088
  function createProducerApp(options = {}) {
21934
22089
  const app = new Hono2();
21935
22090
  const handlers = createRenderHandlers(options);
22091
+ app.post("*", async (c, next) => {
22092
+ if (isCrossOriginBrowserRequest(c)) {
22093
+ return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
22094
+ }
22095
+ await next();
22096
+ });
21936
22097
  app.get("/health", handlers.health);
21937
22098
  app.post("/render", handlers.render);
21938
22099
  app.post("/render/stream", handlers.renderStream);
@@ -22007,7 +22168,7 @@ import { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes
22007
22168
  // src/services/distributed/planV2Execution.ts
22008
22169
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "node:fs";
22009
22170
  import { tmpdir as tmpdir6 } from "node:os";
22010
- import { join as join49 } from "node:path";
22171
+ import { join as join50 } from "node:path";
22011
22172
 
22012
22173
  // src/services/distributed/assemble.ts
22013
22174
  import {
@@ -22016,15 +22177,15 @@ import {
22016
22177
  } from "@hyperframes/engine";
22017
22178
  import {
22018
22179
  cpSync as cpSync3,
22019
- existsSync as existsSync33,
22180
+ existsSync as existsSync34,
22020
22181
  mkdirSync as mkdirSync22,
22021
- readFileSync as readFileSync16,
22182
+ readFileSync as readFileSync17,
22022
22183
  readdirSync as readdirSync12,
22023
22184
  rmSync as rmSync20,
22024
22185
  statSync as statSync14,
22025
22186
  writeFileSync as writeFileSync15
22026
22187
  } from "node:fs";
22027
- import { basename as basename8, dirname as dirname20, join as join48 } from "node:path";
22188
+ import { basename as basename8, dirname as dirname20, join as join49 } from "node:path";
22028
22189
  import {
22029
22190
  appendRateCapArgs as appendRateCapArgs2,
22030
22191
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
@@ -22071,7 +22232,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22071
22232
  }
22072
22233
  const format = plan2.dimensions.format;
22073
22234
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
22074
- if (!existsSync33(dirname20(outputPath))) {
22235
+ if (!existsSync34(dirname20(outputPath))) {
22075
22236
  mkdirSync22(dirname20(outputPath), { recursive: true });
22076
22237
  }
22077
22238
  const workDir = createStagingDir7(dirname20(outputPath), `${basename8(outputPath)}.assemble-work-`);
@@ -22094,8 +22255,8 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22094
22255
  };
22095
22256
  try {
22096
22257
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
22097
- const finalPath = join48(workDir, `output.${format}`);
22098
- const audio = audioPath !== null && existsSync33(audioPath) ? audioPath : null;
22258
+ const finalPath = join49(workDir, `output.${format}`);
22259
+ const audio = audioPath !== null && existsSync34(audioPath) ? audioPath : null;
22099
22260
  await writeJoined(ctx, videoSources, audio, finalPath);
22100
22261
  renameWithRetry11(finalPath, outputPath);
22101
22262
  log.info("[assemble] stage timings", {
@@ -22113,7 +22274,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22113
22274
  });
22114
22275
  }
22115
22276
  }
22116
- const fileSize = existsSync33(outputPath) ? statSync14(outputPath).size : 0;
22277
+ const fileSize = existsSync34(outputPath) ? statSync14(outputPath).size : 0;
22117
22278
  return {
22118
22279
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
22119
22280
  outputPath,
@@ -22123,18 +22284,18 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22123
22284
  };
22124
22285
  }
22125
22286
  function readAssemblePlan(planDir, chunkPaths) {
22126
- const planJsonPath = join48(planDir, "plan.json");
22127
- const chunksJsonPath = join48(planDir, "meta", "chunks.json");
22128
- if (!existsSync33(planJsonPath)) {
22287
+ const planJsonPath = join49(planDir, "plan.json");
22288
+ const chunksJsonPath = join49(planDir, "meta", "chunks.json");
22289
+ if (!existsSync34(planJsonPath)) {
22129
22290
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
22130
22291
  }
22131
- const plan2 = JSON.parse(readFileSync16(planJsonPath, "utf-8"));
22292
+ const plan2 = JSON.parse(readFileSync17(planJsonPath, "utf-8"));
22132
22293
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
22133
22294
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
22134
- if (!existsSync33(chunksJsonPath)) {
22295
+ if (!existsSync34(chunksJsonPath)) {
22135
22296
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
22136
22297
  }
22137
- const chunks = JSON.parse(readFileSync16(chunksJsonPath, "utf-8"));
22298
+ const chunks = JSON.parse(readFileSync17(chunksJsonPath, "utf-8"));
22138
22299
  if (chunkPaths.length !== chunks.length) {
22139
22300
  throw new Error(
22140
22301
  `[assemble] chunkPaths length (${chunkPaths.length}) does not match chunks.json length (${chunks.length}). Adapters must pass one path per chunk, ordered by index.`
@@ -22146,7 +22307,7 @@ function readAssemblePlan(planDir, chunkPaths) {
22146
22307
  }
22147
22308
  }
22148
22309
  for (const path of chunkPaths.flat()) {
22149
- if (!existsSync33(path)) {
22310
+ if (!existsSync34(path)) {
22150
22311
  throw new Error(`[assemble] chunk path does not exist: ${path}`);
22151
22312
  }
22152
22313
  }
@@ -22175,7 +22336,7 @@ function cfrEncodeArgs(inputArgs, encoder, fpsArg) {
22175
22336
  return args;
22176
22337
  }
22177
22338
  async function reencodeCfr(ctx, chunkPaths, encoder) {
22178
- const cfrOutputPath = join48(ctx.workDir, `cfr.${ctx.format}`);
22339
+ const cfrOutputPath = join49(ctx.workDir, `cfr.${ctx.format}`);
22179
22340
  const cfrArgs = cfrEncodeArgs(videoInputArgs(ctx, chunkPaths), encoder, ctx.fpsArg);
22180
22341
  appendRenderProvenanceArgs2(cfrArgs, cfrOutputPath);
22181
22342
  cfrArgs.push("-y", cfrOutputPath);
@@ -22202,7 +22363,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
22202
22363
  );
22203
22364
  return;
22204
22365
  }
22205
- const paddedAudioPath = join48(ctx.workDir, "audio-padded.m4a");
22366
+ const paddedAudioPath = join49(ctx.workDir, "audio-padded.m4a");
22206
22367
  const padTrimResult = await ctx.timed(
22207
22368
  "audioMs",
22208
22369
  () => padOrTrimAudioToVideoFrameCount({
@@ -22242,7 +22403,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
22242
22403
  }
22243
22404
  }
22244
22405
  function concatDemuxerInput(chunkPaths, workDir, fpsArg) {
22245
- const listPath = join48(workDir, "concat-list.txt");
22406
+ const listPath = join49(workDir, "concat-list.txt");
22246
22407
  const body = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
22247
22408
  writeFileSync15(listPath, `${body}
22248
22409
  `, "utf-8");
@@ -22280,13 +22441,13 @@ function stitchesSeparateAudio(planDir) {
22280
22441
  return lockedAudio(planDir).separateAudio === true;
22281
22442
  }
22282
22443
  function planFormat(planDir) {
22283
- const plan2 = JSON.parse(readFileSync16(join48(planDir, "plan.json"), "utf-8"));
22444
+ const plan2 = JSON.parse(readFileSync17(join49(planDir, "plan.json"), "utf-8"));
22284
22445
  return plan2.dimensions.format;
22285
22446
  }
22286
22447
  function lockedAudio(planDir) {
22287
- const encoderJsonPath = join48(planDir, "meta", "encoder.json");
22288
- if (!existsSync33(encoderJsonPath)) return {};
22289
- return JSON.parse(readFileSync16(encoderJsonPath, "utf-8"));
22448
+ const encoderJsonPath = join49(planDir, "meta", "encoder.json");
22449
+ if (!existsSync34(encoderJsonPath)) return {};
22450
+ return JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
22290
22451
  }
22291
22452
  function readCfrEncoder(planDir, format) {
22292
22453
  if (format !== "mp4") {
@@ -22294,11 +22455,11 @@ function readCfrEncoder(planDir, format) {
22294
22455
  `[assemble] cfr=true is only supported for format="mp4" (got "${format}"). Stream-copy paths for webm and mov already produce exact avg_frame_rate; cfr re-encode is not needed.`
22295
22456
  );
22296
22457
  }
22297
- const encoderJsonPath = join48(planDir, "meta", "encoder.json");
22298
- if (!existsSync33(encoderJsonPath)) {
22458
+ const encoderJsonPath = join49(planDir, "meta", "encoder.json");
22459
+ if (!existsSync34(encoderJsonPath)) {
22299
22460
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
22300
22461
  }
22301
- const encoderJson = JSON.parse(readFileSync16(encoderJsonPath, "utf-8"));
22462
+ const encoderJson = JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
22302
22463
  if (encoderJson.encoder === "libx265-software") {
22303
22464
  throw new Error(
22304
22465
  `[assemble] cfr=true is not yet supported with codec: "h265". The cfr re-encode pass uses libx264 and would silently transcode the h265 chunks. Either disable cfr or render with codec: "h264".`
@@ -22307,7 +22468,7 @@ function readCfrEncoder(planDir, format) {
22307
22468
  return encoderJson;
22308
22469
  }
22309
22470
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
22310
- if (existsSync33(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
22471
+ if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
22311
22472
  mkdirSync22(outputPath, { recursive: true });
22312
22473
  let globalIdx = 0;
22313
22474
  for (const chunkDir of chunkPaths) {
@@ -22321,8 +22482,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
22321
22482
  throw new Error(`[assemble] png-sequence chunk has no frames: ${chunkDir}`);
22322
22483
  }
22323
22484
  for (const frame of frames) {
22324
- const dst = join48(outputPath, formatExportFrameName(globalIdx, "png"));
22325
- cpSync3(join48(chunkDir, frame), dst);
22485
+ const dst = join49(outputPath, formatExportFrameName(globalIdx, "png"));
22486
+ cpSync3(join49(chunkDir, frame), dst);
22326
22487
  globalIdx += 1;
22327
22488
  }
22328
22489
  }
@@ -22331,14 +22492,14 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
22331
22492
  `[assemble] png-sequence frame count mismatch: merged ${globalIdx} frames vs plan.totalFrames=${totalFrames}. Using on-disk count.`
22332
22493
  );
22333
22494
  }
22334
- if (audioPath !== null && existsSync33(audioPath)) {
22335
- const sidecar = join48(outputPath, MIXED_AUDIO_FILENAME4);
22495
+ if (audioPath !== null && existsSync34(audioPath)) {
22496
+ const sidecar = join49(outputPath, MIXED_AUDIO_FILENAME4);
22336
22497
  cpSync3(audioPath, sidecar);
22337
22498
  }
22338
22499
  let fileSize = 0;
22339
22500
  for (const name of readdirSync12(outputPath)) {
22340
22501
  try {
22341
- fileSize += statSync14(join48(outputPath, name)).size;
22502
+ fileSize += statSync14(join49(outputPath, name)).size;
22342
22503
  } catch {
22343
22504
  }
22344
22505
  }
@@ -22352,8 +22513,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
22352
22513
 
22353
22514
  // src/services/distributed/planV2Execution.ts
22354
22515
  async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
22355
- const workRoot = mkdtempSync3(join49(tmpdir6(), "hf-plan-v2-chunk-"));
22356
- const materializedPlanDir = join49(workRoot, "plan");
22516
+ const workRoot = mkdtempSync3(join50(tmpdir6(), "hf-plan-v2-chunk-"));
22517
+ const materializedPlanDir = join50(workRoot, "plan");
22357
22518
  try {
22358
22519
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
22359
22520
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
@@ -22362,8 +22523,8 @@ async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
22362
22523
  }
22363
22524
  }
22364
22525
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
22365
- const workRoot = mkdtempSync3(join49(tmpdir6(), "hf-plan-v2-assembler-"));
22366
- const materializedPlanDir = join49(workRoot, "plan");
22526
+ const workRoot = mkdtempSync3(join50(tmpdir6(), "hf-plan-v2-assembler-"));
22527
+ const materializedPlanDir = join50(workRoot, "plan");
22367
22528
  try {
22368
22529
  const materialized = materializePlanV2Target(
22369
22530
  planV2Dir,