@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.
@@ -18,15 +18,20 @@ function requireOutputDimensions(expected, width, height) {
18
18
 
19
19
  // src/server.ts
20
20
  import {
21
+ closeSync as closeSync7,
22
+ constants as fsConstants,
21
23
  existsSync as existsSync26,
24
+ fstatSync as fstatSync5,
25
+ lstatSync as lstatSync4,
22
26
  mkdirSync as mkdirSync13,
27
+ openSync as openSync7,
23
28
  statSync as statSync12,
24
29
  mkdtempSync,
25
30
  writeFileSync as writeFileSync7,
26
- rmSync as rmSync13,
31
+ rmSync as rmSync14,
27
32
  createReadStream as createReadStream4
28
33
  } from "node:fs";
29
- import { resolve as resolve11, dirname as dirname19, join as join40 } from "node:path";
34
+ import { basename as basename8, resolve as resolve11, dirname as dirname19, join as join40 } from "node:path";
30
35
  import { tmpdir as tmpdir4 } from "node:os";
31
36
  import { parseArgs } from "node:util";
32
37
  import { isIP } from "node:net";
@@ -40,6 +45,7 @@ import {
40
45
  referenceBackgroundResult as referenceBackgroundResult5
41
46
  } from "@hyperframes/engine";
42
47
  import { isSafePath as isSafePath4 } from "@hyperframes/core/safe-path";
48
+ import { foreignWritablePath } from "@hyperframes/core/cache-dir";
43
49
 
44
50
  // src/services/renderOrchestrator.ts
45
51
  import { audioFailureDiagnostics as audioFailureDiagnostics2, cpuBudget } from "@hyperframes/engine";
@@ -47,7 +53,7 @@ import {
47
53
  existsSync as existsSync22,
48
54
  mkdirSync as mkdirSync12,
49
55
  readdirSync as readdirSync6,
50
- rmSync as rmSync12,
56
+ rmSync as rmSync13,
51
57
  statSync as statSync10,
52
58
  writeFileSync as writeFileSync6,
53
59
  copyFileSync as copyFileSync5,
@@ -397,7 +403,7 @@ import {
397
403
  } from "@hyperframes/engine";
398
404
  import { join as join35, dirname as dirname15, resolve as resolve9 } from "path";
399
405
  import { totalmem as totalmem2 } from "node:os";
400
- import { randomUUID } from "crypto";
406
+ import { randomUUID as randomUUID3 } from "crypto";
401
407
  import { fileURLToPath as fileURLToPath5 } from "url";
402
408
 
403
409
  // src/services/fileServer.ts
@@ -581,11 +587,11 @@ var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (
581
587
  nodeResolve(fileURLToPath2(import.meta.url), "../../..", "renders");
582
588
  var LEADING_PARENT_SEGMENT_RE = /^\.\.(?:[\\/]|$)/;
583
589
  function isPathInside(childPath, parentPath, options = {}) {
584
- const resolvePath = options.pathModule?.resolve ?? nodeResolve;
590
+ const resolvePath2 = options.pathModule?.resolve ?? nodeResolve;
585
591
  const relativePath = options.pathModule?.relative ?? nodeRelative;
586
592
  const isPathAbsolute = options.pathModule?.isAbsolute ?? nodeIsAbsolute;
587
- const absChild = resolvePath(childPath);
588
- const absParent = resolvePath(parentPath);
593
+ const absChild = resolvePath2(childPath);
594
+ const absParent = resolvePath2(parentPath);
589
595
  if (absChild === absParent) return true;
590
596
  const rel = relativePath(absParent, absChild);
591
597
  return rel !== "" && !LEADING_PARENT_SEGMENT_RE.test(rel) && !isPathAbsolute(rel);
@@ -7149,7 +7155,7 @@ function countAuthoredTimedClips(html) {
7149
7155
 
7150
7156
  // src/services/render/stages/compileStage.ts
7151
7157
  import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7152
- import { join as join23, relative as relative4 } from "node:path";
7158
+ import { join as join23, relative as relative5 } from "node:path";
7153
7159
  import { privateCacheRoot } from "@hyperframes/engine";
7154
7160
  import { suggestMatchingPreset } from "@hyperframes/core";
7155
7161
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -7157,8 +7163,8 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
7157
7163
  import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7158
7164
 
7159
7165
  // src/services/compileInWorker.ts
7160
- import { existsSync as existsSync12 } from "node:fs";
7161
- import { dirname as dirname10, join as join22 } from "node:path";
7166
+ import { existsSync as existsSync12, rmSync as rmSync11 } from "node:fs";
7167
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7162
7168
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7163
7169
  import { Worker } from "node:worker_threads";
7164
7170
 
@@ -7464,7 +7470,7 @@ import {
7464
7470
  } from "@hyperframes/core/fonts/embed";
7465
7471
 
7466
7472
  // src/services/animatedGifPrep.ts
7467
- import { createHash as createHash4 } from "node:crypto";
7473
+ import { createHash as createHash4, randomUUID } from "node:crypto";
7468
7474
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7469
7475
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7470
7476
  import { parseHTML as parseHTML3 } from "linkedom";
@@ -7539,6 +7545,8 @@ function resolveLoop(metadata, override) {
7539
7545
  }
7540
7546
  var MAX_LOOP_ITERATIONS = 1e3;
7541
7547
  var MAX_PAD_SECONDS = 3600;
7548
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
7549
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
7542
7550
  function resolveCompositionDurationSeconds(document2) {
7543
7551
  let max = null;
7544
7552
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -7581,7 +7589,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
7581
7589
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
7582
7590
  }
7583
7591
  function buildAnimatedGifTranscodeArgs(input) {
7584
- const args = ["-hide_banner", "-loglevel", "error"];
7592
+ const args = [
7593
+ "-hide_banner",
7594
+ "-loglevel",
7595
+ "error",
7596
+ "-timelimit",
7597
+ String(FFMPEG_SELF_CPU_SECONDS_CAP)
7598
+ ];
7585
7599
  if (input.loopIterations > 1) {
7586
7600
  args.push("-stream_loop", String(input.loopIterations - 1));
7587
7601
  }
@@ -7609,6 +7623,8 @@ function buildAnimatedGifTranscodeArgs(input) {
7609
7623
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
7610
7624
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
7611
7625
  // extension ffmpeg cannot infer the container from.
7626
+ "-fs",
7627
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
7612
7628
  "-f",
7613
7629
  "webm",
7614
7630
  "-y",
@@ -7616,10 +7632,16 @@ function buildAnimatedGifTranscodeArgs(input) {
7616
7632
  );
7617
7633
  return args;
7618
7634
  }
7635
+ function abortError() {
7636
+ const error = new Error("Aborted");
7637
+ error.name = "AbortError";
7638
+ return error;
7639
+ }
7619
7640
  async function runAnimatedGifTranscode(request) {
7620
7641
  const timeout = request.timeoutMs ?? 3e5;
7621
- const result = await runFfmpeg2(request.args, { timeout });
7642
+ const result = await runFfmpeg2(request.args, { timeout, signal: request.signal });
7622
7643
  if (result.success) return;
7644
+ if (request.signal?.aborted) throw abortError();
7623
7645
  if (result.failureReason === "external_interruption") {
7624
7646
  throw encoderFailureError("Animated GIF transcode failed", {
7625
7647
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -7639,7 +7661,7 @@ async function ensurePreparedWebm(input) {
7639
7661
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7640
7662
  }
7641
7663
  if (!isUsableFile(input.cachePath)) {
7642
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
7664
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
7643
7665
  const args = buildAnimatedGifTranscodeArgs({
7644
7666
  inputPath: input.sourcePath,
7645
7667
  outputPath: tmpPath,
@@ -7652,11 +7674,15 @@ async function ensurePreparedWebm(input) {
7652
7674
  inputPath: input.sourcePath,
7653
7675
  outputPath: tmpPath,
7654
7676
  args,
7655
- timeoutMs: input.timeoutMs
7677
+ timeoutMs: input.timeoutMs,
7678
+ signal: input.signal
7656
7679
  });
7657
7680
  if (!isUsableFile(tmpPath)) {
7658
7681
  throw new Error("Animated GIF transcode produced an empty output");
7659
7682
  }
7683
+ if (statSync6(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
7684
+ throw new Error("Animated GIF transcode reached its output size limit");
7685
+ }
7660
7686
  if (!isUsableFile(input.cachePath)) {
7661
7687
  renameWithRetry2(tmpPath, input.cachePath);
7662
7688
  } else {
@@ -7756,6 +7782,7 @@ async function prepareAnimatedGifInputs(html, options) {
7756
7782
  loopIterations,
7757
7783
  padSeconds,
7758
7784
  timeoutMs: options.timeoutMs,
7785
+ signal: options.signal,
7759
7786
  transcode: options.transcode
7760
7787
  });
7761
7788
  const id = ensureElementId(img, document2, i);
@@ -7780,7 +7807,7 @@ async function prepareAnimatedGifInputs(html, options) {
7780
7807
  }
7781
7808
 
7782
7809
  // src/services/heifImagePrep.ts
7783
- import { createHash as createHash5 } from "node:crypto";
7810
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7784
7811
  import {
7785
7812
  closeSync as closeSync5,
7786
7813
  copyFileSync as copyFileSync3,
@@ -7926,6 +7953,13 @@ var HeifToolUnavailableError = class extends Error {
7926
7953
  this.name = "HeifToolUnavailableError";
7927
7954
  }
7928
7955
  };
7956
+ function abortError2() {
7957
+ const error = new Error("Aborted");
7958
+ error.name = "AbortError";
7959
+ return error;
7960
+ }
7961
+ var FFMPEG_SELF_CPU_SECONDS_CAP2 = 300;
7962
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP2 = 256 * 1024 * 1024;
7929
7963
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
7930
7964
  function isHeifBytes(head) {
7931
7965
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -7993,6 +8027,8 @@ async function convertHeifToJpeg(request) {
7993
8027
  "-hide_banner",
7994
8028
  "-loglevel",
7995
8029
  "error",
8030
+ "-timelimit",
8031
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
7996
8032
  ...urlInputArgs3(request.inputPath),
7997
8033
  "-i",
7998
8034
  request.inputPath,
@@ -8001,14 +8037,17 @@ async function convertHeifToJpeg(request) {
8001
8037
  "1",
8002
8038
  "-q:v",
8003
8039
  "2",
8040
+ "-fs",
8041
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
8004
8042
  "-f",
8005
8043
  "mjpeg",
8006
8044
  "-y",
8007
8045
  request.outputPath
8008
8046
  ],
8009
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
8047
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
8010
8048
  );
8011
8049
  if (!result.success) {
8050
+ if (request.signal?.aborted) throw abortError2();
8012
8051
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
8013
8052
  }
8014
8053
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -8042,7 +8081,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8042
8081
  mkdirSync8(dirname7(cachePath), { recursive: true });
8043
8082
  mkdirSync8(dirname7(outputPath), { recursive: true });
8044
8083
  if (!isUsableFile2(cachePath)) {
8045
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
8084
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8046
8085
  const inlinePath = `${tmpPath}.heic`;
8047
8086
  const inputPath = source.path ?? inlinePath;
8048
8087
  try {
@@ -8050,9 +8089,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8050
8089
  await (options.transcode ?? convertHeifToJpeg)({
8051
8090
  inputPath,
8052
8091
  outputPath: tmpPath,
8053
- timeoutMs: options.timeoutMs
8092
+ timeoutMs: options.timeoutMs,
8093
+ signal: options.signal
8054
8094
  });
8055
8095
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
8096
+ if (statSync7(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP2) {
8097
+ throw new Error("conversion reached its output size limit");
8098
+ }
8056
8099
  renameWithRetry3(tmpPath, cachePath);
8057
8100
  } catch (error) {
8058
8101
  const reason = error instanceof Error ? error.message : String(error);
@@ -8123,6 +8166,7 @@ import {
8123
8166
  isNotImagePayload,
8124
8167
  isNotMediaPayload,
8125
8168
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
8169
+ isStructurallyIncompletePngError,
8126
8170
  playlistLeavesItsFolder,
8127
8171
  NotMediaPayloadError,
8128
8172
  probeMediaProfile,
@@ -8201,6 +8245,13 @@ async function notMediaReferences(path, references) {
8201
8245
  if (images.length > 0 && await isNotImagePayload(path)) return images;
8202
8246
  return await playlistLeavesItsFolder(path) ? references : [];
8203
8247
  }
8248
+ function pngCutShort(references) {
8249
+ return references.filter((reference) => reference.expected === "video").map((reference) => ({
8250
+ expected: "video",
8251
+ detected: "image",
8252
+ elementFingerprint: fingerprintElementId(reference.id)
8253
+ }));
8254
+ }
8204
8255
  async function preflightCompositionAssetMediaTypes(input) {
8205
8256
  const references = [
8206
8257
  ...input.composition.videos.map((asset) => ({
@@ -8246,6 +8297,8 @@ async function preflightCompositionAssetMediaTypes(input) {
8246
8297
  profile = await probeMediaProfile(resolvedPath, { signal: input.signal });
8247
8298
  } catch (error) {
8248
8299
  if (input.signal?.aborted) throw input.signal.reason ?? error;
8300
+ if (isStructurallyIncompletePngError(error))
8301
+ mismatches.push(...pngCutShort(pathReferences));
8249
8302
  return;
8250
8303
  }
8251
8304
  for (const reference of pathReferences) {
@@ -9589,8 +9642,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9589
9642
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
9590
9643
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9591
9644
  if (fontFaceBlocks.length === 0) return;
9645
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9592
9646
  const inlineStyle = `<style>/* Inlined external font stylesheet */
9593
- ${fontFaceBlocks.join("\n")}
9647
+ ${fontCssWithLtAsCssEscape}
9594
9648
  </style>`;
9595
9649
  try {
9596
9650
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -10003,6 +10057,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10003
10057
  cacheDir: options.animatedGifCacheDir,
10004
10058
  sourceAssets: remoteImageAssets,
10005
10059
  timeoutMs: options.ffmpegProcessTimeout,
10060
+ signal: options.abortSignal,
10006
10061
  allowOutsideFiles: assetRoot === void 0
10007
10062
  });
10008
10063
  if (preparedHeifImages.length > 0) {
@@ -10019,6 +10074,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10019
10074
  cacheDir: options.animatedGifCacheDir,
10020
10075
  sourceAssets: gifSourceAssets,
10021
10076
  timeoutMs: options.ffmpegProcessTimeout,
10077
+ signal: options.abortSignal,
10022
10078
  allowOutsideFiles: assetRoot === void 0
10023
10079
  });
10024
10080
  if (preparedGifs.length > 0) {
@@ -10497,6 +10553,24 @@ function compileTimeoutMs() {
10497
10553
  return Number.isInteger(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_COMPILE_TIMEOUT_MS;
10498
10554
  }
10499
10555
  var warnedMissingEntry = false;
10556
+ var endOnProcessExit = /* @__PURE__ */ new Set();
10557
+ var processExitHooked = false;
10558
+ function onProcessExit(end) {
10559
+ if (!processExitHooked) {
10560
+ processExitHooked = true;
10561
+ process.on("exit", () => {
10562
+ for (const each of endOnProcessExit) each();
10563
+ });
10564
+ }
10565
+ endOnProcessExit.add(end);
10566
+ return () => endOnProcessExit.delete(end);
10567
+ }
10568
+ function tryQuietly(action) {
10569
+ try {
10570
+ action();
10571
+ } catch {
10572
+ }
10573
+ }
10500
10574
  function resolveCompileWorkerEntry(explicit, log) {
10501
10575
  if (explicit) return explicit;
10502
10576
  const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
@@ -10530,6 +10604,26 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10530
10604
  const thread = new Worker(entry, {
10531
10605
  workerData: { projectDir, htmlPath, downloadDir, options: cloneable }
10532
10606
  });
10607
+ const children = /* @__PURE__ */ new Map();
10608
+ const scratchRoots = [downloadDir, options.animatedGifCacheDir].flatMap(
10609
+ (dir) => dir ? [resolvePath(dir)] : []
10610
+ );
10611
+ const isScratch = (path) => scratchRoots.some((root) => {
10612
+ const rel = relative4(root, resolvePath(path));
10613
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute4(rel);
10614
+ });
10615
+ const endChildren = (signal) => {
10616
+ for (const [pid, output] of children) {
10617
+ if (signal) tryQuietly(() => process.kill(pid, "SIGKILL"));
10618
+ if (output) tryQuietly(() => rmSync11(output, { force: true }));
10619
+ }
10620
+ children.clear();
10621
+ };
10622
+ const offProcessExit = onProcessExit(() => endChildren(true));
10623
+ const endThread = () => {
10624
+ endChildren(true);
10625
+ void thread.terminate();
10626
+ };
10533
10627
  let settled = false;
10534
10628
  const settle = (finish) => {
10535
10629
  if (settled) return;
@@ -10540,7 +10634,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10540
10634
  };
10541
10635
  const stop = () => {
10542
10636
  thread.postMessage({ type: "abort" });
10543
- setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
10637
+ setTimeout(endThread, TERMINATE_GRACE_MS).unref();
10544
10638
  };
10545
10639
  const timer = setTimeout(() => {
10546
10640
  stop();
@@ -10553,7 +10647,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10553
10647
  abortSignal?.addEventListener("abort", onAbort, { once: true });
10554
10648
  const retire = (graceMs) => {
10555
10649
  thread.unref();
10556
- setTimeout(() => void thread.terminate(), graceMs).unref();
10650
+ setTimeout(endThread, graceMs).unref();
10557
10651
  };
10558
10652
  thread.on(
10559
10653
  "message",
@@ -10572,13 +10666,22 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10572
10666
  }
10573
10667
  }
10574
10668
  );
10575
- thread.on("error", (error) => settle(() => reject(error)));
10576
10669
  thread.on(
10577
- "exit",
10578
- (code) => settle(
10579
- () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10580
- )
10670
+ "message",
10671
+ ({ type, pid, output }) => {
10672
+ if (pid === void 0) return;
10673
+ if (type === "child") children.set(pid, output && isScratch(output) ? output : void 0);
10674
+ else if (type === "childExit") children.delete(pid);
10675
+ }
10581
10676
  );
10677
+ thread.on("error", (error) => settle(() => reject(error)));
10678
+ thread.on("exit", (code) => {
10679
+ offProcessExit();
10680
+ endChildren(false);
10681
+ settle(
10682
+ () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10683
+ );
10684
+ });
10582
10685
  });
10583
10686
  }
10584
10687
 
@@ -10608,10 +10711,10 @@ function resolveEntryHtmlPath(input) {
10608
10711
  const readEntry = (path) => {
10609
10712
  if (escapesAssetRoot(path, input.assetRoot)) {
10610
10713
  throw new Error(
10611
- `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10714
+ `Entry file "${relative5(projectDir, path)}" leads outside the project folder`
10612
10715
  );
10613
10716
  }
10614
- assertCompositionFileSize2(path, relative4(projectDir, path));
10717
+ assertCompositionFileSize2(path, relative5(projectDir, path));
10615
10718
  return readTextFile2(path);
10616
10719
  };
10617
10720
  const htmlPath = join23(projectDir, entryFile);
@@ -14376,7 +14479,7 @@ import {
14376
14479
  mkdirSync as mkdirSync11,
14377
14480
  readdirSync as readdirSync5,
14378
14481
  readFileSync as readFileSync9,
14379
- rmSync as rmSync11,
14482
+ rmSync as rmSync12,
14380
14483
  statSync as statSync9,
14381
14484
  writeFileSync as writeFileSync5
14382
14485
  } from "node:fs";
@@ -14515,7 +14618,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14515
14618
  fileSize
14516
14619
  };
14517
14620
  } finally {
14518
- rmSync11(input.palettePath, { force: true });
14621
+ rmSync12(input.palettePath, { force: true });
14519
14622
  }
14520
14623
  }
14521
14624
  function startEncodeProgress(job, stage, onProgress) {
@@ -15394,7 +15497,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15394
15497
  function createRenderJob(config) {
15395
15498
  return {
15396
15499
  ...referenceBackgroundResult(void 0),
15397
- id: randomUUID(),
15500
+ id: randomUUID3(),
15398
15501
  config: {
15399
15502
  ...config,
15400
15503
  fps: toFps2(config.fps),
@@ -15909,7 +16012,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15909
16012
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
15910
16013
  return;
15911
16014
  }
15912
- rmSync12(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
16015
+ rmSync13(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
15913
16016
  });
15914
16017
  try {
15915
16018
  await executeRenderPipeline({
@@ -17377,7 +17480,7 @@ async function executeRenderPipeline(input) {
17377
17480
  segmentDir
17378
17481
  });
17379
17482
  }
17380
- if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
17483
+ if (completedSegments.size === 0) rmSync13(segmentDir, { recursive: true, force: true });
17381
17484
  const invokeSegmented = () => {
17382
17485
  if (capturePlan.kind !== "sdr_segmented") {
17383
17486
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17470,7 +17573,7 @@ async function executeRenderPipeline(input) {
17470
17573
  probeSession = null;
17471
17574
  await closeOrphanedProbeForRetry(orphaned, closeCaptureSession8, log, "segmented");
17472
17575
  }
17473
- rmSync12(segmentDir, { recursive: true, force: true });
17576
+ rmSync13(segmentDir, { recursive: true, force: true });
17474
17577
  completedSegments = /* @__PURE__ */ new Set();
17475
17578
  segmentManifest = emptySegmentManifest();
17476
17579
  dedupPerfs.length = 0;
@@ -17509,7 +17612,7 @@ async function executeRenderPipeline(input) {
17509
17612
  );
17510
17613
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
17511
17614
  if (job.config.keepSegments !== true) {
17512
- rmSync12(segmentDir, { recursive: true, force: true });
17615
+ rmSync13(segmentDir, { recursive: true, force: true });
17513
17616
  }
17514
17617
  } else {
17515
17618
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -17786,7 +17889,7 @@ async function executeRenderPipeline(input) {
17786
17889
  "capture_disk",
17787
17890
  "drawElement capture failed; retrying with a fresh screenshot session"
17788
17891
  );
17789
- rmSync12(framesDir, { recursive: true, force: true });
17892
+ rmSync13(framesDir, { recursive: true, force: true });
17790
17893
  mkdirSync12(framesDir, { recursive: true });
17791
17894
  resetCaptureAttemptProgress(job);
17792
17895
  dedupPerfs.length = 0;
@@ -18099,7 +18202,7 @@ import {
18099
18202
  closeSync as closeSync6,
18100
18203
  constants as constants4
18101
18204
  } from "node:fs";
18102
- import { resolve as resolve10, join as join36, relative as relative5, isAbsolute as isAbsolute4, sep as sep5, dirname as dirname16 } from "node:path";
18205
+ import { resolve as resolve10, join as join36, relative as relative6, isAbsolute as isAbsolute5, sep as sep5, dirname as dirname16 } from "node:path";
18103
18206
  import { fileURLToPath as fileURLToPath6 } from "node:url";
18104
18207
  import { Worker as Worker3 } from "node:worker_threads";
18105
18208
  function isStringRecord(value) {
@@ -18145,8 +18248,8 @@ function readEntryHtml(filePath) {
18145
18248
  }
18146
18249
  }
18147
18250
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
18148
- const entryRelativePath = relative5(absProjectDir, absoluteEntryPath);
18149
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute4(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
18251
+ const entryRelativePath = relative6(absProjectDir, absoluteEntryPath);
18252
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute5(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
18150
18253
  }
18151
18254
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
18152
18255
  const absProjectDir = resolve10(projectDir);
@@ -18429,7 +18532,7 @@ import {
18429
18532
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
18430
18533
  } from "@hyperframes/engine";
18431
18534
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
18432
- import { extname as extname4, isAbsolute as isAbsolute5, join as join39, relative as relative6, sep as sep6 } from "node:path";
18535
+ import { extname as extname4, isAbsolute as isAbsolute6, join as join39, relative as relative7, sep as sep6 } from "node:path";
18433
18536
  import {
18434
18537
  fpsToNumber as fpsToNumber9,
18435
18538
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -18999,16 +19102,31 @@ function buildRenderJobConfig(input, outputPath, log) {
18999
19102
  }
19000
19103
  function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
19001
19104
  const { input, cleanupProjectDir } = prepared;
19002
- const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
19105
+ const serverNamed = input.outputPath == null;
19106
+ const outputCandidate = input.outputPath ?? join40(rendersDir, `${basename8(resolve11(input.projectDir))}-${crypto.randomUUID()}.mp4`);
19107
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
19108
+ const outputDir = dirname19(absoluteOutputPath);
19003
19109
  if (confineOutput) {
19004
- mkdirSync13(rendersDir, { recursive: true });
19110
+ mkdirSync13(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
19005
19111
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
19006
19112
  throw new Error("outputPath must be inside the renders directory");
19007
19113
  }
19114
+ const foreign = folderAnotherAccountCanChange(outputDir, rendersDir);
19115
+ if (foreign) {
19116
+ throw new Error(
19117
+ `outputPath must be in a folder only this server's account can change; another account can change ${foreign}`
19118
+ );
19119
+ }
19008
19120
  }
19009
- const outputDir = dirname19(absoluteOutputPath);
19010
- if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
19011
- return { input, cleanupProjectDir, absoluteOutputPath };
19121
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
19122
+ return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
19123
+ }
19124
+ var STICKY_BIT = 512;
19125
+ var SERVER_FOLDER_MODE = 493;
19126
+ function folderAnotherAccountCanChange(dir, rendersDir) {
19127
+ const foreign = foreignWritablePath(dir, rendersDir);
19128
+ const stickyRoot = foreign === resolve11(rendersDir) && (lstatSync4(foreign).mode & STICKY_BIT) !== 0;
19129
+ return stickyRoot ? void 0 : foreign;
19012
19130
  }
19013
19131
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
19014
19132
  try {
@@ -19148,35 +19266,74 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
19148
19266
  return fallbackPath;
19149
19267
  }
19150
19268
  }
19151
- function createArtifactStore(ttlMs) {
19269
+ function createArtifactStore(ttlMs, log) {
19152
19270
  const artifacts = /* @__PURE__ */ new Map();
19271
+ const forget = (token) => {
19272
+ const artifact = artifacts.get(token);
19273
+ if (!artifact) return;
19274
+ artifacts.delete(token);
19275
+ if (artifact.pin !== void 0) closeSync7(artifact.pin);
19276
+ if (!artifact.serverNamed) return;
19277
+ try {
19278
+ rmSync14(artifact.path, { force: true });
19279
+ } catch (error) {
19280
+ log.warn("Failed to remove output artifact", {
19281
+ path: artifact.path,
19282
+ error: error instanceof Error ? error.message : String(error)
19283
+ });
19284
+ }
19285
+ };
19153
19286
  const cleanup = setInterval(() => {
19154
19287
  const now = Date.now();
19155
19288
  for (const [token, artifact] of artifacts.entries()) {
19156
- if (artifact.expiresAtMs <= now) {
19157
- artifacts.delete(token);
19158
- }
19289
+ if (artifact.expiresAtMs <= now) forget(token);
19159
19290
  }
19160
19291
  }, 6e4);
19161
19292
  cleanup.unref();
19162
19293
  return {
19163
- register(path) {
19294
+ register(path, serverNamed) {
19295
+ const pin = serverNamed ? openNoFollow(path) : void 0;
19296
+ const stat = pin === void 0 ? lstatSync4(path, { bigint: true, throwIfNoEntry: false }) : fstatSync5(pin, { bigint: true });
19297
+ const identity = stat && fileIdentity(stat);
19164
19298
  const token = crypto.randomUUID();
19165
- artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
19299
+ artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
19166
19300
  return token;
19167
19301
  },
19168
19302
  get(token) {
19169
- return artifacts.get(token);
19303
+ const artifact = artifacts.get(token);
19304
+ if (artifact && artifact.expiresAtMs <= Date.now()) {
19305
+ forget(token);
19306
+ return void 0;
19307
+ }
19308
+ return artifact;
19170
19309
  },
19171
- delete(token) {
19172
- artifacts.delete(token);
19173
- }
19310
+ forget
19174
19311
  };
19175
19312
  }
19313
+ function openArtifact(artifact) {
19314
+ const fd = openNoFollow(artifact.path);
19315
+ if (fd === void 0) return void 0;
19316
+ const stat = fstatSync5(fd, { bigint: true });
19317
+ if (stat.isFile() && fileIdentity(stat) === artifact.identity) return fd;
19318
+ closeSync7(fd);
19319
+ return void 0;
19320
+ }
19321
+ function openNoFollow(path) {
19322
+ try {
19323
+ return openSync7(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
19324
+ } catch (error) {
19325
+ const code = error.code;
19326
+ if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR") return void 0;
19327
+ throw error;
19328
+ }
19329
+ }
19330
+ function fileIdentity(stat) {
19331
+ return `${stat.dev}:${stat.ino}`;
19332
+ }
19176
19333
  function cleanupTempDir(dir, log) {
19177
19334
  if (!dir) return;
19178
19335
  try {
19179
- rmSync13(dir, { recursive: true, force: true });
19336
+ rmSync14(dir, { recursive: true, force: true });
19180
19337
  } catch (error) {
19181
19338
  log.warn("Failed to cleanup temp project dir", {
19182
19339
  cleanupProjectDir: dir,
@@ -19285,10 +19442,10 @@ function createRenderHandlers(options = {}) {
19285
19442
  const log = options.logger ?? defaultLogger;
19286
19443
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
19287
19444
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
19288
- const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
19445
+ const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? mkdtempSync(join40(tmpdir4(), "hyperframes-renders-"));
19289
19446
  const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
19290
19447
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
19291
- const store = createArtifactStore(artifactTtlMs);
19448
+ const store = createArtifactStore(artifactTtlMs, log);
19292
19449
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
19293
19450
  const renderSemaphore = new Semaphore(maxConcurrentRenders);
19294
19451
  const startTime = Date.now();
@@ -19353,7 +19510,7 @@ function createRenderHandlers(options = {}) {
19353
19510
  if ("error" in preparedJob) {
19354
19511
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
19355
19512
  }
19356
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19513
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19357
19514
  const release = await renderSemaphore.acquire();
19358
19515
  log.info("render started", {
19359
19516
  requestId,
@@ -19370,7 +19527,7 @@ function createRenderHandlers(options = {}) {
19370
19527
  );
19371
19528
  const fileSize = outputFileSize(absoluteOutputPath);
19372
19529
  const durationMs = Date.now() - t0;
19373
- const outputToken = store.register(absoluteOutputPath);
19530
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19374
19531
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19375
19532
  log.info("render completed", {
19376
19533
  requestId,
@@ -19442,7 +19599,7 @@ function createRenderHandlers(options = {}) {
19442
19599
  });
19443
19600
  return;
19444
19601
  }
19445
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19602
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19446
19603
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
19447
19604
  const abortController = new AbortController();
19448
19605
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
@@ -19472,7 +19629,7 @@ function createRenderHandlers(options = {}) {
19472
19629
  ).finally(release);
19473
19630
  clearInterval(keepalive);
19474
19631
  const fileSize = outputFileSize(absoluteOutputPath);
19475
- const outputToken = store.register(absoluteOutputPath);
19632
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19476
19633
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19477
19634
  log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
19478
19635
  await stream.writeSSE({
@@ -19515,15 +19672,18 @@ function createRenderHandlers(options = {}) {
19515
19672
  if (!artifact) {
19516
19673
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
19517
19674
  }
19518
- if (!existsSync26(artifact.path)) {
19519
- store.delete(token);
19675
+ const fd = openArtifact(artifact);
19676
+ if (fd === void 0) {
19677
+ store.forget(token);
19520
19678
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
19521
19679
  }
19522
- const stats = statSync12(artifact.path);
19523
- return new Response(createReadStream4(artifact.path), {
19680
+ const { size } = fstatSync5(fd);
19681
+ const body = createReadStream4("", { fd });
19682
+ if (artifact.serverNamed) body.once("end", () => store.forget(token));
19683
+ return new Response(body, {
19524
19684
  headers: {
19525
19685
  "content-type": "video/mp4",
19526
- "content-length": String(stats.size),
19686
+ "content-length": String(size),
19527
19687
  "cache-control": "no-store"
19528
19688
  }
19529
19689
  });