@hyperframes/producer 0.9.85 → 0.9.87
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compileWorker.js +3210 -0
- package/dist/distributed.js +388 -269
- package/dist/hyperframe.manifest.json +1 -1
- package/dist/hyperframe.runtime.iife.js +67 -67
- package/dist/index.js +462 -342
- package/dist/public-server.js +274 -154
- package/dist/services/compileInWorker.d.ts +10 -0
- package/dist/services/compileWorker.d.ts +1 -0
- package/package.json +7 -7
|
@@ -0,0 +1,3210 @@
|
|
|
1
|
+
// src/services/compileWorker.ts
|
|
2
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
|
|
4
|
+
// src/services/htmlCompiler.ts
|
|
5
|
+
import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
|
|
6
|
+
import {
|
|
7
|
+
cssRuleMatches,
|
|
8
|
+
cssUrlMatches,
|
|
9
|
+
fontFaceBlockMatches,
|
|
10
|
+
hasBackgroundImageDeclaration,
|
|
11
|
+
importRuleMatches,
|
|
12
|
+
localFontFaceUrlMatches,
|
|
13
|
+
remoteBackgroundUrlMatches,
|
|
14
|
+
remoteFontFaceUrlMatches,
|
|
15
|
+
replaceMatches,
|
|
16
|
+
styleBlockMatches,
|
|
17
|
+
stylesheetLinkMatches
|
|
18
|
+
} from "@hyperframes/parsers/css-url-scans";
|
|
19
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
20
|
+
import { createReadStream, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync4 } from "fs";
|
|
21
|
+
import { join as join5, dirname as dirname3, resolve as resolve3, basename as basename2, relative, sep as sep2 } from "path";
|
|
22
|
+
import { parseHTML as parseHTML4 } from "linkedom";
|
|
23
|
+
|
|
24
|
+
// src/services/bundledScripts.ts
|
|
25
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { GSAP_CDN_VERSION } from "@hyperframes/core/gsap-cdn";
|
|
28
|
+
var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
|
|
29
|
+
var DEFAULT_CDN_GSAP_3 = /^https:\/\/cdn\.jsdelivr\.net\/npm\/gsap@(3\.\d+\.\d+)\/dist\/([A-Za-z]+\.min\.js)$/;
|
|
30
|
+
var read = (file) => existsSync(file) ? readFileSync(file) : null;
|
|
31
|
+
function bundledScript(url) {
|
|
32
|
+
const dir = process.env[GSAP_VENDOR_DIR_ENV];
|
|
33
|
+
const [, version, file] = DEFAULT_CDN_GSAP_3.exec(url) ?? [];
|
|
34
|
+
if (!dir || !version || !file) return null;
|
|
35
|
+
const at = version === GSAP_CDN_VERSION ? dir : join(dir, "..", "..", `gsap@${version}`, "dist");
|
|
36
|
+
return read(join(at, file));
|
|
37
|
+
}
|
|
38
|
+
function bundledGsapStandIn(url) {
|
|
39
|
+
const dir = process.env[GSAP_VENDOR_DIR_ENV];
|
|
40
|
+
const [, , file] = DEFAULT_CDN_GSAP_3.exec(url) ?? [];
|
|
41
|
+
return dir && file ? read(join(dir, file)) : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/services/htmlTagScans.ts
|
|
45
|
+
function forwardFinder(text, pattern) {
|
|
46
|
+
let start = -1;
|
|
47
|
+
let found = null;
|
|
48
|
+
return (from) => {
|
|
49
|
+
if (start < 0 || from < start || found !== null && from > found.index) {
|
|
50
|
+
start = from;
|
|
51
|
+
pattern.lastIndex = from;
|
|
52
|
+
found = pattern.exec(text);
|
|
53
|
+
}
|
|
54
|
+
return found;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function indexFinder(text, pattern) {
|
|
58
|
+
const find = forwardFinder(text, pattern);
|
|
59
|
+
return (from) => find(from)?.index ?? -1;
|
|
60
|
+
}
|
|
61
|
+
function* inlineScriptBlocks(html) {
|
|
62
|
+
const opener = /<script\b/gi;
|
|
63
|
+
const closer = /<\/script>/gi;
|
|
64
|
+
for (let open = opener.exec(html); open; open = opener.exec(html)) {
|
|
65
|
+
const attrsStart = open.index + open[0].length;
|
|
66
|
+
const gt = html.indexOf(">", attrsStart);
|
|
67
|
+
if (gt < 0) return;
|
|
68
|
+
closer.lastIndex = gt + 1;
|
|
69
|
+
const close = closer.exec(html);
|
|
70
|
+
if (!close) return;
|
|
71
|
+
yield { attrs: html.slice(attrsStart, gt), body: html.slice(gt + 1, close.index) };
|
|
72
|
+
opener.lastIndex = close.index + close[0].length;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function removeDelimitedRuns(source, start, end) {
|
|
76
|
+
let out = "";
|
|
77
|
+
let kept = 0;
|
|
78
|
+
for (let open = source.indexOf(start); open >= 0; open = source.indexOf(start, kept)) {
|
|
79
|
+
const close = source.indexOf(end, open + start.length);
|
|
80
|
+
if (close < 0) break;
|
|
81
|
+
out += source.slice(kept, open);
|
|
82
|
+
kept = close + end.length;
|
|
83
|
+
}
|
|
84
|
+
return out + source.slice(kept);
|
|
85
|
+
}
|
|
86
|
+
function gsapDistFile(value) {
|
|
87
|
+
let dist = -1;
|
|
88
|
+
const distPattern = /\/dist\//gi;
|
|
89
|
+
for (let m = distPattern.exec(value); m; m = distPattern.exec(value)) {
|
|
90
|
+
if (m.index + 6 < value.length) dist = m.index;
|
|
91
|
+
distPattern.lastIndex = m.index + 1;
|
|
92
|
+
}
|
|
93
|
+
const gsap = dist < 0 ? null : /gsap/i.exec(value);
|
|
94
|
+
return gsap && gsap.index + 4 <= dist ? value.slice(dist + 6) : void 0;
|
|
95
|
+
}
|
|
96
|
+
function lastGsapMatch(html, finders, tagStart, gt) {
|
|
97
|
+
const { nextSrc, nextQuote, nextGt } = finders;
|
|
98
|
+
let match;
|
|
99
|
+
for (let src = nextSrc(tagStart); src && src.index < gt; src = nextSrc(src.index + 1)) {
|
|
100
|
+
const valueStart = src.index + 5;
|
|
101
|
+
const close = nextQuote(valueStart);
|
|
102
|
+
const end = close < 0 ? -1 : nextGt(close + 1);
|
|
103
|
+
if (end < 0) return { match, laterTagsFail: true };
|
|
104
|
+
const file = gsapDistFile(html.slice(valueStart, close));
|
|
105
|
+
if (file !== void 0) match = { valueStart, close, end, file };
|
|
106
|
+
}
|
|
107
|
+
return { match, laterTagsFail: false };
|
|
108
|
+
}
|
|
109
|
+
function replaceGsapDistScripts(html, replace) {
|
|
110
|
+
const opener = /<script\b/gi;
|
|
111
|
+
const finders = {
|
|
112
|
+
nextSrc: forwardFinder(html, /\bsrc=["']/gi),
|
|
113
|
+
nextQuote: indexFinder(html, /["']/g),
|
|
114
|
+
nextGt: indexFinder(html, />/g)
|
|
115
|
+
};
|
|
116
|
+
let out = "";
|
|
117
|
+
let kept = 0;
|
|
118
|
+
for (let open = opener.exec(html); open; open = opener.exec(html)) {
|
|
119
|
+
const gt = finders.nextGt(open.index);
|
|
120
|
+
if (gt < 0) break;
|
|
121
|
+
const { match, laterTagsFail } = lastGsapMatch(html, finders, open.index, gt);
|
|
122
|
+
if (match) {
|
|
123
|
+
const { valueStart, close, end, file } = match;
|
|
124
|
+
const full = html.slice(open.index, end + 1);
|
|
125
|
+
const src = html.slice(valueStart, close);
|
|
126
|
+
out += html.slice(kept, open.index);
|
|
127
|
+
out += replace(
|
|
128
|
+
full,
|
|
129
|
+
html.slice(open.index, valueStart),
|
|
130
|
+
src,
|
|
131
|
+
file,
|
|
132
|
+
html.slice(close, end + 1)
|
|
133
|
+
);
|
|
134
|
+
kept = end + 1;
|
|
135
|
+
}
|
|
136
|
+
if (laterTagsFail) break;
|
|
137
|
+
opener.lastIndex = match ? kept : gt;
|
|
138
|
+
}
|
|
139
|
+
return out + html.slice(kept);
|
|
140
|
+
}
|
|
141
|
+
function removeSpanPerTag(html, opener, spanIn) {
|
|
142
|
+
const nextGt = indexFinder(html, />/g);
|
|
143
|
+
let out = "";
|
|
144
|
+
let kept = 0;
|
|
145
|
+
for (let open = opener.exec(html); open; open = opener.exec(html)) {
|
|
146
|
+
const attrsStart = open.index + open[0].length;
|
|
147
|
+
const gt = nextGt(attrsStart);
|
|
148
|
+
const span = spanIn(attrsStart, gt < 0 ? html.length : gt);
|
|
149
|
+
if (span) {
|
|
150
|
+
out += html.slice(kept, span[0]);
|
|
151
|
+
kept = span[1];
|
|
152
|
+
} else if (gt < 0) break;
|
|
153
|
+
opener.lastIndex = span ? kept : gt;
|
|
154
|
+
}
|
|
155
|
+
return out + html.slice(kept);
|
|
156
|
+
}
|
|
157
|
+
function stripCrossoriginAttr(html, tagName) {
|
|
158
|
+
const nextQuote = indexFinder(html, /["']/g);
|
|
159
|
+
const nextAttr = forwardFinder(html, /\scrossorigin/gi);
|
|
160
|
+
return removeSpanPerTag(html, new RegExp(`<${tagName}\\b`, "gi"), (attrsStart, tagEnd) => {
|
|
161
|
+
let last = -1;
|
|
162
|
+
for (let at = nextAttr(attrsStart); at && at.index < tagEnd; at = nextAttr(at.index + 12)) {
|
|
163
|
+
last = at.index;
|
|
164
|
+
}
|
|
165
|
+
if (last < 0) return void 0;
|
|
166
|
+
const nameEnd = last + 12;
|
|
167
|
+
const quote = html[nameEnd + 1];
|
|
168
|
+
const quoted = html[nameEnd] === "=" && (quote === '"' || quote === "'");
|
|
169
|
+
const close = quoted ? nextQuote(nameEnd + 2) : -1;
|
|
170
|
+
return [last, close < 0 ? nameEnd : close + 1];
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function stripPreloadNone(html) {
|
|
174
|
+
const nextAttr = forwardFinder(html, /(?<!\s)\s+preload\s*=\s*["']none["']/gi);
|
|
175
|
+
return removeSpanPerTag(html, /<(?:video|audio)\b/gi, (attrsStart, tagEnd) => {
|
|
176
|
+
const attr = nextAttr(attrsStart);
|
|
177
|
+
return attr && attr.index < tagEnd ? [attr.index, attr.index + attr[0].length] : void 0;
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
var REMOTE_SRC_TAGS = {
|
|
181
|
+
media: { opener: "<(?:video|audio)\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
|
|
182
|
+
source: { opener: "<source\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
|
|
183
|
+
img: { opener: "<img\\b", attr: /(?<![\w-])src\s*=\s*["'](https?:\/\/)/gi }
|
|
184
|
+
};
|
|
185
|
+
function remoteSrcUrls(html, tag) {
|
|
186
|
+
const opener = new RegExp(REMOTE_SRC_TAGS[tag].opener, "gi");
|
|
187
|
+
const nextAttr = forwardFinder(html, new RegExp(REMOTE_SRC_TAGS[tag].attr));
|
|
188
|
+
const nextGt = indexFinder(html, />/g);
|
|
189
|
+
const nextQuote = indexFinder(html, /["']/g);
|
|
190
|
+
const urls = [];
|
|
191
|
+
for (let open = opener.exec(html); open; open = opener.exec(html)) {
|
|
192
|
+
const attrsStart = open.index + open[0].length;
|
|
193
|
+
const gt = nextGt(attrsStart);
|
|
194
|
+
if (gt < 0) break;
|
|
195
|
+
let resumeAt = gt;
|
|
196
|
+
for (let attr = nextAttr(attrsStart); attr && attr.index < gt; attr = nextAttr(attr.index + 1)) {
|
|
197
|
+
const urlRest = attr.index + attr[0].length;
|
|
198
|
+
const close = nextQuote(urlRest);
|
|
199
|
+
if (close < 0) return urls;
|
|
200
|
+
if (close === urlRest) continue;
|
|
201
|
+
const end = nextGt(close + 1);
|
|
202
|
+
if (end < 0) return urls;
|
|
203
|
+
urls.push(html.slice(urlRest - attr[1].length, close));
|
|
204
|
+
resumeAt = end + 1;
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
opener.lastIndex = resumeAt;
|
|
208
|
+
}
|
|
209
|
+
return urls;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/services/htmlCompiler.ts
|
|
213
|
+
import {
|
|
214
|
+
COMPOSITION_SOURCE_URL,
|
|
215
|
+
compileTimingAttrs,
|
|
216
|
+
injectDurations,
|
|
217
|
+
extractResolvedMedia,
|
|
218
|
+
clampDurations,
|
|
219
|
+
shouldClampResolvedMediaDuration,
|
|
220
|
+
isNonRelativeUrl,
|
|
221
|
+
parseStrictFiniteTimingNumber,
|
|
222
|
+
readMediaStart,
|
|
223
|
+
redactTelemetryString,
|
|
224
|
+
resolveNaturalMediaTimelineDurationFromValues,
|
|
225
|
+
rewriteAssetPath,
|
|
226
|
+
rewriteAssetPaths,
|
|
227
|
+
rewriteCssAssetUrls,
|
|
228
|
+
rewriteInlineStyleAssetUrls,
|
|
229
|
+
terminalText as terminalText2
|
|
230
|
+
} from "@hyperframes/core";
|
|
231
|
+
import { MAX_AUDIO_GAIN } from "@hyperframes/core/audio-gain";
|
|
232
|
+
import { CAPTURE_CANVAS_SELECTOR } from "@hyperframes/core/html-in-canvas";
|
|
233
|
+
import { readPlaybackRate } from "@hyperframes/parsers/media-duration";
|
|
234
|
+
import { resolveRateSpec } from "@hyperframes/core/speed-ramp";
|
|
235
|
+
import { gsapCdnDist, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
|
|
236
|
+
import {
|
|
237
|
+
assignBundledRuntimeCompositionIds,
|
|
238
|
+
assignMediaRenderIds,
|
|
239
|
+
emitVariablesByCompScript,
|
|
240
|
+
inlineSubCompositions as inlineSubCompositionsShared,
|
|
241
|
+
ensureExternalLinkTag,
|
|
242
|
+
ensureExternalScriptTag,
|
|
243
|
+
deferScriptsUntilFonts,
|
|
244
|
+
emitMountedModuleScripts,
|
|
245
|
+
isJavaScriptType,
|
|
246
|
+
prepareFlattenedInnerRoot,
|
|
247
|
+
emitRootCompositionVariableStyles,
|
|
248
|
+
dropAuthoredSvgReferenceAliases,
|
|
249
|
+
readDeclaredDefaults,
|
|
250
|
+
parseHostVariableValues,
|
|
251
|
+
boundMediaSrc,
|
|
252
|
+
headStyleRuns,
|
|
253
|
+
isAlwaysAppliedStyle,
|
|
254
|
+
dedupeFontFaceRules,
|
|
255
|
+
inlineScriptRuns,
|
|
256
|
+
parsesAsScript,
|
|
257
|
+
styleElementsFor,
|
|
258
|
+
insertBeforeCloseTag,
|
|
259
|
+
isRuntimeFileUrl
|
|
260
|
+
} from "@hyperframes/core/compiler";
|
|
261
|
+
import {
|
|
262
|
+
checkSubCompositionUsability
|
|
263
|
+
} from "@hyperframes/parsers/sub-composition-validity";
|
|
264
|
+
import {
|
|
265
|
+
isUnresolvedAssetPlaceholder,
|
|
266
|
+
namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
|
|
267
|
+
projectAssetExists,
|
|
268
|
+
readProjectFile,
|
|
269
|
+
readTextFile,
|
|
270
|
+
resolveCompositionSrc
|
|
271
|
+
} from "@hyperframes/parsers/asset-resolution";
|
|
272
|
+
import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
|
|
273
|
+
import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
|
|
274
|
+
|
|
275
|
+
// src/utils/ffprobe.ts
|
|
276
|
+
import {
|
|
277
|
+
extractMediaMetadata,
|
|
278
|
+
extractVideoMetadata,
|
|
279
|
+
extractAudioMetadata
|
|
280
|
+
} from "@hyperframes/engine";
|
|
281
|
+
|
|
282
|
+
// src/services/htmlCompiler.ts
|
|
283
|
+
import {
|
|
284
|
+
assertCompositionFileSize,
|
|
285
|
+
CompositionExpansionBudget,
|
|
286
|
+
ENTRY_PAGE,
|
|
287
|
+
REMOTE_SCRIPTS,
|
|
288
|
+
REMOTE_STYLESHEETS
|
|
289
|
+
} from "@hyperframes/core/compiler";
|
|
290
|
+
|
|
291
|
+
// src/utils/paths.ts
|
|
292
|
+
import {
|
|
293
|
+
basename,
|
|
294
|
+
join as join2,
|
|
295
|
+
sep,
|
|
296
|
+
resolve as nodeResolve,
|
|
297
|
+
relative as nodeRelative,
|
|
298
|
+
isAbsolute as nodeIsAbsolute
|
|
299
|
+
} from "node:path";
|
|
300
|
+
import { statSync } from "node:fs";
|
|
301
|
+
import { fileURLToPath } from "node:url";
|
|
302
|
+
import { isSafePath } from "@hyperframes/core/safe-path";
|
|
303
|
+
import {
|
|
304
|
+
isCopiedOutsideFileType,
|
|
305
|
+
isPrivateOutsideFile,
|
|
306
|
+
isUploadedOutsideFileType,
|
|
307
|
+
leftOutWarning,
|
|
308
|
+
linksOutside
|
|
309
|
+
} from "@hyperframes/studio-server/outside-file";
|
|
310
|
+
import { realFilePath } from "@hyperframes/studio-server/safe-path";
|
|
311
|
+
var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (not URL.pathname): on Windows .pathname is "/D:/..." which
|
|
312
|
+
// resolves to a bogus renders dir.
|
|
313
|
+
nodeResolve(fileURLToPath(import.meta.url), "../../..", "renders");
|
|
314
|
+
var LEADING_PARENT_SEGMENT_RE = /^\.\.(?:[\\/]|$)/;
|
|
315
|
+
function isPathInside(childPath, parentPath, options2 = {}) {
|
|
316
|
+
const resolvePath = options2.pathModule?.resolve ?? nodeResolve;
|
|
317
|
+
const relativePath = options2.pathModule?.relative ?? nodeRelative;
|
|
318
|
+
const isPathAbsolute = options2.pathModule?.isAbsolute ?? nodeIsAbsolute;
|
|
319
|
+
const absChild = resolvePath(childPath);
|
|
320
|
+
const absParent = resolvePath(parentPath);
|
|
321
|
+
if (absChild === absParent) return true;
|
|
322
|
+
const rel = relativePath(absParent, absChild);
|
|
323
|
+
return rel !== "" && !LEADING_PARENT_SEGMENT_RE.test(rel) && !isPathAbsolute(rel);
|
|
324
|
+
}
|
|
325
|
+
function escapesAssetRoot(path, assetRoot) {
|
|
326
|
+
return assetRoot !== void 0 && !isSafePath(assetRoot, path);
|
|
327
|
+
}
|
|
328
|
+
function outsideAssetRefusal(projectDir2, path, policy = {}) {
|
|
329
|
+
if (!linksOutside(projectDir2, path)) return null;
|
|
330
|
+
if (isPrivateOutsideFile(projectDir2, path)) return "blocklisted";
|
|
331
|
+
const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
|
|
332
|
+
if (folder || isUploadedOutsideFileType(path)) return null;
|
|
333
|
+
if (!isCopiedOutsideFileType(path)) return "file_type";
|
|
334
|
+
return policy.includeScripts ? null : "script";
|
|
335
|
+
}
|
|
336
|
+
var leftOutOfRender = (file, reference, reason) => leftOutWarning(file, reference, reason, "render");
|
|
337
|
+
function refusesOutsideLink(projectDir2, path, warn, policy = {}) {
|
|
338
|
+
const refusal = outsideAssetRefusal(projectDir2, path, policy);
|
|
339
|
+
if (!refusal) return false;
|
|
340
|
+
const file = nodeRelative(projectDir2, path).split(sep).join("/");
|
|
341
|
+
warn(leftOutOfRender(file, realFilePath(path), refusal));
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
function toExternalAssetKey(absPath) {
|
|
345
|
+
if (absPath.startsWith("hf-ext/")) return absPath;
|
|
346
|
+
let normalised = absPath.replace(/\\/g, "/");
|
|
347
|
+
normalised = normalised.replace(/^\/\/\?\/UNC\//i, "//");
|
|
348
|
+
normalised = normalised.replace(/^\/\/\?\//, "");
|
|
349
|
+
normalised = normalised.replace(/^\/\/([^/]+)\//, "unc/$1/");
|
|
350
|
+
normalised = normalised.replace(/^\/+/, "");
|
|
351
|
+
normalised = normalised.replace(/^([A-Za-z]):\/?/, "$1/");
|
|
352
|
+
return "hf-ext/" + normalised;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// src/services/renderMediaCollector.ts
|
|
356
|
+
import { parseHTML } from "linkedom";
|
|
357
|
+
import {
|
|
358
|
+
MEDIA_RENDER_ID_ATTR,
|
|
359
|
+
normalizeRateSpec,
|
|
360
|
+
resolveAuthoredTimingWindow,
|
|
361
|
+
shiftRateLane,
|
|
362
|
+
sourceTimeAt
|
|
363
|
+
} from "@hyperframes/core";
|
|
364
|
+
import {
|
|
365
|
+
MEDIA_START_BASIS_ATTR,
|
|
366
|
+
compositionOriginSeconds,
|
|
367
|
+
cutToHostSlots,
|
|
368
|
+
hostInPointSeconds,
|
|
369
|
+
readMediaStartBasis,
|
|
370
|
+
resolveAbsoluteMediaStartSeconds
|
|
371
|
+
} from "@hyperframes/core/media-timing";
|
|
372
|
+
import {
|
|
373
|
+
parseVideoElements,
|
|
374
|
+
hasGradedCanvas,
|
|
375
|
+
parseImageElements,
|
|
376
|
+
parseAudioElements,
|
|
377
|
+
isSelfOrAncestorHidden,
|
|
378
|
+
resolveReferencedStart
|
|
379
|
+
} from "@hyperframes/engine";
|
|
380
|
+
function resolveHostEnd(host, hostStart) {
|
|
381
|
+
return resolveAuthoredTimingWindow({
|
|
382
|
+
start: hostStart,
|
|
383
|
+
duration: host.getAttribute("data-duration"),
|
|
384
|
+
end: host.getAttribute("data-end")
|
|
385
|
+
})?.end ?? null;
|
|
386
|
+
}
|
|
387
|
+
var ROOT_WINDOW = { offset: 0, limit: Infinity, basis: "local", slots: [] };
|
|
388
|
+
var COMPOSITION_HOST_SELECTOR = "[data-composition-id], [data-composition-src], [data-composition-file]";
|
|
389
|
+
function enclosingHosts(element) {
|
|
390
|
+
const hosts = [];
|
|
391
|
+
for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) {
|
|
392
|
+
if (ancestor.matches(COMPOSITION_HOST_SELECTOR)) {
|
|
393
|
+
hosts.unshift(ancestor);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return hosts;
|
|
397
|
+
}
|
|
398
|
+
function resolveHostWindow(element, document2, startCache, visiting) {
|
|
399
|
+
const hosts = enclosingHosts(element);
|
|
400
|
+
if (hosts.length === 0) return ROOT_WINDOW;
|
|
401
|
+
let offset = 0;
|
|
402
|
+
let limit = Infinity;
|
|
403
|
+
const slots = [];
|
|
404
|
+
for (const [index, host] of hosts.entries()) {
|
|
405
|
+
const hostStart = resolveReferencedStart(document2, host, startCache, visiting);
|
|
406
|
+
const hostEnd = resolveHostEnd(host, hostStart);
|
|
407
|
+
if (hostEnd != null && !isRootComposition(host, index)) {
|
|
408
|
+
limit = Math.min(limit, offset + hostEnd);
|
|
409
|
+
}
|
|
410
|
+
if (hostInPointSeconds(host) > 0) {
|
|
411
|
+
slots.push({ start: offset + hostStart, end: offset + (hostEnd ?? Infinity) });
|
|
412
|
+
}
|
|
413
|
+
offset += compositionOriginSeconds(hostStart, host);
|
|
414
|
+
}
|
|
415
|
+
return { offset, limit, basis: mediaStartBasis(element), slots };
|
|
416
|
+
}
|
|
417
|
+
var isRootComposition = (host, depth) => depth === 0 && !host.matches("[data-composition-src], [data-composition-file]");
|
|
418
|
+
function mediaStartBasis(element) {
|
|
419
|
+
const tag = element.tagName.toLowerCase();
|
|
420
|
+
return tag === "video" || tag === "audio" ? readMediaStartBasis(element.getAttribute(MEDIA_START_BASIS_ATTR)) : "local";
|
|
421
|
+
}
|
|
422
|
+
function collectHostWindows(html) {
|
|
423
|
+
const { document: document2 } = parseHTML(html);
|
|
424
|
+
const windows = /* @__PURE__ */ new Map();
|
|
425
|
+
const startCache = /* @__PURE__ */ new Map();
|
|
426
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
427
|
+
for (const element of document2.querySelectorAll("video, audio, img[src]")) {
|
|
428
|
+
const renderId = element.getAttribute(MEDIA_RENDER_ID_ATTR);
|
|
429
|
+
const id = renderId || element.getAttribute("id");
|
|
430
|
+
if (!id || !renderId && windows.has(id)) continue;
|
|
431
|
+
windows.set(
|
|
432
|
+
id,
|
|
433
|
+
resolveHostWindow(element, document2, startCache, visiting)
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
return windows;
|
|
437
|
+
}
|
|
438
|
+
function collectHiddenVideoIds(html) {
|
|
439
|
+
const { document: document2 } = parseHTML(html);
|
|
440
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
441
|
+
for (const element of document2.querySelectorAll("video")) {
|
|
442
|
+
const id = element.getAttribute(MEDIA_RENDER_ID_ATTR) || element.getAttribute("id");
|
|
443
|
+
if (id && isSelfOrAncestorHidden(element)) hidden.add(id);
|
|
444
|
+
}
|
|
445
|
+
return hidden;
|
|
446
|
+
}
|
|
447
|
+
function toAbsoluteWindow(start, end, window2) {
|
|
448
|
+
const absoluteStart = resolveAbsoluteMediaStartSeconds({
|
|
449
|
+
authoredStart: start,
|
|
450
|
+
hostStart: window2.offset,
|
|
451
|
+
basis: window2.basis
|
|
452
|
+
});
|
|
453
|
+
if (absoluteStart >= window2.limit) return null;
|
|
454
|
+
const absoluteEnd = resolveAbsoluteMediaStartSeconds({
|
|
455
|
+
authoredStart: end,
|
|
456
|
+
hostStart: window2.offset,
|
|
457
|
+
basis: window2.basis
|
|
458
|
+
});
|
|
459
|
+
const absolute = { start: absoluteStart, end: Math.min(absoluteEnd, window2.limit) };
|
|
460
|
+
const played = cutToHostSlots(absolute, window2.slots);
|
|
461
|
+
if (played.end === played.start && absolute.end > absolute.start) return null;
|
|
462
|
+
return { start: absolute.start, end: played.end, played };
|
|
463
|
+
}
|
|
464
|
+
function startAtPlayed(clip, played) {
|
|
465
|
+
const head = played.start - clip.start;
|
|
466
|
+
if (head <= 0) return clip;
|
|
467
|
+
if ("loop" in clip && clip.loop) return { ...clip, start: played.start };
|
|
468
|
+
const rate = normalizeRateSpec(clip.playbackRate);
|
|
469
|
+
return {
|
|
470
|
+
...clip,
|
|
471
|
+
start: played.start,
|
|
472
|
+
mediaStart: clip.mediaStart + sourceTimeAt(rate, head),
|
|
473
|
+
playbackRate: shiftRateLane(rate, head)
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function collectRenderMedia(html) {
|
|
477
|
+
const windows = collectHostWindows(html);
|
|
478
|
+
const windowFor = (id) => windows.get(id) ?? ROOT_WINDOW;
|
|
479
|
+
const droppedMediaIds = /* @__PURE__ */ new Set();
|
|
480
|
+
const hiddenIds = collectHiddenVideoIds(html);
|
|
481
|
+
const videos = [];
|
|
482
|
+
for (const video of parseVideoElements(html)) {
|
|
483
|
+
if (hiddenIds.has(video.id)) {
|
|
484
|
+
droppedMediaIds.add(video.id);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
const absolute = toAbsoluteWindow(video.start, video.end, windowFor(video.id));
|
|
488
|
+
if (!absolute) {
|
|
489
|
+
droppedMediaIds.add(video.id);
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
videos.push(
|
|
493
|
+
startAtPlayed({ ...video, start: absolute.start, end: absolute.end }, absolute.played)
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
const images = [];
|
|
497
|
+
for (const image of parseImageElements(html)) {
|
|
498
|
+
const absolute = toAbsoluteWindow(image.start, image.end, windowFor(image.id));
|
|
499
|
+
if (absolute) images.push({ ...image, start: absolute.start, end: absolute.end });
|
|
500
|
+
else droppedMediaIds.add(image.id);
|
|
501
|
+
}
|
|
502
|
+
const audios = [];
|
|
503
|
+
for (const audio of parseAudioElements(html)) {
|
|
504
|
+
const elementId = audio.type === "video" ? audio.id.replace(/-audio$/, "") : audio.id;
|
|
505
|
+
const placed = placeAudio(audio, windowFor(elementId));
|
|
506
|
+
if (placed) audios.push(placed);
|
|
507
|
+
else droppedMediaIds.add(elementId);
|
|
508
|
+
}
|
|
509
|
+
return { videos, audios, images, droppedMediaIds, gradedCanvas: hasGradedCanvas(html) };
|
|
510
|
+
}
|
|
511
|
+
function placeAudio(audio, window2) {
|
|
512
|
+
const authoredEnd = audio.end > 0 ? audio.end : Infinity;
|
|
513
|
+
const absolute = toAbsoluteWindow(audio.start, authoredEnd, window2);
|
|
514
|
+
if (!absolute) return null;
|
|
515
|
+
const end = Number.isFinite(absolute.end) ? absolute.end : 0;
|
|
516
|
+
return startAtPlayed({ ...audio, start: absolute.start, end }, absolute.played);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/services/htmlCompiler.ts
|
|
520
|
+
import {
|
|
521
|
+
analyzeKeyframeIntervals,
|
|
522
|
+
assertMediaPayload,
|
|
523
|
+
createConcurrencyLimit,
|
|
524
|
+
isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
|
|
525
|
+
NotMediaPayloadError as NotMediaPayloadError2,
|
|
526
|
+
parseMasterFxChain,
|
|
527
|
+
probeMediaProfile as probeMediaProfile2
|
|
528
|
+
} from "@hyperframes/engine";
|
|
529
|
+
|
|
530
|
+
// src/utils/urlDownloader.ts
|
|
531
|
+
import {
|
|
532
|
+
downloadToTemp,
|
|
533
|
+
fetchPublicHttpsBytes,
|
|
534
|
+
fetchPublicHttpsText,
|
|
535
|
+
isHttpUrl,
|
|
536
|
+
safeDownloadUrlIdentity,
|
|
537
|
+
writeUrlDownloadTelemetry
|
|
538
|
+
} from "@hyperframes/engine";
|
|
539
|
+
|
|
540
|
+
// src/services/htmlCompiler.ts
|
|
541
|
+
import {
|
|
542
|
+
injectDeterministicFontFaces,
|
|
543
|
+
normalizeSystemFontPrimaryFamilies
|
|
544
|
+
} from "@hyperframes/core/fonts/embed";
|
|
545
|
+
|
|
546
|
+
// src/services/animatedGifPrep.ts
|
|
547
|
+
import { createHash } from "node:crypto";
|
|
548
|
+
import { copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, rmSync, statSync as statSync2 } from "node:fs";
|
|
549
|
+
import { dirname, isAbsolute, join as join3, resolve } from "node:path";
|
|
550
|
+
import { parseHTML as parseHTML2 } from "linkedom";
|
|
551
|
+
import { parseAnimatedGifMetadata } from "@hyperframes/core";
|
|
552
|
+
import {
|
|
553
|
+
DEFAULT_VP9_CPU_USED,
|
|
554
|
+
isPrivateUnderAssetRoots,
|
|
555
|
+
runFfmpeg,
|
|
556
|
+
renameWithRetry,
|
|
557
|
+
urlInputArgs
|
|
558
|
+
} from "@hyperframes/engine";
|
|
559
|
+
import { namesAnotherNetworkRoot } from "@hyperframes/parsers/asset-resolution";
|
|
560
|
+
|
|
561
|
+
// src/services/render/encoderInterruption.ts
|
|
562
|
+
var ENCODER_INTERRUPTED = "ENCODER_INTERRUPTED";
|
|
563
|
+
var EncoderInterruptedError = class extends Error {
|
|
564
|
+
code = ENCODER_INTERRUPTED;
|
|
565
|
+
owner = "system";
|
|
566
|
+
retryable = true;
|
|
567
|
+
/** Retained inside the producer for diagnostics; never copied to the wire envelope. */
|
|
568
|
+
diagnosticMessage;
|
|
569
|
+
audioFailures;
|
|
570
|
+
constructor(prefix, diagnosticMessage, audioFailures = []) {
|
|
571
|
+
super(`${prefix}: encoder process was interrupted by the host lifecycle`);
|
|
572
|
+
this.name = "EncoderInterruptedError";
|
|
573
|
+
this.diagnosticMessage = diagnosticMessage;
|
|
574
|
+
this.audioFailures = audioFailures;
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
function encoderFailureError(prefix, result) {
|
|
578
|
+
const message = `${prefix}: ${result.error ?? "unknown encoder failure"}`;
|
|
579
|
+
return result.failureReason === "external_interruption" ? new EncoderInterruptedError(prefix, message, result.audioFailures) : new Error(message);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/services/animatedGifPrep.ts
|
|
583
|
+
var PREPARED_GIF_SUBDIR = "_animated_gif";
|
|
584
|
+
var CACHE_SCHEMA = "hfgif-v1";
|
|
585
|
+
function splitUrlSuffix(src) {
|
|
586
|
+
const queryIdx = src.indexOf("?");
|
|
587
|
+
const hashIdx = src.indexOf("#");
|
|
588
|
+
if (queryIdx < 0 && hashIdx < 0) return { basePath: src, suffix: "" };
|
|
589
|
+
const cutIdx = queryIdx < 0 ? hashIdx : hashIdx < 0 ? queryIdx : Math.min(queryIdx, hashIdx);
|
|
590
|
+
return { basePath: src.slice(0, cutIdx), suffix: src.slice(cutIdx) };
|
|
591
|
+
}
|
|
592
|
+
function normalizeRelPath(path) {
|
|
593
|
+
return path.replace(/\\/g, "/").replace(/^\/+/, "");
|
|
594
|
+
}
|
|
595
|
+
function hasGifExtension(src) {
|
|
596
|
+
const { basePath } = splitUrlSuffix(src.trim().toLowerCase());
|
|
597
|
+
return basePath.endsWith(".gif");
|
|
598
|
+
}
|
|
599
|
+
function readLoopOverride(el) {
|
|
600
|
+
const raw = el.getAttribute("data-loop");
|
|
601
|
+
if (raw == null) return null;
|
|
602
|
+
const normalized = raw.trim().toLowerCase();
|
|
603
|
+
if (normalized === "" || normalized === "true" || normalized === "1" || normalized === "yes") {
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
if (normalized === "false" || normalized === "0" || normalized === "no") {
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
function resolveLocalImageSourcePath(src, options2) {
|
|
612
|
+
const trimmed = src.trim();
|
|
613
|
+
if (!trimmed || trimmed.startsWith("data:")) return null;
|
|
614
|
+
const { basePath } = splitUrlSuffix(trimmed);
|
|
615
|
+
const normalizedBase = normalizeRelPath(basePath);
|
|
616
|
+
const mapped = options2.sourceAssets?.get(trimmed) ?? options2.sourceAssets?.get(basePath) ?? options2.sourceAssets?.get(normalizedBase);
|
|
617
|
+
if (mapped && existsSync2(mapped)) return mapped;
|
|
618
|
+
if (isHttpUrl(trimmed)) return null;
|
|
619
|
+
const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
|
|
620
|
+
const candidates = [
|
|
621
|
+
isAbsolute(basePath) ? basePath : resolve(options2.projectDir, projectRelative),
|
|
622
|
+
resolve(options2.downloadDir, normalizedBase)
|
|
623
|
+
];
|
|
624
|
+
const assetRoot = options2.allowOutsideFiles ? void 0 : options2.projectDir;
|
|
625
|
+
const allowed = (candidate) => !namesAnotherNetworkRoot(options2.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options2.projectDir, options2.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options2.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options2.downloadDir));
|
|
626
|
+
return candidates.find((candidate) => allowed(candidate) && existsSync2(candidate)) ?? null;
|
|
627
|
+
}
|
|
628
|
+
function isUsableFile(path) {
|
|
629
|
+
try {
|
|
630
|
+
const stat = statSync2(path);
|
|
631
|
+
return stat.isFile() && stat.size > 0;
|
|
632
|
+
} catch {
|
|
633
|
+
return false;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function computePreparedGifHash(bytes, loopIterations, padSeconds) {
|
|
637
|
+
return createHash("sha256").update(CACHE_SCHEMA).update("\0").update(String(loopIterations)).update("\0").update(String(padSeconds)).update("\0").update(bytes).digest("hex");
|
|
638
|
+
}
|
|
639
|
+
function resolveLoop(metadata, override) {
|
|
640
|
+
if (override != null) return override;
|
|
641
|
+
return metadata.loopCount === 0;
|
|
642
|
+
}
|
|
643
|
+
var MAX_LOOP_ITERATIONS = 1e3;
|
|
644
|
+
var MAX_PAD_SECONDS = 3600;
|
|
645
|
+
function resolveCompositionDurationSeconds(document2) {
|
|
646
|
+
let max = null;
|
|
647
|
+
for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
|
|
648
|
+
const value = Number.parseFloat(el.getAttribute("data-duration") || "");
|
|
649
|
+
if (Number.isFinite(value) && value > 0) {
|
|
650
|
+
max = max == null ? value : Math.max(max, value);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return max;
|
|
654
|
+
}
|
|
655
|
+
function resolveClipWindowSeconds(img, compositionDuration) {
|
|
656
|
+
const durationRaw = img.getAttribute("data-duration");
|
|
657
|
+
if (durationRaw != null) {
|
|
658
|
+
const duration = Number.parseFloat(durationRaw);
|
|
659
|
+
if (Number.isFinite(duration) && duration > 0) return duration;
|
|
660
|
+
}
|
|
661
|
+
if (compositionDuration != null) {
|
|
662
|
+
const startRaw = Number.parseFloat(img.getAttribute("data-start") || "0");
|
|
663
|
+
const start = Number.isFinite(startRaw) && startRaw > 0 ? startRaw : 0;
|
|
664
|
+
const window2 = compositionDuration - start;
|
|
665
|
+
return window2 > 0 ? window2 : null;
|
|
666
|
+
}
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
|
|
670
|
+
const gifDuration = metadata.durationSeconds > 0 ? metadata.durationSeconds : null;
|
|
671
|
+
let loopIterations = 1;
|
|
672
|
+
if (resolveLoop(metadata, loopOverride)) {
|
|
673
|
+
loopIterations = windowSeconds != null && gifDuration != null ? Math.min(MAX_LOOP_ITERATIONS, Math.max(1, Math.ceil(windowSeconds / gifDuration))) : 1;
|
|
674
|
+
} else if (loopOverride == null && metadata.loopCount != null && metadata.loopCount > 1) {
|
|
675
|
+
loopIterations = Math.min(MAX_LOOP_ITERATIONS, metadata.loopCount);
|
|
676
|
+
}
|
|
677
|
+
let padSeconds = 0;
|
|
678
|
+
if (windowSeconds != null && gifDuration != null) {
|
|
679
|
+
const covered = gifDuration * loopIterations;
|
|
680
|
+
if (windowSeconds > covered) {
|
|
681
|
+
padSeconds = Math.min(windowSeconds - covered, MAX_PAD_SECONDS);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
|
|
685
|
+
}
|
|
686
|
+
function buildAnimatedGifTranscodeArgs(input) {
|
|
687
|
+
const args = ["-hide_banner", "-loglevel", "error"];
|
|
688
|
+
if (input.loopIterations > 1) {
|
|
689
|
+
args.push("-stream_loop", String(input.loopIterations - 1));
|
|
690
|
+
}
|
|
691
|
+
args.push(
|
|
692
|
+
"-ignore_loop",
|
|
693
|
+
"1",
|
|
694
|
+
...urlInputArgs(input.inputPath),
|
|
695
|
+
"-i",
|
|
696
|
+
input.inputPath,
|
|
697
|
+
"-an",
|
|
698
|
+
"-c:v",
|
|
699
|
+
"libvpx-vp9",
|
|
700
|
+
"-pix_fmt",
|
|
701
|
+
"yuva420p",
|
|
702
|
+
"-auto-alt-ref",
|
|
703
|
+
"0",
|
|
704
|
+
"-deadline",
|
|
705
|
+
"good",
|
|
706
|
+
"-cpu-used",
|
|
707
|
+
String(DEFAULT_VP9_CPU_USED),
|
|
708
|
+
"-crf",
|
|
709
|
+
"18",
|
|
710
|
+
"-b:v",
|
|
711
|
+
"0",
|
|
712
|
+
...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
|
|
713
|
+
// Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
|
|
714
|
+
// extension ffmpeg cannot infer the container from.
|
|
715
|
+
"-f",
|
|
716
|
+
"webm",
|
|
717
|
+
"-y",
|
|
718
|
+
input.outputPath
|
|
719
|
+
);
|
|
720
|
+
return args;
|
|
721
|
+
}
|
|
722
|
+
async function runAnimatedGifTranscode(request) {
|
|
723
|
+
const timeout = request.timeoutMs ?? 3e5;
|
|
724
|
+
const result = await runFfmpeg(request.args, { timeout });
|
|
725
|
+
if (result.success) return;
|
|
726
|
+
if (result.failureReason === "external_interruption") {
|
|
727
|
+
throw encoderFailureError("Animated GIF transcode failed", {
|
|
728
|
+
error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
|
|
729
|
+
failureReason: result.failureReason
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
if (result.terminationReason === "inactivity") {
|
|
733
|
+
throw new Error(`Animated GIF transcode timed out after ${timeout}ms`);
|
|
734
|
+
}
|
|
735
|
+
throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
|
|
736
|
+
}
|
|
737
|
+
async function ensurePreparedWebm(input) {
|
|
738
|
+
if (!existsSync2(dirname(input.cachePath))) {
|
|
739
|
+
mkdirSync(dirname(input.cachePath), { recursive: true });
|
|
740
|
+
}
|
|
741
|
+
if (!existsSync2(dirname(input.outputPath))) {
|
|
742
|
+
mkdirSync(dirname(input.outputPath), { recursive: true });
|
|
743
|
+
}
|
|
744
|
+
if (!isUsableFile(input.cachePath)) {
|
|
745
|
+
const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
|
|
746
|
+
const args = buildAnimatedGifTranscodeArgs({
|
|
747
|
+
inputPath: input.sourcePath,
|
|
748
|
+
outputPath: tmpPath,
|
|
749
|
+
loopIterations: input.loopIterations,
|
|
750
|
+
padSeconds: input.padSeconds
|
|
751
|
+
});
|
|
752
|
+
const transcode = input.transcode ?? runAnimatedGifTranscode;
|
|
753
|
+
try {
|
|
754
|
+
await transcode({
|
|
755
|
+
inputPath: input.sourcePath,
|
|
756
|
+
outputPath: tmpPath,
|
|
757
|
+
args,
|
|
758
|
+
timeoutMs: input.timeoutMs
|
|
759
|
+
});
|
|
760
|
+
if (!isUsableFile(tmpPath)) {
|
|
761
|
+
throw new Error("Animated GIF transcode produced an empty output");
|
|
762
|
+
}
|
|
763
|
+
if (!isUsableFile(input.cachePath)) {
|
|
764
|
+
renameWithRetry(tmpPath, input.cachePath);
|
|
765
|
+
} else {
|
|
766
|
+
rmSync(tmpPath, { force: true });
|
|
767
|
+
}
|
|
768
|
+
} catch (error) {
|
|
769
|
+
rmSync(tmpPath, { force: true });
|
|
770
|
+
throw error;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
if (resolve(input.outputPath) !== resolve(input.cachePath) && !isUsableFile(input.outputPath)) {
|
|
774
|
+
copyFileSync(input.cachePath, input.outputPath);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
function ensureElementId(el, document2, fallbackIndex) {
|
|
778
|
+
const existing = (el.getAttribute("id") || "").trim();
|
|
779
|
+
if (existing) return existing;
|
|
780
|
+
let next = fallbackIndex;
|
|
781
|
+
while (document2.getElementById(`hf-gif-${next}`)) next += 1;
|
|
782
|
+
const id = `hf-gif-${next}`;
|
|
783
|
+
el.setAttribute("id", id);
|
|
784
|
+
return id;
|
|
785
|
+
}
|
|
786
|
+
function ensureTimingAttributes(video) {
|
|
787
|
+
if (!video.hasAttribute("data-start")) {
|
|
788
|
+
video.setAttribute("data-start", "0");
|
|
789
|
+
}
|
|
790
|
+
if (!video.hasAttribute("data-end")) {
|
|
791
|
+
const durationRaw = video.getAttribute("data-duration");
|
|
792
|
+
if (durationRaw != null) {
|
|
793
|
+
const start = Number.parseFloat(video.getAttribute("data-start") || "0");
|
|
794
|
+
const duration = Number.parseFloat(durationRaw);
|
|
795
|
+
if (Number.isFinite(start) && Number.isFinite(duration) && duration > 0) {
|
|
796
|
+
video.setAttribute("data-end", String(start + duration));
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
function replaceImageWithVideo(input) {
|
|
802
|
+
const document2 = input.img.ownerDocument;
|
|
803
|
+
const video = document2.createElement("video");
|
|
804
|
+
for (const attr of Array.from(input.img.attributes)) {
|
|
805
|
+
if (attr.name === "src") continue;
|
|
806
|
+
video.setAttribute(attr.name, attr.value);
|
|
807
|
+
}
|
|
808
|
+
video.setAttribute("id", input.id);
|
|
809
|
+
video.setAttribute("src", input.outputSrc);
|
|
810
|
+
video.setAttribute("muted", "");
|
|
811
|
+
video.setAttribute("playsinline", "");
|
|
812
|
+
video.setAttribute("preload", "auto");
|
|
813
|
+
video.setAttribute("data-has-audio", "false");
|
|
814
|
+
video.setAttribute("data-hf-prepared-gif", "true");
|
|
815
|
+
if (input.loop) {
|
|
816
|
+
video.setAttribute("loop", "");
|
|
817
|
+
} else {
|
|
818
|
+
video.removeAttribute("loop");
|
|
819
|
+
}
|
|
820
|
+
ensureTimingAttributes(video);
|
|
821
|
+
input.img.replaceWith(video);
|
|
822
|
+
return video;
|
|
823
|
+
}
|
|
824
|
+
async function prepareAnimatedGifInputs(html, options2) {
|
|
825
|
+
const outputDir = options2.outputDir ?? join3(options2.downloadDir, PREPARED_GIF_SUBDIR);
|
|
826
|
+
const outputSrcPrefix = normalizeRelPath(options2.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
|
|
827
|
+
const cacheDir = options2.cacheDir ?? outputDir;
|
|
828
|
+
const { document: document2 } = parseHTML2(html);
|
|
829
|
+
const preparedAssets = /* @__PURE__ */ new Map();
|
|
830
|
+
const preparedGifs = [];
|
|
831
|
+
const images = Array.from(document2.querySelectorAll("img[src]"));
|
|
832
|
+
const compositionDuration = resolveCompositionDurationSeconds(document2);
|
|
833
|
+
for (let i = 0; i < images.length; i++) {
|
|
834
|
+
const img = images[i];
|
|
835
|
+
const src = (img.getAttribute("src") || "").trim();
|
|
836
|
+
if (!hasGifExtension(src)) continue;
|
|
837
|
+
const sourcePath = resolveLocalImageSourcePath(src, options2);
|
|
838
|
+
if (!sourcePath) continue;
|
|
839
|
+
const bytes = readFileSync2(sourcePath);
|
|
840
|
+
const metadata = parseAnimatedGifMetadata(bytes);
|
|
841
|
+
if (!metadata?.animated) continue;
|
|
842
|
+
const loopOverride = readLoopOverride(img);
|
|
843
|
+
const loop = resolveLoop(metadata, loopOverride);
|
|
844
|
+
const windowSeconds = resolveClipWindowSeconds(img, compositionDuration);
|
|
845
|
+
const { loopIterations, padSeconds } = resolvePreparedPlayback(
|
|
846
|
+
metadata,
|
|
847
|
+
loopOverride,
|
|
848
|
+
windowSeconds
|
|
849
|
+
);
|
|
850
|
+
const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
|
|
851
|
+
const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
|
|
852
|
+
const cachePath = join3(cacheDir, filename);
|
|
853
|
+
const outputPath = join3(outputDir, filename);
|
|
854
|
+
const outputSrc = `${outputSrcPrefix}/${filename}`;
|
|
855
|
+
await ensurePreparedWebm({
|
|
856
|
+
sourcePath,
|
|
857
|
+
cachePath,
|
|
858
|
+
outputPath,
|
|
859
|
+
loopIterations,
|
|
860
|
+
padSeconds,
|
|
861
|
+
timeoutMs: options2.timeoutMs,
|
|
862
|
+
transcode: options2.transcode
|
|
863
|
+
});
|
|
864
|
+
const id = ensureElementId(img, document2, i);
|
|
865
|
+
replaceImageWithVideo({ img, id, outputSrc, loop });
|
|
866
|
+
preparedAssets.set(outputSrc, outputPath);
|
|
867
|
+
preparedGifs.push({
|
|
868
|
+
id,
|
|
869
|
+
sourceSrc: src,
|
|
870
|
+
outputSrc,
|
|
871
|
+
outputPath,
|
|
872
|
+
metadata,
|
|
873
|
+
loop,
|
|
874
|
+
loopIterations,
|
|
875
|
+
padSeconds
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
return {
|
|
879
|
+
html: preparedGifs.length > 0 ? document2.toString() : html,
|
|
880
|
+
preparedAssets,
|
|
881
|
+
preparedGifs
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/services/heifImagePrep.ts
|
|
886
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
887
|
+
import {
|
|
888
|
+
closeSync,
|
|
889
|
+
copyFileSync as copyFileSync2,
|
|
890
|
+
mkdirSync as mkdirSync2,
|
|
891
|
+
openSync,
|
|
892
|
+
readFileSync as readFileSync3,
|
|
893
|
+
readSync,
|
|
894
|
+
rmSync as rmSync2,
|
|
895
|
+
statSync as statSync3,
|
|
896
|
+
writeFileSync
|
|
897
|
+
} from "node:fs";
|
|
898
|
+
import { dirname as dirname2, join as join4, resolve as resolve2 } from "node:path";
|
|
899
|
+
import { parseHTML as parseHTML3 } from "linkedom";
|
|
900
|
+
import { renameWithRetry as renameWithRetry2, runFfmpeg as runFfmpeg2, runFfprobe, urlInputArgs as urlInputArgs2 } from "@hyperframes/engine";
|
|
901
|
+
|
|
902
|
+
// src/services/heifRotation.ts
|
|
903
|
+
function* boxes(buf, start, end) {
|
|
904
|
+
let at = start;
|
|
905
|
+
while (at + 8 <= end) {
|
|
906
|
+
let size = buf.readUInt32BE(at);
|
|
907
|
+
let header = 8;
|
|
908
|
+
if (size === 1 && at + 16 <= end) {
|
|
909
|
+
size = Number(buf.readBigUInt64BE(at + 8));
|
|
910
|
+
header = 16;
|
|
911
|
+
} else if (size === 0) {
|
|
912
|
+
size = end - at;
|
|
913
|
+
}
|
|
914
|
+
if (size < header || at + size > end) return;
|
|
915
|
+
yield { type: buf.toString("latin1", at + 4, at + 8), start: at + header, end: at + size };
|
|
916
|
+
at += size;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
function child(buf, parent, type, skip = 0) {
|
|
920
|
+
return [...boxes(buf, parent.start + skip, parent.end)].filter((box) => box.type === type);
|
|
921
|
+
}
|
|
922
|
+
function readHeifPrimaryRotation(buf) {
|
|
923
|
+
try {
|
|
924
|
+
const root = { type: "", start: 0, end: buf.length };
|
|
925
|
+
const meta = child(buf, root, "meta")[0];
|
|
926
|
+
const pitm = meta && child(buf, meta, "pitm", 4)[0];
|
|
927
|
+
const iprp = meta && child(buf, meta, "iprp", 4)[0];
|
|
928
|
+
const ipco = iprp && child(buf, iprp, "ipco")[0];
|
|
929
|
+
if (!pitm || !ipco || !iprp) return 0;
|
|
930
|
+
const primaryId = buf[pitm.start] === 0 ? buf.readUInt16BE(pitm.start + 4) : buf.readUInt32BE(pitm.start + 4);
|
|
931
|
+
const props = [...boxes(buf, ipco.start, ipco.end)];
|
|
932
|
+
for (const ipma of child(buf, iprp, "ipma")) {
|
|
933
|
+
const version = buf[ipma.start];
|
|
934
|
+
const wide = (buf[ipma.start + 3] & 1) === 1;
|
|
935
|
+
let at = ipma.start + 8;
|
|
936
|
+
for (let n = buf.readUInt32BE(ipma.start + 4); n > 0 && at < ipma.end; n--) {
|
|
937
|
+
const id = version < 1 ? buf.readUInt16BE(at) : buf.readUInt32BE(at);
|
|
938
|
+
at += version < 1 ? 2 : 4;
|
|
939
|
+
const count = buf[at++];
|
|
940
|
+
for (let i = 0; i < count; i++) {
|
|
941
|
+
const index = wide ? buf.readUInt16BE(at) & 32767 : buf[at] & 127;
|
|
942
|
+
at += wide ? 2 : 1;
|
|
943
|
+
const prop = props[index - 1];
|
|
944
|
+
if (id === primaryId && prop?.type === "irot")
|
|
945
|
+
return (buf[prop.start] & 3) * 90;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
} catch {
|
|
950
|
+
}
|
|
951
|
+
return 0;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// src/utils/semaphore.ts
|
|
955
|
+
var Semaphore = class {
|
|
956
|
+
constructor(maxConcurrent) {
|
|
957
|
+
this.maxConcurrent = maxConcurrent;
|
|
958
|
+
}
|
|
959
|
+
maxConcurrent;
|
|
960
|
+
queue = [];
|
|
961
|
+
active = 0;
|
|
962
|
+
async acquire() {
|
|
963
|
+
if (this.active < this.maxConcurrent) {
|
|
964
|
+
this.active++;
|
|
965
|
+
return () => this.release();
|
|
966
|
+
}
|
|
967
|
+
return new Promise((resolve4) => {
|
|
968
|
+
this.queue.push(() => {
|
|
969
|
+
this.active++;
|
|
970
|
+
resolve4(() => this.release());
|
|
971
|
+
});
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
release() {
|
|
975
|
+
this.active--;
|
|
976
|
+
const next = this.queue.shift();
|
|
977
|
+
if (next) next();
|
|
978
|
+
}
|
|
979
|
+
/** Current number of active slots. */
|
|
980
|
+
get activeCount() {
|
|
981
|
+
return this.active;
|
|
982
|
+
}
|
|
983
|
+
/** Number of waiters in the queue. */
|
|
984
|
+
get waitingCount() {
|
|
985
|
+
return this.queue.length;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
|
|
989
|
+
// src/utils/mediaProbeConcurrency.ts
|
|
990
|
+
var MEDIA_PROBE_CONCURRENCY = 4;
|
|
991
|
+
var sharedMediaProbeSemaphore = new Semaphore(MEDIA_PROBE_CONCURRENCY);
|
|
992
|
+
async function withMediaProbeSlot(operation) {
|
|
993
|
+
const release = await sharedMediaProbeSemaphore.acquire();
|
|
994
|
+
try {
|
|
995
|
+
return await operation();
|
|
996
|
+
} finally {
|
|
997
|
+
release();
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// src/services/heifImagePrep.ts
|
|
1002
|
+
var PREPARED_HEIF_SUBDIR = "_heif_images";
|
|
1003
|
+
var CACHE_SCHEMA2 = "hfheif-v1";
|
|
1004
|
+
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
1005
|
+
var HEIF_IMAGE_CONVERSION_FAILED = "HEIF_IMAGE_CONVERSION_FAILED";
|
|
1006
|
+
var HEIF_TOOL_UNAVAILABLE = "HEIF_TOOL_UNAVAILABLE";
|
|
1007
|
+
var HEIF_BRANDS = /* @__PURE__ */ new Set(["heic", "heix", "hevc", "hevx", "heim", "heis", "mif1", "msf1"]);
|
|
1008
|
+
var AVIF_BRANDS = /* @__PURE__ */ new Set(["avif", "avis"]);
|
|
1009
|
+
var DATA_URL_RE = /^data:image\/(?:heic|heif)(?:-sequence)?;base64,(.*)$/is;
|
|
1010
|
+
var HeifImageConversionError = class extends Error {
|
|
1011
|
+
code = HEIF_IMAGE_CONVERSION_FAILED;
|
|
1012
|
+
owner = "user";
|
|
1013
|
+
retryable = false;
|
|
1014
|
+
constructor(label, reason) {
|
|
1015
|
+
super(
|
|
1016
|
+
`Could not convert HEIC/HEIF image ${label} to JPEG: ${reason}. Re-export the photo as JPEG or PNG and update its src.`
|
|
1017
|
+
);
|
|
1018
|
+
this.name = "HeifImageConversionError";
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
var HeifToolUnavailableError = class extends Error {
|
|
1022
|
+
code = HEIF_TOOL_UNAVAILABLE;
|
|
1023
|
+
owner = "system";
|
|
1024
|
+
retryable = false;
|
|
1025
|
+
constructor(label, reason) {
|
|
1026
|
+
super(
|
|
1027
|
+
`Could not convert HEIC/HEIF image ${label}: ${reason}. Converting HEIC needs ffmpeg and ffprobe 7.0 or newer with the hevc decoder.`
|
|
1028
|
+
);
|
|
1029
|
+
this.name = "HeifToolUnavailableError";
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
|
|
1033
|
+
function isHeifBytes(head) {
|
|
1034
|
+
const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
|
|
1035
|
+
if (bytes.length < 16 || bytes.toString("ascii", 4, 8) !== "ftyp") return false;
|
|
1036
|
+
const boxEnd = Math.min(bytes.readUInt32BE(0), bytes.length);
|
|
1037
|
+
if (boxEnd < 16) return false;
|
|
1038
|
+
const brands = [bytes.toString("ascii", 8, 12)];
|
|
1039
|
+
for (let offset = 16; offset + 4 <= boxEnd; offset += 4) {
|
|
1040
|
+
brands.push(bytes.toString("ascii", offset, offset + 4));
|
|
1041
|
+
}
|
|
1042
|
+
return !brands.some((b) => AVIF_BRANDS.has(b)) && brands.some((b) => HEIF_BRANDS.has(b));
|
|
1043
|
+
}
|
|
1044
|
+
function readHead(path) {
|
|
1045
|
+
let fd;
|
|
1046
|
+
try {
|
|
1047
|
+
fd = openSync(path, "r");
|
|
1048
|
+
const buf = Buffer.alloc(4096);
|
|
1049
|
+
return buf.subarray(0, readSync(fd, buf, 0, buf.length, 0));
|
|
1050
|
+
} catch {
|
|
1051
|
+
return null;
|
|
1052
|
+
} finally {
|
|
1053
|
+
if (fd !== void 0) closeSync(fd);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
async function probeJson(path, withGroups) {
|
|
1057
|
+
const stdout = await runFfprobe(
|
|
1058
|
+
path,
|
|
1059
|
+
withGroups ? ["-show_stream_groups", "-show_streams", "-of", "json"] : ["-show_streams", "-of", "json"]
|
|
1060
|
+
);
|
|
1061
|
+
return JSON.parse(stdout);
|
|
1062
|
+
}
|
|
1063
|
+
var ROTATION_FILTER = {
|
|
1064
|
+
0: "",
|
|
1065
|
+
90: "transpose=2",
|
|
1066
|
+
180: "hflip,vflip",
|
|
1067
|
+
270: "transpose=1"
|
|
1068
|
+
};
|
|
1069
|
+
function primaryGrid(probed) {
|
|
1070
|
+
const groups = probed.stream_groups ?? [];
|
|
1071
|
+
return (groups.find((g) => g.disposition?.default === 1) ?? groups[0])?.components?.[0];
|
|
1072
|
+
}
|
|
1073
|
+
async function convertHeifToJpeg(request) {
|
|
1074
|
+
const probed = await probeJson(request.inputPath, true);
|
|
1075
|
+
const grid = primaryGrid(probed);
|
|
1076
|
+
const rotation = readHeifPrimaryRotation(readFileSync3(request.inputPath));
|
|
1077
|
+
const filters = [];
|
|
1078
|
+
let inputs = [];
|
|
1079
|
+
let size = probed.streams?.[0];
|
|
1080
|
+
if (grid?.subcomponents?.length) {
|
|
1081
|
+
size = grid;
|
|
1082
|
+
const layout = grid.subcomponents.map(
|
|
1083
|
+
(t) => `${t.tile_horizontal_offset}_${t.tile_vertical_offset}`
|
|
1084
|
+
);
|
|
1085
|
+
inputs = grid.subcomponents.map((t) => `[0:${t.stream_index}]`);
|
|
1086
|
+
filters.push(
|
|
1087
|
+
`${inputs.join("")}xstack=inputs=${inputs.length}:layout=${layout.join("|")}`,
|
|
1088
|
+
`crop=${grid.width}:${grid.height}:${grid.horizontal_offset ?? 0}:${grid.vertical_offset ?? 0}`
|
|
1089
|
+
);
|
|
1090
|
+
}
|
|
1091
|
+
if (!size?.width || !size.height) throw new Error("no declared image size");
|
|
1092
|
+
if (rotation && grid) filters.push(ROTATION_FILTER[rotation]);
|
|
1093
|
+
const mapArgs = filters.length > 0 ? ["-filter_complex", `${filters.join(",")}[v]`, "-map", "[v]"] : [];
|
|
1094
|
+
const result = await runFfmpeg2(
|
|
1095
|
+
[
|
|
1096
|
+
"-hide_banner",
|
|
1097
|
+
"-loglevel",
|
|
1098
|
+
"error",
|
|
1099
|
+
...urlInputArgs2(request.inputPath),
|
|
1100
|
+
"-i",
|
|
1101
|
+
request.inputPath,
|
|
1102
|
+
...mapArgs,
|
|
1103
|
+
"-frames:v",
|
|
1104
|
+
"1",
|
|
1105
|
+
"-q:v",
|
|
1106
|
+
"2",
|
|
1107
|
+
"-f",
|
|
1108
|
+
"mjpeg",
|
|
1109
|
+
"-y",
|
|
1110
|
+
request.outputPath
|
|
1111
|
+
],
|
|
1112
|
+
{ timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
|
|
1113
|
+
);
|
|
1114
|
+
if (!result.success) {
|
|
1115
|
+
throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
|
|
1116
|
+
}
|
|
1117
|
+
const out = (await probeJson(request.outputPath, false)).streams?.[0];
|
|
1118
|
+
const same = out?.width === size.width && out.height === size.height;
|
|
1119
|
+
const swapped = out?.width === size.height && out.height === size.width;
|
|
1120
|
+
if (!same && !swapped) {
|
|
1121
|
+
throw new Error(
|
|
1122
|
+
`wrong size: decoded ${out?.width}x${out?.height}, file declares ${size.width}x${size.height}`
|
|
1123
|
+
);
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
function resolveImageSource(src, options2) {
|
|
1127
|
+
const data = DATA_URL_RE.exec(src);
|
|
1128
|
+
if (data) {
|
|
1129
|
+
const bytes = Buffer.from(data[1], "base64");
|
|
1130
|
+
return isHeifBytes(bytes.subarray(0, 4096)) ? { path: null, bytes, label: '"inline image"' } : null;
|
|
1131
|
+
}
|
|
1132
|
+
const path = resolveLocalImageSourcePath(src, options2);
|
|
1133
|
+
const head = path ? readHead(path) : null;
|
|
1134
|
+
if (!path || !head || !isHeifBytes(head)) return null;
|
|
1135
|
+
return { path, bytes: readFileSync3(path), label: `"${splitUrlSuffix(src).basePath}"` };
|
|
1136
|
+
}
|
|
1137
|
+
function isUsableFile2(path) {
|
|
1138
|
+
try {
|
|
1139
|
+
return statSync3(path).size > 0;
|
|
1140
|
+
} catch {
|
|
1141
|
+
return false;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
async function ensurePreparedJpeg(source, cachePath, outputPath, options2) {
|
|
1145
|
+
mkdirSync2(dirname2(cachePath), { recursive: true });
|
|
1146
|
+
mkdirSync2(dirname2(outputPath), { recursive: true });
|
|
1147
|
+
if (!isUsableFile2(cachePath)) {
|
|
1148
|
+
const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
|
|
1149
|
+
const inlinePath = `${tmpPath}.heic`;
|
|
1150
|
+
const inputPath = source.path ?? inlinePath;
|
|
1151
|
+
try {
|
|
1152
|
+
if (!source.path) writeFileSync(inlinePath, source.bytes);
|
|
1153
|
+
await (options2.transcode ?? convertHeifToJpeg)({
|
|
1154
|
+
inputPath,
|
|
1155
|
+
outputPath: tmpPath,
|
|
1156
|
+
timeoutMs: options2.timeoutMs
|
|
1157
|
+
});
|
|
1158
|
+
if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
|
|
1159
|
+
renameWithRetry2(tmpPath, cachePath);
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1162
|
+
throw TOOL_FAILURE_RE.test(reason) ? new HeifToolUnavailableError(source.label, reason) : new HeifImageConversionError(source.label, reason);
|
|
1163
|
+
} finally {
|
|
1164
|
+
rmSync2(tmpPath, { force: true });
|
|
1165
|
+
rmSync2(inlinePath, { force: true });
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
if (resolve2(outputPath) !== resolve2(cachePath) && !isUsableFile2(outputPath)) {
|
|
1169
|
+
copyFileSync2(cachePath, outputPath);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
async function prepareHeifImageInputs(html, options2) {
|
|
1173
|
+
const outputDir = options2.outputDir ?? join4(options2.downloadDir, PREPARED_HEIF_SUBDIR);
|
|
1174
|
+
const outputSrcPrefix = normalizeRelPath(options2.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
|
|
1175
|
+
const cacheDir = options2.cacheDir ?? outputDir;
|
|
1176
|
+
const preparedAssets = /* @__PURE__ */ new Map();
|
|
1177
|
+
const preparedImages = [];
|
|
1178
|
+
if (!/<img\b/i.test(html)) return { html, preparedAssets, preparedImages };
|
|
1179
|
+
const { document: document2 } = parseHTML3(html);
|
|
1180
|
+
const found = [];
|
|
1181
|
+
for (const img of Array.from(document2.querySelectorAll("img[src]"))) {
|
|
1182
|
+
const src = (img.getAttribute("src") || "").trim();
|
|
1183
|
+
const source = src ? resolveImageSource(src, options2) : null;
|
|
1184
|
+
if (!source) continue;
|
|
1185
|
+
const hash = createHash2("sha256").update(CACHE_SCHEMA2).update("\0").update(source.bytes).digest("hex");
|
|
1186
|
+
found.push({ img, src, source, filename: `${CACHE_SCHEMA2}-${hash.slice(0, 24)}.jpg` });
|
|
1187
|
+
}
|
|
1188
|
+
if (found.length === 0) return { html, preparedAssets, preparedImages };
|
|
1189
|
+
const unique = new Map(found.map((item) => [item.filename, item.source]));
|
|
1190
|
+
const failed = /* @__PURE__ */ new Set();
|
|
1191
|
+
await Promise.all(
|
|
1192
|
+
[...unique].map(
|
|
1193
|
+
([filename, source]) => withMediaProbeSlot(
|
|
1194
|
+
() => ensurePreparedJpeg(source, join4(cacheDir, filename), join4(outputDir, filename), options2)
|
|
1195
|
+
).catch((error) => {
|
|
1196
|
+
if (!options2.onFailure) throw error;
|
|
1197
|
+
failed.add(filename);
|
|
1198
|
+
options2.onFailure(error);
|
|
1199
|
+
})
|
|
1200
|
+
)
|
|
1201
|
+
);
|
|
1202
|
+
for (const { img, src, filename } of found) {
|
|
1203
|
+
if (failed.has(filename)) continue;
|
|
1204
|
+
const outputSrc = `${outputSrcPrefix}/${filename}`;
|
|
1205
|
+
img.setAttribute("src", outputSrc);
|
|
1206
|
+
preparedAssets.set(outputSrc, join4(outputDir, filename));
|
|
1207
|
+
preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join4(outputDir, filename) });
|
|
1208
|
+
}
|
|
1209
|
+
return { html: document2.toString(), preparedAssets, preparedImages };
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// src/services/htmlCompiler.ts
|
|
1213
|
+
import {
|
|
1214
|
+
createStudioPositionSeekReapplyScript,
|
|
1215
|
+
htmlHasStudioPositionEdits
|
|
1216
|
+
} from "@hyperframes/studio-server/manual-edits-render-script";
|
|
1217
|
+
import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
|
|
1218
|
+
|
|
1219
|
+
// src/logger.ts
|
|
1220
|
+
import { terminalText } from "@hyperframes/core";
|
|
1221
|
+
var LOG_LEVEL_PRIORITY = {
|
|
1222
|
+
error: 0,
|
|
1223
|
+
warn: 1,
|
|
1224
|
+
info: 2,
|
|
1225
|
+
debug: 3
|
|
1226
|
+
};
|
|
1227
|
+
function createConsoleLogger(level = "info") {
|
|
1228
|
+
const threshold = LOG_LEVEL_PRIORITY[level];
|
|
1229
|
+
const shouldLog = (msgLevel) => LOG_LEVEL_PRIORITY[msgLevel] <= threshold;
|
|
1230
|
+
const formatMeta = (meta) => meta ? ` ${terminalText(JSON.stringify(meta))}` : "";
|
|
1231
|
+
return {
|
|
1232
|
+
error(message, meta) {
|
|
1233
|
+
if (shouldLog("error")) {
|
|
1234
|
+
console.error(`[ERROR] ${terminalText(message)}${formatMeta(meta)}`);
|
|
1235
|
+
}
|
|
1236
|
+
},
|
|
1237
|
+
warn(message, meta) {
|
|
1238
|
+
if (shouldLog("warn")) {
|
|
1239
|
+
console.warn(`[WARN] ${terminalText(message)}${formatMeta(meta)}`);
|
|
1240
|
+
}
|
|
1241
|
+
},
|
|
1242
|
+
info(message, meta) {
|
|
1243
|
+
if (shouldLog("info")) {
|
|
1244
|
+
console.error(`[INFO] ${terminalText(message)}${formatMeta(meta)}`);
|
|
1245
|
+
}
|
|
1246
|
+
},
|
|
1247
|
+
debug(message, meta) {
|
|
1248
|
+
if (shouldLog("debug")) {
|
|
1249
|
+
console.error(`[DEBUG] ${terminalText(message)}${formatMeta(meta)}`);
|
|
1250
|
+
}
|
|
1251
|
+
},
|
|
1252
|
+
isLevelEnabled(msgLevel) {
|
|
1253
|
+
return shouldLog(msgLevel);
|
|
1254
|
+
}
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
var defaultLogger = createConsoleLogger(
|
|
1258
|
+
process.env.HF_DEBUG_RENDER === "1" ? "debug" : "info"
|
|
1259
|
+
);
|
|
1260
|
+
|
|
1261
|
+
// src/services/assetMediaType.ts
|
|
1262
|
+
import {
|
|
1263
|
+
fingerprintElementId,
|
|
1264
|
+
isHttpUrl as isHttpUrl2,
|
|
1265
|
+
isInsideAssetRoots,
|
|
1266
|
+
isNotImagePayload,
|
|
1267
|
+
isNotMediaPayload,
|
|
1268
|
+
isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
|
|
1269
|
+
playlistLeavesItsFolder,
|
|
1270
|
+
NotMediaPayloadError,
|
|
1271
|
+
probeMediaProfile,
|
|
1272
|
+
resolveProjectRelativeSrc
|
|
1273
|
+
} from "@hyperframes/engine";
|
|
1274
|
+
var ASSET_MEDIA_TYPE_MISMATCH = "ASSET_MEDIA_TYPE_MISMATCH";
|
|
1275
|
+
var AssetMediaTypeMismatchError = class extends Error {
|
|
1276
|
+
// fallow-ignore-next-line unused-class-member
|
|
1277
|
+
code = ASSET_MEDIA_TYPE_MISMATCH;
|
|
1278
|
+
// fallow-ignore-next-line unused-class-member
|
|
1279
|
+
owner = "user";
|
|
1280
|
+
// fallow-ignore-next-line unused-class-member
|
|
1281
|
+
retryable = false;
|
|
1282
|
+
mismatches;
|
|
1283
|
+
constructor(mismatches) {
|
|
1284
|
+
const expectedKinds = [...new Set(mismatches.map((item) => item.expected))].sort().join(",");
|
|
1285
|
+
super(
|
|
1286
|
+
`${mismatches.length} composition asset(s) do not match their authored media element type` + (expectedKinds ? ` (expected: ${expectedKinds})` : "")
|
|
1287
|
+
);
|
|
1288
|
+
this.name = "AssetMediaTypeMismatchError";
|
|
1289
|
+
this.mismatches = mismatches;
|
|
1290
|
+
}
|
|
1291
|
+
};
|
|
1292
|
+
function detectedAssetMediaType(profile) {
|
|
1293
|
+
if (profile.visualKind === "moving") return "video";
|
|
1294
|
+
if (profile.visualKind === "still") return "image";
|
|
1295
|
+
if (profile.hasAudioStream) return "audio";
|
|
1296
|
+
return "unknown";
|
|
1297
|
+
}
|
|
1298
|
+
function mediaProfileMatchesElementType(expected, profile) {
|
|
1299
|
+
if (expected === "audio") return profile.hasAudioStream;
|
|
1300
|
+
if (expected === "image") return profile.visualKind === "still";
|
|
1301
|
+
return profile.visualKind === "moving";
|
|
1302
|
+
}
|
|
1303
|
+
function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
|
|
1304
|
+
if (mediaProfileMatchesElementType(expected, profile)) return;
|
|
1305
|
+
throw new AssetMediaTypeMismatchError([
|
|
1306
|
+
{
|
|
1307
|
+
expected,
|
|
1308
|
+
detected: detectedAssetMediaType(profile),
|
|
1309
|
+
elementFingerprint: fingerprintElementId(elementIdentity)
|
|
1310
|
+
}
|
|
1311
|
+
]);
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// src/services/htmlCompiler.ts
|
|
1315
|
+
function logRemoteDownloadTelemetry(event) {
|
|
1316
|
+
defaultLogger.debug("[Compiler] Remote asset download integrity", { ...event });
|
|
1317
|
+
}
|
|
1318
|
+
var INFERRED_MEDIA_DURATION_ATTR = "data-hf-inferred-duration";
|
|
1319
|
+
function parseSubCompHtmlForValidity(html) {
|
|
1320
|
+
return parseHTML4(html).document;
|
|
1321
|
+
}
|
|
1322
|
+
function endsWithSourceUrl(code) {
|
|
1323
|
+
const trimmed = code.trimEnd();
|
|
1324
|
+
const lastLine = trimmed.slice(trimmed.lastIndexOf("\n") + 1).trimStart();
|
|
1325
|
+
return lastLine.startsWith("//# sourceURL=") || lastLine.startsWith("//@ sourceURL=");
|
|
1326
|
+
}
|
|
1327
|
+
function prepareCompositionScripts(html) {
|
|
1328
|
+
const { document: document2 } = parseHTML4(html);
|
|
1329
|
+
for (const el of document2.querySelectorAll("script:not([src])")) {
|
|
1330
|
+
const isModule = (el.getAttribute("type") || "").trim().toLowerCase() === "module";
|
|
1331
|
+
const runsAsScript = isModule || isJavaScriptType(el);
|
|
1332
|
+
const code = el.textContent ?? "";
|
|
1333
|
+
if (!runsAsScript || endsWithSourceUrl(code)) continue;
|
|
1334
|
+
el.textContent = `${code}
|
|
1335
|
+
//# sourceURL=${COMPOSITION_SOURCE_URL}`;
|
|
1336
|
+
}
|
|
1337
|
+
deferScriptsUntilFonts(document2);
|
|
1338
|
+
return document2.toString();
|
|
1339
|
+
}
|
|
1340
|
+
function injectSdkPositionEditsRenderScript(html) {
|
|
1341
|
+
if (!html.includes("data-hf-edit-base-x") && !html.includes("data-hf-edit-base-y")) {
|
|
1342
|
+
return html;
|
|
1343
|
+
}
|
|
1344
|
+
const scriptBody = getPositionEditsRenderScript().replace(/<\/script/gi, "<\\/script");
|
|
1345
|
+
const script = `<script>${scriptBody}
|
|
1346
|
+
//# sourceURL=hyperframes://position-edits</script>`;
|
|
1347
|
+
return insertBeforeCloseTag(html, "body", script) ?? `${html}${script}`;
|
|
1348
|
+
}
|
|
1349
|
+
var EmptyCompositionError = class extends Error {
|
|
1350
|
+
code = "EMPTY_COMPOSITION";
|
|
1351
|
+
problems;
|
|
1352
|
+
constructor(problems) {
|
|
1353
|
+
const lines = problems.map((p) => ` - ${p.srcPath}: ${p.detail}`);
|
|
1354
|
+
super(
|
|
1355
|
+
`${problems.length} composition file${problems.length === 1 ? "" : "s"} referenced by data-composition-src cannot be rendered:
|
|
1356
|
+
${lines.join("\n")}
|
|
1357
|
+
|
|
1358
|
+
Check that each file referenced by data-composition-src contains valid HTML with a [data-composition-id] element in a <template>, <body>, or bare fragment. If a scene-authoring step is still running, wait for it to finish before referencing the file.`
|
|
1359
|
+
);
|
|
1360
|
+
this.name = "EmptyCompositionError";
|
|
1361
|
+
this.problems = problems;
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
function normalizeCompositionSrcs(html, projectDir2) {
|
|
1365
|
+
return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
|
|
1366
|
+
if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
|
|
1367
|
+
const file = resolveCompositionSrc(projectDir2, value);
|
|
1368
|
+
if (file === null) return whole;
|
|
1369
|
+
return `${name}${quote}${relative(projectDir2, file).split(sep2).join("/")}${quote}`;
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
var COMPOSITION_FILE = /\.html?$/i;
|
|
1373
|
+
var NOT_A_COMPOSITION_FILE = "it is not an .html file, so it is refused";
|
|
1374
|
+
function resolveCompositionPath(projectDir2, src, assetRoot) {
|
|
1375
|
+
const file = resolveCompositionSrc(projectDir2, src);
|
|
1376
|
+
return file === null || escapesAssetRoot(file, assetRoot) ? null : file;
|
|
1377
|
+
}
|
|
1378
|
+
function resolveCompositionFile(projectDir2, src, assetRoot) {
|
|
1379
|
+
const file = resolveCompositionPath(projectDir2, src, assetRoot);
|
|
1380
|
+
return file !== null && COMPOSITION_FILE.test(file) ? file : null;
|
|
1381
|
+
}
|
|
1382
|
+
var OUTSIDE_COMPOSITION_NEEDS_FLAG = "it is outside the project, and any scripts in it would run; move it into the project, or pass --include-outside-files to hyperframes render, to include it";
|
|
1383
|
+
var runsOutsideMarkupUnasked = (projectDir2, filePath, assetRoot, outsideFiles) => assetRoot === void 0 && !outsideFiles.includeScripts && linksOutside2(projectDir2, filePath);
|
|
1384
|
+
function assertOutsideMarkupAsked(projectDir2, filePath, srcPath, assetRoot, outsideFiles) {
|
|
1385
|
+
if (runsOutsideMarkupUnasked(projectDir2, filePath, assetRoot, outsideFiles)) {
|
|
1386
|
+
throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
var isPrivateCompositionFile = (projectDir2, filePath) => isPrivateFileUnder(projectDir2, filePath, isStudioPrivatePath);
|
|
1390
|
+
function compositionSrcsIn(html) {
|
|
1391
|
+
const { document: document2 } = parseHTML4(html);
|
|
1392
|
+
const mounts = [];
|
|
1393
|
+
const templated = [];
|
|
1394
|
+
const stack = [...document2.children].reverse().map((el) => [el, false]);
|
|
1395
|
+
for (let next = stack.pop(); next; next = stack.pop()) {
|
|
1396
|
+
const [el, inTemplate] = next;
|
|
1397
|
+
const srcPath = el.getAttribute("data-composition-src");
|
|
1398
|
+
if (srcPath && !isUnresolvedAssetPlaceholder(srcPath)) {
|
|
1399
|
+
(inTemplate ? templated : mounts).push(srcPath);
|
|
1400
|
+
}
|
|
1401
|
+
const childrenInTemplate = inTemplate || el.localName === "template";
|
|
1402
|
+
const children = [...el.children];
|
|
1403
|
+
for (let i = children.length - 1; i >= 0; i -= 1)
|
|
1404
|
+
stack.push([children[i], childrenInTemplate]);
|
|
1405
|
+
}
|
|
1406
|
+
return { mounts, templated };
|
|
1407
|
+
}
|
|
1408
|
+
function compositionPathProblem(projectDir2, filePath, assetRoot, outsideFiles) {
|
|
1409
|
+
if (outsideAssetRefusal(projectDir2, filePath) === "blocklisted") {
|
|
1410
|
+
return "it is outside the project in a private location";
|
|
1411
|
+
}
|
|
1412
|
+
if (runsOutsideMarkupUnasked(projectDir2, filePath, assetRoot, outsideFiles)) {
|
|
1413
|
+
return OUTSIDE_COMPOSITION_NEEDS_FLAG;
|
|
1414
|
+
}
|
|
1415
|
+
if (isPrivateCompositionFile(projectDir2, filePath)) {
|
|
1416
|
+
return "it is git metadata, an env file or a private tool record";
|
|
1417
|
+
}
|
|
1418
|
+
return COMPOSITION_FILE.test(filePath) ? null : NOT_A_COMPOSITION_FILE;
|
|
1419
|
+
}
|
|
1420
|
+
function readSubCompositionFile(filePath, srcPath) {
|
|
1421
|
+
assertCompositionFileSize(filePath, srcPath);
|
|
1422
|
+
const read2 = readProjectFile(filePath);
|
|
1423
|
+
if (read2.kind === "missing") return { detail: "the file does not exist" };
|
|
1424
|
+
if (read2.kind === "folder") return { detail: "it is a folder, not an HTML file" };
|
|
1425
|
+
const validity = checkSubCompositionUsability(read2.text, parseSubCompHtmlForValidity);
|
|
1426
|
+
if (!validity.ok)
|
|
1427
|
+
return { detail: validity.detail ?? "the file is empty or could not be parsed" };
|
|
1428
|
+
return { bytes: Buffer.byteLength(read2.text), ...compositionSrcsIn(read2.text) };
|
|
1429
|
+
}
|
|
1430
|
+
function assertSubCompositionsUsable(html, projectDir2, assetRoot, outsideFiles) {
|
|
1431
|
+
const budget = new CompositionExpansionBudget();
|
|
1432
|
+
const files = /* @__PURE__ */ new Map();
|
|
1433
|
+
const problems = /* @__PURE__ */ new Map();
|
|
1434
|
+
const report = (srcPath, detail) => problems.set(`${srcPath}\0${detail}`, { srcPath, detail });
|
|
1435
|
+
const chain = /* @__PURE__ */ new Set();
|
|
1436
|
+
const paths = /* @__PURE__ */ new Map();
|
|
1437
|
+
const resolveMount = (srcPath) => {
|
|
1438
|
+
const filePath = resolveCompositionPath(projectDir2, srcPath, assetRoot);
|
|
1439
|
+
if (filePath === null) return { detail: "it is outside the project folder" };
|
|
1440
|
+
const detail = compositionPathProblem(projectDir2, filePath, assetRoot, outsideFiles);
|
|
1441
|
+
return detail ? { detail } : { filePath };
|
|
1442
|
+
};
|
|
1443
|
+
const walk = (srcPaths, quiet) => {
|
|
1444
|
+
for (const srcPath of srcPaths) {
|
|
1445
|
+
let resolved = paths.get(srcPath);
|
|
1446
|
+
if (!resolved) {
|
|
1447
|
+
resolved = resolveMount(srcPath);
|
|
1448
|
+
paths.set(srcPath, resolved);
|
|
1449
|
+
}
|
|
1450
|
+
if ("detail" in resolved) {
|
|
1451
|
+
if (!quiet) report(srcPath, resolved.detail);
|
|
1452
|
+
continue;
|
|
1453
|
+
}
|
|
1454
|
+
const { filePath } = resolved;
|
|
1455
|
+
if (chain.has(filePath)) continue;
|
|
1456
|
+
let file = files.get(filePath);
|
|
1457
|
+
if (!file) {
|
|
1458
|
+
file = readSubCompositionFile(filePath, srcPath);
|
|
1459
|
+
files.set(filePath, file);
|
|
1460
|
+
}
|
|
1461
|
+
if ("detail" in file) {
|
|
1462
|
+
if (!quiet) report(srcPath, file.detail);
|
|
1463
|
+
continue;
|
|
1464
|
+
}
|
|
1465
|
+
budget.charge(srcPath, file.bytes);
|
|
1466
|
+
chain.add(filePath);
|
|
1467
|
+
walk(file.mounts, quiet);
|
|
1468
|
+
walk(file.templated, true);
|
|
1469
|
+
chain.delete(filePath);
|
|
1470
|
+
}
|
|
1471
|
+
};
|
|
1472
|
+
const entry = compositionSrcsIn(html);
|
|
1473
|
+
walk(entry.mounts, false);
|
|
1474
|
+
walk(entry.templated, true);
|
|
1475
|
+
if (problems.size > 0) {
|
|
1476
|
+
throw new EmptyCompositionError([...problems.values()]);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
var COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
|
|
1480
|
+
var COMPILER_MOUNT_BLOCK_END = "/* __HF_COMPILER_MOUNT_END__ */";
|
|
1481
|
+
function stripJsComments(source) {
|
|
1482
|
+
return removeDelimitedRuns(source.replace(/\/\/.*$/gm, ""), "/*", "*/");
|
|
1483
|
+
}
|
|
1484
|
+
function stripCompilerMountBootstrap(source) {
|
|
1485
|
+
return removeDelimitedRuns(source, COMPILER_MOUNT_BLOCK_START, COMPILER_MOUNT_BLOCK_END);
|
|
1486
|
+
}
|
|
1487
|
+
function runtimeRoot(document2) {
|
|
1488
|
+
return document2.querySelector('[data-composition-id][data-root="true"]') ?? document2.querySelector("[data-composition-id]");
|
|
1489
|
+
}
|
|
1490
|
+
function detectRenderModeHints(html, pageMotionBlur) {
|
|
1491
|
+
const reasons = [];
|
|
1492
|
+
const { document: document2 } = parseHTML4(html);
|
|
1493
|
+
if (document2.querySelector(CAPTURE_CANVAS_SELECTOR)) {
|
|
1494
|
+
reasons.push({
|
|
1495
|
+
code: "htmlInCanvas",
|
|
1496
|
+
message: "Detected html-in-canvas API (layoutsubtree canvas). Chrome does not support concurrent drawElementImage across multiple workers; render is pinned to a single worker."
|
|
1497
|
+
});
|
|
1498
|
+
} else if (pageMotionBlur !== "off" && runtimeRoot(document2)?.getAttribute("data-motion-blur") === "on") {
|
|
1499
|
+
reasons.push({
|
|
1500
|
+
code: "captureMotionBlur",
|
|
1501
|
+
message: 'Detected motion blur (data-motion-blur="on"), drawn per frame with an SVG filter or, on the capture tier, html-in-canvas; routed through screenshot capture mode.'
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
if (document2.querySelector("iframe")) {
|
|
1505
|
+
reasons.push({
|
|
1506
|
+
code: "iframe",
|
|
1507
|
+
message: "Detected <iframe> in the composition DOM. Nested iframe animation is routed through screenshot capture mode for compatibility."
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
for (const { attrs, body } of inlineScriptBlocks(html)) {
|
|
1511
|
+
if (/\bsrc\s*=/i.test(attrs)) continue;
|
|
1512
|
+
const content = stripJsComments(stripCompilerMountBootstrap(body));
|
|
1513
|
+
if (!/requestAnimationFrame\s*\(/.test(content)) continue;
|
|
1514
|
+
reasons.push({
|
|
1515
|
+
code: "requestAnimationFrame",
|
|
1516
|
+
message: "Detected raw requestAnimationFrame() in an inline script. This render is routed through screenshot capture mode with virtual time enabled."
|
|
1517
|
+
});
|
|
1518
|
+
break;
|
|
1519
|
+
}
|
|
1520
|
+
return {
|
|
1521
|
+
recommendScreenshot: reasons.length > 0,
|
|
1522
|
+
reasons
|
|
1523
|
+
};
|
|
1524
|
+
}
|
|
1525
|
+
var THREE_D_CONTEXT_PATTERN = /transform-style\s*:\s*preserve-3d|backface-visibility\s*:|perspective\s*:\s*[0-9]|perspective\s*\(|matrix3d\s*\(|rotate3d\s*\(|\btransformPerspective\b/i;
|
|
1526
|
+
function detectThreeDTransformUsage(html) {
|
|
1527
|
+
return THREE_D_CONTEXT_PATTERN.test(html);
|
|
1528
|
+
}
|
|
1529
|
+
var CSS_ESCAPE = /\\(?:[0-9a-fA-F]{1,6}[ \t\n\r\f]?|[^])?/y;
|
|
1530
|
+
function ancestorSelectorSteps(list) {
|
|
1531
|
+
const selectors = [];
|
|
1532
|
+
let steps = [];
|
|
1533
|
+
let combinators = [];
|
|
1534
|
+
let compound = "";
|
|
1535
|
+
let open = false;
|
|
1536
|
+
let combinator = null;
|
|
1537
|
+
const skipGroup = (at, close) => {
|
|
1538
|
+
let depth = 0;
|
|
1539
|
+
for (let i = at; i < list.length; i++) {
|
|
1540
|
+
const ch = list[i];
|
|
1541
|
+
if (ch === "\\") i++;
|
|
1542
|
+
else if (ch === '"' || ch === "'") {
|
|
1543
|
+
const end = list.indexOf(ch, i + 1);
|
|
1544
|
+
if (end < 0) return -1;
|
|
1545
|
+
i = end;
|
|
1546
|
+
} else if (ch === list[at]) depth++;
|
|
1547
|
+
else if (ch === close && --depth === 0) return i;
|
|
1548
|
+
}
|
|
1549
|
+
return -1;
|
|
1550
|
+
};
|
|
1551
|
+
const flush = () => {
|
|
1552
|
+
if (!open) return;
|
|
1553
|
+
if ((combinator === "+" || combinator === "~") && steps.length > 0) {
|
|
1554
|
+
steps.pop();
|
|
1555
|
+
combinator = combinators.pop() ?? null;
|
|
1556
|
+
}
|
|
1557
|
+
steps.push({ compound: compound || "*", child: combinator === ">" });
|
|
1558
|
+
combinators.push(combinator);
|
|
1559
|
+
compound = "";
|
|
1560
|
+
open = false;
|
|
1561
|
+
combinator = null;
|
|
1562
|
+
};
|
|
1563
|
+
for (let i = 0; i <= list.length; i++) {
|
|
1564
|
+
const ch = list[i];
|
|
1565
|
+
if (ch === void 0 || ch === ",") {
|
|
1566
|
+
flush();
|
|
1567
|
+
if (steps.length) selectors.push(steps);
|
|
1568
|
+
steps = [];
|
|
1569
|
+
combinators = [];
|
|
1570
|
+
combinator = null;
|
|
1571
|
+
} else if (ch === "\\") {
|
|
1572
|
+
CSS_ESCAPE.lastIndex = i;
|
|
1573
|
+
const escape = CSS_ESCAPE.exec(list)[0];
|
|
1574
|
+
compound += escape;
|
|
1575
|
+
i += escape.length - 1;
|
|
1576
|
+
open = true;
|
|
1577
|
+
} else if (ch === "[") {
|
|
1578
|
+
const end = skipGroup(i, "]");
|
|
1579
|
+
if (end < 0) return null;
|
|
1580
|
+
compound += list.slice(i, end + 1);
|
|
1581
|
+
open = true;
|
|
1582
|
+
i = end;
|
|
1583
|
+
} else if (ch === ":") {
|
|
1584
|
+
while (/[:\w-]/.test(list[i + 1] ?? "")) i++;
|
|
1585
|
+
if (list[i + 1] === "(") i = skipGroup(i + 1, ")");
|
|
1586
|
+
if (i < 0) return null;
|
|
1587
|
+
open = true;
|
|
1588
|
+
} else if (/\s/.test(ch)) {
|
|
1589
|
+
flush();
|
|
1590
|
+
if (steps.length) combinator ??= " ";
|
|
1591
|
+
} else if (ch === ">" || ch === "+" || ch === "~") {
|
|
1592
|
+
flush();
|
|
1593
|
+
combinator = ch;
|
|
1594
|
+
} else if (ch === "(" || ch === ")" || ch === "]") {
|
|
1595
|
+
return null;
|
|
1596
|
+
} else {
|
|
1597
|
+
compound += ch;
|
|
1598
|
+
open = true;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
return selectors;
|
|
1602
|
+
}
|
|
1603
|
+
function matchesAnAncestor(steps, ancestors) {
|
|
1604
|
+
let reach = ancestors.map((el) => el.matches(steps[0].compound));
|
|
1605
|
+
for (const step of steps.slice(1)) {
|
|
1606
|
+
let above = false;
|
|
1607
|
+
const next = ancestors.map(() => false);
|
|
1608
|
+
for (let j = ancestors.length - 1; j >= 0; j--) {
|
|
1609
|
+
const placed = step.child ? reach[j + 1] === true : above;
|
|
1610
|
+
next[j] = placed && ancestors[j].matches(step.compound);
|
|
1611
|
+
above ||= reach[j];
|
|
1612
|
+
}
|
|
1613
|
+
reach = next;
|
|
1614
|
+
}
|
|
1615
|
+
return reach.includes(true);
|
|
1616
|
+
}
|
|
1617
|
+
var MAX_ROOT_ANCESTORS = 256;
|
|
1618
|
+
var MAX_ANCESTOR_SELECTOR_CHECKS = 1e5;
|
|
1619
|
+
function detectAncestorBackgroundImage(html) {
|
|
1620
|
+
const { document: document2 } = parseHTML4(html);
|
|
1621
|
+
const root = document2.querySelector("[data-composition-id]");
|
|
1622
|
+
if (!root) return false;
|
|
1623
|
+
const ancestors = [];
|
|
1624
|
+
for (let el = root.parentElement; el; el = el.parentElement) ancestors.push(el);
|
|
1625
|
+
if (document2.documentElement && !ancestors.includes(document2.documentElement)) {
|
|
1626
|
+
ancestors.push(document2.documentElement);
|
|
1627
|
+
}
|
|
1628
|
+
if (ancestors.length > MAX_ROOT_ANCESTORS) return true;
|
|
1629
|
+
let selectorChecks = 0;
|
|
1630
|
+
for (const el of ancestors) {
|
|
1631
|
+
const style = el.getAttribute("style");
|
|
1632
|
+
if (style && hasBackgroundImageDeclaration(`{${style}}`)) return true;
|
|
1633
|
+
}
|
|
1634
|
+
for (const styleEl of document2.querySelectorAll("style")) {
|
|
1635
|
+
const css = styleEl.textContent ?? "";
|
|
1636
|
+
for (const { parts: rule } of cssRuleMatches(css)) {
|
|
1637
|
+
const [, selectorList, declarations] = rule;
|
|
1638
|
+
if (!hasBackgroundImageDeclaration(`{${declarations}}`)) continue;
|
|
1639
|
+
if (selectorList.trim().startsWith("@")) continue;
|
|
1640
|
+
const selectors = ancestorSelectorSteps(selectorList);
|
|
1641
|
+
if (!selectors) return true;
|
|
1642
|
+
for (const steps of selectors) {
|
|
1643
|
+
selectorChecks += steps.length * ancestors.length;
|
|
1644
|
+
if (selectorChecks > MAX_ANCESTOR_SELECTOR_CHECKS) return true;
|
|
1645
|
+
try {
|
|
1646
|
+
if (matchesAnAncestor(steps, ancestors)) return true;
|
|
1647
|
+
} catch {
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return false;
|
|
1653
|
+
}
|
|
1654
|
+
var SHADER_TRANSITION_USAGE_PATTERN = /\b(?:(?:window|globalThis)\s*\.\s*)?HyperShader\s*\.\s*init\s*\(|\b__hf\s*\.\s*transitions\s*=/;
|
|
1655
|
+
function detectShaderTransitionUsage(html) {
|
|
1656
|
+
for (const { attrs, body } of inlineScriptBlocks(html)) {
|
|
1657
|
+
if (/\bsrc\s*=/i.test(attrs)) continue;
|
|
1658
|
+
const content = stripJsComments(stripCompilerMountBootstrap(body));
|
|
1659
|
+
if (SHADER_TRANSITION_USAGE_PATTERN.test(content)) return true;
|
|
1660
|
+
}
|
|
1661
|
+
return false;
|
|
1662
|
+
}
|
|
1663
|
+
var MAX_REMOTE_ASSETS = 1e3;
|
|
1664
|
+
var ASSET_DOWNLOADS_AT_ONCE = 8;
|
|
1665
|
+
var AssetDownloads = class {
|
|
1666
|
+
reserved = /* @__PURE__ */ new Set();
|
|
1667
|
+
running = 0;
|
|
1668
|
+
queued = [];
|
|
1669
|
+
ended = new AbortController();
|
|
1670
|
+
signal;
|
|
1671
|
+
constructor(cancel) {
|
|
1672
|
+
this.signal = cancel ? AbortSignal.any([cancel, this.ended.signal]) : this.ended.signal;
|
|
1673
|
+
}
|
|
1674
|
+
/** Stops every download still running or queued: the compile that owns them has returned. */
|
|
1675
|
+
end() {
|
|
1676
|
+
this.ended.abort(new Error("The compile that started this download has ended"));
|
|
1677
|
+
}
|
|
1678
|
+
/** Throws before any of `urls` downloads when they would take the compile past the cap. */
|
|
1679
|
+
reserve(urls) {
|
|
1680
|
+
this.signal?.throwIfAborted();
|
|
1681
|
+
const fresh = new Set([...urls].filter((url) => !this.reserved.has(url)));
|
|
1682
|
+
if (this.reserved.size + fresh.size > MAX_REMOTE_ASSETS) {
|
|
1683
|
+
throw new Error(
|
|
1684
|
+
`The composition links more than ${MAX_REMOTE_ASSETS} remote media, image and font files; at most ${MAX_REMOTE_ASSETS} are downloaded at compile time`
|
|
1685
|
+
);
|
|
1686
|
+
}
|
|
1687
|
+
for (const url of fresh) this.reserved.add(url);
|
|
1688
|
+
}
|
|
1689
|
+
async download(url, destDir) {
|
|
1690
|
+
while (this.running >= ASSET_DOWNLOADS_AT_ONCE) {
|
|
1691
|
+
await new Promise((resolve4) => this.queued.push(resolve4));
|
|
1692
|
+
}
|
|
1693
|
+
if (this.signal?.aborted) {
|
|
1694
|
+
this.queued.shift()?.();
|
|
1695
|
+
this.signal.throwIfAborted();
|
|
1696
|
+
}
|
|
1697
|
+
this.running += 1;
|
|
1698
|
+
try {
|
|
1699
|
+
return await downloadToTemp(url, destDir, void 0, this.signal, void 0, {
|
|
1700
|
+
onTelemetry: logRemoteDownloadTelemetry
|
|
1701
|
+
});
|
|
1702
|
+
} finally {
|
|
1703
|
+
this.running -= 1;
|
|
1704
|
+
this.queued.shift()?.();
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
var downloadAsset = (url, destDir, assets) => assets ? assets.download(url, destDir) : downloadToTemp(url, destDir, void 0, void 0, void 0, {
|
|
1709
|
+
onTelemetry: logRemoteDownloadTelemetry
|
|
1710
|
+
});
|
|
1711
|
+
async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir2, baseDir, downloadDir2, tagName, elementIdentity, log2, urlByAbsentLocalPath, run, assetRoot) {
|
|
1712
|
+
let filePath = src;
|
|
1713
|
+
if (isHttpUrl(src)) {
|
|
1714
|
+
const remoteDir = join5(downloadDir2, REMOTE_MEDIA_SUBDIR);
|
|
1715
|
+
if (!existsSync3(remoteDir)) mkdirSync3(remoteDir, { recursive: true });
|
|
1716
|
+
run?.assets.reserve([src]);
|
|
1717
|
+
try {
|
|
1718
|
+
filePath = await downloadAsset(src, remoteDir, run?.assets);
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
if (run?.assets.signal?.aborted) throw err;
|
|
1721
|
+
return { duration: null, resolvedPath: src };
|
|
1722
|
+
}
|
|
1723
|
+
} else {
|
|
1724
|
+
filePath = decodedUrlPath(src);
|
|
1725
|
+
if (!filePath.startsWith("/")) filePath = join5(baseDir, filePath);
|
|
1726
|
+
if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir2, downloadDir2])) {
|
|
1727
|
+
return { duration: null, resolvedPath: filePath };
|
|
1728
|
+
}
|
|
1729
|
+
filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
|
|
1730
|
+
if (!isHttpUrl(filePath) && namesAnotherNetworkRoot2(baseDir, filePath)) {
|
|
1731
|
+
return { duration: null, resolvedPath: filePath };
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
if (!isHttpUrl(filePath) && !existsSync3(filePath)) {
|
|
1735
|
+
return { duration: null, resolvedPath: filePath };
|
|
1736
|
+
}
|
|
1737
|
+
const withSrcContext = (error) => {
|
|
1738
|
+
if (error instanceof NotMediaPayloadError2) return error;
|
|
1739
|
+
const originalMessage = error instanceof Error ? error.message : String(error);
|
|
1740
|
+
const safeSrc = redactTelemetryString(src);
|
|
1741
|
+
const wrapped = new Error(`${originalMessage} [src=${safeSrc}]`);
|
|
1742
|
+
if (error instanceof Error && error.stack) wrapped.stack = error.stack;
|
|
1743
|
+
return wrapped;
|
|
1744
|
+
};
|
|
1745
|
+
const probe = () => withMediaProbeSlot(async () => {
|
|
1746
|
+
try {
|
|
1747
|
+
await assertMediaPayload(filePath, elementIdentity);
|
|
1748
|
+
const signal = run?.assets.signal;
|
|
1749
|
+
const profile = await probeMediaProfile2(filePath, { signal });
|
|
1750
|
+
if (tagName === "video") {
|
|
1751
|
+
const { durationSeconds } = await extractMediaMetadata(filePath, { signal });
|
|
1752
|
+
return { profile, fileDuration: durationSeconds };
|
|
1753
|
+
}
|
|
1754
|
+
try {
|
|
1755
|
+
const { durationSeconds } = await extractAudioMetadata(filePath, { signal });
|
|
1756
|
+
return { profile, fileDuration: durationSeconds };
|
|
1757
|
+
} catch {
|
|
1758
|
+
if (signal?.aborted) throw signal.reason;
|
|
1759
|
+
return { profile, fileDuration: null };
|
|
1760
|
+
}
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
return { error };
|
|
1763
|
+
}
|
|
1764
|
+
});
|
|
1765
|
+
const key = `${tagName}\0${filePath}`;
|
|
1766
|
+
let probed = run?.probes.get(key);
|
|
1767
|
+
if (!probed) {
|
|
1768
|
+
probed = probe();
|
|
1769
|
+
run?.probes.set(key, probed);
|
|
1770
|
+
}
|
|
1771
|
+
const outcome = await probed;
|
|
1772
|
+
if ("error" in outcome) {
|
|
1773
|
+
if (tagName !== "video") {
|
|
1774
|
+
if (outcome.error instanceof NotMediaPayloadError2) {
|
|
1775
|
+
log2?.warn(
|
|
1776
|
+
`[compile] Audio "${elementIdentity}" (${src}) is a text document, not a media file, so the element is dropped from the render. Point it at a rendered media file.`
|
|
1777
|
+
);
|
|
1778
|
+
}
|
|
1779
|
+
return { duration: null, resolvedPath: filePath };
|
|
1780
|
+
}
|
|
1781
|
+
throw withSrcContext(outcome.error);
|
|
1782
|
+
}
|
|
1783
|
+
assertAssetMediaTypeProfile(
|
|
1784
|
+
tagName === "video" ? "video" : "audio",
|
|
1785
|
+
outcome.profile,
|
|
1786
|
+
elementIdentity
|
|
1787
|
+
);
|
|
1788
|
+
if (outcome.fileDuration === null) return { duration: null, resolvedPath: filePath };
|
|
1789
|
+
const duration = resolveNaturalMediaTimelineDurationFromValues(
|
|
1790
|
+
outcome.fileDuration,
|
|
1791
|
+
mediaStart,
|
|
1792
|
+
playbackRate
|
|
1793
|
+
);
|
|
1794
|
+
return { duration, resolvedPath: filePath };
|
|
1795
|
+
}
|
|
1796
|
+
function markInferredVariableMediaDurations(html, unresolvedMedia) {
|
|
1797
|
+
const unresolvedIds = new Set(unresolvedMedia.map((element) => element.id));
|
|
1798
|
+
if (unresolvedIds.size === 0) return html;
|
|
1799
|
+
const { document: document2 } = parseHTML4(html);
|
|
1800
|
+
let changed = false;
|
|
1801
|
+
for (const element of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
|
|
1802
|
+
if (!unresolvedIds.has(element.id)) continue;
|
|
1803
|
+
element.setAttribute(INFERRED_MEDIA_DURATION_ATTR, "");
|
|
1804
|
+
changed = true;
|
|
1805
|
+
}
|
|
1806
|
+
return changed ? document2.toString() : html;
|
|
1807
|
+
}
|
|
1808
|
+
async function compileHtmlFile(html, projectDir2, baseDir, downloadDir2, log2, urlByAbsentLocalPath, run, assetRoot) {
|
|
1809
|
+
const { html: staticCompiled, unresolved } = compileTimingAttrs(html);
|
|
1810
|
+
const mediaUnresolved = unresolved.filter(
|
|
1811
|
+
(el) => (el.tagName === "video" || el.tagName === "audio") && el.src
|
|
1812
|
+
);
|
|
1813
|
+
const unresolvedCompositions = unresolved.filter((el) => el.tagName === "div");
|
|
1814
|
+
run?.assets.reserve(mediaUnresolved.map((el) => el.src).filter(isHttpUrl));
|
|
1815
|
+
const resolvedResults = await Promise.all(
|
|
1816
|
+
mediaUnresolved.map(
|
|
1817
|
+
(el) => resolveMediaDuration(
|
|
1818
|
+
el.src,
|
|
1819
|
+
el.mediaStart,
|
|
1820
|
+
el.playbackRate,
|
|
1821
|
+
projectDir2,
|
|
1822
|
+
baseDir,
|
|
1823
|
+
downloadDir2,
|
|
1824
|
+
el.tagName,
|
|
1825
|
+
el.id,
|
|
1826
|
+
log2,
|
|
1827
|
+
urlByAbsentLocalPath,
|
|
1828
|
+
run,
|
|
1829
|
+
assetRoot
|
|
1830
|
+
).then(({ duration }) => ({ id: el.id, duration }))
|
|
1831
|
+
)
|
|
1832
|
+
);
|
|
1833
|
+
const resolutions = resolvedResults.filter(
|
|
1834
|
+
(r) => r.duration != null && Number.isFinite(r.duration)
|
|
1835
|
+
);
|
|
1836
|
+
const markedStaticHtml = markInferredVariableMediaDurations(staticCompiled, mediaUnresolved);
|
|
1837
|
+
let compiledHtml = resolutions.length > 0 ? injectDurations(markedStaticHtml, resolutions) : markedStaticHtml;
|
|
1838
|
+
const preResolved = extractResolvedMedia(compiledHtml);
|
|
1839
|
+
const hiddenVideoIds = collectHiddenVideoIds(compiledHtml);
|
|
1840
|
+
const clampable = preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id));
|
|
1841
|
+
run?.assets.reserve(clampable.map((el) => el.src).filter(isHttpUrl));
|
|
1842
|
+
const clampResults = await Promise.all(
|
|
1843
|
+
clampable.map(async (el) => {
|
|
1844
|
+
const { duration: maxDuration } = await resolveMediaDuration(
|
|
1845
|
+
el.src,
|
|
1846
|
+
el.mediaStart,
|
|
1847
|
+
el.playbackRate,
|
|
1848
|
+
projectDir2,
|
|
1849
|
+
baseDir,
|
|
1850
|
+
downloadDir2,
|
|
1851
|
+
el.tagName,
|
|
1852
|
+
el.id,
|
|
1853
|
+
log2,
|
|
1854
|
+
void 0,
|
|
1855
|
+
run,
|
|
1856
|
+
assetRoot
|
|
1857
|
+
);
|
|
1858
|
+
return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src };
|
|
1859
|
+
})
|
|
1860
|
+
);
|
|
1861
|
+
const clampList = [];
|
|
1862
|
+
for (const r of clampResults) {
|
|
1863
|
+
if (r.maxDuration != null && shouldClampResolvedMediaDuration(r.tagName, r.duration, r.maxDuration)) {
|
|
1864
|
+
clampList.push({ id: r.id, duration: r.maxDuration });
|
|
1865
|
+
log2?.warn(
|
|
1866
|
+
`[compile] Audio "${r.id}" (${r.src}) is ${r.maxDuration.toFixed(2)}s but its data-duration is ${r.duration.toFixed(2)}s, so the slot is shortened to the media length. Set data-duration to ~${r.maxDuration.toFixed(2)}s, trim data-media-start, or use a longer/looping source if that isn't intended.`
|
|
1867
|
+
);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
if (clampList.length > 0) {
|
|
1871
|
+
compiledHtml = clampDurations(compiledHtml, clampList);
|
|
1872
|
+
}
|
|
1873
|
+
compiledHtml = stripCrossoriginAttr(compiledHtml, "video");
|
|
1874
|
+
compiledHtml = stripCrossoriginAttr(compiledHtml, "img");
|
|
1875
|
+
compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
|
|
1876
|
+
return { html: compiledHtml, unresolvedCompositions };
|
|
1877
|
+
}
|
|
1878
|
+
async function parseSubCompositions(html, projectDir2, downloadDir2, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, run, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
|
|
1879
|
+
const subCompositions = /* @__PURE__ */ new Map();
|
|
1880
|
+
const { document: document2 } = parseHTML4(html);
|
|
1881
|
+
const compEls = document2.querySelectorAll("[data-composition-src]");
|
|
1882
|
+
const workItems = [];
|
|
1883
|
+
for (const el of compEls) {
|
|
1884
|
+
const srcPath = el.getAttribute("data-composition-src");
|
|
1885
|
+
if (!srcPath) continue;
|
|
1886
|
+
const filePath = resolveCompositionFile(projectDir2, srcPath, assetRoot);
|
|
1887
|
+
if (filePath === null || isPrivateCompositionFile(projectDir2, filePath)) continue;
|
|
1888
|
+
if (visited.has(filePath)) {
|
|
1889
|
+
continue;
|
|
1890
|
+
}
|
|
1891
|
+
if (compiledSrcs.has(srcPath)) continue;
|
|
1892
|
+
compiledSrcs.add(srcPath);
|
|
1893
|
+
assertOutsideMarkupAsked(projectDir2, filePath, srcPath, assetRoot, outsideFiles);
|
|
1894
|
+
assertCompositionFileSize(filePath, srcPath);
|
|
1895
|
+
const read2 = readProjectFile(filePath);
|
|
1896
|
+
if (read2.kind !== "file") {
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
const rawSubHtml = normalizeCompositionSrcs(read2.text, projectDir2);
|
|
1900
|
+
const nestedVisited = new Set(visited);
|
|
1901
|
+
nestedVisited.add(filePath);
|
|
1902
|
+
workItems.push({ srcPath, filePath, rawSubHtml, nestedVisited });
|
|
1903
|
+
}
|
|
1904
|
+
const results = await Promise.all(
|
|
1905
|
+
workItems.map(async (item) => {
|
|
1906
|
+
const { html: compiledSub } = await compileHtmlFile(
|
|
1907
|
+
rewriteUnresolvableGsapToCdn(item.rawSubHtml, projectDir2, item.srcPath),
|
|
1908
|
+
projectDir2,
|
|
1909
|
+
dirname3(item.filePath),
|
|
1910
|
+
downloadDir2,
|
|
1911
|
+
void 0,
|
|
1912
|
+
urlByAbsentLocalPath,
|
|
1913
|
+
run,
|
|
1914
|
+
assetRoot
|
|
1915
|
+
);
|
|
1916
|
+
const nested = await parseSubCompositions(
|
|
1917
|
+
compiledSub,
|
|
1918
|
+
projectDir2,
|
|
1919
|
+
downloadDir2,
|
|
1920
|
+
item.nestedVisited,
|
|
1921
|
+
urlByAbsentLocalPath,
|
|
1922
|
+
run,
|
|
1923
|
+
assetRoot,
|
|
1924
|
+
outsideFiles,
|
|
1925
|
+
compiledSrcs
|
|
1926
|
+
);
|
|
1927
|
+
return {
|
|
1928
|
+
srcPath: item.srcPath,
|
|
1929
|
+
compiledSub,
|
|
1930
|
+
nested
|
|
1931
|
+
};
|
|
1932
|
+
})
|
|
1933
|
+
);
|
|
1934
|
+
for (const r of results) {
|
|
1935
|
+
subCompositions.set(r.srcPath, r.compiledSub);
|
|
1936
|
+
for (const [key, value] of r.nested.subCompositions) {
|
|
1937
|
+
subCompositions.set(key, value);
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
return { subCompositions };
|
|
1941
|
+
}
|
|
1942
|
+
function promoteCssImportsToLinkTags(html) {
|
|
1943
|
+
const { document: document2 } = parseHTML4(html);
|
|
1944
|
+
const head = document2.querySelector("head");
|
|
1945
|
+
if (!head) return html;
|
|
1946
|
+
const importRe = /@import\s+url\(\s*['"]?([^'")\s]+)['"]?\s*\)\s*;?/gi;
|
|
1947
|
+
const seenUrls = /* @__PURE__ */ new Set();
|
|
1948
|
+
const styleEls = document2.querySelectorAll("style");
|
|
1949
|
+
for (const styleEl of styleEls) {
|
|
1950
|
+
const original = styleEl.textContent || "";
|
|
1951
|
+
let modified = original;
|
|
1952
|
+
let match;
|
|
1953
|
+
importRe.lastIndex = 0;
|
|
1954
|
+
while ((match = importRe.exec(original)) !== null) {
|
|
1955
|
+
const url = match[1] ?? "";
|
|
1956
|
+
if (!url.startsWith("http://") && !url.startsWith("https://")) continue;
|
|
1957
|
+
if (seenUrls.has(url)) {
|
|
1958
|
+
modified = modified.replace(match[0], "");
|
|
1959
|
+
continue;
|
|
1960
|
+
}
|
|
1961
|
+
seenUrls.add(url);
|
|
1962
|
+
modified = modified.replace(match[0], "");
|
|
1963
|
+
const preload = document2.createElement("link");
|
|
1964
|
+
preload.setAttribute("rel", "preload");
|
|
1965
|
+
preload.setAttribute("href", url);
|
|
1966
|
+
preload.setAttribute("as", "style");
|
|
1967
|
+
head.appendChild(preload);
|
|
1968
|
+
const link = document2.createElement("link");
|
|
1969
|
+
link.setAttribute("rel", "stylesheet");
|
|
1970
|
+
link.setAttribute("href", url);
|
|
1971
|
+
head.appendChild(link);
|
|
1972
|
+
}
|
|
1973
|
+
if (modified !== original) {
|
|
1974
|
+
styleEl.textContent = modified;
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
return document2.toString();
|
|
1978
|
+
}
|
|
1979
|
+
var ProducerHostIdentityMap = class extends Map {
|
|
1980
|
+
#lateInstanceByCompositionId = /* @__PURE__ */ new Map();
|
|
1981
|
+
/** How many elements carry each composition id: the page once, then each mount's copy once. */
|
|
1982
|
+
#idCounts = /* @__PURE__ */ new Map();
|
|
1983
|
+
/** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */
|
|
1984
|
+
#uncounted;
|
|
1985
|
+
constructor(document2, initialHosts) {
|
|
1986
|
+
super(assignBundledRuntimeCompositionIds(initialHosts));
|
|
1987
|
+
this.#uncounted = [document2];
|
|
1988
|
+
}
|
|
1989
|
+
#countUncopied() {
|
|
1990
|
+
for (const root of this.#uncounted.splice(0)) {
|
|
1991
|
+
for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) {
|
|
1992
|
+
this.#adjust(element.getAttribute("data-composition-id"), 1);
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
#adjust(id, by) {
|
|
1997
|
+
if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by);
|
|
1998
|
+
}
|
|
1999
|
+
get(host) {
|
|
2000
|
+
this.#countUncopied();
|
|
2001
|
+
this.#uncounted.push(host);
|
|
2002
|
+
const existing = super.get(host);
|
|
2003
|
+
if (existing) return existing;
|
|
2004
|
+
const authoredCompositionId = (host.getAttribute("data-hf-original-composition-id") || host.getAttribute("data-composition-id") || "").trim() || null;
|
|
2005
|
+
if (!authoredCompositionId) {
|
|
2006
|
+
const identity2 = { authoredCompositionId: null, runtimeCompositionId: null };
|
|
2007
|
+
this.set(host, identity2);
|
|
2008
|
+
return identity2;
|
|
2009
|
+
}
|
|
2010
|
+
const ownId = host.getAttribute("data-composition-id");
|
|
2011
|
+
const heldByOthers = (id) => (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0;
|
|
2012
|
+
let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
|
|
2013
|
+
let runtimeCompositionId;
|
|
2014
|
+
do {
|
|
2015
|
+
instanceIndex += 1;
|
|
2016
|
+
runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
|
|
2017
|
+
} while (heldByOthers(runtimeCompositionId));
|
|
2018
|
+
this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
|
|
2019
|
+
host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
|
|
2020
|
+
host.setAttribute("data-composition-id", runtimeCompositionId);
|
|
2021
|
+
this.#adjust(ownId, -1);
|
|
2022
|
+
this.#adjust(runtimeCompositionId, 1);
|
|
2023
|
+
const identity = { authoredCompositionId, runtimeCompositionId };
|
|
2024
|
+
this.set(host, identity);
|
|
2025
|
+
return identity;
|
|
2026
|
+
}
|
|
2027
|
+
};
|
|
2028
|
+
function coalesceHeadStylesAndBodyScripts(html) {
|
|
2029
|
+
const { document: document2 } = parseHTML4(html);
|
|
2030
|
+
const head = document2.querySelector("head");
|
|
2031
|
+
const body = document2.querySelector("body");
|
|
2032
|
+
if (!head && !body) return html;
|
|
2033
|
+
const liveStyles = [...document2.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
|
|
2034
|
+
const dedupedStyles = dedupeFontFaceRules(liveStyles.map((el) => el.textContent || ""));
|
|
2035
|
+
liveStyles.forEach((el, i) => {
|
|
2036
|
+
el.textContent = dedupedStyles[i] ?? "";
|
|
2037
|
+
});
|
|
2038
|
+
const styleEls = head ? Array.from(head.querySelectorAll("style")) : [];
|
|
2039
|
+
for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
|
|
2040
|
+
const imports = [];
|
|
2041
|
+
const cssParts = [];
|
|
2042
|
+
const seenImports = /* @__PURE__ */ new Set();
|
|
2043
|
+
for (const el of run) {
|
|
2044
|
+
const raw = (el.textContent || "").trim();
|
|
2045
|
+
if (!raw) continue;
|
|
2046
|
+
const nonImportCss = replaceMatches(raw, importRuleMatches(raw), (match) => {
|
|
2047
|
+
const cleaned = match.trim();
|
|
2048
|
+
if (!seenImports.has(cleaned)) {
|
|
2049
|
+
seenImports.add(cleaned);
|
|
2050
|
+
imports.push(cleaned);
|
|
2051
|
+
}
|
|
2052
|
+
return "";
|
|
2053
|
+
});
|
|
2054
|
+
const trimmedCss = nonImportCss.trim();
|
|
2055
|
+
if (trimmedCss) cssParts.push(trimmedCss);
|
|
2056
|
+
}
|
|
2057
|
+
const mergedCss = [...imports, ...cssParts].join("\n\n").trim();
|
|
2058
|
+
if (!mergedCss) continue;
|
|
2059
|
+
run[0].textContent = mergedCss;
|
|
2060
|
+
for (const el of run.slice(1)) el.remove();
|
|
2061
|
+
}
|
|
2062
|
+
if (body) {
|
|
2063
|
+
for (const { members, anchor } of inlineScriptRuns(
|
|
2064
|
+
Array.from(body.querySelectorAll("script"))
|
|
2065
|
+
)) {
|
|
2066
|
+
const mergedJs = members.map((el) => (el.textContent || "").trim()).filter(Boolean).join("\n;\n").trim();
|
|
2067
|
+
if (mergedJs && !parsesAsScript(mergedJs)) continue;
|
|
2068
|
+
for (const el of members) el.remove();
|
|
2069
|
+
if (!mergedJs) continue;
|
|
2070
|
+
const script = document2.createElement("script");
|
|
2071
|
+
script.textContent = mergedJs;
|
|
2072
|
+
if (anchor) anchor.before(script);
|
|
2073
|
+
else body.appendChild(script);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
return document2.toString();
|
|
2077
|
+
}
|
|
2078
|
+
function inlineSubCompositions(html, subCompositions, projectDir2, variableOverrides, assetRoot, outsideFiles, budget) {
|
|
2079
|
+
const { document: document2 } = parseHTML4(html);
|
|
2080
|
+
budget.chargeElements(ENTRY_PAGE, document2.querySelectorAll("*").length);
|
|
2081
|
+
const head = document2.querySelector("head");
|
|
2082
|
+
const body = document2.querySelector("body");
|
|
2083
|
+
const hosts = Array.from(document2.querySelectorAll("[data-composition-src]"));
|
|
2084
|
+
if (!hosts.length) {
|
|
2085
|
+
const dropped = dropAuthoredSvgReferenceAliases(document2);
|
|
2086
|
+
const emitted = emitRootCompositionVariableStyles(
|
|
2087
|
+
document2,
|
|
2088
|
+
{},
|
|
2089
|
+
variableOverrides,
|
|
2090
|
+
{ chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
|
|
2091
|
+
);
|
|
2092
|
+
return { html: emitted || dropped ? document2.toString() : html, variablesByComp: {} };
|
|
2093
|
+
}
|
|
2094
|
+
const readOnce = /* @__PURE__ */ new Map();
|
|
2095
|
+
const readMountHtml = (srcPath) => {
|
|
2096
|
+
const filePath = resolveCompositionFile(projectDir2, srcPath, assetRoot);
|
|
2097
|
+
if (filePath) {
|
|
2098
|
+
assertOutsideMarkupAsked(projectDir2, filePath, srcPath, assetRoot, outsideFiles);
|
|
2099
|
+
assertCompositionFileSize(filePath, srcPath);
|
|
2100
|
+
}
|
|
2101
|
+
const read2 = filePath && !isPrivateCompositionFile(projectDir2, filePath) ? readProjectFile(filePath) : null;
|
|
2102
|
+
return read2?.kind === "file" ? rewriteUnresolvableGsapToCdn(
|
|
2103
|
+
normalizeCompositionSrcs(read2.text, projectDir2),
|
|
2104
|
+
projectDir2,
|
|
2105
|
+
srcPath
|
|
2106
|
+
) : null;
|
|
2107
|
+
};
|
|
2108
|
+
const resolveMountHtml = (srcPath) => {
|
|
2109
|
+
const compiled = subCompositions.get(srcPath);
|
|
2110
|
+
if (compiled) return compiled;
|
|
2111
|
+
if (!readOnce.has(srcPath)) readOnce.set(srcPath, readMountHtml(srcPath));
|
|
2112
|
+
return readOnce.get(srcPath) ?? null;
|
|
2113
|
+
};
|
|
2114
|
+
const hostIdentityByElement = new ProducerHostIdentityMap(
|
|
2115
|
+
document2,
|
|
2116
|
+
hosts
|
|
2117
|
+
);
|
|
2118
|
+
const result = inlineSubCompositionsShared(
|
|
2119
|
+
document2,
|
|
2120
|
+
hosts,
|
|
2121
|
+
{
|
|
2122
|
+
// hostIdentityMap gives each repeated mount a unique runtime id; the
|
|
2123
|
+
// shared inliner's default buildScopeSelector already scopes by
|
|
2124
|
+
// `[data-composition-id="<runtime id>"]`, matching the preview bundler.
|
|
2125
|
+
hostIdentityMap: hostIdentityByElement,
|
|
2126
|
+
readVariableDefaults: readDeclaredDefaults,
|
|
2127
|
+
parseHostVariables: parseHostVariableValues,
|
|
2128
|
+
resolveFilePath: (srcPath) => {
|
|
2129
|
+
const file = resolveCompositionFile(projectDir2, srcPath, assetRoot);
|
|
2130
|
+
return file && relative(projectDir2, file).split(sep2).join("/");
|
|
2131
|
+
},
|
|
2132
|
+
resolveHtml: (srcPath) => {
|
|
2133
|
+
const compHtml = resolveMountHtml(srcPath);
|
|
2134
|
+
if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
|
|
2135
|
+
return compHtml;
|
|
2136
|
+
},
|
|
2137
|
+
chargeEmitted: (srcPath, bytes) => budget.chargeGenerated(srcPath, bytes),
|
|
2138
|
+
chargeElements: (srcPath, count) => budget.chargeElements(srcPath, count),
|
|
2139
|
+
parseHtml: (htmlStr) => parseHTML4(htmlStr).document,
|
|
2140
|
+
// Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
|
|
2141
|
+
// against its own directory, project-root refs stay as authored.
|
|
2142
|
+
assetExists: projectAssetExists(projectDir2),
|
|
2143
|
+
// Preserve the authored root wrapper as a child of the host, matching
|
|
2144
|
+
// the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
|
|
2145
|
+
// which the runtime compositionLoader mirrors with its own copy for the
|
|
2146
|
+
// live-loaded case). Without this, the wrapper element (and its
|
|
2147
|
+
// class/id) is discarded and any CSS anchored on it —
|
|
2148
|
+
// `.wrapper-class .title`, `#wrapper-id` — is dead at render time even
|
|
2149
|
+
// though it works in preview.
|
|
2150
|
+
flattenInnerRoot: prepareFlattenedInnerRoot,
|
|
2151
|
+
onMissingComposition: (srcPath, reason) => {
|
|
2152
|
+
console.warn(
|
|
2153
|
+
terminalText2(
|
|
2154
|
+
`[Compiler] Skipping sub-composition "${srcPath}": ${reason ?? "the file is missing or empty"}.`
|
|
2155
|
+
)
|
|
2156
|
+
);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
);
|
|
2160
|
+
for (const host of hosts) {
|
|
2161
|
+
const hostW = host.getAttribute("data-width");
|
|
2162
|
+
const hostH = host.getAttribute("data-height");
|
|
2163
|
+
if (hostW && hostH) {
|
|
2164
|
+
const existing = host.getAttribute("style") || "";
|
|
2165
|
+
const needsWidth = !existing.includes("width");
|
|
2166
|
+
const needsHeight = !existing.includes("height");
|
|
2167
|
+
const additions = [
|
|
2168
|
+
needsWidth ? `width:${hostW}px` : "",
|
|
2169
|
+
needsHeight ? `height:${hostH}px` : ""
|
|
2170
|
+
].filter(Boolean).join(";");
|
|
2171
|
+
if (additions) {
|
|
2172
|
+
host.setAttribute("style", existing ? `${existing};${additions}` : additions);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
if (head) for (const link of result.externalLinks) ensureExternalLinkTag(document2, link);
|
|
2177
|
+
if (head) {
|
|
2178
|
+
for (const style of styleElementsFor(document2, result.styles, (css) => css.join("\n\n"))) {
|
|
2179
|
+
head.appendChild(style);
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
const isHoisted = (item) => Boolean(item.integrity?.trim()) || isNonRelativeUrl(item.src);
|
|
2183
|
+
if (body) {
|
|
2184
|
+
for (const item of result.scriptItems) {
|
|
2185
|
+
if (item.kind === "external" && isHoisted(item)) {
|
|
2186
|
+
ensureExternalScriptTag(document2, item.src, item);
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
emitVariablesByCompScript(document2, result.variablesByComp);
|
|
2191
|
+
if (body) {
|
|
2192
|
+
let pending = [];
|
|
2193
|
+
const flushInline = () => {
|
|
2194
|
+
if (!pending.length) return;
|
|
2195
|
+
const joined = pending.join("\n;\n");
|
|
2196
|
+
for (const text of parsesAsScript(joined) ? [joined] : pending) {
|
|
2197
|
+
const scriptEl = document2.createElement("script");
|
|
2198
|
+
scriptEl.textContent = text;
|
|
2199
|
+
body.appendChild(scriptEl);
|
|
2200
|
+
}
|
|
2201
|
+
pending = [];
|
|
2202
|
+
};
|
|
2203
|
+
for (const item of result.scriptItems) {
|
|
2204
|
+
if (item.kind === "inline") {
|
|
2205
|
+
pending.push(item.content);
|
|
2206
|
+
} else if (!isHoisted(item)) {
|
|
2207
|
+
flushInline();
|
|
2208
|
+
ensureExternalScriptTag(document2, item.src, item);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
flushInline();
|
|
2212
|
+
}
|
|
2213
|
+
if (body) {
|
|
2214
|
+
emitMountedModuleScripts(
|
|
2215
|
+
document2,
|
|
2216
|
+
result.importMaps,
|
|
2217
|
+
result.moduleScripts
|
|
2218
|
+
);
|
|
2219
|
+
}
|
|
2220
|
+
emitRootCompositionVariableStyles(
|
|
2221
|
+
document2,
|
|
2222
|
+
result.variablesByComp,
|
|
2223
|
+
variableOverrides,
|
|
2224
|
+
{ chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
|
|
2225
|
+
);
|
|
2226
|
+
assignMediaRenderIds(document2);
|
|
2227
|
+
return { html: document2.toString(), variablesByComp: result.variablesByComp };
|
|
2228
|
+
}
|
|
2229
|
+
function ensureFullDocument(html) {
|
|
2230
|
+
const trimmed = html.trim();
|
|
2231
|
+
if (/^<!DOCTYPE\s+html/i.test(trimmed) || /^<html/i.test(trimmed)) {
|
|
2232
|
+
return html;
|
|
2233
|
+
}
|
|
2234
|
+
return `<!DOCTYPE html>
|
|
2235
|
+
<html>
|
|
2236
|
+
<head>
|
|
2237
|
+
<meta charset="UTF-8">
|
|
2238
|
+
<style>*{margin:0;padding:0;box-sizing:border-box;text-rendering:geometricPrecision}body{overflow:hidden;background:#000;font-family:"Inter",sans-serif}</style>
|
|
2239
|
+
</head>
|
|
2240
|
+
<body style="margin:0;overflow:hidden">
|
|
2241
|
+
${html}
|
|
2242
|
+
</body>
|
|
2243
|
+
</html>`;
|
|
2244
|
+
}
|
|
2245
|
+
function injectTextRenderingRule(html) {
|
|
2246
|
+
const { document: document2 } = parseHTML4(html);
|
|
2247
|
+
const head = document2.querySelector("head");
|
|
2248
|
+
if (!head) return html;
|
|
2249
|
+
if (document2.querySelector("style[data-hyperframes-text-rendering]")) {
|
|
2250
|
+
return html;
|
|
2251
|
+
}
|
|
2252
|
+
const styleEl = document2.createElement("style");
|
|
2253
|
+
styleEl.setAttribute("data-hyperframes-text-rendering", "true");
|
|
2254
|
+
styleEl.textContent = "html,body,*{text-rendering:geometricPrecision}";
|
|
2255
|
+
head.insertBefore(styleEl, head.firstChild);
|
|
2256
|
+
return document2.toString();
|
|
2257
|
+
}
|
|
2258
|
+
var ScriptIntegrityError = class extends Error {
|
|
2259
|
+
};
|
|
2260
|
+
function matchesScriptIntegrity(bytes, metadata) {
|
|
2261
|
+
const hashes = [
|
|
2262
|
+
...metadata.matchAll(
|
|
2263
|
+
/(?:^|[\t\n\f\r ])(sha256|sha384|sha512)-([A-Za-z0-9+/_-]+={0,2})(?:\?[\x21-\x7e]*)?(?=$|[\t\n\f\r ])/gi
|
|
2264
|
+
)
|
|
2265
|
+
];
|
|
2266
|
+
const strongest = ["sha512", "sha384", "sha256"].find(
|
|
2267
|
+
(alg) => hashes.some((hash) => hash[1]?.toLowerCase() === alg)
|
|
2268
|
+
);
|
|
2269
|
+
if (!strongest) return true;
|
|
2270
|
+
const actual = createHash3(strongest).update(bytes).digest();
|
|
2271
|
+
return hashes.some(
|
|
2272
|
+
(hash) => hash[1]?.toLowerCase() === strongest && actual.equals(Buffer.from(hash[2], "base64"))
|
|
2273
|
+
);
|
|
2274
|
+
}
|
|
2275
|
+
var MAX_SCRIPT_BYTES = 16 * 1024 * 1024;
|
|
2276
|
+
function operatorGsapMirror() {
|
|
2277
|
+
const raw = process.env.HYPERFRAMES_GSAP_BASE_URL?.trim();
|
|
2278
|
+
if (!raw || raw.startsWith("/")) return void 0;
|
|
2279
|
+
try {
|
|
2280
|
+
return `${normalizeGsapBaseUrl(raw)}/`;
|
|
2281
|
+
} catch {
|
|
2282
|
+
return void 0;
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
async function downloadScript(src, mirror, signal) {
|
|
2286
|
+
if (mirror && new URL(src).href.startsWith(mirror)) {
|
|
2287
|
+
const response = await fetch(src, {
|
|
2288
|
+
redirect: "error",
|
|
2289
|
+
signal: AbortSignal.any([AbortSignal.timeout(15e3), signal])
|
|
2290
|
+
});
|
|
2291
|
+
if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
|
|
2292
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
2293
|
+
if (bytes.byteLength > MAX_SCRIPT_BYTES) throw new Error(`Script over 16 MiB: ${src}`);
|
|
2294
|
+
return bytes;
|
|
2295
|
+
}
|
|
2296
|
+
return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3, signal });
|
|
2297
|
+
}
|
|
2298
|
+
var MAX_CONCURRENT_SCRIPT_FETCHES = 4;
|
|
2299
|
+
var MAX_REMOTE_FETCHES = 32;
|
|
2300
|
+
var REMOTE_FETCH_DEADLINE_MS = 6e4;
|
|
2301
|
+
var fetchSignalOf = (signal) => typeof signal === "function" ? signal() : signal;
|
|
2302
|
+
function assertRemoteFetchCount(kind, count) {
|
|
2303
|
+
if (count > MAX_REMOTE_FETCHES) {
|
|
2304
|
+
throw new Error(
|
|
2305
|
+
`The composition links ${count} remote ${kind}; at most ${MAX_REMOTE_FETCHES} are downloaded at compile time`
|
|
2306
|
+
);
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
async function inlineExternalScripts(html, budget = new CompositionExpansionBudget(), signal) {
|
|
2310
|
+
const fullHtml = ensureFullDocument(html);
|
|
2311
|
+
const wrappedFragment = fullHtml !== html;
|
|
2312
|
+
const { document: document2 } = parseHTML4(fullHtml);
|
|
2313
|
+
const scripts = document2.querySelectorAll("script[src]");
|
|
2314
|
+
const externalScripts = [];
|
|
2315
|
+
for (const el of scripts) {
|
|
2316
|
+
const src = (el.getAttribute("src") || "").trim();
|
|
2317
|
+
if (src && isHttpUrl(src) && !isRuntimeFileUrl(src)) {
|
|
2318
|
+
externalScripts.push({ el, src });
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
if (externalScripts.length === 0) return html;
|
|
2322
|
+
const bundled = /* @__PURE__ */ new Map();
|
|
2323
|
+
const local = externalScripts.map(({ el, src }) => {
|
|
2324
|
+
if (!bundled.has(src)) bundled.set(src, bundledScript(src));
|
|
2325
|
+
const bytes = bundled.get(src);
|
|
2326
|
+
return bytes && matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "") ? bytes : null;
|
|
2327
|
+
});
|
|
2328
|
+
const remote = new Set(externalScripts.filter((_, i) => !local[i]).map(({ src }) => src));
|
|
2329
|
+
assertRemoteFetchCount("scripts", remote.size);
|
|
2330
|
+
const pinned = new Set(
|
|
2331
|
+
externalScripts.filter(({ el }) => el.getAttribute("integrity")).map(({ src }) => src)
|
|
2332
|
+
);
|
|
2333
|
+
const mirror = operatorGsapMirror();
|
|
2334
|
+
const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
|
|
2335
|
+
const stop = new AbortController();
|
|
2336
|
+
const shared = remote.size > 0 ? fetchSignalOf(signal) : void 0;
|
|
2337
|
+
const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
|
|
2338
|
+
const fail = (error) => {
|
|
2339
|
+
stop.abort(error);
|
|
2340
|
+
throw error;
|
|
2341
|
+
};
|
|
2342
|
+
const charge = (bytes) => {
|
|
2343
|
+
try {
|
|
2344
|
+
budget.chargeGenerated(REMOTE_SCRIPTS, bytes);
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
fail(error);
|
|
2347
|
+
}
|
|
2348
|
+
};
|
|
2349
|
+
const fetches = /* @__PURE__ */ new Map();
|
|
2350
|
+
const fetchOnce = (src) => {
|
|
2351
|
+
let bytes = fetches.get(src);
|
|
2352
|
+
if (!bytes) {
|
|
2353
|
+
bytes = limit(async () => {
|
|
2354
|
+
fetchSignal.throwIfAborted();
|
|
2355
|
+
const downloaded = await downloadScript(src, mirror, fetchSignal).catch(
|
|
2356
|
+
(error) => {
|
|
2357
|
+
const standIn = pinned.has(src) || fetchSignal.aborted ? null : bundledGsapStandIn(src);
|
|
2358
|
+
if (!standIn) throw error;
|
|
2359
|
+
defaultLogger.warn(
|
|
2360
|
+
`[Compiler] Could not download ${src} (${error}); using the host's own GSAP instead.`
|
|
2361
|
+
);
|
|
2362
|
+
return standIn;
|
|
2363
|
+
}
|
|
2364
|
+
);
|
|
2365
|
+
charge(downloaded.byteLength);
|
|
2366
|
+
return downloaded;
|
|
2367
|
+
}, fetchSignal);
|
|
2368
|
+
fetches.set(src, bytes);
|
|
2369
|
+
}
|
|
2370
|
+
return bytes;
|
|
2371
|
+
};
|
|
2372
|
+
const placed = /* @__PURE__ */ new Set();
|
|
2373
|
+
const downloads = await Promise.allSettled(
|
|
2374
|
+
externalScripts.map(async ({ el, src }, i) => {
|
|
2375
|
+
const integrity = el.getAttribute("integrity") || "";
|
|
2376
|
+
let bytes = local[i];
|
|
2377
|
+
if (bytes) {
|
|
2378
|
+
charge(bytes.byteLength);
|
|
2379
|
+
} else {
|
|
2380
|
+
bytes = await fetchOnce(src);
|
|
2381
|
+
if (!matchesScriptIntegrity(bytes, integrity)) {
|
|
2382
|
+
fail(new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`));
|
|
2383
|
+
}
|
|
2384
|
+
if (placed.has(src)) charge(bytes.byteLength);
|
|
2385
|
+
placed.add(src);
|
|
2386
|
+
}
|
|
2387
|
+
return { src, text: new TextDecoder().decode(bytes) };
|
|
2388
|
+
})
|
|
2389
|
+
);
|
|
2390
|
+
if (stop.signal.aborted) throw stop.signal.reason;
|
|
2391
|
+
for (let i = 0; i < downloads.length; i++) {
|
|
2392
|
+
const download = downloads[i];
|
|
2393
|
+
const { el, src } = externalScripts[i];
|
|
2394
|
+
if (download.status === "fulfilled") {
|
|
2395
|
+
const safeText = download.value.text.replace(/<\/script/gi, "<\\/script");
|
|
2396
|
+
const inlineScript = document2.createElement("script");
|
|
2397
|
+
for (const attr of Array.from(el.attributes)) {
|
|
2398
|
+
if (attr.name.toLowerCase() === "src") continue;
|
|
2399
|
+
inlineScript.setAttribute(attr.name, attr.value);
|
|
2400
|
+
}
|
|
2401
|
+
inlineScript.textContent = `/* inlined: ${src} */
|
|
2402
|
+
${safeText}
|
|
2403
|
+
//# sourceURL=${new URL(src).href}
|
|
2404
|
+
`;
|
|
2405
|
+
el.replaceWith(inlineScript);
|
|
2406
|
+
defaultLogger.debug(`[Compiler] Inlined CDN script: ${src}`);
|
|
2407
|
+
} else {
|
|
2408
|
+
if (download.reason instanceof ScriptIntegrityError) throw download.reason;
|
|
2409
|
+
defaultLogger.warn(
|
|
2410
|
+
`[Compiler] WARNING: Failed to download CDN script: ${src} (${download.reason}). The render may fail if this script is required (e.g. GSAP). Consider bundling it locally in your project.`
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
|
|
2415
|
+
}
|
|
2416
|
+
function collectExternalAssets(html, projectDir2, log2 = defaultLogger, file = "index.html", policy = {}) {
|
|
2417
|
+
const absProjectDir = resolve3(projectDir2);
|
|
2418
|
+
const externalAssets = /* @__PURE__ */ new Map();
|
|
2419
|
+
const leftOut = /* @__PURE__ */ new Set();
|
|
2420
|
+
function processPath(rawPath) {
|
|
2421
|
+
const trimmed = rawPath.trim();
|
|
2422
|
+
if (isNonRelativeUrl(trimmed)) return null;
|
|
2423
|
+
const absPath = resolve3(absProjectDir, trimmed);
|
|
2424
|
+
if (isPathInside(absPath, absProjectDir)) {
|
|
2425
|
+
return null;
|
|
2426
|
+
}
|
|
2427
|
+
const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
|
|
2428
|
+
if (!onShare && !existsSync3(absPath)) return null;
|
|
2429
|
+
const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
|
|
2430
|
+
if (refusal) {
|
|
2431
|
+
if (!leftOut.has(trimmed)) log2.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
|
|
2432
|
+
leftOut.add(trimmed);
|
|
2433
|
+
return null;
|
|
2434
|
+
}
|
|
2435
|
+
const safeKey = toExternalAssetKey(absPath);
|
|
2436
|
+
externalAssets.set(safeKey, absPath);
|
|
2437
|
+
return safeKey;
|
|
2438
|
+
}
|
|
2439
|
+
const { document: document2 } = parseHTML4(html);
|
|
2440
|
+
for (const el of document2.querySelectorAll("[src], [href]")) {
|
|
2441
|
+
for (const attr of ["src", "href"]) {
|
|
2442
|
+
const val = (el.getAttribute(attr) || "").trim();
|
|
2443
|
+
if (!val) continue;
|
|
2444
|
+
const rewritten = processPath(val);
|
|
2445
|
+
if (rewritten) el.setAttribute(attr, rewritten);
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
for (const styleEl of document2.querySelectorAll("style")) {
|
|
2449
|
+
const css = styleEl.textContent || "";
|
|
2450
|
+
if (!css.includes("url(")) continue;
|
|
2451
|
+
const rewritten = replaceMatches(css, cssUrlMatches(css), (full, quote, rawUrl) => {
|
|
2452
|
+
const result = processPath((rawUrl || "").trim());
|
|
2453
|
+
if (!result) return full;
|
|
2454
|
+
return `url(${quote || ""}${result}${quote || ""})`;
|
|
2455
|
+
});
|
|
2456
|
+
if (rewritten !== css) styleEl.textContent = rewritten;
|
|
2457
|
+
}
|
|
2458
|
+
for (const el of document2.querySelectorAll("[style]")) {
|
|
2459
|
+
const style = el.getAttribute("style") || "";
|
|
2460
|
+
if (!style.includes("url(")) continue;
|
|
2461
|
+
const rewritten = replaceMatches(style, cssUrlMatches(style), (full, quote, rawUrl) => {
|
|
2462
|
+
const result = processPath((rawUrl || "").trim());
|
|
2463
|
+
if (!result) return full;
|
|
2464
|
+
return `url(${quote || ""}${result}${quote || ""})`;
|
|
2465
|
+
});
|
|
2466
|
+
if (rewritten !== style) el.setAttribute("style", rewritten);
|
|
2467
|
+
}
|
|
2468
|
+
if (externalAssets.size > 0) {
|
|
2469
|
+
defaultLogger.debug(
|
|
2470
|
+
`[Compiler] Found ${externalAssets.size} asset(s) outside project directory, will copy to render output`
|
|
2471
|
+
);
|
|
2472
|
+
}
|
|
2473
|
+
return {
|
|
2474
|
+
html: externalAssets.size > 0 ? document2.toString() : html,
|
|
2475
|
+
externalAssets
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
var REMOTE_MEDIA_SUBDIR = "_remote_media";
|
|
2479
|
+
async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, assets, extraRewrite) {
|
|
2480
|
+
assets?.reserve(urlSet);
|
|
2481
|
+
if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
|
|
2482
|
+
if (!existsSync3(remoteDir)) mkdirSync3(remoteDir, { recursive: true });
|
|
2483
|
+
const urlToLocal = /* @__PURE__ */ new Map();
|
|
2484
|
+
await Promise.all(
|
|
2485
|
+
[...urlSet].map(async (url) => {
|
|
2486
|
+
try {
|
|
2487
|
+
const localPath = await downloadAsset(url, remoteDir, assets);
|
|
2488
|
+
urlToLocal.set(url, localPath);
|
|
2489
|
+
} catch (err) {
|
|
2490
|
+
if (assets?.signal?.aborted) throw err;
|
|
2491
|
+
const identity = safeDownloadUrlIdentity(url);
|
|
2492
|
+
defaultLogger.warn(`[Compiler] ${warnLabel}, using original URL as fallback.`, {
|
|
2493
|
+
urlFingerprint: identity.urlFingerprint,
|
|
2494
|
+
host: identity.host,
|
|
2495
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2496
|
+
});
|
|
2497
|
+
}
|
|
2498
|
+
})
|
|
2499
|
+
);
|
|
2500
|
+
if (urlToLocal.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
|
|
2501
|
+
const remoteMediaAssets = /* @__PURE__ */ new Map();
|
|
2502
|
+
const urlToRelPath = /* @__PURE__ */ new Map();
|
|
2503
|
+
for (const [url, absPath] of urlToLocal) {
|
|
2504
|
+
const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename2(absPath)}`;
|
|
2505
|
+
remoteMediaAssets.set(relPath, absPath);
|
|
2506
|
+
urlToRelPath.set(url, relPath);
|
|
2507
|
+
}
|
|
2508
|
+
let result = html;
|
|
2509
|
+
for (const [url, relPath] of urlToRelPath) {
|
|
2510
|
+
result = result.replaceAll(`"${url}"`, `"${relPath}"`).replaceAll(`'${url}'`, `'${relPath}'`);
|
|
2511
|
+
if (extraRewrite) result = extraRewrite(result, url, relPath);
|
|
2512
|
+
}
|
|
2513
|
+
defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
|
|
2514
|
+
return { html: result, remoteMediaAssets };
|
|
2515
|
+
}
|
|
2516
|
+
async function localizeRemoteMediaSources(html, downloadDir2, assets) {
|
|
2517
|
+
const urlSet = /* @__PURE__ */ new Set([...remoteSrcUrls(html, "media"), ...remoteSrcUrls(html, "source")]);
|
|
2518
|
+
const localized = await downloadAndRewriteUrls(
|
|
2519
|
+
urlSet,
|
|
2520
|
+
html,
|
|
2521
|
+
join5(downloadDir2, REMOTE_MEDIA_SUBDIR),
|
|
2522
|
+
"Remote media download failed",
|
|
2523
|
+
"Localized remote media source(s)",
|
|
2524
|
+
assets
|
|
2525
|
+
);
|
|
2526
|
+
return { ...localized, html: dropBindingOnLocalizedMedia(localized.html) };
|
|
2527
|
+
}
|
|
2528
|
+
function dropBindingOnLocalizedMedia(html) {
|
|
2529
|
+
if (!html.includes("data-var-src")) return html;
|
|
2530
|
+
const { document: document2 } = parseHTML4(html);
|
|
2531
|
+
let changed = false;
|
|
2532
|
+
for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
|
|
2533
|
+
if (el.closest("[data-variable-values]")) continue;
|
|
2534
|
+
if (!el.getAttribute("src")?.startsWith(`${REMOTE_MEDIA_SUBDIR}/`)) continue;
|
|
2535
|
+
el.removeAttribute("data-var-src");
|
|
2536
|
+
changed = true;
|
|
2537
|
+
}
|
|
2538
|
+
return changed ? document2.toString() : html;
|
|
2539
|
+
}
|
|
2540
|
+
async function localizeRemoteImageSources(html, downloadDir2, assets) {
|
|
2541
|
+
const urlSet = new Set(remoteSrcUrls(html, "img"));
|
|
2542
|
+
return downloadAndRewriteUrls(
|
|
2543
|
+
urlSet,
|
|
2544
|
+
html,
|
|
2545
|
+
join5(downloadDir2, REMOTE_MEDIA_SUBDIR),
|
|
2546
|
+
"Remote image download failed",
|
|
2547
|
+
"Localized remote image source(s)",
|
|
2548
|
+
assets
|
|
2549
|
+
);
|
|
2550
|
+
}
|
|
2551
|
+
async function localizeRemoteBackgroundImages(html, downloadDir2, assets) {
|
|
2552
|
+
const urlSet = /* @__PURE__ */ new Set();
|
|
2553
|
+
for (const { parts } of remoteBackgroundUrlMatches(html)) {
|
|
2554
|
+
if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
|
|
2555
|
+
}
|
|
2556
|
+
return downloadAndRewriteUrls(
|
|
2557
|
+
urlSet,
|
|
2558
|
+
html,
|
|
2559
|
+
join5(downloadDir2, REMOTE_MEDIA_SUBDIR),
|
|
2560
|
+
"Remote background-image download failed",
|
|
2561
|
+
"Localized remote background-image(s)",
|
|
2562
|
+
assets,
|
|
2563
|
+
// Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
|
|
2564
|
+
// replaceAll; this handles the unquoted url(https://..) form.
|
|
2565
|
+
(h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
|
|
2566
|
+
);
|
|
2567
|
+
}
|
|
2568
|
+
function isGoogleFontsUrl(href) {
|
|
2569
|
+
try {
|
|
2570
|
+
const host = new URL(href).hostname.toLowerCase();
|
|
2571
|
+
return host === "fonts.googleapis.com" || host === "fonts.gstatic.com";
|
|
2572
|
+
} catch {
|
|
2573
|
+
return /fonts\.googleapis\.com|fonts\.gstatic\.com/i.test(href);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
var MAX_STYLESHEET_BYTES = 2 * 1024 * 1024;
|
|
2577
|
+
async function fetchExternalStylesheetCss(href, signal) {
|
|
2578
|
+
const identity = safeDownloadUrlIdentity(href);
|
|
2579
|
+
try {
|
|
2580
|
+
return await fetchPublicHttpsText(href, {
|
|
2581
|
+
maxBytes: MAX_STYLESHEET_BYTES,
|
|
2582
|
+
timeoutMs: 15e3,
|
|
2583
|
+
signal
|
|
2584
|
+
});
|
|
2585
|
+
} catch (err) {
|
|
2586
|
+
defaultLogger.warn("[Compiler] External stylesheet fetch failed, preserving link tag.", {
|
|
2587
|
+
urlFingerprint: identity.urlFingerprint,
|
|
2588
|
+
host: identity.host,
|
|
2589
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2590
|
+
});
|
|
2591
|
+
return null;
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
function extractFontFaceBlocks(css) {
|
|
2595
|
+
const blocks = [];
|
|
2596
|
+
const closes = matchingBraces(css);
|
|
2597
|
+
const atRule = /@font-face\s*/gi;
|
|
2598
|
+
let open = -1;
|
|
2599
|
+
for (let m = atRule.exec(css); m; m = atRule.exec(css)) {
|
|
2600
|
+
if (open < atRule.lastIndex) open = css.indexOf("{", atRule.lastIndex);
|
|
2601
|
+
if (open === -1) break;
|
|
2602
|
+
const close = closes.get(open);
|
|
2603
|
+
if (close === void 0) continue;
|
|
2604
|
+
blocks.push(css.slice(m.index, close + 1));
|
|
2605
|
+
atRule.lastIndex = close + 1;
|
|
2606
|
+
}
|
|
2607
|
+
return blocks;
|
|
2608
|
+
}
|
|
2609
|
+
function matchingBraces(css) {
|
|
2610
|
+
const closes = /* @__PURE__ */ new Map();
|
|
2611
|
+
const unclosed = [];
|
|
2612
|
+
for (let i = 0; i < css.length; i++) {
|
|
2613
|
+
if (css[i] === "{") unclosed.push(i);
|
|
2614
|
+
else if (css[i] === "}" && unclosed.length > 0) closes.set(unclosed.pop(), i);
|
|
2615
|
+
}
|
|
2616
|
+
return closes;
|
|
2617
|
+
}
|
|
2618
|
+
function remoteFontStylesheetHref(tag) {
|
|
2619
|
+
const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
|
|
2620
|
+
if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
|
|
2621
|
+
return href;
|
|
2622
|
+
}
|
|
2623
|
+
async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget(), signal) {
|
|
2624
|
+
const hrefs = /* @__PURE__ */ new Set();
|
|
2625
|
+
for (const { parts } of stylesheetLinkMatches(html)) {
|
|
2626
|
+
const href = remoteFontStylesheetHref(parts[0]);
|
|
2627
|
+
if (href) hrefs.add(href);
|
|
2628
|
+
}
|
|
2629
|
+
if (hrefs.size === 0) return html;
|
|
2630
|
+
assertRemoteFetchCount("stylesheets", hrefs.size);
|
|
2631
|
+
const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
|
|
2632
|
+
const stop = new AbortController();
|
|
2633
|
+
const shared = fetchSignalOf(signal);
|
|
2634
|
+
const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
|
|
2635
|
+
const inlineByHref = /* @__PURE__ */ new Map();
|
|
2636
|
+
const inlineSheet = async (href) => {
|
|
2637
|
+
const css = await fetchExternalStylesheetCss(href, fetchSignal);
|
|
2638
|
+
const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
|
|
2639
|
+
if (fontFaceBlocks.length === 0) return;
|
|
2640
|
+
const inlineStyle = `<style>/* Inlined external font stylesheet */
|
|
2641
|
+
${fontFaceBlocks.join("\n")}
|
|
2642
|
+
</style>`;
|
|
2643
|
+
try {
|
|
2644
|
+
budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
|
|
2645
|
+
} catch (error) {
|
|
2646
|
+
stop.abort(error);
|
|
2647
|
+
throw error;
|
|
2648
|
+
}
|
|
2649
|
+
inlineByHref.set(href, inlineStyle);
|
|
2650
|
+
const identity = safeDownloadUrlIdentity(href);
|
|
2651
|
+
defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
|
|
2652
|
+
count: fontFaceBlocks.length,
|
|
2653
|
+
urlFingerprint: identity.urlFingerprint,
|
|
2654
|
+
host: identity.host
|
|
2655
|
+
});
|
|
2656
|
+
};
|
|
2657
|
+
await Promise.allSettled([...hrefs].map((href) => limit(() => inlineSheet(href), fetchSignal)));
|
|
2658
|
+
if (stop.signal.aborted) throw stop.signal.reason;
|
|
2659
|
+
const placed = /* @__PURE__ */ new Set();
|
|
2660
|
+
return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
|
|
2661
|
+
const href = remoteFontStylesheetHref(tag);
|
|
2662
|
+
const inlineStyle = href ? inlineByHref.get(href) : void 0;
|
|
2663
|
+
if (!href || !inlineStyle) return tag;
|
|
2664
|
+
if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
|
|
2665
|
+
placed.add(href);
|
|
2666
|
+
return inlineStyle;
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
function projectStylesheetFontFamilies(html, projectDir2) {
|
|
2670
|
+
const families = [];
|
|
2671
|
+
for (const {
|
|
2672
|
+
parts: [tag]
|
|
2673
|
+
} of stylesheetLinkMatches(html)) {
|
|
2674
|
+
const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
|
|
2675
|
+
if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
|
|
2676
|
+
const sheet = resolve3(projectDir2, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
|
|
2677
|
+
if (!isPathInside(sheet, projectDir2) || !existsSync3(sheet)) continue;
|
|
2678
|
+
for (const face of extractFontFaceBlocks(readFileSync4(sheet, "utf8"))) {
|
|
2679
|
+
const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
|
|
2680
|
+
const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
|
|
2681
|
+
const path = decodedUrlPath(url);
|
|
2682
|
+
const file = path.startsWith("/") ? resolve3(projectDir2, `.${path}`) : resolve3(dirname3(sheet), path);
|
|
2683
|
+
return isPathInside(file, projectDir2) && existsSync3(file);
|
|
2684
|
+
});
|
|
2685
|
+
if (family && shipsFile) families.push(family);
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
return families;
|
|
2689
|
+
}
|
|
2690
|
+
function collectFontFaceUrls(html) {
|
|
2691
|
+
const urlSet = /* @__PURE__ */ new Set();
|
|
2692
|
+
for (const { parts } of styleBlockMatches(html)) {
|
|
2693
|
+
const cssText = parts[1];
|
|
2694
|
+
let i = 0;
|
|
2695
|
+
while (i < cssText.length) {
|
|
2696
|
+
const atIdx = cssText.indexOf("@font-face", i);
|
|
2697
|
+
if (atIdx === -1) break;
|
|
2698
|
+
const braceStart = cssText.indexOf("{", atIdx);
|
|
2699
|
+
if (braceStart === -1) break;
|
|
2700
|
+
let depth = 1;
|
|
2701
|
+
let j = braceStart + 1;
|
|
2702
|
+
while (j < cssText.length && depth > 0) {
|
|
2703
|
+
if (cssText[j] === "{") depth++;
|
|
2704
|
+
else if (cssText[j] === "}") depth--;
|
|
2705
|
+
j++;
|
|
2706
|
+
}
|
|
2707
|
+
const block = cssText.slice(braceStart + 1, j - 1);
|
|
2708
|
+
for (const { parts: parts2 } of remoteFontFaceUrlMatches(block)) {
|
|
2709
|
+
if (parts2[1]) urlSet.add(parts2[1]);
|
|
2710
|
+
}
|
|
2711
|
+
i = j;
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
return urlSet;
|
|
2715
|
+
}
|
|
2716
|
+
function localizeFontFaceUrls(html, downloadDir2, assets) {
|
|
2717
|
+
return downloadAndRewriteUrls(
|
|
2718
|
+
collectFontFaceUrls(html),
|
|
2719
|
+
html,
|
|
2720
|
+
join5(downloadDir2, REMOTE_MEDIA_SUBDIR),
|
|
2721
|
+
"Remote font download failed",
|
|
2722
|
+
"Localized remote font face(s)",
|
|
2723
|
+
assets,
|
|
2724
|
+
(h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
|
|
2725
|
+
);
|
|
2726
|
+
}
|
|
2727
|
+
var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
|
|
2728
|
+
async function readLocalFont(absPath) {
|
|
2729
|
+
const chunks = [];
|
|
2730
|
+
let totalBytes = 0;
|
|
2731
|
+
for await (const chunk of createReadStream(absPath)) {
|
|
2732
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
2733
|
+
totalBytes += buffer.length;
|
|
2734
|
+
if (totalBytes > MAX_LOCAL_FONT_DATA_URI_BYTES) {
|
|
2735
|
+
return { kind: "file-backed" };
|
|
2736
|
+
}
|
|
2737
|
+
chunks.push(buffer);
|
|
2738
|
+
}
|
|
2739
|
+
return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
|
|
2740
|
+
}
|
|
2741
|
+
async function localFontDataUri(localPath, projectDir2, assetRoot, dataUriByAbsolutePath, log2, downloadedPath, reserve) {
|
|
2742
|
+
const absPath = downloadedPath ?? (localPath.startsWith("/") ? localPath : resolve3(projectDir2, localPath));
|
|
2743
|
+
if (downloadedPath === void 0) {
|
|
2744
|
+
if (!isPathInside(absPath, projectDir2) || escapesAssetRoot(absPath, assetRoot)) {
|
|
2745
|
+
return void 0;
|
|
2746
|
+
}
|
|
2747
|
+
if (refusesOutsideLink(projectDir2, absPath, (line) => log2.warn(`[Compiler] ${line}`))) {
|
|
2748
|
+
return void 0;
|
|
2749
|
+
}
|
|
2750
|
+
if (isPrivateCompositionFile(projectDir2, absPath)) return void 0;
|
|
2751
|
+
}
|
|
2752
|
+
if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
|
|
2753
|
+
const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
|
|
2754
|
+
try {
|
|
2755
|
+
if (!reserve(Math.ceil(statSync4(absPath).size / 3) * 4 + 64)) {
|
|
2756
|
+
dataUriByAbsolutePath.set(absPath, void 0);
|
|
2757
|
+
return void 0;
|
|
2758
|
+
}
|
|
2759
|
+
const font = await readLocalFont(absPath);
|
|
2760
|
+
if (font.kind === "file-backed") {
|
|
2761
|
+
dataUriByAbsolutePath.set(absPath, void 0);
|
|
2762
|
+
defaultLogger.debug(
|
|
2763
|
+
`[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
|
|
2764
|
+
);
|
|
2765
|
+
return void 0;
|
|
2766
|
+
}
|
|
2767
|
+
const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
|
|
2768
|
+
const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
|
|
2769
|
+
dataUriByAbsolutePath.set(absPath, dataUri);
|
|
2770
|
+
defaultLogger.debug(
|
|
2771
|
+
`[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
|
|
2772
|
+
);
|
|
2773
|
+
return dataUri;
|
|
2774
|
+
} catch (error) {
|
|
2775
|
+
defaultLogger.warn(
|
|
2776
|
+
`[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
|
|
2777
|
+
);
|
|
2778
|
+
return void 0;
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
|
|
2782
|
+
async function embedLocalFontFaces(html, projectDir2, assetRoot, budget, log2 = defaultLogger, downloadedFonts = /* @__PURE__ */ new Map()) {
|
|
2783
|
+
const dataUriByPath = /* @__PURE__ */ new Map();
|
|
2784
|
+
const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
|
|
2785
|
+
let warned = false;
|
|
2786
|
+
const keptFileBacked = (localPath) => {
|
|
2787
|
+
if (warned) return;
|
|
2788
|
+
warned = true;
|
|
2789
|
+
log2.warn(
|
|
2790
|
+
`[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
|
|
2791
|
+
);
|
|
2792
|
+
};
|
|
2793
|
+
let reserved = 0;
|
|
2794
|
+
const reserveFor = (localPath) => (bytes) => {
|
|
2795
|
+
if (reserved + bytes > budget.generatedRoom) {
|
|
2796
|
+
keptFileBacked(localPath);
|
|
2797
|
+
return false;
|
|
2798
|
+
}
|
|
2799
|
+
reserved += bytes;
|
|
2800
|
+
return true;
|
|
2801
|
+
};
|
|
2802
|
+
for (const { parts: style } of styleBlockMatches(html)) {
|
|
2803
|
+
for (const { parts: face } of fontFaceBlockMatches(style[1])) {
|
|
2804
|
+
for (const { parts } of localFontFaceUrlMatches(face[1])) {
|
|
2805
|
+
const localPath = parts[1];
|
|
2806
|
+
if (!localPath || dataUriByPath.has(localPath)) continue;
|
|
2807
|
+
dataUriByPath.set(
|
|
2808
|
+
localPath,
|
|
2809
|
+
await localFontDataUri(
|
|
2810
|
+
localPath,
|
|
2811
|
+
projectDir2,
|
|
2812
|
+
assetRoot,
|
|
2813
|
+
dataUriByAbsolutePath,
|
|
2814
|
+
log2,
|
|
2815
|
+
downloadedFonts.get(localPath),
|
|
2816
|
+
reserveFor(localPath)
|
|
2817
|
+
)
|
|
2818
|
+
);
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
if (![...dataUriByPath.values()].some(Boolean)) return html;
|
|
2823
|
+
const embed = (source, localPath) => {
|
|
2824
|
+
const dataUri = dataUriByPath.get(localPath);
|
|
2825
|
+
if (!dataUri) return source;
|
|
2826
|
+
const inlined = `url("${dataUri}")`;
|
|
2827
|
+
if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
|
|
2828
|
+
keptFileBacked(localPath);
|
|
2829
|
+
return source;
|
|
2830
|
+
};
|
|
2831
|
+
return replaceMatches(
|
|
2832
|
+
html,
|
|
2833
|
+
styleBlockMatches(html),
|
|
2834
|
+
(style, css) => replaceInner(
|
|
2835
|
+
style,
|
|
2836
|
+
css,
|
|
2837
|
+
"</style>".length,
|
|
2838
|
+
replaceMatches(
|
|
2839
|
+
css,
|
|
2840
|
+
fontFaceBlockMatches(css),
|
|
2841
|
+
(face, body) => replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed))
|
|
2842
|
+
)
|
|
2843
|
+
)
|
|
2844
|
+
);
|
|
2845
|
+
}
|
|
2846
|
+
function renderGsapDist() {
|
|
2847
|
+
try {
|
|
2848
|
+
return gsapCdnDist(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
|
|
2849
|
+
} catch (cause) {
|
|
2850
|
+
throw new Error(
|
|
2851
|
+
"Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment",
|
|
2852
|
+
{ cause }
|
|
2853
|
+
);
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
function rewriteUnresolvableGsapToCdn(html, projectDir2, compSrcPath) {
|
|
2857
|
+
let gsapDist;
|
|
2858
|
+
const exists = (path) => {
|
|
2859
|
+
const file = resolve3(projectDir2, path);
|
|
2860
|
+
return !namesAnotherNetworkRoot2(projectDir2, file) && existsSync3(file);
|
|
2861
|
+
};
|
|
2862
|
+
return replaceGsapDistScripts(html, (full, prefix, src, file, suffix) => {
|
|
2863
|
+
if (/^https?:\/\//i.test(src)) return full;
|
|
2864
|
+
if (exists(compSrcPath ? rewriteAssetPath(compSrcPath, src, exists) : src)) return full;
|
|
2865
|
+
gsapDist ??= renderGsapDist();
|
|
2866
|
+
defaultLogger.debug(`[Compiler] Rewriting missing gsap script: ${src} \u2192 ${gsapDist}${file}`);
|
|
2867
|
+
return `${prefix}${gsapDist}${file}${suffix}`;
|
|
2868
|
+
});
|
|
2869
|
+
}
|
|
2870
|
+
function rebaseDirectEntryAssetPaths(html, projectDir2, htmlPath2, budget) {
|
|
2871
|
+
if (!isPathInside(htmlPath2, projectDir2)) return html;
|
|
2872
|
+
const entryPath = relative(projectDir2, htmlPath2).replace(/\\/g, "/");
|
|
2873
|
+
if (!entryPath.includes("/")) return html;
|
|
2874
|
+
const { document: document2 } = parseHTML4(html);
|
|
2875
|
+
const assetExists = projectAssetExists(projectDir2);
|
|
2876
|
+
const charge = (bytes) => budget.chargeGenerated(entryPath, bytes);
|
|
2877
|
+
rewriteAssetPaths(
|
|
2878
|
+
document2.querySelectorAll("[src], [href], [srcset]"),
|
|
2879
|
+
entryPath,
|
|
2880
|
+
(el, attr) => el.getAttribute(attr),
|
|
2881
|
+
(el, attr, value) => el.setAttribute(attr, value),
|
|
2882
|
+
assetExists,
|
|
2883
|
+
charge
|
|
2884
|
+
);
|
|
2885
|
+
rewriteInlineStyleAssetUrls(
|
|
2886
|
+
document2.querySelectorAll("[style]"),
|
|
2887
|
+
entryPath,
|
|
2888
|
+
(el) => el.getAttribute("style"),
|
|
2889
|
+
(el, value) => el.setAttribute("style", value),
|
|
2890
|
+
assetExists,
|
|
2891
|
+
charge
|
|
2892
|
+
);
|
|
2893
|
+
for (const style of document2.querySelectorAll("style")) {
|
|
2894
|
+
style.textContent = rewriteCssAssetUrls(
|
|
2895
|
+
style.textContent || "",
|
|
2896
|
+
entryPath,
|
|
2897
|
+
assetExists,
|
|
2898
|
+
charge
|
|
2899
|
+
);
|
|
2900
|
+
}
|
|
2901
|
+
return document2.toString();
|
|
2902
|
+
}
|
|
2903
|
+
var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
|
|
2904
|
+
var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
|
|
2905
|
+
function bindVariableMediaSources(html, variables, budget, log2) {
|
|
2906
|
+
if (!html.includes("data-var-src")) return html;
|
|
2907
|
+
const { document: document2 } = parseHTML4(html);
|
|
2908
|
+
const declared = {};
|
|
2909
|
+
for (const el of document2.querySelectorAll("[data-composition-variables]")) {
|
|
2910
|
+
Object.assign(declared, readDeclaredDefaults(el));
|
|
2911
|
+
}
|
|
2912
|
+
const values = { ...declared, ...variables };
|
|
2913
|
+
let changed = false;
|
|
2914
|
+
for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
|
|
2915
|
+
if (el.closest("[data-variable-values]")) continue;
|
|
2916
|
+
const bound = boundMediaSrc(el, values);
|
|
2917
|
+
if (bound === null) continue;
|
|
2918
|
+
const src = bound.trim();
|
|
2919
|
+
if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
|
|
2920
|
+
log2?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
|
|
2921
|
+
length: src.length
|
|
2922
|
+
});
|
|
2923
|
+
continue;
|
|
2924
|
+
}
|
|
2925
|
+
if (el.getAttribute("src") === src) continue;
|
|
2926
|
+
budget.chargeGenerated("variable media sources", src.length);
|
|
2927
|
+
el.setAttribute("src", src);
|
|
2928
|
+
changed = true;
|
|
2929
|
+
}
|
|
2930
|
+
return changed ? document2.toString() : html;
|
|
2931
|
+
}
|
|
2932
|
+
var entryFileName = (projectDir2, htmlPath2) => isPathInside(htmlPath2, projectDir2) ? relative(projectDir2, htmlPath2).split(sep2).join("/") : basename2(htmlPath2);
|
|
2933
|
+
async function compileForRender(projectDir2, htmlPath2, downloadDir2, options2 = {}) {
|
|
2934
|
+
const assets = new AssetDownloads(options2.abortSignal);
|
|
2935
|
+
try {
|
|
2936
|
+
return await compileWithAssets(projectDir2, htmlPath2, downloadDir2, options2, assets);
|
|
2937
|
+
} finally {
|
|
2938
|
+
assets.end();
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2941
|
+
async function compileWithAssets(projectDir2, htmlPath2, downloadDir2, options2, assets) {
|
|
2942
|
+
const assetRoot = options2.allowOutsideProjectAssets ? void 0 : projectDir2;
|
|
2943
|
+
const outsideFiles = { includeScripts: options2.includeOutsideScripts };
|
|
2944
|
+
if (isPathInside(htmlPath2, projectDir2) && escapesAssetRoot(htmlPath2, assetRoot)) {
|
|
2945
|
+
throw new Error(`Entry file ${htmlPath2} leads outside the project folder`);
|
|
2946
|
+
}
|
|
2947
|
+
if (isPathInside(htmlPath2, projectDir2) && runsOutsideMarkupUnasked(projectDir2, htmlPath2, assetRoot, outsideFiles)) {
|
|
2948
|
+
throw new Error(`Entry file ${htmlPath2} ${OUTSIDE_COMPOSITION_NEEDS_FLAG}`);
|
|
2949
|
+
}
|
|
2950
|
+
if (!COMPOSITION_FILE.test(htmlPath2)) {
|
|
2951
|
+
throw new Error(`Entry file ${htmlPath2} is not an .html file, so it is refused`);
|
|
2952
|
+
}
|
|
2953
|
+
assertCompositionFileSize(htmlPath2, basename2(htmlPath2));
|
|
2954
|
+
const budget = new CompositionExpansionBudget();
|
|
2955
|
+
const entryHtml = rebaseDirectEntryAssetPaths(
|
|
2956
|
+
readTextFile(htmlPath2),
|
|
2957
|
+
projectDir2,
|
|
2958
|
+
htmlPath2,
|
|
2959
|
+
budget
|
|
2960
|
+
);
|
|
2961
|
+
const rawHtml = bindVariableMediaSources(
|
|
2962
|
+
normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir2), projectDir2),
|
|
2963
|
+
options2.variables ?? {},
|
|
2964
|
+
budget,
|
|
2965
|
+
options2.log
|
|
2966
|
+
);
|
|
2967
|
+
assertSubCompositionsUsable(rawHtml, projectDir2, assetRoot, outsideFiles);
|
|
2968
|
+
const run = { probes: /* @__PURE__ */ new Map(), assets };
|
|
2969
|
+
const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
|
|
2970
|
+
rawHtml,
|
|
2971
|
+
projectDir2,
|
|
2972
|
+
projectDir2,
|
|
2973
|
+
downloadDir2,
|
|
2974
|
+
options2.log,
|
|
2975
|
+
options2.urlByAbsentLocalPath,
|
|
2976
|
+
run,
|
|
2977
|
+
assetRoot
|
|
2978
|
+
);
|
|
2979
|
+
const { subCompositions } = await parseSubCompositions(
|
|
2980
|
+
compiledHtml,
|
|
2981
|
+
projectDir2,
|
|
2982
|
+
downloadDir2,
|
|
2983
|
+
void 0,
|
|
2984
|
+
options2.urlByAbsentLocalPath,
|
|
2985
|
+
run,
|
|
2986
|
+
assetRoot,
|
|
2987
|
+
outsideFiles
|
|
2988
|
+
);
|
|
2989
|
+
const fullHtml = ensureFullDocument(compiledHtml);
|
|
2990
|
+
const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
|
|
2991
|
+
fullHtml,
|
|
2992
|
+
subCompositions,
|
|
2993
|
+
projectDir2,
|
|
2994
|
+
options2.variables ?? {},
|
|
2995
|
+
assetRoot,
|
|
2996
|
+
outsideFiles,
|
|
2997
|
+
budget
|
|
2998
|
+
);
|
|
2999
|
+
const sanitizedHtml = stripPreloadNone(inlinedHtml);
|
|
3000
|
+
const renderModeHints = detectRenderModeHints(sanitizedHtml, options2.pageMotionBlur);
|
|
3001
|
+
const hasShaderTransitions = detectShaderTransitionUsage(sanitizedHtml);
|
|
3002
|
+
const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
|
|
3003
|
+
const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
|
|
3004
|
+
let deadline;
|
|
3005
|
+
const remoteFetches = () => deadline ??= AbortSignal.any([
|
|
3006
|
+
AbortSignal.timeout(REMOTE_FETCH_DEADLINE_MS),
|
|
3007
|
+
...options2.abortSignal ? [options2.abortSignal] : []
|
|
3008
|
+
]);
|
|
3009
|
+
const fontSheetHtml = await inlineExternalFontStylesheets(
|
|
3010
|
+
promoteCssImportsToLinkTags(sanitizedHtml),
|
|
3011
|
+
budget,
|
|
3012
|
+
remoteFetches
|
|
3013
|
+
);
|
|
3014
|
+
options2.abortSignal?.throwIfAborted();
|
|
3015
|
+
const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
|
|
3016
|
+
injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml))
|
|
3017
|
+
);
|
|
3018
|
+
const coalescedHtml = await injectDeterministicFontFaces(normalizedFontHtml, {
|
|
3019
|
+
logger: defaultLogger,
|
|
3020
|
+
failClosedFontFetch: options2.failClosedFontFetch === true,
|
|
3021
|
+
allowSystemFontCapture: options2.allowSystemFontCapture,
|
|
3022
|
+
projectFontFamilies: projectStylesheetFontFamilies(fontSheetHtml, projectDir2),
|
|
3023
|
+
abortSignal: options2.abortSignal
|
|
3024
|
+
});
|
|
3025
|
+
const assembledHtml = await inlineExternalScripts(coalescedHtml, budget, remoteFetches);
|
|
3026
|
+
options2.abortSignal?.throwIfAborted();
|
|
3027
|
+
const htmlWithPositionScript = htmlHasStudioPositionEdits(assembledHtml) ? insertBeforeCloseTag(
|
|
3028
|
+
assembledHtml,
|
|
3029
|
+
"body",
|
|
3030
|
+
`<script>${createStudioPositionSeekReapplyScript()}
|
|
3031
|
+
//# sourceURL=hyperframes://position-seek-reapply</script>`
|
|
3032
|
+
) ?? assembledHtml : assembledHtml;
|
|
3033
|
+
const htmlWithDeferredScripts = prepareCompositionScripts(
|
|
3034
|
+
injectSdkPositionEditsRenderScript(htmlWithPositionScript)
|
|
3035
|
+
);
|
|
3036
|
+
const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
|
|
3037
|
+
htmlWithDeferredScripts,
|
|
3038
|
+
downloadDir2,
|
|
3039
|
+
run.assets
|
|
3040
|
+
);
|
|
3041
|
+
const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir2, run.assets);
|
|
3042
|
+
const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir2, run.assets);
|
|
3043
|
+
const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir2, run.assets);
|
|
3044
|
+
const {
|
|
3045
|
+
html: htmlWithJpegs,
|
|
3046
|
+
preparedAssets: preparedHeifAssets,
|
|
3047
|
+
preparedImages: preparedHeifImages
|
|
3048
|
+
} = await prepareHeifImageInputs(htmlWithLocalizedFonts, {
|
|
3049
|
+
projectDir: projectDir2,
|
|
3050
|
+
downloadDir: downloadDir2,
|
|
3051
|
+
cacheDir: options2.animatedGifCacheDir,
|
|
3052
|
+
sourceAssets: remoteImageAssets,
|
|
3053
|
+
timeoutMs: options2.ffmpegProcessTimeout,
|
|
3054
|
+
allowOutsideFiles: assetRoot === void 0
|
|
3055
|
+
});
|
|
3056
|
+
if (preparedHeifImages.length > 0) {
|
|
3057
|
+
defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
|
|
3058
|
+
}
|
|
3059
|
+
const gifSourceAssets = new Map(remoteImageAssets);
|
|
3060
|
+
const {
|
|
3061
|
+
html: htmlWithPreparedGifs,
|
|
3062
|
+
preparedAssets: preparedGifAssets,
|
|
3063
|
+
preparedGifs
|
|
3064
|
+
} = await prepareAnimatedGifInputs(htmlWithJpegs, {
|
|
3065
|
+
projectDir: projectDir2,
|
|
3066
|
+
downloadDir: downloadDir2,
|
|
3067
|
+
cacheDir: options2.animatedGifCacheDir,
|
|
3068
|
+
sourceAssets: gifSourceAssets,
|
|
3069
|
+
timeoutMs: options2.ffmpegProcessTimeout,
|
|
3070
|
+
allowOutsideFiles: assetRoot === void 0
|
|
3071
|
+
});
|
|
3072
|
+
if (preparedGifs.length > 0) {
|
|
3073
|
+
defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
|
|
3074
|
+
}
|
|
3075
|
+
const embeddedHtml = await embedLocalFontFaces(
|
|
3076
|
+
htmlWithPreparedGifs,
|
|
3077
|
+
projectDir2,
|
|
3078
|
+
assetRoot,
|
|
3079
|
+
budget,
|
|
3080
|
+
options2.log,
|
|
3081
|
+
remoteFontAssets
|
|
3082
|
+
);
|
|
3083
|
+
const { html, externalAssets } = options2.allowOutsideProjectAssets ? collectExternalAssets(
|
|
3084
|
+
embeddedHtml,
|
|
3085
|
+
projectDir2,
|
|
3086
|
+
options2.log,
|
|
3087
|
+
entryFileName(projectDir2, htmlPath2),
|
|
3088
|
+
{ includeScripts: options2.includeOutsideScripts }
|
|
3089
|
+
) : { html: embeddedHtml, externalAssets: /* @__PURE__ */ new Map() };
|
|
3090
|
+
for (const [relPath, absPath] of remoteMediaAssets) {
|
|
3091
|
+
externalAssets.set(relPath, absPath);
|
|
3092
|
+
}
|
|
3093
|
+
for (const [relPath, absPath] of remoteImageAssets) {
|
|
3094
|
+
externalAssets.set(relPath, absPath);
|
|
3095
|
+
}
|
|
3096
|
+
for (const [relPath, absPath] of remoteBgAssets) {
|
|
3097
|
+
externalAssets.set(relPath, absPath);
|
|
3098
|
+
}
|
|
3099
|
+
for (const [relPath, absPath] of remoteFontAssets) {
|
|
3100
|
+
externalAssets.set(relPath, absPath);
|
|
3101
|
+
}
|
|
3102
|
+
for (const [relPath, absPath] of preparedGifAssets) {
|
|
3103
|
+
externalAssets.set(relPath, absPath);
|
|
3104
|
+
}
|
|
3105
|
+
for (const [relPath, absPath] of preparedHeifAssets) {
|
|
3106
|
+
externalAssets.set(relPath, absPath);
|
|
3107
|
+
}
|
|
3108
|
+
const { videos, audios, images, droppedMediaIds, gradedCanvas } = collectRenderMedia(html);
|
|
3109
|
+
const masterFxChain = parseMasterFxChain(html);
|
|
3110
|
+
const advised = /* @__PURE__ */ new Set();
|
|
3111
|
+
for (const video of videos) {
|
|
3112
|
+
if (isHttpUrl(video.src)) continue;
|
|
3113
|
+
const videoPath = resolve3(projectDir2, video.src);
|
|
3114
|
+
if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir2, videoPath) || !existsSync3(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir2, downloadDir2]))
|
|
3115
|
+
continue;
|
|
3116
|
+
advised.add(videoPath);
|
|
3117
|
+
const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
|
|
3118
|
+
(async () => {
|
|
3119
|
+
const metadata = await withMediaProbeSlot(() => extractMediaMetadata(videoPath));
|
|
3120
|
+
const analysis = await withMediaProbeSlot(
|
|
3121
|
+
() => analyzeKeyframeIntervals(videoPath, metadata)
|
|
3122
|
+
);
|
|
3123
|
+
if (analysis.isProblematic) {
|
|
3124
|
+
defaultLogger.warn(
|
|
3125
|
+
`[Compiler] WARNING: Video "${video.id}" has sparse keyframes (max interval: ${analysis.maxIntervalSeconds}s). Long GOPs can make preview seeking slower; rendering is unaffected. If preview seeking is slow, re-encode with: ${reencode}`
|
|
3126
|
+
);
|
|
3127
|
+
}
|
|
3128
|
+
if (metadata.isVFR) {
|
|
3129
|
+
defaultLogger.warn(
|
|
3130
|
+
`[Compiler] Video "${video.id}" is variable frame rate (VFR); the engine will normalize it to CFR before frame extraction. If rendering feels slow on this video, pre-encode once with: ${reencode}`
|
|
3131
|
+
);
|
|
3132
|
+
}
|
|
3133
|
+
})().catch(() => {
|
|
3134
|
+
});
|
|
3135
|
+
}
|
|
3136
|
+
const { document: document2 } = parseHTML4(html);
|
|
3137
|
+
const rootEl = document2.querySelector("[data-composition-id]");
|
|
3138
|
+
const width = rootEl ? parseInt(rootEl.getAttribute("data-width") || "1080", 10) : 1080;
|
|
3139
|
+
const height = rootEl ? parseInt(rootEl.getAttribute("data-height") || "1920", 10) : 1920;
|
|
3140
|
+
const staticDuration = rootEl ? parseStrictFiniteTimingNumber(rootEl.getAttribute("data-duration")) ?? parseStrictFiniteTimingNumber(rootEl.getAttribute("data-composition-duration")) ?? 0 : 0;
|
|
3141
|
+
return {
|
|
3142
|
+
html,
|
|
3143
|
+
subCompositions,
|
|
3144
|
+
videos,
|
|
3145
|
+
audios,
|
|
3146
|
+
images,
|
|
3147
|
+
droppedMediaIds,
|
|
3148
|
+
gradedCanvas,
|
|
3149
|
+
...masterFxChain ? { masterFxChain } : {},
|
|
3150
|
+
unresolvedCompositions,
|
|
3151
|
+
variablesByComp,
|
|
3152
|
+
externalAssets,
|
|
3153
|
+
width,
|
|
3154
|
+
height,
|
|
3155
|
+
staticDuration,
|
|
3156
|
+
renderModeHints,
|
|
3157
|
+
hasShaderTransitions,
|
|
3158
|
+
usesThreeDTransforms,
|
|
3159
|
+
hasAncestorBackgroundImage
|
|
3160
|
+
};
|
|
3161
|
+
}
|
|
3162
|
+
|
|
3163
|
+
// src/services/compileWorker.ts
|
|
3164
|
+
var { projectDir, htmlPath, downloadDir, options } = workerData;
|
|
3165
|
+
function post(level, message, meta) {
|
|
3166
|
+
try {
|
|
3167
|
+
parentPort?.postMessage({ type: "log", level, message, meta });
|
|
3168
|
+
} catch {
|
|
3169
|
+
let plain;
|
|
3170
|
+
try {
|
|
3171
|
+
plain = JSON.parse(JSON.stringify(meta));
|
|
3172
|
+
} catch {
|
|
3173
|
+
plain = void 0;
|
|
3174
|
+
}
|
|
3175
|
+
parentPort?.postMessage({ type: "log", level, message, meta: plain });
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
var log = {
|
|
3179
|
+
error: (message, meta) => post("error", message, meta),
|
|
3180
|
+
warn: (message, meta) => post("warn", message, meta),
|
|
3181
|
+
info: (message, meta) => post("info", message, meta),
|
|
3182
|
+
debug: (message, meta) => post("debug", message, meta)
|
|
3183
|
+
};
|
|
3184
|
+
var controller = new AbortController();
|
|
3185
|
+
parentPort?.on("message", (message) => {
|
|
3186
|
+
if (message?.type === "abort") controller.abort(new Error("compile stopped"));
|
|
3187
|
+
});
|
|
3188
|
+
parentPort?.unref();
|
|
3189
|
+
try {
|
|
3190
|
+
const compiled = await compileForRender(projectDir, htmlPath, downloadDir, {
|
|
3191
|
+
...options,
|
|
3192
|
+
log,
|
|
3193
|
+
abortSignal: controller.signal
|
|
3194
|
+
});
|
|
3195
|
+
parentPort?.postMessage({ type: "result", compiled });
|
|
3196
|
+
} catch (error) {
|
|
3197
|
+
const props = {};
|
|
3198
|
+
if (error instanceof Error) {
|
|
3199
|
+
for (const [key, value] of Object.entries(error)) {
|
|
3200
|
+
try {
|
|
3201
|
+
props[key] = structuredClone(value);
|
|
3202
|
+
} catch {
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
parentPort?.postMessage({
|
|
3207
|
+
type: "error",
|
|
3208
|
+
error: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack, props } : { name: "Error", message: String(error), props }
|
|
3209
|
+
});
|
|
3210
|
+
}
|