@hyperframes/producer 0.9.91 → 0.9.93

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
@@ -3056,6 +3056,7 @@ import {
3056
3056
  import { readSync as readSync2 } from "fs";
3057
3057
  import { join as join7 } from "path";
3058
3058
  import {
3059
+ TRANSITIONS,
3059
3060
  captureAlphaPng,
3060
3061
  applyDomLayerMask,
3061
3062
  removeDomLayerMask,
@@ -3092,6 +3093,31 @@ function isAffineMatrix(m) {
3092
3093
  function resolveBlitOpacity(opacity) {
3093
3094
  return opacity < OPAQUE_ALPHA_THRESHOLD ? opacity : void 0;
3094
3095
  }
3096
+ var isTime = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
3097
+ function sanitizeTransitionMeta(raw, warn) {
3098
+ if (!Array.isArray(raw)) return [];
3099
+ const kept = [];
3100
+ for (const [index, entry] of raw.entries()) {
3101
+ if (typeof entry !== "object" || entry === null || !isTime(entry.time) || !isTime(entry.duration) || typeof entry.fromScene !== "string" || typeof entry.toScene !== "string") {
3102
+ warn("[Render] Ignoring malformed shader transition entry", { index });
3103
+ continue;
3104
+ }
3105
+ const { shader } = entry;
3106
+ const known = typeof shader === "string" && Object.hasOwn(TRANSITIONS, shader);
3107
+ if (shader !== void 0 && !known) {
3108
+ warn("[Render] Unknown shader transition; using crossfade", { index });
3109
+ }
3110
+ kept.push({
3111
+ time: entry.time,
3112
+ duration: entry.duration,
3113
+ ease: typeof entry.ease === "string" ? entry.ease : "",
3114
+ fromScene: entry.fromScene,
3115
+ toScene: entry.toScene,
3116
+ ...known ? { shader } : {}
3117
+ });
3118
+ }
3119
+ return kept;
3120
+ }
3095
3121
  function cropRgb48le(src, srcW, srcH, cropX, cropY, cropW, cropH) {
3096
3122
  const dst = Buffer.alloc(cropW * cropH * RGB48_BYTES_PER_PIXEL);
3097
3123
  for (let row = 0; row < cropH; row++) {
@@ -5972,6 +5998,13 @@ function estimateMeasuredCaptureCostMultiplier(samples) {
5972
5998
  medianMs
5973
5999
  };
5974
6000
  }
6001
+ function shouldCalibrateSoftwareGpu(requestedMode, resolvedMode, hardware) {
6002
+ return requestedMode === "auto" && resolvedMode === "hardware" && hardware !== void 0 && hardware.multiplier > 1 && hardware.p95Ms !== void 0;
6003
+ }
6004
+ function pickAutoGpuModeFromCalibration(hardware, software) {
6005
+ if (hardware.p95Ms === void 0 || software?.p95Ms === void 0) return "hardware";
6006
+ return software.p95Ms < hardware.p95Ms ? "software" : "hardware";
6007
+ }
5975
6008
  function selectCaptureCalibrationFrames(totalFrames) {
5976
6009
  if (totalFrames <= 0) return [];
5977
6010
  const lastFrame = totalFrames - 1;
@@ -9491,7 +9524,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9491
9524
  }
9492
9525
  let result = html;
9493
9526
  for (const [url, relPath] of urlToRelPath) {
9494
- result = result.replaceAll(`"${url}"`, `"${relPath}"`).replaceAll(`'${url}'`, `'${relPath}'`);
9527
+ result = result.replaceAll(`"${url}"`, () => `"${relPath}"`).replaceAll(`'${url}'`, () => `'${relPath}'`);
9495
9528
  if (extraRewrite) result = extraRewrite(result, url, relPath);
9496
9529
  }
9497
9530
  defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
@@ -9546,7 +9579,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir, assets) {
9546
9579
  assets,
9547
9580
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
9548
9581
  // replaceAll; this handles the unquoted url(https://..) form.
9549
- (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
9582
+ (h, url, rel) => h.replaceAll(`url(${url})`, () => `url(${rel})`)
9550
9583
  );
9551
9584
  }
9552
9585
  function isGoogleFontsUrl(href) {
@@ -9716,7 +9749,7 @@ function localizeFontFaceUrls(html, downloadDir, assets) {
9716
9749
  style,
9717
9750
  css,
9718
9751
  "</style>".length,
9719
- css.replaceAll(`url(${url})`, `url("${relPath}")`)
9752
+ css.replaceAll(`url(${url})`, () => `url("${relPath}")`)
9720
9753
  )
9721
9754
  )
9722
9755
  );
@@ -13594,7 +13627,7 @@ function createHdrImageTransferCache(options = {}) {
13594
13627
  // src/services/render/stages/captureHdrSequentialLoop.ts
13595
13628
  import { join as join30 } from "node:path";
13596
13629
  import {
13597
- TRANSITIONS,
13630
+ TRANSITIONS as TRANSITIONS2,
13598
13631
  crossfade
13599
13632
  } from "@hyperframes/engine";
13600
13633
  async function runSequentialLayeredFrameLoop(input) {
@@ -13692,7 +13725,7 @@ async function runSequentialLayeredFrameLoop(input) {
13692
13725
  });
13693
13726
  }
13694
13727
  const shaderName = activeTransition.shader;
13695
- const transitionFn = shaderName ? TRANSITIONS[shaderName] ?? crossfade : crossfade;
13728
+ const transitionFn = shaderName ? TRANSITIONS2[shaderName] ?? crossfade : crossfade;
13696
13729
  transitionFn(
13697
13730
  transitionBuffers.bufferA,
13698
13731
  transitionBuffers.bufferB,
@@ -13751,7 +13784,7 @@ async function runSequentialLayeredFrameLoop(input) {
13751
13784
  // src/services/render/stages/captureHdrHybridLoop.ts
13752
13785
  import { join as join32 } from "node:path";
13753
13786
  import {
13754
- TRANSITIONS as TRANSITIONS2,
13787
+ TRANSITIONS as TRANSITIONS3,
13755
13788
  closeCaptureSession as closeCaptureSession6,
13756
13789
  createCaptureSession as createCaptureSession6,
13757
13790
  createFrameReorderBuffer as createFrameReorderBuffer2,
@@ -14036,6 +14069,15 @@ async function runHybridLayeredFrameLoop(input) {
14036
14069
  const workerRanges = distributeLayeredHybridFrameRanges(totalFrames, activeWorkerCount);
14037
14070
  let framesWritten = 0;
14038
14071
  const reorderBuffer = createFrameReorderBuffer2(0, totalFrames);
14072
+ let failure = null;
14073
+ const fail = (err) => {
14074
+ if (failure) return;
14075
+ failure = err instanceof Error ? err : new Error(String(err));
14076
+ reorderBuffer.abort(failure);
14077
+ };
14078
+ const throwIfFailed = () => {
14079
+ if (failure) throw failure;
14080
+ };
14039
14081
  const writeEncoded = async (frameIdx, buf) => {
14040
14082
  await reorderBuffer.waitForFrame(frameIdx);
14041
14083
  const writeStart = Date.now();
@@ -14062,103 +14104,108 @@ async function runHybridLayeredFrameLoop(input) {
14062
14104
  if (!session || !canvas || !range) return;
14063
14105
  const ringInFlight = ring ? ring.map(() => null) : [];
14064
14106
  let nextRingIdx = 0;
14065
- for (let i = range.start; i < range.end; i++) {
14066
- assertNotAborted();
14067
- const time = i * job.config.fps.den / job.config.fps.num;
14068
- const activeTransition = transitionFramesSet.has(i) ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) : void 0;
14069
- if (activeTransition && ring) {
14070
- const slot = nextRingIdx;
14071
- nextRingIdx = (nextRingIdx + 1) % TRANSITION_RING_DEPTH;
14072
- const prev = ringInFlight[slot];
14073
- if (prev) await prev;
14074
- const buffers = ring[slot];
14075
- if (!buffers) continue;
14076
- await captureTransitionFrameOnWorker({
14077
- session,
14078
- frameIdx: i,
14079
- time,
14080
- transition: activeTransition,
14081
- buffers,
14082
- nativeHdrIds,
14083
- nativeHdrImageIds,
14084
- sceneElements,
14085
- hdrCompositeCtx,
14086
- width,
14087
- height,
14088
- compositeTransfer,
14089
- hdrTargetTransfer,
14090
- hdrPerf,
14091
- log
14092
- });
14093
- const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (i - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
14094
- const frameIdx = i;
14095
- const shaderName = activeTransition.shader;
14096
- const dispatch = (async () => {
14097
- if (poolRef && shaderName) {
14098
- const blendStart = Date.now();
14099
- const result = await poolRef.run({
14100
- shader: shaderName,
14101
- bufferA: buffers.bufferA,
14102
- bufferB: buffers.bufferB,
14103
- output: buffers.output,
14104
- width,
14105
- height,
14106
- progress
14107
- });
14108
- buffers.bufferA = result.bufferA;
14109
- buffers.bufferB = result.bufferB;
14110
- buffers.output = result.output;
14111
- addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart);
14112
- } else {
14113
- const transitionFn = shaderName ? TRANSITIONS2[shaderName] ?? crossfade2 : crossfade2;
14114
- const blendStart = Date.now();
14115
- transitionFn(
14116
- buffers.bufferA,
14117
- buffers.bufferB,
14118
- buffers.output,
14119
- width,
14120
- height,
14121
- progress
14107
+ try {
14108
+ for (let i = range.start; i < range.end; i++) {
14109
+ throwIfFailed();
14110
+ assertNotAborted();
14111
+ const time = i * job.config.fps.den / job.config.fps.num;
14112
+ const activeTransition = transitionFramesSet.has(i) ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) : void 0;
14113
+ if (activeTransition && ring) {
14114
+ const slot = nextRingIdx;
14115
+ nextRingIdx = (nextRingIdx + 1) % TRANSITION_RING_DEPTH;
14116
+ const prev = ringInFlight[slot];
14117
+ if (prev) await prev;
14118
+ throwIfFailed();
14119
+ const buffers = ring[slot];
14120
+ if (!buffers) continue;
14121
+ await captureTransitionFrameOnWorker({
14122
+ session,
14123
+ frameIdx: i,
14124
+ time,
14125
+ transition: activeTransition,
14126
+ buffers,
14127
+ nativeHdrIds,
14128
+ nativeHdrImageIds,
14129
+ sceneElements,
14130
+ hdrCompositeCtx,
14131
+ width,
14132
+ height,
14133
+ compositeTransfer,
14134
+ hdrTargetTransfer,
14135
+ hdrPerf,
14136
+ log
14137
+ });
14138
+ const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (i - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
14139
+ const frameIdx = i;
14140
+ const shaderName = activeTransition.shader;
14141
+ const dispatch = (async () => {
14142
+ if (poolRef && shaderName) {
14143
+ const blendStart = Date.now();
14144
+ const result = await poolRef.run({
14145
+ shader: shaderName,
14146
+ bufferA: buffers.bufferA,
14147
+ bufferB: buffers.bufferB,
14148
+ output: buffers.output,
14149
+ width,
14150
+ height,
14151
+ progress
14152
+ });
14153
+ buffers.bufferA = result.bufferA;
14154
+ buffers.bufferB = result.bufferB;
14155
+ buffers.output = result.output;
14156
+ addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart);
14157
+ } else {
14158
+ const transitionFn = shaderName ? TRANSITIONS3[shaderName] ?? crossfade2 : crossfade2;
14159
+ const blendStart = Date.now();
14160
+ transitionFn(
14161
+ buffers.bufferA,
14162
+ buffers.bufferB,
14163
+ buffers.output,
14164
+ width,
14165
+ height,
14166
+ progress
14167
+ );
14168
+ addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart);
14169
+ }
14170
+ await writeEncoded(frameIdx, buffers.output);
14171
+ })();
14172
+ ringInFlight[slot] = dispatch.then(() => void 0, fail);
14173
+ } else {
14174
+ const stackingInfo = await seekInjectAndQueryStacking(
14175
+ session.page,
14176
+ time,
14177
+ session.onBeforeCapture,
14178
+ nativeHdrIds,
14179
+ hdrPerf,
14180
+ "frameSeekMs",
14181
+ "frameInjectMs",
14182
+ "stackingQueryMs"
14183
+ );
14184
+ canvas.fill(0);
14185
+ const wctx = { ...hdrCompositeCtx, domSession: session };
14186
+ await timeHdrPhaseAsync(
14187
+ hdrPerf,
14188
+ "normalCompositeMs",
14189
+ () => compositeHdrFrame(wctx, canvas, time, stackingInfo, void 0, i)
14190
+ );
14191
+ if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
14192
+ writeFileExclusiveSync(
14193
+ join32(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
14194
+ canvas
14122
14195
  );
14123
- addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart);
14124
14196
  }
14125
- await writeEncoded(frameIdx, buffers.output);
14126
- })();
14127
- ringInFlight[slot] = dispatch.catch((err) => {
14128
- throw err instanceof Error ? err : new Error(String(err));
14129
- });
14130
- } else {
14131
- const stackingInfo = await seekInjectAndQueryStacking(
14132
- session.page,
14133
- time,
14134
- session.onBeforeCapture,
14135
- nativeHdrIds,
14136
- hdrPerf,
14137
- "frameSeekMs",
14138
- "frameInjectMs",
14139
- "stackingQueryMs"
14140
- );
14141
- canvas.fill(0);
14142
- const wctx = { ...hdrCompositeCtx, domSession: session };
14143
- await timeHdrPhaseAsync(
14144
- hdrPerf,
14145
- "normalCompositeMs",
14146
- () => compositeHdrFrame(wctx, canvas, time, stackingInfo, void 0, i)
14147
- );
14148
- if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
14149
- writeFileExclusiveSync(
14150
- join32(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
14151
- canvas
14152
- );
14197
+ await writeEncoded(i, canvas);
14153
14198
  }
14154
- await writeEncoded(i, canvas);
14155
14199
  }
14200
+ } catch (err) {
14201
+ fail(err);
14202
+ } finally {
14203
+ await Promise.all(ringInFlight);
14156
14204
  }
14157
- for (const pending of ringInFlight) {
14158
- if (pending) await pending;
14159
- }
14205
+ throwIfFailed();
14160
14206
  };
14161
- await Promise.all(sessions.map((_, w) => workerTaskOf(w)));
14207
+ await Promise.allSettled(sessions.map((_, w) => workerTaskOf(w)));
14208
+ throwIfFailed();
14162
14209
  await reorderBuffer.waitForAllDone();
14163
14210
  } finally {
14164
14211
  for (const s of workerSessions) {
@@ -14250,23 +14297,27 @@ async function runCaptureHdrStage(input) {
14250
14297
  assertNotAborted();
14251
14298
  lastBrowserConsole = domSession.browserConsoleBuffer;
14252
14299
  await initTransparentBackground2(domSession.page, { clearCompositionRoot: true });
14253
- const transitionMeta = await domSession.page.evaluate(() => {
14254
- return window.__hf?.transitions ?? [];
14255
- });
14256
- const sceneElements = await domSession.page.evaluate(() => {
14257
- const scenes = document.querySelectorAll(".scene");
14258
- const map = {};
14259
- for (const scene of scenes) {
14260
- if (!scene.id) continue;
14261
- const ids = /* @__PURE__ */ new Set([scene.id]);
14262
- const els = scene.querySelectorAll("[id]");
14263
- for (const el of els) {
14264
- if (el.id) ids.add(el.id);
14300
+ const transitionMeta = sanitizeTransitionMeta(
14301
+ await domSession.page.evaluate(() => window.__hf?.transitions ?? []),
14302
+ (message, meta) => log.warn(message, meta)
14303
+ );
14304
+ const sceneElements = Object.assign(
14305
+ /* @__PURE__ */ Object.create(null),
14306
+ await domSession.page.evaluate(() => {
14307
+ const scenes = document.querySelectorAll(".scene");
14308
+ const map = {};
14309
+ for (const scene of scenes) {
14310
+ if (!scene.id) continue;
14311
+ const ids = /* @__PURE__ */ new Set([scene.id]);
14312
+ const els = scene.querySelectorAll("[id]");
14313
+ for (const el of els) {
14314
+ if (el.id) ids.add(el.id);
14315
+ }
14316
+ map[scene.id] = Array.from(ids);
14265
14317
  }
14266
- map[scene.id] = Array.from(ids);
14267
- }
14268
- return map;
14269
- });
14318
+ return map;
14319
+ })
14320
+ );
14270
14321
  const fpsDecimal = fpsToNumber7(job.config.fps);
14271
14322
  const transitionRanges = transitionMeta.map((t) => ({
14272
14323
  ...t,
@@ -15161,6 +15212,13 @@ var RenderCancelledError = class extends Error {
15161
15212
  this.reason = reason;
15162
15213
  }
15163
15214
  };
15215
+ var EscapedRejectionError = class extends Error {
15216
+ constructor(cause) {
15217
+ super(cause.message, { cause });
15218
+ Object.assign(this, cause);
15219
+ this.name = cause.name;
15220
+ }
15221
+ };
15164
15222
  function createRenderFileLogger(logPath, base = defaultLogger) {
15165
15223
  const write = (prefix, args) => {
15166
15224
  const ts = (/* @__PURE__ */ new Date()).toISOString();
@@ -16587,7 +16645,7 @@ async function executeRenderPipeline(input) {
16587
16645
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
16588
16646
  code: "start_browsers"
16589
16647
  });
16590
- const resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
16648
+ let resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
16591
16649
  chromePath: resolveHeadlessShellPath(cfg),
16592
16650
  browserTimeout: cfg.browserTimeout
16593
16651
  });
@@ -16900,6 +16958,16 @@ async function executeRenderPipeline(input) {
16900
16958
  "calibration"
16901
16959
  ) : void 0;
16902
16960
  let outcome;
16961
+ let softwareOutcome;
16962
+ const calibrationInput = {
16963
+ fileServer: activeFileServer,
16964
+ log,
16965
+ job,
16966
+ totalFrames,
16967
+ buildCaptureOptions: buildPrepCaptureOptions,
16968
+ createRenderVideoFrameInjector: calibrationFrames ? calibrationFrames.injector : createRenderVideoFrameInjector,
16969
+ assertNotAborted
16970
+ };
16903
16971
  try {
16904
16972
  outcome = await observeRenderStage(
16905
16973
  observability,
@@ -16912,19 +16980,34 @@ async function executeRenderPipeline(input) {
16912
16980
  // ts=1784019503.
16913
16981
  stagePhase: "calibrating"
16914
16982
  }),
16915
- () => runCaptureCalibration({
16916
- cfg: calibrationCaptureConfig(cfg),
16917
- fileServer: activeFileServer,
16918
- workDir,
16919
- log,
16920
- job,
16921
- totalFrames,
16922
- forceScreenshot: captureForceScreenshot,
16923
- probeSession,
16924
- buildCaptureOptions: buildPrepCaptureOptions,
16925
- createRenderVideoFrameInjector: calibrationFrames ? calibrationFrames.injector : createRenderVideoFrameInjector,
16926
- assertNotAborted
16927
- }),
16983
+ async () => {
16984
+ const result = await runCaptureCalibration({
16985
+ ...calibrationInput,
16986
+ cfg: calibrationCaptureConfig(cfg),
16987
+ workDir,
16988
+ forceScreenshot: captureForceScreenshot,
16989
+ probeSession
16990
+ });
16991
+ probeSession = result.probeSession;
16992
+ if (shouldCalibrateSoftwareGpu(
16993
+ cfg.browserGpuMode,
16994
+ resolvedBrowserGpuMode,
16995
+ result.calibration?.estimate
16996
+ )) {
16997
+ softwareOutcome = await runCaptureCalibration({
16998
+ ...calibrationInput,
16999
+ cfg: calibrationCaptureConfig({ ...cfg, browserGpuMode: "software" }),
17000
+ workDir: join35(workDir, "software-gpu"),
17001
+ forceScreenshot: applyConcreteGpuScreenshotClamp(
17002
+ captureForceScreenshot,
17003
+ "software",
17004
+ cfg
17005
+ ),
17006
+ probeSession: null
17007
+ });
17008
+ }
17009
+ return result;
17010
+ },
16928
17011
  { heartbeatMessage: "browser calibrating (frames not started)" }
16929
17012
  );
16930
17013
  } finally {
@@ -16935,15 +17018,41 @@ async function executeRenderPipeline(input) {
16935
17018
  calibrationEvaluateTimedOut = outcome.calibrationEvaluateTimedOut;
16936
17019
  captureForceScreenshot = outcome.forceScreenshot;
16937
17020
  updateCaptureObservability({ forceScreenshot: captureForceScreenshot });
16938
- probeSession = outcome.probeSession;
16939
17021
  if (outcome.lastBrowserConsole.length > 0) {
16940
17022
  lastBrowserConsole = outcome.lastBrowserConsole;
16941
17023
  }
17024
+ if (softwareOutcome && outcome.calibration && pickAutoGpuModeFromCalibration(
17025
+ outcome.calibration.estimate,
17026
+ softwareOutcome.calibration?.estimate
17027
+ ) === "software") {
17028
+ log.warn(
17029
+ "[Render] Auto GPU mode: software capture measured faster than the hardware GPU, rendering in software.",
17030
+ {
17031
+ hardwareP95Ms: outcome.calibration.estimate.p95Ms,
17032
+ softwareP95Ms: softwareOutcome.calibration?.estimate.p95Ms
17033
+ }
17034
+ );
17035
+ cfg.browserGpuMode = "software";
17036
+ resolvedBrowserGpuMode = "software";
17037
+ captureCalibration = softwareOutcome.calibration;
17038
+ captureForceScreenshot = softwareOutcome.forceScreenshot;
17039
+ if (probeSession) {
17040
+ lastBrowserConsole = probeSession.browserConsoleBuffer;
17041
+ await closeCaptureSession8(probeSession).catch(() => {
17042
+ });
17043
+ probeSession = null;
17044
+ }
17045
+ updateCaptureObservability({
17046
+ browserGpuMode: resolvedBrowserGpuMode,
17047
+ forceScreenshot: captureForceScreenshot
17048
+ });
17049
+ }
16942
17050
  observability.checkpoint("capture_calibration", "resolved", {
16943
17051
  forceScreenshot: captureForceScreenshot,
16944
- multiplier: outcome.calibration?.estimate.multiplier ?? null,
16945
- p95Ms: outcome.calibration?.estimate.p95Ms ?? null,
16946
- medianMs: outcome.calibration?.estimate.medianMs ?? null
17052
+ browserGpuMode: resolvedBrowserGpuMode,
17053
+ multiplier: captureCalibration?.estimate.multiplier ?? null,
17054
+ p95Ms: captureCalibration?.estimate.p95Ms ?? null,
17055
+ medianMs: captureCalibration?.estimate.medianMs ?? null
16947
17056
  });
16948
17057
  } else {
16949
17058
  observability.checkpoint("capture_calibration", "skipped", {
@@ -18125,11 +18234,12 @@ async function executeRenderPipeline(input) {
18125
18234
  framesRendered: job.framesRendered ?? 0,
18126
18235
  error: caught
18127
18236
  });
18237
+ const escapedRejection = executionSignal.reason instanceof EscapedRejectionError ? executionSignal.reason : void 0;
18128
18238
  const error = surfaceScriptFailure(
18129
- tooSlowError ?? audioFailure ?? pageNeverReady ?? caught,
18239
+ tooSlowError ?? audioFailure ?? escapedRejection ?? pageNeverReady ?? caught,
18130
18240
  job
18131
18241
  );
18132
- if (!tooSlowError && !audioFailure && (error instanceof RenderCancelledError || executionSignal.aborted)) {
18242
+ if (!tooSlowError && !audioFailure && !escapedRejection && (error instanceof RenderCancelledError || executionSignal.aborted)) {
18133
18243
  job.error = error instanceof Error ? error.message : "render_cancelled";
18134
18244
  updateJobStatus(job, "cancelled", "Render cancelled", job.progress, onProgress);
18135
18245
  await eventPublisher.flush();
@@ -23254,8 +23364,9 @@ import {
23254
23364
  rmSync as rmSync20,
23255
23365
  createReadStream as createReadStream6
23256
23366
  } from "node:fs";
23367
+ import { AsyncLocalStorage } from "node:async_hooks";
23257
23368
  import { basename as basename9, resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23258
- import { tmpdir as tmpdir6 } from "node:os";
23369
+ import { homedir, tmpdir as tmpdir6 } from "node:os";
23259
23370
  import { parseArgs } from "node:util";
23260
23371
  import { isIP } from "node:net";
23261
23372
  import crypto from "node:crypto";
@@ -24149,11 +24260,16 @@ function createRenderHandlers(options = {}) {
24149
24260
  quality: input.quality
24150
24261
  });
24151
24262
  try {
24152
- await executeRenderJob(
24153
- job,
24154
- input.projectDir,
24155
- absoluteOutputPath,
24156
- createBlockingProgressReporter(log, requestId)
24263
+ await runInRenderScope(
24264
+ requestId,
24265
+ new AbortController(),
24266
+ (signal) => executeRenderJob(
24267
+ job,
24268
+ input.projectDir,
24269
+ absoluteOutputPath,
24270
+ createBlockingProgressReporter(log, requestId),
24271
+ signal
24272
+ )
24157
24273
  );
24158
24274
  const fileSize = outputFileSize(absoluteOutputPath);
24159
24275
  const durationMs = Date.now() - t0;
@@ -24250,12 +24366,10 @@ function createRenderHandlers(options = {}) {
24250
24366
  }, SSE_KEEPALIVE_MS);
24251
24367
  const release = await renderSemaphore.acquire();
24252
24368
  try {
24253
- await executeRenderJob(
24254
- job,
24255
- input.projectDir,
24256
- absoluteOutputPath,
24257
- reportProgress,
24258
- abortController.signal
24369
+ await runInRenderScope(
24370
+ requestId,
24371
+ abortController,
24372
+ (signal) => executeRenderJob(job, input.projectDir, absoluteOutputPath, reportProgress, signal)
24259
24373
  ).finally(release);
24260
24374
  clearInterval(keepalive);
24261
24375
  const fileSize = outputFileSize(absoluteOutputPath);
@@ -24423,19 +24537,53 @@ function createProducerApp(options = {}) {
24423
24537
  app.get("/outputs/:token", handlers.outputs);
24424
24538
  return app;
24425
24539
  }
24426
- function startServer(options = {}) {
24427
- const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
24428
- const hostname2 = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
24429
- const log = options.logger ?? defaultLogger;
24430
- if (!isLoopbackHostname(hostname2) && !resolveAuthToken(options)) {
24540
+ var renderScope = new AsyncLocalStorage();
24541
+ function runInRenderScope(requestId, abortController, run) {
24542
+ const fail = (err) => abortController.abort(new EscapedRejectionError(err));
24543
+ return renderScope.run({ requestId, fail }, () => run(abortController.signal));
24544
+ }
24545
+ function onEscapedRejection(reason, log) {
24546
+ const err = reason instanceof Error ? reason : new Error(String(reason));
24547
+ const scope = renderScope.getStore();
24548
+ log.error("Unhandled promise rejection", {
24549
+ requestId: scope?.requestId ?? null,
24550
+ error: err.message,
24551
+ stack: err.stack
24552
+ });
24553
+ scope?.fail(err);
24554
+ }
24555
+ function serverAuth(options, hostname2, port) {
24556
+ const configured = resolveAuthToken(options);
24557
+ if (configured) return { token: configured };
24558
+ if (!isLoopbackHostname(hostname2)) {
24431
24559
  throw new Error(
24432
24560
  `Refusing to listen on ${hostname2} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`
24433
24561
  );
24434
24562
  }
24435
- const app = createProducerApp(options);
24563
+ const file = resolve13(
24564
+ options.authTokenFile?.trim() || process.env.PRODUCER_AUTH_TOKEN_FILE?.trim() || join52(homedir(), ".hyperframes", "producer", `${port}.token`)
24565
+ );
24566
+ const token = crypto.randomBytes(32).toString("base64url");
24567
+ mkdirSync21(dirname22(file), { recursive: true, mode: 448 });
24568
+ rmSync20(file, { force: true });
24569
+ writeFileSync13(file, `${token}
24570
+ `, { flag: "wx", mode: 384 });
24571
+ return { token, generatedFile: file };
24572
+ }
24573
+ function startServer(options = {}) {
24574
+ const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
24575
+ const hostname2 = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
24576
+ const log = options.logger ?? defaultLogger;
24577
+ const auth = serverAuth(options, hostname2, port);
24578
+ const app = createProducerApp({ ...options, authToken: auth.token });
24436
24579
  const server = serve2({ fetch: app.fetch, port, hostname: hostname2 }, (info) => {
24437
24580
  const address = info.family === "IPv6" ? `[${info.address}]` : info.address;
24438
24581
  log.info(`Listening on http://${address}:${info.port}`);
24582
+ if (auth.generatedFile) {
24583
+ log.info(
24584
+ `No auth token was set, so this run made one: send "Authorization: Bearer <token>" with the token in ${auth.generatedFile}`
24585
+ );
24586
+ }
24439
24587
  });
24440
24588
  server.setTimeout(0);
24441
24589
  server.requestTimeout = 0;
@@ -24446,6 +24594,7 @@ function startServer(options = {}) {
24446
24594
  });
24447
24595
  async function shutdown(signal) {
24448
24596
  log.info(`Received ${signal}, shutting down`);
24597
+ if (auth.generatedFile) rmSync20(auth.generatedFile, { force: true });
24449
24598
  const { drainBrowserPool } = await import("@hyperframes/engine");
24450
24599
  await drainBrowserPool().catch(() => {
24451
24600
  });
@@ -24467,6 +24616,7 @@ function startServer(options = {}) {
24467
24616
  }, 3e4).unref();
24468
24617
  }
24469
24618
  process.on("SIGTERM", () => shutdown("SIGTERM"));
24619
+ process.on("unhandledRejection", (reason) => onEscapedRejection(reason, log));
24470
24620
  process.on("SIGINT", () => shutdown("SIGINT"));
24471
24621
  return server;
24472
24622
  }