@hyperframes/producer 0.9.88 → 0.9.89

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
@@ -12,7 +12,7 @@ import {
12
12
  existsSync as existsSync22,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
- rmSync as rmSync12,
15
+ rmSync as rmSync13,
16
16
  statSync as statSync10,
17
17
  writeFileSync as writeFileSync6,
18
18
  copyFileSync as copyFileSync5,
@@ -362,7 +362,7 @@ import {
362
362
  } from "@hyperframes/engine";
363
363
  import { join as join35, dirname as dirname15, resolve as resolve9 } from "path";
364
364
  import { totalmem as totalmem2 } from "node:os";
365
- import { randomUUID } from "crypto";
365
+ import { randomUUID as randomUUID3 } from "crypto";
366
366
  import { fileURLToPath as fileURLToPath5 } from "url";
367
367
 
368
368
  // src/services/fileServer.ts
@@ -546,11 +546,11 @@ var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (
546
546
  nodeResolve(fileURLToPath2(import.meta.url), "../../..", "renders");
547
547
  var LEADING_PARENT_SEGMENT_RE = /^\.\.(?:[\\/]|$)/;
548
548
  function isPathInside(childPath, parentPath, options = {}) {
549
- const resolvePath = options.pathModule?.resolve ?? nodeResolve;
549
+ const resolvePath2 = options.pathModule?.resolve ?? nodeResolve;
550
550
  const relativePath = options.pathModule?.relative ?? nodeRelative;
551
551
  const isPathAbsolute = options.pathModule?.isAbsolute ?? nodeIsAbsolute;
552
- const absChild = resolvePath(childPath);
553
- const absParent = resolvePath(parentPath);
552
+ const absChild = resolvePath2(childPath);
553
+ const absParent = resolvePath2(parentPath);
554
554
  if (absChild === absParent) return true;
555
555
  const rel = relativePath(absParent, absChild);
556
556
  return rel !== "" && !LEADING_PARENT_SEGMENT_RE.test(rel) && !isPathAbsolute(rel);
@@ -7134,7 +7134,7 @@ function requireOutputDimensions(expected, width, height) {
7134
7134
 
7135
7135
  // src/services/render/stages/compileStage.ts
7136
7136
  import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7137
- import { join as join23, relative as relative4 } from "node:path";
7137
+ import { join as join23, relative as relative5 } from "node:path";
7138
7138
  import { privateCacheRoot } from "@hyperframes/engine";
7139
7139
  import { suggestMatchingPreset } from "@hyperframes/core";
7140
7140
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -7142,8 +7142,8 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
7142
7142
  import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7143
7143
 
7144
7144
  // src/services/compileInWorker.ts
7145
- import { existsSync as existsSync12 } from "node:fs";
7146
- import { dirname as dirname10, join as join22 } from "node:path";
7145
+ import { existsSync as existsSync12, rmSync as rmSync11 } from "node:fs";
7146
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7147
7147
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7148
7148
  import { Worker } from "node:worker_threads";
7149
7149
 
@@ -7449,7 +7449,7 @@ import {
7449
7449
  } from "@hyperframes/core/fonts/embed";
7450
7450
 
7451
7451
  // src/services/animatedGifPrep.ts
7452
- import { createHash as createHash4 } from "node:crypto";
7452
+ import { createHash as createHash4, randomUUID } from "node:crypto";
7453
7453
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7454
7454
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7455
7455
  import { parseHTML as parseHTML3 } from "linkedom";
@@ -7524,6 +7524,8 @@ function resolveLoop(metadata, override) {
7524
7524
  }
7525
7525
  var MAX_LOOP_ITERATIONS = 1e3;
7526
7526
  var MAX_PAD_SECONDS = 3600;
7527
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
7528
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
7527
7529
  function resolveCompositionDurationSeconds(document2) {
7528
7530
  let max = null;
7529
7531
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -7566,7 +7568,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
7566
7568
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
7567
7569
  }
7568
7570
  function buildAnimatedGifTranscodeArgs(input) {
7569
- const args = ["-hide_banner", "-loglevel", "error"];
7571
+ const args = [
7572
+ "-hide_banner",
7573
+ "-loglevel",
7574
+ "error",
7575
+ "-timelimit",
7576
+ String(FFMPEG_SELF_CPU_SECONDS_CAP)
7577
+ ];
7570
7578
  if (input.loopIterations > 1) {
7571
7579
  args.push("-stream_loop", String(input.loopIterations - 1));
7572
7580
  }
@@ -7594,6 +7602,8 @@ function buildAnimatedGifTranscodeArgs(input) {
7594
7602
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
7595
7603
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
7596
7604
  // extension ffmpeg cannot infer the container from.
7605
+ "-fs",
7606
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
7597
7607
  "-f",
7598
7608
  "webm",
7599
7609
  "-y",
@@ -7601,10 +7611,16 @@ function buildAnimatedGifTranscodeArgs(input) {
7601
7611
  );
7602
7612
  return args;
7603
7613
  }
7614
+ function abortError() {
7615
+ const error = new Error("Aborted");
7616
+ error.name = "AbortError";
7617
+ return error;
7618
+ }
7604
7619
  async function runAnimatedGifTranscode(request) {
7605
7620
  const timeout = request.timeoutMs ?? 3e5;
7606
- const result = await runFfmpeg2(request.args, { timeout });
7621
+ const result = await runFfmpeg2(request.args, { timeout, signal: request.signal });
7607
7622
  if (result.success) return;
7623
+ if (request.signal?.aborted) throw abortError();
7608
7624
  if (result.failureReason === "external_interruption") {
7609
7625
  throw encoderFailureError("Animated GIF transcode failed", {
7610
7626
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -7624,7 +7640,7 @@ async function ensurePreparedWebm(input) {
7624
7640
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7625
7641
  }
7626
7642
  if (!isUsableFile(input.cachePath)) {
7627
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
7643
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
7628
7644
  const args = buildAnimatedGifTranscodeArgs({
7629
7645
  inputPath: input.sourcePath,
7630
7646
  outputPath: tmpPath,
@@ -7637,11 +7653,15 @@ async function ensurePreparedWebm(input) {
7637
7653
  inputPath: input.sourcePath,
7638
7654
  outputPath: tmpPath,
7639
7655
  args,
7640
- timeoutMs: input.timeoutMs
7656
+ timeoutMs: input.timeoutMs,
7657
+ signal: input.signal
7641
7658
  });
7642
7659
  if (!isUsableFile(tmpPath)) {
7643
7660
  throw new Error("Animated GIF transcode produced an empty output");
7644
7661
  }
7662
+ if (statSync6(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
7663
+ throw new Error("Animated GIF transcode reached its output size limit");
7664
+ }
7645
7665
  if (!isUsableFile(input.cachePath)) {
7646
7666
  renameWithRetry2(tmpPath, input.cachePath);
7647
7667
  } else {
@@ -7741,6 +7761,7 @@ async function prepareAnimatedGifInputs(html, options) {
7741
7761
  loopIterations,
7742
7762
  padSeconds,
7743
7763
  timeoutMs: options.timeoutMs,
7764
+ signal: options.signal,
7744
7765
  transcode: options.transcode
7745
7766
  });
7746
7767
  const id = ensureElementId(img, document2, i);
@@ -7765,7 +7786,7 @@ async function prepareAnimatedGifInputs(html, options) {
7765
7786
  }
7766
7787
 
7767
7788
  // src/services/heifImagePrep.ts
7768
- import { createHash as createHash5 } from "node:crypto";
7789
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7769
7790
  import {
7770
7791
  closeSync as closeSync5,
7771
7792
  copyFileSync as copyFileSync3,
@@ -7911,6 +7932,13 @@ var HeifToolUnavailableError = class extends Error {
7911
7932
  this.name = "HeifToolUnavailableError";
7912
7933
  }
7913
7934
  };
7935
+ function abortError2() {
7936
+ const error = new Error("Aborted");
7937
+ error.name = "AbortError";
7938
+ return error;
7939
+ }
7940
+ var FFMPEG_SELF_CPU_SECONDS_CAP2 = 300;
7941
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP2 = 256 * 1024 * 1024;
7914
7942
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
7915
7943
  function isHeifBytes(head) {
7916
7944
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -7978,6 +8006,8 @@ async function convertHeifToJpeg(request) {
7978
8006
  "-hide_banner",
7979
8007
  "-loglevel",
7980
8008
  "error",
8009
+ "-timelimit",
8010
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
7981
8011
  ...urlInputArgs3(request.inputPath),
7982
8012
  "-i",
7983
8013
  request.inputPath,
@@ -7986,14 +8016,17 @@ async function convertHeifToJpeg(request) {
7986
8016
  "1",
7987
8017
  "-q:v",
7988
8018
  "2",
8019
+ "-fs",
8020
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
7989
8021
  "-f",
7990
8022
  "mjpeg",
7991
8023
  "-y",
7992
8024
  request.outputPath
7993
8025
  ],
7994
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
8026
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
7995
8027
  );
7996
8028
  if (!result.success) {
8029
+ if (request.signal?.aborted) throw abortError2();
7997
8030
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
7998
8031
  }
7999
8032
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -8027,7 +8060,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8027
8060
  mkdirSync8(dirname7(cachePath), { recursive: true });
8028
8061
  mkdirSync8(dirname7(outputPath), { recursive: true });
8029
8062
  if (!isUsableFile2(cachePath)) {
8030
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
8063
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8031
8064
  const inlinePath = `${tmpPath}.heic`;
8032
8065
  const inputPath = source.path ?? inlinePath;
8033
8066
  try {
@@ -8035,9 +8068,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8035
8068
  await (options.transcode ?? convertHeifToJpeg)({
8036
8069
  inputPath,
8037
8070
  outputPath: tmpPath,
8038
- timeoutMs: options.timeoutMs
8071
+ timeoutMs: options.timeoutMs,
8072
+ signal: options.signal
8039
8073
  });
8040
8074
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
8075
+ if (statSync7(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP2) {
8076
+ throw new Error("conversion reached its output size limit");
8077
+ }
8041
8078
  renameWithRetry3(tmpPath, cachePath);
8042
8079
  } catch (error) {
8043
8080
  const reason = error instanceof Error ? error.message : String(error);
@@ -8108,6 +8145,7 @@ import {
8108
8145
  isNotImagePayload,
8109
8146
  isNotMediaPayload,
8110
8147
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
8148
+ isStructurallyIncompletePngError,
8111
8149
  playlistLeavesItsFolder,
8112
8150
  NotMediaPayloadError,
8113
8151
  probeMediaProfile,
@@ -8186,6 +8224,13 @@ async function notMediaReferences(path, references) {
8186
8224
  if (images.length > 0 && await isNotImagePayload(path)) return images;
8187
8225
  return await playlistLeavesItsFolder(path) ? references : [];
8188
8226
  }
8227
+ function pngCutShort(references) {
8228
+ return references.filter((reference) => reference.expected === "video").map((reference) => ({
8229
+ expected: "video",
8230
+ detected: "image",
8231
+ elementFingerprint: fingerprintElementId(reference.id)
8232
+ }));
8233
+ }
8189
8234
  async function preflightCompositionAssetMediaTypes(input) {
8190
8235
  const references = [
8191
8236
  ...input.composition.videos.map((asset) => ({
@@ -8231,6 +8276,8 @@ async function preflightCompositionAssetMediaTypes(input) {
8231
8276
  profile = await probeMediaProfile(resolvedPath, { signal: input.signal });
8232
8277
  } catch (error) {
8233
8278
  if (input.signal?.aborted) throw input.signal.reason ?? error;
8279
+ if (isStructurallyIncompletePngError(error))
8280
+ mismatches.push(...pngCutShort(pathReferences));
8234
8281
  return;
8235
8282
  }
8236
8283
  for (const reference of pathReferences) {
@@ -9574,8 +9621,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9574
9621
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
9575
9622
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9576
9623
  if (fontFaceBlocks.length === 0) return;
9624
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9577
9625
  const inlineStyle = `<style>/* Inlined external font stylesheet */
9578
- ${fontFaceBlocks.join("\n")}
9626
+ ${fontCssWithLtAsCssEscape}
9579
9627
  </style>`;
9580
9628
  try {
9581
9629
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -9991,6 +10039,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
9991
10039
  cacheDir: options.animatedGifCacheDir,
9992
10040
  sourceAssets: remoteImageAssets,
9993
10041
  timeoutMs: options.ffmpegProcessTimeout,
10042
+ signal: options.abortSignal,
9994
10043
  allowOutsideFiles: assetRoot === void 0
9995
10044
  });
9996
10045
  if (preparedHeifImages.length > 0) {
@@ -10007,6 +10056,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10007
10056
  cacheDir: options.animatedGifCacheDir,
10008
10057
  sourceAssets: gifSourceAssets,
10009
10058
  timeoutMs: options.ffmpegProcessTimeout,
10059
+ signal: options.abortSignal,
10010
10060
  allowOutsideFiles: assetRoot === void 0
10011
10061
  });
10012
10062
  if (preparedGifs.length > 0) {
@@ -10485,6 +10535,24 @@ function compileTimeoutMs() {
10485
10535
  return Number.isInteger(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_COMPILE_TIMEOUT_MS;
10486
10536
  }
10487
10537
  var warnedMissingEntry = false;
10538
+ var endOnProcessExit = /* @__PURE__ */ new Set();
10539
+ var processExitHooked = false;
10540
+ function onProcessExit(end) {
10541
+ if (!processExitHooked) {
10542
+ processExitHooked = true;
10543
+ process.on("exit", () => {
10544
+ for (const each of endOnProcessExit) each();
10545
+ });
10546
+ }
10547
+ endOnProcessExit.add(end);
10548
+ return () => endOnProcessExit.delete(end);
10549
+ }
10550
+ function tryQuietly(action) {
10551
+ try {
10552
+ action();
10553
+ } catch {
10554
+ }
10555
+ }
10488
10556
  function resolveCompileWorkerEntry(explicit, log) {
10489
10557
  if (explicit) return explicit;
10490
10558
  const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
@@ -10518,6 +10586,26 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10518
10586
  const thread = new Worker(entry, {
10519
10587
  workerData: { projectDir, htmlPath, downloadDir, options: cloneable }
10520
10588
  });
10589
+ const children = /* @__PURE__ */ new Map();
10590
+ const scratchRoots = [downloadDir, options.animatedGifCacheDir].flatMap(
10591
+ (dir) => dir ? [resolvePath(dir)] : []
10592
+ );
10593
+ const isScratch = (path) => scratchRoots.some((root) => {
10594
+ const rel = relative4(root, resolvePath(path));
10595
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute4(rel);
10596
+ });
10597
+ const endChildren = (signal) => {
10598
+ for (const [pid, output] of children) {
10599
+ if (signal) tryQuietly(() => process.kill(pid, "SIGKILL"));
10600
+ if (output) tryQuietly(() => rmSync11(output, { force: true }));
10601
+ }
10602
+ children.clear();
10603
+ };
10604
+ const offProcessExit = onProcessExit(() => endChildren(true));
10605
+ const endThread = () => {
10606
+ endChildren(true);
10607
+ void thread.terminate();
10608
+ };
10521
10609
  let settled = false;
10522
10610
  const settle = (finish) => {
10523
10611
  if (settled) return;
@@ -10528,7 +10616,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10528
10616
  };
10529
10617
  const stop = () => {
10530
10618
  thread.postMessage({ type: "abort" });
10531
- setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
10619
+ setTimeout(endThread, TERMINATE_GRACE_MS).unref();
10532
10620
  };
10533
10621
  const timer = setTimeout(() => {
10534
10622
  stop();
@@ -10541,7 +10629,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10541
10629
  abortSignal?.addEventListener("abort", onAbort, { once: true });
10542
10630
  const retire = (graceMs) => {
10543
10631
  thread.unref();
10544
- setTimeout(() => void thread.terminate(), graceMs).unref();
10632
+ setTimeout(endThread, graceMs).unref();
10545
10633
  };
10546
10634
  thread.on(
10547
10635
  "message",
@@ -10560,13 +10648,22 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10560
10648
  }
10561
10649
  }
10562
10650
  );
10563
- thread.on("error", (error) => settle(() => reject(error)));
10564
10651
  thread.on(
10565
- "exit",
10566
- (code) => settle(
10567
- () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10568
- )
10652
+ "message",
10653
+ ({ type, pid, output }) => {
10654
+ if (pid === void 0) return;
10655
+ if (type === "child") children.set(pid, output && isScratch(output) ? output : void 0);
10656
+ else if (type === "childExit") children.delete(pid);
10657
+ }
10569
10658
  );
10659
+ thread.on("error", (error) => settle(() => reject(error)));
10660
+ thread.on("exit", (code) => {
10661
+ offProcessExit();
10662
+ endChildren(false);
10663
+ settle(
10664
+ () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10665
+ );
10666
+ });
10570
10667
  });
10571
10668
  }
10572
10669
 
@@ -10596,10 +10693,10 @@ function resolveEntryHtmlPath(input) {
10596
10693
  const readEntry = (path) => {
10597
10694
  if (escapesAssetRoot(path, input.assetRoot)) {
10598
10695
  throw new Error(
10599
- `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10696
+ `Entry file "${relative5(projectDir, path)}" leads outside the project folder`
10600
10697
  );
10601
10698
  }
10602
- assertCompositionFileSize2(path, relative4(projectDir, path));
10699
+ assertCompositionFileSize2(path, relative5(projectDir, path));
10603
10700
  return readTextFile2(path);
10604
10701
  };
10605
10702
  const htmlPath = join23(projectDir, entryFile);
@@ -14401,7 +14498,7 @@ import {
14401
14498
  mkdirSync as mkdirSync11,
14402
14499
  readdirSync as readdirSync5,
14403
14500
  readFileSync as readFileSync9,
14404
- rmSync as rmSync11,
14501
+ rmSync as rmSync12,
14405
14502
  statSync as statSync9,
14406
14503
  writeFileSync as writeFileSync5
14407
14504
  } from "node:fs";
@@ -14540,7 +14637,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14540
14637
  fileSize
14541
14638
  };
14542
14639
  } finally {
14543
- rmSync11(input.palettePath, { force: true });
14640
+ rmSync12(input.palettePath, { force: true });
14544
14641
  }
14545
14642
  }
14546
14643
  function startEncodeProgress(job, stage, onProgress) {
@@ -15419,7 +15516,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15419
15516
  function createRenderJob(config) {
15420
15517
  return {
15421
15518
  ...referenceBackgroundResult(void 0),
15422
- id: randomUUID(),
15519
+ id: randomUUID3(),
15423
15520
  config: {
15424
15521
  ...config,
15425
15522
  fps: toFps2(config.fps),
@@ -15934,7 +16031,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15934
16031
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
15935
16032
  return;
15936
16033
  }
15937
- rmSync12(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
16034
+ rmSync13(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
15938
16035
  });
15939
16036
  try {
15940
16037
  await executeRenderPipeline({
@@ -17402,7 +17499,7 @@ async function executeRenderPipeline(input) {
17402
17499
  segmentDir
17403
17500
  });
17404
17501
  }
17405
- if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
17502
+ if (completedSegments.size === 0) rmSync13(segmentDir, { recursive: true, force: true });
17406
17503
  const invokeSegmented = () => {
17407
17504
  if (capturePlan.kind !== "sdr_segmented") {
17408
17505
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17495,7 +17592,7 @@ async function executeRenderPipeline(input) {
17495
17592
  probeSession = null;
17496
17593
  await closeOrphanedProbeForRetry(orphaned, closeCaptureSession8, log, "segmented");
17497
17594
  }
17498
- rmSync12(segmentDir, { recursive: true, force: true });
17595
+ rmSync13(segmentDir, { recursive: true, force: true });
17499
17596
  completedSegments = /* @__PURE__ */ new Set();
17500
17597
  segmentManifest = emptySegmentManifest();
17501
17598
  dedupPerfs.length = 0;
@@ -17534,7 +17631,7 @@ async function executeRenderPipeline(input) {
17534
17631
  );
17535
17632
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
17536
17633
  if (job.config.keepSegments !== true) {
17537
- rmSync12(segmentDir, { recursive: true, force: true });
17634
+ rmSync13(segmentDir, { recursive: true, force: true });
17538
17635
  }
17539
17636
  } else {
17540
17637
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -17811,7 +17908,7 @@ async function executeRenderPipeline(input) {
17811
17908
  "capture_disk",
17812
17909
  "drawElement capture failed; retrying with a fresh screenshot session"
17813
17910
  );
17814
- rmSync12(framesDir, { recursive: true, force: true });
17911
+ rmSync13(framesDir, { recursive: true, force: true });
17815
17912
  mkdirSync12(framesDir, { recursive: true });
17816
17913
  resetCaptureAttemptProgress(job);
17817
17914
  dedupPerfs.length = 0;
@@ -18119,12 +18216,12 @@ import {
18119
18216
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD4,
18120
18217
  referenceBackgroundResult as referenceBackgroundResult6
18121
18218
  } from "@hyperframes/engine";
18122
- import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync18 } from "node:fs";
18219
+ import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync19 } from "node:fs";
18123
18220
  import { join as join49 } from "node:path";
18124
18221
  import { tmpdir as tmpdir5 } from "node:os";
18125
18222
 
18126
18223
  // src/services/distributed/mp4Stitch.ts
18127
- import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
18224
+ import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync14 } from "node:fs";
18128
18225
  import { open } from "node:fs/promises";
18129
18226
  import { renameWithRetry as renameWithRetry6 } from "@hyperframes/engine";
18130
18227
  import { basename as basename8, dirname as dirname16, join as join36 } from "node:path";
@@ -18503,7 +18600,7 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
18503
18600
  renameWithRetry6(join36(workDir, "out.mp4"), outputPath);
18504
18601
  } finally {
18505
18602
  out.destroy();
18506
- rmSync13(workDir, { recursive: true, force: true });
18603
+ rmSync14(workDir, { recursive: true, force: true });
18507
18604
  }
18508
18605
  }
18509
18606
 
@@ -18520,10 +18617,10 @@ import {
18520
18617
  existsSync as existsSync27,
18521
18618
  linkSync,
18522
18619
  mkdirSync as mkdirSync16,
18523
- rmSync as rmSync14,
18620
+ rmSync as rmSync15,
18524
18621
  writeFileSync as writeFileSync9
18525
18622
  } from "node:fs";
18526
- import { extname as extname6, isAbsolute as isAbsolute4, join as join44, relative as relative7, sep as sep5 } from "node:path";
18623
+ import { extname as extname6, isAbsolute as isAbsolute5, join as join44, relative as relative8, sep as sep5 } from "node:path";
18527
18624
  import {
18528
18625
  fpsToNumber as fpsToNumber9,
18529
18626
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -19197,7 +19294,7 @@ async function readPlanReferenceBackground(input) {
19197
19294
 
19198
19295
  // src/services/render/stages/freezePlan.ts
19199
19296
  import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
19200
- import { join as join41, relative as relative5, resolve as resolve10 } from "node:path";
19297
+ import { join as join41, relative as relative6, resolve as resolve10 } from "node:path";
19201
19298
  import {
19202
19299
  REFERENCE_BACKGROUND_FIELD,
19203
19300
  referenceBackgroundResult as referenceBackgroundResult3
@@ -19420,7 +19517,7 @@ function listPlanFiles(planDir) {
19420
19517
  walk(full);
19421
19518
  } else if (entry.isFile()) {
19422
19519
  results.push({
19423
- planRelativePath: relative5(rootResolved, full).split(/[\\/]+/).join("/"),
19520
+ planRelativePath: relative6(rootResolved, full).split(/[\\/]+/).join("/"),
19424
19521
  absolutePath: full
19425
19522
  });
19426
19523
  }
@@ -19756,7 +19853,7 @@ async function muxChunkWithAudio(input) {
19756
19853
  // src/services/distributed/planSize.ts
19757
19854
  import { createHash as createHash9 } from "node:crypto";
19758
19855
  import { lstatSync as lstatSync4, readdirSync as readdirSync9 } from "node:fs";
19759
- import { extname as extname5, join as join43, relative as relative6 } from "node:path";
19856
+ import { extname as extname5, join as join43, relative as relative7 } from "node:path";
19760
19857
  var MAX_TOP_COMPONENTS = 10;
19761
19858
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
19762
19859
  ".aac",
@@ -19845,7 +19942,7 @@ function recordFile(result, components, rootDir, rootKind, filePath) {
19845
19942
  } catch {
19846
19943
  return;
19847
19944
  }
19848
- const rel = relative6(rootDir, filePath);
19945
+ const rel = relative7(rootDir, filePath);
19849
19946
  const segments = rel.split(/[\\/]+/).filter(Boolean);
19850
19947
  const classified = classifyFile(segments, rootKind);
19851
19948
  result.totalBytes += sizeBytes;
@@ -20090,7 +20187,7 @@ var FREEZE_OWNED_PLAN_FILES = [
20090
20187
  ];
20091
20188
  function removeFreezeOwnedPlanFiles(planDir) {
20092
20189
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
20093
- rmSync14(join44(planDir, relativePath), { force: true });
20190
+ rmSync15(join44(planDir, relativePath), { force: true });
20094
20191
  }
20095
20192
  }
20096
20193
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -20229,10 +20326,10 @@ function resolveDistributedEngineConfig(config) {
20229
20326
  };
20230
20327
  }
20231
20328
  function leavesRoot(rel) {
20232
- return rel === ".." || rel.startsWith(`..${sep5}`) || isAbsolute4(rel);
20329
+ return rel === ".." || rel.startsWith(`..${sep5}`) || isAbsolute5(rel);
20233
20330
  }
20234
20331
  function pathInside(root, path) {
20235
- const rel = relative7(root, path);
20332
+ const rel = relative8(root, path);
20236
20333
  return rel === "" || leavesRoot(rel) ? null : rel;
20237
20334
  }
20238
20335
  function stableSourcePath(roots, srcPath) {
@@ -20319,7 +20416,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20319
20416
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
20320
20417
  }
20321
20418
  const workDir = join44(planDir, ".plan-work");
20322
- rmSync14(workDir, { recursive: true, force: true });
20419
+ rmSync15(workDir, { recursive: true, force: true });
20323
20420
  mkdirSync16(workDir, { recursive: true });
20324
20421
  const compiledDir = join44(workDir, "compiled");
20325
20422
  mkdirSync16(compiledDir, { recursive: true });
@@ -20328,7 +20425,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20328
20425
  recursive: true,
20329
20426
  dereference: true,
20330
20427
  filter: (src) => {
20331
- const rel = relative7(projectDir, src);
20428
+ const rel = relative8(projectDir, src);
20332
20429
  if (rel === "") return true;
20333
20430
  if (leavesRoot(rel)) return false;
20334
20431
  if (job.config.allowOutsideProjectAssets) {
@@ -20551,15 +20648,15 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20551
20648
  logPlanStage(log, "extract", stageStarted);
20552
20649
  const stagedVideoFrames = join44(compiledDir, "__hyperframes_video_frames");
20553
20650
  const videoFramesDst = join44(planDir, "video-frames");
20554
- if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
20651
+ if (existsSync27(videoFramesDst)) rmSync15(videoFramesDst, { recursive: true, force: true });
20555
20652
  const videoSourcesDir = join44(planDir, "video-sources");
20556
- rmSync14(videoSourcesDir, { recursive: true, force: true });
20653
+ rmSync15(videoSourcesDir, { recursive: true, force: true });
20557
20654
  if (existsSync27(stagedVideoFrames)) {
20558
20655
  renameWithRetry7(stagedVideoFrames, videoFramesDst);
20559
20656
  } else {
20560
20657
  mkdirSync16(videoFramesDst, { recursive: true });
20561
20658
  }
20562
- if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
20659
+ if (existsSync27(finalCompiledDir)) rmSync15(finalCompiledDir, { recursive: true, force: true });
20563
20660
  renameWithRetry7(compiledDir, finalCompiledDir);
20564
20661
  const shipVideoSource = createVideoSourceShipper({
20565
20662
  planDir,
@@ -20729,7 +20826,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20729
20826
  format: config.format
20730
20827
  };
20731
20828
  try {
20732
- rmSync14(workDir, { recursive: true, force: true });
20829
+ rmSync15(workDir, { recursive: true, force: true });
20733
20830
  } catch (err) {
20734
20831
  log.warn("[plan] failed to remove temp work dir", {
20735
20832
  workDir,
@@ -20805,7 +20902,7 @@ async function plan(projectDir, config, planDir, options = {}) {
20805
20902
 
20806
20903
  // src/services/distributed/renderChunk.ts
20807
20904
  import { randomBytes } from "node:crypto";
20808
- import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync12 } from "node:fs";
20905
+ import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync18, writeFileSync as writeFileSync12 } from "node:fs";
20809
20906
  import { join as join48 } from "node:path";
20810
20907
  import {
20811
20908
  assertSwiftShader,
@@ -20837,12 +20934,12 @@ import {
20837
20934
  mkdirSync as mkdirSync18,
20838
20935
  readFileSync as readFileSync13,
20839
20936
  readdirSync as readdirSync10,
20840
- rmSync as rmSync16,
20937
+ rmSync as rmSync17,
20841
20938
  statSync as statSync12,
20842
20939
  writeFileSync as writeFileSync11
20843
20940
  } from "node:fs";
20844
20941
  import { tmpdir as tmpdir4 } from "node:os";
20845
- import { dirname as dirname19, isAbsolute as isAbsolute5, join as join47, relative as relative8, resolve as resolve11, sep as sep6 } from "node:path";
20942
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join47, relative as relative9, resolve as resolve11, sep as sep6 } from "node:path";
20846
20943
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
20847
20944
  import {
20848
20945
  createFrameLookupTable as createFrameLookupTable5,
@@ -20856,7 +20953,7 @@ import {
20856
20953
  existsSync as existsSync28,
20857
20954
  linkSync as linkSync2,
20858
20955
  mkdirSync as mkdirSync17,
20859
- rmSync as rmSync15,
20956
+ rmSync as rmSync16,
20860
20957
  statSync as statSync11,
20861
20958
  writeFileSync as writeFileSync10
20862
20959
  } from "node:fs";
@@ -20947,7 +21044,7 @@ var LocalPlanV2ArtifactPublisher = class {
20947
21044
  }
20948
21045
  renameWithRetry8(temporaryPath, destinationPath);
20949
21046
  } finally {
20950
- rmSync15(stagingDir, { recursive: true, force: true });
21047
+ rmSync16(stagingDir, { recursive: true, force: true });
20951
21048
  }
20952
21049
  }
20953
21050
  async commitManifest(manifestBytes) {
@@ -20964,7 +21061,7 @@ var LocalPlanV2ArtifactPublisher = class {
20964
21061
  }
20965
21062
  async abort() {
20966
21063
  if (!this.#committed) {
20967
- rmSync15(this.temporaryDir, { recursive: true, force: true });
21064
+ rmSync16(this.temporaryDir, { recursive: true, force: true });
20968
21065
  }
20969
21066
  }
20970
21067
  };
@@ -20995,7 +21092,7 @@ function readJsonFile(path, label) {
20995
21092
  }
20996
21093
  function assertSafeRelativePath(path) {
20997
21094
  const normalized = path.split(/[\\/]+/);
20998
- if (path.length === 0 || isAbsolute5(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
21095
+ if (path.length === 0 || isAbsolute6(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
20999
21096
  throw new PlanV2IntegrityError(`unsafe artifact path: ${JSON.stringify(path)}`);
21000
21097
  }
21001
21098
  }
@@ -21009,7 +21106,7 @@ function listFiles(root) {
21009
21106
  walk(absolutePath);
21010
21107
  } else if (entry.isFile()) {
21011
21108
  files.push({
21012
- path: relative8(rootResolved, absolutePath).split(sep6).join("/"),
21109
+ path: relative9(rootResolved, absolutePath).split(sep6).join("/"),
21013
21110
  absolutePath
21014
21111
  });
21015
21112
  } else {
@@ -21209,7 +21306,7 @@ function collectChunkVideoDependencies(input) {
21209
21306
  for (let frame = chunk.startFrame; frame < chunk.endFrame; frame++) {
21210
21307
  const globalTime = frame * input.fpsDen / input.fpsNum;
21211
21308
  for (const [videoId, payload] of input.table.getActiveFramePayloads(globalTime)) {
21212
- const path = input.deferredSources.get(videoId) ?? relative8(resolve11(input.executionPlanDir), payload.framePath).split(sep6).join("/");
21309
+ const path = input.deferredSources.get(videoId) ?? relative9(resolve11(input.executionPlanDir), payload.framePath).split(sep6).join("/");
21213
21310
  assertSafeRelativePath(path);
21214
21311
  const indexes = mutable.get(path) ?? /* @__PURE__ */ new Set();
21215
21312
  indexes.add(chunk.index);
@@ -21234,7 +21331,7 @@ function writeBlob(sourcePath, destinationPath) {
21234
21331
  copyFileSync8(sourcePath, temporaryPath);
21235
21332
  renameWithRetry9(temporaryPath, destinationPath);
21236
21333
  } finally {
21237
- rmSync16(temporaryDir, { recursive: true, force: true });
21334
+ rmSync17(temporaryDir, { recursive: true, force: true });
21238
21335
  }
21239
21336
  }
21240
21337
  function publishBlobFor(absolutePath, digests) {
@@ -21367,7 +21464,7 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
21367
21464
  renameWithRetry9(tempDir, planV2Dir);
21368
21465
  return resultFromManifest(planV2Dir, publication.manifest);
21369
21466
  } catch (error) {
21370
- rmSync16(tempDir, { recursive: true, force: true });
21467
+ rmSync17(tempDir, { recursive: true, force: true });
21371
21468
  throw error;
21372
21469
  }
21373
21470
  }
@@ -21432,7 +21529,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
21432
21529
  }
21433
21530
  throw error;
21434
21531
  } finally {
21435
- rmSync16(stagingRoot, { recursive: true, force: true });
21532
+ rmSync17(stagingRoot, { recursive: true, force: true });
21436
21533
  }
21437
21534
  }
21438
21535
  async function planV2(projectDir, config, planV2Dir) {
@@ -21654,7 +21751,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21654
21751
  );
21655
21752
  renameWithRetry9(tempDir, destinationDir);
21656
21753
  } catch (error) {
21657
- rmSync16(tempDir, { recursive: true, force: true });
21754
+ rmSync17(tempDir, { recursive: true, force: true });
21658
21755
  throw error;
21659
21756
  }
21660
21757
  return {
@@ -22289,7 +22386,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22289
22386
  return observedChunkCaptureMode(capturePerfs);
22290
22387
  },
22291
22388
  resetForScreenshotRetry: () => {
22292
- rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22389
+ rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22293
22390
  boxesMeasured();
22294
22391
  mkdirSync19(framesDir, { recursive: true });
22295
22392
  capturePerfs.length = 0;
@@ -22335,8 +22432,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22335
22432
  fps: { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen },
22336
22433
  timeoutMs: cfg.ffmpegProcessTimeout
22337
22434
  });
22338
- rmSync17(videoOnlyPath, { force: true });
22339
- rmSync17(audioScratchPath, { force: true });
22435
+ rmSync18(videoOnlyPath, { force: true });
22436
+ rmSync18(audioScratchPath, { force: true });
22340
22437
  }
22341
22438
  encodeStageMs = Date.now() - encodeStarted;
22342
22439
  } finally {
@@ -22386,8 +22483,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22386
22483
  writeFileSync12(perfPath, `${JSON.stringify(perfPayload, null, 2)}
22387
22484
  `, "utf-8");
22388
22485
  try {
22389
- rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22390
- rmSync17(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22486
+ rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22487
+ rmSync18(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22391
22488
  } catch (err) {
22392
22489
  log.warn("[renderChunk] failed to remove work dir", {
22393
22490
  workDir,
@@ -22491,7 +22588,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
22491
22588
  framesEncoded: endFrame - startFrame
22492
22589
  };
22493
22590
  } finally {
22494
- rmSync18(workDir, { recursive: true, force: true });
22591
+ rmSync19(workDir, { recursive: true, force: true });
22495
22592
  }
22496
22593
  }
22497
22594
 
@@ -23135,15 +23232,20 @@ import {
23135
23232
 
23136
23233
  // src/server.ts
23137
23234
  import {
23235
+ closeSync as closeSync9,
23236
+ constants as fsConstants,
23138
23237
  existsSync as existsSync33,
23238
+ fstatSync as fstatSync5,
23239
+ lstatSync as lstatSync6,
23139
23240
  mkdirSync as mkdirSync21,
23241
+ openSync as openSync9,
23140
23242
  statSync as statSync14,
23141
23243
  mkdtempSync as mkdtempSync2,
23142
23244
  writeFileSync as writeFileSync13,
23143
- rmSync as rmSync19,
23245
+ rmSync as rmSync20,
23144
23246
  createReadStream as createReadStream6
23145
23247
  } from "node:fs";
23146
- import { resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23248
+ import { basename as basename9, resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23147
23249
  import { tmpdir as tmpdir6 } from "node:os";
23148
23250
  import { parseArgs } from "node:util";
23149
23251
  import { isIP } from "node:net";
@@ -23157,6 +23259,7 @@ import {
23157
23259
  referenceBackgroundResult as referenceBackgroundResult7
23158
23260
  } from "@hyperframes/engine";
23159
23261
  import { isSafePath as isSafePath4 } from "@hyperframes/core/safe-path";
23262
+ import { foreignWritablePath } from "@hyperframes/core/cache-dir";
23160
23263
 
23161
23264
  // src/services/hyperframeLint.ts
23162
23265
  import {
@@ -23168,7 +23271,7 @@ import {
23168
23271
  closeSync as closeSync8,
23169
23272
  constants as constants4
23170
23273
  } from "node:fs";
23171
- import { resolve as resolve12, join as join50, relative as relative9, isAbsolute as isAbsolute6, sep as sep7, dirname as dirname20 } from "node:path";
23274
+ import { resolve as resolve12, join as join50, relative as relative10, isAbsolute as isAbsolute7, sep as sep7, dirname as dirname20 } from "node:path";
23172
23275
  import { fileURLToPath as fileURLToPath7 } from "node:url";
23173
23276
  import { Worker as Worker3 } from "node:worker_threads";
23174
23277
  function isStringRecord(value) {
@@ -23214,8 +23317,8 @@ function readEntryHtml(filePath) {
23214
23317
  }
23215
23318
  }
23216
23319
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
23217
- const entryRelativePath = relative9(absProjectDir, absoluteEntryPath);
23218
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep7}`) || isAbsolute6(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
23320
+ const entryRelativePath = relative10(absProjectDir, absoluteEntryPath);
23321
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep7}`) || isAbsolute7(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
23219
23322
  }
23220
23323
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
23221
23324
  const absProjectDir = resolve12(projectDir);
@@ -23620,16 +23723,31 @@ function buildRenderJobConfig(input, outputPath, log) {
23620
23723
  }
23621
23724
  function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
23622
23725
  const { input, cleanupProjectDir } = prepared;
23623
- const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
23726
+ const serverNamed = input.outputPath == null;
23727
+ const outputCandidate = input.outputPath ?? join52(rendersDir, `${basename9(resolve13(input.projectDir))}-${crypto.randomUUID()}.mp4`);
23728
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
23729
+ const outputDir = dirname22(absoluteOutputPath);
23624
23730
  if (confineOutput) {
23625
- mkdirSync21(rendersDir, { recursive: true });
23731
+ mkdirSync21(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23626
23732
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
23627
23733
  throw new Error("outputPath must be inside the renders directory");
23628
23734
  }
23735
+ const foreign = folderAnotherAccountCanChange(outputDir, rendersDir);
23736
+ if (foreign) {
23737
+ throw new Error(
23738
+ `outputPath must be in a folder only this server's account can change; another account can change ${foreign}`
23739
+ );
23740
+ }
23629
23741
  }
23630
- const outputDir = dirname22(absoluteOutputPath);
23631
- if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
23632
- return { input, cleanupProjectDir, absoluteOutputPath };
23742
+ if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23743
+ return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
23744
+ }
23745
+ var STICKY_BIT = 512;
23746
+ var SERVER_FOLDER_MODE = 493;
23747
+ function folderAnotherAccountCanChange(dir, rendersDir) {
23748
+ const foreign = foreignWritablePath(dir, rendersDir);
23749
+ const stickyRoot = foreign === resolve13(rendersDir) && (lstatSync6(foreign).mode & STICKY_BIT) !== 0;
23750
+ return stickyRoot ? void 0 : foreign;
23633
23751
  }
23634
23752
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
23635
23753
  try {
@@ -23769,35 +23887,74 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
23769
23887
  return fallbackPath;
23770
23888
  }
23771
23889
  }
23772
- function createArtifactStore(ttlMs) {
23890
+ function createArtifactStore(ttlMs, log) {
23773
23891
  const artifacts = /* @__PURE__ */ new Map();
23892
+ const forget = (token) => {
23893
+ const artifact = artifacts.get(token);
23894
+ if (!artifact) return;
23895
+ artifacts.delete(token);
23896
+ if (artifact.pin !== void 0) closeSync9(artifact.pin);
23897
+ if (!artifact.serverNamed) return;
23898
+ try {
23899
+ rmSync20(artifact.path, { force: true });
23900
+ } catch (error) {
23901
+ log.warn("Failed to remove output artifact", {
23902
+ path: artifact.path,
23903
+ error: error instanceof Error ? error.message : String(error)
23904
+ });
23905
+ }
23906
+ };
23774
23907
  const cleanup = setInterval(() => {
23775
23908
  const now = Date.now();
23776
23909
  for (const [token, artifact] of artifacts.entries()) {
23777
- if (artifact.expiresAtMs <= now) {
23778
- artifacts.delete(token);
23779
- }
23910
+ if (artifact.expiresAtMs <= now) forget(token);
23780
23911
  }
23781
23912
  }, 6e4);
23782
23913
  cleanup.unref();
23783
23914
  return {
23784
- register(path) {
23915
+ register(path, serverNamed) {
23916
+ const pin = serverNamed ? openNoFollow(path) : void 0;
23917
+ const stat = pin === void 0 ? lstatSync6(path, { bigint: true, throwIfNoEntry: false }) : fstatSync5(pin, { bigint: true });
23918
+ const identity = stat && fileIdentity(stat);
23785
23919
  const token = crypto.randomUUID();
23786
- artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
23920
+ artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
23787
23921
  return token;
23788
23922
  },
23789
23923
  get(token) {
23790
- return artifacts.get(token);
23924
+ const artifact = artifacts.get(token);
23925
+ if (artifact && artifact.expiresAtMs <= Date.now()) {
23926
+ forget(token);
23927
+ return void 0;
23928
+ }
23929
+ return artifact;
23791
23930
  },
23792
- delete(token) {
23793
- artifacts.delete(token);
23794
- }
23931
+ forget
23795
23932
  };
23796
23933
  }
23934
+ function openArtifact(artifact) {
23935
+ const fd = openNoFollow(artifact.path);
23936
+ if (fd === void 0) return void 0;
23937
+ const stat = fstatSync5(fd, { bigint: true });
23938
+ if (stat.isFile() && fileIdentity(stat) === artifact.identity) return fd;
23939
+ closeSync9(fd);
23940
+ return void 0;
23941
+ }
23942
+ function openNoFollow(path) {
23943
+ try {
23944
+ return openSync9(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
23945
+ } catch (error) {
23946
+ const code = error.code;
23947
+ if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR") return void 0;
23948
+ throw error;
23949
+ }
23950
+ }
23951
+ function fileIdentity(stat) {
23952
+ return `${stat.dev}:${stat.ino}`;
23953
+ }
23797
23954
  function cleanupTempDir(dir, log) {
23798
23955
  if (!dir) return;
23799
23956
  try {
23800
- rmSync19(dir, { recursive: true, force: true });
23957
+ rmSync20(dir, { recursive: true, force: true });
23801
23958
  } catch (error) {
23802
23959
  log.warn("Failed to cleanup temp project dir", {
23803
23960
  cleanupProjectDir: dir,
@@ -23906,10 +24063,10 @@ function createRenderHandlers(options = {}) {
23906
24063
  const log = options.logger ?? defaultLogger;
23907
24064
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
23908
24065
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
23909
- const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
24066
+ const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? mkdtempSync2(join52(tmpdir6(), "hyperframes-renders-"));
23910
24067
  const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
23911
24068
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
23912
- const store = createArtifactStore(artifactTtlMs);
24069
+ const store = createArtifactStore(artifactTtlMs, log);
23913
24070
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
23914
24071
  const renderSemaphore = new Semaphore(maxConcurrentRenders);
23915
24072
  const startTime = Date.now();
@@ -23974,7 +24131,7 @@ function createRenderHandlers(options = {}) {
23974
24131
  if ("error" in preparedJob) {
23975
24132
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
23976
24133
  }
23977
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
24134
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
23978
24135
  const release = await renderSemaphore.acquire();
23979
24136
  log.info("render started", {
23980
24137
  requestId,
@@ -23991,7 +24148,7 @@ function createRenderHandlers(options = {}) {
23991
24148
  );
23992
24149
  const fileSize = outputFileSize(absoluteOutputPath);
23993
24150
  const durationMs = Date.now() - t0;
23994
- const outputToken = store.register(absoluteOutputPath);
24151
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
23995
24152
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
23996
24153
  log.info("render completed", {
23997
24154
  requestId,
@@ -24063,7 +24220,7 @@ function createRenderHandlers(options = {}) {
24063
24220
  });
24064
24221
  return;
24065
24222
  }
24066
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
24223
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
24067
24224
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
24068
24225
  const abortController = new AbortController();
24069
24226
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
@@ -24093,7 +24250,7 @@ function createRenderHandlers(options = {}) {
24093
24250
  ).finally(release);
24094
24251
  clearInterval(keepalive);
24095
24252
  const fileSize = outputFileSize(absoluteOutputPath);
24096
- const outputToken = store.register(absoluteOutputPath);
24253
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
24097
24254
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
24098
24255
  log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
24099
24256
  await stream.writeSSE({
@@ -24136,15 +24293,18 @@ function createRenderHandlers(options = {}) {
24136
24293
  if (!artifact) {
24137
24294
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
24138
24295
  }
24139
- if (!existsSync33(artifact.path)) {
24140
- store.delete(token);
24296
+ const fd = openArtifact(artifact);
24297
+ if (fd === void 0) {
24298
+ store.forget(token);
24141
24299
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
24142
24300
  }
24143
- const stats = statSync14(artifact.path);
24144
- return new Response(createReadStream6(artifact.path), {
24301
+ const { size } = fstatSync5(fd);
24302
+ const body = createReadStream6("", { fd });
24303
+ if (artifact.serverNamed) body.once("end", () => store.forget(token));
24304
+ return new Response(body, {
24145
24305
  headers: {
24146
24306
  "content-type": "video/mp4",
24147
- "content-length": String(stats.size),
24307
+ "content-length": String(size),
24148
24308
  "cache-control": "no-store"
24149
24309
  }
24150
24310
  });
@@ -24325,7 +24485,7 @@ import {
24325
24485
  import { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes/engine";
24326
24486
 
24327
24487
  // src/services/distributed/planV2Execution.ts
24328
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "node:fs";
24488
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync22 } from "node:fs";
24329
24489
  import { tmpdir as tmpdir7 } from "node:os";
24330
24490
  import { join as join54 } from "node:path";
24331
24491
 
@@ -24340,11 +24500,11 @@ import {
24340
24500
  mkdirSync as mkdirSync22,
24341
24501
  readFileSync as readFileSync17,
24342
24502
  readdirSync as readdirSync12,
24343
- rmSync as rmSync20,
24503
+ rmSync as rmSync21,
24344
24504
  statSync as statSync15
24345
24505
  } from "node:fs";
24346
24506
  import { localContainerInputArgs as localContainerInputArgs2 } from "@hyperframes/parsers/ff-binaries";
24347
- import { basename as basename9, dirname as dirname23, join as join53 } from "node:path";
24507
+ import { basename as basename10, dirname as dirname23, join as join53 } from "node:path";
24348
24508
  import {
24349
24509
  appendRateCapArgs as appendRateCapArgs2,
24350
24510
  writeVideoConcatList,
@@ -24396,7 +24556,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
24396
24556
  if (!existsSync34(dirname23(outputPath))) {
24397
24557
  mkdirSync22(dirname23(outputPath), { recursive: true });
24398
24558
  }
24399
- const workDir = createStagingDir7(dirname23(outputPath), `${basename9(outputPath)}.assemble-work-`);
24559
+ const workDir = createStagingDir7(dirname23(outputPath), `${basename10(outputPath)}.assemble-work-`);
24400
24560
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
24401
24561
  const stageMs = {};
24402
24562
  const ctx = {
@@ -24427,7 +24587,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
24427
24587
  });
24428
24588
  } finally {
24429
24589
  try {
24430
- rmSync20(workDir, { recursive: true, force: true });
24590
+ rmSync21(workDir, { recursive: true, force: true });
24431
24591
  } catch (err) {
24432
24592
  log.warn("[assemble] failed to remove work dir", {
24433
24593
  workDir,
@@ -24630,7 +24790,7 @@ function readCfrEncoder(planDir, format) {
24630
24790
  return encoderJson;
24631
24791
  }
24632
24792
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
24633
- if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
24793
+ if (existsSync34(outputPath)) rmSync21(outputPath, { recursive: true, force: true });
24634
24794
  mkdirSync22(outputPath, { recursive: true });
24635
24795
  let globalIdx = 0;
24636
24796
  for (const chunkDir of chunkPaths) {
@@ -24681,7 +24841,7 @@ async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
24681
24841
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
24682
24842
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
24683
24843
  } finally {
24684
- rmSync21(workRoot, { recursive: true, force: true });
24844
+ rmSync22(workRoot, { recursive: true, force: true });
24685
24845
  }
24686
24846
  }
24687
24847
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
@@ -24701,7 +24861,7 @@ async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
24701
24861
  options
24702
24862
  );
24703
24863
  } finally {
24704
- rmSync21(workRoot, { recursive: true, force: true });
24864
+ rmSync22(workRoot, { recursive: true, force: true });
24705
24865
  }
24706
24866
  }
24707
24867