@hyperframes/producer 0.9.88 → 0.9.90

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/README.md CHANGED
@@ -51,7 +51,7 @@ except `/health` then requires `Authorization: Bearer <token>`, and the server r
51
51
  start without one. A request's `projectDir` must resolve, symlinks included, inside
52
52
  `projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
53
53
  must stay inside that project, and `outputPath` must be inside `rendersDir`
54
- (`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set
54
+ (`PRODUCER_RENDERS_DIR`, default: a new private folder in the OS temp dir). `debug: true` is refused unless you set
55
55
  `allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and
56
56
  debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own
57
57
  trusted service, applies them only with `confineRequests: true`.
@@ -1,5 +1,14 @@
1
1
  // src/services/compileWorker.ts
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
+ import { onTrackedChildProcess } from "@hyperframes/engine";
4
+
5
+ // src/services/compileScratch.ts
6
+ import { basename } from "node:path";
7
+ function scratchOutputOf(spawnfile, args) {
8
+ const last = args.at(-1);
9
+ if (!/^ffmpeg(\.exe)?$/i.test(basename(spawnfile)) || !last) return void 0;
10
+ return /\.tmp-\d+-[\w-]+$/.test(basename(last)) ? last : void 0;
11
+ }
3
12
 
4
13
  // src/services/htmlCompiler.ts
5
14
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
@@ -18,7 +27,7 @@ import {
18
27
  } from "@hyperframes/parsers/css-url-scans";
19
28
  import { createHash as createHash3 } from "node:crypto";
20
29
  import { createReadStream, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync4 } from "fs";
21
- import { join as join5, dirname as dirname3, resolve as resolve3, basename as basename2, relative, sep as sep2 } from "path";
30
+ import { join as join5, dirname as dirname3, resolve as resolve3, basename as basename3, relative, sep as sep2 } from "path";
22
31
  import { parseHTML as parseHTML4 } from "linkedom";
23
32
 
24
33
  // src/services/bundledScripts.ts
@@ -290,7 +299,7 @@ import {
290
299
 
291
300
  // src/utils/paths.ts
292
301
  import {
293
- basename,
302
+ basename as basename2,
294
303
  join as join2,
295
304
  sep,
296
305
  resolve as nodeResolve,
@@ -544,7 +553,7 @@ import {
544
553
  } from "@hyperframes/core/fonts/embed";
545
554
 
546
555
  // src/services/animatedGifPrep.ts
547
- import { createHash } from "node:crypto";
556
+ import { createHash, randomUUID } from "node:crypto";
548
557
  import { copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, rmSync, statSync as statSync2 } from "node:fs";
549
558
  import { dirname, isAbsolute, join as join3, resolve } from "node:path";
550
559
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -642,6 +651,8 @@ function resolveLoop(metadata, override) {
642
651
  }
643
652
  var MAX_LOOP_ITERATIONS = 1e3;
644
653
  var MAX_PAD_SECONDS = 3600;
654
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
655
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
645
656
  function resolveCompositionDurationSeconds(document2) {
646
657
  let max = null;
647
658
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -684,7 +695,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
684
695
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
685
696
  }
686
697
  function buildAnimatedGifTranscodeArgs(input) {
687
- const args = ["-hide_banner", "-loglevel", "error"];
698
+ const args = [
699
+ "-hide_banner",
700
+ "-loglevel",
701
+ "error",
702
+ "-timelimit",
703
+ String(FFMPEG_SELF_CPU_SECONDS_CAP)
704
+ ];
688
705
  if (input.loopIterations > 1) {
689
706
  args.push("-stream_loop", String(input.loopIterations - 1));
690
707
  }
@@ -712,6 +729,8 @@ function buildAnimatedGifTranscodeArgs(input) {
712
729
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
713
730
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
714
731
  // extension ffmpeg cannot infer the container from.
732
+ "-fs",
733
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
715
734
  "-f",
716
735
  "webm",
717
736
  "-y",
@@ -719,10 +738,16 @@ function buildAnimatedGifTranscodeArgs(input) {
719
738
  );
720
739
  return args;
721
740
  }
741
+ function abortError() {
742
+ const error = new Error("Aborted");
743
+ error.name = "AbortError";
744
+ return error;
745
+ }
722
746
  async function runAnimatedGifTranscode(request) {
723
747
  const timeout = request.timeoutMs ?? 3e5;
724
- const result = await runFfmpeg(request.args, { timeout });
748
+ const result = await runFfmpeg(request.args, { timeout, signal: request.signal });
725
749
  if (result.success) return;
750
+ if (request.signal?.aborted) throw abortError();
726
751
  if (result.failureReason === "external_interruption") {
727
752
  throw encoderFailureError("Animated GIF transcode failed", {
728
753
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -742,7 +767,7 @@ async function ensurePreparedWebm(input) {
742
767
  mkdirSync(dirname(input.outputPath), { recursive: true });
743
768
  }
744
769
  if (!isUsableFile(input.cachePath)) {
745
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
770
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
746
771
  const args = buildAnimatedGifTranscodeArgs({
747
772
  inputPath: input.sourcePath,
748
773
  outputPath: tmpPath,
@@ -755,11 +780,15 @@ async function ensurePreparedWebm(input) {
755
780
  inputPath: input.sourcePath,
756
781
  outputPath: tmpPath,
757
782
  args,
758
- timeoutMs: input.timeoutMs
783
+ timeoutMs: input.timeoutMs,
784
+ signal: input.signal
759
785
  });
760
786
  if (!isUsableFile(tmpPath)) {
761
787
  throw new Error("Animated GIF transcode produced an empty output");
762
788
  }
789
+ if (statSync2(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
790
+ throw new Error("Animated GIF transcode reached its output size limit");
791
+ }
763
792
  if (!isUsableFile(input.cachePath)) {
764
793
  renameWithRetry(tmpPath, input.cachePath);
765
794
  } else {
@@ -859,6 +888,7 @@ async function prepareAnimatedGifInputs(html, options2) {
859
888
  loopIterations,
860
889
  padSeconds,
861
890
  timeoutMs: options2.timeoutMs,
891
+ signal: options2.signal,
862
892
  transcode: options2.transcode
863
893
  });
864
894
  const id = ensureElementId(img, document2, i);
@@ -883,7 +913,7 @@ async function prepareAnimatedGifInputs(html, options2) {
883
913
  }
884
914
 
885
915
  // src/services/heifImagePrep.ts
886
- import { createHash as createHash2 } from "node:crypto";
916
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
887
917
  import {
888
918
  closeSync,
889
919
  copyFileSync as copyFileSync2,
@@ -1029,6 +1059,13 @@ var HeifToolUnavailableError = class extends Error {
1029
1059
  this.name = "HeifToolUnavailableError";
1030
1060
  }
1031
1061
  };
1062
+ function abortError2() {
1063
+ const error = new Error("Aborted");
1064
+ error.name = "AbortError";
1065
+ return error;
1066
+ }
1067
+ var FFMPEG_SELF_CPU_SECONDS_CAP2 = 300;
1068
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP2 = 256 * 1024 * 1024;
1032
1069
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
1033
1070
  function isHeifBytes(head) {
1034
1071
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -1096,6 +1133,8 @@ async function convertHeifToJpeg(request) {
1096
1133
  "-hide_banner",
1097
1134
  "-loglevel",
1098
1135
  "error",
1136
+ "-timelimit",
1137
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
1099
1138
  ...urlInputArgs2(request.inputPath),
1100
1139
  "-i",
1101
1140
  request.inputPath,
@@ -1104,14 +1143,17 @@ async function convertHeifToJpeg(request) {
1104
1143
  "1",
1105
1144
  "-q:v",
1106
1145
  "2",
1146
+ "-fs",
1147
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
1107
1148
  "-f",
1108
1149
  "mjpeg",
1109
1150
  "-y",
1110
1151
  request.outputPath
1111
1152
  ],
1112
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
1153
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
1113
1154
  );
1114
1155
  if (!result.success) {
1156
+ if (request.signal?.aborted) throw abortError2();
1115
1157
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
1116
1158
  }
1117
1159
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -1145,7 +1187,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options2) {
1145
1187
  mkdirSync2(dirname2(cachePath), { recursive: true });
1146
1188
  mkdirSync2(dirname2(outputPath), { recursive: true });
1147
1189
  if (!isUsableFile2(cachePath)) {
1148
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
1190
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
1149
1191
  const inlinePath = `${tmpPath}.heic`;
1150
1192
  const inputPath = source.path ?? inlinePath;
1151
1193
  try {
@@ -1153,9 +1195,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options2) {
1153
1195
  await (options2.transcode ?? convertHeifToJpeg)({
1154
1196
  inputPath,
1155
1197
  outputPath: tmpPath,
1156
- timeoutMs: options2.timeoutMs
1198
+ timeoutMs: options2.timeoutMs,
1199
+ signal: options2.signal
1157
1200
  });
1158
1201
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
1202
+ if (statSync3(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP2) {
1203
+ throw new Error("conversion reached its output size limit");
1204
+ }
1159
1205
  renameWithRetry2(tmpPath, cachePath);
1160
1206
  } catch (error) {
1161
1207
  const reason = error instanceof Error ? error.message : String(error);
@@ -1266,6 +1312,7 @@ import {
1266
1312
  isNotImagePayload,
1267
1313
  isNotMediaPayload,
1268
1314
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
1315
+ isStructurallyIncompletePngError,
1269
1316
  playlistLeavesItsFolder,
1270
1317
  NotMediaPayloadError,
1271
1318
  probeMediaProfile,
@@ -2501,7 +2548,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
2501
2548
  const remoteMediaAssets = /* @__PURE__ */ new Map();
2502
2549
  const urlToRelPath = /* @__PURE__ */ new Map();
2503
2550
  for (const [url, absPath] of urlToLocal) {
2504
- const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename2(absPath)}`;
2551
+ const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename3(absPath)}`;
2505
2552
  remoteMediaAssets.set(relPath, absPath);
2506
2553
  urlToRelPath.set(url, relPath);
2507
2554
  }
@@ -2637,8 +2684,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
2637
2684
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
2638
2685
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
2639
2686
  if (fontFaceBlocks.length === 0) return;
2687
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
2640
2688
  const inlineStyle = `<style>/* Inlined external font stylesheet */
2641
- ${fontFaceBlocks.join("\n")}
2689
+ ${fontCssWithLtAsCssEscape}
2642
2690
  </style>`;
2643
2691
  try {
2644
2692
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -2721,7 +2769,16 @@ function localizeFontFaceUrls(html, downloadDir2, assets) {
2721
2769
  "Remote font download failed",
2722
2770
  "Localized remote font face(s)",
2723
2771
  assets,
2724
- (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
2772
+ (h, url, relPath) => replaceMatches(
2773
+ h,
2774
+ styleBlockMatches(h),
2775
+ (style, css) => replaceInner(
2776
+ style,
2777
+ css,
2778
+ "</style>".length,
2779
+ css.replaceAll(`url(${url})`, `url("${relPath}")`)
2780
+ )
2781
+ )
2725
2782
  );
2726
2783
  }
2727
2784
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
@@ -2901,7 +2958,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir2, htmlPath2, budget) {
2901
2958
  return document2.toString();
2902
2959
  }
2903
2960
  var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
2904
- var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
2961
+ var MEDIA_SRC_NON_URL_CHARS = /[\u0000-\u001f\u007f<>]/;
2905
2962
  function bindVariableMediaSources(html, variables, budget, log2) {
2906
2963
  if (!html.includes("data-var-src")) return html;
2907
2964
  const { document: document2 } = parseHTML4(html);
@@ -2916,7 +2973,7 @@ function bindVariableMediaSources(html, variables, budget, log2) {
2916
2973
  const bound = boundMediaSrc(el, values);
2917
2974
  if (bound === null) continue;
2918
2975
  const src = bound.trim();
2919
- if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
2976
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_NON_URL_CHARS.test(src)) {
2920
2977
  log2?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
2921
2978
  length: src.length
2922
2979
  });
@@ -2929,7 +2986,7 @@ function bindVariableMediaSources(html, variables, budget, log2) {
2929
2986
  }
2930
2987
  return changed ? document2.toString() : html;
2931
2988
  }
2932
- var entryFileName = (projectDir2, htmlPath2) => isPathInside(htmlPath2, projectDir2) ? relative(projectDir2, htmlPath2).split(sep2).join("/") : basename2(htmlPath2);
2989
+ var entryFileName = (projectDir2, htmlPath2) => isPathInside(htmlPath2, projectDir2) ? relative(projectDir2, htmlPath2).split(sep2).join("/") : basename3(htmlPath2);
2933
2990
  async function compileForRender(projectDir2, htmlPath2, downloadDir2, options2 = {}) {
2934
2991
  const assets = new AssetDownloads(options2.abortSignal);
2935
2992
  try {
@@ -2950,7 +3007,7 @@ async function compileWithAssets(projectDir2, htmlPath2, downloadDir2, options2,
2950
3007
  if (!COMPOSITION_FILE.test(htmlPath2)) {
2951
3008
  throw new Error(`Entry file ${htmlPath2} is not an .html file, so it is refused`);
2952
3009
  }
2953
- assertCompositionFileSize(htmlPath2, basename2(htmlPath2));
3010
+ assertCompositionFileSize(htmlPath2, basename3(htmlPath2));
2954
3011
  const budget = new CompositionExpansionBudget();
2955
3012
  const entryHtml = rebaseDirectEntryAssetPaths(
2956
3013
  readTextFile(htmlPath2),
@@ -3051,6 +3108,7 @@ async function compileWithAssets(projectDir2, htmlPath2, downloadDir2, options2,
3051
3108
  cacheDir: options2.animatedGifCacheDir,
3052
3109
  sourceAssets: remoteImageAssets,
3053
3110
  timeoutMs: options2.ffmpegProcessTimeout,
3111
+ signal: options2.abortSignal,
3054
3112
  allowOutsideFiles: assetRoot === void 0
3055
3113
  });
3056
3114
  if (preparedHeifImages.length > 0) {
@@ -3067,6 +3125,7 @@ async function compileWithAssets(projectDir2, htmlPath2, downloadDir2, options2,
3067
3125
  cacheDir: options2.animatedGifCacheDir,
3068
3126
  sourceAssets: gifSourceAssets,
3069
3127
  timeoutMs: options2.ffmpegProcessTimeout,
3128
+ signal: options2.abortSignal,
3070
3129
  allowOutsideFiles: assetRoot === void 0
3071
3130
  });
3072
3131
  if (preparedGifs.length > 0) {
@@ -3186,6 +3245,16 @@ parentPort?.on("message", (message) => {
3186
3245
  if (message?.type === "abort") controller.abort(new Error("compile stopped"));
3187
3246
  });
3188
3247
  parentPort?.unref();
3248
+ onTrackedChildProcess((proc) => {
3249
+ const { pid } = proc;
3250
+ if (pid === void 0) return;
3251
+ parentPort?.postMessage({
3252
+ type: "child",
3253
+ pid,
3254
+ output: scratchOutputOf(proc.spawnfile, proc.spawnargs)
3255
+ });
3256
+ proc.once("exit", () => parentPort?.postMessage({ type: "childExit", pid }));
3257
+ });
3189
3258
  try {
3190
3259
  const compiled = await compileForRender(projectDir, htmlPath, downloadDir, {
3191
3260
  ...options,