@hyperframes/producer 0.9.87 → 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);
@@ -1673,12 +1679,12 @@ var workerPhasesByJob = /* @__PURE__ */ new WeakMap();
1673
1679
  function forgetWorkerPhases(job) {
1674
1680
  workerPhasesByJob.delete(job);
1675
1681
  }
1676
- var staticDedupActivityByJob = /* @__PURE__ */ new WeakMap();
1677
- function noteStaticDedupActivity(job) {
1678
- staticDedupActivityByJob.set(job, (staticDedupActivityByJob.get(job) ?? 0) + 1);
1682
+ var captureActivityByJob = /* @__PURE__ */ new WeakMap();
1683
+ function noteCaptureActivity(job) {
1684
+ captureActivityByJob.set(job, (captureActivityByJob.get(job) ?? 0) + 1);
1679
1685
  }
1680
- function staticDedupActivity(job) {
1681
- return staticDedupActivityByJob.get(job) ?? 0;
1686
+ function captureActivity(job) {
1687
+ return captureActivityByJob.get(job) ?? 0;
1682
1688
  }
1683
1689
  function describeWorkerPhases(job) {
1684
1690
  const phases = workerPhasesByJob.get(job);
@@ -6287,7 +6293,8 @@ async function extractDeferredFrames(input) {
6287
6293
  outputDir: input.outputRoot,
6288
6294
  format: range.format,
6289
6295
  frameRanges: contiguousRuns(indexes),
6290
- shownBox: input.shownBoxes?.get(video.videoId)
6296
+ shownBox: input.shownBoxes?.get(video.videoId),
6297
+ ...input.onProgress && { onProgress: input.onProgress }
6291
6298
  },
6292
6299
  input.signal,
6293
6300
  input.cfg
@@ -7148,7 +7155,7 @@ function countAuthoredTimedClips(html) {
7148
7155
 
7149
7156
  // src/services/render/stages/compileStage.ts
7150
7157
  import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7151
- import { join as join23, relative as relative4 } from "node:path";
7158
+ import { join as join23, relative as relative5 } from "node:path";
7152
7159
  import { privateCacheRoot } from "@hyperframes/engine";
7153
7160
  import { suggestMatchingPreset } from "@hyperframes/core";
7154
7161
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -7156,8 +7163,8 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
7156
7163
  import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7157
7164
 
7158
7165
  // src/services/compileInWorker.ts
7159
- import { existsSync as existsSync12 } from "node:fs";
7160
- 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";
7161
7168
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7162
7169
  import { Worker } from "node:worker_threads";
7163
7170
 
@@ -7463,7 +7470,7 @@ import {
7463
7470
  } from "@hyperframes/core/fonts/embed";
7464
7471
 
7465
7472
  // src/services/animatedGifPrep.ts
7466
- import { createHash as createHash4 } from "node:crypto";
7473
+ import { createHash as createHash4, randomUUID } from "node:crypto";
7467
7474
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7468
7475
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7469
7476
  import { parseHTML as parseHTML3 } from "linkedom";
@@ -7538,6 +7545,8 @@ function resolveLoop(metadata, override) {
7538
7545
  }
7539
7546
  var MAX_LOOP_ITERATIONS = 1e3;
7540
7547
  var MAX_PAD_SECONDS = 3600;
7548
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
7549
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
7541
7550
  function resolveCompositionDurationSeconds(document2) {
7542
7551
  let max = null;
7543
7552
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -7580,7 +7589,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
7580
7589
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
7581
7590
  }
7582
7591
  function buildAnimatedGifTranscodeArgs(input) {
7583
- 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
+ ];
7584
7599
  if (input.loopIterations > 1) {
7585
7600
  args.push("-stream_loop", String(input.loopIterations - 1));
7586
7601
  }
@@ -7608,6 +7623,8 @@ function buildAnimatedGifTranscodeArgs(input) {
7608
7623
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
7609
7624
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
7610
7625
  // extension ffmpeg cannot infer the container from.
7626
+ "-fs",
7627
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
7611
7628
  "-f",
7612
7629
  "webm",
7613
7630
  "-y",
@@ -7615,10 +7632,16 @@ function buildAnimatedGifTranscodeArgs(input) {
7615
7632
  );
7616
7633
  return args;
7617
7634
  }
7635
+ function abortError() {
7636
+ const error = new Error("Aborted");
7637
+ error.name = "AbortError";
7638
+ return error;
7639
+ }
7618
7640
  async function runAnimatedGifTranscode(request) {
7619
7641
  const timeout = request.timeoutMs ?? 3e5;
7620
- const result = await runFfmpeg2(request.args, { timeout });
7642
+ const result = await runFfmpeg2(request.args, { timeout, signal: request.signal });
7621
7643
  if (result.success) return;
7644
+ if (request.signal?.aborted) throw abortError();
7622
7645
  if (result.failureReason === "external_interruption") {
7623
7646
  throw encoderFailureError("Animated GIF transcode failed", {
7624
7647
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -7638,7 +7661,7 @@ async function ensurePreparedWebm(input) {
7638
7661
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7639
7662
  }
7640
7663
  if (!isUsableFile(input.cachePath)) {
7641
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
7664
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
7642
7665
  const args = buildAnimatedGifTranscodeArgs({
7643
7666
  inputPath: input.sourcePath,
7644
7667
  outputPath: tmpPath,
@@ -7651,11 +7674,15 @@ async function ensurePreparedWebm(input) {
7651
7674
  inputPath: input.sourcePath,
7652
7675
  outputPath: tmpPath,
7653
7676
  args,
7654
- timeoutMs: input.timeoutMs
7677
+ timeoutMs: input.timeoutMs,
7678
+ signal: input.signal
7655
7679
  });
7656
7680
  if (!isUsableFile(tmpPath)) {
7657
7681
  throw new Error("Animated GIF transcode produced an empty output");
7658
7682
  }
7683
+ if (statSync6(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
7684
+ throw new Error("Animated GIF transcode reached its output size limit");
7685
+ }
7659
7686
  if (!isUsableFile(input.cachePath)) {
7660
7687
  renameWithRetry2(tmpPath, input.cachePath);
7661
7688
  } else {
@@ -7755,6 +7782,7 @@ async function prepareAnimatedGifInputs(html, options) {
7755
7782
  loopIterations,
7756
7783
  padSeconds,
7757
7784
  timeoutMs: options.timeoutMs,
7785
+ signal: options.signal,
7758
7786
  transcode: options.transcode
7759
7787
  });
7760
7788
  const id = ensureElementId(img, document2, i);
@@ -7779,7 +7807,7 @@ async function prepareAnimatedGifInputs(html, options) {
7779
7807
  }
7780
7808
 
7781
7809
  // src/services/heifImagePrep.ts
7782
- import { createHash as createHash5 } from "node:crypto";
7810
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7783
7811
  import {
7784
7812
  closeSync as closeSync5,
7785
7813
  copyFileSync as copyFileSync3,
@@ -7925,6 +7953,13 @@ var HeifToolUnavailableError = class extends Error {
7925
7953
  this.name = "HeifToolUnavailableError";
7926
7954
  }
7927
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;
7928
7963
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
7929
7964
  function isHeifBytes(head) {
7930
7965
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -7992,6 +8027,8 @@ async function convertHeifToJpeg(request) {
7992
8027
  "-hide_banner",
7993
8028
  "-loglevel",
7994
8029
  "error",
8030
+ "-timelimit",
8031
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
7995
8032
  ...urlInputArgs3(request.inputPath),
7996
8033
  "-i",
7997
8034
  request.inputPath,
@@ -8000,14 +8037,17 @@ async function convertHeifToJpeg(request) {
8000
8037
  "1",
8001
8038
  "-q:v",
8002
8039
  "2",
8040
+ "-fs",
8041
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
8003
8042
  "-f",
8004
8043
  "mjpeg",
8005
8044
  "-y",
8006
8045
  request.outputPath
8007
8046
  ],
8008
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
8047
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
8009
8048
  );
8010
8049
  if (!result.success) {
8050
+ if (request.signal?.aborted) throw abortError2();
8011
8051
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
8012
8052
  }
8013
8053
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -8041,7 +8081,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8041
8081
  mkdirSync8(dirname7(cachePath), { recursive: true });
8042
8082
  mkdirSync8(dirname7(outputPath), { recursive: true });
8043
8083
  if (!isUsableFile2(cachePath)) {
8044
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
8084
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8045
8085
  const inlinePath = `${tmpPath}.heic`;
8046
8086
  const inputPath = source.path ?? inlinePath;
8047
8087
  try {
@@ -8049,9 +8089,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8049
8089
  await (options.transcode ?? convertHeifToJpeg)({
8050
8090
  inputPath,
8051
8091
  outputPath: tmpPath,
8052
- timeoutMs: options.timeoutMs
8092
+ timeoutMs: options.timeoutMs,
8093
+ signal: options.signal
8053
8094
  });
8054
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
+ }
8055
8099
  renameWithRetry3(tmpPath, cachePath);
8056
8100
  } catch (error) {
8057
8101
  const reason = error instanceof Error ? error.message : String(error);
@@ -8122,6 +8166,7 @@ import {
8122
8166
  isNotImagePayload,
8123
8167
  isNotMediaPayload,
8124
8168
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
8169
+ isStructurallyIncompletePngError,
8125
8170
  playlistLeavesItsFolder,
8126
8171
  NotMediaPayloadError,
8127
8172
  probeMediaProfile,
@@ -8200,6 +8245,13 @@ async function notMediaReferences(path, references) {
8200
8245
  if (images.length > 0 && await isNotImagePayload(path)) return images;
8201
8246
  return await playlistLeavesItsFolder(path) ? references : [];
8202
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
+ }
8203
8255
  async function preflightCompositionAssetMediaTypes(input) {
8204
8256
  const references = [
8205
8257
  ...input.composition.videos.map((asset) => ({
@@ -8245,6 +8297,8 @@ async function preflightCompositionAssetMediaTypes(input) {
8245
8297
  profile = await probeMediaProfile(resolvedPath, { signal: input.signal });
8246
8298
  } catch (error) {
8247
8299
  if (input.signal?.aborted) throw input.signal.reason ?? error;
8300
+ if (isStructurallyIncompletePngError(error))
8301
+ mismatches.push(...pngCutShort(pathReferences));
8248
8302
  return;
8249
8303
  }
8250
8304
  for (const reference of pathReferences) {
@@ -9588,8 +9642,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9588
9642
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
9589
9643
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9590
9644
  if (fontFaceBlocks.length === 0) return;
9645
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9591
9646
  const inlineStyle = `<style>/* Inlined external font stylesheet */
9592
- ${fontFaceBlocks.join("\n")}
9647
+ ${fontCssWithLtAsCssEscape}
9593
9648
  </style>`;
9594
9649
  try {
9595
9650
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -10002,6 +10057,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10002
10057
  cacheDir: options.animatedGifCacheDir,
10003
10058
  sourceAssets: remoteImageAssets,
10004
10059
  timeoutMs: options.ffmpegProcessTimeout,
10060
+ signal: options.abortSignal,
10005
10061
  allowOutsideFiles: assetRoot === void 0
10006
10062
  });
10007
10063
  if (preparedHeifImages.length > 0) {
@@ -10018,6 +10074,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10018
10074
  cacheDir: options.animatedGifCacheDir,
10019
10075
  sourceAssets: gifSourceAssets,
10020
10076
  timeoutMs: options.ffmpegProcessTimeout,
10077
+ signal: options.abortSignal,
10021
10078
  allowOutsideFiles: assetRoot === void 0
10022
10079
  });
10023
10080
  if (preparedGifs.length > 0) {
@@ -10496,6 +10553,24 @@ function compileTimeoutMs() {
10496
10553
  return Number.isInteger(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_COMPILE_TIMEOUT_MS;
10497
10554
  }
10498
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
+ }
10499
10574
  function resolveCompileWorkerEntry(explicit, log) {
10500
10575
  if (explicit) return explicit;
10501
10576
  const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
@@ -10529,6 +10604,26 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10529
10604
  const thread = new Worker(entry, {
10530
10605
  workerData: { projectDir, htmlPath, downloadDir, options: cloneable }
10531
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
+ };
10532
10627
  let settled = false;
10533
10628
  const settle = (finish) => {
10534
10629
  if (settled) return;
@@ -10539,7 +10634,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10539
10634
  };
10540
10635
  const stop = () => {
10541
10636
  thread.postMessage({ type: "abort" });
10542
- setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
10637
+ setTimeout(endThread, TERMINATE_GRACE_MS).unref();
10543
10638
  };
10544
10639
  const timer = setTimeout(() => {
10545
10640
  stop();
@@ -10552,7 +10647,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10552
10647
  abortSignal?.addEventListener("abort", onAbort, { once: true });
10553
10648
  const retire = (graceMs) => {
10554
10649
  thread.unref();
10555
- setTimeout(() => void thread.terminate(), graceMs).unref();
10650
+ setTimeout(endThread, graceMs).unref();
10556
10651
  };
10557
10652
  thread.on(
10558
10653
  "message",
@@ -10571,13 +10666,22 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10571
10666
  }
10572
10667
  }
10573
10668
  );
10574
- thread.on("error", (error) => settle(() => reject(error)));
10575
10669
  thread.on(
10576
- "exit",
10577
- (code) => settle(
10578
- () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10579
- )
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
+ }
10580
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
+ });
10581
10685
  });
10582
10686
  }
10583
10687
 
@@ -10607,10 +10711,10 @@ function resolveEntryHtmlPath(input) {
10607
10711
  const readEntry = (path) => {
10608
10712
  if (escapesAssetRoot(path, input.assetRoot)) {
10609
10713
  throw new Error(
10610
- `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10714
+ `Entry file "${relative5(projectDir, path)}" leads outside the project folder`
10611
10715
  );
10612
10716
  }
10613
- assertCompositionFileSize2(path, relative4(projectDir, path));
10717
+ assertCompositionFileSize2(path, relative5(projectDir, path));
10614
10718
  return readTextFile2(path);
10615
10719
  };
10616
10720
  const htmlPath = join23(projectDir, entryFile);
@@ -11178,7 +11282,7 @@ async function runProbeStage(input) {
11178
11282
  staticDedupMemo,
11179
11283
  compositionHash: computeCompositionObservabilityHash(compiled.html),
11180
11284
  deferStaticDedup: true,
11181
- onStaticDedupActivity: () => noteStaticDedupActivity(job)
11285
+ onStaticDedupActivity: () => noteCaptureActivity(job)
11182
11286
  };
11183
11287
  const PROBE_MAX_ATTEMPTS = 2;
11184
11288
  for (let attempt = 1; attempt <= PROBE_MAX_ATTEMPTS; attempt++) {
@@ -14375,7 +14479,7 @@ import {
14375
14479
  mkdirSync as mkdirSync11,
14376
14480
  readdirSync as readdirSync5,
14377
14481
  readFileSync as readFileSync9,
14378
- rmSync as rmSync11,
14482
+ rmSync as rmSync12,
14379
14483
  statSync as statSync9,
14380
14484
  writeFileSync as writeFileSync5
14381
14485
  } from "node:fs";
@@ -14514,7 +14618,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14514
14618
  fileSize
14515
14619
  };
14516
14620
  } finally {
14517
- rmSync11(input.palettePath, { force: true });
14621
+ rmSync12(input.palettePath, { force: true });
14518
14622
  }
14519
14623
  }
14520
14624
  function startEncodeProgress(job, stage, onProgress) {
@@ -15184,7 +15288,7 @@ function frameStallRule(job, totalFrames, probeStartupMs) {
15184
15288
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
15185
15289
  detail: () => describeWorkerPhases(job),
15186
15290
  attemptOpened: () => forgetWorkerPhases(job),
15187
- activity: () => staticDedupActivity(job)
15291
+ activity: () => captureActivity(job)
15188
15292
  };
15189
15293
  }
15190
15294
  function isRecoverableParallelCaptureError(error) {
@@ -15393,7 +15497,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15393
15497
  function createRenderJob(config) {
15394
15498
  return {
15395
15499
  ...referenceBackgroundResult(void 0),
15396
- id: randomUUID(),
15500
+ id: randomUUID3(),
15397
15501
  config: {
15398
15502
  ...config,
15399
15503
  fps: toFps2(config.fps),
@@ -15908,7 +16012,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15908
16012
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
15909
16013
  return;
15910
16014
  }
15911
- rmSync12(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
16015
+ rmSync13(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
15912
16016
  });
15913
16017
  try {
15914
16018
  await executeRenderPipeline({
@@ -16512,7 +16616,7 @@ async function executeRenderPipeline(input) {
16512
16616
  subTimelineWaitMemo,
16513
16617
  staticDedupMemo,
16514
16618
  compositionHash,
16515
- onStaticDedupActivity: () => noteStaticDedupActivity(job),
16619
+ onStaticDedupActivity: () => noteCaptureActivity(job),
16516
16620
  // Probe-resolved duration: drawElement self-verification derives its
16517
16621
  // sample frame indices from this so they land inside the drained range.
16518
16622
  compositionDurationSeconds: job.duration,
@@ -17376,7 +17480,7 @@ async function executeRenderPipeline(input) {
17376
17480
  segmentDir
17377
17481
  });
17378
17482
  }
17379
- if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
17483
+ if (completedSegments.size === 0) rmSync13(segmentDir, { recursive: true, force: true });
17380
17484
  const invokeSegmented = () => {
17381
17485
  if (capturePlan.kind !== "sdr_segmented") {
17382
17486
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17469,7 +17573,7 @@ async function executeRenderPipeline(input) {
17469
17573
  probeSession = null;
17470
17574
  await closeOrphanedProbeForRetry(orphaned, closeCaptureSession8, log, "segmented");
17471
17575
  }
17472
- rmSync12(segmentDir, { recursive: true, force: true });
17576
+ rmSync13(segmentDir, { recursive: true, force: true });
17473
17577
  completedSegments = /* @__PURE__ */ new Set();
17474
17578
  segmentManifest = emptySegmentManifest();
17475
17579
  dedupPerfs.length = 0;
@@ -17508,7 +17612,7 @@ async function executeRenderPipeline(input) {
17508
17612
  );
17509
17613
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
17510
17614
  if (job.config.keepSegments !== true) {
17511
- rmSync12(segmentDir, { recursive: true, force: true });
17615
+ rmSync13(segmentDir, { recursive: true, force: true });
17512
17616
  }
17513
17617
  } else {
17514
17618
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -17785,7 +17889,7 @@ async function executeRenderPipeline(input) {
17785
17889
  "capture_disk",
17786
17890
  "drawElement capture failed; retrying with a fresh screenshot session"
17787
17891
  );
17788
- rmSync12(framesDir, { recursive: true, force: true });
17892
+ rmSync13(framesDir, { recursive: true, force: true });
17789
17893
  mkdirSync12(framesDir, { recursive: true });
17790
17894
  resetCaptureAttemptProgress(job);
17791
17895
  dedupPerfs.length = 0;
@@ -18098,7 +18202,7 @@ import {
18098
18202
  closeSync as closeSync6,
18099
18203
  constants as constants4
18100
18204
  } from "node:fs";
18101
- 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";
18102
18206
  import { fileURLToPath as fileURLToPath6 } from "node:url";
18103
18207
  import { Worker as Worker3 } from "node:worker_threads";
18104
18208
  function isStringRecord(value) {
@@ -18144,8 +18248,8 @@ function readEntryHtml(filePath) {
18144
18248
  }
18145
18249
  }
18146
18250
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
18147
- const entryRelativePath = relative5(absProjectDir, absoluteEntryPath);
18148
- 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);
18149
18253
  }
18150
18254
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
18151
18255
  const absProjectDir = resolve10(projectDir);
@@ -18428,7 +18532,7 @@ import {
18428
18532
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
18429
18533
  } from "@hyperframes/engine";
18430
18534
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
18431
- 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";
18432
18536
  import {
18433
18537
  fpsToNumber as fpsToNumber9,
18434
18538
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -18998,16 +19102,31 @@ function buildRenderJobConfig(input, outputPath, log) {
18998
19102
  }
18999
19103
  function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
19000
19104
  const { input, cleanupProjectDir } = prepared;
19001
- 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);
19002
19109
  if (confineOutput) {
19003
- mkdirSync13(rendersDir, { recursive: true });
19110
+ mkdirSync13(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
19004
19111
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
19005
19112
  throw new Error("outputPath must be inside the renders directory");
19006
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
+ }
19007
19120
  }
19008
- const outputDir = dirname19(absoluteOutputPath);
19009
- if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
19010
- 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;
19011
19130
  }
19012
19131
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
19013
19132
  try {
@@ -19147,35 +19266,74 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
19147
19266
  return fallbackPath;
19148
19267
  }
19149
19268
  }
19150
- function createArtifactStore(ttlMs) {
19269
+ function createArtifactStore(ttlMs, log) {
19151
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
+ };
19152
19286
  const cleanup = setInterval(() => {
19153
19287
  const now = Date.now();
19154
19288
  for (const [token, artifact] of artifacts.entries()) {
19155
- if (artifact.expiresAtMs <= now) {
19156
- artifacts.delete(token);
19157
- }
19289
+ if (artifact.expiresAtMs <= now) forget(token);
19158
19290
  }
19159
19291
  }, 6e4);
19160
19292
  cleanup.unref();
19161
19293
  return {
19162
- 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);
19163
19298
  const token = crypto.randomUUID();
19164
- artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
19299
+ artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
19165
19300
  return token;
19166
19301
  },
19167
19302
  get(token) {
19168
- 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;
19169
19309
  },
19170
- delete(token) {
19171
- artifacts.delete(token);
19172
- }
19310
+ forget
19173
19311
  };
19174
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
+ }
19175
19333
  function cleanupTempDir(dir, log) {
19176
19334
  if (!dir) return;
19177
19335
  try {
19178
- rmSync13(dir, { recursive: true, force: true });
19336
+ rmSync14(dir, { recursive: true, force: true });
19179
19337
  } catch (error) {
19180
19338
  log.warn("Failed to cleanup temp project dir", {
19181
19339
  cleanupProjectDir: dir,
@@ -19284,10 +19442,10 @@ function createRenderHandlers(options = {}) {
19284
19442
  const log = options.logger ?? defaultLogger;
19285
19443
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
19286
19444
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
19287
- 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-"));
19288
19446
  const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
19289
19447
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
19290
- const store = createArtifactStore(artifactTtlMs);
19448
+ const store = createArtifactStore(artifactTtlMs, log);
19291
19449
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
19292
19450
  const renderSemaphore = new Semaphore(maxConcurrentRenders);
19293
19451
  const startTime = Date.now();
@@ -19352,7 +19510,7 @@ function createRenderHandlers(options = {}) {
19352
19510
  if ("error" in preparedJob) {
19353
19511
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
19354
19512
  }
19355
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19513
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19356
19514
  const release = await renderSemaphore.acquire();
19357
19515
  log.info("render started", {
19358
19516
  requestId,
@@ -19369,7 +19527,7 @@ function createRenderHandlers(options = {}) {
19369
19527
  );
19370
19528
  const fileSize = outputFileSize(absoluteOutputPath);
19371
19529
  const durationMs = Date.now() - t0;
19372
- const outputToken = store.register(absoluteOutputPath);
19530
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19373
19531
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19374
19532
  log.info("render completed", {
19375
19533
  requestId,
@@ -19441,7 +19599,7 @@ function createRenderHandlers(options = {}) {
19441
19599
  });
19442
19600
  return;
19443
19601
  }
19444
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19602
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19445
19603
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
19446
19604
  const abortController = new AbortController();
19447
19605
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
@@ -19471,7 +19629,7 @@ function createRenderHandlers(options = {}) {
19471
19629
  ).finally(release);
19472
19630
  clearInterval(keepalive);
19473
19631
  const fileSize = outputFileSize(absoluteOutputPath);
19474
- const outputToken = store.register(absoluteOutputPath);
19632
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19475
19633
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19476
19634
  log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
19477
19635
  await stream.writeSSE({
@@ -19514,15 +19672,18 @@ function createRenderHandlers(options = {}) {
19514
19672
  if (!artifact) {
19515
19673
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
19516
19674
  }
19517
- if (!existsSync26(artifact.path)) {
19518
- store.delete(token);
19675
+ const fd = openArtifact(artifact);
19676
+ if (fd === void 0) {
19677
+ store.forget(token);
19519
19678
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
19520
19679
  }
19521
- const stats = statSync12(artifact.path);
19522
- 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, {
19523
19684
  headers: {
19524
19685
  "content-type": "video/mp4",
19525
- "content-length": String(stats.size),
19686
+ "content-length": String(size),
19526
19687
  "cache-control": "no-store"
19527
19688
  }
19528
19689
  });