@hyperframes/producer 0.9.69 → 0.9.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,12 +9,12 @@ import {
9
9
  // src/services/renderOrchestrator.ts
10
10
  import { audioFailureDiagnostics as audioFailureDiagnostics2, usableCpuCount as usableCpuCount2 } from "@hyperframes/engine";
11
11
  import {
12
- existsSync as existsSync22,
12
+ existsSync as existsSync21,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync12,
16
16
  statSync as statSync10,
17
- writeFileSync as writeFileSync7,
17
+ writeFileSync as writeFileSync6,
18
18
  copyFileSync as copyFileSync5,
19
19
  appendFileSync
20
20
  } from "fs";
@@ -2593,7 +2593,7 @@ function replanAfterFailure(plan2, failure) {
2593
2593
  }
2594
2594
 
2595
2595
  // src/services/render/stages/captureSegmentedStage.ts
2596
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2596
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2597
2597
  import { join as join12 } from "node:path";
2598
2598
  import {
2599
2599
  captureFrameToBuffer as captureFrameToBuffer2,
@@ -4325,16 +4325,25 @@ function createSegmentQueue(slices) {
4325
4325
  // src/services/render/segmentManifest.ts
4326
4326
  import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
4327
4327
  import {
4328
+ closeSync as closeSync4,
4329
+ constants as constants3,
4328
4330
  createReadStream as createReadStream2,
4329
- existsSync as existsSync7,
4331
+ fstatSync as fstatSync3,
4330
4332
  lstatSync as lstatSync3,
4331
4333
  mkdirSync as mkdirSync3,
4332
- readFileSync as readFileSync4,
4333
- writeFileSync as writeFileSync3
4334
+ openSync as openSync4,
4335
+ readFileSync as readFileSync4
4334
4336
  } from "node:fs";
4335
4337
  import { join as join10 } from "node:path";
4338
+ import {
4339
+ assertPrivateCachePath,
4340
+ ensurePrivateCacheDir,
4341
+ hyperframesCacheDir
4342
+ } from "@hyperframes/core/cache-dir";
4343
+ import { isSafePath as isSafePath2, realpath } from "@hyperframes/core/safe-path";
4344
+ import { isPathInside as isPathInside3 } from "@hyperframes/parsers/asset-paths";
4336
4345
  import { previewToken } from "@hyperframes/core/preview-proof";
4337
- import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
4346
+ import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
4338
4347
  var MANIFEST_FILENAME = "segments.json";
4339
4348
  function computeSegmentPlanHash(input) {
4340
4349
  const ordered = [
@@ -4360,8 +4369,20 @@ function computeSegmentPlanHash(input) {
4360
4369
  if (delivery.some((v) => v !== "")) ordered.push(...delivery.map(String));
4361
4370
  return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
4362
4371
  }
4363
- function segmentDirFor(projectRendersDir, planHash) {
4364
- return join10(projectRendersDir, ".hf-segments", planHash);
4372
+ function segmentDirFor(projectDir, planHash) {
4373
+ const root = hyperframesCacheDir();
4374
+ const projectKey = createHash2("sha256").update(realpath(projectDir)).digest("hex");
4375
+ const parent = join10(root, "segments", projectKey);
4376
+ const dir = join10(parent, planHash);
4377
+ if (isPathInside3(root, projectDir) || isSafePath2(projectDir, root) || isSafePath2(projectDir, parent) || isSafePath2(projectDir, dir)) {
4378
+ throw new Error("Segmented capture requires HYPERFRAMES_CACHE_DIR outside the project.");
4379
+ }
4380
+ assertPrivateCachePath(root, root);
4381
+ ensurePrivateCacheDir(parent, root);
4382
+ if (!isSafePath2(parent, dir) || lstatSync3(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
4383
+ throw new Error("Invalid segment cache directory");
4384
+ }
4385
+ return dir;
4365
4386
  }
4366
4387
  function hasNumber(value, key) {
4367
4388
  return key in value && typeof Reflect.get(value, key) === "number";
@@ -4380,12 +4401,22 @@ function isManifest(value) {
4380
4401
  }
4381
4402
  function readSegmentManifest(segmentDir) {
4382
4403
  const path = join10(segmentDir, MANIFEST_FILENAME);
4383
- if (!existsSync7(path)) return null;
4404
+ let fd;
4384
4405
  try {
4385
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
4406
+ fd = openSync4(
4407
+ path,
4408
+ constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0)
4409
+ );
4410
+ const opened = fstatSync3(fd);
4411
+ if (!opened.isFile() || opened.nlink !== 1) return null;
4412
+ const named = lstatSync3(path);
4413
+ if (!named.isFile() || named.dev !== opened.dev || named.ino !== opened.ino) return null;
4414
+ const parsed = JSON.parse(readFileSync4(fd, "utf-8"));
4386
4415
  return isManifest(parsed) ? parsed : null;
4387
4416
  } catch {
4388
4417
  return null;
4418
+ } finally {
4419
+ if (fd !== void 0) closeSync4(fd);
4389
4420
  }
4390
4421
  }
4391
4422
  function segmentManifestKey(token = previewToken()) {
@@ -4418,9 +4449,11 @@ async function hashSegmentFile(path) {
4418
4449
  }
4419
4450
  function writeSegmentManifest(segmentDir, manifest, key) {
4420
4451
  mkdirSync3(segmentDir, { recursive: true });
4421
- const tmp = join10(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
4422
- writeFileSync3(tmp, JSON.stringify(signSegmentManifest(manifest, key), null, 2), "utf-8");
4423
- renameWithRetry2(tmp, join10(segmentDir, MANIFEST_FILENAME));
4452
+ replaceFileAtomically(
4453
+ join10(segmentDir, MANIFEST_FILENAME),
4454
+ JSON.stringify(signSegmentManifest(manifest, key), null, 2),
4455
+ 384
4456
+ );
4424
4457
  }
4425
4458
  async function probeSegmentFrameCount(path, probe) {
4426
4459
  try {
@@ -4440,19 +4473,27 @@ function plannedSlice(entry, plan2) {
4440
4473
  }
4441
4474
  return slice;
4442
4475
  }
4443
- function isPlainFileOfSize(path, bytes) {
4444
- const stat = lstatSync3(path, { throwIfNoEntry: false });
4445
- return stat !== void 0 && stat.isFile() && stat.size > 0 && stat.size === bytes;
4476
+ async function matchesSegmentFile(path, entry) {
4477
+ try {
4478
+ const stat = lstatSync3(path, { throwIfNoEntry: false });
4479
+ if (!stat?.isFile() || stat.nlink !== 1 || stat.size <= 0 || stat.size !== entry.bytes) {
4480
+ return false;
4481
+ }
4482
+ return await hashSegmentFile(path) === entry.sha256;
4483
+ } catch {
4484
+ return false;
4485
+ }
4446
4486
  }
4447
4487
  async function validateCompletedSegments(manifest, check) {
4448
4488
  const ok = /* @__PURE__ */ new Set();
4449
- if (manifest.planHash !== check.expectedHash || !hasValidMac(manifest, check.key)) return ok;
4489
+ if (manifest.totalFrames !== check.totalFrames || manifest.segmentFrames !== check.segmentFrames || manifest.planHash !== check.expectedHash || !hasValidMac(manifest, check.key))
4490
+ return ok;
4491
+ const plan2 = planSegments(check.totalFrames, check.segmentFrames);
4450
4492
  for (const entry of manifest.completed) {
4451
- const slice = plannedSlice(entry, check.plan);
4493
+ const slice = plannedSlice(entry, plan2);
4452
4494
  if (!slice) continue;
4453
4495
  const path = segmentOutputPath(check.segmentDir, slice.index);
4454
- if (!isPlainFileOfSize(path, entry.bytes)) continue;
4455
- if (await hashSegmentFile(path) !== entry.sha256) continue;
4496
+ if (entry.path !== path || !await matchesSegmentFile(path, entry)) continue;
4456
4497
  const frames = await check.probeFrames(path);
4457
4498
  if (frames !== slice.endFrame - slice.startFrame) continue;
4458
4499
  ok.add(slice.index);
@@ -5343,6 +5384,7 @@ async function captureSegment(ctx, segment) {
5343
5384
  }
5344
5385
  async function captureSegmentToEncoder(ctx, segment) {
5345
5386
  const segmentPath = segmentOutputPath(ctx.segmentDir, segment.index);
5387
+ rmSync6(segmentPath, { force: true });
5346
5388
  let encoder;
5347
5389
  try {
5348
5390
  encoder = await ctx.spawnEncoder(
@@ -5371,8 +5413,8 @@ async function captureSegmentToEncoder(ctx, segment) {
5371
5413
  path: segmentPath,
5372
5414
  // Recorded so resume can prove the file on disk is the one that
5373
5415
  // finished; absent only in unit tests, whose fake encoder writes none.
5374
- bytes: existsSync8(segmentPath) ? statSync4(segmentPath).size : 0,
5375
- sha256: existsSync8(segmentPath) ? await hashSegmentFile(segmentPath) : ""
5416
+ bytes: existsSync7(segmentPath) ? statSync4(segmentPath).size : 0,
5417
+ sha256: existsSync7(segmentPath) ? await hashSegmentFile(segmentPath) : ""
5376
5418
  });
5377
5419
  return encodeResult;
5378
5420
  } finally {
@@ -7051,7 +7093,7 @@ function requireOutputDimensions(expected, width, height) {
7051
7093
  }
7052
7094
 
7053
7095
  // src/services/render/stages/compileStage.ts
7054
- import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
7096
+ import { existsSync as existsSync12, writeFileSync as writeFileSync4 } from "node:fs";
7055
7097
  import { join as join22, relative as relative4 } from "node:path";
7056
7098
  import { privateCacheRoot } from "@hyperframes/engine";
7057
7099
  import { suggestMatchingPreset } from "@hyperframes/core";
@@ -7063,7 +7105,7 @@ import { statSync as statSync6 } from "node:fs";
7063
7105
  var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
7064
7106
  var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
7065
7107
  var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
7066
- var MAX_EXPANDED_COMPOSITION_BYTES = 2 * MAX_COMPOSITION_HTML_BYTES;
7108
+ var MAX_EXPANDED_COMPOSITION_BYTES = 4 * MAX_COMPOSITION_HTML_BYTES;
7067
7109
  var MAX_COMPOSITION_MOUNTS = 1e4;
7068
7110
  var CompositionTooLargeError = class extends Error {
7069
7111
  constructor(message, publicMetadata) {
@@ -7160,12 +7202,12 @@ import {
7160
7202
  stylesheetLinkMatches
7161
7203
  } from "@hyperframes/parsers/css-url-scans";
7162
7204
  import { createHash as createHash6 } from "node:crypto";
7163
- import { createReadStream as createReadStream3, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7205
+ import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7164
7206
  import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7165
7207
  import { parseHTML as parseHTML5 } from "linkedom";
7166
7208
 
7167
7209
  // src/services/bundledScripts.ts
7168
- import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
7210
+ import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7169
7211
  import { join as join17 } from "node:path";
7170
7212
  import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
7171
7213
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
@@ -7173,7 +7215,7 @@ function bundledScript(url) {
7173
7215
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
7174
7216
  if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
7175
7217
  const file = join17(dir, "gsap.min.js");
7176
- return existsSync9(file) ? readFileSync5(file) : null;
7218
+ return existsSync8(file) ? readFileSync5(file) : null;
7177
7219
  }
7178
7220
 
7179
7221
  // src/services/htmlCompiler.ts
@@ -7212,6 +7254,7 @@ import {
7212
7254
  isJavaScriptType,
7213
7255
  prepareFlattenedInnerRoot,
7214
7256
  emitRootCompositionVariableStyles,
7257
+ dropAuthoredSvgReferenceAliases,
7215
7258
  readDeclaredDefaults,
7216
7259
  parseHostVariableValues,
7217
7260
  boundMediaSrc,
@@ -7431,7 +7474,7 @@ import {
7431
7474
 
7432
7475
  // src/services/animatedGifPrep.ts
7433
7476
  import { createHash as createHash4 } from "node:crypto";
7434
- import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7477
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7435
7478
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7436
7479
  import { parseHTML as parseHTML3 } from "linkedom";
7437
7480
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7439,7 +7482,7 @@ import {
7439
7482
  DEFAULT_VP9_CPU_USED,
7440
7483
  isPrivateUnderAssetRoots,
7441
7484
  runFfmpeg as runFfmpeg2,
7442
- renameWithRetry as renameWithRetry3,
7485
+ renameWithRetry as renameWithRetry2,
7443
7486
  urlInputArgs as urlInputArgs2
7444
7487
  } from "@hyperframes/engine";
7445
7488
  import { namesAnotherNetworkRoot } from "@hyperframes/parsers/asset-resolution";
@@ -7477,7 +7520,7 @@ function resolveLocalImageSourcePath(src, options) {
7477
7520
  const { basePath } = splitUrlSuffix(trimmed);
7478
7521
  const normalizedBase = normalizeRelPath(basePath);
7479
7522
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
7480
- if (mapped && existsSync10(mapped)) return mapped;
7523
+ if (mapped && existsSync9(mapped)) return mapped;
7481
7524
  if (isHttpUrl(trimmed)) return null;
7482
7525
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
7483
7526
  const candidates = [
@@ -7486,7 +7529,7 @@ function resolveLocalImageSourcePath(src, options) {
7486
7529
  ];
7487
7530
  const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7488
7531
  const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7489
- return candidates.find((candidate) => allowed(candidate) && existsSync10(candidate)) ?? null;
7532
+ return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7490
7533
  }
7491
7534
  function isUsableFile(path) {
7492
7535
  try {
@@ -7598,10 +7641,10 @@ async function runAnimatedGifTranscode(request) {
7598
7641
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
7599
7642
  }
7600
7643
  async function ensurePreparedWebm(input) {
7601
- if (!existsSync10(dirname6(input.cachePath))) {
7644
+ if (!existsSync9(dirname6(input.cachePath))) {
7602
7645
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
7603
7646
  }
7604
- if (!existsSync10(dirname6(input.outputPath))) {
7647
+ if (!existsSync9(dirname6(input.outputPath))) {
7605
7648
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7606
7649
  }
7607
7650
  if (!isUsableFile(input.cachePath)) {
@@ -7624,7 +7667,7 @@ async function ensurePreparedWebm(input) {
7624
7667
  throw new Error("Animated GIF transcode produced an empty output");
7625
7668
  }
7626
7669
  if (!isUsableFile(input.cachePath)) {
7627
- renameWithRetry3(tmpPath, input.cachePath);
7670
+ renameWithRetry2(tmpPath, input.cachePath);
7628
7671
  } else {
7629
7672
  rmSync9(tmpPath, { force: true });
7630
7673
  }
@@ -7748,19 +7791,19 @@ async function prepareAnimatedGifInputs(html, options) {
7748
7791
  // src/services/heifImagePrep.ts
7749
7792
  import { createHash as createHash5 } from "node:crypto";
7750
7793
  import {
7751
- closeSync as closeSync4,
7794
+ closeSync as closeSync5,
7752
7795
  copyFileSync as copyFileSync3,
7753
7796
  mkdirSync as mkdirSync8,
7754
- openSync as openSync4,
7797
+ openSync as openSync5,
7755
7798
  readFileSync as readFileSync7,
7756
7799
  readSync as readSync3,
7757
7800
  rmSync as rmSync10,
7758
7801
  statSync as statSync8,
7759
- writeFileSync as writeFileSync4
7802
+ writeFileSync as writeFileSync3
7760
7803
  } from "node:fs";
7761
7804
  import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
7762
7805
  import { parseHTML as parseHTML4 } from "linkedom";
7763
- import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7806
+ import { renameWithRetry as renameWithRetry3, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7764
7807
 
7765
7808
  // src/services/heifRotation.ts
7766
7809
  function* boxes(buf, start, end) {
@@ -7907,13 +7950,13 @@ function isHeifBytes(head) {
7907
7950
  function readHead(path) {
7908
7951
  let fd;
7909
7952
  try {
7910
- fd = openSync4(path, "r");
7953
+ fd = openSync5(path, "r");
7911
7954
  const buf = Buffer.alloc(4096);
7912
7955
  return buf.subarray(0, readSync3(fd, buf, 0, buf.length, 0));
7913
7956
  } catch {
7914
7957
  return null;
7915
7958
  } finally {
7916
- if (fd !== void 0) closeSync4(fd);
7959
+ if (fd !== void 0) closeSync5(fd);
7917
7960
  }
7918
7961
  }
7919
7962
  async function probeJson(path, withGroups) {
@@ -8012,14 +8055,14 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8012
8055
  const inlinePath = `${tmpPath}.heic`;
8013
8056
  const inputPath = source.path ?? inlinePath;
8014
8057
  try {
8015
- if (!source.path) writeFileSync4(inlinePath, source.bytes);
8058
+ if (!source.path) writeFileSync3(inlinePath, source.bytes);
8016
8059
  await (options.transcode ?? convertHeifToJpeg)({
8017
8060
  inputPath,
8018
8061
  outputPath: tmpPath,
8019
8062
  timeoutMs: options.timeoutMs
8020
8063
  });
8021
8064
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
8022
- renameWithRetry4(tmpPath, cachePath);
8065
+ renameWithRetry3(tmpPath, cachePath);
8023
8066
  } catch (error) {
8024
8067
  const reason = error instanceof Error ? error.message : String(error);
8025
8068
  throw TOOL_FAILURE_RE.test(reason) ? new HeifToolUnavailableError(source.label, reason) : new HeifImageConversionError(source.label, reason);
@@ -8080,7 +8123,7 @@ import {
8080
8123
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
8081
8124
 
8082
8125
  // src/services/assetMediaType.ts
8083
- import { existsSync as existsSync11 } from "node:fs";
8126
+ import { existsSync as existsSync10 } from "node:fs";
8084
8127
  import { dirname as dirname8, join as join20 } from "node:path";
8085
8128
  import {
8086
8129
  fingerprintElementId,
@@ -8193,7 +8236,7 @@ async function preflightCompositionAssetMediaTypes(input) {
8193
8236
  input.projectDir,
8194
8237
  input.compiledDir
8195
8238
  );
8196
- if (!existsSync11(resolvedPath)) continue;
8239
+ if (!existsSync10(resolvedPath)) continue;
8197
8240
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
8198
8241
  }
8199
8242
  const mismatches = [];
@@ -8490,7 +8533,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8490
8533
  let filePath = src;
8491
8534
  if (isHttpUrl(src)) {
8492
8535
  const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8493
- if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8536
+ if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8494
8537
  try {
8495
8538
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8496
8539
  onTelemetry: logRemoteDownloadTelemetry
@@ -8509,7 +8552,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8509
8552
  return { duration: null, resolvedPath: filePath };
8510
8553
  }
8511
8554
  }
8512
- if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
8555
+ if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
8513
8556
  return { duration: null, resolvedPath: filePath };
8514
8557
  }
8515
8558
  const withSrcContext = (error) => {
@@ -8835,13 +8878,14 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8835
8878
  const body = document2.querySelector("body");
8836
8879
  const hosts = Array.from(document2.querySelectorAll("[data-composition-src]"));
8837
8880
  if (!hosts.length) {
8881
+ const dropped = dropAuthoredSvgReferenceAliases(document2);
8838
8882
  const emitted = emitRootCompositionVariableStyles(
8839
8883
  document2,
8840
8884
  {},
8841
8885
  variableOverrides,
8842
8886
  { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8843
8887
  );
8844
- return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8888
+ return { html: emitted || dropped ? document2.toString() : html, variablesByComp: {} };
8845
8889
  }
8846
8890
  const readOnce = /* @__PURE__ */ new Map();
8847
8891
  const readMountHtml = (srcPath) => {
@@ -9033,18 +9077,31 @@ function operatorGsapMirror() {
9033
9077
  return void 0;
9034
9078
  }
9035
9079
  }
9036
- async function downloadScript(src, mirror) {
9080
+ async function downloadScript(src, mirror, signal) {
9037
9081
  if (mirror && new URL(src).href.startsWith(mirror)) {
9038
- const response = await fetch(src, { redirect: "error", signal: AbortSignal.timeout(15e3) });
9082
+ const response = await fetch(src, {
9083
+ redirect: "error",
9084
+ signal: AbortSignal.any([AbortSignal.timeout(15e3), signal])
9085
+ });
9039
9086
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
9040
9087
  const bytes = new Uint8Array(await response.arrayBuffer());
9041
9088
  if (bytes.byteLength > MAX_SCRIPT_BYTES) throw new Error(`Script over 16 MiB: ${src}`);
9042
9089
  return bytes;
9043
9090
  }
9044
- return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3 });
9091
+ return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3, signal });
9045
9092
  }
9046
9093
  var MAX_CONCURRENT_SCRIPT_FETCHES = 4;
9047
- async function inlineExternalScripts(html, budget = new CompositionExpansionBudget()) {
9094
+ var MAX_REMOTE_FETCHES = 32;
9095
+ var REMOTE_FETCH_DEADLINE_MS = 6e4;
9096
+ var fetchSignalOf = (signal) => typeof signal === "function" ? signal() : signal;
9097
+ function assertRemoteFetchCount(kind, count) {
9098
+ if (count > MAX_REMOTE_FETCHES) {
9099
+ throw new Error(
9100
+ `The composition links ${count} remote ${kind}; at most ${MAX_REMOTE_FETCHES} are downloaded at compile time`
9101
+ );
9102
+ }
9103
+ }
9104
+ async function inlineExternalScripts(html, budget = new CompositionExpansionBudget(), signal) {
9048
9105
  const fullHtml = ensureFullDocument(html);
9049
9106
  const wrappedFragment = fullHtml !== html;
9050
9107
  const { document: document2 } = parseHTML5(fullHtml);
@@ -9057,9 +9114,19 @@ async function inlineExternalScripts(html, budget = new CompositionExpansionBudg
9057
9114
  }
9058
9115
  }
9059
9116
  if (externalScripts.length === 0) return html;
9117
+ const bundled = /* @__PURE__ */ new Map();
9118
+ const local = externalScripts.map(({ el, src }) => {
9119
+ if (!bundled.has(src)) bundled.set(src, bundledScript(src));
9120
+ const bytes = bundled.get(src);
9121
+ return bytes && matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "") ? bytes : null;
9122
+ });
9123
+ const remote = new Set(externalScripts.filter((_, i) => !local[i]).map(({ src }) => src));
9124
+ assertRemoteFetchCount("scripts", remote.size);
9060
9125
  const mirror = operatorGsapMirror();
9061
9126
  const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
9062
9127
  const stop = new AbortController();
9128
+ const shared = remote.size > 0 ? fetchSignalOf(signal) : void 0;
9129
+ const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
9063
9130
  const fail = (error) => {
9064
9131
  stop.abort(error);
9065
9132
  throw error;
@@ -9076,21 +9143,21 @@ async function inlineExternalScripts(html, budget = new CompositionExpansionBudg
9076
9143
  let bytes = fetches.get(src);
9077
9144
  if (!bytes) {
9078
9145
  bytes = limit(async () => {
9079
- if (stop.signal.aborted) throw stop.signal.reason;
9080
- const downloaded = await downloadScript(src, mirror);
9146
+ fetchSignal.throwIfAborted();
9147
+ const downloaded = await downloadScript(src, mirror, fetchSignal);
9081
9148
  charge(downloaded.byteLength);
9082
9149
  return downloaded;
9083
- }, stop.signal);
9150
+ }, fetchSignal);
9084
9151
  fetches.set(src, bytes);
9085
9152
  }
9086
9153
  return bytes;
9087
9154
  };
9088
9155
  const placed = /* @__PURE__ */ new Set();
9089
9156
  const downloads = await Promise.allSettled(
9090
- externalScripts.map(async ({ el, src }) => {
9157
+ externalScripts.map(async ({ el, src }, i) => {
9091
9158
  const integrity = el.getAttribute("integrity") || "";
9092
- let bytes = bundledScript(src);
9093
- if (bytes && matchesScriptIntegrity(bytes, integrity)) {
9159
+ let bytes = local[i];
9160
+ if (bytes) {
9094
9161
  charge(bytes.byteLength);
9095
9162
  } else {
9096
9163
  bytes = await fetchOnce(src);
@@ -9141,7 +9208,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9141
9208
  return null;
9142
9209
  }
9143
9210
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
9144
- if (!onShare && !existsSync12(absPath)) return null;
9211
+ if (!onShare && !existsSync11(absPath)) return null;
9145
9212
  const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
9146
9213
  if (refusal) {
9147
9214
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
@@ -9194,7 +9261,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9194
9261
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9195
9262
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9196
9263
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9197
- if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9264
+ if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9198
9265
  const urlToLocal = /* @__PURE__ */ new Map();
9199
9266
  await Promise.all(
9200
9267
  [...urlSet].map(async (url) => {
@@ -9287,12 +9354,13 @@ function isGoogleFontsUrl(href) {
9287
9354
  }
9288
9355
  }
9289
9356
  var MAX_STYLESHEET_BYTES = 2 * 1024 * 1024;
9290
- async function fetchExternalStylesheetCss(href) {
9357
+ async function fetchExternalStylesheetCss(href, signal) {
9291
9358
  const identity = safeDownloadUrlIdentity(href);
9292
9359
  try {
9293
9360
  return await fetchPublicHttpsText(href, {
9294
9361
  maxBytes: MAX_STYLESHEET_BYTES,
9295
- timeoutMs: 15e3
9362
+ timeoutMs: 15e3,
9363
+ signal
9296
9364
  });
9297
9365
  } catch (err) {
9298
9366
  defaultLogger.warn("[Compiler] External stylesheet fetch failed, preserving link tag.", {
@@ -9332,36 +9400,42 @@ function remoteFontStylesheetHref(tag) {
9332
9400
  if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9333
9401
  return href;
9334
9402
  }
9335
- async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget()) {
9403
+ async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget(), signal) {
9336
9404
  const hrefs = /* @__PURE__ */ new Set();
9337
9405
  for (const { parts } of stylesheetLinkMatches(html)) {
9338
9406
  const href = remoteFontStylesheetHref(parts[0]);
9339
9407
  if (href) hrefs.add(href);
9340
9408
  }
9341
9409
  if (hrefs.size === 0) return html;
9342
- const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9410
+ assertRemoteFetchCount("stylesheets", hrefs.size);
9411
+ const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
9412
+ const stop = new AbortController();
9413
+ const shared = fetchSignalOf(signal);
9414
+ const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
9343
9415
  const inlineByHref = /* @__PURE__ */ new Map();
9344
- const unique = [...hrefs];
9345
- for (let i = 0; i < unique.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9346
- const batch = unique.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9347
- const sheets = await Promise.all(batch.map(fetchExternalStylesheetCss));
9348
- batch.forEach((href, index) => {
9349
- const css = sheets[index];
9350
- const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9351
- if (fontFaceBlocks.length === 0) return;
9352
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9416
+ const inlineSheet = async (href) => {
9417
+ const css = await fetchExternalStylesheetCss(href, fetchSignal);
9418
+ const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9419
+ if (fontFaceBlocks.length === 0) return;
9420
+ const inlineStyle = `<style>/* Inlined external font stylesheet */
9353
9421
  ${fontFaceBlocks.join("\n")}
9354
9422
  </style>`;
9423
+ try {
9355
9424
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9356
- inlineByHref.set(href, inlineStyle);
9357
- const identity = safeDownloadUrlIdentity(href);
9358
- defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9359
- count: fontFaceBlocks.length,
9360
- urlFingerprint: identity.urlFingerprint,
9361
- host: identity.host
9362
- });
9425
+ } catch (error) {
9426
+ stop.abort(error);
9427
+ throw error;
9428
+ }
9429
+ inlineByHref.set(href, inlineStyle);
9430
+ const identity = safeDownloadUrlIdentity(href);
9431
+ defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9432
+ count: fontFaceBlocks.length,
9433
+ urlFingerprint: identity.urlFingerprint,
9434
+ host: identity.host
9363
9435
  });
9364
- }
9436
+ };
9437
+ await Promise.allSettled([...hrefs].map((href) => limit(() => inlineSheet(href), fetchSignal)));
9438
+ if (stop.signal.aborted) throw stop.signal.reason;
9365
9439
  const placed = /* @__PURE__ */ new Set();
9366
9440
  return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9367
9441
  const href = remoteFontStylesheetHref(tag);
@@ -9380,13 +9454,13 @@ function projectStylesheetFontFamilies(html, projectDir) {
9380
9454
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9381
9455
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
9382
9456
  const sheet = resolve8(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9383
- if (!isPathInside(sheet, projectDir) || !existsSync12(sheet)) continue;
9457
+ if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
9384
9458
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
9385
9459
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
9386
9460
  const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
9387
9461
  const path = decodedUrlPath(url);
9388
9462
  const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname9(sheet), path);
9389
- return isPathInside(file, projectDir) && existsSync12(file);
9463
+ return isPathInside(file, projectDir) && existsSync11(file);
9390
9464
  });
9391
9465
  if (family && shipsFile) families.push(family);
9392
9466
  }
@@ -9538,7 +9612,7 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9538
9612
  let gsapDist;
9539
9613
  const exists = (path) => {
9540
9614
  const file = resolve8(projectDir, path);
9541
- return !namesAnotherNetworkRoot2(projectDir, file) && existsSync12(file);
9615
+ return !namesAnotherNetworkRoot2(projectDir, file) && existsSync11(file);
9542
9616
  };
9543
9617
  return replaceGsapDistScripts(html, (full, prefix, src, file, suffix) => {
9544
9618
  if (/^https?:\/\//i.test(src)) return full;
@@ -9674,10 +9748,17 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9674
9748
  const hasShaderTransitions = detectShaderTransitionUsage(sanitizedHtml);
9675
9749
  const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
9676
9750
  const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
9751
+ let deadline;
9752
+ const remoteFetches = () => deadline ??= AbortSignal.any([
9753
+ AbortSignal.timeout(REMOTE_FETCH_DEADLINE_MS),
9754
+ ...options.abortSignal ? [options.abortSignal] : []
9755
+ ]);
9677
9756
  const fontSheetHtml = await inlineExternalFontStylesheets(
9678
9757
  promoteCssImportsToLinkTags(sanitizedHtml),
9679
- budget
9758
+ budget,
9759
+ remoteFetches
9680
9760
  );
9761
+ options.abortSignal?.throwIfAborted();
9681
9762
  const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
9682
9763
  injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml))
9683
9764
  );
@@ -9688,7 +9769,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9688
9769
  projectFontFamilies: projectStylesheetFontFamilies(fontSheetHtml, projectDir),
9689
9770
  abortSignal: options.abortSignal
9690
9771
  });
9691
- const assembledHtml = await inlineExternalScripts(coalescedHtml, budget);
9772
+ const assembledHtml = await inlineExternalScripts(coalescedHtml, budget, remoteFetches);
9773
+ options.abortSignal?.throwIfAborted();
9692
9774
  const htmlWithPositionScript = htmlHasStudioPositionEdits(assembledHtml) ? insertBeforeCloseTag(
9693
9775
  assembledHtml,
9694
9776
  "body",
@@ -9774,7 +9856,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9774
9856
  for (const video of videos) {
9775
9857
  if (isHttpUrl(video.src)) continue;
9776
9858
  const videoPath = resolve8(projectDir, video.src);
9777
- if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync12(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9859
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9778
9860
  continue;
9779
9861
  advised.add(videoPath);
9780
9862
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
@@ -10221,7 +10303,7 @@ function resolveEntryHtmlPath(input) {
10221
10303
  const rawEntry = readEntry(htmlPath);
10222
10304
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
10223
10305
  const projectIndexPath = join22(projectDir, "index.html");
10224
- if (!existsSync13(projectIndexPath)) {
10306
+ if (!existsSync12(projectIndexPath)) {
10225
10307
  throw new Error(
10226
10308
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
10227
10309
  );
@@ -10237,7 +10319,7 @@ function resolveEntryHtmlPath(input) {
10237
10319
  );
10238
10320
  }
10239
10321
  const wrapperPath = join22(workDir, "standalone-entry.html");
10240
- writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
10322
+ writeFileSync4(wrapperPath, standaloneHtml, "utf-8");
10241
10323
  log.info("Extracted standalone entry from index.html host context", { entryFile });
10242
10324
  return wrapperPath;
10243
10325
  }
@@ -11230,7 +11312,7 @@ function validateDistributedDuration(input) {
11230
11312
  }
11231
11313
 
11232
11314
  // src/services/render/stages/extractVideosStage.ts
11233
- import { existsSync as existsSync14 } from "node:fs";
11315
+ import { existsSync as existsSync13 } from "node:fs";
11234
11316
  import { join as join24 } from "node:path";
11235
11317
  import {
11236
11318
  classifyVideoExtractionError,
@@ -11683,7 +11765,7 @@ function isPublicHttpsUrl(url) {
11683
11765
  }
11684
11766
  }
11685
11767
  function opensLocally(path, assetRoots) {
11686
- return existsSync14(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11768
+ return existsSync13(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11687
11769
  }
11688
11770
  function localProbeSource(src, input) {
11689
11771
  const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
@@ -11736,7 +11818,7 @@ async function appendVideoAudioFromProbe(input) {
11736
11818
  }
11737
11819
 
11738
11820
  // src/services/render/videoLayerPassthroughPlan.ts
11739
- import { existsSync as existsSync15 } from "node:fs";
11821
+ import { existsSync as existsSync14 } from "node:fs";
11740
11822
  import {
11741
11823
  buildVideoLayerInput,
11742
11824
  isHttpUrl as isHttpUrl4,
@@ -11804,7 +11886,7 @@ async function planVideoLayerPassthrough(input) {
11804
11886
  const { video } = q;
11805
11887
  if (isHttpUrl4(video.src)) return { reason: "remote_source" };
11806
11888
  const path = resolveProjectRelativeSrc5(video.src, input.projectDir, input.compiledDir);
11807
- if (!existsSync15(path)) return { reason: "source_missing" };
11889
+ if (!existsSync14(path)) return { reason: "source_missing" };
11808
11890
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
11809
11891
  if ("reason" in layout) return layout;
11810
11892
  const layer = await buildVideoLayerInput(
@@ -11819,7 +11901,7 @@ async function planVideoLayerPassthrough(input) {
11819
11901
  }
11820
11902
 
11821
11903
  // src/services/render/stages/audioStage.ts
11822
- import { existsSync as existsSync17 } from "node:fs";
11904
+ import { existsSync as existsSync16 } from "node:fs";
11823
11905
  import { join as join27 } from "node:path";
11824
11906
  import {
11825
11907
  MIXED_AUDIO_FILENAME,
@@ -11831,16 +11913,17 @@ import {
11831
11913
  } from "@hyperframes/engine";
11832
11914
 
11833
11915
  // src/services/render/audioDeliveryLimit.ts
11834
- import { existsSync as existsSync16 } from "node:fs";
11916
+ import { existsSync as existsSync15 } from "node:fs";
11835
11917
  import { dirname as dirname11, join as join26 } from "node:path";
11836
11918
  import {
11837
11919
  applyAudioFxChain,
11838
11920
  describeFfmpegFailure as describeFfmpegFailure3,
11839
11921
  encodeAac as encodeAac2,
11840
- renameWithRetry as renameWithRetry6
11922
+ renameWithRetry as renameWithRetry5
11841
11923
  } from "@hyperframes/engine";
11842
11924
 
11843
11925
  // src/services/render/audioPadTrim.ts
11926
+ import { localContainerInputArgs } from "@hyperframes/parsers/ff-binaries";
11844
11927
  import { spawn } from "node:child_process";
11845
11928
  import { dirname as dirname10, join as join25 } from "node:path";
11846
11929
  import {
@@ -11851,7 +11934,7 @@ import {
11851
11934
  getFfprobeBinary,
11852
11935
  ManagedChildProcess,
11853
11936
  removeScratch,
11854
- renameWithRetry as renameWithRetry5,
11937
+ renameWithRetry as renameWithRetry4,
11855
11938
  runFfmpeg as runFfmpeg5,
11856
11939
  trackChildProcess,
11857
11940
  withPublicOnlyProxy
@@ -11992,10 +12075,10 @@ function sanitizeProbeFailure(reason, paths) {
11992
12075
  }
11993
12076
  async function padOrTrimAudioToVideoFrameCount(input) {
11994
12077
  const probeVideo = input.probeVideoFrameInfo ?? ((videoPath) => defaultProbeVideoFrameInfo(videoPath, input.signal));
11995
- const probeAudio = input.probeAudioInfo ?? defaultProbeAudioInfo;
12078
+ const probeAudio = input.probeAudioInfo ?? ((path, signal) => defaultProbeAudioInfo(path, signal, input.audioContainer));
11996
12079
  const timeoutMs = input.timeoutMs ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
11997
12080
  const runner = input.runFfmpeg ?? ((args) => defaultRunFfmpeg(args, timeoutMs, input.signal));
11998
- const encode = input.encodeAac ?? defaultAacEncoder(timeoutMs, input.signal, input.sourcePath);
12081
+ const encode = input.encodeAac ?? defaultAacEncoder(timeoutMs, input.signal, input.sourcePath, input.audioContainer);
11999
12082
  const probeTruePeak = input.probeAudioTruePeakDbfs ?? (input.runFfmpeg || input.encodeAac ? void 0 : (audioPath, signal) => measureTruePeakDbfs(audioPath, { timeoutMs, signal }));
12000
12083
  const [videoResult, audioResult] = await Promise.allSettled([
12001
12084
  probeVideo(input.videoPath),
@@ -12043,7 +12126,7 @@ async function padOrTrimAudioToVideoFrameCount(input) {
12043
12126
  );
12044
12127
  try {
12045
12128
  for (const step of plan2.steps) {
12046
- const ffmpegResult = step.kind === "copy" ? await runner(step.args) : await encode(
12129
+ const ffmpegResult = step.kind === "copy" ? await runner([...localContainerInputArgs(input.audioContainer), ...step.args]) : await encode(
12047
12130
  input.sourcePath ?? input.audioPath,
12048
12131
  input.outputPath,
12049
12132
  targetDurationSeconds,
@@ -12127,7 +12210,7 @@ async function cutSource(input, scratchDir, attenuationDb) {
12127
12210
  try {
12128
12211
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
12129
12212
  if (!result.success) throw new Error(result.error);
12130
- renameWithRetry5(cutPath, input.sourcePath, { copyFallback: true });
12213
+ renameWithRetry4(cutPath, input.sourcePath, { copyFallback: true });
12131
12214
  return true;
12132
12215
  } catch {
12133
12216
  removeScratch(input.sourcePath);
@@ -12154,7 +12237,7 @@ async function enforceAacTruePeak(input) {
12154
12237
  if (truePeakDbfs <= AAC_DELIVERY_TRUE_PEAK_DBFS) {
12155
12238
  if (measuredPath !== correctedPath) return { success: true };
12156
12239
  const sourceCut = await cutSource(input, scratchDir, attenuationDb);
12157
- renameWithRetry5(correctedPath, input.audioPath, { copyFallback: true });
12240
+ renameWithRetry4(correctedPath, input.audioPath, { copyFallback: true });
12158
12241
  const loweredDb = Number((-attenuationDb).toFixed(2));
12159
12242
  return sourceCut ? { success: true, loweredDb } : { success: true, loweredDb, sourceStale: true };
12160
12243
  }
@@ -12209,7 +12292,8 @@ function failResult(outputPath, target, source, error) {
12209
12292
  error
12210
12293
  };
12211
12294
  }
12212
- async function defaultProbeVideoFrameInfo(videoPath, signal) {
12295
+ async function defaultProbeVideoFrameInfo(videoPath, signal, container) {
12296
+ const inputArgs = localContainerInputArgs(container);
12213
12297
  const fastInfo = await runFfprobeJson(
12214
12298
  [
12215
12299
  "-v",
@@ -12220,6 +12304,7 @@ async function defaultProbeVideoFrameInfo(videoPath, signal) {
12220
12304
  "stream=nb_frames,r_frame_rate",
12221
12305
  "-of",
12222
12306
  "json",
12307
+ ...inputArgs,
12223
12308
  "--",
12224
12309
  videoPath
12225
12310
  ],
@@ -12241,6 +12326,7 @@ async function defaultProbeVideoFrameInfo(videoPath, signal) {
12241
12326
  "stream=nb_read_packets,r_frame_rate",
12242
12327
  "-of",
12243
12328
  "json",
12329
+ ...inputArgs,
12244
12330
  "--",
12245
12331
  videoPath
12246
12332
  ],
@@ -12263,8 +12349,8 @@ function parseFrameRate(rate) {
12263
12349
  }
12264
12350
  return { fpsNum, fpsDen };
12265
12351
  }
12266
- async function defaultProbeAudioInfo(audioPath, signal) {
12267
- const metadata = await extractAudioMetadata3(audioPath, { signal });
12352
+ async function defaultProbeAudioInfo(audioPath, signal, inputContainer) {
12353
+ const metadata = await extractAudioMetadata3(audioPath, { signal, inputContainer });
12268
12354
  return {
12269
12355
  durationSeconds: metadata.durationSeconds,
12270
12356
  sampleRate: metadata.sampleRate,
@@ -12275,9 +12361,9 @@ async function defaultProbeAudioInfo(audioPath, signal) {
12275
12361
  async function defaultRunFfmpeg(args, timeoutMs, signal) {
12276
12362
  return toStepResult(await runFfmpeg5(args, { signal, timeout: timeoutMs }), timeoutMs);
12277
12363
  }
12278
- function defaultAacEncoder(timeoutMs, signal, pcmSourcePath) {
12364
+ function defaultAacEncoder(timeoutMs, signal, pcmSourcePath, inputContainer) {
12279
12365
  return async (inputPath, outputPath, durationSeconds, filter) => {
12280
- const options = pcmSourcePath ? { signal, timeout: timeoutMs, filter } : { signal, timeout: timeoutMs, filter, segments: 1 };
12366
+ const options = pcmSourcePath ? { signal, timeout: timeoutMs, filter } : { signal, timeout: timeoutMs, filter, segments: 1, inputContainer };
12281
12367
  return toStepResult(
12282
12368
  await encodeAac(pcmSourcePath ?? inputPath, outputPath, durationSeconds, options),
12283
12369
  timeoutMs
@@ -12350,8 +12436,8 @@ async function limitDeliveryPeaks(input, deps = {
12350
12436
  measure: measureTruePeakDbfs,
12351
12437
  applyChain: applyAudioFxChain,
12352
12438
  encode: encodeAac2,
12353
- rename: renameWithRetry6,
12354
- sourceExists: existsSync16
12439
+ rename: renameWithRetry5,
12440
+ sourceExists: existsSync15
12355
12441
  }) {
12356
12442
  const { audioPath, sourcePath, signal, timeoutMs } = input;
12357
12443
  if (!deps.sourceExists(sourcePath)) return { success: true };
@@ -12447,7 +12533,7 @@ async function runAudioStageScoped(input) {
12447
12533
  );
12448
12534
  audioLoweredDb = guard.loweredDb;
12449
12535
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
12450
- if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
12536
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
12451
12537
  deliverySourcePath = pcmSourcePath;
12452
12538
  }
12453
12539
  }
@@ -12576,7 +12662,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12576
12662
  }
12577
12663
 
12578
12664
  // src/services/render/stages/captureStage.ts
12579
- import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12665
+ import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12580
12666
  import { join as join28 } from "node:path";
12581
12667
  import {
12582
12668
  classifyCaptureFailure as classifyCaptureFailure2,
@@ -12647,7 +12733,7 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
12647
12733
  }
12648
12734
  function measureCaptureFrameBytes(workDir, framesDir) {
12649
12735
  let total = sampleDirectoryBytes(framesDir);
12650
- if (!existsSync18(workDir)) return total;
12736
+ if (!existsSync17(workDir)) return total;
12651
12737
  for (const attempt of readdirSync4(workDir)) {
12652
12738
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
12653
12739
  total += sampleDirectoryBytes(join28(workDir, attempt));
@@ -12954,7 +13040,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
12954
13040
  }
12955
13041
 
12956
13042
  // src/services/render/stages/captureHdrStage.ts
12957
- import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
13043
+ import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
12958
13044
  import { join as join32 } from "node:path";
12959
13045
  import {
12960
13046
  closeCaptureSession as closeCaptureSession7,
@@ -13201,7 +13287,7 @@ import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
13201
13287
  import { dirname as dirname12, join as join30 } from "node:path";
13202
13288
  import { createRequire } from "node:module";
13203
13289
  import { usableCpuCount } from "@hyperframes/engine";
13204
- import { existsSync as existsSync19 } from "node:fs";
13290
+ import { existsSync as existsSync18 } from "node:fs";
13205
13291
  function resolveWorkerEntry(explicit) {
13206
13292
  if (explicit && explicit.length > 0) {
13207
13293
  return { path: explicit, isTs: explicit.endsWith(".ts") };
@@ -13213,7 +13299,7 @@ function resolveWorkerEntry(explicit) {
13213
13299
  }
13214
13300
  const moduleDir = dirname12(fileURLToPath3(import.meta.url));
13215
13301
  const jsPath = join30(moduleDir, "shaderTransitionWorker.js");
13216
- if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
13302
+ if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
13217
13303
  const tsPath = join30(moduleDir, "shaderTransitionWorker.ts");
13218
13304
  return { path: tsPath, isTs: true };
13219
13305
  }
@@ -13779,7 +13865,7 @@ async function runCaptureHdrStage(input) {
13779
13865
  }
13780
13866
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
13781
13867
  const debugDumpDir = debugDumpEnabled ? join32(framesDir, "debug-composite") : null;
13782
- if (debugDumpDir && !existsSync20(debugDumpDir)) {
13868
+ if (debugDumpDir && !existsSync19(debugDumpDir)) {
13783
13869
  mkdirSync10(debugDumpDir, { recursive: true });
13784
13870
  }
13785
13871
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -13938,13 +14024,13 @@ async function runCaptureHdrStage(input) {
13938
14024
  // src/services/render/stages/encodeStage.ts
13939
14025
  import {
13940
14026
  copyFileSync as copyFileSync4,
13941
- existsSync as existsSync21,
14027
+ existsSync as existsSync20,
13942
14028
  mkdirSync as mkdirSync11,
13943
14029
  readdirSync as readdirSync5,
13944
14030
  readFileSync as readFileSync9,
13945
14031
  rmSync as rmSync11,
13946
14032
  statSync as statSync9,
13947
- writeFileSync as writeFileSync6
14033
+ writeFileSync as writeFileSync5
13948
14034
  } from "node:fs";
13949
14035
  import { readFile as readFile2 } from "node:fs/promises";
13950
14036
  import { dirname as dirname13, join as join33 } from "node:path";
@@ -14040,7 +14126,7 @@ async function reencodeWithClearedWholeFrames(argsInput, run, startTime) {
14040
14126
  const error = "[FFmpeg] GIF output could not be parsed to clear its frames";
14041
14127
  return gifEncodeFailure(startTime, outputPath, error);
14042
14128
  }
14043
- writeFileSync6(outputPath, gif);
14129
+ writeFileSync5(outputPath, gif);
14044
14130
  return null;
14045
14131
  }
14046
14132
  async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
@@ -14072,7 +14158,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14072
14158
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
14073
14159
  if (failure) return failure;
14074
14160
  }
14075
- const fileSize = existsSync21(outputPath) ? statSync9(outputPath).size : 0;
14161
+ const fileSize = existsSync20(outputPath) ? statSync9(outputPath).size : 0;
14076
14162
  return {
14077
14163
  success: true,
14078
14164
  outputPath,
@@ -14241,7 +14327,7 @@ async function runEncodeStage(input) {
14241
14327
  const stage5Start = Date.now();
14242
14328
  if (isPngSequence) {
14243
14329
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
14244
- if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
14330
+ if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
14245
14331
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
14246
14332
  if (captured.length === 0) {
14247
14333
  throw new Error(
@@ -14252,7 +14338,7 @@ async function runEncodeStage(input) {
14252
14338
  const dst = join33(outputPath, formatExportFrameName(i, "png"));
14253
14339
  copyFileSync4(join33(framesDir, name), dst);
14254
14340
  });
14255
- if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
14341
+ if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
14256
14342
  copyFileSync4(audioOutputPath, join33(outputPath, MIXED_AUDIO_FILENAME2));
14257
14343
  log.info(
14258
14344
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
@@ -14643,7 +14729,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14643
14729
  let rangeStart = null;
14644
14730
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14645
14731
  const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14646
- const missing = !existsSync22(framePath) || statSync10(framePath).size <= 8;
14732
+ const missing = !existsSync21(framePath) || statSync10(framePath).size <= 8;
14647
14733
  if (missing && rangeStart === null) {
14648
14734
  rangeStart = frameIndex;
14649
14735
  } else if (!missing && rangeStart !== null) {
@@ -14776,7 +14862,7 @@ function countCapturedFrames(totalFrames, framesDir, frameExt) {
14776
14862
  let captured = 0;
14777
14863
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14778
14864
  const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14779
- if (existsSync22(framePath)) captured++;
14865
+ if (existsSync21(framePath)) captured++;
14780
14866
  }
14781
14867
  return captured;
14782
14868
  }
@@ -15457,7 +15543,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15457
15543
  validateChromaSubsamplingConfig(job.config);
15458
15544
  const debugDir = resolveRenderDebugDir();
15459
15545
  const outputDir = dirname14(outputPath);
15460
- if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
15546
+ if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
15461
15547
  const workDir = job.config.debug ? join34(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15462
15548
  const pipelineStart = Date.now();
15463
15549
  const baseLog = job.config.logger ?? defaultLogger;
@@ -15614,7 +15700,7 @@ async function executeRenderPipeline(input) {
15614
15700
  job.startedAt = /* @__PURE__ */ new Date();
15615
15701
  assertNotAborted();
15616
15702
  assertConfiguredFfmpegBinariesExist();
15617
- if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
15703
+ if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
15618
15704
  if (job.config.debug) {
15619
15705
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
15620
15706
  }
@@ -15644,7 +15730,7 @@ async function executeRenderPipeline(input) {
15644
15730
  });
15645
15731
  const entryFile = job.config.entryFile || "index.html";
15646
15732
  const htmlPath = join34(projectDir, entryFile);
15647
- if (!existsSync22(htmlPath)) {
15733
+ if (!existsSync21(htmlPath)) {
15648
15734
  throw new Error(`Entry file not found: ${htmlPath}`);
15649
15735
  }
15650
15736
  assertNotAborted();
@@ -15665,6 +15751,7 @@ async function executeRenderPipeline(input) {
15665
15751
  needsAlpha,
15666
15752
  log,
15667
15753
  assertNotAborted,
15754
+ abortSignal: executionSignal,
15668
15755
  variables: job.config.variables,
15669
15756
  pageMotionBlur: job.config.pageMotionBlur
15670
15757
  })
@@ -16012,7 +16099,7 @@ async function executeRenderPipeline(input) {
16012
16099
  throw new Error("File server failed to initialize before frame capture");
16013
16100
  }
16014
16101
  const framesDir = join34(workDir, "captured-frames");
16015
- if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
16102
+ if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
16016
16103
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
16017
16104
  code: "start_browsers"
16018
16105
  });
@@ -16909,29 +16996,8 @@ async function executeRenderPipeline(input) {
16909
16996
  pageMotionBlur: job.config.pageMotionBlur,
16910
16997
  captureQuality: captureOptions.quality
16911
16998
  });
16912
- const segmentDir = segmentDirFor(join34(projectDir, "renders"), segmentPlanHash);
16999
+ const segmentDir = segmentDirFor(projectDir, segmentPlanHash);
16913
17000
  const manifestKey = loadResumeKeyOrWarn(job.config.resumeSegments === true, log);
16914
- let completedSegments = /* @__PURE__ */ new Set();
16915
- if (job.config.resumeSegments === true) {
16916
- const existing = readSegmentManifest(segmentDir);
16917
- if (existing) {
16918
- completedSegments = await validateCompletedSegments(existing, {
16919
- expectedHash: segmentPlanHash,
16920
- segmentDir,
16921
- plan: planSegments(totalFrames, segmentFrames),
16922
- key: manifestKey,
16923
- probeFrames: (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
16924
- });
16925
- log.info(`[Render] resuming: ${completedSegments.size} segments complete`, {
16926
- segmentDir
16927
- });
16928
- }
16929
- if (completedSegments.size === 0) {
16930
- rmSync12(segmentDir, { recursive: true, force: true });
16931
- }
16932
- } else {
16933
- rmSync12(segmentDir, { recursive: true, force: true });
16934
- }
16935
17001
  const emptySegmentManifest = () => ({
16936
17002
  version: 1,
16937
17003
  planHash: segmentPlanHash,
@@ -16939,7 +17005,26 @@ async function executeRenderPipeline(input) {
16939
17005
  segmentFrames,
16940
17006
  completed: []
16941
17007
  });
16942
- let segmentManifest = readSegmentManifest(segmentDir) ?? emptySegmentManifest();
17008
+ let segmentManifest = emptySegmentManifest();
17009
+ let completedSegments = /* @__PURE__ */ new Set();
17010
+ const existing = job.config.resumeSegments ? readSegmentManifest(segmentDir) : null;
17011
+ if (existing) {
17012
+ completedSegments = await validateCompletedSegments(existing, {
17013
+ expectedHash: segmentPlanHash,
17014
+ segmentDir,
17015
+ totalFrames,
17016
+ segmentFrames,
17017
+ key: manifestKey,
17018
+ probeFrames: (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
17019
+ });
17020
+ segmentManifest.completed = existing.completed.filter(
17021
+ (entry) => completedSegments.has(entry.index)
17022
+ );
17023
+ log.info(`[Render] resuming: ${completedSegments.size} segments complete`, {
17024
+ segmentDir
17025
+ });
17026
+ }
17027
+ if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
16943
17028
  const invokeSegmented = () => {
16944
17029
  if (capturePlan.kind !== "sdr_segmented") {
16945
17030
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17456,7 +17541,7 @@ async function executeRenderPipeline(input) {
17456
17541
  })
17457
17542
  );
17458
17543
  const totalElapsed = Date.now() - pipelineStart;
17459
- const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
17544
+ const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
17460
17545
  recordTransientRetryObservability();
17461
17546
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
17462
17547
  const observabilitySummary = observability.summary({
@@ -17528,7 +17613,7 @@ async function executeRenderPipeline(input) {
17528
17613
  job.perfSummary = perfSummary;
17529
17614
  if (job.config.debug) {
17530
17615
  try {
17531
- writeFileSync7(perfOutputPath, JSON.stringify(perfSummary, null, 2), "utf-8");
17616
+ writeFileSync6(perfOutputPath, JSON.stringify(perfSummary, null, 2), "utf-8");
17532
17617
  } catch (err) {
17533
17618
  log.debug("Failed to write perf summary", {
17534
17619
  perfOutputPath,
@@ -17537,7 +17622,7 @@ async function executeRenderPipeline(input) {
17537
17622
  }
17538
17623
  }
17539
17624
  if (job.config.debug) {
17540
- if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
17625
+ if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
17541
17626
  const debugOutput = join34(workDir, `output${videoExt}`);
17542
17627
  copyFileSync5(stagedOutputPath, debugOutput);
17543
17628
  }
@@ -17663,7 +17748,7 @@ import { tmpdir as tmpdir5 } from "node:os";
17663
17748
  // src/services/distributed/mp4Stitch.ts
17664
17749
  import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
17665
17750
  import { open } from "node:fs/promises";
17666
- import { renameWithRetry as renameWithRetry7 } from "@hyperframes/engine";
17751
+ import { renameWithRetry as renameWithRetry6 } from "@hyperframes/engine";
17667
17752
  import { basename as basename8, dirname as dirname15, join as join35 } from "node:path";
17668
17753
  import { finished, pipeline } from "node:stream/promises";
17669
17754
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
@@ -18037,7 +18122,7 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
18037
18122
  for (const [i, path] of sourcePaths.entries()) await copyPayload(path, layouts[i], i, out);
18038
18123
  out.end();
18039
18124
  await finished(out);
18040
- renameWithRetry7(join35(workDir, "out.mp4"), outputPath);
18125
+ renameWithRetry6(join35(workDir, "out.mp4"), outputPath);
18041
18126
  } finally {
18042
18127
  out.destroy();
18043
18128
  rmSync13(workDir, { recursive: true, force: true });
@@ -18054,25 +18139,25 @@ import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframe
18054
18139
  import {
18055
18140
  copyFileSync as copyFileSync6,
18056
18141
  cpSync as cpSync2,
18057
- existsSync as existsSync27,
18142
+ existsSync as existsSync26,
18058
18143
  linkSync,
18059
18144
  mkdirSync as mkdirSync16,
18060
18145
  rmSync as rmSync14,
18061
- writeFileSync as writeFileSync10
18146
+ writeFileSync as writeFileSync9
18062
18147
  } from "node:fs";
18063
18148
  import { extname as extname6, isAbsolute as isAbsolute4, join as join43, relative as relative7, sep as sep5 } from "node:path";
18064
18149
  import {
18065
18150
  fpsToNumber as fpsToNumber9,
18066
18151
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
18067
18152
  } from "@hyperframes/core";
18068
- import { isSafePath as isSafePath2 } from "@hyperframes/core/safe-path";
18153
+ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
18069
18154
  import {
18070
18155
  getEncoderPreset as getEncoderPreset4,
18071
18156
  keyframeIntervalToGopSize as keyframeIntervalToGopSize3,
18072
18157
  normalizeVp9CpuUsed,
18073
18158
  resolveConfig as resolveConfig3,
18074
18159
  declareContentAddressedUrl,
18075
- renameWithRetry as renameWithRetry8,
18160
+ renameWithRetry as renameWithRetry7,
18076
18161
  declareProbeFactsUrl
18077
18162
  } from "@hyperframes/engine";
18078
18163
 
@@ -18086,7 +18171,7 @@ import {
18086
18171
  } from "@hyperframes/engine";
18087
18172
 
18088
18173
  // src/services/distributed/chunkFrames.ts
18089
- import { existsSync as existsSync24, readdirSync as readdirSync7 } from "node:fs";
18174
+ import { existsSync as existsSync23, readdirSync as readdirSync7 } from "node:fs";
18090
18175
  import { extname as extname4, join as join37 } from "node:path";
18091
18176
  import {
18092
18177
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
@@ -18097,7 +18182,7 @@ import {
18097
18182
  // src/services/distributed/shared.ts
18098
18183
  import { execFile as execFileCallback } from "node:child_process";
18099
18184
  import { dirname as dirname16, join as join36 } from "node:path";
18100
- import { existsSync as existsSync23, readFileSync as readFileSync10 } from "node:fs";
18185
+ import { existsSync as existsSync22, readFileSync as readFileSync10 } from "node:fs";
18101
18186
  import { fileURLToPath as fileURLToPath5 } from "node:url";
18102
18187
  import { promisify as promisify2 } from "node:util";
18103
18188
  import {
@@ -18113,7 +18198,7 @@ function isPlanAudioArtifactPath(path) {
18113
18198
  function resolvePlanAudioPath(planDir) {
18114
18199
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
18115
18200
  const candidate = join36(planDir, name);
18116
- if (existsSync23(candidate)) return candidate;
18201
+ if (existsSync22(candidate)) return candidate;
18117
18202
  }
18118
18203
  return null;
18119
18204
  }
@@ -18378,7 +18463,7 @@ function readProducerVersion() {
18378
18463
  let current = startDir;
18379
18464
  for (let i = 0; i < 10; i++) {
18380
18465
  const candidate = join36(current, "package.json");
18381
- if (existsSync23(candidate)) {
18466
+ if (existsSync22(candidate)) {
18382
18467
  try {
18383
18468
  const pkg = JSON.parse(readFileSync10(candidate, "utf-8"));
18384
18469
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
@@ -18433,7 +18518,7 @@ function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v
18433
18518
  const result = [];
18434
18519
  for (const v of videos) {
18435
18520
  const outputDir = join37(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
18436
- if (!existsSync24(outputDir)) {
18521
+ if (!existsSync23(outputDir)) {
18437
18522
  throw new Error(
18438
18523
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
18439
18524
  );
@@ -18532,7 +18617,7 @@ async function extractDeferredVideoFramesForChunk(input) {
18532
18617
  const range = planned.get(video.videoId).deferredRange;
18533
18618
  const remoteUrl = remoteSources[range.sourcePath];
18534
18619
  const sourcePath = remoteUrl ?? join37(input.planDir, ...range.sourcePath.split("/"));
18535
- if (remoteUrl === void 0 && !existsSync24(sourcePath)) {
18620
+ if (remoteUrl === void 0 && !existsSync23(sourcePath)) {
18536
18621
  throw new RenderChunkValidationError(
18537
18622
  MISSING_PLAN_ARTIFACT,
18538
18623
  `[renderChunk] planDir is missing the source for video ${JSON.stringify(video.videoId)}: ${range.sourcePath}`
@@ -18732,7 +18817,7 @@ async function readPlanReferenceBackground(input) {
18732
18817
  }
18733
18818
 
18734
18819
  // src/services/render/stages/freezePlan.ts
18735
- import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
18820
+ import { existsSync as existsSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
18736
18821
  import { join as join40, relative as relative5, resolve as resolve10 } from "node:path";
18737
18822
  import {
18738
18823
  REFERENCE_BACKGROUND_FIELD,
@@ -18832,7 +18917,7 @@ function readPlanProtocolV1(planJson, capabilities = DISTRIBUTED_RENDER_CAPABILI
18832
18917
 
18833
18918
  // src/services/render/stages/planHash.ts
18834
18919
  import { createHash as createHash8 } from "node:crypto";
18835
- import { closeSync as closeSync5, createReadStream as createReadStream5, openSync as openSync5, readSync as readSync5 } from "node:fs";
18920
+ import { closeSync as closeSync6, createReadStream as createReadStream5, openSync as openSync6, readSync as readSync5 } from "node:fs";
18836
18921
  var PLAN_HASH_SCHEMA_PREFIX = "hyperframes-plan-hash-v1\0";
18837
18922
  var FIELD_DELIMITER = Buffer.from([0]);
18838
18923
  function computePlanHash(input) {
@@ -18890,7 +18975,7 @@ function sha256Hex(bytes) {
18890
18975
  function sha256File(path) {
18891
18976
  const hash = createHash8("sha256");
18892
18977
  const buffer = Buffer.allocUnsafe(1024 * 1024);
18893
- const fd = openSync5(path, "r");
18978
+ const fd = openSync6(path, "r");
18894
18979
  try {
18895
18980
  let bytesRead = 0;
18896
18981
  do {
@@ -18898,7 +18983,7 @@ function sha256File(path) {
18898
18983
  if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead));
18899
18984
  } while (bytesRead > 0);
18900
18985
  } finally {
18901
- closeSync5(fd);
18986
+ closeSync6(fd);
18902
18987
  }
18903
18988
  return hash.digest("hex");
18904
18989
  }
@@ -18926,7 +19011,7 @@ function planFileSha256(absolutePath, digests) {
18926
19011
  return sha256;
18927
19012
  }
18928
19013
  async function prehashPlanFiles(dir, digests) {
18929
- if (!existsSync25(dir)) return;
19014
+ if (!existsSync24(dir)) return;
18930
19015
  for (const { absolutePath } of listPlanFiles(dir)) {
18931
19016
  if (!digests.has(absolutePath)) digests.set(absolutePath, await sha256FileAsync(absolutePath));
18932
19017
  }
@@ -18992,19 +19077,19 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
18992
19077
  function writePlanRemoteFiles(planDir, files) {
18993
19078
  if (files.length === 0) return;
18994
19079
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
18995
- writeFileSync8(join40(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
19080
+ writeFileSync7(join40(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
18996
19081
  }
18997
19082
  function readPlanRemoteFiles(planDir) {
18998
19083
  const path = join40(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
18999
- return existsSync25(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
19084
+ return existsSync24(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
19000
19085
  }
19001
19086
  function recomputePlanHashFromPlanDir(planDir, digests) {
19002
19087
  const planJsonPath = join40(planDir, "plan.json");
19003
19088
  const encoderJsonPath = join40(planDir, "meta", "encoder.json");
19004
- if (!existsSync25(planJsonPath)) {
19089
+ if (!existsSync24(planJsonPath)) {
19005
19090
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
19006
19091
  }
19007
- if (!existsSync25(encoderJsonPath)) {
19092
+ if (!existsSync24(encoderJsonPath)) {
19008
19093
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
19009
19094
  }
19010
19095
  const planJson = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
@@ -19034,12 +19119,12 @@ async function freezePlan(input) {
19034
19119
  hasAudio,
19035
19120
  digests
19036
19121
  } = input;
19037
- if (!existsSync25(planDir)) {
19122
+ if (!existsSync24(planDir)) {
19038
19123
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
19039
19124
  }
19040
19125
  const metaDir = join40(planDir, "meta");
19041
- if (!existsSync25(metaDir)) mkdirSync14(metaDir, { recursive: true });
19042
- writeFileSync8(
19126
+ if (!existsSync24(metaDir)) mkdirSync14(metaDir, { recursive: true });
19127
+ writeFileSync7(
19043
19128
  join40(metaDir, "composition.json"),
19044
19129
  `${JSON.stringify(composition, null, 2)}
19045
19130
  `,
@@ -19047,8 +19132,8 @@ async function freezePlan(input) {
19047
19132
  );
19048
19133
  const encoderForCanonical = stripUndefined(encoder);
19049
19134
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
19050
- writeFileSync8(join40(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
19051
- writeFileSync8(join40(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
19135
+ writeFileSync7(join40(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
19136
+ writeFileSync7(join40(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
19052
19137
  `, "utf-8");
19053
19138
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
19054
19139
  const planHash = computePlanHash({
@@ -19074,7 +19159,7 @@ async function freezePlan(input) {
19074
19159
  hasAudio
19075
19160
  };
19076
19161
  const planJsonPath = join40(planDir, "plan.json");
19077
- writeFileSync8(planJsonPath, `${JSON.stringify(planJson, null, 2)}
19162
+ writeFileSync7(planJsonPath, `${JSON.stringify(planJson, null, 2)}
19078
19163
  `, "utf-8");
19079
19164
  return { planJsonPath, planHash };
19080
19165
  }
@@ -19115,8 +19200,8 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
19115
19200
  }
19116
19201
 
19117
19202
  // src/services/distributed/chunkAudio.ts
19118
- import { closeSync as closeSync6, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
19119
- import { writeFileSync as writeFileSync9, writeSync } from "node:fs";
19203
+ import { closeSync as closeSync7, existsSync as existsSync25, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync7, readFileSync as readFileSync12 } from "node:fs";
19204
+ import { writeFileSync as writeFileSync8, writeSync } from "node:fs";
19120
19205
  import { join as join41 } from "node:path";
19121
19206
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
19122
19207
  function audioCutForChunk(grid, chunks, index, fps) {
@@ -19213,18 +19298,18 @@ async function writeChunkAudioSlices(input) {
19213
19298
  const start = offsets[cut.firstPacket];
19214
19299
  layout.partStarts[index] = start;
19215
19300
  const end = offsets[last] + track.sizes[last];
19216
- writeFileSync9(join41(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
19301
+ writeFileSync8(join41(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
19217
19302
  });
19218
19303
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
19219
- writeFileSync9(join41(input.planDir, SLICE_FRAME), Buffer.concat(frame));
19220
- writeFileSync9(join41(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
19304
+ writeFileSync8(join41(input.planDir, SLICE_FRAME), Buffer.concat(frame));
19305
+ writeFileSync8(join41(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
19221
19306
  }
19222
19307
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19223
19308
  const layoutPath = join41(planDir, SLICE_LAYOUT);
19224
- if (!existsSync26(layoutPath)) return resolvePlanAudioPath(planDir);
19309
+ if (!existsSync25(layoutPath)) return resolvePlanAudioPath(planDir);
19225
19310
  const layout = JSON.parse(readFileSync12(layoutPath, "utf-8"));
19226
19311
  const frame = readFileSync12(join41(planDir, SLICE_FRAME));
19227
- const fd = openSync6(scratchPath, "w");
19312
+ const fd = openSync7(scratchPath, "w");
19228
19313
  try {
19229
19314
  writeSync(fd, frame, 0, layout.payloadStart, 0);
19230
19315
  writeSync(
@@ -19241,7 +19326,7 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19241
19326
  }
19242
19327
  ftruncateSync(fd, layout.sizeBytes);
19243
19328
  } finally {
19244
- closeSync6(fd);
19329
+ closeSync7(fd);
19245
19330
  }
19246
19331
  return scratchPath;
19247
19332
  }
@@ -19788,7 +19873,7 @@ function createVideoSourceShipper(input) {
19788
19873
  let result = null;
19789
19874
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
19790
19875
  const rel = pathInside(root, srcPath);
19791
- if (rel !== null && (existsSync27(join43(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
19876
+ if (rel !== null && (existsSync26(join43(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
19792
19877
  result = ["compiled", ...rel.split(sep5)].join("/");
19793
19878
  break;
19794
19879
  }
@@ -19816,7 +19901,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19816
19901
  useGpu: false,
19817
19902
  browserGpuMode: "software"
19818
19903
  });
19819
- if (!existsSync27(planDir)) mkdirSync16(planDir, { recursive: true });
19904
+ if (!existsSync26(planDir)) mkdirSync16(planDir, { recursive: true });
19820
19905
  const log = config.logger ?? defaultLogger;
19821
19906
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
19822
19907
  const abortSignal = config.abortSignal;
@@ -19851,7 +19936,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19851
19936
  });
19852
19937
  const entryFile = config.entryFile ?? "index.html";
19853
19938
  const htmlPath = join43(projectDir, entryFile);
19854
- if (!existsSync27(htmlPath)) {
19939
+ if (!existsSync26(htmlPath)) {
19855
19940
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
19856
19941
  }
19857
19942
  const workDir = join43(planDir, ".plan-work");
@@ -19871,7 +19956,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19871
19956
  const warn = (line) => log.warn(`[Plan] ${line}`);
19872
19957
  const policy = { includeScripts: job.config.includeOutsideScripts };
19873
19958
  if (refusesOutsideLink(projectDir, src, warn, policy)) return false;
19874
- } else if (!isSafePath2(projectDir, src)) return false;
19959
+ } else if (!isSafePath3(projectDir, src)) return false;
19875
19960
  const firstSegment = rel.split(sep5, 1)[0];
19876
19961
  return firstSegment === void 0 || !PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(firstSegment);
19877
19962
  }
@@ -20087,16 +20172,16 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20087
20172
  logPlanStage(log, "extract", stageStarted);
20088
20173
  const stagedVideoFrames = join43(compiledDir, "__hyperframes_video_frames");
20089
20174
  const videoFramesDst = join43(planDir, "video-frames");
20090
- if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
20175
+ if (existsSync26(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
20091
20176
  const videoSourcesDir = join43(planDir, "video-sources");
20092
20177
  rmSync14(videoSourcesDir, { recursive: true, force: true });
20093
- if (existsSync27(stagedVideoFrames)) {
20094
- renameWithRetry8(stagedVideoFrames, videoFramesDst);
20178
+ if (existsSync26(stagedVideoFrames)) {
20179
+ renameWithRetry7(stagedVideoFrames, videoFramesDst);
20095
20180
  } else {
20096
20181
  mkdirSync16(videoFramesDst, { recursive: true });
20097
20182
  }
20098
- if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
20099
- renameWithRetry8(compiledDir, finalCompiledDir);
20183
+ if (existsSync26(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
20184
+ renameWithRetry7(compiledDir, finalCompiledDir);
20100
20185
  const shipVideoSource = createVideoSourceShipper({
20101
20186
  planDir,
20102
20187
  projectDir,
@@ -20134,7 +20219,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20134
20219
  sizeBytes
20135
20220
  }))
20136
20221
  );
20137
- writeFileSync10(
20222
+ writeFileSync9(
20138
20223
  join43(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
20139
20224
  JSON.stringify(planVideosJson, null, 2),
20140
20225
  "utf-8"
@@ -20216,10 +20301,10 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20216
20301
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
20217
20302
  }
20218
20303
  const planAudioPath = join43(planDir, PLAN_AUDIO_RELATIVE_PATH);
20219
- if (audioResult?.hasAudio && existsSync27(audioResult.audioOutputPath)) {
20220
- renameWithRetry8(audioResult.audioOutputPath, planAudioPath);
20304
+ if (audioResult?.hasAudio && existsSync26(audioResult.audioOutputPath)) {
20305
+ renameWithRetry7(audioResult.audioOutputPath, planAudioPath);
20221
20306
  }
20222
- if (chunksCarryAudio && existsSync27(planAudioPath)) {
20307
+ if (chunksCarryAudio && existsSync26(planAudioPath)) {
20223
20308
  if (options.sliceChunkAudio) {
20224
20309
  stageStarted = Date.now();
20225
20310
  await writeChunkAudioSlices({
@@ -20341,7 +20426,7 @@ async function plan(projectDir, config, planDir, options = {}) {
20341
20426
 
20342
20427
  // src/services/distributed/renderChunk.ts
20343
20428
  import { randomBytes } from "node:crypto";
20344
- import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
20429
+ import { existsSync as existsSync29, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync12 } from "node:fs";
20345
20430
  import { join as join47 } from "node:path";
20346
20431
  import {
20347
20432
  assertSwiftShader,
@@ -20368,14 +20453,14 @@ import {
20368
20453
  } from "@hyperframes/engine";
20369
20454
  import {
20370
20455
  copyFileSync as copyFileSync8,
20371
- existsSync as existsSync29,
20456
+ existsSync as existsSync28,
20372
20457
  lstatSync as lstatSync5,
20373
20458
  mkdirSync as mkdirSync18,
20374
20459
  readFileSync as readFileSync13,
20375
20460
  readdirSync as readdirSync10,
20376
20461
  rmSync as rmSync16,
20377
20462
  statSync as statSync12,
20378
- writeFileSync as writeFileSync12
20463
+ writeFileSync as writeFileSync11
20379
20464
  } from "node:fs";
20380
20465
  import { tmpdir as tmpdir4 } from "node:os";
20381
20466
  import { dirname as dirname18, isAbsolute as isAbsolute5, join as join46, relative as relative8, resolve as resolve11, sep as sep6 } from "node:path";
@@ -20383,20 +20468,20 @@ import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
20383
20468
  import {
20384
20469
  createFrameLookupTable as createFrameLookupTable5,
20385
20470
  mediaIdPathSegment as mediaIdPathSegment4,
20386
- renameWithRetry as renameWithRetry10
20471
+ renameWithRetry as renameWithRetry9
20387
20472
  } from "@hyperframes/engine";
20388
20473
 
20389
20474
  // src/services/distributed/planV2Publisher.ts
20390
20475
  import {
20391
20476
  copyFileSync as copyFileSync7,
20392
- existsSync as existsSync28,
20477
+ existsSync as existsSync27,
20393
20478
  linkSync as linkSync2,
20394
20479
  mkdirSync as mkdirSync17,
20395
20480
  rmSync as rmSync15,
20396
20481
  statSync as statSync11,
20397
- writeFileSync as writeFileSync11
20482
+ writeFileSync as writeFileSync10
20398
20483
  } from "node:fs";
20399
- import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
20484
+ import { renameWithRetry as renameWithRetry8 } from "@hyperframes/engine";
20400
20485
  import { dirname as dirname17, join as join45 } from "node:path";
20401
20486
 
20402
20487
  // src/services/distributed/planV2Errors.ts
@@ -20453,7 +20538,7 @@ var LocalPlanV2ArtifactPublisher = class {
20453
20538
  #linkFile;
20454
20539
  #committed = false;
20455
20540
  constructor(destinationDir, options = {}) {
20456
- if (existsSync28(destinationDir)) {
20541
+ if (existsSync27(destinationDir)) {
20457
20542
  throw new PlanV2IntegrityError(`output directory already exists: ${destinationDir}`);
20458
20543
  }
20459
20544
  this.destinationDir = destinationDir;
@@ -20470,7 +20555,7 @@ var LocalPlanV2ArtifactPublisher = class {
20470
20555
  );
20471
20556
  }
20472
20557
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
20473
- if (existsSync28(destinationPath)) return;
20558
+ if (existsSync27(destinationPath)) return;
20474
20559
  mkdirSync17(dirname17(destinationPath), { recursive: true });
20475
20560
  const stagingDir = createStagingDir5(dirname17(destinationPath), ".plan-v2-blob-");
20476
20561
  const temporaryPath = join45(stagingDir, "blob");
@@ -20481,21 +20566,21 @@ var LocalPlanV2ArtifactPublisher = class {
20481
20566
  if (!cannotHardLink(error)) throw error;
20482
20567
  copyFileSync7(blob.sourcePath, temporaryPath);
20483
20568
  }
20484
- renameWithRetry9(temporaryPath, destinationPath);
20569
+ renameWithRetry8(temporaryPath, destinationPath);
20485
20570
  } finally {
20486
20571
  rmSync15(stagingDir, { recursive: true, force: true });
20487
20572
  }
20488
20573
  }
20489
20574
  async commitManifest(manifestBytes) {
20490
20575
  for (const digest of new Set(manifestDigests(manifestBytes))) {
20491
- if (!existsSync28(planV2BlobPath(this.temporaryDir, digest))) {
20576
+ if (!existsSync27(planV2BlobPath(this.temporaryDir, digest))) {
20492
20577
  throw new PlanV2IntegrityError(
20493
20578
  `cannot commit manifest before referenced blob is durable: ${digest}`
20494
20579
  );
20495
20580
  }
20496
20581
  }
20497
- writeFileSync11(join45(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
20498
- renameWithRetry9(this.temporaryDir, this.destinationDir);
20582
+ writeFileSync10(join45(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
20583
+ renameWithRetry8(this.temporaryDir, this.destinationDir);
20499
20584
  this.#committed = true;
20500
20585
  }
20501
20586
  async abort() {
@@ -20568,7 +20653,7 @@ function assertValidExtractionCacheCompleteSentinel(path) {
20568
20653
  }
20569
20654
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
20570
20655
  const videoRoot = join46(executionPlanDir, "video-frames");
20571
- if (!existsSync29(videoRoot)) return;
20656
+ if (!existsSync28(videoRoot)) return;
20572
20657
  for (const videoEntry of readdirSync10(videoRoot, { withFileTypes: true })) {
20573
20658
  if (!videoEntry.isDirectory()) continue;
20574
20659
  const videoDir = join46(videoRoot, videoEntry.name);
@@ -20669,7 +20754,7 @@ function parsePlanVideosJson2(value) {
20669
20754
  }
20670
20755
  function materializeExtractedVideoDirectories(planDir) {
20671
20756
  const videosPath = join46(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20672
- if (!existsSync29(videosPath)) return;
20757
+ if (!existsSync28(videosPath)) return;
20673
20758
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
20674
20759
  for (const video of videos.extracted) {
20675
20760
  mkdirSync18(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
@@ -20703,9 +20788,9 @@ function parseChunkSlices(value) {
20703
20788
  }
20704
20789
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
20705
20790
  const videoRoot = join46(executionPlanDir, "video-frames");
20706
- const hasExtractedFrames = existsSync29(videoRoot) && listFiles(videoRoot).length > 0;
20791
+ const hasExtractedFrames = existsSync28(videoRoot) && listFiles(videoRoot).length > 0;
20707
20792
  const videosPath = join46(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20708
- if (!existsSync29(videosPath)) {
20793
+ if (!existsSync28(videosPath)) {
20709
20794
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
20710
20795
  }
20711
20796
  const chunksPath = join46(executionPlanDir, "meta", "chunks.json");
@@ -20762,13 +20847,13 @@ function computeManifestHash(manifest) {
20762
20847
  return sha256Hex(`${PLAN_V2_HASH_PREFIX}${canonicalJsonStringify(manifestPayload(manifest))}`);
20763
20848
  }
20764
20849
  function writeBlob(sourcePath, destinationPath) {
20765
- if (existsSync29(destinationPath)) return;
20850
+ if (existsSync28(destinationPath)) return;
20766
20851
  mkdirSync18(dirname18(destinationPath), { recursive: true });
20767
20852
  const temporaryDir = createStagingDir6(dirname18(destinationPath), ".plan-v2-blob-");
20768
20853
  const temporaryPath = join46(temporaryDir, "blob");
20769
20854
  try {
20770
20855
  copyFileSync8(sourcePath, temporaryPath);
20771
- renameWithRetry10(temporaryPath, destinationPath);
20856
+ renameWithRetry9(temporaryPath, destinationPath);
20772
20857
  } finally {
20773
20858
  rmSync16(temporaryDir, { recursive: true, force: true });
20774
20859
  }
@@ -20802,7 +20887,7 @@ async function putTasks(tasks) {
20802
20887
  }
20803
20888
  function buildPlanV2Publication(executionPlanDir, digests) {
20804
20889
  const executionPlanPath = join46(executionPlanDir, "plan.json");
20805
- if (!existsSync29(executionPlanPath)) {
20890
+ if (!existsSync28(executionPlanPath)) {
20806
20891
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
20807
20892
  }
20808
20893
  const executionPlanValue = readJsonFile(executionPlanPath, "execution plan.json");
@@ -20882,7 +20967,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
20882
20967
  };
20883
20968
  }
20884
20969
  function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
20885
- if (existsSync29(planV2Dir)) {
20970
+ if (existsSync28(planV2Dir)) {
20886
20971
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
20887
20972
  }
20888
20973
  const publication = buildPlanV2Publication(executionPlanDir);
@@ -20895,12 +20980,12 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
20895
20980
  for (const blob of publication.blobs) {
20896
20981
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
20897
20982
  }
20898
- writeFileSync12(
20983
+ writeFileSync11(
20899
20984
  join46(tempDir, "plan.json"),
20900
20985
  canonicalJsonStringify(publication.manifest),
20901
20986
  "utf-8"
20902
20987
  );
20903
- renameWithRetry10(tempDir, planV2Dir);
20988
+ renameWithRetry9(tempDir, planV2Dir);
20904
20989
  return resultFromManifest(planV2Dir, publication.manifest);
20905
20990
  } catch (error) {
20906
20991
  rmSync16(tempDir, { recursive: true, force: true });
@@ -20972,7 +21057,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
20972
21057
  }
20973
21058
  }
20974
21059
  async function planV2(projectDir, config, planV2Dir) {
20975
- if (existsSync29(planV2Dir)) {
21060
+ if (existsSync28(planV2Dir)) {
20976
21061
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
20977
21062
  }
20978
21063
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
@@ -21126,7 +21211,7 @@ function parsePlanV2Manifest(value) {
21126
21211
  }
21127
21212
  function readPlanV2Manifest(planV2Dir) {
21128
21213
  const manifestPath = join46(planV2Dir, "plan.json");
21129
- if (!existsSync29(manifestPath)) {
21214
+ if (!existsSync28(manifestPath)) {
21130
21215
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
21131
21216
  }
21132
21217
  const value = readJsonFile(manifestPath, "v2 manifest");
@@ -21145,7 +21230,7 @@ function listPlanV2ArtifactsForTarget(manifest, target) {
21145
21230
  }
21146
21231
  function verifyBlob(planV2Dir, artifact) {
21147
21232
  const sourcePath = planV2BlobPath(planV2Dir, artifact.sha256);
21148
- if (!existsSync29(sourcePath)) {
21233
+ if (!existsSync28(sourcePath)) {
21149
21234
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
21150
21235
  }
21151
21236
  const stats = statSync12(sourcePath);
@@ -21158,7 +21243,7 @@ function verifyBlob(planV2Dir, artifact) {
21158
21243
  return sourcePath;
21159
21244
  }
21160
21245
  function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}) {
21161
- if (existsSync29(destinationDir)) {
21246
+ if (existsSync28(destinationDir)) {
21162
21247
  throw new PlanV2IntegrityError(`materialization destination already exists: ${destinationDir}`);
21163
21248
  }
21164
21249
  const manifest = readPlanV2Manifest(planV2Dir);
@@ -21179,7 +21264,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21179
21264
  copyFileSync8(sourcePath, destinationPath);
21180
21265
  }
21181
21266
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
21182
- writeFileSync12(
21267
+ writeFileSync11(
21183
21268
  join46(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
21184
21269
  canonicalJsonStringify({
21185
21270
  manifest,
@@ -21188,7 +21273,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21188
21273
  }),
21189
21274
  "utf-8"
21190
21275
  );
21191
- renameWithRetry10(tempDir, destinationDir);
21276
+ renameWithRetry9(tempDir, destinationDir);
21192
21277
  } catch (error) {
21193
21278
  rmSync16(tempDir, { recursive: true, force: true });
21194
21279
  throw error;
@@ -21223,7 +21308,7 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
21223
21308
  }
21224
21309
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
21225
21310
  const markerPath = join46(planDir, PLAN_V2_MATERIALIZATION_MARKER);
21226
- if (!existsSync29(markerPath)) return null;
21311
+ if (!existsSync28(markerPath)) return null;
21227
21312
  const marker = readJsonFile(markerPath, "materialization marker");
21228
21313
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
21229
21314
  throw new PlanV2IntegrityError("malformed materialization marker");
@@ -21241,7 +21326,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
21241
21326
  for (const artifact of required) {
21242
21327
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
21243
21328
  const path = join46(planDir, ...artifact.path.split("/"));
21244
- if (!existsSync29(path) || statSync12(path).size !== artifact.sizeBytes) {
21329
+ if (!existsSync28(path) || statSync12(path).size !== artifact.sizeBytes) {
21245
21330
  throw new PlanV2IntegrityError(
21246
21331
  `materialized artifact missing or truncated: ${artifact.path}`
21247
21332
  );
@@ -21392,7 +21477,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21392
21477
  const planJsonPath = join47(planDir, "plan.json");
21393
21478
  const encoderJsonPath = join47(planDir, "meta", "encoder.json");
21394
21479
  const chunksJsonPath = join47(planDir, "meta", "chunks.json");
21395
- if (!existsSync30(planJsonPath)) {
21480
+ if (!existsSync29(planJsonPath)) {
21396
21481
  throw new RenderChunkValidationError(
21397
21482
  MISSING_PLAN_ARTIFACT,
21398
21483
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
@@ -21408,7 +21493,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21408
21493
  const v2Manifest = v2Materialization?.manifest ?? null;
21409
21494
  const remoteSources = v2Materialization?.remoteSources ?? {};
21410
21495
  for (const required of [encoderJsonPath, chunksJsonPath]) {
21411
- if (!existsSync30(required)) {
21496
+ if (!existsSync29(required)) {
21412
21497
  throw new RenderChunkValidationError(
21413
21498
  MISSING_PLAN_ARTIFACT,
21414
21499
  `[renderChunk] planDir is missing required artifact: ${required}`
@@ -21419,7 +21504,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21419
21504
  const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
21420
21505
  const videosJsonPath = join47(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
21421
21506
  let planVideos = null;
21422
- if (existsSync30(videosJsonPath)) {
21507
+ if (existsSync29(videosJsonPath)) {
21423
21508
  try {
21424
21509
  planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync14(videosJsonPath, "utf-8")));
21425
21510
  } catch (err) {
@@ -21450,7 +21535,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21450
21535
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
21451
21536
  const framesInChunk = range.endFrame - range.startFrame;
21452
21537
  const compiledDir = join47(planDir, "compiled");
21453
- if (!existsSync30(compiledDir)) {
21538
+ if (!existsSync29(compiledDir)) {
21454
21539
  throw new RenderChunkValidationError(
21455
21540
  MISSING_PLAN_ARTIFACT,
21456
21541
  `[renderChunk] planDir missing compiled/ directory: ${compiledDir}`
@@ -21702,10 +21787,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21702
21787
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
21703
21788
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
21704
21789
  if (isPngSequence) {
21705
- if (!existsSync30(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
21790
+ if (!existsSync29(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
21706
21791
  } else {
21707
21792
  const outDir = join47(outputChunkPath, "..");
21708
- if (!existsSync30(outDir)) mkdirSync19(outDir, { recursive: true });
21793
+ if (!existsSync29(outDir)) mkdirSync19(outDir, { recursive: true });
21709
21794
  }
21710
21795
  const encodeInput = {
21711
21796
  job,
@@ -21918,7 +22003,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21918
22003
  producerVersion: plan2.producerVersion,
21919
22004
  ffmpegVersion
21920
22005
  };
21921
- writeFileSync13(perfPath, `${JSON.stringify(perfPayload, null, 2)}
22006
+ writeFileSync12(perfPath, `${JSON.stringify(perfPayload, null, 2)}
21922
22007
  `, "utf-8");
21923
22008
  try {
21924
22009
  rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
@@ -22669,11 +22754,11 @@ import {
22669
22754
 
22670
22755
  // src/server.ts
22671
22756
  import {
22672
- existsSync as existsSync33,
22757
+ existsSync as existsSync32,
22673
22758
  mkdirSync as mkdirSync21,
22674
22759
  statSync as statSync14,
22675
22760
  mkdtempSync as mkdtempSync2,
22676
- writeFileSync as writeFileSync14,
22761
+ writeFileSync as writeFileSync13,
22677
22762
  rmSync as rmSync19,
22678
22763
  createReadStream as createReadStream6
22679
22764
  } from "node:fs";
@@ -22690,17 +22775,17 @@ import {
22690
22775
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD5,
22691
22776
  referenceBackgroundResult as referenceBackgroundResult7
22692
22777
  } from "@hyperframes/engine";
22693
- import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
22778
+ import { isSafePath as isSafePath4 } from "@hyperframes/core/safe-path";
22694
22779
 
22695
22780
  // src/services/hyperframeLint.ts
22696
22781
  import {
22697
- existsSync as existsSync31,
22782
+ existsSync as existsSync30,
22698
22783
  readFileSync as readFileSync16,
22699
22784
  statSync as statSync13,
22700
- openSync as openSync7,
22701
- fstatSync as fstatSync3,
22702
- closeSync as closeSync7,
22703
- constants as constants3
22785
+ openSync as openSync8,
22786
+ fstatSync as fstatSync4,
22787
+ closeSync as closeSync8,
22788
+ constants as constants4
22704
22789
  } from "node:fs";
22705
22790
  import { resolve as resolve12, join as join49, relative as relative9, isAbsolute as isAbsolute6, sep as sep7, dirname as dirname19 } from "node:path";
22706
22791
  import { fileURLToPath as fileURLToPath6 } from "node:url";
@@ -22733,7 +22818,7 @@ function pickEntryFile(files, preferredEntryFile) {
22733
22818
  function readEntryHtml(filePath) {
22734
22819
  let fd;
22735
22820
  try {
22736
- fd = openSync7(filePath, constants3.O_RDONLY | constants3.O_NONBLOCK);
22821
+ fd = openSync8(filePath, constants4.O_RDONLY | constants4.O_NONBLOCK);
22737
22822
  } catch (error) {
22738
22823
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
22739
22824
  return null;
@@ -22741,10 +22826,10 @@ function readEntryHtml(filePath) {
22741
22826
  throw error;
22742
22827
  }
22743
22828
  try {
22744
- if (!fstatSync3(fd).isFile()) return null;
22829
+ if (!fstatSync4(fd).isFile()) return null;
22745
22830
  return readFileSync16(fd, "utf-8");
22746
22831
  } finally {
22747
- closeSync7(fd);
22832
+ closeSync8(fd);
22748
22833
  }
22749
22834
  }
22750
22835
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
@@ -22753,7 +22838,7 @@ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
22753
22838
  }
22754
22839
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
22755
22840
  const absProjectDir = resolve12(projectDir);
22756
- if (!existsSync31(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
22841
+ if (!existsSync30(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
22757
22842
  return { error: `Project directory not found: ${absProjectDir}` };
22758
22843
  }
22759
22844
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -22844,7 +22929,7 @@ function resolveLintWorkerEntry() {
22844
22929
  const here = dirname19(fileURLToPath6(import.meta.url));
22845
22930
  for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
22846
22931
  const candidate = join49(here, name);
22847
- if (existsSync31(candidate)) return candidate;
22932
+ if (existsSync30(candidate)) return candidate;
22848
22933
  }
22849
22934
  return void 0;
22850
22935
  }
@@ -22915,7 +23000,7 @@ async function runHyperframeLint(prepared, options = {}) {
22915
23000
  import { Worker as Worker3 } from "node:worker_threads";
22916
23001
  import { fileURLToPath as fileURLToPath7 } from "node:url";
22917
23002
  import { dirname as dirname20, join as join50 } from "node:path";
22918
- import { existsSync as existsSync32 } from "node:fs";
23003
+ import { existsSync as existsSync31 } from "node:fs";
22919
23004
  var DEFAULT_HEALTH_PORT = 9848;
22920
23005
  async function startHealthWorker(options = {}) {
22921
23006
  const log = options.logger ?? defaultLogger2();
@@ -22992,7 +23077,7 @@ function resolveWorkerEntry2() {
22992
23077
  const here = dirname20(fileURLToPath7(import.meta.url));
22993
23078
  const candidates = [join50(here, "healthWorkerThread.js"), join50(here, "healthWorkerThread.ts")];
22994
23079
  for (const candidate of candidates) {
22995
- if (existsSync32(candidate)) return candidate;
23080
+ if (existsSync31(candidate)) return candidate;
22996
23081
  }
22997
23082
  return void 0;
22998
23083
  }
@@ -23157,12 +23242,12 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
23157
23242
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
23158
23243
  if (confineOutput) {
23159
23244
  mkdirSync21(rendersDir, { recursive: true });
23160
- if (!isSafePath3(rendersDir, absoluteOutputPath)) {
23245
+ if (!isSafePath4(rendersDir, absoluteOutputPath)) {
23161
23246
  throw new Error("outputPath must be inside the renders directory");
23162
23247
  }
23163
23248
  }
23164
23249
  const outputDir = dirname21(absoluteOutputPath);
23165
- if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
23250
+ if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
23166
23251
  return { input, cleanupProjectDir, absoluteOutputPath };
23167
23252
  }
23168
23253
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
@@ -23230,22 +23315,22 @@ function resolveRenderRequestPolicy(options) {
23230
23315
  };
23231
23316
  }
23232
23317
  function isAllowedProjectPath(projectsDir, path) {
23233
- return isSafePath3(projectsDir, path) && !isSafePath3(resolveRenderDebugDir(), path);
23318
+ return isSafePath4(projectsDir, path) && !isSafePath4(resolveRenderDebugDir(), path);
23234
23319
  }
23235
23320
  function isAllowedEntryPath(policy, projectDir, path) {
23236
- return isSafePath3(projectDir, path) && isAllowedProjectPath(policy.projectsDir, path);
23321
+ return isSafePath4(projectDir, path) && isAllowedProjectPath(policy.projectsDir, path);
23237
23322
  }
23238
23323
  function prepareProjectDirectory(projectDir, options, policy) {
23239
23324
  const candidate = nonEmptyString(projectDir);
23240
23325
  if (!candidate) return null;
23241
23326
  const absProjectDir = policy ? resolve13(policy.projectsDir, candidate) : resolve13(candidate);
23242
23327
  const shown = policy ? candidate : absProjectDir;
23243
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync33(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
23328
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
23244
23329
  return { error: `Project directory not found: ${shown}` };
23245
23330
  }
23246
23331
  const entry = options.entryFile || "index.html";
23247
23332
  const entryPath = resolve13(absProjectDir, entry);
23248
- if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync33(entryPath)) {
23333
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync32(entryPath)) {
23249
23334
  return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
23250
23335
  }
23251
23336
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -23267,7 +23352,7 @@ async function resolveInlineRenderHtml(body) {
23267
23352
  function materializeInlineProject(html, options) {
23268
23353
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir6();
23269
23354
  const tempProjectDir = mkdtempSync2(join51(tempRoot, "producer-project-"));
23270
- writeFileSync14(join51(tempProjectDir, "index.html"), html, "utf-8");
23355
+ writeFileSync13(join51(tempProjectDir, "index.html"), html, "utf-8");
23271
23356
  return {
23272
23357
  prepared: {
23273
23358
  input: { projectDir: tempProjectDir, ...options },
@@ -23343,7 +23428,7 @@ function publicPerfSummary(job) {
23343
23428
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
23344
23429
  }
23345
23430
  function outputFileSize(path) {
23346
- return existsSync33(path) ? statSync14(path).size : 0;
23431
+ return existsSync32(path) ? statSync14(path).size : 0;
23347
23432
  }
23348
23433
  function createBlockingProgressReporter(log, requestId) {
23349
23434
  let lastLoggedPct = -10;
@@ -23670,7 +23755,7 @@ function createRenderHandlers(options = {}) {
23670
23755
  if (!artifact) {
23671
23756
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
23672
23757
  }
23673
- if (!existsSync33(artifact.path)) {
23758
+ if (!existsSync32(artifact.path)) {
23674
23759
  store.delete(token);
23675
23760
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
23676
23761
  }
@@ -23870,17 +23955,18 @@ import {
23870
23955
  } from "@hyperframes/engine";
23871
23956
  import {
23872
23957
  cpSync as cpSync3,
23873
- existsSync as existsSync34,
23958
+ existsSync as existsSync33,
23874
23959
  mkdirSync as mkdirSync22,
23875
23960
  readFileSync as readFileSync17,
23876
23961
  readdirSync as readdirSync12,
23877
23962
  rmSync as rmSync20,
23878
- statSync as statSync15,
23879
- writeFileSync as writeFileSync15
23963
+ statSync as statSync15
23880
23964
  } from "node:fs";
23965
+ import { localContainerInputArgs as localContainerInputArgs2 } from "@hyperframes/parsers/ff-binaries";
23881
23966
  import { basename as basename9, dirname as dirname22, join as join52 } from "node:path";
23882
23967
  import {
23883
23968
  appendRateCapArgs as appendRateCapArgs2,
23969
+ writeVideoConcatList,
23884
23970
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
23885
23971
  concatListInputArgs,
23886
23972
  describeFfmpegFailure as describeFfmpegFailure5,
@@ -23890,7 +23976,7 @@ import {
23890
23976
  resolveConfig as resolveConfig7,
23891
23977
  runFfmpeg as runFfmpeg8,
23892
23978
  appendSoftwareEncoderThreadsArg,
23893
- renameWithRetry as renameWithRetry11
23979
+ renameWithRetry as renameWithRetry10
23894
23980
  } from "@hyperframes/engine";
23895
23981
  import { fpsToFfmpegArg as fpsToFfmpegArg3 } from "@hyperframes/core";
23896
23982
  import { createStagingDir as createStagingDir7 } from "@hyperframes/core/atomic-file";
@@ -23926,7 +24012,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23926
24012
  }
23927
24013
  const format = plan2.dimensions.format;
23928
24014
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
23929
- if (!existsSync34(dirname22(outputPath))) {
24015
+ if (!existsSync33(dirname22(outputPath))) {
23930
24016
  mkdirSync22(dirname22(outputPath), { recursive: true });
23931
24017
  }
23932
24018
  const workDir = createStagingDir7(dirname22(outputPath), `${basename9(outputPath)}.assemble-work-`);
@@ -23950,9 +24036,9 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23950
24036
  try {
23951
24037
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
23952
24038
  const finalPath = join52(workDir, `output.${format}`);
23953
- const audio = audioPath !== null && existsSync34(audioPath) ? audioPath : null;
24039
+ const audio = audioPath !== null && existsSync33(audioPath) ? audioPath : null;
23954
24040
  await writeJoined(ctx, videoSources, audio, finalPath);
23955
- renameWithRetry11(finalPath, outputPath);
24041
+ renameWithRetry10(finalPath, outputPath);
23956
24042
  log.info("[assemble] stage timings", {
23957
24043
  ...stageMs,
23958
24044
  chunks: chunkPaths.length,
@@ -23968,7 +24054,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23968
24054
  });
23969
24055
  }
23970
24056
  }
23971
- const fileSize = existsSync34(outputPath) ? statSync15(outputPath).size : 0;
24057
+ const fileSize = existsSync33(outputPath) ? statSync15(outputPath).size : 0;
23972
24058
  return {
23973
24059
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
23974
24060
  outputPath,
@@ -23980,13 +24066,13 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23980
24066
  function readAssemblePlan(planDir, chunkPaths) {
23981
24067
  const planJsonPath = join52(planDir, "plan.json");
23982
24068
  const chunksJsonPath = join52(planDir, "meta", "chunks.json");
23983
- if (!existsSync34(planJsonPath)) {
24069
+ if (!existsSync33(planJsonPath)) {
23984
24070
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
23985
24071
  }
23986
24072
  const plan2 = JSON.parse(readFileSync17(planJsonPath, "utf-8"));
23987
24073
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
23988
24074
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
23989
- if (!existsSync34(chunksJsonPath)) {
24075
+ if (!existsSync33(chunksJsonPath)) {
23990
24076
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
23991
24077
  }
23992
24078
  const chunks = JSON.parse(readFileSync17(chunksJsonPath, "utf-8"));
@@ -24001,14 +24087,18 @@ function readAssemblePlan(planDir, chunkPaths) {
24001
24087
  }
24002
24088
  }
24003
24089
  for (const path of chunkPaths.flat()) {
24004
- if (!existsSync34(path)) {
24090
+ if (!existsSync33(path)) {
24005
24091
  throw new Error(`[assemble] chunk path does not exist: ${path}`);
24006
24092
  }
24007
24093
  }
24008
24094
  return plan2;
24009
24095
  }
24010
24096
  function videoInputArgs(ctx, videoSources) {
24011
- return videoSources.length === 1 ? ["-i", videoSources[0]] : concatDemuxerInput(videoSources, ctx.workDir, ctx.fpsArg);
24097
+ return videoSources.length === 1 ? [
24098
+ ...localContainerInputArgs2(ctx.format === "webm" ? "matroska" : "mov"),
24099
+ "-i",
24100
+ videoSources[0]
24101
+ ] : ["-r", ctx.fpsArg, ...concatListInputArgs(writeVideoConcatList(ctx.workDir, videoSources))];
24012
24102
  }
24013
24103
  function cfrEncodeArgs(inputArgs, encoder, fpsArg) {
24014
24104
  const args = [
@@ -24062,8 +24152,9 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
24062
24152
  "audioMs",
24063
24153
  () => padOrTrimAudioToVideoFrameCount({
24064
24154
  videoPath: videoSources[0],
24065
- probeVideoFrameInfo: () => probeJoinedFrameInfo(videoSources, ctx.fps, ctx.signal),
24155
+ probeVideoFrameInfo: () => probeJoinedFrameInfo(videoSources, ctx),
24066
24156
  audioPath,
24157
+ audioContainer: "mov",
24067
24158
  outputPath: paddedAudioPath,
24068
24159
  signal: ctx.signal,
24069
24160
  timeoutMs: ctx.timeout
@@ -24086,6 +24177,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
24086
24177
  ctx.signal,
24087
24178
  {
24088
24179
  audioCodec: "aac",
24180
+ audioContainer: "mov",
24089
24181
  ffmpegProcessTimeout: ctx.timeout,
24090
24182
  videoInputArgs: videoInputArgs(ctx, videoSources)
24091
24183
  },
@@ -24096,21 +24188,16 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
24096
24188
  throw encoderFailureError("[assemble] audio mux failed", muxResult);
24097
24189
  }
24098
24190
  }
24099
- function concatDemuxerInput(chunkPaths, workDir, fpsArg) {
24100
- const listPath = join52(workDir, "concat-list.txt");
24101
- const body = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
24102
- writeFileSync15(listPath, `${body}
24103
- `, "utf-8");
24104
- return ["-r", fpsArg, ...concatListInputArgs(listPath)];
24105
- }
24106
- async function probeJoinedFrameInfo(videoPaths, fps, signal) {
24191
+ async function probeJoinedFrameInfo(videoPaths, ctx) {
24107
24192
  const infos = await Promise.all(
24108
- videoPaths.map((path) => defaultProbeVideoFrameInfo(path, signal))
24193
+ videoPaths.map(
24194
+ (path) => defaultProbeVideoFrameInfo(path, ctx.signal, ctx.format === "webm" ? "matroska" : "mov")
24195
+ )
24109
24196
  );
24110
24197
  return {
24111
24198
  frameCount: infos.reduce((sum2, info) => sum2 + info.frameCount, 0),
24112
- fpsNum: fps.num,
24113
- fpsDen: fps.den
24199
+ fpsNum: ctx.fps.num,
24200
+ fpsDen: ctx.fps.den
24114
24201
  };
24115
24202
  }
24116
24203
  async function runAssembleFfmpeg(args, step, signal, timeout) {
@@ -24140,7 +24227,7 @@ function planFormat(planDir) {
24140
24227
  }
24141
24228
  function lockedAudio(planDir) {
24142
24229
  const encoderJsonPath = join52(planDir, "meta", "encoder.json");
24143
- if (!existsSync34(encoderJsonPath)) return {};
24230
+ if (!existsSync33(encoderJsonPath)) return {};
24144
24231
  return JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
24145
24232
  }
24146
24233
  function readCfrEncoder(planDir, format) {
@@ -24150,7 +24237,7 @@ function readCfrEncoder(planDir, format) {
24150
24237
  );
24151
24238
  }
24152
24239
  const encoderJsonPath = join52(planDir, "meta", "encoder.json");
24153
- if (!existsSync34(encoderJsonPath)) {
24240
+ if (!existsSync33(encoderJsonPath)) {
24154
24241
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
24155
24242
  }
24156
24243
  const encoderJson = JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
@@ -24162,7 +24249,7 @@ function readCfrEncoder(planDir, format) {
24162
24249
  return encoderJson;
24163
24250
  }
24164
24251
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
24165
- if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
24252
+ if (existsSync33(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
24166
24253
  mkdirSync22(outputPath, { recursive: true });
24167
24254
  let globalIdx = 0;
24168
24255
  for (const chunkDir of chunkPaths) {
@@ -24186,7 +24273,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
24186
24273
  `[assemble] png-sequence frame count mismatch: merged ${globalIdx} frames vs plan.totalFrames=${totalFrames}. Using on-disk count.`
24187
24274
  );
24188
24275
  }
24189
- if (audioPath !== null && existsSync34(audioPath)) {
24276
+ if (audioPath !== null && existsSync33(audioPath)) {
24190
24277
  const sidecar = join52(outputPath, MIXED_AUDIO_FILENAME4);
24191
24278
  cpSync3(audioPath, sidecar);
24192
24279
  }