@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.
@@ -8,13 +8,13 @@ import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframe
8
8
  import {
9
9
  copyFileSync as copyFileSync6,
10
10
  cpSync as cpSync2,
11
- existsSync as existsSync19,
11
+ existsSync as existsSync20,
12
12
  linkSync,
13
13
  mkdirSync as mkdirSync10,
14
14
  rmSync as rmSync7,
15
15
  writeFileSync as writeFileSync8
16
16
  } from "node:fs";
17
- import { extname as extname4, isAbsolute as isAbsolute3, join as join25, relative as relative5, sep as sep3 } from "node:path";
17
+ import { extname as extname4, isAbsolute as isAbsolute3, join as join26, relative as relative5, sep as sep3 } from "node:path";
18
18
  import {
19
19
  fpsToNumber as fpsToNumber9,
20
20
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -71,7 +71,7 @@ var defaultLogger = createConsoleLogger("info");
71
71
  // src/services/renderOrchestrator.ts
72
72
  import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
73
73
  import {
74
- existsSync as existsSync14,
74
+ existsSync as existsSync15,
75
75
  mkdirSync as mkdirSync6,
76
76
  readdirSync as readdirSync3,
77
77
  rmSync as rmSync5,
@@ -128,7 +128,7 @@ import {
128
128
  referenceBackgroundResult,
129
129
  createReferenceBackgroundRecorder
130
130
  } from "@hyperframes/engine";
131
- import { join as join16, dirname as dirname10, resolve as resolve7 } from "path";
131
+ import { join as join17, dirname as dirname10, resolve as resolve7 } from "path";
132
132
  import { randomUUID } from "crypto";
133
133
 
134
134
  // src/services/fileServer.ts
@@ -964,6 +964,9 @@ import {
964
964
  CANVAS_DIMENSIONS,
965
965
  checkOutputResolutionCompatibility
966
966
  } from "@hyperframes/core";
967
+ import {
968
+ mediaIdPathSegment
969
+ } from "@hyperframes/engine";
967
970
 
968
971
  // src/utils/paths.ts
969
972
  import {
@@ -1041,6 +1044,10 @@ function writeCompiledArtifacts(compiled, workDir, includeSummary) {
1041
1044
  writeFileSync(join3(compileDir, "index.html"), compiled.html, "utf-8");
1042
1045
  for (const [srcPath, html] of compiled.subCompositions) {
1043
1046
  const outPath = join3(compileDir, srcPath);
1047
+ if (!isPathInside2(outPath, compileDir)) {
1048
+ console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
1049
+ continue;
1050
+ }
1044
1051
  mkdirSync(dirname2(outPath), { recursive: true });
1045
1052
  writeFileSync(outPath, html, "utf-8");
1046
1053
  }
@@ -1251,7 +1258,7 @@ function materializeExtractedFramesForCompiledDir(extracted, compiledDir, option
1251
1258
  for (const ext of extracted) {
1252
1259
  const resolvedOut = pathModule.resolve(ext.outputDir);
1253
1260
  if (isPathInside2(resolvedOut, resolvedCompiledDir, { pathModule })) continue;
1254
- const linkPath = pathModule.join(compiledFrameRoot, ext.videoId);
1261
+ const linkPath = pathModule.join(compiledFrameRoot, mediaIdPathSegment(ext.videoId));
1255
1262
  if (!fileSystem.existsSync(linkPath)) {
1256
1263
  fileSystem.mkdirSync(pathModule.dirname(linkPath), { recursive: true });
1257
1264
  stageExtractedFrameDir(
@@ -1703,6 +1710,7 @@ import { dirname as dirname3, join as join4 } from "node:path";
1703
1710
  import {
1704
1711
  createFrameLookupTable,
1705
1712
  extractVideoFramesRange,
1713
+ mediaIdPathSegment as mediaIdPathSegment2,
1706
1714
  runVideoExtractionWithRetry
1707
1715
  } from "@hyperframes/engine";
1708
1716
  function contiguousRuns(sortedIndexes) {
@@ -1743,7 +1751,7 @@ async function extractDeferredFrames(input) {
1743
1751
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
1744
1752
  return Promise.all(
1745
1753
  deferred.map(async (video) => {
1746
- const outputDir = join4(input.outputRoot, video.videoId);
1754
+ const outputDir = join4(input.outputRoot, mediaIdPathSegment2(video.videoId));
1747
1755
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
1748
1756
  if (indexes.length === 0) {
1749
1757
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -2144,8 +2152,8 @@ import {
2144
2152
  } from "@hyperframes/engine";
2145
2153
 
2146
2154
  // src/services/render/stages/compileStage.ts
2147
- import { existsSync as existsSync8, writeFileSync as writeFileSync3 } from "node:fs";
2148
- import { join as join8 } from "node:path";
2155
+ import { existsSync as existsSync9, writeFileSync as writeFileSync3 } from "node:fs";
2156
+ import { join as join9 } from "node:path";
2149
2157
  import { suggestMatchingPreset } from "@hyperframes/core";
2150
2158
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
2151
2159
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
@@ -2153,9 +2161,23 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
2153
2161
  // src/services/htmlCompiler.ts
2154
2162
  import { decodedUrlPath as decodedUrlPath2 } from "@hyperframes/parsers/asset-paths";
2155
2163
  import { createHash as createHash4 } from "node:crypto";
2156
- import { createReadStream as createReadStream2, existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync4 } from "fs";
2157
- import { join as join7, dirname as dirname6, resolve as resolve6, basename as basename3, relative as relative2, sep as sep2 } from "path";
2164
+ import { createReadStream as createReadStream2, existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync5 } from "fs";
2165
+ import { join as join8, dirname as dirname6, resolve as resolve6, basename as basename3, relative as relative2, sep as sep2 } from "path";
2158
2166
  import { parseHTML as parseHTML5 } from "linkedom";
2167
+
2168
+ // src/services/bundledScripts.ts
2169
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
2170
+ import { join as join5 } from "node:path";
2171
+ import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
2172
+ var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
2173
+ function bundledScript(url) {
2174
+ const dir = process.env[GSAP_VENDOR_DIR_ENV];
2175
+ if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
2176
+ const file = join5(dir, "gsap.min.js");
2177
+ return existsSync5(file) ? readFileSync2(file) : null;
2178
+ }
2179
+
2180
+ // src/services/htmlCompiler.ts
2159
2181
  import {
2160
2182
  COMPOSITION_SOURCE_URL,
2161
2183
  compileTimingAttrs,
@@ -2177,7 +2199,7 @@ import {
2177
2199
  import { MAX_AUDIO_GAIN } from "@hyperframes/core/audio-gain";
2178
2200
  import { readPlaybackRate } from "@hyperframes/parsers/media-duration";
2179
2201
  import { resolveRateSpec } from "@hyperframes/core/speed-ramp";
2180
- import { gsapCdnDist, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
2202
+ import { gsapCdnDist as gsapCdnDist2, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
2181
2203
  import {
2182
2204
  assignBundledRuntimeCompositionIds,
2183
2205
  assignMediaRenderIds,
@@ -2400,8 +2422,8 @@ import {
2400
2422
 
2401
2423
  // src/services/animatedGifPrep.ts
2402
2424
  import { createHash as createHash2 } from "node:crypto";
2403
- import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync as statSync2 } from "node:fs";
2404
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join5, resolve as resolve4 } from "node:path";
2425
+ import { copyFileSync as copyFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync2 } from "node:fs";
2426
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolve4 } from "node:path";
2405
2427
  import { parseHTML as parseHTML3 } from "linkedom";
2406
2428
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
2407
2429
  import { DEFAULT_VP9_CPU_USED, runFfmpeg as runFfmpeg2, renameWithRetry as renameWithRetry3 } from "@hyperframes/engine";
@@ -2439,14 +2461,14 @@ function resolveLocalImageSourcePath(src, options) {
2439
2461
  const { basePath } = splitUrlSuffix(trimmed);
2440
2462
  const normalizedBase = normalizeRelPath(basePath);
2441
2463
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
2442
- if (mapped && existsSync5(mapped)) return mapped;
2464
+ if (mapped && existsSync6(mapped)) return mapped;
2443
2465
  if (isHttpUrl(trimmed)) return null;
2444
2466
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
2445
2467
  const candidates = [
2446
2468
  isAbsolute2(basePath) ? basePath : resolve4(options.projectDir, projectRelative),
2447
2469
  resolve4(options.downloadDir, normalizedBase)
2448
2470
  ];
2449
- return candidates.find((candidate) => existsSync5(candidate)) ?? null;
2471
+ return candidates.find((candidate) => existsSync6(candidate)) ?? null;
2450
2472
  }
2451
2473
  function isUsableFile(path) {
2452
2474
  try {
@@ -2557,10 +2579,10 @@ async function runAnimatedGifTranscode(request) {
2557
2579
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
2558
2580
  }
2559
2581
  async function ensurePreparedWebm(input) {
2560
- if (!existsSync5(dirname4(input.cachePath))) {
2582
+ if (!existsSync6(dirname4(input.cachePath))) {
2561
2583
  mkdirSync2(dirname4(input.cachePath), { recursive: true });
2562
2584
  }
2563
- if (!existsSync5(dirname4(input.outputPath))) {
2585
+ if (!existsSync6(dirname4(input.outputPath))) {
2564
2586
  mkdirSync2(dirname4(input.outputPath), { recursive: true });
2565
2587
  }
2566
2588
  if (!isUsableFile(input.cachePath)) {
@@ -2644,7 +2666,7 @@ function replaceImageWithVideo(input) {
2644
2666
  return video;
2645
2667
  }
2646
2668
  async function prepareAnimatedGifInputs(html, options) {
2647
- const outputDir = options.outputDir ?? join5(options.downloadDir, PREPARED_GIF_SUBDIR);
2669
+ const outputDir = options.outputDir ?? join6(options.downloadDir, PREPARED_GIF_SUBDIR);
2648
2670
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
2649
2671
  const cacheDir = options.cacheDir ?? outputDir;
2650
2672
  const { document: document2 } = parseHTML3(html);
@@ -2658,7 +2680,7 @@ async function prepareAnimatedGifInputs(html, options) {
2658
2680
  if (!hasGifExtension(src)) continue;
2659
2681
  const sourcePath = resolveLocalImageSourcePath(src, options);
2660
2682
  if (!sourcePath) continue;
2661
- const bytes = readFileSync2(sourcePath);
2683
+ const bytes = readFileSync3(sourcePath);
2662
2684
  const metadata = parseAnimatedGifMetadata(bytes);
2663
2685
  if (!metadata?.animated) continue;
2664
2686
  const loopOverride = readLoopOverride(img);
@@ -2671,8 +2693,8 @@ async function prepareAnimatedGifInputs(html, options) {
2671
2693
  );
2672
2694
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
2673
2695
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
2674
- const cachePath = join5(cacheDir, filename);
2675
- const outputPath = join5(outputDir, filename);
2696
+ const cachePath = join6(cacheDir, filename);
2697
+ const outputPath = join6(outputDir, filename);
2676
2698
  const outputSrc = `${outputSrcPrefix}/${filename}`;
2677
2699
  await ensurePreparedWebm({
2678
2700
  sourcePath,
@@ -2711,13 +2733,13 @@ import {
2711
2733
  copyFileSync as copyFileSync3,
2712
2734
  mkdirSync as mkdirSync3,
2713
2735
  openSync as openSync2,
2714
- readFileSync as readFileSync3,
2736
+ readFileSync as readFileSync4,
2715
2737
  readSync,
2716
2738
  rmSync as rmSync3,
2717
2739
  statSync as statSync3,
2718
2740
  writeFileSync as writeFileSync2
2719
2741
  } from "node:fs";
2720
- import { dirname as dirname5, join as join6, resolve as resolve5 } from "node:path";
2742
+ import { dirname as dirname5, join as join7, resolve as resolve5 } from "node:path";
2721
2743
  import { parseHTML as parseHTML4 } from "linkedom";
2722
2744
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe } from "@hyperframes/engine";
2723
2745
 
@@ -2895,7 +2917,7 @@ function primaryGrid(probed) {
2895
2917
  async function convertHeifToJpeg(request) {
2896
2918
  const probed = await probeJson(request.inputPath, true);
2897
2919
  const grid = primaryGrid(probed);
2898
- const rotation = readHeifPrimaryRotation(readFileSync3(request.inputPath));
2920
+ const rotation = readHeifPrimaryRotation(readFileSync4(request.inputPath));
2899
2921
  const filters = [];
2900
2922
  let inputs = [];
2901
2923
  let size = probed.streams?.[0];
@@ -2953,7 +2975,7 @@ function resolveImageSource(src, options) {
2953
2975
  const path = resolveLocalImageSourcePath(src, options);
2954
2976
  const head = path ? readHead(path) : null;
2955
2977
  if (!path || !head || !isHeifBytes(head)) return null;
2956
- return { path, bytes: readFileSync3(path), label: `"${splitUrlSuffix(src).basePath}"` };
2978
+ return { path, bytes: readFileSync4(path), label: `"${splitUrlSuffix(src).basePath}"` };
2957
2979
  }
2958
2980
  function isUsableFile2(path) {
2959
2981
  try {
@@ -2991,7 +3013,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
2991
3013
  }
2992
3014
  }
2993
3015
  async function prepareHeifImageInputs(html, options) {
2994
- const outputDir = options.outputDir ?? join6(options.downloadDir, PREPARED_HEIF_SUBDIR);
3016
+ const outputDir = options.outputDir ?? join7(options.downloadDir, PREPARED_HEIF_SUBDIR);
2995
3017
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
2996
3018
  const cacheDir = options.cacheDir ?? outputDir;
2997
3019
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -3012,7 +3034,7 @@ async function prepareHeifImageInputs(html, options) {
3012
3034
  await Promise.all(
3013
3035
  [...unique].map(
3014
3036
  ([filename, source]) => withMediaProbeSlot(
3015
- () => ensurePreparedJpeg(source, join6(cacheDir, filename), join6(outputDir, filename), options)
3037
+ () => ensurePreparedJpeg(source, join7(cacheDir, filename), join7(outputDir, filename), options)
3016
3038
  ).catch((error) => {
3017
3039
  if (!options.onFailure) throw error;
3018
3040
  failed.add(filename);
@@ -3024,8 +3046,8 @@ async function prepareHeifImageInputs(html, options) {
3024
3046
  if (failed.has(filename)) continue;
3025
3047
  const outputSrc = `${outputSrcPrefix}/${filename}`;
3026
3048
  img.setAttribute("src", outputSrc);
3027
- preparedAssets.set(outputSrc, join6(outputDir, filename));
3028
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join6(outputDir, filename) });
3049
+ preparedAssets.set(outputSrc, join7(outputDir, filename));
3050
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join7(outputDir, filename) });
3029
3051
  }
3030
3052
  return { html: document2.toString(), preparedAssets, preparedImages };
3031
3053
  }
@@ -3035,7 +3057,7 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
3035
3057
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
3036
3058
 
3037
3059
  // src/services/assetMediaType.ts
3038
- import { existsSync as existsSync6 } from "node:fs";
3060
+ import { existsSync as existsSync7 } from "node:fs";
3039
3061
  import {
3040
3062
  fingerprintElementId,
3041
3063
  isNotMediaPayload,
@@ -3108,7 +3130,7 @@ async function preflightCompositionAssetMediaTypes(input) {
3108
3130
  input.projectDir,
3109
3131
  input.compiledDir
3110
3132
  );
3111
- if (!existsSync6(resolvedPath)) continue;
3133
+ if (!existsSync7(resolvedPath)) continue;
3112
3134
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
3113
3135
  }
3114
3136
  const mismatches = [];
@@ -3361,8 +3383,8 @@ function detectShaderTransitionUsage(html) {
3361
3383
  async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes) {
3362
3384
  let filePath = src;
3363
3385
  if (isHttpUrl(src)) {
3364
- const remoteDir = join7(downloadDir, REMOTE_MEDIA_SUBDIR);
3365
- if (!existsSync7(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
3386
+ const remoteDir = join8(downloadDir, REMOTE_MEDIA_SUBDIR);
3387
+ if (!existsSync8(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
3366
3388
  try {
3367
3389
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
3368
3390
  onTelemetry: logRemoteDownloadTelemetry
@@ -3372,10 +3394,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
3372
3394
  }
3373
3395
  } else {
3374
3396
  filePath = decodedUrlPath2(src);
3375
- if (!filePath.startsWith("/")) filePath = join7(baseDir, filePath);
3397
+ if (!filePath.startsWith("/")) filePath = join8(baseDir, filePath);
3376
3398
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
3377
3399
  }
3378
- if (!isHttpUrl(filePath) && !existsSync7(filePath)) {
3400
+ if (!isHttpUrl(filePath) && !existsSync8(filePath)) {
3379
3401
  return { duration: null, resolvedPath: filePath };
3380
3402
  }
3381
3403
  const withSrcContext = (error) => {
@@ -3724,7 +3746,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
3724
3746
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
3725
3747
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
3726
3748
  // against its own directory, project-root refs stay as authored.
3727
- assetExists: (path) => existsSync7(resolve6(projectDir, path)),
3749
+ assetExists: (path) => existsSync8(resolve6(projectDir, path)),
3728
3750
  // Preserve the authored root wrapper as a child of the host, matching
3729
3751
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
3730
3752
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -3869,12 +3891,17 @@ async function inlineExternalScripts(html) {
3869
3891
  if (externalScripts.length === 0) return html;
3870
3892
  const downloads = await Promise.allSettled(
3871
3893
  externalScripts.map(async ({ el, src }) => {
3894
+ const integrity = el.getAttribute("integrity") || "";
3895
+ const bundled = bundledScript(src);
3896
+ if (bundled && matchesScriptIntegrity(bundled, integrity)) {
3897
+ return { src, text: new TextDecoder().decode(bundled) };
3898
+ }
3872
3899
  const response = await fetch(src, {
3873
3900
  signal: AbortSignal.timeout(15e3)
3874
3901
  });
3875
3902
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
3876
3903
  const bytes = new Uint8Array(await response.arrayBuffer());
3877
- if (!matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "")) {
3904
+ if (!matchesScriptIntegrity(bytes, integrity)) {
3878
3905
  throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
3879
3906
  }
3880
3907
  return { src, text: new TextDecoder().decode(bytes) };
@@ -3915,7 +3942,7 @@ function collectExternalAssets(html, projectDir) {
3915
3942
  if (isPathInside2(absPath, absProjectDir)) {
3916
3943
  return null;
3917
3944
  }
3918
- if (!existsSync7(absPath)) return null;
3945
+ if (!existsSync8(absPath)) return null;
3919
3946
  const safeKey = toExternalAssetKey(absPath);
3920
3947
  externalAssets.set(safeKey, absPath);
3921
3948
  return safeKey;
@@ -3965,7 +3992,7 @@ var REMOTE_SOURCE_TAG_RE = /<source\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+)["
3965
3992
  var REMOTE_IMG_TAG_RE = /<img\b[^>]*?(?<![\w-])src\s*=\s*["'](https?:\/\/[^"']+)["'][^>]*>/gi;
3966
3993
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
3967
3994
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
3968
- if (!existsSync7(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
3995
+ if (!existsSync8(remoteDir)) mkdirSync4(remoteDir, { recursive: true });
3969
3996
  const urlToLocal = /* @__PURE__ */ new Map();
3970
3997
  await Promise.all(
3971
3998
  [...urlSet].map(async (url) => {
@@ -4012,7 +4039,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
4012
4039
  return downloadAndRewriteUrls(
4013
4040
  urlSet,
4014
4041
  html,
4015
- join7(downloadDir, REMOTE_MEDIA_SUBDIR),
4042
+ join8(downloadDir, REMOTE_MEDIA_SUBDIR),
4016
4043
  "Remote media download failed",
4017
4044
  "Localized remote media source(s)"
4018
4045
  );
@@ -4027,7 +4054,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
4027
4054
  return downloadAndRewriteUrls(
4028
4055
  urlSet,
4029
4056
  html,
4030
- join7(downloadDir, REMOTE_MEDIA_SUBDIR),
4057
+ join8(downloadDir, REMOTE_MEDIA_SUBDIR),
4031
4058
  "Remote image download failed",
4032
4059
  "Localized remote image source(s)"
4033
4060
  );
@@ -4043,7 +4070,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
4043
4070
  return downloadAndRewriteUrls(
4044
4071
  urlSet,
4045
4072
  html,
4046
- join7(downloadDir, REMOTE_MEDIA_SUBDIR),
4073
+ join8(downloadDir, REMOTE_MEDIA_SUBDIR),
4047
4074
  "Remote background-image download failed",
4048
4075
  "Localized remote background-image(s)",
4049
4076
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -4148,13 +4175,13 @@ function projectStylesheetFontFamilies(html, projectDir) {
4148
4175
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
4149
4176
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
4150
4177
  const sheet = resolve6(projectDir, decodedUrlPath2(href).replace(/^(?:\.?\/)+/, ""));
4151
- if (!isPathInside2(sheet, projectDir) || !existsSync7(sheet)) continue;
4152
- for (const face of extractFontFaceBlocks(readFileSync4(sheet, "utf8"))) {
4178
+ if (!isPathInside2(sheet, projectDir) || !existsSync8(sheet)) continue;
4179
+ for (const face of extractFontFaceBlocks(readFileSync5(sheet, "utf8"))) {
4153
4180
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
4154
4181
  const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
4155
4182
  const path = decodedUrlPath2(url);
4156
4183
  const file = path.startsWith("/") ? resolve6(projectDir, `.${path}`) : resolve6(dirname6(sheet), path);
4157
- return isPathInside2(file, projectDir) && existsSync7(file);
4184
+ return isPathInside2(file, projectDir) && existsSync8(file);
4158
4185
  });
4159
4186
  if (family && shipsFile) families.push(family);
4160
4187
  }
@@ -4195,7 +4222,7 @@ function localizeFontFaceUrls(html, downloadDir) {
4195
4222
  return downloadAndRewriteUrls(
4196
4223
  collectFontFaceUrls(html),
4197
4224
  html,
4198
- join7(downloadDir, REMOTE_MEDIA_SUBDIR),
4225
+ join8(downloadDir, REMOTE_MEDIA_SUBDIR),
4199
4226
  "Remote font download failed",
4200
4227
  "Localized remote font face(s)",
4201
4228
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -4279,7 +4306,7 @@ async function embedLocalFontFaces(html, projectDir) {
4279
4306
  }
4280
4307
  function renderGsapDist() {
4281
4308
  try {
4282
- return gsapCdnDist(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
4309
+ return gsapCdnDist2(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
4283
4310
  } catch (cause) {
4284
4311
  throw new Error(
4285
4312
  "Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment",
@@ -4289,7 +4316,7 @@ function renderGsapDist() {
4289
4316
  }
4290
4317
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
4291
4318
  let gsapDist;
4292
- const exists = (path) => existsSync7(resolve6(projectDir, path));
4319
+ const exists = (path) => existsSync8(resolve6(projectDir, path));
4293
4320
  return html.replace(
4294
4321
  /(<script\b[^>]*\bsrc=["'])([^"']*gsap[^"']*\/dist\/([^"']+))(["'][^>]*>)/gi,
4295
4322
  (full, prefix, src, file, suffix) => {
@@ -4306,7 +4333,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
4306
4333
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
4307
4334
  if (!entryPath.includes("/")) return html;
4308
4335
  const { document: document2 } = parseHTML5(html);
4309
- const assetExists = (path) => existsSync7(resolve6(projectDir, path));
4336
+ const assetExists = (path) => existsSync8(resolve6(projectDir, path));
4310
4337
  rewriteAssetPaths(
4311
4338
  document2.querySelectorAll("[src], [href], [srcset]"),
4312
4339
  entryPath,
@@ -4872,11 +4899,11 @@ function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height,
4872
4899
  }
4873
4900
  function resolveEntryHtmlPath(input) {
4874
4901
  const { projectDir, workDir, entryFile, log } = input;
4875
- const htmlPath = join8(projectDir, entryFile);
4902
+ const htmlPath = join9(projectDir, entryFile);
4876
4903
  const rawEntry = readTextFile2(htmlPath);
4877
4904
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
4878
- const projectIndexPath = join8(projectDir, "index.html");
4879
- if (!existsSync8(projectIndexPath)) {
4905
+ const projectIndexPath = join9(projectDir, "index.html");
4906
+ if (!existsSync9(projectIndexPath)) {
4880
4907
  throw new Error(
4881
4908
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
4882
4909
  );
@@ -4891,11 +4918,19 @@ function resolveEntryHtmlPath(input) {
4891
4918
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
4892
4919
  );
4893
4920
  }
4894
- const wrapperPath = join8(workDir, "standalone-entry.html");
4921
+ const wrapperPath = join9(workDir, "standalone-entry.html");
4895
4922
  writeFileSync3(wrapperPath, standaloneHtml, "utf-8");
4896
4923
  log.info("Extracted standalone entry from index.html host context", { entryFile });
4897
4924
  return wrapperPath;
4898
4925
  }
4926
+ function applyChroma444Gate(cfg, chromaSubsampling, gate, log) {
4927
+ if (!cfg.useDrawElement || chromaSubsampling !== "444") return gate;
4928
+ cfg.useDrawElement = false;
4929
+ log.info(
4930
+ "[Render] Fast capture: chromaSubsampling 444 captures lossless PNG frames, so disabling drawElementImage for this render. Capture uses the platform's baseline route."
4931
+ );
4932
+ return "chroma_444";
4933
+ }
4899
4934
  async function runCompileStage(input) {
4900
4935
  const {
4901
4936
  projectDir,
@@ -4912,7 +4947,7 @@ async function runCompileStage(input) {
4912
4947
  } = input;
4913
4948
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log });
4914
4949
  const compileStart = Date.now();
4915
- const compiled = await compileForRender(projectDir, htmlPath, join8(workDir, "downloads"), {
4950
+ const compiled = await compileForRender(projectDir, htmlPath, join9(workDir, "downloads"), {
4916
4951
  log,
4917
4952
  failClosedFontFetch: failClosedFontFetch === true,
4918
4953
  allowSystemFontCapture,
@@ -4920,7 +4955,7 @@ async function runCompileStage(input) {
4920
4955
  variables: input.variables,
4921
4956
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
4922
4957
  pageMotionBlur: input.pageMotionBlur,
4923
- animatedGifCacheDir: cfg.extractCacheDir ? join8(cfg.extractCacheDir, "animated-gif") : void 0,
4958
+ animatedGifCacheDir: cfg.extractCacheDir ? join9(cfg.extractCacheDir, "animated-gif") : void 0,
4924
4959
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout
4925
4960
  });
4926
4961
  assertNotAborted();
@@ -4947,6 +4982,7 @@ async function runCompileStage(input) {
4947
4982
  "[Render] Fast capture: composition uses shader transitions, so disabling drawElementImage so page-side compositing stays available."
4948
4983
  );
4949
4984
  }
4985
+ deCompileGate = applyChroma444Gate(cfg, job.config.chromaSubsampling, deCompileGate, log);
4950
4986
  if (!cfg.useDrawElement && cfg.pageSideCompositingAutoDisabled) {
4951
4987
  cfg.enablePageSideCompositing = true;
4952
4988
  cfg.pageSideCompositingAutoDisabled = false;
@@ -4977,7 +5013,7 @@ async function runCompileStage(input) {
4977
5013
  };
4978
5014
  await preflightCompositionAssetMediaTypes({
4979
5015
  projectDir,
4980
- compiledDir: join8(workDir, "compiled"),
5016
+ compiledDir: join9(workDir, "compiled"),
4981
5017
  composition,
4982
5018
  signal: abortSignal
4983
5019
  });
@@ -5023,7 +5059,7 @@ async function runCompileStage(input) {
5023
5059
 
5024
5060
  // src/services/render/stages/probeStage.ts
5025
5061
  import { createHash as createHash5 } from "node:crypto";
5026
- import { basename as basename4, join as join9 } from "node:path";
5062
+ import { basename as basename4, join as join10 } from "node:path";
5027
5063
  import { parseHTML as parseHTML6 } from "linkedom";
5028
5064
  import {
5029
5065
  closeCaptureSession as closeCaptureSession4,
@@ -5058,11 +5094,19 @@ function isActionableProbeFailure(line) {
5058
5094
 
5059
5095
  // src/services/render/captureImageFormat.ts
5060
5096
  function resolveCaptureImageFormat(input) {
5061
- return input.needsAlpha || input.motionBlur ? "png" : "jpeg";
5097
+ return input.needsAlpha || input.motionBlur || input.chromaSubsampling === "444" ? "png" : "jpeg";
5062
5098
  }
5063
5099
  function resolveCaptureJpegQuality(quality) {
5064
5100
  return quality === "draft" ? 80 : 100;
5065
5101
  }
5102
+ function resolveCaptureSurface(input, quality) {
5103
+ const format = resolveCaptureImageFormat(input);
5104
+ return {
5105
+ format,
5106
+ quality: format === "png" ? void 0 : resolveCaptureJpegQuality(quality),
5107
+ transparent: input.needsAlpha
5108
+ };
5109
+ }
5066
5110
 
5067
5111
  // src/services/render/stages/probeStage.ts
5068
5112
  var FRAME_BOUNDARY_EPSILON = 1e-3;
@@ -5232,22 +5276,22 @@ async function runProbeStage(input) {
5232
5276
  });
5233
5277
  fileServer = await createFileServer({
5234
5278
  projectDir,
5235
- compiledDir: join9(workDir, "compiled"),
5279
+ compiledDir: join10(workDir, "compiled"),
5236
5280
  port: 0,
5237
5281
  preHeadScripts: [VIRTUAL_TIME_SHIM],
5238
5282
  fps: job.config.fps
5239
5283
  });
5240
5284
  assertNotAborted();
5241
5285
  const motionBlur = job.config.motionBlur;
5242
- const captureFormat = resolveCaptureImageFormat({ needsAlpha, motionBlur });
5243
5286
  const captureOpts = {
5244
5287
  recordReferenceBackground: input.recordReferenceBackground,
5245
5288
  width,
5246
5289
  height,
5247
5290
  fps: job.config.fps,
5248
- format: captureFormat,
5249
- transparent: needsAlpha,
5250
- quality: captureFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
5291
+ ...resolveCaptureSurface(
5292
+ { needsAlpha, motionBlur, chromaSubsampling: job.config.chromaSubsampling },
5293
+ job.config.quality
5294
+ ),
5251
5295
  variables: job.config.variables,
5252
5296
  deviceScaleFactor,
5253
5297
  motionBlur,
@@ -5262,7 +5306,7 @@ async function runProbeStage(input) {
5262
5306
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
5263
5307
  probeSession = await createCaptureSession4(
5264
5308
  fileServer.url,
5265
- join9(workDir, "probe"),
5309
+ join10(workDir, "probe"),
5266
5310
  captureOpts,
5267
5311
  null,
5268
5312
  probeCfg
@@ -5347,7 +5391,7 @@ async function runProbeStage(input) {
5347
5391
  });
5348
5392
  probeSession = await createCaptureSession4(
5349
5393
  fileServer.url,
5350
- join9(workDir, "probe-screenshot"),
5394
+ join10(workDir, "probe-screenshot"),
5351
5395
  captureOpts,
5352
5396
  null,
5353
5397
  { ...probeCfg, forceScreenshot: true }
@@ -5385,7 +5429,7 @@ async function runProbeStage(input) {
5385
5429
  compiled,
5386
5430
  resolutions,
5387
5431
  projectDir,
5388
- join9(workDir, "downloads")
5432
+ join10(workDir, "downloads")
5389
5433
  );
5390
5434
  assertNotAborted();
5391
5435
  composition.videos = compiled.videos;
@@ -5576,7 +5620,7 @@ async function runProbeStage(input) {
5576
5620
  }
5577
5621
  await preflightCompositionAssetMediaTypes({
5578
5622
  projectDir,
5579
- compiledDir: join9(workDir, "compiled"),
5623
+ compiledDir: join10(workDir, "compiled"),
5580
5624
  composition,
5581
5625
  signal: abortSignal
5582
5626
  });
@@ -5742,8 +5786,8 @@ function validateDistributedDuration(input) {
5742
5786
  }
5743
5787
 
5744
5788
  // src/services/render/stages/extractVideosStage.ts
5745
- import { existsSync as existsSync9 } from "node:fs";
5746
- import { join as join10 } from "node:path";
5789
+ import { existsSync as existsSync10 } from "node:fs";
5790
+ import { join as join11 } from "node:path";
5747
5791
  import {
5748
5792
  classifyVideoExtractionError,
5749
5793
  createFrameLookupTable as createFrameLookupTable3,
@@ -6017,7 +6061,7 @@ async function runExtractVideosStage(input) {
6017
6061
  const probeFailures = await Promise.all(
6018
6062
  composition.videos.map(async (v) => {
6019
6063
  const videoPath = resolveProjectRelativeSrc3(v.src, projectDir, compiledDir);
6020
- if (!existsSync9(videoPath)) return null;
6064
+ if (!existsSync10(videoPath)) return null;
6021
6065
  try {
6022
6066
  const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata3(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata3(videoPath), {
6023
6067
  signal: abortSignal,
@@ -6055,7 +6099,7 @@ async function runExtractVideosStage(input) {
6055
6099
  const probed = await Promise.all(
6056
6100
  composition.images.map(async (img) => {
6057
6101
  const imgPath = resolveProjectRelativeSrc3(img.src, projectDir, compiledDir);
6058
- if (!existsSync9(imgPath)) return null;
6102
+ if (!existsSync10(imgPath)) return null;
6059
6103
  const colorSpace = await probeColorSpaceSafely(imgPath, log);
6060
6104
  if (isHdrColorSpace2(colorSpace)) {
6061
6105
  nativeHdrImageIds.add(img.id);
@@ -6089,14 +6133,14 @@ async function runExtractVideosStage(input) {
6089
6133
  // because short boundary counts can differ by one frame.
6090
6134
  {
6091
6135
  fps: job.config.fps,
6092
- outputDir: join10(compiledDir, "__hyperframes_video_frames"),
6136
+ outputDir: join11(compiledDir, "__hyperframes_video_frames"),
6093
6137
  format: job.config.videoFrameFormat ?? "auto",
6094
6138
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
6095
6139
  timelineEnd: composition.duration,
6096
6140
  maxTransientRetries: extractionPolicy.maxTransientRetries,
6097
6141
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
6098
6142
  deferRangeExtraction,
6099
- contentKeyedDirs: [join10(compiledDir, REMOTE_MEDIA_SUBDIR)],
6143
+ contentKeyedDirs: [join11(compiledDir, REMOTE_MEDIA_SUBDIR)],
6100
6144
  urlByAbsentLocalPath,
6101
6145
  onProgress: ({ planned = 0, done = 0 }) => {
6102
6146
  framesPlanned += planned;
@@ -6175,7 +6219,7 @@ async function appendVideoAudioFromProbe(input) {
6175
6219
  videos.map(async (video) => {
6176
6220
  const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc3(video.src, projectDir, compiledDir);
6177
6221
  const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
6178
- if (!isHttpUrl2(readFrom) && !existsSync9(readFrom)) return null;
6222
+ if (!isHttpUrl2(readFrom) && !existsSync10(readFrom)) return null;
6179
6223
  const metadata = await extractMediaMetadata3(readFrom);
6180
6224
  const window2 = await resolveFinalFrameExtractionWindow2(
6181
6225
  readFrom,
@@ -6203,8 +6247,8 @@ import {
6203
6247
  } from "@hyperframes/engine";
6204
6248
 
6205
6249
  // src/services/render/stages/audioStage.ts
6206
- import { existsSync as existsSync11 } from "node:fs";
6207
- import { join as join13 } from "node:path";
6250
+ import { existsSync as existsSync12 } from "node:fs";
6251
+ import { join as join14 } from "node:path";
6208
6252
  import {
6209
6253
  MIXED_AUDIO_FILENAME,
6210
6254
  audioFailureDiagnostics,
@@ -6214,8 +6258,8 @@ import {
6214
6258
  } from "@hyperframes/engine";
6215
6259
 
6216
6260
  // src/services/render/audioDeliveryLimit.ts
6217
- import { existsSync as existsSync10 } from "node:fs";
6218
- import { dirname as dirname8, join as join12 } from "node:path";
6261
+ import { existsSync as existsSync11 } from "node:fs";
6262
+ import { dirname as dirname8, join as join13 } from "node:path";
6219
6263
  import {
6220
6264
  applyAudioFxChain,
6221
6265
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -6225,7 +6269,7 @@ import {
6225
6269
 
6226
6270
  // src/services/render/audioPadTrim.ts
6227
6271
  import { spawn } from "node:child_process";
6228
- import { dirname as dirname7, join as join11 } from "node:path";
6272
+ import { dirname as dirname7, join as join12 } from "node:path";
6229
6273
  import {
6230
6274
  DEFAULT_CONFIG,
6231
6275
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -6505,7 +6549,7 @@ async function constrainAacTruePeak(input) {
6505
6549
  }
6506
6550
  async function cutSource(input, scratchDir, attenuationDb) {
6507
6551
  if (!input.sourcePath || !input.rewriteSource) return true;
6508
- const cutPath = join11(scratchDir, "source.wav");
6552
+ const cutPath = join12(scratchDir, "source.wav");
6509
6553
  try {
6510
6554
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
6511
6555
  if (!result.success) throw new Error(result.error);
@@ -6520,7 +6564,7 @@ async function enforceAacTruePeak(input) {
6520
6564
  let scratchDir;
6521
6565
  try {
6522
6566
  scratchDir = createStagingDir3(dirname7(input.audioPath), ".true-peak-");
6523
- const correctedPath = join11(scratchDir, "audio.m4a");
6567
+ const correctedPath = join12(scratchDir, "audio.m4a");
6524
6568
  const measurements = [];
6525
6569
  let attenuationDb = 0;
6526
6570
  let sourcePeakDbfs;
@@ -6723,14 +6767,14 @@ async function limitDeliveryPeaks(input, deps = {
6723
6767
  applyChain: applyAudioFxChain,
6724
6768
  encode: encodeAac2,
6725
6769
  rename: renameWithRetry6,
6726
- sourceExists: existsSync10
6770
+ sourceExists: existsSync11
6727
6771
  }) {
6728
6772
  const { audioPath, sourcePath, signal, timeoutMs } = input;
6729
6773
  if (!deps.sourceExists(sourcePath)) return { success: true };
6730
6774
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
6731
6775
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
6732
6776
  const alternating = ["a", "b"].map(
6733
- (k) => join12(dirname8(sourcePath), `audio-source-limited-${k}.wav`)
6777
+ (k) => join13(dirname8(sourcePath), `audio-source-limited-${k}.wav`)
6734
6778
  );
6735
6779
  let encodedFrom;
6736
6780
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -6802,7 +6846,7 @@ function runAudioStage(input) {
6802
6846
  }
6803
6847
  async function runAudioStageScoped(input) {
6804
6848
  const stageStart = Date.now();
6805
- const pcmSourcePath = join13(input.workDir, "audio-source.wav");
6849
+ const pcmSourcePath = join14(input.workDir, "audio-source.wav");
6806
6850
  const duration = input.totalFrames * input.fps.den / input.fps.num;
6807
6851
  let deliverySourcePath;
6808
6852
  try {
@@ -6818,7 +6862,7 @@ async function runAudioStageScoped(input) {
6818
6862
  );
6819
6863
  audioLoweredDb = guard.loweredDb;
6820
6864
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
6821
- if (input.keepDeliverySource && !guard.sourceStale && existsSync11(pcmSourcePath)) {
6865
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync12(pcmSourcePath)) {
6822
6866
  deliverySourcePath = pcmSourcePath;
6823
6867
  }
6824
6868
  }
@@ -6867,7 +6911,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
6867
6911
  assertNotAborted,
6868
6912
  log
6869
6913
  } = input;
6870
- const audioOutputPath = join13(workDir, MIXED_AUDIO_FILENAME);
6914
+ const audioOutputPath = join14(workDir, MIXED_AUDIO_FILENAME);
6871
6915
  let hasAudio = false;
6872
6916
  let audioError;
6873
6917
  let audioFailures;
@@ -6878,7 +6922,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
6878
6922
  audioResult = await processCompositionAudio(
6879
6923
  audios,
6880
6924
  projectDir,
6881
- join13(workDir, "audio-work"),
6925
+ join14(workDir, "audio-work"),
6882
6926
  audioOutputPath,
6883
6927
  duration,
6884
6928
  abortSignal,
@@ -6946,8 +6990,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
6946
6990
  }
6947
6991
 
6948
6992
  // src/services/render/stages/captureStage.ts
6949
- import { existsSync as existsSync12, readdirSync, statfsSync } from "node:fs";
6950
- import { join as join14 } from "node:path";
6993
+ import { existsSync as existsSync13, readdirSync, statfsSync } from "node:fs";
6994
+ import { join as join15 } from "node:path";
6951
6995
  import {
6952
6996
  classifyCaptureFailure as classifyCaptureFailure2,
6953
6997
  frameFileExtension,
@@ -6998,16 +7042,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
6998
7042
  }
6999
7043
  function measureCaptureFrameBytes(workDir, framesDir) {
7000
7044
  let total = sampleDirectoryBytes(framesDir);
7001
- if (!existsSync12(workDir)) return total;
7045
+ if (!existsSync13(workDir)) return total;
7002
7046
  for (const attempt of readdirSync(workDir)) {
7003
7047
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
7004
- total += sampleDirectoryBytes(join14(workDir, attempt));
7048
+ total += sampleDirectoryBytes(join15(workDir, attempt));
7005
7049
  continue;
7006
7050
  }
7007
7051
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
7008
- const attemptDir = join14(workDir, attempt);
7052
+ const attemptDir = join15(workDir, attempt);
7009
7053
  for (const name of readdirSync(attemptDir)) {
7010
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join14(attemptDir, name));
7054
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join15(attemptDir, name));
7011
7055
  }
7012
7056
  }
7013
7057
  return total;
@@ -7339,16 +7383,16 @@ import {
7339
7383
  // src/services/render/stages/encodeStage.ts
7340
7384
  import {
7341
7385
  copyFileSync as copyFileSync4,
7342
- existsSync as existsSync13,
7386
+ existsSync as existsSync14,
7343
7387
  mkdirSync as mkdirSync5,
7344
7388
  readdirSync as readdirSync2,
7345
- readFileSync as readFileSync5,
7389
+ readFileSync as readFileSync6,
7346
7390
  rmSync as rmSync4,
7347
7391
  statSync as statSync4,
7348
7392
  writeFileSync as writeFileSync4
7349
7393
  } from "node:fs";
7350
7394
  import { readFile as readFile2 } from "node:fs/promises";
7351
- import { dirname as dirname9, join as join15 } from "node:path";
7395
+ import { dirname as dirname9, join as join16 } from "node:path";
7352
7396
  import {
7353
7397
  encodeFramesChunkedConcat,
7354
7398
  encodeFramesFromDir,
@@ -7436,7 +7480,7 @@ async function reencodeWithClearedWholeFrames(argsInput, run, startTime) {
7436
7480
  const error = formatFfmpegError(result.exitCode, result.stderr);
7437
7481
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
7438
7482
  }
7439
- const gif = readFileSync5(outputPath);
7483
+ const gif = readFileSync6(outputPath);
7440
7484
  if (!clearGifFramesBeforeNext(gif)) {
7441
7485
  const error = "[FFmpeg] GIF output could not be parsed to clear its frames";
7442
7486
  return gifEncodeFailure(startTime, outputPath, error);
@@ -7469,11 +7513,11 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
7469
7513
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
7470
7514
  }
7471
7515
  }
7472
- if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync5(outputPath)) !== false) {
7516
+ if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync6(outputPath)) !== false) {
7473
7517
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
7474
7518
  if (failure) return failure;
7475
7519
  }
7476
- const fileSize = existsSync13(outputPath) ? statSync4(outputPath).size : 0;
7520
+ const fileSize = existsSync14(outputPath) ? statSync4(outputPath).size : 0;
7477
7521
  return {
7478
7522
  success: true,
7479
7523
  outputPath,
@@ -7559,7 +7603,7 @@ function encodeWhileCapturing(input, totalFrames) {
7559
7603
  await new Promise((resolve10) => wake = resolve10);
7560
7604
  }
7561
7605
  if (signal.aborted) return;
7562
- const mergedPath = join15(input.framesDir, formatCaptureFrameName(next, "jpg"));
7606
+ const mergedPath = join16(input.framesDir, formatCaptureFrameName(next, "jpg"));
7563
7607
  const frame = await readLandedFrame(landed.get(next), mergedPath);
7564
7608
  landed.delete(next);
7565
7609
  if (!await stream.writeFrame(frame)) {
@@ -7634,7 +7678,7 @@ async function runEncodeStage(input) {
7634
7678
  const stage5Start = Date.now();
7635
7679
  if (isPngSequence) {
7636
7680
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
7637
- if (!existsSync13(outputPath)) mkdirSync5(outputPath, { recursive: true });
7681
+ if (!existsSync14(outputPath)) mkdirSync5(outputPath, { recursive: true });
7638
7682
  const captured = readdirSync2(framesDir).filter((name) => name.endsWith(".png")).sort();
7639
7683
  if (captured.length === 0) {
7640
7684
  throw new Error(
@@ -7642,11 +7686,11 @@ async function runEncodeStage(input) {
7642
7686
  );
7643
7687
  }
7644
7688
  captured.forEach((name, i) => {
7645
- const dst = join15(outputPath, formatExportFrameName(i, "png"));
7646
- copyFileSync4(join15(framesDir, name), dst);
7689
+ const dst = join16(outputPath, formatExportFrameName(i, "png"));
7690
+ copyFileSync4(join16(framesDir, name), dst);
7647
7691
  });
7648
- if (hasAudio && audioOutputPath && existsSync13(audioOutputPath)) {
7649
- copyFileSync4(audioOutputPath, join15(outputPath, MIXED_AUDIO_FILENAME2));
7692
+ if (hasAudio && audioOutputPath && existsSync14(audioOutputPath)) {
7693
+ copyFileSync4(audioOutputPath, join16(outputPath, MIXED_AUDIO_FILENAME2));
7650
7694
  log.info(
7651
7695
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
7652
7696
  );
@@ -7666,7 +7710,7 @@ async function runEncodeStage(input) {
7666
7710
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
7667
7711
  fps: job.config.fps,
7668
7712
  loop,
7669
- palettePath: join15(dirname9(videoOnlyPath), "gif-palette.png"),
7713
+ palettePath: join16(dirname9(videoOnlyPath), "gif-palette.png"),
7670
7714
  preserveAlpha: needsAlpha,
7671
7715
  signal: abortSignal,
7672
7716
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -7725,7 +7769,7 @@ function sampleDirectoryBytes(dir) {
7725
7769
  continue;
7726
7770
  }
7727
7771
  for (const name of entries) {
7728
- const full = join16(current, name);
7772
+ const full = join17(current, name);
7729
7773
  try {
7730
7774
  const st = statSync5(full);
7731
7775
  if (st.isDirectory()) {
@@ -7807,8 +7851,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
7807
7851
  const ranges = [];
7808
7852
  let rangeStart = null;
7809
7853
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
7810
- const framePath = join16(framesDir, formatCaptureFrameName(frameIndex, frameExt));
7811
- const missing = !existsSync14(framePath) || statSync5(framePath).size <= 8;
7854
+ const framePath = join17(framesDir, formatCaptureFrameName(frameIndex, frameExt));
7855
+ const missing = !existsSync15(framePath) || statSync5(framePath).size <= 8;
7812
7856
  if (missing && rangeStart === null) {
7813
7857
  rangeStart = frameIndex;
7814
7858
  } else if (!missing && rangeStart !== null) {
@@ -7824,7 +7868,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
7824
7868
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
7825
7869
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
7826
7870
  const batches = [];
7827
- const outputDirFor = (batchIndex, workerId) => join16(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
7871
+ const outputDirFor = (batchIndex, workerId) => join17(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
7828
7872
  if (stride > 1) {
7829
7873
  const spans = /* @__PURE__ */ new Map();
7830
7874
  for (const range of ranges) {
@@ -7874,13 +7918,20 @@ function captureAttemptMadeProgress(attemptTargetFrameCount, remainingFrameCount
7874
7918
  return remainingFrameCount < attemptTargetFrameCount;
7875
7919
  }
7876
7920
  var FIRST_FRAME_STALL_MS = 3e5;
7921
+ var FIRST_FRAME_STARTUP_FACTOR = 2;
7922
+ var FIRST_FRAME_STALL_CEILING_MS = 9e5;
7877
7923
  var TAIL_STALL_MS = FIRST_FRAME_STALL_MS;
7878
- function frameStallRule(job, totalFrames) {
7924
+ function firstFrameWindowMs(probeStartupMs) {
7925
+ const fromStartup = (probeStartupMs ?? 0) * FIRST_FRAME_STARTUP_FACTOR;
7926
+ if (!Number.isFinite(fromStartup)) return FIRST_FRAME_STALL_MS;
7927
+ return Math.max(FIRST_FRAME_STALL_MS, Math.min(FIRST_FRAME_STALL_CEILING_MS, fromStartup));
7928
+ }
7929
+ function frameStallRule(job, totalFrames, probeStartupMs) {
7879
7930
  const noProgressMs = resolveCaptureStallTimeoutMs();
7880
7931
  return {
7881
7932
  progress: () => job.framesRendered ?? 0,
7882
7933
  noProgressMs,
7883
- firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
7934
+ firstProgressMs: Math.max(firstFrameWindowMs(probeStartupMs), noProgressMs),
7884
7935
  complete: () => (job.framesRendered ?? 0) >= totalFrames,
7885
7936
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
7886
7937
  detail: () => describeWorkerPhases(job),
@@ -7897,8 +7948,8 @@ function isRecoverableParallelCaptureError(error) {
7897
7948
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
7898
7949
  let captured = 0;
7899
7950
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
7900
- const framePath = join16(framesDir, formatCaptureFrameName(frameIndex, frameExt));
7901
- if (existsSync14(framePath)) captured++;
7951
+ const framePath = join17(framesDir, formatCaptureFrameName(frameIndex, frameExt));
7952
+ if (existsSync15(framePath)) captured++;
7902
7953
  }
7903
7954
  return captured;
7904
7955
  }
@@ -7923,7 +7974,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
7923
7974
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
7924
7975
  });
7925
7976
  pendingTransientRetry = false;
7926
- const attemptWorkDir = join16(options.workDir, `capture-attempt-${attempt}`);
7977
+ const attemptWorkDir = join17(options.workDir, `capture-attempt-${attempt}`);
7927
7978
  const batches = missingRanges ? buildMissingFrameRetryBatches(
7928
7979
  missingRanges,
7929
7980
  currentWorkers,
@@ -8116,7 +8167,7 @@ function explainStreamingEncodeGate(cfg, outputFormat, workerCount, durationSeco
8116
8167
  var DEFAULT_SEGMENTED_MIN_SECONDS = Number.POSITIVE_INFINITY;
8117
8168
 
8118
8169
  // src/services/distributed/planFrameCost.ts
8119
- import { join as join19 } from "node:path";
8170
+ import { join as join20 } from "node:path";
8120
8171
  import {
8121
8172
  closeCaptureSession as closeCaptureSession9,
8122
8173
  createCaptureSession as createCaptureSession9,
@@ -8125,17 +8176,18 @@ import {
8125
8176
  } from "@hyperframes/engine";
8126
8177
 
8127
8178
  // src/services/distributed/chunkFrames.ts
8128
- import { existsSync as existsSync16, readdirSync as readdirSync4 } from "node:fs";
8129
- import { extname as extname2, join as join18 } from "node:path";
8179
+ import { existsSync as existsSync17, readdirSync as readdirSync4 } from "node:fs";
8180
+ import { extname as extname2, join as join19 } from "node:path";
8130
8181
  import {
8131
8182
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
8132
- createVideoFrameInjector as createVideoFrameInjector3
8183
+ createVideoFrameInjector as createVideoFrameInjector3,
8184
+ mediaIdPathSegment as mediaIdPathSegment3
8133
8185
  } from "@hyperframes/engine";
8134
8186
 
8135
8187
  // src/services/distributed/shared.ts
8136
8188
  import { execFile as execFileCallback } from "node:child_process";
8137
- import { dirname as dirname11, join as join17 } from "node:path";
8138
- import { existsSync as existsSync15, readFileSync as readFileSync6 } from "node:fs";
8189
+ import { dirname as dirname11, join as join18 } from "node:path";
8190
+ import { existsSync as existsSync16, readFileSync as readFileSync7 } from "node:fs";
8139
8191
  import { fileURLToPath as fileURLToPath3 } from "node:url";
8140
8192
  import { promisify as promisify2 } from "node:util";
8141
8193
  import {
@@ -8150,8 +8202,8 @@ function isPlanAudioArtifactPath(path) {
8150
8202
  }
8151
8203
  function resolvePlanAudioPath(planDir) {
8152
8204
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
8153
- const candidate = join17(planDir, name);
8154
- if (existsSync15(candidate)) return candidate;
8205
+ const candidate = join18(planDir, name);
8206
+ if (existsSync16(candidate)) return candidate;
8155
8207
  }
8156
8208
  return null;
8157
8209
  }
@@ -8411,10 +8463,10 @@ function readProducerVersion() {
8411
8463
  const startDir = dirname11(fileURLToPath3(import.meta.url));
8412
8464
  let current = startDir;
8413
8465
  for (let i = 0; i < 10; i++) {
8414
- const candidate = join17(current, "package.json");
8415
- if (existsSync15(candidate)) {
8466
+ const candidate = join18(current, "package.json");
8467
+ if (existsSync16(candidate)) {
8416
8468
  try {
8417
- const pkg = JSON.parse(readFileSync6(candidate, "utf-8"));
8469
+ const pkg = JSON.parse(readFileSync7(candidate, "utf-8"));
8418
8470
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
8419
8471
  cachedProducerVersion = pkg.version;
8420
8472
  return pkg.version;
@@ -8466,8 +8518,8 @@ function frameNumberFromFileName(name) {
8466
8518
  function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v1") {
8467
8519
  const result = [];
8468
8520
  for (const v of videos) {
8469
- const outputDir = join18(planDir, "video-frames", v.videoId);
8470
- if (!existsSync16(outputDir)) {
8521
+ const outputDir = join19(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
8522
+ if (!existsSync17(outputDir)) {
8471
8523
  throw new Error(
8472
8524
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
8473
8525
  );
@@ -8485,7 +8537,7 @@ function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v
8485
8537
  if (!frameName) continue;
8486
8538
  const frameNumber = indexMode === "sparse-v2" ? frameNumberFromFileName(frameName) : null;
8487
8539
  const frameIndex = frameNumber === null ? i : frameNumber - 1;
8488
- framePaths.set(frameIndex, join18(outputDir, frameName));
8540
+ framePaths.set(frameIndex, join19(outputDir, frameName));
8489
8541
  }
8490
8542
  result.push({
8491
8543
  videoId: v.videoId,
@@ -8565,8 +8617,8 @@ async function extractDeferredVideoFramesForChunk(input) {
8565
8617
  sourceOf: (video) => {
8566
8618
  const range = planned.get(video.videoId).deferredRange;
8567
8619
  const remoteUrl = remoteSources[range.sourcePath];
8568
- const sourcePath = remoteUrl ?? join18(input.planDir, ...range.sourcePath.split("/"));
8569
- if (remoteUrl === void 0 && !existsSync16(sourcePath)) {
8620
+ const sourcePath = remoteUrl ?? join19(input.planDir, ...range.sourcePath.split("/"));
8621
+ if (remoteUrl === void 0 && !existsSync17(sourcePath)) {
8570
8622
  throw new RenderChunkValidationError(
8571
8623
  MISSING_PLAN_ARTIFACT,
8572
8624
  `[renderChunk] planDir is missing the source for video ${JSON.stringify(video.videoId)}: ${range.sourcePath}`
@@ -8596,12 +8648,12 @@ async function measurePlanSecondsPerFrame(input) {
8596
8648
  planVideos,
8597
8649
  frames: sampled,
8598
8650
  fps: fpsRatio,
8599
- outputRoot: join19(workDir, "frame-cost-video-frames"),
8651
+ outputRoot: join20(workDir, "frame-cost-video-frames"),
8600
8652
  cfg: input.cfg
8601
8653
  })
8602
8654
  ];
8603
8655
  const lookup = extracted.length > 0 ? createFrameLookupTable4(planVideos.videos, extracted, resolveRenderFpsConfig(fpsRatio).value) : null;
8604
- const compiledDir = join19(planDir, "compiled");
8656
+ const compiledDir = join20(planDir, "compiled");
8605
8657
  const fileServer = await createFileServer({
8606
8658
  projectDir: compiledDir,
8607
8659
  compiledDir,
@@ -8613,7 +8665,7 @@ async function measurePlanSecondsPerFrame(input) {
8613
8665
  try {
8614
8666
  session = await createCaptureSession9(
8615
8667
  fileServer.url,
8616
- join19(workDir, "frame-cost"),
8668
+ join20(workDir, "frame-cost"),
8617
8669
  buildChunkCaptureOptions({
8618
8670
  dimensions: { ...input, fpsNum: fps, fpsDen: 1 },
8619
8671
  encoder: input,
@@ -8710,7 +8762,7 @@ function buildWeightedChunkSlices(weights, chunkCount, minFrames, maxFrames) {
8710
8762
  }
8711
8763
 
8712
8764
  // src/services/render/planReferenceBackground.ts
8713
- import { join as join20 } from "node:path";
8765
+ import { join as join21 } from "node:path";
8714
8766
  import {
8715
8767
  closeCaptureSession as closeCaptureSession10,
8716
8768
  createCaptureSession as createCaptureSession10,
@@ -8723,14 +8775,14 @@ async function readPlanReferenceBackground(input) {
8723
8775
  try {
8724
8776
  server = await createFileServer({
8725
8777
  projectDir: input.projectDir,
8726
- compiledDir: join20(input.workDir, "compiled"),
8778
+ compiledDir: join21(input.workDir, "compiled"),
8727
8779
  port: 0,
8728
8780
  preHeadScripts: [VIRTUAL_TIME_SHIM],
8729
8781
  fps: input.options.fps
8730
8782
  });
8731
8783
  session = await createCaptureSession10(
8732
8784
  server.url,
8733
- join20(input.workDir, "reference"),
8785
+ join21(input.workDir, "reference"),
8734
8786
  {
8735
8787
  ...input.options,
8736
8788
  requiresWebGpu: false
@@ -8766,8 +8818,8 @@ async function readPlanReferenceBackground(input) {
8766
8818
  }
8767
8819
 
8768
8820
  // src/services/render/stages/freezePlan.ts
8769
- import { existsSync as existsSync17, mkdirSync as mkdirSync7, readFileSync as readFileSync7, readdirSync as readdirSync5, writeFileSync as writeFileSync6 } from "node:fs";
8770
- import { join as join21, relative as relative3, resolve as resolve8 } from "node:path";
8821
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, readFileSync as readFileSync8, readdirSync as readdirSync5, writeFileSync as writeFileSync6 } from "node:fs";
8822
+ import { join as join22, relative as relative3, resolve as resolve8 } from "node:path";
8771
8823
  import {
8772
8824
  REFERENCE_BACKGROUND_FIELD,
8773
8825
  referenceBackgroundResult as referenceBackgroundResult3
@@ -8960,7 +9012,7 @@ function planFileSha256(absolutePath, digests) {
8960
9012
  return sha256;
8961
9013
  }
8962
9014
  async function prehashPlanFiles(dir, digests) {
8963
- if (!existsSync17(dir)) return;
9015
+ if (!existsSync18(dir)) return;
8964
9016
  for (const { absolutePath } of listPlanFiles(dir)) {
8965
9017
  if (!digests.has(absolutePath)) digests.set(absolutePath, await sha256FileAsync(absolutePath));
8966
9018
  }
@@ -8985,7 +9037,7 @@ function listPlanFiles(planDir) {
8985
9037
  function walk(dir) {
8986
9038
  const entries = readdirSync5(dir, { withFileTypes: true });
8987
9039
  for (const entry of entries) {
8988
- const full = join21(dir, entry.name);
9040
+ const full = join22(dir, entry.name);
8989
9041
  if (entry.isDirectory()) {
8990
9042
  walk(full);
8991
9043
  } else if (entry.isFile()) {
@@ -9006,7 +9058,7 @@ function collectPlanAssetShas(planDir, digests) {
9006
9058
  const assets = [];
9007
9059
  for (const file of files) {
9008
9060
  if (file.planRelativePath === COMPILED_INDEX_RELATIVE_PATH) {
9009
- compositionHtml = readFileSync7(file.absolutePath);
9061
+ compositionHtml = readFileSync8(file.absolutePath);
9010
9062
  continue;
9011
9063
  }
9012
9064
  if (HASH_EXCLUDED_PLAN_FILES.has(file.planRelativePath)) continue;
@@ -9026,23 +9078,23 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
9026
9078
  function writePlanRemoteFiles(planDir, files) {
9027
9079
  if (files.length === 0) return;
9028
9080
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
9029
- writeFileSync6(join21(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
9081
+ writeFileSync6(join22(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
9030
9082
  }
9031
9083
  function readPlanRemoteFiles(planDir) {
9032
- const path = join21(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
9033
- return existsSync17(path) ? JSON.parse(readFileSync7(path, "utf-8")) : [];
9084
+ const path = join22(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
9085
+ return existsSync18(path) ? JSON.parse(readFileSync8(path, "utf-8")) : [];
9034
9086
  }
9035
9087
  function recomputePlanHashFromPlanDir(planDir, digests) {
9036
- const planJsonPath = join21(planDir, "plan.json");
9037
- const encoderJsonPath = join21(planDir, "meta", "encoder.json");
9038
- if (!existsSync17(planJsonPath)) {
9088
+ const planJsonPath = join22(planDir, "plan.json");
9089
+ const encoderJsonPath = join22(planDir, "meta", "encoder.json");
9090
+ if (!existsSync18(planJsonPath)) {
9039
9091
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
9040
9092
  }
9041
- if (!existsSync17(encoderJsonPath)) {
9093
+ if (!existsSync18(encoderJsonPath)) {
9042
9094
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
9043
9095
  }
9044
- const planJson = JSON.parse(readFileSync7(planJsonPath, "utf-8"));
9045
- const encoderConfigCanonicalJson = readFileSync7(encoderJsonPath, "utf-8");
9096
+ const planJson = JSON.parse(readFileSync8(planJsonPath, "utf-8"));
9097
+ const encoderConfigCanonicalJson = readFileSync8(encoderJsonPath, "utf-8");
9046
9098
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
9047
9099
  return computePlanHash({
9048
9100
  compositionHtml,
@@ -9068,21 +9120,21 @@ async function freezePlan(input) {
9068
9120
  hasAudio,
9069
9121
  digests
9070
9122
  } = input;
9071
- if (!existsSync17(planDir)) {
9123
+ if (!existsSync18(planDir)) {
9072
9124
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
9073
9125
  }
9074
- const metaDir = join21(planDir, "meta");
9075
- if (!existsSync17(metaDir)) mkdirSync7(metaDir, { recursive: true });
9126
+ const metaDir = join22(planDir, "meta");
9127
+ if (!existsSync18(metaDir)) mkdirSync7(metaDir, { recursive: true });
9076
9128
  writeFileSync6(
9077
- join21(metaDir, "composition.json"),
9129
+ join22(metaDir, "composition.json"),
9078
9130
  `${JSON.stringify(composition, null, 2)}
9079
9131
  `,
9080
9132
  "utf-8"
9081
9133
  );
9082
9134
  const encoderForCanonical = stripUndefined(encoder);
9083
9135
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
9084
- writeFileSync6(join21(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
9085
- writeFileSync6(join21(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
9136
+ writeFileSync6(join22(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
9137
+ writeFileSync6(join22(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
9086
9138
  `, "utf-8");
9087
9139
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
9088
9140
  const planHash = computePlanHash({
@@ -9107,7 +9159,7 @@ async function freezePlan(input) {
9107
9159
  duration: durationSeconds,
9108
9160
  hasAudio
9109
9161
  };
9110
- const planJsonPath = join21(planDir, "plan.json");
9162
+ const planJsonPath = join22(planDir, "plan.json");
9111
9163
  writeFileSync6(planJsonPath, `${JSON.stringify(planJson, null, 2)}
9112
9164
  `, "utf-8");
9113
9165
  return { planJsonPath, planHash };
@@ -9149,16 +9201,16 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
9149
9201
  }
9150
9202
 
9151
9203
  // src/services/distributed/chunkAudio.ts
9152
- import { closeSync as closeSync4, existsSync as existsSync18, ftruncateSync, mkdirSync as mkdirSync9, openSync as openSync4, readFileSync as readFileSync8 } from "node:fs";
9204
+ import { closeSync as closeSync4, existsSync as existsSync19, ftruncateSync, mkdirSync as mkdirSync9, openSync as openSync4, readFileSync as readFileSync9 } from "node:fs";
9153
9205
  import { writeFileSync as writeFileSync7, writeSync } from "node:fs";
9154
- import { join as join23 } from "node:path";
9206
+ import { join as join24 } from "node:path";
9155
9207
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
9156
9208
 
9157
9209
  // src/services/distributed/mp4Stitch.ts
9158
9210
  import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync8, rmSync as rmSync6 } from "node:fs";
9159
9211
  import { open } from "node:fs/promises";
9160
9212
  import { renameWithRetry as renameWithRetry7 } from "@hyperframes/engine";
9161
- import { basename as basename5, dirname as dirname12, join as join22 } from "node:path";
9213
+ import { basename as basename5, dirname as dirname12, join as join23 } from "node:path";
9162
9214
  import { finished, pipeline } from "node:stream/promises";
9163
9215
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
9164
9216
  function boxAt(src, off, at, limit) {
@@ -9525,13 +9577,13 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
9525
9577
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
9526
9578
  mkdirSync8(dirname12(outputPath), { recursive: true });
9527
9579
  const workDir = createStagingDir4(dirname12(outputPath), `${basename5(outputPath)}.stitch-`);
9528
- const out = createWriteStream(join22(workDir, "out.mp4"));
9580
+ const out = createWriteStream(join23(workDir, "out.mp4"));
9529
9581
  try {
9530
9582
  out.write(header);
9531
9583
  for (const [i, path] of sourcePaths.entries()) await copyPayload(path, layouts[i], i, out);
9532
9584
  out.end();
9533
9585
  await finished(out);
9534
- renameWithRetry7(join22(workDir, "out.mp4"), outputPath);
9586
+ renameWithRetry7(join23(workDir, "out.mp4"), outputPath);
9535
9587
  } finally {
9536
9588
  out.destroy();
9537
9589
  rmSync6(workDir, { recursive: true, force: true });
@@ -9623,9 +9675,9 @@ async function writeChunkAudioSlices(input) {
9623
9675
  offset += track.sizes[offsets.length - 1];
9624
9676
  }
9625
9677
  });
9626
- const bytes = readFileSync8(input.audioPath);
9678
+ const bytes = readFileSync9(input.audioPath);
9627
9679
  const layout = { sizeBytes: bytes.length, payloadStart, payloadEnd, partStarts: {} };
9628
- mkdirSync9(join23(input.planDir, SLICE_DIR), { recursive: true });
9680
+ mkdirSync9(join24(input.planDir, SLICE_DIR), { recursive: true });
9629
9681
  input.chunks.forEach((_, index) => {
9630
9682
  const cut = audioCutForChunk(grid, input.chunks, index, input.fps);
9631
9683
  if (!cut) return;
@@ -9633,17 +9685,17 @@ async function writeChunkAudioSlices(input) {
9633
9685
  const start = offsets[cut.firstPacket];
9634
9686
  layout.partStarts[index] = start;
9635
9687
  const end = offsets[last] + track.sizes[last];
9636
- writeFileSync7(join23(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
9688
+ writeFileSync7(join24(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
9637
9689
  });
9638
9690
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
9639
- writeFileSync7(join23(input.planDir, SLICE_FRAME), Buffer.concat(frame));
9640
- writeFileSync7(join23(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
9691
+ writeFileSync7(join24(input.planDir, SLICE_FRAME), Buffer.concat(frame));
9692
+ writeFileSync7(join24(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
9641
9693
  }
9642
9694
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
9643
- const layoutPath = join23(planDir, SLICE_LAYOUT);
9644
- if (!existsSync18(layoutPath)) return resolvePlanAudioPath(planDir);
9645
- const layout = JSON.parse(readFileSync8(layoutPath, "utf-8"));
9646
- const frame = readFileSync8(join23(planDir, SLICE_FRAME));
9695
+ const layoutPath = join24(planDir, SLICE_LAYOUT);
9696
+ if (!existsSync19(layoutPath)) return resolvePlanAudioPath(planDir);
9697
+ const layout = JSON.parse(readFileSync9(layoutPath, "utf-8"));
9698
+ const frame = readFileSync9(join24(planDir, SLICE_FRAME));
9647
9699
  const fd = openSync4(scratchPath, "w");
9648
9700
  try {
9649
9701
  writeSync(fd, frame, 0, layout.payloadStart, 0);
@@ -9656,7 +9708,7 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
9656
9708
  );
9657
9709
  const start = layout.partStarts[chunkIndex];
9658
9710
  if (start !== void 0) {
9659
- const part = readFileSync8(join23(planDir, chunkAudioSlicePath(chunkIndex)));
9711
+ const part = readFileSync9(join24(planDir, chunkAudioSlicePath(chunkIndex)));
9660
9712
  writeSync(fd, part, 0, part.length, start);
9661
9713
  }
9662
9714
  ftruncateSync(fd, layout.sizeBytes);
@@ -9712,7 +9764,7 @@ async function muxChunkWithAudio(input) {
9712
9764
  // src/services/distributed/planSize.ts
9713
9765
  import { createHash as createHash7 } from "node:crypto";
9714
9766
  import { lstatSync, readdirSync as readdirSync6 } from "node:fs";
9715
- import { extname as extname3, join as join24, relative as relative4 } from "node:path";
9767
+ import { extname as extname3, join as join25, relative as relative4 } from "node:path";
9716
9768
  var MAX_TOP_COMPONENTS = 10;
9717
9769
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
9718
9770
  ".aac",
@@ -9824,7 +9876,7 @@ function walkRegularFiles(dir, visit) {
9824
9876
  return;
9825
9877
  }
9826
9878
  for (const entry of entries) {
9827
- const full = join24(dir, entry.name);
9879
+ const full = join25(dir, entry.name);
9828
9880
  if (entry.isDirectory()) {
9829
9881
  walkRegularFiles(full, visit);
9830
9882
  } else if (entry.isFile()) {
@@ -10044,13 +10096,13 @@ function assertPositiveInteger(name, value) {
10044
10096
  }
10045
10097
  var FREEZE_OWNED_PLAN_FILES = [
10046
10098
  "plan.json",
10047
- join25("meta", "composition.json"),
10048
- join25("meta", "encoder.json"),
10049
- join25("meta", "chunks.json")
10099
+ join26("meta", "composition.json"),
10100
+ join26("meta", "encoder.json"),
10101
+ join26("meta", "chunks.json")
10050
10102
  ];
10051
10103
  function removeFreezeOwnedPlanFiles(planDir) {
10052
10104
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
10053
- rmSync7(join25(planDir, relativePath), { force: true });
10105
+ rmSync7(join26(planDir, relativePath), { force: true });
10054
10106
  }
10055
10107
  }
10056
10108
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -10205,19 +10257,19 @@ function createVideoSourceShipper(input) {
10205
10257
  const known = shipped.get(srcPath);
10206
10258
  if (known) return known;
10207
10259
  const stagedRel = pathInside(input.workVideoFramesDir, srcPath);
10208
- const current = stagedRel === null ? srcPath : join25(input.planDir, "video-frames", stagedRel);
10260
+ const current = stagedRel === null ? srcPath : join26(input.planDir, "video-frames", stagedRel);
10209
10261
  let result = null;
10210
10262
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
10211
10263
  const rel = pathInside(root, srcPath);
10212
- if (rel !== null && (existsSync19(join25(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
10264
+ if (rel !== null && (existsSync20(join26(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
10213
10265
  result = ["compiled", ...rel.split(sep3)].join("/");
10214
10266
  break;
10215
10267
  }
10216
10268
  }
10217
10269
  if (result === null) {
10218
10270
  result = `video-sources/${shipped.size}${extname4(current)}`;
10219
- const destination = join25(input.planDir, ...result.split("/"));
10220
- mkdirSync10(join25(input.planDir, "video-sources"), { recursive: true });
10271
+ const destination = join26(input.planDir, ...result.split("/"));
10272
+ mkdirSync10(join26(input.planDir, "video-sources"), { recursive: true });
10221
10273
  try {
10222
10274
  linkSync(current, destination);
10223
10275
  } catch {
@@ -10237,7 +10289,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
10237
10289
  useGpu: false,
10238
10290
  browserGpuMode: "software"
10239
10291
  });
10240
- if (!existsSync19(planDir)) mkdirSync10(planDir, { recursive: true });
10292
+ if (!existsSync20(planDir)) mkdirSync10(planDir, { recursive: true });
10241
10293
  const log = config.logger ?? defaultLogger;
10242
10294
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
10243
10295
  const abortSignal = config.abortSignal;
@@ -10267,14 +10319,14 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
10267
10319
  pageMotionBlur: config.pageMotionBlur
10268
10320
  });
10269
10321
  const entryFile = config.entryFile ?? "index.html";
10270
- const htmlPath = join25(projectDir, entryFile);
10271
- if (!existsSync19(htmlPath)) {
10322
+ const htmlPath = join26(projectDir, entryFile);
10323
+ if (!existsSync20(htmlPath)) {
10272
10324
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
10273
10325
  }
10274
- const workDir = join25(planDir, ".plan-work");
10326
+ const workDir = join26(planDir, ".plan-work");
10275
10327
  rmSync7(workDir, { recursive: true, force: true });
10276
10328
  mkdirSync10(workDir, { recursive: true });
10277
- const compiledDir = join25(workDir, "compiled");
10329
+ const compiledDir = join26(workDir, "compiled");
10278
10330
  mkdirSync10(compiledDir, { recursive: true });
10279
10331
  let stageStarted = Date.now();
10280
10332
  cpSync2(projectDir, compiledDir, {
@@ -10288,10 +10340,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
10288
10340
  }
10289
10341
  });
10290
10342
  logPlanStage(log, "copy", stageStarted);
10291
- const finalCompiledDir = join25(planDir, "compiled");
10343
+ const finalCompiledDir = join26(planDir, "compiled");
10292
10344
  const needsAlpha = outputNeedsAlpha(config.format);
10293
10345
  const remoteFiles = Object.entries(options.remoteFiles ?? {});
10294
- const remoteLocalPath = (rel) => join25(projectDir, ...rel.split("/"));
10346
+ const remoteLocalPath = (rel) => join26(projectDir, ...rel.split("/"));
10295
10347
  for (const [, file] of remoteFiles) {
10296
10348
  declareContentAddressedUrl(file.url, file.sha256);
10297
10349
  if (file.probeFactsUrl) declareProbeFactsUrl(file.url, file.probeFactsUrl);
@@ -10494,17 +10546,17 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
10494
10546
  let stageStarted = Date.now();
10495
10547
  const extractResult = await extractPlanVideos(c, options.deferVideoExtraction);
10496
10548
  logPlanStage(log, "extract", stageStarted);
10497
- const stagedVideoFrames = join25(compiledDir, "__hyperframes_video_frames");
10498
- const videoFramesDst = join25(planDir, "video-frames");
10499
- if (existsSync19(videoFramesDst)) rmSync7(videoFramesDst, { recursive: true, force: true });
10500
- const videoSourcesDir = join25(planDir, "video-sources");
10549
+ const stagedVideoFrames = join26(compiledDir, "__hyperframes_video_frames");
10550
+ const videoFramesDst = join26(planDir, "video-frames");
10551
+ if (existsSync20(videoFramesDst)) rmSync7(videoFramesDst, { recursive: true, force: true });
10552
+ const videoSourcesDir = join26(planDir, "video-sources");
10501
10553
  rmSync7(videoSourcesDir, { recursive: true, force: true });
10502
- if (existsSync19(stagedVideoFrames)) {
10554
+ if (existsSync20(stagedVideoFrames)) {
10503
10555
  renameWithRetry8(stagedVideoFrames, videoFramesDst);
10504
10556
  } else {
10505
10557
  mkdirSync10(videoFramesDst, { recursive: true });
10506
10558
  }
10507
- if (existsSync19(finalCompiledDir)) rmSync7(finalCompiledDir, { recursive: true, force: true });
10559
+ if (existsSync20(finalCompiledDir)) rmSync7(finalCompiledDir, { recursive: true, force: true });
10508
10560
  renameWithRetry8(compiledDir, finalCompiledDir);
10509
10561
  const shipVideoSource = createVideoSourceShipper({
10510
10562
  planDir,
@@ -10534,7 +10586,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
10534
10586
  };
10535
10587
  })
10536
10588
  });
10537
- mkdirSync10(join25(planDir, "meta"), { recursive: true });
10589
+ mkdirSync10(join26(planDir, "meta"), { recursive: true });
10538
10590
  writePlanRemoteFiles(
10539
10591
  planDir,
10540
10592
  remoteFiles.map(([rel, { sha256, sizeBytes }]) => ({
@@ -10544,7 +10596,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
10544
10596
  }))
10545
10597
  );
10546
10598
  writeFileSync8(
10547
- join25(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
10599
+ join26(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
10548
10600
  JSON.stringify(planVideosJson, null, 2),
10549
10601
  "utf-8"
10550
10602
  );
@@ -10624,11 +10676,11 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
10624
10676
  if (audioResult?.audioError) {
10625
10677
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
10626
10678
  }
10627
- const planAudioPath = join25(planDir, PLAN_AUDIO_RELATIVE_PATH);
10628
- if (audioResult?.hasAudio && existsSync19(audioResult.audioOutputPath)) {
10679
+ const planAudioPath = join26(planDir, PLAN_AUDIO_RELATIVE_PATH);
10680
+ if (audioResult?.hasAudio && existsSync20(audioResult.audioOutputPath)) {
10629
10681
  renameWithRetry8(audioResult.audioOutputPath, planAudioPath);
10630
10682
  }
10631
- if (chunksCarryAudio && existsSync19(planAudioPath)) {
10683
+ if (chunksCarryAudio && existsSync20(planAudioPath)) {
10632
10684
  if (options.sliceChunkAudio) {
10633
10685
  stageStarted = Date.now();
10634
10686
  await writeChunkAudioSlices({
@@ -10741,7 +10793,7 @@ async function buildPlanAudio(projectDir, config, workRoot, outputPath, options
10741
10793
  if (mixed.audioError) {
10742
10794
  applyDistributedAudioWarningPolicy(c.job, mixed.audioError, mixed.audioFailures, c.log);
10743
10795
  }
10744
- if (!mixed.hasAudio || !existsSync19(mixed.audioOutputPath)) return { hasAudio: false };
10796
+ if (!mixed.hasAudio || !existsSync20(mixed.audioOutputPath)) return { hasAudio: false };
10745
10797
  renameWithRetry8(mixed.audioOutputPath, outputPath);
10746
10798
  return { hasAudio: true };
10747
10799
  } finally {
@@ -10756,24 +10808,28 @@ import {
10756
10808
  } from "@hyperframes/engine";
10757
10809
  import {
10758
10810
  copyFileSync as copyFileSync8,
10759
- existsSync as existsSync21,
10811
+ existsSync as existsSync22,
10760
10812
  lstatSync as lstatSync2,
10761
10813
  mkdirSync as mkdirSync12,
10762
- readFileSync as readFileSync9,
10814
+ readFileSync as readFileSync10,
10763
10815
  readdirSync as readdirSync7,
10764
10816
  rmSync as rmSync9,
10765
10817
  statSync as statSync7,
10766
10818
  writeFileSync as writeFileSync10
10767
10819
  } from "node:fs";
10768
10820
  import { tmpdir } from "node:os";
10769
- import { dirname as dirname14, isAbsolute as isAbsolute4, join as join28, relative as relative6, resolve as resolve9, sep as sep4 } from "node:path";
10821
+ import { dirname as dirname14, isAbsolute as isAbsolute4, join as join29, relative as relative6, resolve as resolve9, sep as sep4 } from "node:path";
10770
10822
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
10771
- import { createFrameLookupTable as createFrameLookupTable5, renameWithRetry as renameWithRetry10 } from "@hyperframes/engine";
10823
+ import {
10824
+ createFrameLookupTable as createFrameLookupTable5,
10825
+ mediaIdPathSegment as mediaIdPathSegment4,
10826
+ renameWithRetry as renameWithRetry10
10827
+ } from "@hyperframes/engine";
10772
10828
 
10773
10829
  // src/services/distributed/planV2Publisher.ts
10774
10830
  import {
10775
10831
  copyFileSync as copyFileSync7,
10776
- existsSync as existsSync20,
10832
+ existsSync as existsSync21,
10777
10833
  linkSync as linkSync2,
10778
10834
  mkdirSync as mkdirSync11,
10779
10835
  rmSync as rmSync8,
@@ -10781,7 +10837,7 @@ import {
10781
10837
  writeFileSync as writeFileSync9
10782
10838
  } from "node:fs";
10783
10839
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
10784
- import { dirname as dirname13, join as join27 } from "node:path";
10840
+ import { dirname as dirname13, join as join28 } from "node:path";
10785
10841
 
10786
10842
  // src/services/distributed/planV2Errors.ts
10787
10843
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -10796,7 +10852,7 @@ var PlanV2IntegrityError = class extends Error {
10796
10852
  };
10797
10853
 
10798
10854
  // src/services/distributed/planV2Layout.ts
10799
- import { join as join26 } from "node:path";
10855
+ import { join as join27 } from "node:path";
10800
10856
  var SHA256_PATTERN = /^[0-9a-f]{64}$/;
10801
10857
  function assertPlanV2Sha256(value, field) {
10802
10858
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
@@ -10806,7 +10862,7 @@ function assertPlanV2Sha256(value, field) {
10806
10862
  }
10807
10863
  function planV2BlobPath(root, sha256) {
10808
10864
  const digest = assertPlanV2Sha256(sha256, "artifact sha256");
10809
- return join26(root, "artifacts", "sha256", digest.slice(0, 2), digest);
10865
+ return join27(root, "artifacts", "sha256", digest.slice(0, 2), digest);
10810
10866
  }
10811
10867
 
10812
10868
  // src/services/distributed/planV2Publisher.ts
@@ -10842,7 +10898,7 @@ var LocalPlanV2ArtifactPublisher = class {
10842
10898
  #linkFile;
10843
10899
  #committed = false;
10844
10900
  constructor(destinationDir, options = {}) {
10845
- if (existsSync20(destinationDir)) {
10901
+ if (existsSync21(destinationDir)) {
10846
10902
  throw new PlanV2IntegrityError(`output directory already exists: ${destinationDir}`);
10847
10903
  }
10848
10904
  this.destinationDir = destinationDir;
@@ -10859,10 +10915,10 @@ var LocalPlanV2ArtifactPublisher = class {
10859
10915
  );
10860
10916
  }
10861
10917
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
10862
- if (existsSync20(destinationPath)) return;
10918
+ if (existsSync21(destinationPath)) return;
10863
10919
  mkdirSync11(dirname13(destinationPath), { recursive: true });
10864
10920
  const stagingDir = createStagingDir5(dirname13(destinationPath), ".plan-v2-blob-");
10865
- const temporaryPath = join27(stagingDir, "blob");
10921
+ const temporaryPath = join28(stagingDir, "blob");
10866
10922
  try {
10867
10923
  try {
10868
10924
  this.#linkFile(blob.sourcePath, temporaryPath);
@@ -10877,13 +10933,13 @@ var LocalPlanV2ArtifactPublisher = class {
10877
10933
  }
10878
10934
  async commitManifest(manifestBytes) {
10879
10935
  for (const digest of new Set(manifestDigests(manifestBytes))) {
10880
- if (!existsSync20(planV2BlobPath(this.temporaryDir, digest))) {
10936
+ if (!existsSync21(planV2BlobPath(this.temporaryDir, digest))) {
10881
10937
  throw new PlanV2IntegrityError(
10882
10938
  `cannot commit manifest before referenced blob is durable: ${digest}`
10883
10939
  );
10884
10940
  }
10885
10941
  }
10886
- writeFileSync9(join27(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
10942
+ writeFileSync9(join28(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
10887
10943
  renameWithRetry9(this.temporaryDir, this.destinationDir);
10888
10944
  this.#committed = true;
10889
10945
  }
@@ -10909,7 +10965,7 @@ function isNonNegativeIntegerArray(value) {
10909
10965
  return Array.isArray(value) && value.every((item) => typeof item === "number" && Number.isInteger(item) && item >= 0);
10910
10966
  }
10911
10967
  function readJsonFile(path, label) {
10912
- const contents = readFileSync9(path, "utf-8");
10968
+ const contents = readFileSync10(path, "utf-8");
10913
10969
  try {
10914
10970
  const parsed = JSON.parse(contents);
10915
10971
  return parsed;
@@ -10929,7 +10985,7 @@ function listFiles(root) {
10929
10985
  const rootResolved = resolve9(root);
10930
10986
  function walk(dir) {
10931
10987
  for (const entry of readdirSync7(dir, { withFileTypes: true })) {
10932
- const absolutePath = join28(dir, entry.name);
10988
+ const absolutePath = join29(dir, entry.name);
10933
10989
  if (entry.isDirectory()) {
10934
10990
  walk(absolutePath);
10935
10991
  } else if (entry.isFile()) {
@@ -10956,13 +11012,13 @@ function assertValidExtractionCacheCompleteSentinel(path) {
10956
11012
  }
10957
11013
  }
10958
11014
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
10959
- const videoRoot = join28(executionPlanDir, "video-frames");
10960
- if (!existsSync21(videoRoot)) return;
11015
+ const videoRoot = join29(executionPlanDir, "video-frames");
11016
+ if (!existsSync22(videoRoot)) return;
10961
11017
  for (const videoEntry of readdirSync7(videoRoot, { withFileTypes: true })) {
10962
11018
  if (!videoEntry.isDirectory()) continue;
10963
- const videoDir = join28(videoRoot, videoEntry.name);
11019
+ const videoDir = join29(videoRoot, videoEntry.name);
10964
11020
  if (readdirSync7(videoDir).includes(EXTRACTION_CACHE_COMPLETE_SENTINEL)) {
10965
- const sentinelPath = join28(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
11021
+ const sentinelPath = join29(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
10966
11022
  assertValidExtractionCacheCompleteSentinel(sentinelPath);
10967
11023
  }
10968
11024
  }
@@ -10973,7 +11029,7 @@ function isExtractionCacheCompleteSentinelPath(path) {
10973
11029
  }
10974
11030
  function resolveExtractedVideoOutputDir(planDir, videoId) {
10975
11031
  const videoRoot = resolve9(planDir, "video-frames");
10976
- const outputDir = resolve9(videoRoot, videoId);
11032
+ const outputDir = resolve9(videoRoot, mediaIdPathSegment4(videoId));
10977
11033
  if (outputDir === videoRoot || !outputDir.startsWith(`${videoRoot}${sep4}`)) {
10978
11034
  throw new PlanV2IntegrityError(`unsafe extracted video id: ${JSON.stringify(videoId)}`);
10979
11035
  }
@@ -11009,7 +11065,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
11009
11065
  if (video.deferredRange) {
11010
11066
  const framePaths2 = /* @__PURE__ */ new Map();
11011
11067
  for (let index = 0; index < video.totalFrames; index++) {
11012
- framePaths2.set(index, join28(outputDir, String(index)));
11068
+ framePaths2.set(index, join29(outputDir, String(index)));
11013
11069
  }
11014
11070
  return { ...video, outputDir, framePaths: framePaths2, ownedByLookup: false };
11015
11071
  }
@@ -11017,7 +11073,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
11017
11073
  const framePaths = /* @__PURE__ */ new Map();
11018
11074
  for (const frameName of frameNames) {
11019
11075
  if (frameName === EXTRACTION_CACHE_COMPLETE_SENTINEL) {
11020
- assertValidExtractionCacheCompleteSentinel(join28(outputDir, frameName));
11076
+ assertValidExtractionCacheCompleteSentinel(join29(outputDir, frameName));
11021
11077
  continue;
11022
11078
  }
11023
11079
  const match = /(\d+)(?=\.[^.]+$)/.exec(frameName);
@@ -11036,7 +11092,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
11036
11092
  `duplicate extracted frame index ${frameIndex} in ${outputDir}`
11037
11093
  );
11038
11094
  }
11039
- framePaths.set(frameIndex, join28(outputDir, frameName));
11095
+ framePaths.set(frameIndex, join29(outputDir, frameName));
11040
11096
  }
11041
11097
  return {
11042
11098
  ...video,
@@ -11057,8 +11113,8 @@ function parsePlanVideosJson2(value) {
11057
11113
  }
11058
11114
  }
11059
11115
  function materializeExtractedVideoDirectories(planDir) {
11060
- const videosPath = join28(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
11061
- if (!existsSync21(videosPath)) return;
11116
+ const videosPath = join29(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
11117
+ if (!existsSync22(videosPath)) return;
11062
11118
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
11063
11119
  for (const video of videos.extracted) {
11064
11120
  mkdirSync12(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
@@ -11091,13 +11147,13 @@ function parseChunkSlices(value) {
11091
11147
  });
11092
11148
  }
11093
11149
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
11094
- const videoRoot = join28(executionPlanDir, "video-frames");
11095
- const hasExtractedFrames = existsSync21(videoRoot) && listFiles(videoRoot).length > 0;
11096
- const videosPath = join28(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
11097
- if (!existsSync21(videosPath)) {
11150
+ const videoRoot = join29(executionPlanDir, "video-frames");
11151
+ const hasExtractedFrames = existsSync22(videoRoot) && listFiles(videoRoot).length > 0;
11152
+ const videosPath = join29(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
11153
+ if (!existsSync22(videosPath)) {
11098
11154
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
11099
11155
  }
11100
- const chunksPath = join28(executionPlanDir, "meta", "chunks.json");
11156
+ const chunksPath = join29(executionPlanDir, "meta", "chunks.json");
11101
11157
  const videos = readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH);
11102
11158
  const chunks = readJsonFile(chunksPath, "meta/chunks.json");
11103
11159
  const parsedVideos = parsePlanVideosJson2(videos);
@@ -11151,10 +11207,10 @@ function computeManifestHash(manifest) {
11151
11207
  return sha256Hex(`${PLAN_V2_HASH_PREFIX}${canonicalJsonStringify(manifestPayload(manifest))}`);
11152
11208
  }
11153
11209
  function writeBlob(sourcePath, destinationPath) {
11154
- if (existsSync21(destinationPath)) return;
11210
+ if (existsSync22(destinationPath)) return;
11155
11211
  mkdirSync12(dirname14(destinationPath), { recursive: true });
11156
11212
  const temporaryDir = createStagingDir6(dirname14(destinationPath), ".plan-v2-blob-");
11157
- const temporaryPath = join28(temporaryDir, "blob");
11213
+ const temporaryPath = join29(temporaryDir, "blob");
11158
11214
  try {
11159
11215
  copyFileSync8(sourcePath, temporaryPath);
11160
11216
  renameWithRetry10(temporaryPath, destinationPath);
@@ -11190,8 +11246,8 @@ async function putTasks(tasks) {
11190
11246
  if (failure) throw failure.reason;
11191
11247
  }
11192
11248
  function buildPlanV2Publication(executionPlanDir, digests) {
11193
- const executionPlanPath = join28(executionPlanDir, "plan.json");
11194
- if (!existsSync21(executionPlanPath)) {
11249
+ const executionPlanPath = join29(executionPlanDir, "plan.json");
11250
+ if (!existsSync22(executionPlanPath)) {
11195
11251
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
11196
11252
  }
11197
11253
  const executionPlanValue = readJsonFile(executionPlanPath, "execution plan.json");
@@ -11218,7 +11274,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
11218
11274
  }
11219
11275
  validateExtractionCacheCompleteSentinels(executionPlanDir);
11220
11276
  const videoDependencyPlan = buildVideoChunkDependencies(executionPlanDir, dimensions);
11221
- const encoder = readJsonFile(join28(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
11277
+ const encoder = readJsonFile(join29(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
11222
11278
  const files = listFiles(executionPlanDir);
11223
11279
  const chunkAudio = !isRecord3(encoder) || encoder.chunksCarryAudio !== true ? "none" : files.some((file) => chunkAudioSliceTarget(file.path) !== null) ? "sliced" : "whole";
11224
11280
  for (const file of files) {
@@ -11271,7 +11327,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
11271
11327
  };
11272
11328
  }
11273
11329
  function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
11274
- if (existsSync21(planV2Dir)) {
11330
+ if (existsSync22(planV2Dir)) {
11275
11331
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
11276
11332
  }
11277
11333
  const publication = buildPlanV2Publication(executionPlanDir);
@@ -11285,7 +11341,7 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
11285
11341
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
11286
11342
  }
11287
11343
  writeFileSync10(
11288
- join28(tempDir, "plan.json"),
11344
+ join29(tempDir, "plan.json"),
11289
11345
  canonicalJsonStringify(publication.manifest),
11290
11346
  "utf-8"
11291
11347
  );
@@ -11337,7 +11393,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
11337
11393
  // artifactTargets ships every compiled/ file to all chunks, so each is in the manifest.
11338
11394
  whileAudioMixes: () => putBlobs(
11339
11395
  publisher,
11340
- listFiles(join28(stagingRoot, "compiled")).map(
11396
+ listFiles(join29(stagingRoot, "compiled")).map(
11341
11397
  (file) => publishBlobFor(file.absolutePath, digests)
11342
11398
  )
11343
11399
  ),
@@ -11357,7 +11413,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
11357
11413
  }
11358
11414
  }
11359
11415
  async function planV2(projectDir, config, planV2Dir) {
11360
- if (existsSync21(planV2Dir)) {
11416
+ if (existsSync22(planV2Dir)) {
11361
11417
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
11362
11418
  }
11363
11419
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
@@ -11374,7 +11430,7 @@ function resultFromManifest(planV2Dir, manifest) {
11374
11430
  isRecord3(executionPlan) ? executionPlan[REFERENCE_BACKGROUND_FIELD3] : void 0
11375
11431
  ),
11376
11432
  planDir: planV2Dir,
11377
- manifestPath: join28(planV2Dir, "plan.json"),
11433
+ manifestPath: join29(planV2Dir, "plan.json"),
11378
11434
  planProtocol: PLAN_PROTOCOL_V2,
11379
11435
  planHash: manifest.planHash,
11380
11436
  sourcePlanV1Hash: getPlanV2ExecutionPlanHash(manifest),
@@ -11510,8 +11566,8 @@ function parsePlanV2Manifest(value) {
11510
11566
  return parsed;
11511
11567
  }
11512
11568
  function readPlanV2Manifest(planV2Dir) {
11513
- const manifestPath = join28(planV2Dir, "plan.json");
11514
- if (!existsSync21(manifestPath)) {
11569
+ const manifestPath = join29(planV2Dir, "plan.json");
11570
+ if (!existsSync22(manifestPath)) {
11515
11571
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
11516
11572
  }
11517
11573
  const value = readJsonFile(manifestPath, "v2 manifest");
@@ -11530,7 +11586,7 @@ function listPlanV2ArtifactsForTarget(manifest, target) {
11530
11586
  }
11531
11587
  function verifyBlob(planV2Dir, artifact) {
11532
11588
  const sourcePath = planV2BlobPath(planV2Dir, artifact.sha256);
11533
- if (!existsSync21(sourcePath)) {
11589
+ if (!existsSync22(sourcePath)) {
11534
11590
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
11535
11591
  }
11536
11592
  const stats = statSync7(sourcePath);
@@ -11543,7 +11599,7 @@ function verifyBlob(planV2Dir, artifact) {
11543
11599
  return sourcePath;
11544
11600
  }
11545
11601
  function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}) {
11546
- if (existsSync21(destinationDir)) {
11602
+ if (existsSync22(destinationDir)) {
11547
11603
  throw new PlanV2IntegrityError(`materialization destination already exists: ${destinationDir}`);
11548
11604
  }
11549
11605
  const manifest = readPlanV2Manifest(planV2Dir);
@@ -11559,13 +11615,13 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
11559
11615
  const tempDir = createStagingDir6(dirname14(destinationDir), ".plan-v2-materialize-");
11560
11616
  try {
11561
11617
  for (const { artifact, sourcePath } of verified) {
11562
- const destinationPath = join28(tempDir, ...artifact.path.split("/"));
11618
+ const destinationPath = join29(tempDir, ...artifact.path.split("/"));
11563
11619
  mkdirSync12(dirname14(destinationPath), { recursive: true });
11564
11620
  copyFileSync8(sourcePath, destinationPath);
11565
11621
  }
11566
11622
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
11567
11623
  writeFileSync10(
11568
- join28(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
11624
+ join29(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
11569
11625
  canonicalJsonStringify({
11570
11626
  manifest,
11571
11627
  target,
@@ -11588,7 +11644,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
11588
11644
  // Join the artifact's OWN name, not the current constant: a plan written
11589
11645
  // before the container change carries the legacy name, and materializing it
11590
11646
  // under the new one would point at a file that was never written.
11591
- audioPath: target.role === "assembler" ? audioArtifact ? join28(destinationDir, audioArtifact.path) : null : null
11647
+ audioPath: target.role === "assembler" ? audioArtifact ? join29(destinationDir, audioArtifact.path) : null : null
11592
11648
  };
11593
11649
  }
11594
11650
  function assertRemoteSources(remoteSources, artifacts) {
@@ -11607,8 +11663,8 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
11607
11663
  return readValidatedPlanV2Materialization(planDir, expectedTarget)?.manifest ?? null;
11608
11664
  }
11609
11665
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
11610
- const markerPath = join28(planDir, PLAN_V2_MATERIALIZATION_MARKER);
11611
- if (!existsSync21(markerPath)) return null;
11666
+ const markerPath = join29(planDir, PLAN_V2_MATERIALIZATION_MARKER);
11667
+ if (!existsSync22(markerPath)) return null;
11612
11668
  const marker = readJsonFile(markerPath, "materialization marker");
11613
11669
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
11614
11670
  throw new PlanV2IntegrityError("malformed materialization marker");
@@ -11625,8 +11681,8 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
11625
11681
  assertRemoteSources(remoteSources, required);
11626
11682
  for (const artifact of required) {
11627
11683
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
11628
- const path = join28(planDir, ...artifact.path.split("/"));
11629
- if (!existsSync21(path) || statSync7(path).size !== artifact.sizeBytes) {
11684
+ const path = join29(planDir, ...artifact.path.split("/"));
11685
+ if (!existsSync22(path) || statSync7(path).size !== artifact.sizeBytes) {
11630
11686
  throw new PlanV2IntegrityError(
11631
11687
  `materialized artifact missing or truncated: ${artifact.path}`
11632
11688
  );
@@ -11641,7 +11697,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
11641
11697
  // src/services/distributed/planV2Execution.ts
11642
11698
  import { mkdtempSync, rmSync as rmSync12 } from "node:fs";
11643
11699
  import { tmpdir as tmpdir2 } from "node:os";
11644
- import { join as join31 } from "node:path";
11700
+ import { join as join32 } from "node:path";
11645
11701
 
11646
11702
  // src/services/distributed/assemble.ts
11647
11703
  import {
@@ -11650,15 +11706,15 @@ import {
11650
11706
  } from "@hyperframes/engine";
11651
11707
  import {
11652
11708
  cpSync as cpSync3,
11653
- existsSync as existsSync22,
11709
+ existsSync as existsSync23,
11654
11710
  mkdirSync as mkdirSync13,
11655
- readFileSync as readFileSync10,
11711
+ readFileSync as readFileSync11,
11656
11712
  readdirSync as readdirSync8,
11657
11713
  rmSync as rmSync10,
11658
11714
  statSync as statSync8,
11659
11715
  writeFileSync as writeFileSync11
11660
11716
  } from "node:fs";
11661
- import { basename as basename6, dirname as dirname15, join as join29 } from "node:path";
11717
+ import { basename as basename6, dirname as dirname15, join as join30 } from "node:path";
11662
11718
  import {
11663
11719
  appendRateCapArgs as appendRateCapArgs2,
11664
11720
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
@@ -11705,7 +11761,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
11705
11761
  }
11706
11762
  const format = plan.dimensions.format;
11707
11763
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
11708
- if (!existsSync22(dirname15(outputPath))) {
11764
+ if (!existsSync23(dirname15(outputPath))) {
11709
11765
  mkdirSync13(dirname15(outputPath), { recursive: true });
11710
11766
  }
11711
11767
  const workDir = createStagingDir7(dirname15(outputPath), `${basename6(outputPath)}.assemble-work-`);
@@ -11728,8 +11784,8 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
11728
11784
  };
11729
11785
  try {
11730
11786
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
11731
- const finalPath = join29(workDir, `output.${format}`);
11732
- const audio = audioPath !== null && existsSync22(audioPath) ? audioPath : null;
11787
+ const finalPath = join30(workDir, `output.${format}`);
11788
+ const audio = audioPath !== null && existsSync23(audioPath) ? audioPath : null;
11733
11789
  await writeJoined(ctx, videoSources, audio, finalPath);
11734
11790
  renameWithRetry11(finalPath, outputPath);
11735
11791
  log.info("[assemble] stage timings", {
@@ -11747,7 +11803,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
11747
11803
  });
11748
11804
  }
11749
11805
  }
11750
- const fileSize = existsSync22(outputPath) ? statSync8(outputPath).size : 0;
11806
+ const fileSize = existsSync23(outputPath) ? statSync8(outputPath).size : 0;
11751
11807
  return {
11752
11808
  ...referenceBackgroundResult6(plan[REFERENCE_BACKGROUND_FIELD4]),
11753
11809
  outputPath,
@@ -11757,18 +11813,18 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
11757
11813
  };
11758
11814
  }
11759
11815
  function readAssemblePlan(planDir, chunkPaths) {
11760
- const planJsonPath = join29(planDir, "plan.json");
11761
- const chunksJsonPath = join29(planDir, "meta", "chunks.json");
11762
- if (!existsSync22(planJsonPath)) {
11816
+ const planJsonPath = join30(planDir, "plan.json");
11817
+ const chunksJsonPath = join30(planDir, "meta", "chunks.json");
11818
+ if (!existsSync23(planJsonPath)) {
11763
11819
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
11764
11820
  }
11765
- const plan = JSON.parse(readFileSync10(planJsonPath, "utf-8"));
11821
+ const plan = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
11766
11822
  readPlanProtocolV1(plan, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
11767
11823
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
11768
- if (!existsSync22(chunksJsonPath)) {
11824
+ if (!existsSync23(chunksJsonPath)) {
11769
11825
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
11770
11826
  }
11771
- const chunks = JSON.parse(readFileSync10(chunksJsonPath, "utf-8"));
11827
+ const chunks = JSON.parse(readFileSync11(chunksJsonPath, "utf-8"));
11772
11828
  if (chunkPaths.length !== chunks.length) {
11773
11829
  throw new Error(
11774
11830
  `[assemble] chunkPaths length (${chunkPaths.length}) does not match chunks.json length (${chunks.length}). Adapters must pass one path per chunk, ordered by index.`
@@ -11780,7 +11836,7 @@ function readAssemblePlan(planDir, chunkPaths) {
11780
11836
  }
11781
11837
  }
11782
11838
  for (const path of chunkPaths.flat()) {
11783
- if (!existsSync22(path)) {
11839
+ if (!existsSync23(path)) {
11784
11840
  throw new Error(`[assemble] chunk path does not exist: ${path}`);
11785
11841
  }
11786
11842
  }
@@ -11809,7 +11865,7 @@ function cfrEncodeArgs(inputArgs, encoder, fpsArg) {
11809
11865
  return args;
11810
11866
  }
11811
11867
  async function reencodeCfr(ctx, chunkPaths, encoder) {
11812
- const cfrOutputPath = join29(ctx.workDir, `cfr.${ctx.format}`);
11868
+ const cfrOutputPath = join30(ctx.workDir, `cfr.${ctx.format}`);
11813
11869
  const cfrArgs = cfrEncodeArgs(videoInputArgs(ctx, chunkPaths), encoder, ctx.fpsArg);
11814
11870
  appendRenderProvenanceArgs2(cfrArgs, cfrOutputPath);
11815
11871
  cfrArgs.push("-y", cfrOutputPath);
@@ -11836,7 +11892,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
11836
11892
  );
11837
11893
  return;
11838
11894
  }
11839
- const paddedAudioPath = join29(ctx.workDir, "audio-padded.m4a");
11895
+ const paddedAudioPath = join30(ctx.workDir, "audio-padded.m4a");
11840
11896
  const padTrimResult = await ctx.timed(
11841
11897
  "audioMs",
11842
11898
  () => padOrTrimAudioToVideoFrameCount({
@@ -11876,7 +11932,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
11876
11932
  }
11877
11933
  }
11878
11934
  function concatDemuxerInput(chunkPaths, workDir, fpsArg) {
11879
- const listPath = join29(workDir, "concat-list.txt");
11935
+ const listPath = join30(workDir, "concat-list.txt");
11880
11936
  const body = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
11881
11937
  writeFileSync11(listPath, `${body}
11882
11938
  `, "utf-8");
@@ -11914,13 +11970,13 @@ function stitchesSeparateAudio(planDir) {
11914
11970
  return lockedAudio(planDir).separateAudio === true;
11915
11971
  }
11916
11972
  function planFormat(planDir) {
11917
- const plan = JSON.parse(readFileSync10(join29(planDir, "plan.json"), "utf-8"));
11973
+ const plan = JSON.parse(readFileSync11(join30(planDir, "plan.json"), "utf-8"));
11918
11974
  return plan.dimensions.format;
11919
11975
  }
11920
11976
  function lockedAudio(planDir) {
11921
- const encoderJsonPath = join29(planDir, "meta", "encoder.json");
11922
- if (!existsSync22(encoderJsonPath)) return {};
11923
- return JSON.parse(readFileSync10(encoderJsonPath, "utf-8"));
11977
+ const encoderJsonPath = join30(planDir, "meta", "encoder.json");
11978
+ if (!existsSync23(encoderJsonPath)) return {};
11979
+ return JSON.parse(readFileSync11(encoderJsonPath, "utf-8"));
11924
11980
  }
11925
11981
  function readCfrEncoder(planDir, format) {
11926
11982
  if (format !== "mp4") {
@@ -11928,11 +11984,11 @@ function readCfrEncoder(planDir, format) {
11928
11984
  `[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.`
11929
11985
  );
11930
11986
  }
11931
- const encoderJsonPath = join29(planDir, "meta", "encoder.json");
11932
- if (!existsSync22(encoderJsonPath)) {
11987
+ const encoderJsonPath = join30(planDir, "meta", "encoder.json");
11988
+ if (!existsSync23(encoderJsonPath)) {
11933
11989
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
11934
11990
  }
11935
- const encoderJson = JSON.parse(readFileSync10(encoderJsonPath, "utf-8"));
11991
+ const encoderJson = JSON.parse(readFileSync11(encoderJsonPath, "utf-8"));
11936
11992
  if (encoderJson.encoder === "libx265-software") {
11937
11993
  throw new Error(
11938
11994
  `[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".`
@@ -11941,7 +11997,7 @@ function readCfrEncoder(planDir, format) {
11941
11997
  return encoderJson;
11942
11998
  }
11943
11999
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
11944
- if (existsSync22(outputPath)) rmSync10(outputPath, { recursive: true, force: true });
12000
+ if (existsSync23(outputPath)) rmSync10(outputPath, { recursive: true, force: true });
11945
12001
  mkdirSync13(outputPath, { recursive: true });
11946
12002
  let globalIdx = 0;
11947
12003
  for (const chunkDir of chunkPaths) {
@@ -11955,8 +12011,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
11955
12011
  throw new Error(`[assemble] png-sequence chunk has no frames: ${chunkDir}`);
11956
12012
  }
11957
12013
  for (const frame of frames) {
11958
- const dst = join29(outputPath, formatExportFrameName(globalIdx, "png"));
11959
- cpSync3(join29(chunkDir, frame), dst);
12014
+ const dst = join30(outputPath, formatExportFrameName(globalIdx, "png"));
12015
+ cpSync3(join30(chunkDir, frame), dst);
11960
12016
  globalIdx += 1;
11961
12017
  }
11962
12018
  }
@@ -11965,14 +12021,14 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
11965
12021
  `[assemble] png-sequence frame count mismatch: merged ${globalIdx} frames vs plan.totalFrames=${totalFrames}. Using on-disk count.`
11966
12022
  );
11967
12023
  }
11968
- if (audioPath !== null && existsSync22(audioPath)) {
11969
- const sidecar = join29(outputPath, MIXED_AUDIO_FILENAME4);
12024
+ if (audioPath !== null && existsSync23(audioPath)) {
12025
+ const sidecar = join30(outputPath, MIXED_AUDIO_FILENAME4);
11970
12026
  cpSync3(audioPath, sidecar);
11971
12027
  }
11972
12028
  let fileSize = 0;
11973
12029
  for (const name of readdirSync8(outputPath)) {
11974
12030
  try {
11975
- fileSize += statSync8(join29(outputPath, name)).size;
12031
+ fileSize += statSync8(join30(outputPath, name)).size;
11976
12032
  } catch {
11977
12033
  }
11978
12034
  }
@@ -11986,9 +12042,9 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
11986
12042
 
11987
12043
  // src/services/distributed/renderChunk.ts
11988
12044
  import { randomBytes } from "node:crypto";
11989
- import { existsSync as existsSync23, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync9, rmSync as rmSync11, writeFileSync as writeFileSync12 } from "node:fs";
12045
+ import { existsSync as existsSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync12, readdirSync as readdirSync9, rmSync as rmSync11, writeFileSync as writeFileSync12 } from "node:fs";
11990
12046
  import { cpus } from "node:os";
11991
- import { join as join30 } from "node:path";
12047
+ import { join as join31 } from "node:path";
11992
12048
  import {
11993
12049
  assertSwiftShader,
11994
12050
  BROWSER_GPU_NOT_SOFTWARE as BROWSER_GPU_NOT_SOFTWARE4,
@@ -12120,10 +12176,10 @@ async function beginFrameSessionNeedsScreenshotFallback(session, probe = probeBe
12120
12176
  return !await probe(session.page, timeoutMs, probeTick, session.beginFrameIntervalMs);
12121
12177
  }
12122
12178
  function hashChunkOutput(outputPath, kind) {
12123
- if (kind === "file") return sha256Hex(readFileSync11(outputPath));
12179
+ if (kind === "file") return sha256Hex(readFileSync12(outputPath));
12124
12180
  const entries = readdirSync9(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
12125
12181
  const lines = entries.map(
12126
- (name) => `${name}\0${sha256Hex(readFileSync11(join30(outputPath, name)))}`
12182
+ (name) => `${name}\0${sha256Hex(readFileSync12(join31(outputPath, name)))}`
12127
12183
  );
12128
12184
  return sha256Hex(lines.join("\0"));
12129
12185
  }
@@ -12140,16 +12196,16 @@ function resolveLockedVp9CpuUsed(lockedEncoder) {
12140
12196
  async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12141
12197
  const start = Date.now();
12142
12198
  const log = defaultLogger;
12143
- const planJsonPath = join30(planDir, "plan.json");
12144
- const encoderJsonPath = join30(planDir, "meta", "encoder.json");
12145
- const chunksJsonPath = join30(planDir, "meta", "chunks.json");
12146
- if (!existsSync23(planJsonPath)) {
12199
+ const planJsonPath = join31(planDir, "plan.json");
12200
+ const encoderJsonPath = join31(planDir, "meta", "encoder.json");
12201
+ const chunksJsonPath = join31(planDir, "meta", "chunks.json");
12202
+ if (!existsSync24(planJsonPath)) {
12147
12203
  throw new RenderChunkValidationError(
12148
12204
  MISSING_PLAN_ARTIFACT,
12149
12205
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
12150
12206
  );
12151
12207
  }
12152
- const plan = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
12208
+ const plan = JSON.parse(readFileSync12(planJsonPath, "utf-8"));
12153
12209
  readPlanProtocolV1(plan, DISTRIBUTED_RENDER_CAPABILITIES.roles.chunk);
12154
12210
  const planHashStarted = Date.now();
12155
12211
  const v2Materialization = readValidatedPlanV2Materialization(planDir, {
@@ -12159,20 +12215,20 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12159
12215
  const v2Manifest = v2Materialization?.manifest ?? null;
12160
12216
  const remoteSources = v2Materialization?.remoteSources ?? {};
12161
12217
  for (const required of [encoderJsonPath, chunksJsonPath]) {
12162
- if (!existsSync23(required)) {
12218
+ if (!existsSync24(required)) {
12163
12219
  throw new RenderChunkValidationError(
12164
12220
  MISSING_PLAN_ARTIFACT,
12165
12221
  `[renderChunk] planDir is missing required artifact: ${required}`
12166
12222
  );
12167
12223
  }
12168
12224
  }
12169
- const encoder = JSON.parse(readFileSync11(encoderJsonPath, "utf-8"));
12170
- const chunks = JSON.parse(readFileSync11(chunksJsonPath, "utf-8"));
12171
- const videosJsonPath = join30(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
12225
+ const encoder = JSON.parse(readFileSync12(encoderJsonPath, "utf-8"));
12226
+ const chunks = JSON.parse(readFileSync12(chunksJsonPath, "utf-8"));
12227
+ const videosJsonPath = join31(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
12172
12228
  let planVideos = null;
12173
- if (existsSync23(videosJsonPath)) {
12229
+ if (existsSync24(videosJsonPath)) {
12174
12230
  try {
12175
- planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync11(videosJsonPath, "utf-8")));
12231
+ planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync12(videosJsonPath, "utf-8")));
12176
12232
  } catch (err) {
12177
12233
  if (err instanceof RenderChunkValidationError) throw err;
12178
12234
  throw new RenderChunkValidationError(
@@ -12200,8 +12256,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12200
12256
  }
12201
12257
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
12202
12258
  const framesInChunk = range.endFrame - range.startFrame;
12203
- const compiledDir = join30(planDir, "compiled");
12204
- if (!existsSync23(compiledDir)) {
12259
+ const compiledDir = join31(planDir, "compiled");
12260
+ if (!existsSync24(compiledDir)) {
12205
12261
  throw new RenderChunkValidationError(
12206
12262
  MISSING_PLAN_ARTIFACT,
12207
12263
  `[renderChunk] planDir missing compiled/ directory: ${compiledDir}`
@@ -12259,7 +12315,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12259
12315
  };
12260
12316
  const workDir = `${outputChunkPath}.work.${process.pid}.${randomBytes(4).toString("hex")}`;
12261
12317
  mkdirSync14(workDir, { recursive: true });
12262
- const framesDir = join30(workDir, "captured-frames");
12318
+ const framesDir = join31(workDir, "captured-frames");
12263
12319
  mkdirSync14(framesDir, { recursive: true });
12264
12320
  const videoFramesDir = `${workDir}.video-frames`;
12265
12321
  const chunkFrameNumbers = Array.from({ length: framesInChunk }, (_, i) => range.startFrame + i);
@@ -12284,7 +12340,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12284
12340
  dimensions: plan.dimensions,
12285
12341
  encoder,
12286
12342
  videoCount: planVideos?.videos.length ?? 0,
12287
- html: readFileSync11(join30(compiledDir, "index.html"), "utf-8"),
12343
+ html: readFileSync12(join31(compiledDir, "index.html"), "utf-8"),
12288
12344
  // The plan ships a deferred source only to chunks that show it; don't wait on the rest.
12289
12345
  skipReadinessVideoIds: deferredVideos.filter(
12290
12346
  (video) => !shownFrames.get(video.videoId)?.size || remoteVideoIds.has(video.videoId)
@@ -12452,10 +12508,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12452
12508
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
12453
12509
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
12454
12510
  if (isPngSequence) {
12455
- if (!existsSync23(outputChunkPath)) mkdirSync14(outputChunkPath, { recursive: true });
12511
+ if (!existsSync24(outputChunkPath)) mkdirSync14(outputChunkPath, { recursive: true });
12456
12512
  } else {
12457
- const outDir = join30(outputChunkPath, "..");
12458
- if (!existsSync23(outDir)) mkdirSync14(outDir, { recursive: true });
12513
+ const outDir = join31(outputChunkPath, "..");
12514
+ if (!existsSync24(outDir)) mkdirSync14(outDir, { recursive: true });
12459
12515
  }
12460
12516
  const encodeInput = {
12461
12517
  job,
@@ -12562,7 +12618,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12562
12618
  openAttempt,
12563
12619
  verifyFirstSession: forceScreenshot || !verifyInWorker ? void 0 : verifyFirstWorker
12564
12620
  }),
12565
- { stall: frameStallRule(job, framesInChunk) }
12621
+ { stall: frameStallRule(job, framesInChunk, void 0) }
12566
12622
  ).catch(async (captureError) => {
12567
12623
  await overlap.current?.abort();
12568
12624
  overlap.current = null;
@@ -12698,8 +12754,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
12698
12754
 
12699
12755
  // src/services/distributed/planV2Execution.ts
12700
12756
  async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
12701
- const workRoot = mkdtempSync(join31(tmpdir2(), "hf-plan-v2-chunk-"));
12702
- const materializedPlanDir = join31(workRoot, "plan");
12757
+ const workRoot = mkdtempSync(join32(tmpdir2(), "hf-plan-v2-chunk-"));
12758
+ const materializedPlanDir = join32(workRoot, "plan");
12703
12759
  try {
12704
12760
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
12705
12761
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
@@ -12708,8 +12764,8 @@ async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
12708
12764
  }
12709
12765
  }
12710
12766
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
12711
- const workRoot = mkdtempSync(join31(tmpdir2(), "hf-plan-v2-assembler-"));
12712
- const materializedPlanDir = join31(workRoot, "plan");
12767
+ const workRoot = mkdtempSync(join32(tmpdir2(), "hf-plan-v2-assembler-"));
12768
+ const materializedPlanDir = join32(workRoot, "plan");
12713
12769
  try {
12714
12770
  const materialized = materializePlanV2Target(
12715
12771
  planV2Dir,
@@ -12917,6 +12973,13 @@ function validateDistributedRenderConfig(config) {
12917
12973
  `distributed mode supports only ${ALLOWED_HDR_MODES.join(", ")}; got ${String(config.hdrMode)}`
12918
12974
  );
12919
12975
  }
12976
+ const chromaSubsampling = config.chromaSubsampling;
12977
+ if (chromaSubsampling !== void 0 && chromaSubsampling !== "420") {
12978
+ throw new InvalidConfigError(
12979
+ "config.chromaSubsampling",
12980
+ `distributed mode encodes 4:2:0 only; got ${String(chromaSubsampling)}`
12981
+ );
12982
+ }
12920
12983
  if (config.variables !== void 0) {
12921
12984
  validateVariablesPayload(config.variables);
12922
12985
  }
@@ -13015,16 +13078,18 @@ function validateIntDimension(field, value) {
13015
13078
  // src/services/distributed/projectHash.ts
13016
13079
  import { closeSync as closeSync5, openSync as openSync5, readdirSync as readdirSync10, readSync as readSync4, realpathSync as realpathSync2, statSync as statSync9 } from "node:fs";
13017
13080
  import { createHash as createHash8 } from "node:crypto";
13018
- import { join as join32 } from "node:path";
13081
+ import { join as join33 } from "node:path";
13019
13082
  var SITE_ID_SCHEME = "site-v2\0";
13020
13083
  var READ_CHUNK_BYTES = 256 * 1024;
13084
+ var ENV_FILE = /^\.env([._-].*|rc)?$/i;
13085
+ var leftOut = (rel, name) => rel === "" && PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(name) || ENV_FILE.test(name);
13021
13086
  function listSiteFiles(projectDir) {
13022
13087
  const files = [];
13023
13088
  const ancestors = /* @__PURE__ */ new Set([realpathSync2(projectDir)]);
13024
13089
  function walk(dir, rel) {
13025
13090
  for (const name of readdirSync10(dir).sort()) {
13026
- if (rel === "" && PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(name)) continue;
13027
- const full = join32(dir, name);
13091
+ if (leftOut(rel, name)) continue;
13092
+ const full = join33(dir, name);
13028
13093
  const relPath = rel === "" ? name : `${rel}/${name}`;
13029
13094
  let stat;
13030
13095
  try {
@@ -13054,7 +13119,7 @@ function hashProjectDir(projectDir, files = listSiteFiles(projectDir)) {
13054
13119
  for (const rel of files) {
13055
13120
  hash.update(rel);
13056
13121
  hash.update("\0");
13057
- const fd = openSync5(join32(projectDir, rel), "r");
13122
+ const fd = openSync5(join33(projectDir, rel), "r");
13058
13123
  try {
13059
13124
  let read;
13060
13125
  while ((read = readSync4(fd, chunk, 0, chunk.length, null)) > 0) {