@hyperframes/producer 0.9.66 → 0.9.68

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,16 +18,16 @@ function requireOutputDimensions(expected, width, height) {
18
18
 
19
19
  // src/server.ts
20
20
  import {
21
- existsSync as existsSync25,
21
+ existsSync as existsSync26,
22
22
  mkdirSync as mkdirSync13,
23
- statSync as statSync13,
23
+ statSync as statSync12,
24
24
  mkdtempSync,
25
25
  writeFileSync as writeFileSync8,
26
26
  rmSync as rmSync13,
27
- createReadStream as createReadStream3
27
+ createReadStream as createReadStream4
28
28
  } from "node:fs";
29
- import { resolve as resolve10, dirname as dirname18, join as join37 } from "node:path";
30
- import { tmpdir as tmpdir3 } from "node:os";
29
+ import { resolve as resolve11, dirname as dirname18, join as join39 } from "node:path";
30
+ import { tmpdir as tmpdir4 } from "node:os";
31
31
  import { parseArgs } from "node:util";
32
32
  import { isIP } from "node:net";
33
33
  import crypto from "node:crypto";
@@ -44,16 +44,16 @@ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
44
44
  // src/services/renderOrchestrator.ts
45
45
  import { audioFailureDiagnostics as audioFailureDiagnostics2, usableCpuCount as usableCpuCount2 } from "@hyperframes/engine";
46
46
  import {
47
- existsSync as existsSync21,
47
+ existsSync as existsSync22,
48
48
  mkdirSync as mkdirSync12,
49
49
  readdirSync as readdirSync6,
50
50
  rmSync as rmSync12,
51
- statSync as statSync11,
51
+ statSync as statSync10,
52
52
  writeFileSync as writeFileSync7,
53
53
  copyFileSync as copyFileSync5,
54
54
  appendFileSync
55
55
  } from "fs";
56
- import { tmpdir as tmpdir2 } from "node:os";
56
+ import { tmpdir as tmpdir3 } from "node:os";
57
57
  import {
58
58
  chainCapture,
59
59
  fpsToNumber as fpsToNumber8,
@@ -395,7 +395,7 @@ import {
395
395
  referenceBackgroundResult,
396
396
  createReferenceBackgroundRecorder
397
397
  } from "@hyperframes/engine";
398
- import { join as join32, dirname as dirname14, resolve as resolve8 } from "path";
398
+ import { join as join34, dirname as dirname14, resolve as resolve9 } from "path";
399
399
  import { totalmem as totalmem2 } from "node:os";
400
400
  import { randomUUID } from "crypto";
401
401
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -1302,13 +1302,13 @@ function createFileServer(options) {
1302
1302
  if (!streamOwnsFd) closeSync(fd);
1303
1303
  }
1304
1304
  });
1305
- return new Promise((resolve11, reject) => {
1305
+ return new Promise((resolve12, reject) => {
1306
1306
  const connections = /* @__PURE__ */ new Set();
1307
1307
  const server = serve({ fetch: app.fetch, port, hostname: "127.0.0.1" }, (info) => {
1308
1308
  const bound = port === 0 ? settleOnBrowserSafePort(server, "127.0.0.1") : Promise.resolve(info.port);
1309
1309
  bound.then((boundPort) => {
1310
1310
  listeningPort = boundPort;
1311
- resolve11({
1311
+ resolve12({
1312
1312
  url: `http://localhost:${boundPort}`,
1313
1313
  port: boundPort,
1314
1314
  addPreHeadScript: (script) => {
@@ -1871,10 +1871,96 @@ function buildRenderErrorDetails(input) {
1871
1871
  perfStages: Object.keys(input.perfStages).length > 0 ? { ...input.perfStages } : void 0,
1872
1872
  hdrDiagnostics: input.hdrDiagnostics.videoExtractionFailures > 0 || input.hdrDiagnostics.imageDecodeFailures > 0 ? { ...input.hdrDiagnostics } : void 0,
1873
1873
  observability: input.observability,
1874
- subTimelineWait: input.subTimelineWait
1874
+ subTimelineWait: input.subTimelineWait,
1875
+ missingPath: input.missingPath
1875
1876
  };
1876
1877
  }
1877
1878
 
1879
+ // src/services/render/missingPath.ts
1880
+ import { existsSync as existsSync4, lstatSync, readlinkSync } from "node:fs";
1881
+ import { tmpdir } from "node:os";
1882
+ import { basename as basename3, join as join4, relative as relative2, resolve as resolve4, isAbsolute as isAbsolute2, sep as sep3 } from "node:path";
1883
+ import { errnoMissingPathOf } from "@hyperframes/core/missing-path";
1884
+ var SYNCED = /onedrive|dropbox|icloud|mobile documents|clouddocs|google ?drive|cloudstorage/i;
1885
+ var inside = (path, folder) => {
1886
+ const rel = relative2(resolve4(folder), resolve4(path));
1887
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
1888
+ };
1889
+ function lstatOrNull(path) {
1890
+ try {
1891
+ return lstatSync(path);
1892
+ } catch {
1893
+ return null;
1894
+ }
1895
+ }
1896
+ var ROOT_SCOPES = [
1897
+ ["tempRoot", "temp_root"],
1898
+ ["cacheDir", "cache_root"],
1899
+ ["workDir", "work_dir"]
1900
+ ];
1901
+ var NAME_SCOPES = [
1902
+ [/\.partial/, "cache_partial"],
1903
+ [/^hfcache-/, "cache_entry"],
1904
+ [/^hyperframes-extract-cache/, "cache_root"],
1905
+ [/^(hf-render-|work-[0-9a-f]{8}-)/, "work_dir"]
1906
+ ];
1907
+ function scopeOfGone(path, where, throughLink) {
1908
+ const root = ROOT_SCOPES.find(([key]) => {
1909
+ const dir = where[key];
1910
+ return !!dir && resolve4(path) === resolve4(dir);
1911
+ });
1912
+ if (root) return root[1];
1913
+ const name = basename3(path);
1914
+ return NAME_SCOPES.find(([pattern]) => pattern.test(name))?.[1] ?? (throughLink ? "link_target" : "other");
1915
+ }
1916
+ var MAX_LINK_HOPS = 4;
1917
+ function rootOf(path, where) {
1918
+ if (inside(path, where.tempRoot)) return "system_temp";
1919
+ if (where.cacheDir && inside(path, where.cacheDir)) return "cache_dir";
1920
+ return "other";
1921
+ }
1922
+ var ownerOf = (path, where) => [where.tempRoot, where.cacheDir, where.workDir].filter((root) => !!root && inside(path, root)).sort((a, b) => resolve4(a).length - resolve4(b).length)[0];
1923
+ var linkTarget = (link, folder) => resolve4(folder, readlinkSync(link).replace(/^\\\\\?\\/, ""));
1924
+ function goneAt(path, last, where, hops) {
1925
+ const scope = scopeOfGone(path, where, hops > 0);
1926
+ return last && scope === "other" ? "file" : scope;
1927
+ }
1928
+ function highestGone(path, where, hops = 0) {
1929
+ const root = ownerOf(path, where);
1930
+ if (!root || hops > MAX_LINK_HOPS) return "link_target";
1931
+ if (!existsSync4(root)) return scopeOfGone(root, where, hops > 0);
1932
+ const parts = relative2(resolve4(root), resolve4(path)).split(sep3).filter(Boolean);
1933
+ let at = resolve4(root);
1934
+ for (const [index, part] of parts.entries()) {
1935
+ const next = join4(at, part);
1936
+ const stat = lstatOrNull(next);
1937
+ if (!stat) return goneAt(next, index === parts.length - 1, where, hops);
1938
+ at = stat.isSymbolicLink() ? linkTarget(next, at) : next;
1939
+ const gone = at === next ? void 0 : highestGone(at, where, hops + 1);
1940
+ if (gone) return gone;
1941
+ }
1942
+ return void 0;
1943
+ }
1944
+ var isSpawnFailure = (error) => !!error?.syscall?.startsWith("spawn");
1945
+ function describeMissingPath(error, {
1946
+ cacheDir,
1947
+ workDir,
1948
+ tempRoot = tmpdir()
1949
+ } = {}) {
1950
+ try {
1951
+ const path = errnoMissingPathOf(error);
1952
+ if (!path || isSpawnFailure(error)) return void 0;
1953
+ const where = { tempRoot, cacheDir, workDir };
1954
+ return {
1955
+ scope: ownerOf(path, where) ? highestGone(path, where) ?? "other" : scopeOfGone(path, where, false),
1956
+ synced: SYNCED.test(path),
1957
+ root: rootOf(path, where)
1958
+ };
1959
+ } catch {
1960
+ return void 0;
1961
+ }
1962
+ }
1963
+
1878
1964
  // src/services/render/renderEventPublisher.ts
1879
1965
  import { cloneCaptureWarnings } from "@hyperframes/engine";
1880
1966
  var FLUSH_TIMEOUT_MS = 1e4;
@@ -1910,8 +1996,8 @@ var OrderedRenderEventPublisher = class {
1910
1996
  let timer;
1911
1997
  const drained = await Promise.race([
1912
1998
  this.tail.then(() => true),
1913
- new Promise((resolve11) => {
1914
- timer = setTimeout(() => resolve11(false), FLUSH_TIMEOUT_MS);
1999
+ new Promise((resolve12) => {
2000
+ timer = setTimeout(() => resolve12(false), FLUSH_TIMEOUT_MS);
1915
2001
  })
1916
2002
  ]);
1917
2003
  clearTimeout(timer);
@@ -2015,8 +2101,8 @@ var RenderExecutionContext = class {
2015
2101
  };
2016
2102
 
2017
2103
  // src/services/render/artifactTransaction.ts
2018
- import { closeSync as closeSync2, existsSync as existsSync5, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
2019
- import { basename as basename4, dirname as dirname4, extname as extname2, join as join5, resolve as resolve4 } from "node:path";
2104
+ import { closeSync as closeSync2, existsSync as existsSync6, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
2105
+ import { basename as basename5, dirname as dirname4, extname as extname2, join as join6, resolve as resolve5 } from "node:path";
2020
2106
  import { HLS_MASTER_PLAYLIST, HLS_VIDEO_PLAYLIST, renameWithRetry } from "@hyperframes/engine";
2021
2107
 
2022
2108
  // src/utils/ffprobe.ts
@@ -2028,16 +2114,16 @@ import {
2028
2114
 
2029
2115
  // src/services/render/renderDirOwner.ts
2030
2116
  import {
2031
- existsSync as existsSync4,
2032
- lstatSync,
2117
+ existsSync as existsSync5,
2118
+ lstatSync as lstatSync2,
2033
2119
  readFileSync as readFileSync2,
2034
2120
  readdirSync,
2035
- readlinkSync,
2121
+ readlinkSync as readlinkSync2,
2036
2122
  rmSync as rmSync2,
2037
2123
  writeFileSync as writeFileSync2
2038
2124
  } from "node:fs";
2039
2125
  import { hostname, uptime } from "node:os";
2040
- import { basename as basename3, dirname as dirname3, join as join4 } from "node:path";
2126
+ import { basename as basename4, dirname as dirname3, join as join5 } from "node:path";
2041
2127
  import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
2042
2128
  import { createStagingDir } from "@hyperframes/core/atomic-file";
2043
2129
  var OWNER_FILE = "owner.json";
@@ -2054,13 +2140,13 @@ function pidScope() {
2054
2140
  host: hostname(),
2055
2141
  // Without /proc (macOS, Windows) the boot time, to the minute, stands in for the boot id.
2056
2142
  boot: attempt(() => readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim()) ?? attempt(() => String(Math.round(Date.now() / 6e4 - uptime() / 60))),
2057
- pidns: attempt(() => readlinkSync("/proc/self/ns/pid"))
2143
+ pidns: attempt(() => readlinkSync2("/proc/self/ns/pid"))
2058
2144
  };
2059
2145
  }
2060
2146
  function createOwnedRenderDir(prefix) {
2061
- const dir = createStagingDir(dirname3(prefix), basename3(prefix));
2147
+ const dir = createStagingDir(dirname3(prefix), basename4(prefix));
2062
2148
  const owner = { pid: process.pid, ...pidScope() };
2063
- writeFileSync2(join4(dir, OWNER_FILE), JSON.stringify(owner));
2149
+ writeFileSync2(join5(dir, OWNER_FILE), JSON.stringify(owner));
2064
2150
  return dir;
2065
2151
  }
2066
2152
  function alive(pid) {
@@ -2083,7 +2169,7 @@ function inThisPidScope(owner) {
2083
2169
  function ownerState(dir) {
2084
2170
  let owner;
2085
2171
  try {
2086
- owner = JSON.parse(readFileSync2(join4(dir, OWNER_FILE), "utf-8"));
2172
+ owner = JSON.parse(readFileSync2(join5(dir, OWNER_FILE), "utf-8"));
2087
2173
  } catch (error) {
2088
2174
  return error.code === "ENOENT" ? "none" : "unknown";
2089
2175
  }
@@ -2094,16 +2180,16 @@ function ownerState(dir) {
2094
2180
  return alive(pid) ? "live" : "gone";
2095
2181
  }
2096
2182
  function newestWriteMs(path) {
2097
- const stat = lstatSync(path);
2183
+ const stat = lstatSync2(path);
2098
2184
  if (!stat.isDirectory()) return stat.mtimeMs;
2099
2185
  return readdirSync(path).reduce(
2100
- (newest, name) => Math.max(newest, newestWriteMs(join4(path, name))),
2186
+ (newest, name) => Math.max(newest, newestWriteMs(join5(path, name))),
2101
2187
  stat.mtimeMs
2102
2188
  );
2103
2189
  }
2104
2190
  function isAbandoned(dir, ownerlessIdleMs, now) {
2105
2191
  try {
2106
- if (!lstatSync(dir).isDirectory() || existsSync4(join4(dir, TRANSACTION_BACKUP))) return false;
2192
+ if (!lstatSync2(dir).isDirectory() || existsSync5(join5(dir, TRANSACTION_BACKUP))) return false;
2107
2193
  const owner = ownerState(dir);
2108
2194
  if (owner === "gone") return true;
2109
2195
  return owner === "none" && ownerlessIdleMs !== void 0 && now - newestWriteMs(dir) >= ownerlessIdleMs;
@@ -2119,7 +2205,7 @@ function listAbandonedRenderDirs(parent, options = {}) {
2119
2205
  return [];
2120
2206
  }
2121
2207
  const now = Date.now();
2122
- return names.filter((name) => (options.names ?? RENDER_TEMP_DIR).test(name)).map((name) => join4(parent, name)).filter((dir) => isAbandoned(dir, options.ownerlessIdleMs, now));
2208
+ return names.filter((name) => (options.names ?? RENDER_TEMP_DIR).test(name)).map((name) => join5(parent, name)).filter((dir) => isAbandoned(dir, options.ownerlessIdleMs, now));
2123
2209
  }
2124
2210
  function createRenderWorkDir(prefix, outputDir) {
2125
2211
  for (const parent of /* @__PURE__ */ new Set([outputDir, dirname3(prefix)])) {
@@ -2135,7 +2221,7 @@ function createRenderWorkDir(prefix, outputDir) {
2135
2221
 
2136
2222
  // src/services/render/artifactTransaction.ts
2137
2223
  var defaultFileSystem = {
2138
- existsSync: existsSync5,
2224
+ existsSync: existsSync6,
2139
2225
  renameSync: (source, destination) => renameWithRetry(source, destination),
2140
2226
  rmSync: rmSync3
2141
2227
  };
@@ -2168,8 +2254,8 @@ function buildArtifactExpectation(input) {
2168
2254
  function createSiblingTransactionDirectory(destination) {
2169
2255
  const parent = dirname4(destination);
2170
2256
  const extension = extname2(destination);
2171
- const stem = extension ? basename4(destination, extension) : basename4(destination);
2172
- return createOwnedRenderDir(join5(parent, `.${stem}.hf-transaction-`));
2257
+ const stem = extension ? basename5(destination, extension) : basename5(destination);
2258
+ return createOwnedRenderDir(join6(parent, `.${stem}.hf-transaction-`));
2173
2259
  }
2174
2260
  function assertReadableNonEmptyFile(path) {
2175
2261
  const fd = openSync2(path, "r");
@@ -2187,7 +2273,7 @@ function collectDirectoryFiles(root) {
2187
2273
  const files = [];
2188
2274
  const visit = (directory) => {
2189
2275
  for (const entry of readdirSync2(directory, { withFileTypes: true })) {
2190
- const path = join5(directory, entry.name);
2276
+ const path = join6(directory, entry.name);
2191
2277
  if (entry.isDirectory()) visit(path);
2192
2278
  else if (entry.isFile()) files.push(path);
2193
2279
  }
@@ -2242,10 +2328,10 @@ var ArtifactTransaction = class {
2242
2328
  this.kind = kind;
2243
2329
  this.fileSystem = fileSystem;
2244
2330
  this.logger = logger;
2245
- this.destinationPath = resolve4(destinationPath);
2331
+ this.destinationPath = resolve5(destinationPath);
2246
2332
  this.transactionDirectory = createSiblingTransactionDirectory(this.destinationPath);
2247
- this.stagingPath = join5(this.transactionDirectory, basename4(this.destinationPath));
2248
- this.backupPath = join5(this.transactionDirectory, TRANSACTION_BACKUP);
2333
+ this.stagingPath = join6(this.transactionDirectory, basename5(this.destinationPath));
2334
+ this.backupPath = join6(this.transactionDirectory, TRANSACTION_BACKUP);
2249
2335
  this.durationProbe = durationProbe;
2250
2336
  }
2251
2337
  kind;
@@ -2288,19 +2374,19 @@ var ArtifactTransaction = class {
2288
2374
  */
2289
2375
  async assertDirectoryExpectation(expected, files) {
2290
2376
  for (const required of expected.requiredFiles ?? []) {
2291
- const path = join5(this.stagingPath, required);
2292
- if (!existsSync5(path)) {
2377
+ const path = join6(this.stagingPath, required);
2378
+ if (!existsSync6(path)) {
2293
2379
  throw new Error(`Render artifact directory is missing ${required}: ${this.stagingPath}`);
2294
2380
  }
2295
2381
  assertReadableNonEmptyFile(path);
2296
2382
  }
2297
2383
  if (expected.probeTarget !== void 0) {
2298
- await this.assertArtifactDuration(expected, join5(this.stagingPath, expected.probeTarget));
2384
+ await this.assertArtifactDuration(expected, join6(this.stagingPath, expected.probeTarget));
2299
2385
  return;
2300
2386
  }
2301
2387
  if (expected.expectedFrames === void 0) return;
2302
2388
  const frameCount = files.filter(
2303
- (file) => dirname4(file) === this.stagingPath && /^frame_\d+\.png$/.test(basename4(file))
2389
+ (file) => dirname4(file) === this.stagingPath && /^frame_\d+\.png$/.test(basename5(file))
2304
2390
  ).length;
2305
2391
  if (frameCount === 0) {
2306
2392
  throw new Error(
@@ -2538,8 +2624,8 @@ function replanAfterFailure(plan, failure) {
2538
2624
  }
2539
2625
 
2540
2626
  // src/services/render/stages/captureSegmentedStage.ts
2541
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2542
- import { join as join9 } from "node:path";
2627
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2628
+ import { join as join12 } from "node:path";
2543
2629
  import {
2544
2630
  captureFrameToBuffer as captureFrameToBuffer2,
2545
2631
  closeCaptureSession as closeCaptureSession2,
@@ -2960,7 +3046,7 @@ import {
2960
3046
 
2961
3047
  // src/services/hdrCompositor.ts
2962
3048
  import { readSync as readSync2 } from "fs";
2963
- import { join as join6 } from "path";
3049
+ import { join as join7 } from "path";
2964
3050
  import {
2965
3051
  captureAlphaPng,
2966
3052
  applyDomLayerMask,
@@ -3400,7 +3486,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
3400
3486
  if (shouldLog && debugDumpDir) {
3401
3487
  const after = countNonZeroRgb48(canvas);
3402
3488
  const dumpName = `frame_${String(debugFrameIndex).padStart(4, "0")}_layer_${String(layerIdx).padStart(2, "0")}_dom.png`;
3403
- const dumpPath = join6(debugDumpDir, dumpName);
3489
+ const dumpPath = join7(debugDumpDir, dumpName);
3404
3490
  writeFileExclusiveSync(dumpPath, domPng);
3405
3491
  log.info("[diag] dom layer blit", {
3406
3492
  frame: debugFrameIndex,
@@ -3455,7 +3541,7 @@ import { fpsToFfmpegArg, fpsToNumber as fpsToNumber3 } from "@hyperframes/core";
3455
3541
 
3456
3542
  // src/services/hdrFrameWindows.ts
3457
3543
  import { closeSync as closeSync3, constants as constants2, openSync as openSync3, rmSync as rmSync4 } from "node:fs";
3458
- import { join as join7 } from "node:path";
3544
+ import { join as join8 } from "node:path";
3459
3545
  function createHdrFrameWindows(opts) {
3460
3546
  const { dir, frameSize, windowFrames, maxResident, extract } = opts;
3461
3547
  let totalFrames = opts.totalFrames;
@@ -3479,7 +3565,7 @@ function createHdrFrameWindows(opts) {
3479
3565
  const firstFrame = index * windowFrames;
3480
3566
  const w = {
3481
3567
  firstFrame,
3482
- path: join7(dir, `window-${index}.rgb48le`),
3568
+ path: join8(dir, `window-${index}.rgb48le`),
3483
3569
  frames: 0,
3484
3570
  fd: -1,
3485
3571
  pins: 0,
@@ -4226,6 +4312,7 @@ function cleanupEndedHdrVideos(args) {
4226
4312
  }
4227
4313
 
4228
4314
  // src/services/render/segmentPlan.ts
4315
+ import { join as join9 } from "node:path";
4229
4316
  var DEFAULT_SEGMENT_FRAMES = 3e3;
4230
4317
  var MIN_SEGMENT_FRAMES = 30;
4231
4318
  function assertPositiveInteger(name, value) {
@@ -4246,6 +4333,9 @@ function planSegments(totalFrames, segmentFrames) {
4246
4333
  }
4247
4334
  return slices;
4248
4335
  }
4336
+ function segmentOutputPath(segmentDir, index) {
4337
+ return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
4338
+ }
4249
4339
  function resolveSegmentFrames(env) {
4250
4340
  const raw = env.HF_SEGMENT_FRAMES;
4251
4341
  if (raw === void 0 || raw.trim() === "") return DEFAULT_SEGMENT_FRAMES;
@@ -4263,6 +4353,144 @@ function createSegmentQueue(slices) {
4263
4353
  };
4264
4354
  }
4265
4355
 
4356
+ // src/services/render/segmentManifest.ts
4357
+ import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
4358
+ import {
4359
+ createReadStream as createReadStream2,
4360
+ existsSync as existsSync7,
4361
+ lstatSync as lstatSync3,
4362
+ mkdirSync as mkdirSync3,
4363
+ readFileSync as readFileSync4,
4364
+ writeFileSync as writeFileSync3
4365
+ } from "node:fs";
4366
+ import { join as join10 } from "node:path";
4367
+ import { previewToken } from "@hyperframes/core/preview-proof";
4368
+ import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
4369
+ var MANIFEST_FILENAME = "segments.json";
4370
+ function computeSegmentPlanHash(input) {
4371
+ const ordered = [
4372
+ input.compositionHash,
4373
+ input.cliVersion,
4374
+ String(input.totalFrames),
4375
+ String(input.segmentFrames),
4376
+ `${input.fps.num}/${input.fps.den}`,
4377
+ `${input.width}x${input.height}`,
4378
+ input.codec,
4379
+ input.preset,
4380
+ input.quality === void 0 ? "" : String(input.quality),
4381
+ input.bitrate ?? "",
4382
+ input.pixelFormat ?? "",
4383
+ input.imageFormat,
4384
+ input.useGpu ? "gpu" : "cpu",
4385
+ `${input.outputWidth}x${input.outputHeight}`,
4386
+ input.motionBlur,
4387
+ input.pageMotionBlur ?? "",
4388
+ input.captureQuality === void 0 ? "" : String(input.captureQuality)
4389
+ ];
4390
+ const delivery = [input.maxBitrate, input.bufferSize, input.gopSize].map((v) => v ?? "");
4391
+ if (delivery.some((v) => v !== "")) ordered.push(...delivery.map(String));
4392
+ return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
4393
+ }
4394
+ function segmentDirFor(projectRendersDir, planHash) {
4395
+ return join10(projectRendersDir, ".hf-segments", planHash);
4396
+ }
4397
+ function hasNumber(value, key) {
4398
+ return key in value && typeof Reflect.get(value, key) === "number";
4399
+ }
4400
+ function hasString(value, key) {
4401
+ return key in value && typeof Reflect.get(value, key) === "string";
4402
+ }
4403
+ function isEntry(value) {
4404
+ if (typeof value !== "object" || value === null) return false;
4405
+ return hasNumber(value, "index") && hasNumber(value, "startFrame") && hasNumber(value, "endFrame") && hasString(value, "path") && hasNumber(value, "bytes") && hasString(value, "sha256") && hasString(value, "completedAt");
4406
+ }
4407
+ function isManifest(value) {
4408
+ if (typeof value !== "object" || value === null) return false;
4409
+ const completed = Reflect.get(value, "completed");
4410
+ return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
4411
+ }
4412
+ function readSegmentManifest(segmentDir) {
4413
+ const path = join10(segmentDir, MANIFEST_FILENAME);
4414
+ if (!existsSync7(path)) return null;
4415
+ try {
4416
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
4417
+ return isManifest(parsed) ? parsed : null;
4418
+ } catch {
4419
+ return null;
4420
+ }
4421
+ }
4422
+ function segmentManifestKey(token = previewToken()) {
4423
+ return token ? createHmac("sha256", token).update("segment-manifest").digest() : null;
4424
+ }
4425
+ function manifestMac(manifest, key) {
4426
+ const signed = [
4427
+ manifest.planHash,
4428
+ manifest.totalFrames,
4429
+ manifest.segmentFrames,
4430
+ manifest.completed.map((e) => [e.index, e.startFrame, e.endFrame, e.bytes, e.sha256])
4431
+ ];
4432
+ return createHmac("sha256", key).update(JSON.stringify(signed)).digest("hex");
4433
+ }
4434
+ function signSegmentManifest(manifest, key) {
4435
+ const { version, planHash, totalFrames, segmentFrames, completed } = manifest;
4436
+ const unsigned = { version, planHash, totalFrames, segmentFrames, completed };
4437
+ return key ? { ...unsigned, mac: manifestMac(unsigned, key) } : unsigned;
4438
+ }
4439
+ function hasValidMac(manifest, key) {
4440
+ if (!key || typeof manifest.mac !== "string") return false;
4441
+ const expected = Buffer.from(manifestMac(manifest, key), "hex");
4442
+ const actual = Buffer.from(manifest.mac, "hex");
4443
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
4444
+ }
4445
+ async function hashSegmentFile(path) {
4446
+ const hash = createHash2("sha256");
4447
+ for await (const chunk of createReadStream2(path)) hash.update(chunk);
4448
+ return hash.digest("hex");
4449
+ }
4450
+ function writeSegmentManifest(segmentDir, manifest, key) {
4451
+ mkdirSync3(segmentDir, { recursive: true });
4452
+ const tmp = join10(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
4453
+ writeFileSync3(tmp, JSON.stringify(signSegmentManifest(manifest, key), null, 2), "utf-8");
4454
+ renameWithRetry2(tmp, join10(segmentDir, MANIFEST_FILENAME));
4455
+ }
4456
+ async function probeSegmentFrameCount(path, probe) {
4457
+ try {
4458
+ const meta = await probe(path);
4459
+ if (!Number.isFinite(meta.videoStreamDurationSeconds) || !Number.isFinite(meta.fps))
4460
+ return null;
4461
+ if (meta.fps <= 0) return null;
4462
+ return Math.round(meta.videoStreamDurationSeconds * meta.fps);
4463
+ } catch {
4464
+ return null;
4465
+ }
4466
+ }
4467
+ function plannedSlice(entry, plan) {
4468
+ const slice = Number.isInteger(entry.index) ? plan[entry.index] : void 0;
4469
+ if (!slice || slice.startFrame !== entry.startFrame || slice.endFrame !== entry.endFrame) {
4470
+ return void 0;
4471
+ }
4472
+ return slice;
4473
+ }
4474
+ function isPlainFileOfSize(path, bytes) {
4475
+ const stat = lstatSync3(path, { throwIfNoEntry: false });
4476
+ return stat !== void 0 && stat.isFile() && stat.size > 0 && stat.size === bytes;
4477
+ }
4478
+ async function validateCompletedSegments(manifest, check) {
4479
+ const ok = /* @__PURE__ */ new Set();
4480
+ if (manifest.planHash !== check.expectedHash || !hasValidMac(manifest, check.key)) return ok;
4481
+ for (const entry of manifest.completed) {
4482
+ const slice = plannedSlice(entry, check.plan);
4483
+ if (!slice) continue;
4484
+ const path = segmentOutputPath(check.segmentDir, slice.index);
4485
+ if (!isPlainFileOfSize(path, entry.bytes)) continue;
4486
+ if (await hashSegmentFile(path) !== entry.sha256) continue;
4487
+ const frames = await check.probeFrames(path);
4488
+ if (frames !== slice.endFrame - slice.startFrame) continue;
4489
+ ok.add(slice.index);
4490
+ }
4491
+ return ok;
4492
+ }
4493
+
4266
4494
  // src/services/render/segmentRecycle.ts
4267
4495
  var DEFAULT_SEGMENT_BROWSER_RECYCLE = 3;
4268
4496
  function resolveSegmentBrowserRecycle(env) {
@@ -4279,8 +4507,8 @@ function isTargetLossError(error) {
4279
4507
 
4280
4508
  // src/services/render/stages/captureStreamingStage.ts
4281
4509
  import { mkdtemp, writeFile } from "node:fs/promises";
4282
- import { tmpdir } from "node:os";
4283
- import { join as join8 } from "node:path";
4510
+ import { tmpdir as tmpdir2 } from "node:os";
4511
+ import { join as join11 } from "node:path";
4284
4512
  import {
4285
4513
  DrawElementVerificationError,
4286
4514
  captureFrameToBuffer,
@@ -4374,7 +4602,7 @@ var SequentialCaptureStallError = class extends Error {
4374
4602
  }
4375
4603
  };
4376
4604
  function raceAgainstStall(promise, deadlineMs, input, signal) {
4377
- return new Promise((resolve11, reject) => {
4605
+ return new Promise((resolve12, reject) => {
4378
4606
  const clock = createStallClock();
4379
4607
  const trip = () => reject(
4380
4608
  signal?.aborted ? new Error(
@@ -4399,7 +4627,7 @@ function raceAgainstStall(promise, deadlineMs, input, signal) {
4399
4627
  promise.then(
4400
4628
  (value) => {
4401
4629
  clearTimeout(timer);
4402
- resolve11(value);
4630
+ resolve12(value);
4403
4631
  },
4404
4632
  (error) => {
4405
4633
  clearTimeout(timer);
@@ -4503,11 +4731,11 @@ async function verifyDrawElementSample(session, idx, buf, ctx) {
4503
4731
  return;
4504
4732
  }
4505
4733
  if (db < verifyMinDb) {
4506
- const dumpDir = await mkdtemp(join8(tmpdir(), "hf-de-verify-fail-")).catch(() => null);
4734
+ const dumpDir = await mkdtemp(join11(tmpdir2(), "hf-de-verify-fail-")).catch(() => null);
4507
4735
  if (dumpDir) {
4508
4736
  await Promise.all([
4509
- writeFile(join8(dumpDir, `frame-${idx}-de.jpg`), buf),
4510
- writeFile(join8(dumpDir, `frame-${idx}-truth.jpg`), truth)
4737
+ writeFile(join11(dumpDir, `frame-${idx}-de.jpg`), buf),
4738
+ writeFile(join11(dumpDir, `frame-${idx}-truth.jpg`), truth)
4511
4739
  ]).catch(() => {
4512
4740
  });
4513
4741
  }
@@ -5077,9 +5305,6 @@ async function runCaptureStreamingStage(input) {
5077
5305
  }
5078
5306
 
5079
5307
  // src/services/render/stages/captureSegmentedStage.ts
5080
- function segmentOutputPath(segmentDir, index) {
5081
- return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
5082
- }
5083
5308
  function segmentEncoderOptions(base, segment) {
5084
5309
  return {
5085
5310
  ...base,
@@ -5177,7 +5402,8 @@ async function captureSegmentToEncoder(ctx, segment) {
5177
5402
  path: segmentPath,
5178
5403
  // Recorded so resume can prove the file on disk is the one that
5179
5404
  // finished; absent only in unit tests, whose fake encoder writes none.
5180
- bytes: existsSync6(segmentPath) ? statSync4(segmentPath).size : 0
5405
+ bytes: existsSync8(segmentPath) ? statSync4(segmentPath).size : 0,
5406
+ sha256: existsSync8(segmentPath) ? await hashSegmentFile(segmentPath) : ""
5181
5407
  });
5182
5408
  return encodeResult;
5183
5409
  } finally {
@@ -5411,8 +5637,8 @@ async function runCaptureSegmentedStage(input) {
5411
5637
  const { log, dedupPerfs, assertNotAborted } = input;
5412
5638
  const deps = { ...DEFAULT_DEPS, ...input.deps };
5413
5639
  const segments = planSegments(input.totalFrames, input.segmentFrames);
5414
- const segmentDir = input.segmentDir ?? join9(input.workDir, "segments");
5415
- mkdirSync3(segmentDir, { recursive: true });
5640
+ const segmentDir = input.segmentDir ?? join12(input.workDir, "segments");
5641
+ mkdirSync4(segmentDir, { recursive: true });
5416
5642
  const skip = input.completedSegments ?? /* @__PURE__ */ new Set();
5417
5643
  const pending = segments.filter((s) => !skip.has(s.index));
5418
5644
  for (const index of skip) log.info("[Render] segment skipped (resume)", { index });
@@ -5567,7 +5793,7 @@ function startRenderEtaGuard(options) {
5567
5793
  }
5568
5794
 
5569
5795
  // src/services/render/captureCost.ts
5570
- import { join as join10 } from "node:path";
5796
+ import { join as join13 } from "node:path";
5571
5797
  import { fpsToNumber as fpsToNumber4 } from "@hyperframes/core";
5572
5798
  import {
5573
5799
  calculateOptimalWorkers,
@@ -5820,7 +6046,7 @@ async function runCaptureCalibration(input) {
5820
6046
  });
5821
6047
  let calibration;
5822
6048
  try {
5823
- calibration = await runOneCalibration(join10(workDir, "capture-calibration"), calibrationCfg);
6049
+ calibration = await runOneCalibration(join13(workDir, "capture-calibration"), calibrationCfg);
5824
6050
  } catch (error) {
5825
6051
  const shouldFallback = !forceScreenshot && shouldFallbackToScreenshotAfterCalibrationError(error);
5826
6052
  if (!shouldFallback) {
@@ -5854,7 +6080,7 @@ async function runCaptureCalibration(input) {
5854
6080
  const screenshotCfg = createCaptureCalibrationConfig({ ...cfg, forceScreenshot: true });
5855
6081
  try {
5856
6082
  calibration = await runOneCalibration(
5857
- join10(workDir, "capture-calibration-screenshot"),
6083
+ join13(workDir, "capture-calibration-screenshot"),
5858
6084
  screenshotCfg
5859
6085
  );
5860
6086
  } catch (fallbackError) {
@@ -5918,8 +6144,8 @@ function checkPageNeverReady(input) {
5918
6144
  }
5919
6145
 
5920
6146
  // src/services/render/deferredVideoFrames.ts
5921
- import { mkdirSync as mkdirSync4, rmSync as rmSync7 } from "node:fs";
5922
- import { dirname as dirname5, join as join11 } from "node:path";
6147
+ import { mkdirSync as mkdirSync5, rmSync as rmSync7 } from "node:fs";
6148
+ import { dirname as dirname5, join as join14 } from "node:path";
5923
6149
  import {
5924
6150
  createFrameLookupTable,
5925
6151
  extractVideoFramesRange,
@@ -5964,7 +6190,7 @@ async function extractDeferredFrames(input) {
5964
6190
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5965
6191
  return Promise.all(
5966
6192
  deferred.map(async (video) => {
5967
- const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
6193
+ const outputDir = join14(input.outputRoot, mediaIdPathSegment2(video.videoId));
5968
6194
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5969
6195
  if (indexes.length === 0) {
5970
6196
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -6020,7 +6246,7 @@ async function extractAllDeferredFrames(extracted, input) {
6020
6246
  maxTransientRetries: input.maxTransientRetries,
6021
6247
  onRetry: () => {
6022
6248
  rmSync7(video.outputDir, { recursive: true, force: true });
6023
- mkdirSync4(video.outputDir, { recursive: true });
6249
+ mkdirSync5(video.outputDir, { recursive: true });
6024
6250
  }
6025
6251
  }
6026
6252
  );
@@ -6111,14 +6337,14 @@ async function measureLocalShownBoxes(page, videos, fps, duration, log) {
6111
6337
  }
6112
6338
 
6113
6339
  // src/services/render/segmentVideoFrames.ts
6114
- import { mkdirSync as mkdirSync5, rmSync as rmSync8 } from "node:fs";
6115
- import { join as join12 } from "node:path";
6340
+ import { mkdirSync as mkdirSync6, rmSync as rmSync8 } from "node:fs";
6341
+ import { join as join15 } from "node:path";
6116
6342
  import {
6117
6343
  createFrameLookupTable as createFrameLookupTable2,
6118
6344
  createVideoFrameInjector
6119
6345
  } from "@hyperframes/engine";
6120
6346
  function segmentFramesDir(rootDir, index) {
6121
- return join12(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6347
+ return join15(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6122
6348
  }
6123
6349
  function createSegmentVideoFrames(input) {
6124
6350
  const extractFrames = input.extractFrames ?? extractDeferredFrames;
@@ -6149,7 +6375,7 @@ function createSegmentVideoFrames(input) {
6149
6375
  let onDemandCalls = 0;
6150
6376
  const onDemandHook = () => Object.assign(
6151
6377
  async (page, time, heldVideoTime) => {
6152
- const dir = join12(
6378
+ const dir = join15(
6153
6379
  input.rootDir,
6154
6380
  "segment-frames",
6155
6381
  `on-demand_${String(onDemandCalls++).padStart(5, "0")}`
@@ -6166,11 +6392,11 @@ function createSegmentVideoFrames(input) {
6166
6392
  );
6167
6393
  return {
6168
6394
  async forFrames(frames, name) {
6169
- const dir = join12(input.rootDir, "segment-frames", name);
6395
+ const dir = join15(input.rootDir, "segment-frames", name);
6170
6396
  const release = () => rmSync8(dir, { recursive: true, force: true });
6171
6397
  try {
6172
6398
  release();
6173
- mkdirSync5(dir, { recursive: true });
6399
+ mkdirSync6(dir, { recursive: true });
6174
6400
  const table = await tableFor([...frames], dir);
6175
6401
  return { injector: () => createVideoFrameInjector(table, input.injectorOptions), release };
6176
6402
  } catch (error) {
@@ -6199,7 +6425,7 @@ function createSegmentVideoFrames(input) {
6199
6425
  folder = dir;
6200
6426
  try {
6201
6427
  rmSync8(dir, { recursive: true, force: true });
6202
- mkdirSync5(dir, { recursive: true });
6428
+ mkdirSync6(dir, { recursive: true });
6203
6429
  injector = await injectorFor(
6204
6430
  Array.from(
6205
6431
  { length: segment.endFrame - segment.startFrame },
@@ -6219,7 +6445,7 @@ function createSegmentVideoFrames(input) {
6219
6445
 
6220
6446
  // src/services/render/videoFrameWindow.ts
6221
6447
  import { readdirSync as readdirSync3, statSync as statSync5 } from "node:fs";
6222
- import { join as join13 } from "node:path";
6448
+ import { join as join16 } from "node:path";
6223
6449
  function shouldWindowVideoFrames(args) {
6224
6450
  return args.segmented && args.env.HF_VIDEO_FRAME_WINDOW?.trim().toLowerCase() === "true";
6225
6451
  }
@@ -6232,7 +6458,7 @@ function directoryBytes(path) {
6232
6458
  return 0;
6233
6459
  }
6234
6460
  for (const entry of entries) {
6235
- const child2 = join13(path, entry.name);
6461
+ const child2 = join16(path, entry.name);
6236
6462
  try {
6237
6463
  bytes += entry.isDirectory() ? directoryBytes(child2) : statSync5(child2).size;
6238
6464
  } catch {
@@ -6250,7 +6476,7 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6250
6476
  ...worker,
6251
6477
  async prepare(segment) {
6252
6478
  await worker.prepare(segment);
6253
- const held = directoryBytes(join13(rootDir, "segment-frames"));
6479
+ const held = directoryBytes(join16(rootDir, "segment-frames"));
6254
6480
  if (held > peak) {
6255
6481
  peak = held;
6256
6482
  onPeak(peak);
@@ -6261,95 +6487,6 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6261
6487
  };
6262
6488
  }
6263
6489
 
6264
- // src/services/render/segmentManifest.ts
6265
- import { createHash as createHash2 } from "node:crypto";
6266
- import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync4, statSync as statSync6, writeFileSync as writeFileSync3 } from "node:fs";
6267
- import { join as join14 } from "node:path";
6268
- import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
6269
- var MANIFEST_FILENAME = "segments.json";
6270
- function computeSegmentPlanHash(input) {
6271
- const ordered = [
6272
- input.compositionHash,
6273
- input.cliVersion,
6274
- String(input.totalFrames),
6275
- String(input.segmentFrames),
6276
- `${input.fps.num}/${input.fps.den}`,
6277
- `${input.width}x${input.height}`,
6278
- input.codec,
6279
- input.preset,
6280
- input.quality === void 0 ? "" : String(input.quality),
6281
- input.bitrate ?? "",
6282
- input.pixelFormat ?? "",
6283
- input.imageFormat,
6284
- input.useGpu ? "gpu" : "cpu",
6285
- `${input.outputWidth}x${input.outputHeight}`,
6286
- input.motionBlur,
6287
- input.pageMotionBlur ?? "",
6288
- input.captureQuality === void 0 ? "" : String(input.captureQuality)
6289
- ];
6290
- const delivery = [input.maxBitrate, input.bufferSize, input.gopSize].map((v) => v ?? "");
6291
- if (delivery.some((v) => v !== "")) ordered.push(...delivery.map(String));
6292
- return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
6293
- }
6294
- function segmentDirFor(projectRendersDir, planHash) {
6295
- return join14(projectRendersDir, ".hf-segments", planHash);
6296
- }
6297
- function hasNumber(value, key) {
6298
- return key in value && typeof Reflect.get(value, key) === "number";
6299
- }
6300
- function hasString(value, key) {
6301
- return key in value && typeof Reflect.get(value, key) === "string";
6302
- }
6303
- function isEntry(value) {
6304
- if (typeof value !== "object" || value === null) return false;
6305
- return hasNumber(value, "index") && hasNumber(value, "startFrame") && hasNumber(value, "endFrame") && hasString(value, "path") && hasNumber(value, "bytes") && hasString(value, "completedAt");
6306
- }
6307
- function isManifest(value) {
6308
- if (typeof value !== "object" || value === null) return false;
6309
- const completed = Reflect.get(value, "completed");
6310
- return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
6311
- }
6312
- function readSegmentManifest(segmentDir) {
6313
- const path = join14(segmentDir, MANIFEST_FILENAME);
6314
- if (!existsSync7(path)) return null;
6315
- try {
6316
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
6317
- return isManifest(parsed) ? parsed : null;
6318
- } catch {
6319
- return null;
6320
- }
6321
- }
6322
- function writeSegmentManifest(segmentDir, manifest) {
6323
- mkdirSync6(segmentDir, { recursive: true });
6324
- const tmp = join14(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
6325
- writeFileSync3(tmp, JSON.stringify(manifest, null, 2), "utf-8");
6326
- renameWithRetry2(tmp, join14(segmentDir, MANIFEST_FILENAME));
6327
- }
6328
- async function probeSegmentFrameCount(path, probe) {
6329
- try {
6330
- const meta = await probe(path);
6331
- if (!Number.isFinite(meta.videoStreamDurationSeconds) || !Number.isFinite(meta.fps))
6332
- return null;
6333
- if (meta.fps <= 0) return null;
6334
- return Math.round(meta.videoStreamDurationSeconds * meta.fps);
6335
- } catch {
6336
- return null;
6337
- }
6338
- }
6339
- async function validateCompletedSegments(manifest, expectedHash, probeFrames) {
6340
- const ok = /* @__PURE__ */ new Set();
6341
- if (manifest.planHash !== expectedHash) return ok;
6342
- for (const entry of manifest.completed) {
6343
- if (!existsSync7(entry.path)) continue;
6344
- const size = statSync6(entry.path).size;
6345
- if (size <= 0 || size !== entry.bytes) continue;
6346
- const frames = await probeFrames(entry.path);
6347
- if (frames !== entry.endFrame - entry.startFrame) continue;
6348
- ok.add(entry.index);
6349
- }
6350
- return ok;
6351
- }
6352
-
6353
6490
  // src/services/render/hdrMode.ts
6354
6491
  import {
6355
6492
  analyzeCompositionHdr,
@@ -6929,15 +7066,15 @@ function countAuthoredTimedClips(html) {
6929
7066
  }
6930
7067
 
6931
7068
  // src/services/render/stages/compileStage.ts
6932
- import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6933
- import { join as join20, relative as relative3 } from "node:path";
7069
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
7070
+ import { join as join22, relative as relative4 } from "node:path";
6934
7071
  import { privateCacheRoot } from "@hyperframes/engine";
6935
7072
  import { suggestMatchingPreset } from "@hyperframes/core";
6936
7073
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6937
7074
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6938
7075
 
6939
7076
  // src/services/compositionSizeLimit.ts
6940
- import { statSync as statSync7 } from "node:fs";
7077
+ import { statSync as statSync6 } from "node:fs";
6941
7078
  var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
6942
7079
  var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
6943
7080
  var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
@@ -6960,6 +7097,8 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6960
7097
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6961
7098
  );
6962
7099
  var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
7100
+ var REMOTE_SCRIPTS = "remote scripts";
7101
+ var REMOTE_STYLESHEETS = "remote stylesheets";
6963
7102
  function generatedTooLarge(file, bytes) {
6964
7103
  if (file === "composition variables") {
6965
7104
  return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
@@ -6967,6 +7106,9 @@ function generatedTooLarge(file, bytes) {
6967
7106
  if (file === "variable media sources") {
6968
7107
  return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
6969
7108
  }
7109
+ if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
7110
+ return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
7111
+ }
6970
7112
  return `Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ${megabytes(bytes)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`;
6971
7113
  }
6972
7114
  var CompositionExpansionBudget = class {
@@ -7008,7 +7150,7 @@ var CompositionExpansionBudget = class {
7008
7150
  function assertCompositionFileSize(path, file) {
7009
7151
  let bytes;
7010
7152
  try {
7011
- const stats = statSync7(path);
7153
+ const stats = statSync6(path);
7012
7154
  if (!stats.isFile()) return;
7013
7155
  bytes = stats.size;
7014
7156
  } catch {
@@ -7033,20 +7175,20 @@ import {
7033
7175
  stylesheetLinkMatches
7034
7176
  } from "@hyperframes/parsers/css-url-scans";
7035
7177
  import { createHash as createHash6 } from "node:crypto";
7036
- import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7037
- import { join as join19, dirname as dirname9, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
7178
+ import { createReadStream as createReadStream3, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7179
+ import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7038
7180
  import { parseHTML as parseHTML5 } from "linkedom";
7039
7181
 
7040
7182
  // src/services/bundledScripts.ts
7041
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7042
- import { join as join15 } from "node:path";
7183
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
7184
+ import { join as join17 } from "node:path";
7043
7185
  import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
7044
7186
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
7045
7187
  function bundledScript(url) {
7046
7188
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
7047
7189
  if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
7048
- const file = join15(dir, "gsap.min.js");
7049
- return existsSync8(file) ? readFileSync5(file) : null;
7190
+ const file = join17(dir, "gsap.min.js");
7191
+ return existsSync9(file) ? readFileSync5(file) : null;
7050
7192
  }
7051
7193
 
7052
7194
  // src/services/htmlCompiler.ts
@@ -7279,6 +7421,7 @@ function placeAudio(audio, window2) {
7279
7421
  import {
7280
7422
  analyzeKeyframeIntervals,
7281
7423
  assertMediaPayload,
7424
+ createConcurrencyLimit,
7282
7425
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
7283
7426
  NotMediaPayloadError as NotMediaPayloadError2,
7284
7427
  parseMasterFxChain,
@@ -7303,8 +7446,8 @@ import {
7303
7446
 
7304
7447
  // src/services/animatedGifPrep.ts
7305
7448
  import { createHash as createHash4 } from "node:crypto";
7306
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7307
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7449
+ import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7450
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7308
7451
  import { parseHTML as parseHTML3 } from "linkedom";
7309
7452
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
7310
7453
  import {
@@ -7349,20 +7492,20 @@ function resolveLocalImageSourcePath(src, options) {
7349
7492
  const { basePath } = splitUrlSuffix(trimmed);
7350
7493
  const normalizedBase = normalizeRelPath(basePath);
7351
7494
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
7352
- if (mapped && existsSync9(mapped)) return mapped;
7495
+ if (mapped && existsSync10(mapped)) return mapped;
7353
7496
  if (isHttpUrl(trimmed)) return null;
7354
7497
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
7355
7498
  const candidates = [
7356
- isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7357
- resolve5(options.downloadDir, normalizedBase)
7499
+ isAbsolute3(basePath) ? basePath : resolve6(options.projectDir, projectRelative),
7500
+ resolve6(options.downloadDir, normalizedBase)
7358
7501
  ];
7359
7502
  const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7360
7503
  const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7361
- return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7504
+ return candidates.find((candidate) => allowed(candidate) && existsSync10(candidate)) ?? null;
7362
7505
  }
7363
7506
  function isUsableFile(path) {
7364
7507
  try {
7365
- const stat = statSync8(path);
7508
+ const stat = statSync7(path);
7366
7509
  return stat.isFile() && stat.size > 0;
7367
7510
  } catch {
7368
7511
  return false;
@@ -7470,10 +7613,10 @@ async function runAnimatedGifTranscode(request) {
7470
7613
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
7471
7614
  }
7472
7615
  async function ensurePreparedWebm(input) {
7473
- if (!existsSync9(dirname6(input.cachePath))) {
7616
+ if (!existsSync10(dirname6(input.cachePath))) {
7474
7617
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
7475
7618
  }
7476
- if (!existsSync9(dirname6(input.outputPath))) {
7619
+ if (!existsSync10(dirname6(input.outputPath))) {
7477
7620
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7478
7621
  }
7479
7622
  if (!isUsableFile(input.cachePath)) {
@@ -7505,7 +7648,7 @@ async function ensurePreparedWebm(input) {
7505
7648
  throw error;
7506
7649
  }
7507
7650
  }
7508
- if (resolve5(input.outputPath) !== resolve5(input.cachePath) && !isUsableFile(input.outputPath)) {
7651
+ if (resolve6(input.outputPath) !== resolve6(input.cachePath) && !isUsableFile(input.outputPath)) {
7509
7652
  copyFileSync2(input.cachePath, input.outputPath);
7510
7653
  }
7511
7654
  }
@@ -7557,7 +7700,7 @@ function replaceImageWithVideo(input) {
7557
7700
  return video;
7558
7701
  }
7559
7702
  async function prepareAnimatedGifInputs(html, options) {
7560
- const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_GIF_SUBDIR);
7703
+ const outputDir = options.outputDir ?? join18(options.downloadDir, PREPARED_GIF_SUBDIR);
7561
7704
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
7562
7705
  const cacheDir = options.cacheDir ?? outputDir;
7563
7706
  const { document: document2 } = parseHTML3(html);
@@ -7584,8 +7727,8 @@ async function prepareAnimatedGifInputs(html, options) {
7584
7727
  );
7585
7728
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
7586
7729
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
7587
- const cachePath = join16(cacheDir, filename);
7588
- const outputPath = join16(outputDir, filename);
7730
+ const cachePath = join18(cacheDir, filename);
7731
+ const outputPath = join18(outputDir, filename);
7589
7732
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7590
7733
  await ensurePreparedWebm({
7591
7734
  sourcePath,
@@ -7627,10 +7770,10 @@ import {
7627
7770
  readFileSync as readFileSync7,
7628
7771
  readSync as readSync3,
7629
7772
  rmSync as rmSync10,
7630
- statSync as statSync9,
7773
+ statSync as statSync8,
7631
7774
  writeFileSync as writeFileSync4
7632
7775
  } from "node:fs";
7633
- import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
7776
+ import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
7634
7777
  import { parseHTML as parseHTML4 } from "linkedom";
7635
7778
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7636
7779
 
@@ -7699,10 +7842,10 @@ var Semaphore = class {
7699
7842
  this.active++;
7700
7843
  return () => this.release();
7701
7844
  }
7702
- return new Promise((resolve11) => {
7845
+ return new Promise((resolve12) => {
7703
7846
  this.queue.push(() => {
7704
7847
  this.active++;
7705
- resolve11(() => this.release());
7848
+ resolve12(() => this.release());
7706
7849
  });
7707
7850
  });
7708
7851
  }
@@ -7871,7 +8014,7 @@ function resolveImageSource(src, options) {
7871
8014
  }
7872
8015
  function isUsableFile2(path) {
7873
8016
  try {
7874
- return statSync9(path).size > 0;
8017
+ return statSync8(path).size > 0;
7875
8018
  } catch {
7876
8019
  return false;
7877
8020
  }
@@ -7900,12 +8043,12 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
7900
8043
  rmSync10(inlinePath, { force: true });
7901
8044
  }
7902
8045
  }
7903
- if (resolve6(outputPath) !== resolve6(cachePath) && !isUsableFile2(outputPath)) {
8046
+ if (resolve7(outputPath) !== resolve7(cachePath) && !isUsableFile2(outputPath)) {
7904
8047
  copyFileSync3(cachePath, outputPath);
7905
8048
  }
7906
8049
  }
7907
8050
  async function prepareHeifImageInputs(html, options) {
7908
- const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_HEIF_SUBDIR);
8051
+ const outputDir = options.outputDir ?? join19(options.downloadDir, PREPARED_HEIF_SUBDIR);
7909
8052
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
7910
8053
  const cacheDir = options.cacheDir ?? outputDir;
7911
8054
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -7926,7 +8069,7 @@ async function prepareHeifImageInputs(html, options) {
7926
8069
  await Promise.all(
7927
8070
  [...unique].map(
7928
8071
  ([filename, source]) => withMediaProbeSlot(
7929
- () => ensurePreparedJpeg(source, join17(cacheDir, filename), join17(outputDir, filename), options)
8072
+ () => ensurePreparedJpeg(source, join19(cacheDir, filename), join19(outputDir, filename), options)
7930
8073
  ).catch((error) => {
7931
8074
  if (!options.onFailure) throw error;
7932
8075
  failed.add(filename);
@@ -7938,8 +8081,8 @@ async function prepareHeifImageInputs(html, options) {
7938
8081
  if (failed.has(filename)) continue;
7939
8082
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7940
8083
  img.setAttribute("src", outputSrc);
7941
- preparedAssets.set(outputSrc, join17(outputDir, filename));
7942
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join17(outputDir, filename) });
8084
+ preparedAssets.set(outputSrc, join19(outputDir, filename));
8085
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join19(outputDir, filename) });
7943
8086
  }
7944
8087
  return { html: document2.toString(), preparedAssets, preparedImages };
7945
8088
  }
@@ -7949,8 +8092,8 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7949
8092
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7950
8093
 
7951
8094
  // src/services/assetMediaType.ts
7952
- import { existsSync as existsSync10 } from "node:fs";
7953
- import { dirname as dirname8, join as join18 } from "node:path";
8095
+ import { existsSync as existsSync11 } from "node:fs";
8096
+ import { dirname as dirname8, join as join20 } from "node:path";
7954
8097
  import {
7955
8098
  fingerprintElementId,
7956
8099
  isHttpUrl as isHttpUrl2,
@@ -8003,11 +8146,11 @@ function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
8003
8146
  ]);
8004
8147
  }
8005
8148
  function mediaAssetRoots(projectDir, compiledDir) {
8006
- return [projectDir, compiledDir, join18(dirname8(compiledDir), "downloads")];
8149
+ return [projectDir, compiledDir, join20(dirname8(compiledDir), "downloads")];
8007
8150
  }
8008
8151
  function dropMediaOutsideProject(input) {
8009
8152
  const { projectDir, workDir, composition, log } = input;
8010
- const compiledDir = join18(workDir, "compiled");
8153
+ const compiledDir = join20(workDir, "compiled");
8011
8154
  const roots = mediaAssetRoots(projectDir, compiledDir);
8012
8155
  const staysInside = ({ id, src }) => {
8013
8156
  if (!src || isHttpUrl2(src)) return true;
@@ -8062,7 +8205,7 @@ async function preflightCompositionAssetMediaTypes(input) {
8062
8205
  input.projectDir,
8063
8206
  input.compiledDir
8064
8207
  );
8065
- if (!existsSync10(resolvedPath)) continue;
8208
+ if (!existsSync11(resolvedPath)) continue;
8066
8209
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
8067
8210
  }
8068
8211
  const mismatches = [];
@@ -8153,7 +8296,7 @@ function normalizeCompositionSrcs(html, projectDir) {
8153
8296
  if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
8154
8297
  const file = resolveCompositionSrc(projectDir, value);
8155
8298
  if (file === null) return whole;
8156
- return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
8299
+ return `${name}${quote}${relative3(projectDir, file).split(sep4).join("/")}${quote}`;
8157
8300
  });
8158
8301
  }
8159
8302
  var COMPOSITION_FILE = /\.html?$/i;
@@ -8358,8 +8501,8 @@ function detectShaderTransitionUsage(html) {
8358
8501
  async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
8359
8502
  let filePath = src;
8360
8503
  if (isHttpUrl(src)) {
8361
- const remoteDir = join19(downloadDir, REMOTE_MEDIA_SUBDIR);
8362
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8504
+ const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8505
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8363
8506
  try {
8364
8507
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8365
8508
  onTelemetry: logRemoteDownloadTelemetry
@@ -8369,7 +8512,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8369
8512
  }
8370
8513
  } else {
8371
8514
  filePath = decodedUrlPath(src);
8372
- if (!filePath.startsWith("/")) filePath = join19(baseDir, filePath);
8515
+ if (!filePath.startsWith("/")) filePath = join21(baseDir, filePath);
8373
8516
  if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir, downloadDir])) {
8374
8517
  return { duration: null, resolvedPath: filePath };
8375
8518
  }
@@ -8378,7 +8521,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8378
8521
  return { duration: null, resolvedPath: filePath };
8379
8522
  }
8380
8523
  }
8381
- if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
8524
+ if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
8382
8525
  return { duration: null, resolvedPath: filePath };
8383
8526
  }
8384
8527
  const withSrcContext = (error) => {
@@ -8748,7 +8891,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8748
8891
  parseHostVariables: parseHostVariableValues,
8749
8892
  resolveFilePath: (srcPath) => {
8750
8893
  const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
8751
- return file && relative2(projectDir, file).split(sep3).join("/");
8894
+ return file && relative3(projectDir, file).split(sep4).join("/");
8752
8895
  },
8753
8896
  resolveHtml: (srcPath) => {
8754
8897
  const compHtml = resolveMountHtml(srcPath);
@@ -8912,7 +9055,8 @@ async function downloadScript(src, mirror) {
8912
9055
  }
8913
9056
  return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3 });
8914
9057
  }
8915
- async function inlineExternalScripts(html) {
9058
+ var MAX_CONCURRENT_SCRIPT_FETCHES = 4;
9059
+ async function inlineExternalScripts(html, budget = new CompositionExpansionBudget()) {
8916
9060
  const fullHtml = ensureFullDocument(html);
8917
9061
  const wrappedFragment = fullHtml !== html;
8918
9062
  const { document: document2 } = parseHTML5(fullHtml);
@@ -8926,20 +9070,52 @@ async function inlineExternalScripts(html) {
8926
9070
  }
8927
9071
  if (externalScripts.length === 0) return html;
8928
9072
  const mirror = operatorGsapMirror();
9073
+ const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
9074
+ const stop = new AbortController();
9075
+ const fail = (error) => {
9076
+ stop.abort(error);
9077
+ throw error;
9078
+ };
9079
+ const charge = (bytes) => {
9080
+ try {
9081
+ budget.chargeGenerated(REMOTE_SCRIPTS, bytes);
9082
+ } catch (error) {
9083
+ fail(error);
9084
+ }
9085
+ };
9086
+ const fetches = /* @__PURE__ */ new Map();
9087
+ const fetchOnce = (src) => {
9088
+ let bytes = fetches.get(src);
9089
+ if (!bytes) {
9090
+ bytes = limit(async () => {
9091
+ if (stop.signal.aborted) throw stop.signal.reason;
9092
+ const downloaded = await downloadScript(src, mirror);
9093
+ charge(downloaded.byteLength);
9094
+ return downloaded;
9095
+ }, stop.signal);
9096
+ fetches.set(src, bytes);
9097
+ }
9098
+ return bytes;
9099
+ };
9100
+ const placed = /* @__PURE__ */ new Set();
8929
9101
  const downloads = await Promise.allSettled(
8930
9102
  externalScripts.map(async ({ el, src }) => {
8931
9103
  const integrity = el.getAttribute("integrity") || "";
8932
- const bundled = bundledScript(src);
8933
- if (bundled && matchesScriptIntegrity(bundled, integrity)) {
8934
- return { src, text: new TextDecoder().decode(bundled) };
8935
- }
8936
- const bytes = await downloadScript(src, mirror);
8937
- if (!matchesScriptIntegrity(bytes, integrity)) {
8938
- throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
9104
+ let bytes = bundledScript(src);
9105
+ if (bytes && matchesScriptIntegrity(bytes, integrity)) {
9106
+ charge(bytes.byteLength);
9107
+ } else {
9108
+ bytes = await fetchOnce(src);
9109
+ if (!matchesScriptIntegrity(bytes, integrity)) {
9110
+ fail(new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`));
9111
+ }
9112
+ if (placed.has(src)) charge(bytes.byteLength);
9113
+ placed.add(src);
8939
9114
  }
8940
9115
  return { src, text: new TextDecoder().decode(bytes) };
8941
9116
  })
8942
9117
  );
9118
+ if (stop.signal.aborted) throw stop.signal.reason;
8943
9119
  for (let i = 0; i < downloads.length; i++) {
8944
9120
  const download = downloads[i];
8945
9121
  const { el, src } = externalScripts[i];
@@ -8966,18 +9142,18 @@ ${safeText}
8966
9142
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8967
9143
  }
8968
9144
  function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8969
- const absProjectDir = resolve7(projectDir);
9145
+ const absProjectDir = resolve8(projectDir);
8970
9146
  const externalAssets = /* @__PURE__ */ new Map();
8971
9147
  const leftOut = /* @__PURE__ */ new Set();
8972
9148
  function processPath(rawPath) {
8973
9149
  const trimmed = rawPath.trim();
8974
9150
  if (isNonRelativeUrl(trimmed)) return null;
8975
- const absPath = resolve7(absProjectDir, trimmed);
9151
+ const absPath = resolve8(absProjectDir, trimmed);
8976
9152
  if (isPathInside(absPath, absProjectDir)) {
8977
9153
  return null;
8978
9154
  }
8979
9155
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8980
- if (!onShare && !existsSync11(absPath)) return null;
9156
+ if (!onShare && !existsSync12(absPath)) return null;
8981
9157
  const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8982
9158
  if (refusal) {
8983
9159
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
@@ -9030,7 +9206,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9030
9206
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9031
9207
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9032
9208
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9033
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9209
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9034
9210
  const urlToLocal = /* @__PURE__ */ new Map();
9035
9211
  await Promise.all(
9036
9212
  [...urlSet].map(async (url) => {
@@ -9053,7 +9229,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9053
9229
  const remoteMediaAssets = /* @__PURE__ */ new Map();
9054
9230
  const urlToRelPath = /* @__PURE__ */ new Map();
9055
9231
  for (const [url, absPath] of urlToLocal) {
9056
- const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename5(absPath)}`;
9232
+ const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename6(absPath)}`;
9057
9233
  remoteMediaAssets.set(relPath, absPath);
9058
9234
  urlToRelPath.set(url, relPath);
9059
9235
  }
@@ -9070,7 +9246,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
9070
9246
  const localized = await downloadAndRewriteUrls(
9071
9247
  urlSet,
9072
9248
  html,
9073
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9249
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9074
9250
  "Remote media download failed",
9075
9251
  "Localized remote media source(s)"
9076
9252
  );
@@ -9093,7 +9269,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
9093
9269
  return downloadAndRewriteUrls(
9094
9270
  urlSet,
9095
9271
  html,
9096
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9272
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9097
9273
  "Remote image download failed",
9098
9274
  "Localized remote image source(s)"
9099
9275
  );
@@ -9106,7 +9282,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
9106
9282
  return downloadAndRewriteUrls(
9107
9283
  urlSet,
9108
9284
  html,
9109
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9285
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9110
9286
  "Remote background-image download failed",
9111
9287
  "Localized remote background-image(s)",
9112
9288
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -9163,48 +9339,50 @@ function matchingBraces(css) {
9163
9339
  }
9164
9340
  return closes;
9165
9341
  }
9166
- async function inlineExternalFontStylesheets(html) {
9167
- const hrefRe = /\bhref=["']([^"']+)["']/i;
9168
- const linkMatches = [];
9342
+ function remoteFontStylesheetHref(tag) {
9343
+ const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9344
+ if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9345
+ return href;
9346
+ }
9347
+ async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget()) {
9348
+ const hrefs = /* @__PURE__ */ new Set();
9169
9349
  for (const { parts } of stylesheetLinkMatches(html)) {
9170
- const tag = parts[0];
9171
- const hrefMatch = hrefRe.exec(tag);
9172
- if (!hrefMatch?.[1]) continue;
9173
- const href = hrefMatch[1];
9174
- if (!/^https?:\/\//i.test(href)) continue;
9175
- if (isGoogleFontsUrl(href)) continue;
9176
- linkMatches.push({ fullMatch: tag, href });
9177
- }
9178
- if (linkMatches.length === 0) return html;
9179
- const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9180
- const fetches = [];
9181
- for (let i = 0; i < linkMatches.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9182
- const batch = linkMatches.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9183
- const results = await Promise.all(
9184
- batch.map(async ({ fullMatch, href }) => {
9185
- const css = await fetchExternalStylesheetCss(href);
9186
- return { fullMatch, href, css };
9187
- })
9188
- );
9189
- fetches.push(...results);
9350
+ const href = remoteFontStylesheetHref(parts[0]);
9351
+ if (href) hrefs.add(href);
9190
9352
  }
9191
- let result = html;
9192
- for (const { fullMatch, href, css } of fetches) {
9193
- if (css === null) continue;
9194
- const fontFaceBlocks = extractFontFaceBlocks(css);
9195
- if (fontFaceBlocks.length === 0) continue;
9196
- const identity = safeDownloadUrlIdentity(href);
9197
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9353
+ if (hrefs.size === 0) return html;
9354
+ const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9355
+ const inlineByHref = /* @__PURE__ */ new Map();
9356
+ const unique = [...hrefs];
9357
+ for (let i = 0; i < unique.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9358
+ const batch = unique.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9359
+ const sheets = await Promise.all(batch.map(fetchExternalStylesheetCss));
9360
+ batch.forEach((href, index) => {
9361
+ const css = sheets[index];
9362
+ const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9363
+ if (fontFaceBlocks.length === 0) return;
9364
+ const inlineStyle = `<style>/* Inlined external font stylesheet */
9198
9365
  ${fontFaceBlocks.join("\n")}
9199
9366
  </style>`;
9200
- result = result.replace(fullMatch, inlineStyle);
9201
- defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9202
- count: fontFaceBlocks.length,
9203
- urlFingerprint: identity.urlFingerprint,
9204
- host: identity.host
9367
+ budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9368
+ inlineByHref.set(href, inlineStyle);
9369
+ const identity = safeDownloadUrlIdentity(href);
9370
+ defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9371
+ count: fontFaceBlocks.length,
9372
+ urlFingerprint: identity.urlFingerprint,
9373
+ host: identity.host
9374
+ });
9205
9375
  });
9206
9376
  }
9207
- return result;
9377
+ const placed = /* @__PURE__ */ new Set();
9378
+ return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9379
+ const href = remoteFontStylesheetHref(tag);
9380
+ const inlineStyle = href ? inlineByHref.get(href) : void 0;
9381
+ if (!href || !inlineStyle) return tag;
9382
+ if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9383
+ placed.add(href);
9384
+ return inlineStyle;
9385
+ });
9208
9386
  }
9209
9387
  function projectStylesheetFontFamilies(html, projectDir) {
9210
9388
  const families = [];
@@ -9213,14 +9391,14 @@ function projectStylesheetFontFamilies(html, projectDir) {
9213
9391
  } of stylesheetLinkMatches(html)) {
9214
9392
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9215
9393
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
9216
- const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9217
- if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
9394
+ const sheet = resolve8(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9395
+ if (!isPathInside(sheet, projectDir) || !existsSync12(sheet)) continue;
9218
9396
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
9219
9397
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
9220
9398
  const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
9221
9399
  const path = decodedUrlPath(url);
9222
- const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname9(sheet), path);
9223
- return isPathInside(file, projectDir) && existsSync11(file);
9400
+ const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname9(sheet), path);
9401
+ return isPathInside(file, projectDir) && existsSync12(file);
9224
9402
  });
9225
9403
  if (family && shipsFile) families.push(family);
9226
9404
  }
@@ -9257,7 +9435,7 @@ function localizeFontFaceUrls(html, downloadDir) {
9257
9435
  return downloadAndRewriteUrls(
9258
9436
  collectFontFaceUrls(html),
9259
9437
  html,
9260
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9438
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9261
9439
  "Remote font download failed",
9262
9440
  "Localized remote font face(s)",
9263
9441
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -9267,7 +9445,7 @@ var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
9267
9445
  async function readLocalFont(absPath) {
9268
9446
  const chunks = [];
9269
9447
  let totalBytes = 0;
9270
- for await (const chunk of createReadStream2(absPath)) {
9448
+ for await (const chunk of createReadStream3(absPath)) {
9271
9449
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
9272
9450
  totalBytes += buffer.length;
9273
9451
  if (totalBytes > MAX_LOCAL_FONT_DATA_URI_BYTES) {
@@ -9278,7 +9456,7 @@ async function readLocalFont(absPath) {
9278
9456
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9279
9457
  }
9280
9458
  async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9281
- const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9459
+ const absPath = localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath);
9282
9460
  if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9283
9461
  if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9284
9462
  return void 0;
@@ -9368,8 +9546,8 @@ function renderGsapDist() {
9368
9546
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9369
9547
  let gsapDist;
9370
9548
  const exists = (path) => {
9371
- const file = resolve7(projectDir, path);
9372
- return !namesAnotherNetworkRoot2(projectDir, file) && existsSync11(file);
9549
+ const file = resolve8(projectDir, path);
9550
+ return !namesAnotherNetworkRoot2(projectDir, file) && existsSync12(file);
9373
9551
  };
9374
9552
  return replaceGsapDistScripts(html, (full, prefix, src, file, suffix) => {
9375
9553
  if (/^https?:\/\//i.test(src)) return full;
@@ -9381,7 +9559,7 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9381
9559
  }
9382
9560
  function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9383
9561
  if (!isPathInside(htmlPath, projectDir)) return html;
9384
- const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9562
+ const entryPath = relative3(projectDir, htmlPath).replace(/\\/g, "/");
9385
9563
  if (!entryPath.includes("/")) return html;
9386
9564
  const { document: document2 } = parseHTML5(html);
9387
9565
  const assetExists = projectAssetExists(projectDir);
@@ -9441,7 +9619,7 @@ function bindVariableMediaSources(html, variables, budget, log) {
9441
9619
  }
9442
9620
  return changed ? document2.toString() : html;
9443
9621
  }
9444
- var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9622
+ var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative3(projectDir, htmlPath).split(sep4).join("/") : basename6(htmlPath);
9445
9623
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9446
9624
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9447
9625
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
@@ -9454,7 +9632,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9454
9632
  if (!COMPOSITION_FILE.test(htmlPath)) {
9455
9633
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9456
9634
  }
9457
- assertCompositionFileSize(htmlPath, basename5(htmlPath));
9635
+ assertCompositionFileSize(htmlPath, basename6(htmlPath));
9458
9636
  const budget = new CompositionExpansionBudget();
9459
9637
  const entryHtml = rebaseDirectEntryAssetPaths(
9460
9638
  readTextFile(htmlPath),
@@ -9506,7 +9684,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9506
9684
  const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
9507
9685
  const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
9508
9686
  const fontSheetHtml = await inlineExternalFontStylesheets(
9509
- promoteCssImportsToLinkTags(sanitizedHtml)
9687
+ promoteCssImportsToLinkTags(sanitizedHtml),
9688
+ budget
9510
9689
  );
9511
9690
  const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
9512
9691
  injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml))
@@ -9518,7 +9697,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9518
9697
  projectFontFamilies: projectStylesheetFontFamilies(fontSheetHtml, projectDir),
9519
9698
  abortSignal: options.abortSignal
9520
9699
  });
9521
- const assembledHtml = await inlineExternalScripts(coalescedHtml);
9700
+ const assembledHtml = await inlineExternalScripts(coalescedHtml, budget);
9522
9701
  const HF_POSITION_ATTRS = [
9523
9702
  'data-hf-studio-path-offset="true"',
9524
9703
  'data-hf-studio-box-size="true"',
@@ -9610,8 +9789,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9610
9789
  const advised = /* @__PURE__ */ new Set();
9611
9790
  for (const video of videos) {
9612
9791
  if (isHttpUrl(video.src)) continue;
9613
- const videoPath = resolve7(projectDir, video.src);
9614
- if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9792
+ const videoPath = resolve8(projectDir, video.src);
9793
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync12(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9615
9794
  continue;
9616
9795
  advised.add(videoPath);
9617
9796
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
@@ -10026,7 +10205,7 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
10026
10205
  function animatedGifCacheDir(extractCacheDir) {
10027
10206
  try {
10028
10207
  const root = extractCacheDir && privateCacheRoot(extractCacheDir);
10029
- return root ? join20(root, "animated-gif") : void 0;
10208
+ return root ? join22(root, "animated-gif") : void 0;
10030
10209
  } catch {
10031
10210
  return void 0;
10032
10211
  }
@@ -10048,17 +10227,17 @@ function resolveEntryHtmlPath(input) {
10048
10227
  const readEntry = (path) => {
10049
10228
  if (escapesAssetRoot(path, input.assetRoot)) {
10050
10229
  throw new Error(
10051
- `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
10230
+ `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10052
10231
  );
10053
10232
  }
10054
- assertCompositionFileSize(path, relative3(projectDir, path));
10233
+ assertCompositionFileSize(path, relative4(projectDir, path));
10055
10234
  return readTextFile2(path);
10056
10235
  };
10057
- const htmlPath = join20(projectDir, entryFile);
10236
+ const htmlPath = join22(projectDir, entryFile);
10058
10237
  const rawEntry = readEntry(htmlPath);
10059
10238
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
10060
- const projectIndexPath = join20(projectDir, "index.html");
10061
- if (!existsSync12(projectIndexPath)) {
10239
+ const projectIndexPath = join22(projectDir, "index.html");
10240
+ if (!existsSync13(projectIndexPath)) {
10062
10241
  throw new Error(
10063
10242
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
10064
10243
  );
@@ -10073,7 +10252,7 @@ function resolveEntryHtmlPath(input) {
10073
10252
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
10074
10253
  );
10075
10254
  }
10076
- const wrapperPath = join20(workDir, "standalone-entry.html");
10255
+ const wrapperPath = join22(workDir, "standalone-entry.html");
10077
10256
  writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
10078
10257
  log.info("Extracted standalone entry from index.html host context", { entryFile });
10079
10258
  return wrapperPath;
@@ -10103,7 +10282,7 @@ async function runCompileStage(input) {
10103
10282
  const assetRoot = job.config.allowOutsideProjectAssets ? void 0 : projectDir;
10104
10283
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log, assetRoot });
10105
10284
  const compileStart = Date.now();
10106
- const compiled = await compileForRender(projectDir, htmlPath, join20(workDir, "downloads"), {
10285
+ const compiled = await compileForRender(projectDir, htmlPath, join22(workDir, "downloads"), {
10107
10286
  log,
10108
10287
  failClosedFontFetch: failClosedFontFetch === true,
10109
10288
  allowSystemFontCapture,
@@ -10178,7 +10357,7 @@ async function runCompileStage(input) {
10178
10357
  });
10179
10358
  await preflightCompositionAssetMediaTypes({
10180
10359
  projectDir,
10181
- compiledDir: join20(workDir, "compiled"),
10360
+ compiledDir: join22(workDir, "compiled"),
10182
10361
  composition,
10183
10362
  signal: abortSignal
10184
10363
  });
@@ -10226,7 +10405,7 @@ async function runCompileStage(input) {
10226
10405
 
10227
10406
  // src/services/render/stages/probeStage.ts
10228
10407
  import { createHash as createHash7 } from "node:crypto";
10229
- import { basename as basename6, join as join21 } from "node:path";
10408
+ import { basename as basename7, join as join23 } from "node:path";
10230
10409
  import { parseHTML as parseHTML6 } from "linkedom";
10231
10410
  import {
10232
10411
  closeCaptureSession as closeCaptureSession4,
@@ -10474,7 +10653,7 @@ function probeRequiresBrowser(args) {
10474
10653
  function reportedLengthSource(source) {
10475
10654
  if (!source) return null;
10476
10655
  if (source.from !== "media") return { from: source.from };
10477
- const name = basename6(source.src.split(/[?#]/, 1)[0] ?? "");
10656
+ const name = basename7(source.src.split(/[?#]/, 1)[0] ?? "");
10478
10657
  const srcHash = createHash7("sha256").update(name).digest("hex").slice(0, 12);
10479
10658
  return { from: "media", tag: source.tag, trimmed: source.trimmed, srcHash };
10480
10659
  }
@@ -10540,7 +10719,7 @@ async function runProbeStage(input) {
10540
10719
  });
10541
10720
  fileServer = await createFileServer({
10542
10721
  projectDir,
10543
- compiledDir: join21(workDir, "compiled"),
10722
+ compiledDir: join23(workDir, "compiled"),
10544
10723
  port: 0,
10545
10724
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10546
10725
  fps: job.config.fps,
@@ -10577,7 +10756,7 @@ async function runProbeStage(input) {
10577
10756
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
10578
10757
  probeSession = await createCaptureSession4(
10579
10758
  fileServer.url,
10580
- join21(workDir, "probe"),
10759
+ join23(workDir, "probe"),
10581
10760
  captureOpts,
10582
10761
  null,
10583
10762
  probeCfg
@@ -10662,7 +10841,7 @@ async function runProbeStage(input) {
10662
10841
  });
10663
10842
  probeSession = await createCaptureSession4(
10664
10843
  fileServer.url,
10665
- join21(workDir, "probe-screenshot"),
10844
+ join23(workDir, "probe-screenshot"),
10666
10845
  captureOpts,
10667
10846
  null,
10668
10847
  { ...probeCfg, forceScreenshot: true }
@@ -10700,7 +10879,7 @@ async function runProbeStage(input) {
10700
10879
  compiled,
10701
10880
  resolutions,
10702
10881
  projectDir,
10703
- join21(workDir, "downloads"),
10882
+ join23(workDir, "downloads"),
10704
10883
  job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10705
10884
  { includeScripts: job.config.includeOutsideScripts }
10706
10885
  );
@@ -10900,7 +11079,7 @@ async function runProbeStage(input) {
10900
11079
  });
10901
11080
  await preflightCompositionAssetMediaTypes({
10902
11081
  projectDir,
10903
- compiledDir: join21(workDir, "compiled"),
11082
+ compiledDir: join23(workDir, "compiled"),
10904
11083
  composition,
10905
11084
  signal: abortSignal
10906
11085
  });
@@ -11035,8 +11214,8 @@ function validateRenderDuration(input) {
11035
11214
  }
11036
11215
 
11037
11216
  // src/services/render/stages/extractVideosStage.ts
11038
- import { existsSync as existsSync13 } from "node:fs";
11039
- import { join as join22 } from "node:path";
11217
+ import { existsSync as existsSync14 } from "node:fs";
11218
+ import { join as join24 } from "node:path";
11040
11219
  import {
11041
11220
  classifyVideoExtractionError,
11042
11221
  createFrameLookupTable as createFrameLookupTable3,
@@ -11395,7 +11574,7 @@ async function runExtractVideosStage(input) {
11395
11574
  // because short boundary counts can differ by one frame.
11396
11575
  {
11397
11576
  fps: job.config.fps,
11398
- outputDir: join22(compiledDir, "__hyperframes_video_frames"),
11577
+ outputDir: join24(compiledDir, "__hyperframes_video_frames"),
11399
11578
  format: job.config.videoFrameFormat ?? "auto",
11400
11579
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
11401
11580
  timelineEnd: composition.duration,
@@ -11403,7 +11582,7 @@ async function runExtractVideosStage(input) {
11403
11582
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
11404
11583
  deferRangeExtraction,
11405
11584
  shownBoxes,
11406
- contentKeyedDirs: [join22(compiledDir, REMOTE_MEDIA_SUBDIR)],
11585
+ contentKeyedDirs: [join24(compiledDir, REMOTE_MEDIA_SUBDIR)],
11407
11586
  urlByAbsentLocalPath,
11408
11587
  assetRoots,
11409
11588
  onProgress: ({ planned = 0, done = 0 }) => {
@@ -11483,7 +11662,7 @@ function isPublicHttpsUrl(url) {
11483
11662
  }
11484
11663
  }
11485
11664
  function opensLocally(path, assetRoots) {
11486
- return existsSync13(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11665
+ return existsSync14(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11487
11666
  }
11488
11667
  function localProbeSource(src, input) {
11489
11668
  const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
@@ -11495,7 +11674,7 @@ async function remoteProbeSource(video, input) {
11495
11674
  if (!isPublicHttpsUrl(video.src)) return null;
11496
11675
  if (!resolveRestrictPageNetwork()) return video.src;
11497
11676
  if (!video.hasAudio || video.hidden) return null;
11498
- const downloadDir = input.downloadDir ?? join22(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11677
+ const downloadDir = input.downloadDir ?? join24(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11499
11678
  try {
11500
11679
  return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
11501
11680
  onTelemetry: writeUrlDownloadTelemetry2
@@ -11536,7 +11715,7 @@ async function appendVideoAudioFromProbe(input) {
11536
11715
  }
11537
11716
 
11538
11717
  // src/services/render/videoLayerPassthroughPlan.ts
11539
- import { existsSync as existsSync14 } from "node:fs";
11718
+ import { existsSync as existsSync15 } from "node:fs";
11540
11719
  import {
11541
11720
  buildVideoLayerInput,
11542
11721
  isHttpUrl as isHttpUrl4,
@@ -11604,7 +11783,7 @@ async function planVideoLayerPassthrough(input) {
11604
11783
  const { video } = q;
11605
11784
  if (isHttpUrl4(video.src)) return { reason: "remote_source" };
11606
11785
  const path = resolveProjectRelativeSrc5(video.src, input.projectDir, input.compiledDir);
11607
- if (!existsSync14(path)) return { reason: "source_missing" };
11786
+ if (!existsSync15(path)) return { reason: "source_missing" };
11608
11787
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
11609
11788
  if ("reason" in layout) return layout;
11610
11789
  const layer = await buildVideoLayerInput(
@@ -11619,8 +11798,8 @@ async function planVideoLayerPassthrough(input) {
11619
11798
  }
11620
11799
 
11621
11800
  // src/services/render/stages/audioStage.ts
11622
- import { existsSync as existsSync16 } from "node:fs";
11623
- import { join as join25 } from "node:path";
11801
+ import { existsSync as existsSync17 } from "node:fs";
11802
+ import { join as join27 } from "node:path";
11624
11803
  import {
11625
11804
  MIXED_AUDIO_FILENAME,
11626
11805
  audioFailureDiagnostics,
@@ -11631,8 +11810,8 @@ import {
11631
11810
  } from "@hyperframes/engine";
11632
11811
 
11633
11812
  // src/services/render/audioDeliveryLimit.ts
11634
- import { existsSync as existsSync15 } from "node:fs";
11635
- import { dirname as dirname11, join as join24 } from "node:path";
11813
+ import { existsSync as existsSync16 } from "node:fs";
11814
+ import { dirname as dirname11, join as join26 } from "node:path";
11636
11815
  import {
11637
11816
  applyAudioFxChain,
11638
11817
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -11642,7 +11821,7 @@ import {
11642
11821
 
11643
11822
  // src/services/render/audioPadTrim.ts
11644
11823
  import { spawn } from "node:child_process";
11645
- import { dirname as dirname10, join as join23 } from "node:path";
11824
+ import { dirname as dirname10, join as join25 } from "node:path";
11646
11825
  import {
11647
11826
  DEFAULT_CONFIG,
11648
11827
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -11923,7 +12102,7 @@ async function constrainAacTruePeak(input) {
11923
12102
  }
11924
12103
  async function cutSource(input, scratchDir, attenuationDb) {
11925
12104
  if (!input.sourcePath || !input.rewriteSource) return true;
11926
- const cutPath = join23(scratchDir, "source.wav");
12105
+ const cutPath = join25(scratchDir, "source.wav");
11927
12106
  try {
11928
12107
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
11929
12108
  if (!result.success) throw new Error(result.error);
@@ -11938,7 +12117,7 @@ async function enforceAacTruePeak(input) {
11938
12117
  let scratchDir;
11939
12118
  try {
11940
12119
  scratchDir = createStagingDir3(dirname10(input.audioPath), ".true-peak-");
11941
- const correctedPath = join23(scratchDir, "audio.m4a");
12120
+ const correctedPath = join25(scratchDir, "audio.m4a");
11942
12121
  const measurements = [];
11943
12122
  let attenuationDb = 0;
11944
12123
  let sourcePeakDbfs;
@@ -12151,14 +12330,14 @@ async function limitDeliveryPeaks(input, deps = {
12151
12330
  applyChain: applyAudioFxChain,
12152
12331
  encode: encodeAac2,
12153
12332
  rename: renameWithRetry6,
12154
- sourceExists: existsSync15
12333
+ sourceExists: existsSync16
12155
12334
  }) {
12156
12335
  const { audioPath, sourcePath, signal, timeoutMs } = input;
12157
12336
  if (!deps.sourceExists(sourcePath)) return { success: true };
12158
12337
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
12159
12338
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
12160
12339
  const alternating = ["a", "b"].map(
12161
- (k) => join24(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12340
+ (k) => join26(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12162
12341
  );
12163
12342
  let encodedFrom;
12164
12343
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -12231,7 +12410,7 @@ function runAudioStage(input) {
12231
12410
  }
12232
12411
  async function runAudioStageScoped(input) {
12233
12412
  const stageStart = Date.now();
12234
- const pcmSourcePath = join25(input.workDir, "audio-source.wav");
12413
+ const pcmSourcePath = join27(input.workDir, "audio-source.wav");
12235
12414
  const duration = input.totalFrames * input.fps.den / input.fps.num;
12236
12415
  let deliverySourcePath;
12237
12416
  try {
@@ -12247,7 +12426,7 @@ async function runAudioStageScoped(input) {
12247
12426
  );
12248
12427
  audioLoweredDb = guard.loweredDb;
12249
12428
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
12250
- if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
12429
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
12251
12430
  deliverySourcePath = pcmSourcePath;
12252
12431
  }
12253
12432
  }
@@ -12296,7 +12475,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12296
12475
  assertNotAborted,
12297
12476
  log
12298
12477
  } = input;
12299
- const audioOutputPath = join25(workDir, MIXED_AUDIO_FILENAME);
12478
+ const audioOutputPath = join27(workDir, MIXED_AUDIO_FILENAME);
12300
12479
  let hasAudio = false;
12301
12480
  let audioError;
12302
12481
  let audioFailures;
@@ -12376,8 +12555,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12376
12555
  }
12377
12556
 
12378
12557
  // src/services/render/stages/captureStage.ts
12379
- import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12380
- import { join as join26 } from "node:path";
12558
+ import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12559
+ import { join as join28 } from "node:path";
12381
12560
  import {
12382
12561
  classifyCaptureFailure as classifyCaptureFailure2,
12383
12562
  frameFileExtension,
@@ -12447,16 +12626,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
12447
12626
  }
12448
12627
  function measureCaptureFrameBytes(workDir, framesDir) {
12449
12628
  let total = sampleDirectoryBytes(framesDir);
12450
- if (!existsSync17(workDir)) return total;
12629
+ if (!existsSync18(workDir)) return total;
12451
12630
  for (const attempt of readdirSync4(workDir)) {
12452
12631
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
12453
- total += sampleDirectoryBytes(join26(workDir, attempt));
12632
+ total += sampleDirectoryBytes(join28(workDir, attempt));
12454
12633
  continue;
12455
12634
  }
12456
12635
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
12457
- const attemptDir = join26(workDir, attempt);
12636
+ const attemptDir = join28(workDir, attempt);
12458
12637
  for (const name of readdirSync4(attemptDir)) {
12459
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join26(attemptDir, name));
12638
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join28(attemptDir, name));
12460
12639
  }
12461
12640
  }
12462
12641
  return total;
@@ -12754,8 +12933,8 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
12754
12933
  }
12755
12934
 
12756
12935
  // src/services/render/stages/captureHdrStage.ts
12757
- import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
12758
- import { join as join30 } from "node:path";
12936
+ import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
12937
+ import { join as join32 } from "node:path";
12759
12938
  import {
12760
12939
  closeCaptureSession as closeCaptureSession7,
12761
12940
  cloneCaptureWarnings as cloneCaptureWarnings2,
@@ -12827,7 +13006,7 @@ function createHdrImageTransferCache(options = {}) {
12827
13006
  }
12828
13007
 
12829
13008
  // src/services/render/stages/captureHdrSequentialLoop.ts
12830
- import { join as join27 } from "node:path";
13009
+ import { join as join29 } from "node:path";
12831
13010
  import {
12832
13011
  TRANSITIONS,
12833
13012
  crossfade
@@ -12952,7 +13131,7 @@ async function runSequentialLayeredFrameLoop(input) {
12952
13131
  );
12953
13132
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
12954
13133
  writeFileExclusiveSync(
12955
- join27(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13134
+ join29(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12956
13135
  normalCanvas
12957
13136
  );
12958
13137
  }
@@ -12984,7 +13163,7 @@ async function runSequentialLayeredFrameLoop(input) {
12984
13163
  }
12985
13164
 
12986
13165
  // src/services/render/stages/captureHdrHybridLoop.ts
12987
- import { join as join29 } from "node:path";
13166
+ import { join as join31 } from "node:path";
12988
13167
  import {
12989
13168
  TRANSITIONS as TRANSITIONS2,
12990
13169
  closeCaptureSession as closeCaptureSession6,
@@ -12998,10 +13177,10 @@ import {
12998
13177
  // src/services/shaderTransitionWorkerPool.ts
12999
13178
  import { Worker } from "node:worker_threads";
13000
13179
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
13001
- import { dirname as dirname12, join as join28 } from "node:path";
13180
+ import { dirname as dirname12, join as join30 } from "node:path";
13002
13181
  import { createRequire } from "node:module";
13003
13182
  import { usableCpuCount } from "@hyperframes/engine";
13004
- import { existsSync as existsSync18 } from "node:fs";
13183
+ import { existsSync as existsSync19 } from "node:fs";
13005
13184
  function resolveWorkerEntry(explicit) {
13006
13185
  if (explicit && explicit.length > 0) {
13007
13186
  return { path: explicit, isTs: explicit.endsWith(".ts") };
@@ -13012,9 +13191,9 @@ function resolveWorkerEntry(explicit) {
13012
13191
  return { path: override, isTs };
13013
13192
  }
13014
13193
  const moduleDir = dirname12(fileURLToPath3(import.meta.url));
13015
- const jsPath = join28(moduleDir, "shaderTransitionWorker.js");
13016
- if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
13017
- const tsPath = join28(moduleDir, "shaderTransitionWorker.ts");
13194
+ const jsPath = join30(moduleDir, "shaderTransitionWorker.js");
13195
+ if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
13196
+ const tsPath = join30(moduleDir, "shaderTransitionWorker.ts");
13018
13197
  return { path: tsPath, isTs: true };
13019
13198
  }
13020
13199
  function buildExecArgv(entryIsTs) {
@@ -13157,8 +13336,8 @@ async function createShaderTransitionWorkerPool(opts) {
13157
13336
  if (terminated) {
13158
13337
  throw new Error("shader-blend pool already terminated");
13159
13338
  }
13160
- return new Promise((resolve11, reject) => {
13161
- const task = traceEnabled ? { req, resolve: resolve11, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve11, reject };
13339
+ return new Promise((resolve12, reject) => {
13340
+ const task = traceEnabled ? { req, resolve: resolve12, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve12, reject };
13162
13341
  const idle = slots.find((s) => !s.busy && !s.dead);
13163
13342
  if (idle) {
13164
13343
  queue.unshift(task);
@@ -13382,7 +13561,7 @@ async function runHybridLayeredFrameLoop(input) {
13382
13561
  );
13383
13562
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
13384
13563
  writeFileExclusiveSync(
13385
- join29(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13564
+ join31(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13386
13565
  canvas
13387
13566
  );
13388
13567
  }
@@ -13578,8 +13757,8 @@ async function runCaptureHdrStage(input) {
13578
13757
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
13579
13758
  }
13580
13759
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
13581
- const debugDumpDir = debugDumpEnabled ? join30(framesDir, "debug-composite") : null;
13582
- if (debugDumpDir && !existsSync19(debugDumpDir)) {
13760
+ const debugDumpDir = debugDumpEnabled ? join32(framesDir, "debug-composite") : null;
13761
+ if (debugDumpDir && !existsSync20(debugDumpDir)) {
13583
13762
  mkdirSync10(debugDumpDir, { recursive: true });
13584
13763
  }
13585
13764
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -13738,16 +13917,16 @@ async function runCaptureHdrStage(input) {
13738
13917
  // src/services/render/stages/encodeStage.ts
13739
13918
  import {
13740
13919
  copyFileSync as copyFileSync4,
13741
- existsSync as existsSync20,
13920
+ existsSync as existsSync21,
13742
13921
  mkdirSync as mkdirSync11,
13743
13922
  readdirSync as readdirSync5,
13744
13923
  readFileSync as readFileSync9,
13745
13924
  rmSync as rmSync11,
13746
- statSync as statSync10,
13925
+ statSync as statSync9,
13747
13926
  writeFileSync as writeFileSync6
13748
13927
  } from "node:fs";
13749
13928
  import { readFile as readFile2 } from "node:fs/promises";
13750
- import { dirname as dirname13, join as join31 } from "node:path";
13929
+ import { dirname as dirname13, join as join33 } from "node:path";
13751
13930
  import {
13752
13931
  encodeFramesChunkedConcat,
13753
13932
  encodeFramesFromDir,
@@ -13872,7 +14051,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13872
14051
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13873
14052
  if (failure) return failure;
13874
14053
  }
13875
- const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
14054
+ const fileSize = existsSync21(outputPath) ? statSync9(outputPath).size : 0;
13876
14055
  return {
13877
14056
  success: true,
13878
14057
  outputPath,
@@ -13963,10 +14142,10 @@ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13963
14142
  const stream = await encoder;
13964
14143
  for (let next = 0; next < totalFrames; next++) {
13965
14144
  while (!landed.has(next) && !captureDone && !signal.aborted) {
13966
- await new Promise((resolve11) => wake = resolve11);
14145
+ await new Promise((resolve12) => wake = resolve12);
13967
14146
  }
13968
14147
  if (signal.aborted) return;
13969
- const mergedPath = join31(input.framesDir, formatCaptureFrameName(next, "jpg"));
14148
+ const mergedPath = join33(input.framesDir, formatCaptureFrameName(next, "jpg"));
13970
14149
  const frame = await readLandedFrame(landed.get(next), mergedPath);
13971
14150
  landed.delete(next);
13972
14151
  if (!await stream.writeFrame(frame)) {
@@ -14041,7 +14220,7 @@ async function runEncodeStage(input) {
14041
14220
  const stage5Start = Date.now();
14042
14221
  if (isPngSequence) {
14043
14222
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
14044
- if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
14223
+ if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
14045
14224
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
14046
14225
  if (captured.length === 0) {
14047
14226
  throw new Error(
@@ -14049,11 +14228,11 @@ async function runEncodeStage(input) {
14049
14228
  );
14050
14229
  }
14051
14230
  captured.forEach((name, i) => {
14052
- const dst = join31(outputPath, formatExportFrameName(i, "png"));
14053
- copyFileSync4(join31(framesDir, name), dst);
14231
+ const dst = join33(outputPath, formatExportFrameName(i, "png"));
14232
+ copyFileSync4(join33(framesDir, name), dst);
14054
14233
  });
14055
- if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
14056
- copyFileSync4(audioOutputPath, join31(outputPath, MIXED_AUDIO_FILENAME2));
14234
+ if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
14235
+ copyFileSync4(audioOutputPath, join33(outputPath, MIXED_AUDIO_FILENAME2));
14057
14236
  log.info(
14058
14237
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
14059
14238
  );
@@ -14073,7 +14252,7 @@ async function runEncodeStage(input) {
14073
14252
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
14074
14253
  fps: job.config.fps,
14075
14254
  loop,
14076
- palettePath: join31(dirname13(videoOnlyPath), "gif-palette.png"),
14255
+ palettePath: join33(dirname13(videoOnlyPath), "gif-palette.png"),
14077
14256
  preserveAlpha: needsAlpha,
14078
14257
  signal: abortSignal,
14079
14258
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -14284,9 +14463,9 @@ function sampleDirectoryBytes(dir) {
14284
14463
  continue;
14285
14464
  }
14286
14465
  for (const name of entries) {
14287
- const full = join32(current, name);
14466
+ const full = join34(current, name);
14288
14467
  try {
14289
- const st = statSync11(full);
14468
+ const st = statSync10(full);
14290
14469
  if (st.isDirectory()) {
14291
14470
  stack.push(full);
14292
14471
  } else if (st.isFile()) {
@@ -14320,6 +14499,7 @@ function summarizeExtractionObservability(extractionResult, videoCount, coverage
14320
14499
  vfrPreflightCount: phaseBreakdown?.vfrPreflightCount,
14321
14500
  cacheHits: phaseBreakdown?.cacheHits,
14322
14501
  cacheMisses: phaseBreakdown?.cacheMisses,
14502
+ cachePublishFailures: phaseBreakdown?.cachePublishFailures,
14323
14503
  transientRetries: phaseBreakdown?.transientRetries,
14324
14504
  ...coverageGauges,
14325
14505
  authoredTimedClipCount
@@ -14441,8 +14621,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14441
14621
  const ranges = [];
14442
14622
  let rangeStart = null;
14443
14623
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14444
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14445
- const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14624
+ const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14625
+ const missing = !existsSync22(framePath) || statSync10(framePath).size <= 8;
14446
14626
  if (missing && rangeStart === null) {
14447
14627
  rangeStart = frameIndex;
14448
14628
  } else if (!missing && rangeStart !== null) {
@@ -14458,7 +14638,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14458
14638
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
14459
14639
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
14460
14640
  const batches = [];
14461
- const outputDirFor = (batchIndex, workerId) => join32(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14641
+ const outputDirFor = (batchIndex, workerId) => join34(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14462
14642
  if (stride > 1) {
14463
14643
  const spans = /* @__PURE__ */ new Map();
14464
14644
  for (const range of ranges) {
@@ -14517,9 +14697,9 @@ function createCaptureObservabilityUpdater(observability, platform2 = process.pl
14517
14697
  function getNextRetryWorkerCount(currentWorkers) {
14518
14698
  return Math.max(1, Math.floor(currentWorkers / 2));
14519
14699
  }
14520
- function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
14521
- if (platform2 === "win32" || platform2 === "darwin") return join32(systemTempDir, "hf-render-");
14522
- return join32(dirname14(outputPath), `work-${jobId}-`);
14700
+ function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir3()) {
14701
+ if (platform2 === "win32" || platform2 === "darwin") return join34(systemTempDir, "hf-render-");
14702
+ return join34(dirname14(outputPath), `work-${jobId}-`);
14523
14703
  }
14524
14704
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
14525
14705
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -14574,8 +14754,8 @@ The composition is too large for the available memory. To reduce memory pressure
14574
14754
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
14575
14755
  let captured = 0;
14576
14756
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14577
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14578
- if (existsSync21(framePath)) captured++;
14757
+ const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14758
+ if (existsSync22(framePath)) captured++;
14579
14759
  }
14580
14760
  return captured;
14581
14761
  }
@@ -14600,7 +14780,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
14600
14780
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
14601
14781
  });
14602
14782
  pendingTransientRetry = false;
14603
- const attemptWorkDir = join32(options.workDir, `capture-attempt-${attempt}`);
14783
+ const attemptWorkDir = join34(options.workDir, `capture-attempt-${attempt}`);
14604
14784
  const batches = missingRanges ? buildMissingFrameRetryBatches(
14605
14785
  missingRanges,
14606
14786
  currentWorkers,
@@ -15247,8 +15427,8 @@ function deVerifyFallbackTelemetry(err) {
15247
15427
  };
15248
15428
  }
15249
15429
  function resolveRenderDebugDir() {
15250
- const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname14(fileURLToPath4(import.meta.url)), "../..");
15251
- return join32(producerRoot, ".debug");
15430
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve9(process.env.PRODUCER_RENDERS_DIR, "..") : resolve9(dirname14(fileURLToPath4(import.meta.url)), "../..");
15431
+ return join34(producerRoot, ".debug");
15252
15432
  }
15253
15433
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
15254
15434
  validateHlsRenderConfig(job.config);
@@ -15256,11 +15436,11 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15256
15436
  validateChromaSubsamplingConfig(job.config);
15257
15437
  const debugDir = resolveRenderDebugDir();
15258
15438
  const outputDir = dirname14(outputPath);
15259
- if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
15260
- const workDir = job.config.debug ? join32(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15439
+ if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
15440
+ const workDir = job.config.debug ? join34(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15261
15441
  const pipelineStart = Date.now();
15262
15442
  const baseLog = job.config.logger ?? defaultLogger;
15263
- const logPath = job.config.debug ? join32(workDir, "render.log") : null;
15443
+ const logPath = job.config.debug ? join34(workDir, "render.log") : null;
15264
15444
  const execution = new RenderExecutionContext({
15265
15445
  request: { renderJobId: job.id, projectDir, outputPath },
15266
15446
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -15291,6 +15471,15 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15291
15471
  await execution.dispose();
15292
15472
  }
15293
15473
  }
15474
+ function loadResumeKeyOrWarn(resume, log) {
15475
+ const key = segmentManifestKey();
15476
+ if (resume && !key) {
15477
+ log.warn(
15478
+ "[Render] --resume: no preview token could be read or created, so every segment will be captured again"
15479
+ );
15480
+ }
15481
+ return key;
15482
+ }
15294
15483
  async function executeRenderPipeline(input) {
15295
15484
  const {
15296
15485
  job,
@@ -15328,7 +15517,7 @@ async function executeRenderPipeline(input) {
15328
15517
  imageDecodeFailures: 0
15329
15518
  };
15330
15519
  let hdrPerf;
15331
- const perfOutputPath = join32(workDir, "perf-summary.json");
15520
+ const perfOutputPath = join34(workDir, "perf-summary.json");
15332
15521
  const cfg = { ...job.config.producerConfig ?? resolveConfig2() };
15333
15522
  const observability = new RenderObservabilityRecorder({
15334
15523
  pipelineStartMs: pipelineStart,
@@ -15404,7 +15593,7 @@ async function executeRenderPipeline(input) {
15404
15593
  job.startedAt = /* @__PURE__ */ new Date();
15405
15594
  assertNotAborted();
15406
15595
  assertConfiguredFfmpegBinariesExist();
15407
- if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
15596
+ if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
15408
15597
  if (job.config.debug) {
15409
15598
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
15410
15599
  }
@@ -15433,8 +15622,8 @@ async function executeRenderPipeline(input) {
15433
15622
  requestedWorkers: job.config.workers ?? "auto"
15434
15623
  });
15435
15624
  const entryFile = job.config.entryFile || "index.html";
15436
- const htmlPath = join32(projectDir, entryFile);
15437
- if (!existsSync21(htmlPath)) {
15625
+ const htmlPath = join34(projectDir, entryFile);
15626
+ if (!existsSync22(htmlPath)) {
15438
15627
  throw new Error(`Entry file not found: ${htmlPath}`);
15439
15628
  }
15440
15629
  assertNotAborted();
@@ -15530,7 +15719,7 @@ async function executeRenderPipeline(input) {
15530
15719
  const largerThanCanvas = await oversizedVideos(
15531
15720
  composition.videos,
15532
15721
  projectDir,
15533
- join32(workDir, "compiled"),
15722
+ join34(workDir, "compiled"),
15534
15723
  { width: outputWidth, height: outputHeight }
15535
15724
  );
15536
15725
  const probeResult = await observeRenderStage(
@@ -15627,7 +15816,7 @@ async function executeRenderPipeline(input) {
15627
15816
  canvas: { width, height },
15628
15817
  page: probeSession.page,
15629
15818
  projectDir,
15630
- compiledDir: join32(workDir, "compiled")
15819
+ compiledDir: join34(workDir, "compiled")
15631
15820
  });
15632
15821
  if (videoLayerPlan.videoId === void 0) {
15633
15822
  log.info(`[Render] Video layer passthrough off: ${videoLayerPlan.reason}`);
@@ -15645,7 +15834,7 @@ async function executeRenderPipeline(input) {
15645
15834
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
15646
15835
  code: "extract_video"
15647
15836
  });
15648
- const compiledDir = join32(workDir, "compiled");
15837
+ const compiledDir = join34(workDir, "compiled");
15649
15838
  const segmentsCapture = (layeredOrEffectRoute) => shouldSegmentCapture({
15650
15839
  env: process.env,
15651
15840
  durationSeconds: probeResult.duration,
@@ -15781,7 +15970,7 @@ async function executeRenderPipeline(input) {
15781
15970
  try {
15782
15971
  fileServer = await createFileServer({
15783
15972
  projectDir,
15784
- compiledDir: join32(workDir, "compiled"),
15973
+ compiledDir: join34(workDir, "compiled"),
15785
15974
  port: 0,
15786
15975
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15787
15976
  fps: job.config.fps,
@@ -15801,8 +15990,8 @@ async function executeRenderPipeline(input) {
15801
15990
  if (!activeFileServer) {
15802
15991
  throw new Error("File server failed to initialize before frame capture");
15803
15992
  }
15804
- const framesDir = join32(workDir, "captured-frames");
15805
- if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
15993
+ const framesDir = join34(workDir, "captured-frames");
15994
+ if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
15806
15995
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
15807
15996
  code: "start_browsers"
15808
15997
  });
@@ -16382,7 +16571,7 @@ async function executeRenderPipeline(input) {
16382
16571
  hls: ".mp4"
16383
16572
  };
16384
16573
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
16385
- const videoOnlyPath = join32(workDir, `video-only${videoExt}`);
16574
+ const videoOnlyPath = join34(workDir, `video-only${videoExt}`);
16386
16575
  let usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
16387
16576
  if (usePageSideCompositingForTransitions) {
16388
16577
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -16699,16 +16888,19 @@ async function executeRenderPipeline(input) {
16699
16888
  pageMotionBlur: job.config.pageMotionBlur,
16700
16889
  captureQuality: captureOptions.quality
16701
16890
  });
16702
- const segmentDir = segmentDirFor(join32(projectDir, "renders"), segmentPlanHash);
16891
+ const segmentDir = segmentDirFor(join34(projectDir, "renders"), segmentPlanHash);
16892
+ const manifestKey = loadResumeKeyOrWarn(job.config.resumeSegments === true, log);
16703
16893
  let completedSegments = /* @__PURE__ */ new Set();
16704
16894
  if (job.config.resumeSegments === true) {
16705
16895
  const existing = readSegmentManifest(segmentDir);
16706
16896
  if (existing) {
16707
- completedSegments = await validateCompletedSegments(
16708
- existing,
16709
- segmentPlanHash,
16710
- (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
16711
- );
16897
+ completedSegments = await validateCompletedSegments(existing, {
16898
+ expectedHash: segmentPlanHash,
16899
+ segmentDir,
16900
+ plan: planSegments(totalFrames, segmentFrames),
16901
+ key: manifestKey,
16902
+ probeFrames: (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
16903
+ });
16712
16904
  log.info(`[Render] resuming: ${completedSegments.size} segments complete`, {
16713
16905
  segmentDir
16714
16906
  });
@@ -16782,7 +16974,7 @@ async function executeRenderPipeline(input) {
16782
16974
  ...segmentManifest.completed.filter((e) => e.index !== entry.index),
16783
16975
  { ...entry, completedAt: (/* @__PURE__ */ new Date()).toISOString() }
16784
16976
  ];
16785
- writeSegmentManifest(segmentDir, segmentManifest);
16977
+ writeSegmentManifest(segmentDir, segmentManifest, manifestKey);
16786
16978
  },
16787
16979
  updateCaptureObservability
16788
16980
  })
@@ -17243,7 +17435,7 @@ async function executeRenderPipeline(input) {
17243
17435
  })
17244
17436
  );
17245
17437
  const totalElapsed = Date.now() - pipelineStart;
17246
- const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
17438
+ const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
17247
17439
  recordTransientRetryObservability();
17248
17440
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
17249
17441
  const observabilitySummary = observability.summary({
@@ -17324,8 +17516,8 @@ async function executeRenderPipeline(input) {
17324
17516
  }
17325
17517
  }
17326
17518
  if (job.config.debug) {
17327
- if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
17328
- const debugOutput = join32(workDir, `output${videoExt}`);
17519
+ if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
17520
+ const debugOutput = join34(workDir, `output${videoExt}`);
17329
17521
  copyFileSync5(stagedOutputPath, debugOutput);
17330
17522
  }
17331
17523
  }
@@ -17404,7 +17596,8 @@ async function executeRenderPipeline(input) {
17404
17596
  perfStages,
17405
17597
  hdrDiagnostics,
17406
17598
  observability: observabilitySummary,
17407
- subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs)
17599
+ subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs),
17600
+ missingPath: describeMissingPath(error, { cacheDir: cfg.extractCacheDir, workDir })
17408
17601
  });
17409
17602
  publishRenderFailure(
17410
17603
  job,
@@ -17439,15 +17632,15 @@ async function executeRenderPipeline(input) {
17439
17632
 
17440
17633
  // src/services/hyperframeLint.ts
17441
17634
  import {
17442
- existsSync as existsSync22,
17635
+ existsSync as existsSync23,
17443
17636
  readFileSync as readFileSync10,
17444
- statSync as statSync12,
17637
+ statSync as statSync11,
17445
17638
  openSync as openSync5,
17446
17639
  fstatSync as fstatSync3,
17447
17640
  closeSync as closeSync5,
17448
17641
  constants as constants3
17449
17642
  } from "node:fs";
17450
- import { resolve as resolve9, join as join33, relative as relative4, isAbsolute as isAbsolute3, sep as sep4, dirname as dirname15 } from "node:path";
17643
+ import { resolve as resolve10, join as join35, relative as relative5, isAbsolute as isAbsolute4, sep as sep5, dirname as dirname15 } from "node:path";
17451
17644
  import { fileURLToPath as fileURLToPath5 } from "node:url";
17452
17645
  import { Worker as Worker2 } from "node:worker_threads";
17453
17646
  function isStringRecord(value) {
@@ -17482,7 +17675,7 @@ function readEntryHtml(filePath) {
17482
17675
  } catch (error) {
17483
17676
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
17484
17677
  return null;
17485
- if (!statSync12(filePath, { throwIfNoEntry: false })?.isFile()) return null;
17678
+ if (!statSync11(filePath, { throwIfNoEntry: false })?.isFile()) return null;
17486
17679
  throw error;
17487
17680
  }
17488
17681
  try {
@@ -17493,19 +17686,19 @@ function readEntryHtml(filePath) {
17493
17686
  }
17494
17687
  }
17495
17688
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
17496
- const entryRelativePath = relative4(absProjectDir, absoluteEntryPath);
17497
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep4}`) || isAbsolute3(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
17689
+ const entryRelativePath = relative5(absProjectDir, absoluteEntryPath);
17690
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute4(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
17498
17691
  }
17499
17692
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
17500
- const absProjectDir = resolve9(projectDir);
17501
- if (!existsSync22(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17693
+ const absProjectDir = resolve10(projectDir);
17694
+ if (!existsSync23(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
17502
17695
  return { error: `Project directory not found: ${absProjectDir}` };
17503
17696
  }
17504
17697
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
17505
17698
  (value) => typeof value === "string" && value.trim().length > 0
17506
17699
  );
17507
17700
  for (const entryFile of entryCandidates) {
17508
- const absoluteEntryPath = resolve9(absProjectDir, entryFile);
17701
+ const absoluteEntryPath = resolve10(absProjectDir, entryFile);
17509
17702
  if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) {
17510
17703
  return { error: `Entry file must stay inside project directory: ${entryFile}` };
17511
17704
  }
@@ -17519,7 +17712,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
17519
17712
  }
17520
17713
  }
17521
17714
  return {
17522
- error: `No HTML entry file found in project directory: ${join33(absProjectDir, preferredEntryFile || "index.html")}`
17715
+ error: `No HTML entry file found in project directory: ${join35(absProjectDir, preferredEntryFile || "index.html")}`
17523
17716
  };
17524
17717
  }
17525
17718
  function prepareHyperframeLintBody(body, isAllowedEntry) {
@@ -17565,16 +17758,16 @@ function takeLintSlot(limit, waitMs) {
17565
17758
  running++;
17566
17759
  return Promise.resolve(true);
17567
17760
  }
17568
- return new Promise((resolve11) => {
17761
+ return new Promise((resolve12) => {
17569
17762
  const entry = () => {
17570
17763
  clearTimeout(timer);
17571
17764
  running++;
17572
- resolve11(true);
17765
+ resolve12(true);
17573
17766
  };
17574
17767
  const timer = setTimeout(
17575
17768
  () => {
17576
17769
  waiting.splice(waiting.indexOf(entry), 1);
17577
- resolve11(false);
17770
+ resolve12(false);
17578
17771
  },
17579
17772
  Math.max(0, waitMs)
17580
17773
  );
@@ -17588,8 +17781,8 @@ function freeLintSlot() {
17588
17781
  function resolveLintWorkerEntry() {
17589
17782
  const here = dirname15(fileURLToPath5(import.meta.url));
17590
17783
  for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
17591
- const candidate = join33(here, name);
17592
- if (existsSync22(candidate)) return candidate;
17784
+ const candidate = join35(here, name);
17785
+ if (existsSync23(candidate)) return candidate;
17593
17786
  }
17594
17787
  return void 0;
17595
17788
  }
@@ -17659,8 +17852,8 @@ async function runHyperframeLint(prepared, options = {}) {
17659
17852
  // src/services/healthWorker.ts
17660
17853
  import { Worker as Worker3 } from "node:worker_threads";
17661
17854
  import { fileURLToPath as fileURLToPath6 } from "node:url";
17662
- import { dirname as dirname16, join as join34 } from "node:path";
17663
- import { existsSync as existsSync23 } from "node:fs";
17855
+ import { dirname as dirname16, join as join36 } from "node:path";
17856
+ import { existsSync as existsSync24 } from "node:fs";
17664
17857
  var DEFAULT_HEALTH_PORT = 9848;
17665
17858
  async function startHealthWorker(options = {}) {
17666
17859
  const log = options.logger ?? defaultLogger2();
@@ -17678,12 +17871,12 @@ async function startHealthWorker(options = {}) {
17678
17871
  stdout: false,
17679
17872
  stderr: false
17680
17873
  });
17681
- await new Promise((resolve11, reject) => {
17874
+ await new Promise((resolve12, reject) => {
17682
17875
  const onMessage = (msg) => {
17683
17876
  if (msg?.type === "listening") {
17684
17877
  worker.off("error", onError);
17685
17878
  worker.off("message", onMessage);
17686
- resolve11();
17879
+ resolve12();
17687
17880
  } else if (msg?.type === "listen-error") {
17688
17881
  worker.off("error", onError);
17689
17882
  worker.off("message", onMessage);
@@ -17735,9 +17928,9 @@ function defaultLogger2() {
17735
17928
  }
17736
17929
  function resolveWorkerEntry2() {
17737
17930
  const here = dirname16(fileURLToPath6(import.meta.url));
17738
- const candidates = [join34(here, "healthWorkerThread.js"), join34(here, "healthWorkerThread.ts")];
17931
+ const candidates = [join36(here, "healthWorkerThread.js"), join36(here, "healthWorkerThread.ts")];
17739
17932
  for (const candidate of candidates) {
17740
- if (existsSync23(candidate)) return candidate;
17933
+ if (existsSync24(candidate)) return candidate;
17741
17934
  }
17742
17935
  return void 0;
17743
17936
  }
@@ -17777,7 +17970,7 @@ import {
17777
17970
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
17778
17971
  } from "@hyperframes/engine";
17779
17972
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
17780
- import { extname as extname4, isAbsolute as isAbsolute4, join as join36, relative as relative5, sep as sep5 } from "node:path";
17973
+ import { extname as extname4, isAbsolute as isAbsolute5, join as join38, relative as relative6, sep as sep6 } from "node:path";
17781
17974
  import {
17782
17975
  fpsToNumber as fpsToNumber9,
17783
17976
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -17810,8 +18003,8 @@ import {
17810
18003
 
17811
18004
  // src/services/distributed/shared.ts
17812
18005
  import { execFile as execFileCallback } from "node:child_process";
17813
- import { dirname as dirname17, join as join35 } from "node:path";
17814
- import { existsSync as existsSync24, readFileSync as readFileSync11 } from "node:fs";
18006
+ import { dirname as dirname17, join as join37 } from "node:path";
18007
+ import { existsSync as existsSync25, readFileSync as readFileSync11 } from "node:fs";
17815
18008
  import { fileURLToPath as fileURLToPath7 } from "node:url";
17816
18009
  import { promisify as promisify2 } from "node:util";
17817
18010
  import {
@@ -17826,8 +18019,8 @@ function readProducerVersion() {
17826
18019
  const startDir = dirname17(fileURLToPath7(import.meta.url));
17827
18020
  let current = startDir;
17828
18021
  for (let i = 0; i < 10; i++) {
17829
- const candidate = join35(current, "package.json");
17830
- if (existsSync24(candidate)) {
18022
+ const candidate = join37(current, "package.json");
18023
+ if (existsSync25(candidate)) {
17831
18024
  try {
17832
18025
  const pkg = JSON.parse(readFileSync11(candidate, "utf-8"));
17833
18026
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
@@ -17924,9 +18117,9 @@ var PLAN_ROOT_CATEGORY = {
17924
18117
  var PLAN_DIR_SIZE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024;
17925
18118
  var FREEZE_OWNED_PLAN_FILES = [
17926
18119
  "plan.json",
17927
- join36("meta", "composition.json"),
17928
- join36("meta", "encoder.json"),
17929
- join36("meta", "chunks.json")
18120
+ join38("meta", "composition.json"),
18121
+ join38("meta", "encoder.json"),
18122
+ join38("meta", "chunks.json")
17930
18123
  ];
17931
18124
 
17932
18125
  // src/services/distributed/renderConfigValidation.ts
@@ -18354,7 +18547,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
18354
18547
  }
18355
18548
  }
18356
18549
  const outputDir = dirname18(absoluteOutputPath);
18357
- if (!existsSync25(outputDir)) mkdirSync13(outputDir, { recursive: true });
18550
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
18358
18551
  return { input, cleanupProjectDir, absoluteOutputPath };
18359
18552
  }
18360
18553
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
@@ -18415,7 +18608,7 @@ function validateOutputResolutionOverride(body) {
18415
18608
  var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
18416
18609
  function resolveRenderRequestPolicy(options) {
18417
18610
  return {
18418
- projectsDir: resolve10(
18611
+ projectsDir: resolve11(
18419
18612
  options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd())
18420
18613
  ),
18421
18614
  allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1"
@@ -18430,14 +18623,14 @@ function isAllowedEntryPath(policy, projectDir, path) {
18430
18623
  function prepareProjectDirectory(projectDir, options, policy) {
18431
18624
  const candidate = nonEmptyString(projectDir);
18432
18625
  if (!candidate) return null;
18433
- const absProjectDir = policy ? resolve10(policy.projectsDir, candidate) : resolve10(candidate);
18626
+ const absProjectDir = policy ? resolve11(policy.projectsDir, candidate) : resolve11(candidate);
18434
18627
  const shown = policy ? candidate : absProjectDir;
18435
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync25(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
18628
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync26(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
18436
18629
  return { error: `Project directory not found: ${shown}` };
18437
18630
  }
18438
18631
  const entry = options.entryFile || "index.html";
18439
- const entryPath = resolve10(absProjectDir, entry);
18440
- if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync25(entryPath)) {
18632
+ const entryPath = resolve11(absProjectDir, entry);
18633
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync26(entryPath)) {
18441
18634
  return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
18442
18635
  }
18443
18636
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -18457,9 +18650,9 @@ async function resolveInlineRenderHtml(body) {
18457
18650
  }
18458
18651
  }
18459
18652
  function materializeInlineProject(html, options) {
18460
- const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir3();
18461
- const tempProjectDir = mkdtempSync(join37(tempRoot, "producer-project-"));
18462
- writeFileSync8(join37(tempProjectDir, "index.html"), html, "utf-8");
18653
+ const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir4();
18654
+ const tempProjectDir = mkdtempSync(join39(tempRoot, "producer-project-"));
18655
+ writeFileSync8(join39(tempProjectDir, "index.html"), html, "utf-8");
18463
18656
  return {
18464
18657
  prepared: {
18465
18658
  input: { projectDir: tempProjectDir, ...options },
@@ -18487,7 +18680,7 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
18487
18680
  try {
18488
18681
  return resolveRenderPaths(projectDir, outputCandidate, rendersDir).absoluteOutputPath;
18489
18682
  } catch (error) {
18490
- const fallbackPath = resolve10(rendersDir, `producer-fallback-${Date.now()}.mp4`);
18683
+ const fallbackPath = resolve11(rendersDir, `producer-fallback-${Date.now()}.mp4`);
18491
18684
  log.warn("Failed to resolve output path, using fallback", {
18492
18685
  fallback: fallbackPath,
18493
18686
  error: error instanceof Error ? error.message : String(error)
@@ -18535,7 +18728,7 @@ function publicPerfSummary(job) {
18535
18728
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
18536
18729
  }
18537
18730
  function outputFileSize(path) {
18538
- return existsSync25(path) ? statSync13(path).size : 0;
18731
+ return existsSync26(path) ? statSync12(path).size : 0;
18539
18732
  }
18540
18733
  function createBlockingProgressReporter(log, requestId) {
18541
18734
  let lastLoggedPct = -10;
@@ -18655,7 +18848,7 @@ function createRenderHandlers(options = {}) {
18655
18848
  const lintProjectDir = nonEmptyString(body.projectDir);
18656
18849
  let isAllowedEntry;
18657
18850
  if (policy && lintProjectDir) {
18658
- const absProjectDir = resolve10(policy.projectsDir, lintProjectDir);
18851
+ const absProjectDir = resolve11(policy.projectsDir, lintProjectDir);
18659
18852
  if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) {
18660
18853
  const error = `Project directory not found: ${lintProjectDir}`;
18661
18854
  return c.json({ success: false, requestId, error }, 400);
@@ -18862,12 +19055,12 @@ function createRenderHandlers(options = {}) {
18862
19055
  if (!artifact) {
18863
19056
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
18864
19057
  }
18865
- if (!existsSync25(artifact.path)) {
19058
+ if (!existsSync26(artifact.path)) {
18866
19059
  store.delete(token);
18867
19060
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
18868
19061
  }
18869
- const stats = statSync13(artifact.path);
18870
- return new Response(createReadStream3(artifact.path), {
19062
+ const stats = statSync12(artifact.path);
19063
+ return new Response(createReadStream4(artifact.path), {
18871
19064
  headers: {
18872
19065
  "content-type": "video/mp4",
18873
19066
  "content-length": String(stats.size),
@@ -19027,7 +19220,7 @@ function startServer(options = {}) {
19027
19220
  process.on("SIGINT", () => shutdown("SIGINT"));
19028
19221
  return server;
19029
19222
  }
19030
- var entryScript = process.argv[1] ? resolve10(process.argv[1]) : "";
19223
+ var entryScript = process.argv[1] ? resolve11(process.argv[1]) : "";
19031
19224
  var isPublicServerEntry = entryScript.endsWith("/public-server.js") || entryScript.endsWith("/src/server.ts");
19032
19225
  if (isPublicServerEntry) {
19033
19226
  const { values } = parseArgs({