@hyperframes/producer 0.9.65 → 0.9.67

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,7 +18,7 @@ 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
23
  statSync as statSync13,
24
24
  mkdtempSync,
@@ -26,8 +26,8 @@ import {
26
26
  rmSync as rmSync13,
27
27
  createReadStream as createReadStream3
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 join38 } 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,7 +44,7 @@ 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,
@@ -53,7 +53,7 @@ import {
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 join33, 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 existsSync7, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2628
+ import { join as join10 } 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,
@@ -4279,8 +4365,8 @@ function isTargetLossError(error) {
4279
4365
 
4280
4366
  // src/services/render/stages/captureStreamingStage.ts
4281
4367
  import { mkdtemp, writeFile } from "node:fs/promises";
4282
- import { tmpdir } from "node:os";
4283
- import { join as join8 } from "node:path";
4368
+ import { tmpdir as tmpdir2 } from "node:os";
4369
+ import { join as join9 } from "node:path";
4284
4370
  import {
4285
4371
  DrawElementVerificationError,
4286
4372
  captureFrameToBuffer,
@@ -4374,7 +4460,7 @@ var SequentialCaptureStallError = class extends Error {
4374
4460
  }
4375
4461
  };
4376
4462
  function raceAgainstStall(promise, deadlineMs, input, signal) {
4377
- return new Promise((resolve11, reject) => {
4463
+ return new Promise((resolve12, reject) => {
4378
4464
  const clock = createStallClock();
4379
4465
  const trip = () => reject(
4380
4466
  signal?.aborted ? new Error(
@@ -4399,7 +4485,7 @@ function raceAgainstStall(promise, deadlineMs, input, signal) {
4399
4485
  promise.then(
4400
4486
  (value) => {
4401
4487
  clearTimeout(timer);
4402
- resolve11(value);
4488
+ resolve12(value);
4403
4489
  },
4404
4490
  (error) => {
4405
4491
  clearTimeout(timer);
@@ -4503,11 +4589,11 @@ async function verifyDrawElementSample(session, idx, buf, ctx) {
4503
4589
  return;
4504
4590
  }
4505
4591
  if (db < verifyMinDb) {
4506
- const dumpDir = await mkdtemp(join8(tmpdir(), "hf-de-verify-fail-")).catch(() => null);
4592
+ const dumpDir = await mkdtemp(join9(tmpdir2(), "hf-de-verify-fail-")).catch(() => null);
4507
4593
  if (dumpDir) {
4508
4594
  await Promise.all([
4509
- writeFile(join8(dumpDir, `frame-${idx}-de.jpg`), buf),
4510
- writeFile(join8(dumpDir, `frame-${idx}-truth.jpg`), truth)
4595
+ writeFile(join9(dumpDir, `frame-${idx}-de.jpg`), buf),
4596
+ writeFile(join9(dumpDir, `frame-${idx}-truth.jpg`), truth)
4511
4597
  ]).catch(() => {
4512
4598
  });
4513
4599
  }
@@ -5078,7 +5164,7 @@ async function runCaptureStreamingStage(input) {
5078
5164
 
5079
5165
  // src/services/render/stages/captureSegmentedStage.ts
5080
5166
  function segmentOutputPath(segmentDir, index) {
5081
- return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
5167
+ return join10(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
5082
5168
  }
5083
5169
  function segmentEncoderOptions(base, segment) {
5084
5170
  return {
@@ -5177,7 +5263,7 @@ async function captureSegmentToEncoder(ctx, segment) {
5177
5263
  path: segmentPath,
5178
5264
  // Recorded so resume can prove the file on disk is the one that
5179
5265
  // finished; absent only in unit tests, whose fake encoder writes none.
5180
- bytes: existsSync6(segmentPath) ? statSync4(segmentPath).size : 0
5266
+ bytes: existsSync7(segmentPath) ? statSync4(segmentPath).size : 0
5181
5267
  });
5182
5268
  return encodeResult;
5183
5269
  } finally {
@@ -5411,7 +5497,7 @@ async function runCaptureSegmentedStage(input) {
5411
5497
  const { log, dedupPerfs, assertNotAborted } = input;
5412
5498
  const deps = { ...DEFAULT_DEPS, ...input.deps };
5413
5499
  const segments = planSegments(input.totalFrames, input.segmentFrames);
5414
- const segmentDir = input.segmentDir ?? join9(input.workDir, "segments");
5500
+ const segmentDir = input.segmentDir ?? join10(input.workDir, "segments");
5415
5501
  mkdirSync3(segmentDir, { recursive: true });
5416
5502
  const skip = input.completedSegments ?? /* @__PURE__ */ new Set();
5417
5503
  const pending = segments.filter((s) => !skip.has(s.index));
@@ -5567,7 +5653,7 @@ function startRenderEtaGuard(options) {
5567
5653
  }
5568
5654
 
5569
5655
  // src/services/render/captureCost.ts
5570
- import { join as join10 } from "node:path";
5656
+ import { join as join11 } from "node:path";
5571
5657
  import { fpsToNumber as fpsToNumber4 } from "@hyperframes/core";
5572
5658
  import {
5573
5659
  calculateOptimalWorkers,
@@ -5820,7 +5906,7 @@ async function runCaptureCalibration(input) {
5820
5906
  });
5821
5907
  let calibration;
5822
5908
  try {
5823
- calibration = await runOneCalibration(join10(workDir, "capture-calibration"), calibrationCfg);
5909
+ calibration = await runOneCalibration(join11(workDir, "capture-calibration"), calibrationCfg);
5824
5910
  } catch (error) {
5825
5911
  const shouldFallback = !forceScreenshot && shouldFallbackToScreenshotAfterCalibrationError(error);
5826
5912
  if (!shouldFallback) {
@@ -5854,7 +5940,7 @@ async function runCaptureCalibration(input) {
5854
5940
  const screenshotCfg = createCaptureCalibrationConfig({ ...cfg, forceScreenshot: true });
5855
5941
  try {
5856
5942
  calibration = await runOneCalibration(
5857
- join10(workDir, "capture-calibration-screenshot"),
5943
+ join11(workDir, "capture-calibration-screenshot"),
5858
5944
  screenshotCfg
5859
5945
  );
5860
5946
  } catch (fallbackError) {
@@ -5919,7 +6005,7 @@ function checkPageNeverReady(input) {
5919
6005
 
5920
6006
  // src/services/render/deferredVideoFrames.ts
5921
6007
  import { mkdirSync as mkdirSync4, rmSync as rmSync7 } from "node:fs";
5922
- import { dirname as dirname5, join as join11 } from "node:path";
6008
+ import { dirname as dirname5, join as join12 } from "node:path";
5923
6009
  import {
5924
6010
  createFrameLookupTable,
5925
6011
  extractVideoFramesRange,
@@ -5964,7 +6050,7 @@ async function extractDeferredFrames(input) {
5964
6050
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5965
6051
  return Promise.all(
5966
6052
  deferred.map(async (video) => {
5967
- const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
6053
+ const outputDir = join12(input.outputRoot, mediaIdPathSegment2(video.videoId));
5968
6054
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5969
6055
  if (indexes.length === 0) {
5970
6056
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -6112,13 +6198,13 @@ async function measureLocalShownBoxes(page, videos, fps, duration, log) {
6112
6198
 
6113
6199
  // src/services/render/segmentVideoFrames.ts
6114
6200
  import { mkdirSync as mkdirSync5, rmSync as rmSync8 } from "node:fs";
6115
- import { join as join12 } from "node:path";
6201
+ import { join as join13 } from "node:path";
6116
6202
  import {
6117
6203
  createFrameLookupTable as createFrameLookupTable2,
6118
6204
  createVideoFrameInjector
6119
6205
  } from "@hyperframes/engine";
6120
6206
  function segmentFramesDir(rootDir, index) {
6121
- return join12(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6207
+ return join13(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6122
6208
  }
6123
6209
  function createSegmentVideoFrames(input) {
6124
6210
  const extractFrames = input.extractFrames ?? extractDeferredFrames;
@@ -6149,7 +6235,7 @@ function createSegmentVideoFrames(input) {
6149
6235
  let onDemandCalls = 0;
6150
6236
  const onDemandHook = () => Object.assign(
6151
6237
  async (page, time, heldVideoTime) => {
6152
- const dir = join12(
6238
+ const dir = join13(
6153
6239
  input.rootDir,
6154
6240
  "segment-frames",
6155
6241
  `on-demand_${String(onDemandCalls++).padStart(5, "0")}`
@@ -6166,7 +6252,7 @@ function createSegmentVideoFrames(input) {
6166
6252
  );
6167
6253
  return {
6168
6254
  async forFrames(frames, name) {
6169
- const dir = join12(input.rootDir, "segment-frames", name);
6255
+ const dir = join13(input.rootDir, "segment-frames", name);
6170
6256
  const release = () => rmSync8(dir, { recursive: true, force: true });
6171
6257
  try {
6172
6258
  release();
@@ -6219,7 +6305,7 @@ function createSegmentVideoFrames(input) {
6219
6305
 
6220
6306
  // src/services/render/videoFrameWindow.ts
6221
6307
  import { readdirSync as readdirSync3, statSync as statSync5 } from "node:fs";
6222
- import { join as join13 } from "node:path";
6308
+ import { join as join14 } from "node:path";
6223
6309
  function shouldWindowVideoFrames(args) {
6224
6310
  return args.segmented && args.env.HF_VIDEO_FRAME_WINDOW?.trim().toLowerCase() === "true";
6225
6311
  }
@@ -6232,7 +6318,7 @@ function directoryBytes(path) {
6232
6318
  return 0;
6233
6319
  }
6234
6320
  for (const entry of entries) {
6235
- const child2 = join13(path, entry.name);
6321
+ const child2 = join14(path, entry.name);
6236
6322
  try {
6237
6323
  bytes += entry.isDirectory() ? directoryBytes(child2) : statSync5(child2).size;
6238
6324
  } catch {
@@ -6250,7 +6336,7 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6250
6336
  ...worker,
6251
6337
  async prepare(segment) {
6252
6338
  await worker.prepare(segment);
6253
- const held = directoryBytes(join13(rootDir, "segment-frames"));
6339
+ const held = directoryBytes(join14(rootDir, "segment-frames"));
6254
6340
  if (held > peak) {
6255
6341
  peak = held;
6256
6342
  onPeak(peak);
@@ -6263,8 +6349,8 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6263
6349
 
6264
6350
  // src/services/render/segmentManifest.ts
6265
6351
  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";
6352
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync4, statSync as statSync6, writeFileSync as writeFileSync3 } from "node:fs";
6353
+ import { join as join15 } from "node:path";
6268
6354
  import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
6269
6355
  var MANIFEST_FILENAME = "segments.json";
6270
6356
  function computeSegmentPlanHash(input) {
@@ -6292,7 +6378,7 @@ function computeSegmentPlanHash(input) {
6292
6378
  return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
6293
6379
  }
6294
6380
  function segmentDirFor(projectRendersDir, planHash) {
6295
- return join14(projectRendersDir, ".hf-segments", planHash);
6381
+ return join15(projectRendersDir, ".hf-segments", planHash);
6296
6382
  }
6297
6383
  function hasNumber(value, key) {
6298
6384
  return key in value && typeof Reflect.get(value, key) === "number";
@@ -6310,8 +6396,8 @@ function isManifest(value) {
6310
6396
  return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
6311
6397
  }
6312
6398
  function readSegmentManifest(segmentDir) {
6313
- const path = join14(segmentDir, MANIFEST_FILENAME);
6314
- if (!existsSync7(path)) return null;
6399
+ const path = join15(segmentDir, MANIFEST_FILENAME);
6400
+ if (!existsSync8(path)) return null;
6315
6401
  try {
6316
6402
  const parsed = JSON.parse(readFileSync4(path, "utf-8"));
6317
6403
  return isManifest(parsed) ? parsed : null;
@@ -6321,9 +6407,9 @@ function readSegmentManifest(segmentDir) {
6321
6407
  }
6322
6408
  function writeSegmentManifest(segmentDir, manifest) {
6323
6409
  mkdirSync6(segmentDir, { recursive: true });
6324
- const tmp = join14(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
6410
+ const tmp = join15(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
6325
6411
  writeFileSync3(tmp, JSON.stringify(manifest, null, 2), "utf-8");
6326
- renameWithRetry2(tmp, join14(segmentDir, MANIFEST_FILENAME));
6412
+ renameWithRetry2(tmp, join15(segmentDir, MANIFEST_FILENAME));
6327
6413
  }
6328
6414
  async function probeSegmentFrameCount(path, probe) {
6329
6415
  try {
@@ -6340,7 +6426,7 @@ async function validateCompletedSegments(manifest, expectedHash, probeFrames) {
6340
6426
  const ok = /* @__PURE__ */ new Set();
6341
6427
  if (manifest.planHash !== expectedHash) return ok;
6342
6428
  for (const entry of manifest.completed) {
6343
- if (!existsSync7(entry.path)) continue;
6429
+ if (!existsSync8(entry.path)) continue;
6344
6430
  const size = statSync6(entry.path).size;
6345
6431
  if (size <= 0 || size !== entry.bytes) continue;
6346
6432
  const frames = await probeFrames(entry.path);
@@ -6929,8 +7015,8 @@ function countAuthoredTimedClips(html) {
6929
7015
  }
6930
7016
 
6931
7017
  // 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";
7018
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
7019
+ import { join as join21, relative as relative4 } from "node:path";
6934
7020
  import { privateCacheRoot } from "@hyperframes/engine";
6935
7021
  import { suggestMatchingPreset } from "@hyperframes/core";
6936
7022
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -6959,6 +7045,21 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6959
7045
  `Composition file "${file}" is ${megabytes(bytes)}, over the ${megabytes(MAX_COMPOSITION_HTML_BYTES)} limit for one composition HTML file. Keep large data such as images, fonts and JSON in separate asset files and reference them by path instead of inlining them.`,
6960
7046
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6961
7047
  );
7048
+ var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
7049
+ var REMOTE_SCRIPTS = "remote scripts";
7050
+ var REMOTE_STYLESHEETS = "remote stylesheets";
7051
+ function generatedTooLarge(file, bytes) {
7052
+ if (file === "composition variables") {
7053
+ return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
7054
+ }
7055
+ if (file === "variable media sources") {
7056
+ return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
7057
+ }
7058
+ if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
7059
+ return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
7060
+ }
7061
+ 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.`;
7062
+ }
6962
7063
  var CompositionExpansionBudget = class {
6963
7064
  bytes = 0;
6964
7065
  mounts = 0;
@@ -6967,10 +7068,16 @@ var CompositionExpansionBudget = class {
6967
7068
  chargeGenerated(file, bytes) {
6968
7069
  this.generated += bytes;
6969
7070
  if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
6970
- throw new CompositionTooLargeError(
6971
- `Scripts and styles generated for sub-composition mounts, ending at "${file}", add up to ${megabytes(this.generated)}. 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.`,
6972
- { bytes: this.generated, limitBytes: MAX_EXPANDED_COMPOSITION_BYTES, exceeded: "generated" }
6973
- );
7071
+ throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
7072
+ bytes: this.generated,
7073
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
7074
+ exceeded: "generated"
7075
+ });
7076
+ }
7077
+ chargeGeneratedIfItFits(bytes) {
7078
+ if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
7079
+ this.generated += bytes;
7080
+ return true;
6974
7081
  }
6975
7082
  charge(file, bytes) {
6976
7083
  this.bytes += bytes;
@@ -7017,20 +7124,20 @@ import {
7017
7124
  stylesheetLinkMatches
7018
7125
  } from "@hyperframes/parsers/css-url-scans";
7019
7126
  import { createHash as createHash6 } from "node:crypto";
7020
- import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7021
- import { join as join19, dirname as dirname9, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
7127
+ import { createReadStream as createReadStream2, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7128
+ import { join as join20, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7022
7129
  import { parseHTML as parseHTML5 } from "linkedom";
7023
7130
 
7024
7131
  // src/services/bundledScripts.ts
7025
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7026
- import { join as join15 } from "node:path";
7132
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
7133
+ import { join as join16 } from "node:path";
7027
7134
  import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
7028
7135
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
7029
7136
  function bundledScript(url) {
7030
7137
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
7031
7138
  if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
7032
- const file = join15(dir, "gsap.min.js");
7033
- return existsSync8(file) ? readFileSync5(file) : null;
7139
+ const file = join16(dir, "gsap.min.js");
7140
+ return existsSync9(file) ? readFileSync5(file) : null;
7034
7141
  }
7035
7142
 
7036
7143
  // src/services/htmlCompiler.ts
@@ -7263,6 +7370,7 @@ function placeAudio(audio, window2) {
7263
7370
  import {
7264
7371
  analyzeKeyframeIntervals,
7265
7372
  assertMediaPayload,
7373
+ createConcurrencyLimit,
7266
7374
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
7267
7375
  NotMediaPayloadError as NotMediaPayloadError2,
7268
7376
  parseMasterFxChain,
@@ -7287,8 +7395,8 @@ import {
7287
7395
 
7288
7396
  // src/services/animatedGifPrep.ts
7289
7397
  import { createHash as createHash4 } from "node:crypto";
7290
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7291
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7398
+ import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7399
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join17, resolve as resolve6 } from "node:path";
7292
7400
  import { parseHTML as parseHTML3 } from "linkedom";
7293
7401
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
7294
7402
  import {
@@ -7333,16 +7441,16 @@ function resolveLocalImageSourcePath(src, options) {
7333
7441
  const { basePath } = splitUrlSuffix(trimmed);
7334
7442
  const normalizedBase = normalizeRelPath(basePath);
7335
7443
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
7336
- if (mapped && existsSync9(mapped)) return mapped;
7444
+ if (mapped && existsSync10(mapped)) return mapped;
7337
7445
  if (isHttpUrl(trimmed)) return null;
7338
7446
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
7339
7447
  const candidates = [
7340
- isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7341
- resolve5(options.downloadDir, normalizedBase)
7448
+ isAbsolute3(basePath) ? basePath : resolve6(options.projectDir, projectRelative),
7449
+ resolve6(options.downloadDir, normalizedBase)
7342
7450
  ];
7343
7451
  const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7344
7452
  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));
7345
- return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7453
+ return candidates.find((candidate) => allowed(candidate) && existsSync10(candidate)) ?? null;
7346
7454
  }
7347
7455
  function isUsableFile(path) {
7348
7456
  try {
@@ -7454,10 +7562,10 @@ async function runAnimatedGifTranscode(request) {
7454
7562
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
7455
7563
  }
7456
7564
  async function ensurePreparedWebm(input) {
7457
- if (!existsSync9(dirname6(input.cachePath))) {
7565
+ if (!existsSync10(dirname6(input.cachePath))) {
7458
7566
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
7459
7567
  }
7460
- if (!existsSync9(dirname6(input.outputPath))) {
7568
+ if (!existsSync10(dirname6(input.outputPath))) {
7461
7569
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7462
7570
  }
7463
7571
  if (!isUsableFile(input.cachePath)) {
@@ -7489,7 +7597,7 @@ async function ensurePreparedWebm(input) {
7489
7597
  throw error;
7490
7598
  }
7491
7599
  }
7492
- if (resolve5(input.outputPath) !== resolve5(input.cachePath) && !isUsableFile(input.outputPath)) {
7600
+ if (resolve6(input.outputPath) !== resolve6(input.cachePath) && !isUsableFile(input.outputPath)) {
7493
7601
  copyFileSync2(input.cachePath, input.outputPath);
7494
7602
  }
7495
7603
  }
@@ -7541,7 +7649,7 @@ function replaceImageWithVideo(input) {
7541
7649
  return video;
7542
7650
  }
7543
7651
  async function prepareAnimatedGifInputs(html, options) {
7544
- const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_GIF_SUBDIR);
7652
+ const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_GIF_SUBDIR);
7545
7653
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
7546
7654
  const cacheDir = options.cacheDir ?? outputDir;
7547
7655
  const { document: document2 } = parseHTML3(html);
@@ -7568,8 +7676,8 @@ async function prepareAnimatedGifInputs(html, options) {
7568
7676
  );
7569
7677
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
7570
7678
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
7571
- const cachePath = join16(cacheDir, filename);
7572
- const outputPath = join16(outputDir, filename);
7679
+ const cachePath = join17(cacheDir, filename);
7680
+ const outputPath = join17(outputDir, filename);
7573
7681
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7574
7682
  await ensurePreparedWebm({
7575
7683
  sourcePath,
@@ -7614,7 +7722,7 @@ import {
7614
7722
  statSync as statSync9,
7615
7723
  writeFileSync as writeFileSync4
7616
7724
  } from "node:fs";
7617
- import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
7725
+ import { dirname as dirname7, join as join18, resolve as resolve7 } from "node:path";
7618
7726
  import { parseHTML as parseHTML4 } from "linkedom";
7619
7727
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7620
7728
 
@@ -7683,10 +7791,10 @@ var Semaphore = class {
7683
7791
  this.active++;
7684
7792
  return () => this.release();
7685
7793
  }
7686
- return new Promise((resolve11) => {
7794
+ return new Promise((resolve12) => {
7687
7795
  this.queue.push(() => {
7688
7796
  this.active++;
7689
- resolve11(() => this.release());
7797
+ resolve12(() => this.release());
7690
7798
  });
7691
7799
  });
7692
7800
  }
@@ -7884,12 +7992,12 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
7884
7992
  rmSync10(inlinePath, { force: true });
7885
7993
  }
7886
7994
  }
7887
- if (resolve6(outputPath) !== resolve6(cachePath) && !isUsableFile2(outputPath)) {
7995
+ if (resolve7(outputPath) !== resolve7(cachePath) && !isUsableFile2(outputPath)) {
7888
7996
  copyFileSync3(cachePath, outputPath);
7889
7997
  }
7890
7998
  }
7891
7999
  async function prepareHeifImageInputs(html, options) {
7892
- const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_HEIF_SUBDIR);
8000
+ const outputDir = options.outputDir ?? join18(options.downloadDir, PREPARED_HEIF_SUBDIR);
7893
8001
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
7894
8002
  const cacheDir = options.cacheDir ?? outputDir;
7895
8003
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -7910,7 +8018,7 @@ async function prepareHeifImageInputs(html, options) {
7910
8018
  await Promise.all(
7911
8019
  [...unique].map(
7912
8020
  ([filename, source]) => withMediaProbeSlot(
7913
- () => ensurePreparedJpeg(source, join17(cacheDir, filename), join17(outputDir, filename), options)
8021
+ () => ensurePreparedJpeg(source, join18(cacheDir, filename), join18(outputDir, filename), options)
7914
8022
  ).catch((error) => {
7915
8023
  if (!options.onFailure) throw error;
7916
8024
  failed.add(filename);
@@ -7922,8 +8030,8 @@ async function prepareHeifImageInputs(html, options) {
7922
8030
  if (failed.has(filename)) continue;
7923
8031
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7924
8032
  img.setAttribute("src", outputSrc);
7925
- preparedAssets.set(outputSrc, join17(outputDir, filename));
7926
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join17(outputDir, filename) });
8033
+ preparedAssets.set(outputSrc, join18(outputDir, filename));
8034
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join18(outputDir, filename) });
7927
8035
  }
7928
8036
  return { html: document2.toString(), preparedAssets, preparedImages };
7929
8037
  }
@@ -7933,8 +8041,8 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7933
8041
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7934
8042
 
7935
8043
  // src/services/assetMediaType.ts
7936
- import { existsSync as existsSync10 } from "node:fs";
7937
- import { dirname as dirname8, join as join18 } from "node:path";
8044
+ import { existsSync as existsSync11 } from "node:fs";
8045
+ import { dirname as dirname8, join as join19 } from "node:path";
7938
8046
  import {
7939
8047
  fingerprintElementId,
7940
8048
  isHttpUrl as isHttpUrl2,
@@ -7987,11 +8095,11 @@ function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
7987
8095
  ]);
7988
8096
  }
7989
8097
  function mediaAssetRoots(projectDir, compiledDir) {
7990
- return [projectDir, compiledDir, join18(dirname8(compiledDir), "downloads")];
8098
+ return [projectDir, compiledDir, join19(dirname8(compiledDir), "downloads")];
7991
8099
  }
7992
8100
  function dropMediaOutsideProject(input) {
7993
8101
  const { projectDir, workDir, composition, log } = input;
7994
- const compiledDir = join18(workDir, "compiled");
8102
+ const compiledDir = join19(workDir, "compiled");
7995
8103
  const roots = mediaAssetRoots(projectDir, compiledDir);
7996
8104
  const staysInside = ({ id, src }) => {
7997
8105
  if (!src || isHttpUrl2(src)) return true;
@@ -8046,7 +8154,7 @@ async function preflightCompositionAssetMediaTypes(input) {
8046
8154
  input.projectDir,
8047
8155
  input.compiledDir
8048
8156
  );
8049
- if (!existsSync10(resolvedPath)) continue;
8157
+ if (!existsSync11(resolvedPath)) continue;
8050
8158
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
8051
8159
  }
8052
8160
  const mismatches = [];
@@ -8137,7 +8245,7 @@ function normalizeCompositionSrcs(html, projectDir) {
8137
8245
  if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
8138
8246
  const file = resolveCompositionSrc(projectDir, value);
8139
8247
  if (file === null) return whole;
8140
- return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
8248
+ return `${name}${quote}${relative3(projectDir, file).split(sep4).join("/")}${quote}`;
8141
8249
  });
8142
8250
  }
8143
8251
  var COMPOSITION_FILE = /\.html?$/i;
@@ -8342,8 +8450,8 @@ function detectShaderTransitionUsage(html) {
8342
8450
  async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
8343
8451
  let filePath = src;
8344
8452
  if (isHttpUrl(src)) {
8345
- const remoteDir = join19(downloadDir, REMOTE_MEDIA_SUBDIR);
8346
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8453
+ const remoteDir = join20(downloadDir, REMOTE_MEDIA_SUBDIR);
8454
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8347
8455
  try {
8348
8456
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8349
8457
  onTelemetry: logRemoteDownloadTelemetry
@@ -8353,7 +8461,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8353
8461
  }
8354
8462
  } else {
8355
8463
  filePath = decodedUrlPath(src);
8356
- if (!filePath.startsWith("/")) filePath = join19(baseDir, filePath);
8464
+ if (!filePath.startsWith("/")) filePath = join20(baseDir, filePath);
8357
8465
  if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir, downloadDir])) {
8358
8466
  return { duration: null, resolvedPath: filePath };
8359
8467
  }
@@ -8362,7 +8470,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8362
8470
  return { duration: null, resolvedPath: filePath };
8363
8471
  }
8364
8472
  }
8365
- if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
8473
+ if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
8366
8474
  return { duration: null, resolvedPath: filePath };
8367
8475
  }
8368
8476
  const withSrcContext = (error) => {
@@ -8682,7 +8790,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8682
8790
  }
8683
8791
  return document2.toString();
8684
8792
  }
8685
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8793
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
8686
8794
  const { document: document2 } = parseHTML5(html);
8687
8795
  const head = document2.querySelector("head");
8688
8796
  const body = document2.querySelector("body");
@@ -8691,11 +8799,11 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8691
8799
  const emitted = emitRootCompositionVariableStyles(
8692
8800
  document2,
8693
8801
  {},
8694
- variableOverrides
8802
+ variableOverrides,
8803
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8695
8804
  );
8696
8805
  return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8697
8806
  }
8698
- const budget = new CompositionExpansionBudget();
8699
8807
  const readOnce = /* @__PURE__ */ new Map();
8700
8808
  const readMountHtml = (srcPath) => {
8701
8809
  const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
@@ -8730,6 +8838,10 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8730
8838
  hostIdentityMap: hostIdentityByElement,
8731
8839
  readVariableDefaults: readDeclaredDefaults,
8732
8840
  parseHostVariables: parseHostVariableValues,
8841
+ resolveFilePath: (srcPath) => {
8842
+ const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
8843
+ return file && relative3(projectDir, file).split(sep4).join("/");
8844
+ },
8733
8845
  resolveHtml: (srcPath) => {
8734
8846
  const compHtml = resolveMountHtml(srcPath);
8735
8847
  if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
@@ -8820,7 +8932,8 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8820
8932
  emitRootCompositionVariableStyles(
8821
8933
  document2,
8822
8934
  result.variablesByComp,
8823
- variableOverrides
8935
+ variableOverrides,
8936
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
8824
8937
  );
8825
8938
  assignMediaRenderIds(document2);
8826
8939
  return { html: document2.toString(), variablesByComp: result.variablesByComp };
@@ -8891,7 +9004,8 @@ async function downloadScript(src, mirror) {
8891
9004
  }
8892
9005
  return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3 });
8893
9006
  }
8894
- async function inlineExternalScripts(html) {
9007
+ var MAX_CONCURRENT_SCRIPT_FETCHES = 4;
9008
+ async function inlineExternalScripts(html, budget = new CompositionExpansionBudget()) {
8895
9009
  const fullHtml = ensureFullDocument(html);
8896
9010
  const wrappedFragment = fullHtml !== html;
8897
9011
  const { document: document2 } = parseHTML5(fullHtml);
@@ -8905,20 +9019,52 @@ async function inlineExternalScripts(html) {
8905
9019
  }
8906
9020
  if (externalScripts.length === 0) return html;
8907
9021
  const mirror = operatorGsapMirror();
9022
+ const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
9023
+ const stop = new AbortController();
9024
+ const fail = (error) => {
9025
+ stop.abort(error);
9026
+ throw error;
9027
+ };
9028
+ const charge = (bytes) => {
9029
+ try {
9030
+ budget.chargeGenerated(REMOTE_SCRIPTS, bytes);
9031
+ } catch (error) {
9032
+ fail(error);
9033
+ }
9034
+ };
9035
+ const fetches = /* @__PURE__ */ new Map();
9036
+ const fetchOnce = (src) => {
9037
+ let bytes = fetches.get(src);
9038
+ if (!bytes) {
9039
+ bytes = limit(async () => {
9040
+ if (stop.signal.aborted) throw stop.signal.reason;
9041
+ const downloaded = await downloadScript(src, mirror);
9042
+ charge(downloaded.byteLength);
9043
+ return downloaded;
9044
+ }, stop.signal);
9045
+ fetches.set(src, bytes);
9046
+ }
9047
+ return bytes;
9048
+ };
9049
+ const placed = /* @__PURE__ */ new Set();
8908
9050
  const downloads = await Promise.allSettled(
8909
9051
  externalScripts.map(async ({ el, src }) => {
8910
9052
  const integrity = el.getAttribute("integrity") || "";
8911
- const bundled = bundledScript(src);
8912
- if (bundled && matchesScriptIntegrity(bundled, integrity)) {
8913
- return { src, text: new TextDecoder().decode(bundled) };
8914
- }
8915
- const bytes = await downloadScript(src, mirror);
8916
- if (!matchesScriptIntegrity(bytes, integrity)) {
8917
- throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
9053
+ let bytes = bundledScript(src);
9054
+ if (bytes && matchesScriptIntegrity(bytes, integrity)) {
9055
+ charge(bytes.byteLength);
9056
+ } else {
9057
+ bytes = await fetchOnce(src);
9058
+ if (!matchesScriptIntegrity(bytes, integrity)) {
9059
+ fail(new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`));
9060
+ }
9061
+ if (placed.has(src)) charge(bytes.byteLength);
9062
+ placed.add(src);
8918
9063
  }
8919
9064
  return { src, text: new TextDecoder().decode(bytes) };
8920
9065
  })
8921
9066
  );
9067
+ if (stop.signal.aborted) throw stop.signal.reason;
8922
9068
  for (let i = 0; i < downloads.length; i++) {
8923
9069
  const download = downloads[i];
8924
9070
  const { el, src } = externalScripts[i];
@@ -8945,18 +9091,18 @@ ${safeText}
8945
9091
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8946
9092
  }
8947
9093
  function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8948
- const absProjectDir = resolve7(projectDir);
9094
+ const absProjectDir = resolve8(projectDir);
8949
9095
  const externalAssets = /* @__PURE__ */ new Map();
8950
9096
  const leftOut = /* @__PURE__ */ new Set();
8951
9097
  function processPath(rawPath) {
8952
9098
  const trimmed = rawPath.trim();
8953
9099
  if (isNonRelativeUrl(trimmed)) return null;
8954
- const absPath = resolve7(absProjectDir, trimmed);
9100
+ const absPath = resolve8(absProjectDir, trimmed);
8955
9101
  if (isPathInside(absPath, absProjectDir)) {
8956
9102
  return null;
8957
9103
  }
8958
9104
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8959
- if (!onShare && !existsSync11(absPath)) return null;
9105
+ if (!onShare && !existsSync12(absPath)) return null;
8960
9106
  const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8961
9107
  if (refusal) {
8962
9108
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
@@ -9009,7 +9155,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9009
9155
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9010
9156
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9011
9157
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9012
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9158
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9013
9159
  const urlToLocal = /* @__PURE__ */ new Map();
9014
9160
  await Promise.all(
9015
9161
  [...urlSet].map(async (url) => {
@@ -9032,7 +9178,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9032
9178
  const remoteMediaAssets = /* @__PURE__ */ new Map();
9033
9179
  const urlToRelPath = /* @__PURE__ */ new Map();
9034
9180
  for (const [url, absPath] of urlToLocal) {
9035
- const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename5(absPath)}`;
9181
+ const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename6(absPath)}`;
9036
9182
  remoteMediaAssets.set(relPath, absPath);
9037
9183
  urlToRelPath.set(url, relPath);
9038
9184
  }
@@ -9049,7 +9195,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
9049
9195
  const localized = await downloadAndRewriteUrls(
9050
9196
  urlSet,
9051
9197
  html,
9052
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9198
+ join20(downloadDir, REMOTE_MEDIA_SUBDIR),
9053
9199
  "Remote media download failed",
9054
9200
  "Localized remote media source(s)"
9055
9201
  );
@@ -9072,7 +9218,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
9072
9218
  return downloadAndRewriteUrls(
9073
9219
  urlSet,
9074
9220
  html,
9075
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9221
+ join20(downloadDir, REMOTE_MEDIA_SUBDIR),
9076
9222
  "Remote image download failed",
9077
9223
  "Localized remote image source(s)"
9078
9224
  );
@@ -9085,7 +9231,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
9085
9231
  return downloadAndRewriteUrls(
9086
9232
  urlSet,
9087
9233
  html,
9088
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9234
+ join20(downloadDir, REMOTE_MEDIA_SUBDIR),
9089
9235
  "Remote background-image download failed",
9090
9236
  "Localized remote background-image(s)",
9091
9237
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -9142,48 +9288,50 @@ function matchingBraces(css) {
9142
9288
  }
9143
9289
  return closes;
9144
9290
  }
9145
- async function inlineExternalFontStylesheets(html) {
9146
- const hrefRe = /\bhref=["']([^"']+)["']/i;
9147
- const linkMatches = [];
9291
+ function remoteFontStylesheetHref(tag) {
9292
+ const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9293
+ if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9294
+ return href;
9295
+ }
9296
+ async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget()) {
9297
+ const hrefs = /* @__PURE__ */ new Set();
9148
9298
  for (const { parts } of stylesheetLinkMatches(html)) {
9149
- const tag = parts[0];
9150
- const hrefMatch = hrefRe.exec(tag);
9151
- if (!hrefMatch?.[1]) continue;
9152
- const href = hrefMatch[1];
9153
- if (!/^https?:\/\//i.test(href)) continue;
9154
- if (isGoogleFontsUrl(href)) continue;
9155
- linkMatches.push({ fullMatch: tag, href });
9156
- }
9157
- if (linkMatches.length === 0) return html;
9158
- const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9159
- const fetches = [];
9160
- for (let i = 0; i < linkMatches.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9161
- const batch = linkMatches.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9162
- const results = await Promise.all(
9163
- batch.map(async ({ fullMatch, href }) => {
9164
- const css = await fetchExternalStylesheetCss(href);
9165
- return { fullMatch, href, css };
9166
- })
9167
- );
9168
- fetches.push(...results);
9299
+ const href = remoteFontStylesheetHref(parts[0]);
9300
+ if (href) hrefs.add(href);
9169
9301
  }
9170
- let result = html;
9171
- for (const { fullMatch, href, css } of fetches) {
9172
- if (css === null) continue;
9173
- const fontFaceBlocks = extractFontFaceBlocks(css);
9174
- if (fontFaceBlocks.length === 0) continue;
9175
- const identity = safeDownloadUrlIdentity(href);
9176
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9302
+ if (hrefs.size === 0) return html;
9303
+ const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9304
+ const inlineByHref = /* @__PURE__ */ new Map();
9305
+ const unique = [...hrefs];
9306
+ for (let i = 0; i < unique.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9307
+ const batch = unique.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9308
+ const sheets = await Promise.all(batch.map(fetchExternalStylesheetCss));
9309
+ batch.forEach((href, index) => {
9310
+ const css = sheets[index];
9311
+ const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9312
+ if (fontFaceBlocks.length === 0) return;
9313
+ const inlineStyle = `<style>/* Inlined external font stylesheet */
9177
9314
  ${fontFaceBlocks.join("\n")}
9178
9315
  </style>`;
9179
- result = result.replace(fullMatch, inlineStyle);
9180
- defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9181
- count: fontFaceBlocks.length,
9182
- urlFingerprint: identity.urlFingerprint,
9183
- host: identity.host
9316
+ budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9317
+ inlineByHref.set(href, inlineStyle);
9318
+ const identity = safeDownloadUrlIdentity(href);
9319
+ defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9320
+ count: fontFaceBlocks.length,
9321
+ urlFingerprint: identity.urlFingerprint,
9322
+ host: identity.host
9323
+ });
9184
9324
  });
9185
9325
  }
9186
- return result;
9326
+ const placed = /* @__PURE__ */ new Set();
9327
+ return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9328
+ const href = remoteFontStylesheetHref(tag);
9329
+ const inlineStyle = href ? inlineByHref.get(href) : void 0;
9330
+ if (!href || !inlineStyle) return tag;
9331
+ if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9332
+ placed.add(href);
9333
+ return inlineStyle;
9334
+ });
9187
9335
  }
9188
9336
  function projectStylesheetFontFamilies(html, projectDir) {
9189
9337
  const families = [];
@@ -9192,14 +9340,14 @@ function projectStylesheetFontFamilies(html, projectDir) {
9192
9340
  } of stylesheetLinkMatches(html)) {
9193
9341
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9194
9342
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
9195
- const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9196
- if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
9343
+ const sheet = resolve8(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9344
+ if (!isPathInside(sheet, projectDir) || !existsSync12(sheet)) continue;
9197
9345
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
9198
9346
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
9199
9347
  const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
9200
9348
  const path = decodedUrlPath(url);
9201
- const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname9(sheet), path);
9202
- return isPathInside(file, projectDir) && existsSync11(file);
9349
+ const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname9(sheet), path);
9350
+ return isPathInside(file, projectDir) && existsSync12(file);
9203
9351
  });
9204
9352
  if (family && shipsFile) families.push(family);
9205
9353
  }
@@ -9236,16 +9384,12 @@ function localizeFontFaceUrls(html, downloadDir) {
9236
9384
  return downloadAndRewriteUrls(
9237
9385
  collectFontFaceUrls(html),
9238
9386
  html,
9239
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9387
+ join20(downloadDir, REMOTE_MEDIA_SUBDIR),
9240
9388
  "Remote font download failed",
9241
9389
  "Localized remote font face(s)",
9242
9390
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9243
9391
  );
9244
9392
  }
9245
- function urlOccurrenceRe(localPath) {
9246
- const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9247
- return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
9248
- }
9249
9393
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
9250
9394
  async function readLocalFont(absPath) {
9251
9395
  const chunks = [];
@@ -9260,59 +9404,83 @@ async function readLocalFont(absPath) {
9260
9404
  }
9261
9405
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9262
9406
  }
9263
- async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
9264
- const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
9265
- let result = html;
9266
- const embeddedPaths = /* @__PURE__ */ new Set();
9407
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9408
+ const absPath = localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath);
9409
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9410
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9411
+ return void 0;
9412
+ }
9413
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9414
+ if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
9415
+ const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9416
+ try {
9417
+ const font = await readLocalFont(absPath);
9418
+ if (font.kind === "file-backed") {
9419
+ dataUriByAbsolutePath.set(absPath, void 0);
9420
+ defaultLogger.debug(
9421
+ `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9422
+ );
9423
+ return void 0;
9424
+ }
9425
+ const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
9426
+ const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
9427
+ dataUriByAbsolutePath.set(absPath, dataUri);
9428
+ defaultLogger.debug(
9429
+ `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9430
+ );
9431
+ return dataUri;
9432
+ } catch (error) {
9433
+ defaultLogger.warn(
9434
+ `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9435
+ );
9436
+ return void 0;
9437
+ }
9438
+ }
9439
+ var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
9440
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
9441
+ const dataUriByPath = /* @__PURE__ */ new Map();
9267
9442
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
9268
- const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
9269
9443
  for (const { parts: style } of styleBlockMatches(html)) {
9270
9444
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
9271
- const block = face[1];
9272
- for (const { parts } of localFontFaceUrlMatches(block)) {
9445
+ for (const { parts } of localFontFaceUrlMatches(face[1])) {
9273
9446
  const localPath = parts[1];
9274
- if (!localPath || embeddedPaths.has(localPath)) continue;
9275
- const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9276
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
9277
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9278
- embeddedPaths.add(localPath);
9279
- continue;
9280
- }
9281
- if (isPrivateCompositionFile(projectDir, absPath)) continue;
9282
- const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9283
- try {
9284
- if (fileBackedAbsolutePaths.has(absPath)) {
9285
- embeddedPaths.add(localPath);
9286
- continue;
9287
- }
9288
- let dataUri = dataUriByAbsolutePath.get(absPath);
9289
- if (!dataUri) {
9290
- const font = await readLocalFont(absPath);
9291
- if (font.kind === "file-backed") {
9292
- fileBackedAbsolutePaths.add(absPath);
9293
- defaultLogger.debug(
9294
- `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
9295
- );
9296
- embeddedPaths.add(localPath);
9297
- continue;
9298
- }
9299
- dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
9300
- dataUriByAbsolutePath.set(absPath, dataUri);
9301
- defaultLogger.debug(
9302
- `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
9303
- );
9304
- }
9305
- result = result.replace(urlOccurrenceRe(localPath), `url("${dataUri}")`);
9306
- embeddedPaths.add(localPath);
9307
- } catch (error) {
9308
- defaultLogger.warn(
9309
- `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
9310
- );
9311
- }
9447
+ if (!localPath || dataUriByPath.has(localPath)) continue;
9448
+ dataUriByPath.set(
9449
+ localPath,
9450
+ await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
9451
+ );
9312
9452
  }
9313
9453
  }
9314
9454
  }
9315
- return result;
9455
+ if (![...dataUriByPath.values()].some(Boolean)) return html;
9456
+ let warned = false;
9457
+ const embed = (source, localPath) => {
9458
+ const dataUri = dataUriByPath.get(localPath);
9459
+ if (!dataUri) return source;
9460
+ const inlined = `url("${dataUri}")`;
9461
+ if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
9462
+ if (!warned) {
9463
+ warned = true;
9464
+ log.warn(
9465
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9466
+ );
9467
+ }
9468
+ return source;
9469
+ };
9470
+ return replaceMatches(
9471
+ html,
9472
+ styleBlockMatches(html),
9473
+ (style, css) => replaceInner(
9474
+ style,
9475
+ css,
9476
+ "</style>".length,
9477
+ replaceMatches(
9478
+ css,
9479
+ fontFaceBlockMatches(css),
9480
+ (face, body) => replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed))
9481
+ )
9482
+ )
9483
+ );
9316
9484
  }
9317
9485
  function renderGsapDist() {
9318
9486
  try {
@@ -9327,8 +9495,8 @@ function renderGsapDist() {
9327
9495
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9328
9496
  let gsapDist;
9329
9497
  const exists = (path) => {
9330
- const file = resolve7(projectDir, path);
9331
- return !namesAnotherNetworkRoot2(projectDir, file) && existsSync11(file);
9498
+ const file = resolve8(projectDir, path);
9499
+ return !namesAnotherNetworkRoot2(projectDir, file) && existsSync12(file);
9332
9500
  };
9333
9501
  return replaceGsapDistScripts(html, (full, prefix, src, file, suffix) => {
9334
9502
  if (/^https?:\/\//i.test(src)) return full;
@@ -9338,32 +9506,42 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9338
9506
  return `${prefix}${gsapDist}${file}${suffix}`;
9339
9507
  });
9340
9508
  }
9341
- function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9509
+ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9342
9510
  if (!isPathInside(htmlPath, projectDir)) return html;
9343
- const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9511
+ const entryPath = relative3(projectDir, htmlPath).replace(/\\/g, "/");
9344
9512
  if (!entryPath.includes("/")) return html;
9345
9513
  const { document: document2 } = parseHTML5(html);
9346
9514
  const assetExists = projectAssetExists(projectDir);
9515
+ const charge = (bytes) => budget.chargeGenerated(entryPath, bytes);
9347
9516
  rewriteAssetPaths(
9348
9517
  document2.querySelectorAll("[src], [href], [srcset]"),
9349
9518
  entryPath,
9350
9519
  (el, attr) => el.getAttribute(attr),
9351
9520
  (el, attr, value) => el.setAttribute(attr, value),
9352
- assetExists
9521
+ assetExists,
9522
+ charge
9353
9523
  );
9354
9524
  rewriteInlineStyleAssetUrls(
9355
9525
  document2.querySelectorAll("[style]"),
9356
9526
  entryPath,
9357
9527
  (el) => el.getAttribute("style"),
9358
9528
  (el, value) => el.setAttribute("style", value),
9359
- assetExists
9529
+ assetExists,
9530
+ charge
9360
9531
  );
9361
9532
  for (const style of document2.querySelectorAll("style")) {
9362
- style.textContent = rewriteCssAssetUrls(style.textContent || "", entryPath, assetExists);
9533
+ style.textContent = rewriteCssAssetUrls(
9534
+ style.textContent || "",
9535
+ entryPath,
9536
+ assetExists,
9537
+ charge
9538
+ );
9363
9539
  }
9364
9540
  return document2.toString();
9365
9541
  }
9366
- function bindVariableMediaSources(html, variables) {
9542
+ var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
9543
+ var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
9544
+ function bindVariableMediaSources(html, variables, budget, log) {
9367
9545
  if (!html.includes("data-var-src")) return html;
9368
9546
  const { document: document2 } = parseHTML5(html);
9369
9547
  const declared = {};
@@ -9374,14 +9552,23 @@ function bindVariableMediaSources(html, variables) {
9374
9552
  let changed = false;
9375
9553
  for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
9376
9554
  if (el.closest("[data-variable-values]")) continue;
9377
- const src = boundMediaSrc(el, values);
9378
- if (src === null || el.getAttribute("src") === src) continue;
9555
+ const bound = boundMediaSrc(el, values);
9556
+ if (bound === null) continue;
9557
+ const src = bound.trim();
9558
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
9559
+ log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
9560
+ length: src.length
9561
+ });
9562
+ continue;
9563
+ }
9564
+ if (el.getAttribute("src") === src) continue;
9565
+ budget.chargeGenerated("variable media sources", src.length);
9379
9566
  el.setAttribute("src", src);
9380
9567
  changed = true;
9381
9568
  }
9382
9569
  return changed ? document2.toString() : html;
9383
9570
  }
9384
- var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9571
+ var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative3(projectDir, htmlPath).split(sep4).join("/") : basename6(htmlPath);
9385
9572
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9386
9573
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9387
9574
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
@@ -9394,11 +9581,19 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9394
9581
  if (!COMPOSITION_FILE.test(htmlPath)) {
9395
9582
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9396
9583
  }
9397
- assertCompositionFileSize(htmlPath, basename5(htmlPath));
9398
- const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9584
+ assertCompositionFileSize(htmlPath, basename6(htmlPath));
9585
+ const budget = new CompositionExpansionBudget();
9586
+ const entryHtml = rebaseDirectEntryAssetPaths(
9587
+ readTextFile(htmlPath),
9588
+ projectDir,
9589
+ htmlPath,
9590
+ budget
9591
+ );
9399
9592
  const rawHtml = bindVariableMediaSources(
9400
9593
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9401
- options.variables ?? {}
9594
+ options.variables ?? {},
9595
+ budget,
9596
+ options.log
9402
9597
  );
9403
9598
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9404
9599
  const probes = /* @__PURE__ */ new Map();
@@ -9429,7 +9624,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9429
9624
  projectDir,
9430
9625
  options.variables ?? {},
9431
9626
  assetRoot,
9432
- outsideFiles
9627
+ outsideFiles,
9628
+ budget
9433
9629
  );
9434
9630
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9435
9631
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9437,7 +9633,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9437
9633
  const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
9438
9634
  const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
9439
9635
  const fontSheetHtml = await inlineExternalFontStylesheets(
9440
- promoteCssImportsToLinkTags(sanitizedHtml)
9636
+ promoteCssImportsToLinkTags(sanitizedHtml),
9637
+ budget
9441
9638
  );
9442
9639
  const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
9443
9640
  injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml))
@@ -9449,7 +9646,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9449
9646
  projectFontFamilies: projectStylesheetFontFamilies(fontSheetHtml, projectDir),
9450
9647
  abortSignal: options.abortSignal
9451
9648
  });
9452
- const assembledHtml = await inlineExternalScripts(coalescedHtml);
9649
+ const assembledHtml = await inlineExternalScripts(coalescedHtml, budget);
9453
9650
  const HF_POSITION_ATTRS = [
9454
9651
  'data-hf-studio-path-offset="true"',
9455
9652
  'data-hf-studio-box-size="true"',
@@ -9508,6 +9705,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9508
9705
  htmlWithPreparedGifs,
9509
9706
  projectDir,
9510
9707
  assetRoot,
9708
+ budget,
9511
9709
  options.log
9512
9710
  );
9513
9711
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
@@ -9540,8 +9738,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9540
9738
  const advised = /* @__PURE__ */ new Set();
9541
9739
  for (const video of videos) {
9542
9740
  if (isHttpUrl(video.src)) continue;
9543
- const videoPath = resolve7(projectDir, video.src);
9544
- if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9741
+ const videoPath = resolve8(projectDir, video.src);
9742
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync12(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9545
9743
  continue;
9546
9744
  advised.add(videoPath);
9547
9745
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
@@ -9956,7 +10154,7 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9956
10154
  function animatedGifCacheDir(extractCacheDir) {
9957
10155
  try {
9958
10156
  const root = extractCacheDir && privateCacheRoot(extractCacheDir);
9959
- return root ? join20(root, "animated-gif") : void 0;
10157
+ return root ? join21(root, "animated-gif") : void 0;
9960
10158
  } catch {
9961
10159
  return void 0;
9962
10160
  }
@@ -9978,17 +10176,17 @@ function resolveEntryHtmlPath(input) {
9978
10176
  const readEntry = (path) => {
9979
10177
  if (escapesAssetRoot(path, input.assetRoot)) {
9980
10178
  throw new Error(
9981
- `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
10179
+ `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
9982
10180
  );
9983
10181
  }
9984
- assertCompositionFileSize(path, relative3(projectDir, path));
10182
+ assertCompositionFileSize(path, relative4(projectDir, path));
9985
10183
  return readTextFile2(path);
9986
10184
  };
9987
- const htmlPath = join20(projectDir, entryFile);
10185
+ const htmlPath = join21(projectDir, entryFile);
9988
10186
  const rawEntry = readEntry(htmlPath);
9989
10187
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
9990
- const projectIndexPath = join20(projectDir, "index.html");
9991
- if (!existsSync12(projectIndexPath)) {
10188
+ const projectIndexPath = join21(projectDir, "index.html");
10189
+ if (!existsSync13(projectIndexPath)) {
9992
10190
  throw new Error(
9993
10191
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
9994
10192
  );
@@ -10003,7 +10201,7 @@ function resolveEntryHtmlPath(input) {
10003
10201
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
10004
10202
  );
10005
10203
  }
10006
- const wrapperPath = join20(workDir, "standalone-entry.html");
10204
+ const wrapperPath = join21(workDir, "standalone-entry.html");
10007
10205
  writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
10008
10206
  log.info("Extracted standalone entry from index.html host context", { entryFile });
10009
10207
  return wrapperPath;
@@ -10033,7 +10231,7 @@ async function runCompileStage(input) {
10033
10231
  const assetRoot = job.config.allowOutsideProjectAssets ? void 0 : projectDir;
10034
10232
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log, assetRoot });
10035
10233
  const compileStart = Date.now();
10036
- const compiled = await compileForRender(projectDir, htmlPath, join20(workDir, "downloads"), {
10234
+ const compiled = await compileForRender(projectDir, htmlPath, join21(workDir, "downloads"), {
10037
10235
  log,
10038
10236
  failClosedFontFetch: failClosedFontFetch === true,
10039
10237
  allowSystemFontCapture,
@@ -10108,7 +10306,7 @@ async function runCompileStage(input) {
10108
10306
  });
10109
10307
  await preflightCompositionAssetMediaTypes({
10110
10308
  projectDir,
10111
- compiledDir: join20(workDir, "compiled"),
10309
+ compiledDir: join21(workDir, "compiled"),
10112
10310
  composition,
10113
10311
  signal: abortSignal
10114
10312
  });
@@ -10156,7 +10354,7 @@ async function runCompileStage(input) {
10156
10354
 
10157
10355
  // src/services/render/stages/probeStage.ts
10158
10356
  import { createHash as createHash7 } from "node:crypto";
10159
- import { basename as basename6, join as join21 } from "node:path";
10357
+ import { basename as basename7, join as join22 } from "node:path";
10160
10358
  import { parseHTML as parseHTML6 } from "linkedom";
10161
10359
  import {
10162
10360
  closeCaptureSession as closeCaptureSession4,
@@ -10404,7 +10602,7 @@ function probeRequiresBrowser(args) {
10404
10602
  function reportedLengthSource(source) {
10405
10603
  if (!source) return null;
10406
10604
  if (source.from !== "media") return { from: source.from };
10407
- const name = basename6(source.src.split(/[?#]/, 1)[0] ?? "");
10605
+ const name = basename7(source.src.split(/[?#]/, 1)[0] ?? "");
10408
10606
  const srcHash = createHash7("sha256").update(name).digest("hex").slice(0, 12);
10409
10607
  return { from: "media", tag: source.tag, trimmed: source.trimmed, srcHash };
10410
10608
  }
@@ -10470,7 +10668,7 @@ async function runProbeStage(input) {
10470
10668
  });
10471
10669
  fileServer = await createFileServer({
10472
10670
  projectDir,
10473
- compiledDir: join21(workDir, "compiled"),
10671
+ compiledDir: join22(workDir, "compiled"),
10474
10672
  port: 0,
10475
10673
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10476
10674
  fps: job.config.fps,
@@ -10507,7 +10705,7 @@ async function runProbeStage(input) {
10507
10705
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
10508
10706
  probeSession = await createCaptureSession4(
10509
10707
  fileServer.url,
10510
- join21(workDir, "probe"),
10708
+ join22(workDir, "probe"),
10511
10709
  captureOpts,
10512
10710
  null,
10513
10711
  probeCfg
@@ -10592,7 +10790,7 @@ async function runProbeStage(input) {
10592
10790
  });
10593
10791
  probeSession = await createCaptureSession4(
10594
10792
  fileServer.url,
10595
- join21(workDir, "probe-screenshot"),
10793
+ join22(workDir, "probe-screenshot"),
10596
10794
  captureOpts,
10597
10795
  null,
10598
10796
  { ...probeCfg, forceScreenshot: true }
@@ -10630,7 +10828,7 @@ async function runProbeStage(input) {
10630
10828
  compiled,
10631
10829
  resolutions,
10632
10830
  projectDir,
10633
- join21(workDir, "downloads"),
10831
+ join22(workDir, "downloads"),
10634
10832
  job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10635
10833
  { includeScripts: job.config.includeOutsideScripts }
10636
10834
  );
@@ -10830,7 +11028,7 @@ async function runProbeStage(input) {
10830
11028
  });
10831
11029
  await preflightCompositionAssetMediaTypes({
10832
11030
  projectDir,
10833
- compiledDir: join21(workDir, "compiled"),
11031
+ compiledDir: join22(workDir, "compiled"),
10834
11032
  composition,
10835
11033
  signal: abortSignal
10836
11034
  });
@@ -10965,8 +11163,8 @@ function validateRenderDuration(input) {
10965
11163
  }
10966
11164
 
10967
11165
  // src/services/render/stages/extractVideosStage.ts
10968
- import { existsSync as existsSync13 } from "node:fs";
10969
- import { join as join22 } from "node:path";
11166
+ import { existsSync as existsSync14 } from "node:fs";
11167
+ import { join as join23 } from "node:path";
10970
11168
  import {
10971
11169
  classifyVideoExtractionError,
10972
11170
  createFrameLookupTable as createFrameLookupTable3,
@@ -11325,7 +11523,7 @@ async function runExtractVideosStage(input) {
11325
11523
  // because short boundary counts can differ by one frame.
11326
11524
  {
11327
11525
  fps: job.config.fps,
11328
- outputDir: join22(compiledDir, "__hyperframes_video_frames"),
11526
+ outputDir: join23(compiledDir, "__hyperframes_video_frames"),
11329
11527
  format: job.config.videoFrameFormat ?? "auto",
11330
11528
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
11331
11529
  timelineEnd: composition.duration,
@@ -11333,7 +11531,7 @@ async function runExtractVideosStage(input) {
11333
11531
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
11334
11532
  deferRangeExtraction,
11335
11533
  shownBoxes,
11336
- contentKeyedDirs: [join22(compiledDir, REMOTE_MEDIA_SUBDIR)],
11534
+ contentKeyedDirs: [join23(compiledDir, REMOTE_MEDIA_SUBDIR)],
11337
11535
  urlByAbsentLocalPath,
11338
11536
  assetRoots,
11339
11537
  onProgress: ({ planned = 0, done = 0 }) => {
@@ -11413,7 +11611,7 @@ function isPublicHttpsUrl(url) {
11413
11611
  }
11414
11612
  }
11415
11613
  function opensLocally(path, assetRoots) {
11416
- return existsSync13(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11614
+ return existsSync14(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11417
11615
  }
11418
11616
  function localProbeSource(src, input) {
11419
11617
  const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
@@ -11425,7 +11623,7 @@ async function remoteProbeSource(video, input) {
11425
11623
  if (!isPublicHttpsUrl(video.src)) return null;
11426
11624
  if (!resolveRestrictPageNetwork()) return video.src;
11427
11625
  if (!video.hasAudio || video.hidden) return null;
11428
- const downloadDir = input.downloadDir ?? join22(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11626
+ const downloadDir = input.downloadDir ?? join23(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11429
11627
  try {
11430
11628
  return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
11431
11629
  onTelemetry: writeUrlDownloadTelemetry2
@@ -11466,7 +11664,7 @@ async function appendVideoAudioFromProbe(input) {
11466
11664
  }
11467
11665
 
11468
11666
  // src/services/render/videoLayerPassthroughPlan.ts
11469
- import { existsSync as existsSync14 } from "node:fs";
11667
+ import { existsSync as existsSync15 } from "node:fs";
11470
11668
  import {
11471
11669
  buildVideoLayerInput,
11472
11670
  isHttpUrl as isHttpUrl4,
@@ -11534,7 +11732,7 @@ async function planVideoLayerPassthrough(input) {
11534
11732
  const { video } = q;
11535
11733
  if (isHttpUrl4(video.src)) return { reason: "remote_source" };
11536
11734
  const path = resolveProjectRelativeSrc5(video.src, input.projectDir, input.compiledDir);
11537
- if (!existsSync14(path)) return { reason: "source_missing" };
11735
+ if (!existsSync15(path)) return { reason: "source_missing" };
11538
11736
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
11539
11737
  if ("reason" in layout) return layout;
11540
11738
  const layer = await buildVideoLayerInput(
@@ -11549,8 +11747,8 @@ async function planVideoLayerPassthrough(input) {
11549
11747
  }
11550
11748
 
11551
11749
  // src/services/render/stages/audioStage.ts
11552
- import { existsSync as existsSync16 } from "node:fs";
11553
- import { join as join25 } from "node:path";
11750
+ import { existsSync as existsSync17 } from "node:fs";
11751
+ import { join as join26 } from "node:path";
11554
11752
  import {
11555
11753
  MIXED_AUDIO_FILENAME,
11556
11754
  audioFailureDiagnostics,
@@ -11561,8 +11759,8 @@ import {
11561
11759
  } from "@hyperframes/engine";
11562
11760
 
11563
11761
  // src/services/render/audioDeliveryLimit.ts
11564
- import { existsSync as existsSync15 } from "node:fs";
11565
- import { dirname as dirname11, join as join24 } from "node:path";
11762
+ import { existsSync as existsSync16 } from "node:fs";
11763
+ import { dirname as dirname11, join as join25 } from "node:path";
11566
11764
  import {
11567
11765
  applyAudioFxChain,
11568
11766
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -11572,7 +11770,7 @@ import {
11572
11770
 
11573
11771
  // src/services/render/audioPadTrim.ts
11574
11772
  import { spawn } from "node:child_process";
11575
- import { dirname as dirname10, join as join23 } from "node:path";
11773
+ import { dirname as dirname10, join as join24 } from "node:path";
11576
11774
  import {
11577
11775
  DEFAULT_CONFIG,
11578
11776
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -11853,7 +12051,7 @@ async function constrainAacTruePeak(input) {
11853
12051
  }
11854
12052
  async function cutSource(input, scratchDir, attenuationDb) {
11855
12053
  if (!input.sourcePath || !input.rewriteSource) return true;
11856
- const cutPath = join23(scratchDir, "source.wav");
12054
+ const cutPath = join24(scratchDir, "source.wav");
11857
12055
  try {
11858
12056
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
11859
12057
  if (!result.success) throw new Error(result.error);
@@ -11868,7 +12066,7 @@ async function enforceAacTruePeak(input) {
11868
12066
  let scratchDir;
11869
12067
  try {
11870
12068
  scratchDir = createStagingDir3(dirname10(input.audioPath), ".true-peak-");
11871
- const correctedPath = join23(scratchDir, "audio.m4a");
12069
+ const correctedPath = join24(scratchDir, "audio.m4a");
11872
12070
  const measurements = [];
11873
12071
  let attenuationDb = 0;
11874
12072
  let sourcePeakDbfs;
@@ -12081,14 +12279,14 @@ async function limitDeliveryPeaks(input, deps = {
12081
12279
  applyChain: applyAudioFxChain,
12082
12280
  encode: encodeAac2,
12083
12281
  rename: renameWithRetry6,
12084
- sourceExists: existsSync15
12282
+ sourceExists: existsSync16
12085
12283
  }) {
12086
12284
  const { audioPath, sourcePath, signal, timeoutMs } = input;
12087
12285
  if (!deps.sourceExists(sourcePath)) return { success: true };
12088
12286
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
12089
12287
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
12090
12288
  const alternating = ["a", "b"].map(
12091
- (k) => join24(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12289
+ (k) => join25(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12092
12290
  );
12093
12291
  let encodedFrom;
12094
12292
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -12161,7 +12359,7 @@ function runAudioStage(input) {
12161
12359
  }
12162
12360
  async function runAudioStageScoped(input) {
12163
12361
  const stageStart = Date.now();
12164
- const pcmSourcePath = join25(input.workDir, "audio-source.wav");
12362
+ const pcmSourcePath = join26(input.workDir, "audio-source.wav");
12165
12363
  const duration = input.totalFrames * input.fps.den / input.fps.num;
12166
12364
  let deliverySourcePath;
12167
12365
  try {
@@ -12177,7 +12375,7 @@ async function runAudioStageScoped(input) {
12177
12375
  );
12178
12376
  audioLoweredDb = guard.loweredDb;
12179
12377
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
12180
- if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
12378
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
12181
12379
  deliverySourcePath = pcmSourcePath;
12182
12380
  }
12183
12381
  }
@@ -12226,7 +12424,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12226
12424
  assertNotAborted,
12227
12425
  log
12228
12426
  } = input;
12229
- const audioOutputPath = join25(workDir, MIXED_AUDIO_FILENAME);
12427
+ const audioOutputPath = join26(workDir, MIXED_AUDIO_FILENAME);
12230
12428
  let hasAudio = false;
12231
12429
  let audioError;
12232
12430
  let audioFailures;
@@ -12306,8 +12504,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12306
12504
  }
12307
12505
 
12308
12506
  // src/services/render/stages/captureStage.ts
12309
- import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12310
- import { join as join26 } from "node:path";
12507
+ import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12508
+ import { join as join27 } from "node:path";
12311
12509
  import {
12312
12510
  classifyCaptureFailure as classifyCaptureFailure2,
12313
12511
  frameFileExtension,
@@ -12377,16 +12575,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
12377
12575
  }
12378
12576
  function measureCaptureFrameBytes(workDir, framesDir) {
12379
12577
  let total = sampleDirectoryBytes(framesDir);
12380
- if (!existsSync17(workDir)) return total;
12578
+ if (!existsSync18(workDir)) return total;
12381
12579
  for (const attempt of readdirSync4(workDir)) {
12382
12580
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
12383
- total += sampleDirectoryBytes(join26(workDir, attempt));
12581
+ total += sampleDirectoryBytes(join27(workDir, attempt));
12384
12582
  continue;
12385
12583
  }
12386
12584
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
12387
- const attemptDir = join26(workDir, attempt);
12585
+ const attemptDir = join27(workDir, attempt);
12388
12586
  for (const name of readdirSync4(attemptDir)) {
12389
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join26(attemptDir, name));
12587
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join27(attemptDir, name));
12390
12588
  }
12391
12589
  }
12392
12590
  return total;
@@ -12684,8 +12882,8 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
12684
12882
  }
12685
12883
 
12686
12884
  // src/services/render/stages/captureHdrStage.ts
12687
- import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
12688
- import { join as join30 } from "node:path";
12885
+ import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
12886
+ import { join as join31 } from "node:path";
12689
12887
  import {
12690
12888
  closeCaptureSession as closeCaptureSession7,
12691
12889
  cloneCaptureWarnings as cloneCaptureWarnings2,
@@ -12757,7 +12955,7 @@ function createHdrImageTransferCache(options = {}) {
12757
12955
  }
12758
12956
 
12759
12957
  // src/services/render/stages/captureHdrSequentialLoop.ts
12760
- import { join as join27 } from "node:path";
12958
+ import { join as join28 } from "node:path";
12761
12959
  import {
12762
12960
  TRANSITIONS,
12763
12961
  crossfade
@@ -12882,7 +13080,7 @@ async function runSequentialLayeredFrameLoop(input) {
12882
13080
  );
12883
13081
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
12884
13082
  writeFileExclusiveSync(
12885
- join27(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13083
+ join28(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12886
13084
  normalCanvas
12887
13085
  );
12888
13086
  }
@@ -12914,7 +13112,7 @@ async function runSequentialLayeredFrameLoop(input) {
12914
13112
  }
12915
13113
 
12916
13114
  // src/services/render/stages/captureHdrHybridLoop.ts
12917
- import { join as join29 } from "node:path";
13115
+ import { join as join30 } from "node:path";
12918
13116
  import {
12919
13117
  TRANSITIONS as TRANSITIONS2,
12920
13118
  closeCaptureSession as closeCaptureSession6,
@@ -12928,10 +13126,10 @@ import {
12928
13126
  // src/services/shaderTransitionWorkerPool.ts
12929
13127
  import { Worker } from "node:worker_threads";
12930
13128
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
12931
- import { dirname as dirname12, join as join28 } from "node:path";
13129
+ import { dirname as dirname12, join as join29 } from "node:path";
12932
13130
  import { createRequire } from "node:module";
12933
13131
  import { usableCpuCount } from "@hyperframes/engine";
12934
- import { existsSync as existsSync18 } from "node:fs";
13132
+ import { existsSync as existsSync19 } from "node:fs";
12935
13133
  function resolveWorkerEntry(explicit) {
12936
13134
  if (explicit && explicit.length > 0) {
12937
13135
  return { path: explicit, isTs: explicit.endsWith(".ts") };
@@ -12942,9 +13140,9 @@ function resolveWorkerEntry(explicit) {
12942
13140
  return { path: override, isTs };
12943
13141
  }
12944
13142
  const moduleDir = dirname12(fileURLToPath3(import.meta.url));
12945
- const jsPath = join28(moduleDir, "shaderTransitionWorker.js");
12946
- if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
12947
- const tsPath = join28(moduleDir, "shaderTransitionWorker.ts");
13143
+ const jsPath = join29(moduleDir, "shaderTransitionWorker.js");
13144
+ if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
13145
+ const tsPath = join29(moduleDir, "shaderTransitionWorker.ts");
12948
13146
  return { path: tsPath, isTs: true };
12949
13147
  }
12950
13148
  function buildExecArgv(entryIsTs) {
@@ -13087,8 +13285,8 @@ async function createShaderTransitionWorkerPool(opts) {
13087
13285
  if (terminated) {
13088
13286
  throw new Error("shader-blend pool already terminated");
13089
13287
  }
13090
- return new Promise((resolve11, reject) => {
13091
- const task = traceEnabled ? { req, resolve: resolve11, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve11, reject };
13288
+ return new Promise((resolve12, reject) => {
13289
+ const task = traceEnabled ? { req, resolve: resolve12, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve12, reject };
13092
13290
  const idle = slots.find((s) => !s.busy && !s.dead);
13093
13291
  if (idle) {
13094
13292
  queue.unshift(task);
@@ -13312,7 +13510,7 @@ async function runHybridLayeredFrameLoop(input) {
13312
13510
  );
13313
13511
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
13314
13512
  writeFileExclusiveSync(
13315
- join29(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13513
+ join30(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13316
13514
  canvas
13317
13515
  );
13318
13516
  }
@@ -13508,8 +13706,8 @@ async function runCaptureHdrStage(input) {
13508
13706
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
13509
13707
  }
13510
13708
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
13511
- const debugDumpDir = debugDumpEnabled ? join30(framesDir, "debug-composite") : null;
13512
- if (debugDumpDir && !existsSync19(debugDumpDir)) {
13709
+ const debugDumpDir = debugDumpEnabled ? join31(framesDir, "debug-composite") : null;
13710
+ if (debugDumpDir && !existsSync20(debugDumpDir)) {
13513
13711
  mkdirSync10(debugDumpDir, { recursive: true });
13514
13712
  }
13515
13713
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -13668,7 +13866,7 @@ async function runCaptureHdrStage(input) {
13668
13866
  // src/services/render/stages/encodeStage.ts
13669
13867
  import {
13670
13868
  copyFileSync as copyFileSync4,
13671
- existsSync as existsSync20,
13869
+ existsSync as existsSync21,
13672
13870
  mkdirSync as mkdirSync11,
13673
13871
  readdirSync as readdirSync5,
13674
13872
  readFileSync as readFileSync9,
@@ -13677,7 +13875,7 @@ import {
13677
13875
  writeFileSync as writeFileSync6
13678
13876
  } from "node:fs";
13679
13877
  import { readFile as readFile2 } from "node:fs/promises";
13680
- import { dirname as dirname13, join as join31 } from "node:path";
13878
+ import { dirname as dirname13, join as join32 } from "node:path";
13681
13879
  import {
13682
13880
  encodeFramesChunkedConcat,
13683
13881
  encodeFramesFromDir,
@@ -13802,7 +14000,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13802
14000
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13803
14001
  if (failure) return failure;
13804
14002
  }
13805
- const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
14003
+ const fileSize = existsSync21(outputPath) ? statSync10(outputPath).size : 0;
13806
14004
  return {
13807
14005
  success: true,
13808
14006
  outputPath,
@@ -13893,10 +14091,10 @@ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13893
14091
  const stream = await encoder;
13894
14092
  for (let next = 0; next < totalFrames; next++) {
13895
14093
  while (!landed.has(next) && !captureDone && !signal.aborted) {
13896
- await new Promise((resolve11) => wake = resolve11);
14094
+ await new Promise((resolve12) => wake = resolve12);
13897
14095
  }
13898
14096
  if (signal.aborted) return;
13899
- const mergedPath = join31(input.framesDir, formatCaptureFrameName(next, "jpg"));
14097
+ const mergedPath = join32(input.framesDir, formatCaptureFrameName(next, "jpg"));
13900
14098
  const frame = await readLandedFrame(landed.get(next), mergedPath);
13901
14099
  landed.delete(next);
13902
14100
  if (!await stream.writeFrame(frame)) {
@@ -13971,7 +14169,7 @@ async function runEncodeStage(input) {
13971
14169
  const stage5Start = Date.now();
13972
14170
  if (isPngSequence) {
13973
14171
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
13974
- if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
14172
+ if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
13975
14173
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
13976
14174
  if (captured.length === 0) {
13977
14175
  throw new Error(
@@ -13979,11 +14177,11 @@ async function runEncodeStage(input) {
13979
14177
  );
13980
14178
  }
13981
14179
  captured.forEach((name, i) => {
13982
- const dst = join31(outputPath, formatExportFrameName(i, "png"));
13983
- copyFileSync4(join31(framesDir, name), dst);
14180
+ const dst = join32(outputPath, formatExportFrameName(i, "png"));
14181
+ copyFileSync4(join32(framesDir, name), dst);
13984
14182
  });
13985
- if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
13986
- copyFileSync4(audioOutputPath, join31(outputPath, MIXED_AUDIO_FILENAME2));
14183
+ if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
14184
+ copyFileSync4(audioOutputPath, join32(outputPath, MIXED_AUDIO_FILENAME2));
13987
14185
  log.info(
13988
14186
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
13989
14187
  );
@@ -14003,7 +14201,7 @@ async function runEncodeStage(input) {
14003
14201
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
14004
14202
  fps: job.config.fps,
14005
14203
  loop,
14006
- palettePath: join31(dirname13(videoOnlyPath), "gif-palette.png"),
14204
+ palettePath: join32(dirname13(videoOnlyPath), "gif-palette.png"),
14007
14205
  preserveAlpha: needsAlpha,
14008
14206
  signal: abortSignal,
14009
14207
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -14214,7 +14412,7 @@ function sampleDirectoryBytes(dir) {
14214
14412
  continue;
14215
14413
  }
14216
14414
  for (const name of entries) {
14217
- const full = join32(current, name);
14415
+ const full = join33(current, name);
14218
14416
  try {
14219
14417
  const st = statSync11(full);
14220
14418
  if (st.isDirectory()) {
@@ -14250,6 +14448,7 @@ function summarizeExtractionObservability(extractionResult, videoCount, coverage
14250
14448
  vfrPreflightCount: phaseBreakdown?.vfrPreflightCount,
14251
14449
  cacheHits: phaseBreakdown?.cacheHits,
14252
14450
  cacheMisses: phaseBreakdown?.cacheMisses,
14451
+ cachePublishFailures: phaseBreakdown?.cachePublishFailures,
14253
14452
  transientRetries: phaseBreakdown?.transientRetries,
14254
14453
  ...coverageGauges,
14255
14454
  authoredTimedClipCount
@@ -14371,8 +14570,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14371
14570
  const ranges = [];
14372
14571
  let rangeStart = null;
14373
14572
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14374
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14375
- const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14573
+ const framePath = join33(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14574
+ const missing = !existsSync22(framePath) || statSync11(framePath).size <= 8;
14376
14575
  if (missing && rangeStart === null) {
14377
14576
  rangeStart = frameIndex;
14378
14577
  } else if (!missing && rangeStart !== null) {
@@ -14388,7 +14587,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14388
14587
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
14389
14588
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
14390
14589
  const batches = [];
14391
- const outputDirFor = (batchIndex, workerId) => join32(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14590
+ const outputDirFor = (batchIndex, workerId) => join33(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14392
14591
  if (stride > 1) {
14393
14592
  const spans = /* @__PURE__ */ new Map();
14394
14593
  for (const range of ranges) {
@@ -14447,9 +14646,9 @@ function createCaptureObservabilityUpdater(observability, platform2 = process.pl
14447
14646
  function getNextRetryWorkerCount(currentWorkers) {
14448
14647
  return Math.max(1, Math.floor(currentWorkers / 2));
14449
14648
  }
14450
- function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
14451
- if (platform2 === "win32" || platform2 === "darwin") return join32(systemTempDir, "hf-render-");
14452
- return join32(dirname14(outputPath), `work-${jobId}-`);
14649
+ function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir3()) {
14650
+ if (platform2 === "win32" || platform2 === "darwin") return join33(systemTempDir, "hf-render-");
14651
+ return join33(dirname14(outputPath), `work-${jobId}-`);
14453
14652
  }
14454
14653
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
14455
14654
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -14504,8 +14703,8 @@ The composition is too large for the available memory. To reduce memory pressure
14504
14703
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
14505
14704
  let captured = 0;
14506
14705
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14507
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14508
- if (existsSync21(framePath)) captured++;
14706
+ const framePath = join33(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14707
+ if (existsSync22(framePath)) captured++;
14509
14708
  }
14510
14709
  return captured;
14511
14710
  }
@@ -14530,7 +14729,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
14530
14729
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
14531
14730
  });
14532
14731
  pendingTransientRetry = false;
14533
- const attemptWorkDir = join32(options.workDir, `capture-attempt-${attempt}`);
14732
+ const attemptWorkDir = join33(options.workDir, `capture-attempt-${attempt}`);
14534
14733
  const batches = missingRanges ? buildMissingFrameRetryBatches(
14535
14734
  missingRanges,
14536
14735
  currentWorkers,
@@ -15177,8 +15376,8 @@ function deVerifyFallbackTelemetry(err) {
15177
15376
  };
15178
15377
  }
15179
15378
  function resolveRenderDebugDir() {
15180
- const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname14(fileURLToPath4(import.meta.url)), "../..");
15181
- return join32(producerRoot, ".debug");
15379
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve9(process.env.PRODUCER_RENDERS_DIR, "..") : resolve9(dirname14(fileURLToPath4(import.meta.url)), "../..");
15380
+ return join33(producerRoot, ".debug");
15182
15381
  }
15183
15382
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
15184
15383
  validateHlsRenderConfig(job.config);
@@ -15186,11 +15385,11 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15186
15385
  validateChromaSubsamplingConfig(job.config);
15187
15386
  const debugDir = resolveRenderDebugDir();
15188
15387
  const outputDir = dirname14(outputPath);
15189
- if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
15190
- const workDir = job.config.debug ? join32(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15388
+ if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
15389
+ const workDir = job.config.debug ? join33(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15191
15390
  const pipelineStart = Date.now();
15192
15391
  const baseLog = job.config.logger ?? defaultLogger;
15193
- const logPath = job.config.debug ? join32(workDir, "render.log") : null;
15392
+ const logPath = job.config.debug ? join33(workDir, "render.log") : null;
15194
15393
  const execution = new RenderExecutionContext({
15195
15394
  request: { renderJobId: job.id, projectDir, outputPath },
15196
15395
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -15258,7 +15457,7 @@ async function executeRenderPipeline(input) {
15258
15457
  imageDecodeFailures: 0
15259
15458
  };
15260
15459
  let hdrPerf;
15261
- const perfOutputPath = join32(workDir, "perf-summary.json");
15460
+ const perfOutputPath = join33(workDir, "perf-summary.json");
15262
15461
  const cfg = { ...job.config.producerConfig ?? resolveConfig2() };
15263
15462
  const observability = new RenderObservabilityRecorder({
15264
15463
  pipelineStartMs: pipelineStart,
@@ -15334,7 +15533,7 @@ async function executeRenderPipeline(input) {
15334
15533
  job.startedAt = /* @__PURE__ */ new Date();
15335
15534
  assertNotAborted();
15336
15535
  assertConfiguredFfmpegBinariesExist();
15337
- if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
15536
+ if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
15338
15537
  if (job.config.debug) {
15339
15538
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
15340
15539
  }
@@ -15363,8 +15562,8 @@ async function executeRenderPipeline(input) {
15363
15562
  requestedWorkers: job.config.workers ?? "auto"
15364
15563
  });
15365
15564
  const entryFile = job.config.entryFile || "index.html";
15366
- const htmlPath = join32(projectDir, entryFile);
15367
- if (!existsSync21(htmlPath)) {
15565
+ const htmlPath = join33(projectDir, entryFile);
15566
+ if (!existsSync22(htmlPath)) {
15368
15567
  throw new Error(`Entry file not found: ${htmlPath}`);
15369
15568
  }
15370
15569
  assertNotAborted();
@@ -15460,7 +15659,7 @@ async function executeRenderPipeline(input) {
15460
15659
  const largerThanCanvas = await oversizedVideos(
15461
15660
  composition.videos,
15462
15661
  projectDir,
15463
- join32(workDir, "compiled"),
15662
+ join33(workDir, "compiled"),
15464
15663
  { width: outputWidth, height: outputHeight }
15465
15664
  );
15466
15665
  const probeResult = await observeRenderStage(
@@ -15557,7 +15756,7 @@ async function executeRenderPipeline(input) {
15557
15756
  canvas: { width, height },
15558
15757
  page: probeSession.page,
15559
15758
  projectDir,
15560
- compiledDir: join32(workDir, "compiled")
15759
+ compiledDir: join33(workDir, "compiled")
15561
15760
  });
15562
15761
  if (videoLayerPlan.videoId === void 0) {
15563
15762
  log.info(`[Render] Video layer passthrough off: ${videoLayerPlan.reason}`);
@@ -15575,7 +15774,7 @@ async function executeRenderPipeline(input) {
15575
15774
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
15576
15775
  code: "extract_video"
15577
15776
  });
15578
- const compiledDir = join32(workDir, "compiled");
15777
+ const compiledDir = join33(workDir, "compiled");
15579
15778
  const segmentsCapture = (layeredOrEffectRoute) => shouldSegmentCapture({
15580
15779
  env: process.env,
15581
15780
  durationSeconds: probeResult.duration,
@@ -15711,7 +15910,7 @@ async function executeRenderPipeline(input) {
15711
15910
  try {
15712
15911
  fileServer = await createFileServer({
15713
15912
  projectDir,
15714
- compiledDir: join32(workDir, "compiled"),
15913
+ compiledDir: join33(workDir, "compiled"),
15715
15914
  port: 0,
15716
15915
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15717
15916
  fps: job.config.fps,
@@ -15731,8 +15930,8 @@ async function executeRenderPipeline(input) {
15731
15930
  if (!activeFileServer) {
15732
15931
  throw new Error("File server failed to initialize before frame capture");
15733
15932
  }
15734
- const framesDir = join32(workDir, "captured-frames");
15735
- if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
15933
+ const framesDir = join33(workDir, "captured-frames");
15934
+ if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
15736
15935
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
15737
15936
  code: "start_browsers"
15738
15937
  });
@@ -16312,7 +16511,7 @@ async function executeRenderPipeline(input) {
16312
16511
  hls: ".mp4"
16313
16512
  };
16314
16513
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
16315
- const videoOnlyPath = join32(workDir, `video-only${videoExt}`);
16514
+ const videoOnlyPath = join33(workDir, `video-only${videoExt}`);
16316
16515
  let usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
16317
16516
  if (usePageSideCompositingForTransitions) {
16318
16517
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -16629,7 +16828,7 @@ async function executeRenderPipeline(input) {
16629
16828
  pageMotionBlur: job.config.pageMotionBlur,
16630
16829
  captureQuality: captureOptions.quality
16631
16830
  });
16632
- const segmentDir = segmentDirFor(join32(projectDir, "renders"), segmentPlanHash);
16831
+ const segmentDir = segmentDirFor(join33(projectDir, "renders"), segmentPlanHash);
16633
16832
  let completedSegments = /* @__PURE__ */ new Set();
16634
16833
  if (job.config.resumeSegments === true) {
16635
16834
  const existing = readSegmentManifest(segmentDir);
@@ -17173,7 +17372,7 @@ async function executeRenderPipeline(input) {
17173
17372
  })
17174
17373
  );
17175
17374
  const totalElapsed = Date.now() - pipelineStart;
17176
- const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
17375
+ const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
17177
17376
  recordTransientRetryObservability();
17178
17377
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
17179
17378
  const observabilitySummary = observability.summary({
@@ -17254,8 +17453,8 @@ async function executeRenderPipeline(input) {
17254
17453
  }
17255
17454
  }
17256
17455
  if (job.config.debug) {
17257
- if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
17258
- const debugOutput = join32(workDir, `output${videoExt}`);
17456
+ if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
17457
+ const debugOutput = join33(workDir, `output${videoExt}`);
17259
17458
  copyFileSync5(stagedOutputPath, debugOutput);
17260
17459
  }
17261
17460
  }
@@ -17334,7 +17533,8 @@ async function executeRenderPipeline(input) {
17334
17533
  perfStages,
17335
17534
  hdrDiagnostics,
17336
17535
  observability: observabilitySummary,
17337
- subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs)
17536
+ subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs),
17537
+ missingPath: describeMissingPath(error, { cacheDir: cfg.extractCacheDir, workDir })
17338
17538
  });
17339
17539
  publishRenderFailure(
17340
17540
  job,
@@ -17369,7 +17569,7 @@ async function executeRenderPipeline(input) {
17369
17569
 
17370
17570
  // src/services/hyperframeLint.ts
17371
17571
  import {
17372
- existsSync as existsSync22,
17572
+ existsSync as existsSync23,
17373
17573
  readFileSync as readFileSync10,
17374
17574
  statSync as statSync12,
17375
17575
  openSync as openSync5,
@@ -17377,7 +17577,7 @@ import {
17377
17577
  closeSync as closeSync5,
17378
17578
  constants as constants3
17379
17579
  } from "node:fs";
17380
- import { resolve as resolve9, join as join33, relative as relative4, isAbsolute as isAbsolute3, sep as sep4, dirname as dirname15 } from "node:path";
17580
+ import { resolve as resolve10, join as join34, relative as relative5, isAbsolute as isAbsolute4, sep as sep5, dirname as dirname15 } from "node:path";
17381
17581
  import { fileURLToPath as fileURLToPath5 } from "node:url";
17382
17582
  import { Worker as Worker2 } from "node:worker_threads";
17383
17583
  function isStringRecord(value) {
@@ -17423,19 +17623,19 @@ function readEntryHtml(filePath) {
17423
17623
  }
17424
17624
  }
17425
17625
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
17426
- const entryRelativePath = relative4(absProjectDir, absoluteEntryPath);
17427
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep4}`) || isAbsolute3(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
17626
+ const entryRelativePath = relative5(absProjectDir, absoluteEntryPath);
17627
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute4(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
17428
17628
  }
17429
17629
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
17430
- const absProjectDir = resolve9(projectDir);
17431
- if (!existsSync22(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17630
+ const absProjectDir = resolve10(projectDir);
17631
+ if (!existsSync23(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17432
17632
  return { error: `Project directory not found: ${absProjectDir}` };
17433
17633
  }
17434
17634
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
17435
17635
  (value) => typeof value === "string" && value.trim().length > 0
17436
17636
  );
17437
17637
  for (const entryFile of entryCandidates) {
17438
- const absoluteEntryPath = resolve9(absProjectDir, entryFile);
17638
+ const absoluteEntryPath = resolve10(absProjectDir, entryFile);
17439
17639
  if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) {
17440
17640
  return { error: `Entry file must stay inside project directory: ${entryFile}` };
17441
17641
  }
@@ -17449,7 +17649,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
17449
17649
  }
17450
17650
  }
17451
17651
  return {
17452
- error: `No HTML entry file found in project directory: ${join33(absProjectDir, preferredEntryFile || "index.html")}`
17652
+ error: `No HTML entry file found in project directory: ${join34(absProjectDir, preferredEntryFile || "index.html")}`
17453
17653
  };
17454
17654
  }
17455
17655
  function prepareHyperframeLintBody(body, isAllowedEntry) {
@@ -17495,16 +17695,16 @@ function takeLintSlot(limit, waitMs) {
17495
17695
  running++;
17496
17696
  return Promise.resolve(true);
17497
17697
  }
17498
- return new Promise((resolve11) => {
17698
+ return new Promise((resolve12) => {
17499
17699
  const entry = () => {
17500
17700
  clearTimeout(timer);
17501
17701
  running++;
17502
- resolve11(true);
17702
+ resolve12(true);
17503
17703
  };
17504
17704
  const timer = setTimeout(
17505
17705
  () => {
17506
17706
  waiting.splice(waiting.indexOf(entry), 1);
17507
- resolve11(false);
17707
+ resolve12(false);
17508
17708
  },
17509
17709
  Math.max(0, waitMs)
17510
17710
  );
@@ -17518,8 +17718,8 @@ function freeLintSlot() {
17518
17718
  function resolveLintWorkerEntry() {
17519
17719
  const here = dirname15(fileURLToPath5(import.meta.url));
17520
17720
  for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
17521
- const candidate = join33(here, name);
17522
- if (existsSync22(candidate)) return candidate;
17721
+ const candidate = join34(here, name);
17722
+ if (existsSync23(candidate)) return candidate;
17523
17723
  }
17524
17724
  return void 0;
17525
17725
  }
@@ -17589,8 +17789,8 @@ async function runHyperframeLint(prepared, options = {}) {
17589
17789
  // src/services/healthWorker.ts
17590
17790
  import { Worker as Worker3 } from "node:worker_threads";
17591
17791
  import { fileURLToPath as fileURLToPath6 } from "node:url";
17592
- import { dirname as dirname16, join as join34 } from "node:path";
17593
- import { existsSync as existsSync23 } from "node:fs";
17792
+ import { dirname as dirname16, join as join35 } from "node:path";
17793
+ import { existsSync as existsSync24 } from "node:fs";
17594
17794
  var DEFAULT_HEALTH_PORT = 9848;
17595
17795
  async function startHealthWorker(options = {}) {
17596
17796
  const log = options.logger ?? defaultLogger2();
@@ -17608,12 +17808,12 @@ async function startHealthWorker(options = {}) {
17608
17808
  stdout: false,
17609
17809
  stderr: false
17610
17810
  });
17611
- await new Promise((resolve11, reject) => {
17811
+ await new Promise((resolve12, reject) => {
17612
17812
  const onMessage = (msg) => {
17613
17813
  if (msg?.type === "listening") {
17614
17814
  worker.off("error", onError);
17615
17815
  worker.off("message", onMessage);
17616
- resolve11();
17816
+ resolve12();
17617
17817
  } else if (msg?.type === "listen-error") {
17618
17818
  worker.off("error", onError);
17619
17819
  worker.off("message", onMessage);
@@ -17665,9 +17865,9 @@ function defaultLogger2() {
17665
17865
  }
17666
17866
  function resolveWorkerEntry2() {
17667
17867
  const here = dirname16(fileURLToPath6(import.meta.url));
17668
- const candidates = [join34(here, "healthWorkerThread.js"), join34(here, "healthWorkerThread.ts")];
17868
+ const candidates = [join35(here, "healthWorkerThread.js"), join35(here, "healthWorkerThread.ts")];
17669
17869
  for (const candidate of candidates) {
17670
- if (existsSync23(candidate)) return candidate;
17870
+ if (existsSync24(candidate)) return candidate;
17671
17871
  }
17672
17872
  return void 0;
17673
17873
  }
@@ -17707,7 +17907,7 @@ import {
17707
17907
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
17708
17908
  } from "@hyperframes/engine";
17709
17909
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
17710
- import { extname as extname4, isAbsolute as isAbsolute4, join as join36, relative as relative5, sep as sep5 } from "node:path";
17910
+ import { extname as extname4, isAbsolute as isAbsolute5, join as join37, relative as relative6, sep as sep6 } from "node:path";
17711
17911
  import {
17712
17912
  fpsToNumber as fpsToNumber9,
17713
17913
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -17740,8 +17940,8 @@ import {
17740
17940
 
17741
17941
  // src/services/distributed/shared.ts
17742
17942
  import { execFile as execFileCallback } from "node:child_process";
17743
- import { dirname as dirname17, join as join35 } from "node:path";
17744
- import { existsSync as existsSync24, readFileSync as readFileSync11 } from "node:fs";
17943
+ import { dirname as dirname17, join as join36 } from "node:path";
17944
+ import { existsSync as existsSync25, readFileSync as readFileSync11 } from "node:fs";
17745
17945
  import { fileURLToPath as fileURLToPath7 } from "node:url";
17746
17946
  import { promisify as promisify2 } from "node:util";
17747
17947
  import {
@@ -17756,8 +17956,8 @@ function readProducerVersion() {
17756
17956
  const startDir = dirname17(fileURLToPath7(import.meta.url));
17757
17957
  let current = startDir;
17758
17958
  for (let i = 0; i < 10; i++) {
17759
- const candidate = join35(current, "package.json");
17760
- if (existsSync24(candidate)) {
17959
+ const candidate = join36(current, "package.json");
17960
+ if (existsSync25(candidate)) {
17761
17961
  try {
17762
17962
  const pkg = JSON.parse(readFileSync11(candidate, "utf-8"));
17763
17963
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
@@ -17854,9 +18054,9 @@ var PLAN_ROOT_CATEGORY = {
17854
18054
  var PLAN_DIR_SIZE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024;
17855
18055
  var FREEZE_OWNED_PLAN_FILES = [
17856
18056
  "plan.json",
17857
- join36("meta", "composition.json"),
17858
- join36("meta", "encoder.json"),
17859
- join36("meta", "chunks.json")
18057
+ join37("meta", "composition.json"),
18058
+ join37("meta", "encoder.json"),
18059
+ join37("meta", "chunks.json")
17860
18060
  ];
17861
18061
 
17862
18062
  // src/services/distributed/renderConfigValidation.ts
@@ -18284,7 +18484,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
18284
18484
  }
18285
18485
  }
18286
18486
  const outputDir = dirname18(absoluteOutputPath);
18287
- if (!existsSync25(outputDir)) mkdirSync13(outputDir, { recursive: true });
18487
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
18288
18488
  return { input, cleanupProjectDir, absoluteOutputPath };
18289
18489
  }
18290
18490
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
@@ -18345,7 +18545,7 @@ function validateOutputResolutionOverride(body) {
18345
18545
  var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
18346
18546
  function resolveRenderRequestPolicy(options) {
18347
18547
  return {
18348
- projectsDir: resolve10(
18548
+ projectsDir: resolve11(
18349
18549
  options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd())
18350
18550
  ),
18351
18551
  allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1"
@@ -18360,14 +18560,14 @@ function isAllowedEntryPath(policy, projectDir, path) {
18360
18560
  function prepareProjectDirectory(projectDir, options, policy) {
18361
18561
  const candidate = nonEmptyString(projectDir);
18362
18562
  if (!candidate) return null;
18363
- const absProjectDir = policy ? resolve10(policy.projectsDir, candidate) : resolve10(candidate);
18563
+ const absProjectDir = policy ? resolve11(policy.projectsDir, candidate) : resolve11(candidate);
18364
18564
  const shown = policy ? candidate : absProjectDir;
18365
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync25(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
18565
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync26(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
18366
18566
  return { error: `Project directory not found: ${shown}` };
18367
18567
  }
18368
18568
  const entry = options.entryFile || "index.html";
18369
- const entryPath = resolve10(absProjectDir, entry);
18370
- if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync25(entryPath)) {
18569
+ const entryPath = resolve11(absProjectDir, entry);
18570
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync26(entryPath)) {
18371
18571
  return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
18372
18572
  }
18373
18573
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -18387,9 +18587,9 @@ async function resolveInlineRenderHtml(body) {
18387
18587
  }
18388
18588
  }
18389
18589
  function materializeInlineProject(html, options) {
18390
- const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir3();
18391
- const tempProjectDir = mkdtempSync(join37(tempRoot, "producer-project-"));
18392
- writeFileSync8(join37(tempProjectDir, "index.html"), html, "utf-8");
18590
+ const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir4();
18591
+ const tempProjectDir = mkdtempSync(join38(tempRoot, "producer-project-"));
18592
+ writeFileSync8(join38(tempProjectDir, "index.html"), html, "utf-8");
18393
18593
  return {
18394
18594
  prepared: {
18395
18595
  input: { projectDir: tempProjectDir, ...options },
@@ -18417,7 +18617,7 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
18417
18617
  try {
18418
18618
  return resolveRenderPaths(projectDir, outputCandidate, rendersDir).absoluteOutputPath;
18419
18619
  } catch (error) {
18420
- const fallbackPath = resolve10(rendersDir, `producer-fallback-${Date.now()}.mp4`);
18620
+ const fallbackPath = resolve11(rendersDir, `producer-fallback-${Date.now()}.mp4`);
18421
18621
  log.warn("Failed to resolve output path, using fallback", {
18422
18622
  fallback: fallbackPath,
18423
18623
  error: error instanceof Error ? error.message : String(error)
@@ -18465,7 +18665,7 @@ function publicPerfSummary(job) {
18465
18665
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
18466
18666
  }
18467
18667
  function outputFileSize(path) {
18468
- return existsSync25(path) ? statSync13(path).size : 0;
18668
+ return existsSync26(path) ? statSync13(path).size : 0;
18469
18669
  }
18470
18670
  function createBlockingProgressReporter(log, requestId) {
18471
18671
  let lastLoggedPct = -10;
@@ -18585,7 +18785,7 @@ function createRenderHandlers(options = {}) {
18585
18785
  const lintProjectDir = nonEmptyString(body.projectDir);
18586
18786
  let isAllowedEntry;
18587
18787
  if (policy && lintProjectDir) {
18588
- const absProjectDir = resolve10(policy.projectsDir, lintProjectDir);
18788
+ const absProjectDir = resolve11(policy.projectsDir, lintProjectDir);
18589
18789
  if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) {
18590
18790
  const error = `Project directory not found: ${lintProjectDir}`;
18591
18791
  return c.json({ success: false, requestId, error }, 400);
@@ -18792,7 +18992,7 @@ function createRenderHandlers(options = {}) {
18792
18992
  if (!artifact) {
18793
18993
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
18794
18994
  }
18795
- if (!existsSync25(artifact.path)) {
18995
+ if (!existsSync26(artifact.path)) {
18796
18996
  store.delete(token);
18797
18997
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
18798
18998
  }
@@ -18957,7 +19157,7 @@ function startServer(options = {}) {
18957
19157
  process.on("SIGINT", () => shutdown("SIGINT"));
18958
19158
  return server;
18959
19159
  }
18960
- var entryScript = process.argv[1] ? resolve10(process.argv[1]) : "";
19160
+ var entryScript = process.argv[1] ? resolve11(process.argv[1]) : "";
18961
19161
  var isPublicServerEntry = entryScript.endsWith("/public-server.js") || entryScript.endsWith("/src/server.ts");
18962
19162
  if (isPublicServerEntry) {
18963
19163
  const { values } = parseArgs({