@hyperframes/core 0.10.6 → 0.10.7

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.
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { endsWithLineComment, stripJsCommentsInProcess } from "./stripJsComments.js";
2
2
  import { compositionStyle, cssStyleMergeKey, deferScriptsUntilFonts, isAlwaysAppliedStyle, headStyleRuns, INLINED_FILE_ATTR, inlineScriptRuns, styleElementsFor, } from "./scriptRuns.js";
3
3
  import { countPageRoot, executableScripts, isJavaScriptType, planCompositionAssembly, } from "./compositionAssembly.js";
4
4
  import { SCENE_FONTS_ATTR, SCENE_PART_ATTR } from "../sceneParts.js";
@@ -667,7 +667,7 @@ function pushRun(runs, scene, chunk) {
667
667
  else
668
668
  runs.push({ scene, chunks: [chunk] });
669
669
  }
670
- async function coalesceHeadStylesAndBodyScripts(document, provenance) {
670
+ function coalesceHeadStylesAndBodyScripts(document, provenance) {
671
671
  const allHeadStyles = [...document.querySelectorAll("head style")];
672
672
  const isScenePart = (el) => el.hasAttribute(SCENE_PART_ATTR);
673
673
  for (const run of allHeadStyles.length > 1 ? headStyleRuns(allHeadStyles, isScenePart) : []) {
@@ -685,7 +685,7 @@ async function coalesceHeadStylesAndBodyScripts(document, provenance) {
685
685
  const mergedJs = joinJsChunks(members.map((el) => el.textContent || ""));
686
686
  if (mergedJs && !parsesAsScript(mergedJs)) {
687
687
  for (const el of members)
688
- el.textContent = await inlineScriptSource(el.textContent || "", provenance);
688
+ el.textContent = inlineScriptSource(el.textContent || "", provenance);
689
689
  continue;
690
690
  }
691
691
  for (const el of members)
@@ -693,7 +693,7 @@ async function coalesceHeadStylesAndBodyScripts(document, provenance) {
693
693
  if (!mergedJs)
694
694
  continue;
695
695
  const inlineScript = document.createElement("script");
696
- inlineScript.textContent = await inlineScriptSource(mergedJs, provenance);
696
+ inlineScript.textContent = inlineScriptSource(mergedJs, provenance);
697
697
  if (anchor)
698
698
  anchor.before(inlineScript);
699
699
  else
@@ -742,7 +742,7 @@ function joinJsChunks(chunks) {
742
742
  return chunks
743
743
  .map((chunk) => chunk.trim())
744
744
  .filter((chunk) => chunk.length > 0)
745
- .map((chunk) => (chunk.endsWith(";") ? chunk : chunk + "\n;"))
745
+ .map((chunk) => chunk.endsWith(";") ? chunk : chunk + (endsWithLineComment(chunk) ? "\n;" : ";"))
746
746
  .join("\n");
747
747
  }
748
748
  // acorn in script mode, not the host engine: Bun 1.3's vm.Script compiles lazily and accepts anything.
@@ -756,32 +756,8 @@ export function parsesAsScript(source) {
756
756
  return false;
757
757
  }
758
758
  }
759
- async function stripJsCommentsParserSafe(source, provenance) {
760
- if (!source)
761
- return source;
762
- const { transform } = await import("esbuild");
763
- try {
764
- const result = await transform(source, {
765
- loader: "js",
766
- minify: false,
767
- legalComments: "none",
768
- ...(provenance
769
- ? { sourcemap: "external", sourcefile: "hf-authored-bundle.js" }
770
- : {}),
771
- });
772
- if (provenance) {
773
- const sourceURL = `hf-inspect-${createHash("sha256").update(source).digest("hex")}.js`;
774
- provenance({ input: source, output: result.code.trim(), sourceMap: result.map, sourceURL });
775
- return `${result.code.trim()}\n//# sourceURL=${sourceURL}`;
776
- }
777
- return result.code.trim();
778
- }
779
- catch {
780
- return source;
781
- }
782
- }
783
- async function inlineScriptSource(js, provenance) {
784
- return escapeInlineScriptSource(await stripJsCommentsParserSafe(js, provenance));
759
+ function inlineScriptSource(js, provenance) {
760
+ return escapeInlineScriptSource(stripJsCommentsInProcess(js, provenance));
785
761
  }
786
762
  /** The page's script tags by `src`, collected at first use; a pin carried to a new spelling adds its tag. */
787
763
  function scriptTagsBySrc(doc) {
@@ -1289,7 +1265,7 @@ async function bundleProject(projectDir, options) {
1289
1265
  if (scene)
1290
1266
  script.setAttribute(SCENE_PART_ATTR, scene);
1291
1267
  script.textContent = skipsRunMerge
1292
- ? await inlineScriptSource(text, options?.scriptProvenance)
1268
+ ? inlineScriptSource(text, options?.scriptProvenance)
1293
1269
  : text;
1294
1270
  document.body.appendChild(script);
1295
1271
  }
@@ -1298,10 +1274,10 @@ async function bundleProject(projectDir, options) {
1298
1274
  emitRootCompositionVariableStyles(document, compVariablesByComp);
1299
1275
  enforceCompositionPixelSizing(document);
1300
1276
  autoHealMissingCompositionIds(document);
1301
- await coalesceHeadStylesAndBodyScripts(document, options?.scriptProvenance);
1277
+ coalesceHeadStylesAndBodyScripts(document, options?.scriptProvenance);
1302
1278
  for (const el of document.querySelectorAll(`script[${INLINED_FILE_ATTR}]`)) {
1303
1279
  const js = el.textContent ?? "";
1304
- el.textContent = escapeInlineScriptSource(isJavaScriptType(el) ? await stripJsCommentsParserSafe(js, options?.scriptProvenance) : js);
1280
+ el.textContent = escapeInlineScriptSource(isJavaScriptType(el) ? stripJsCommentsInProcess(js, options?.scriptProvenance) : js);
1305
1281
  }
1306
1282
  deferScriptsUntilFonts(document, (el) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR));
1307
1283
  injectTextRenderingRule(document);
@@ -5,7 +5,7 @@ export { resolveTimings, } from "./timingResolver.js";
5
5
  export { compileTimingAttrs, injectDurations, extractResolvedMedia, clampDurations, shouldClampMediaDuration, shouldClampResolvedMediaDuration, } from "./timingCompiler.js";
6
6
  // HTML compiler (Node.js — requires fs)
7
7
  export { compileHtml } from "./htmlCompiler.js";
8
- // HTML bundler (Node.js — requires fs, linkedom, esbuild)
8
+ // HTML bundler (Node.js — requires fs, linkedom, acorn)
9
9
  export { assignBundledRuntimeCompositionIds, bundleToSingleHtml, prepareFlattenedInnerRoot, FLATTENED_INNER_ROOT_STRIP_ATTRS, emitRootCompositionVariableStyles, MAX_COMPOSITION_VARIABLE_STYLE_BYTES, parsesAsScript, } from "./htmlBundler.js";
10
10
  export { readDeclaredDefaults, parseHostVariableValues } from "../runtime/getVariables.js";
11
11
  export { dropAuthoredCompositionFiles } from "../compositionSource.js";
@@ -0,0 +1,12 @@
1
+ export interface StrippedScriptProvenance {
2
+ input: string;
3
+ output: string;
4
+ sourceMap: string;
5
+ sourceURL: string;
6
+ }
7
+ /**
8
+ * Whether `source` ends with an unterminated single-line comment (so appending `;`
9
+ * on the same line would be swallowed by the comment).
10
+ */
11
+ export declare function endsWithLineComment(source: string): boolean;
12
+ export declare function stripJsCommentsInProcess(source: string, provenance?: (script: StrippedScriptProvenance) => void): string;
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto";
2
+ import { tokenizer } from "acorn";
3
+ const VLQ_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4
+ function encodeVlq(value) {
5
+ let vlq = value < 0 ? (-value << 1) | 1 : value << 1;
6
+ let encoded = "";
7
+ do {
8
+ let digit = vlq & 31;
9
+ vlq >>>= 5;
10
+ if (vlq > 0)
11
+ digit |= 32;
12
+ encoded += VLQ_CHARS[digit];
13
+ } while (vlq > 0);
14
+ return encoded;
15
+ }
16
+ // Identity v3 source map: space-filling comments keeps every token at its original (line, col).
17
+ function buildIdentityTokenSourceMap(source, tokens) {
18
+ const lines = [];
19
+ let prevOrigLine = 0;
20
+ let prevOrigCol = 0;
21
+ for (const { line, col } of tokens) {
22
+ const lineIndex = line - 1;
23
+ while (lines.length <= lineIndex)
24
+ lines.push([]);
25
+ const row = lines[lineIndex];
26
+ const prevGenCol = row.length === 0 ? 0 : prevOrigCol;
27
+ row.push(encodeVlq(col - prevGenCol) +
28
+ "A" +
29
+ encodeVlq(lineIndex - prevOrigLine) +
30
+ encodeVlq(col - prevOrigCol));
31
+ prevOrigLine = lineIndex;
32
+ prevOrigCol = col;
33
+ }
34
+ return JSON.stringify({
35
+ version: 3,
36
+ sources: ["hf-authored-bundle.js"],
37
+ sourcesContent: [source],
38
+ mappings: lines.map((row) => row.join(",")).join(";"),
39
+ names: [],
40
+ });
41
+ }
42
+ function replaceCommentSpansWithSpaces(source, comments) {
43
+ if (comments.length === 0)
44
+ return source.trimEnd();
45
+ let out = "";
46
+ let cursor = 0;
47
+ for (const [start, end] of comments) {
48
+ out += source.slice(cursor, start);
49
+ out += source.slice(start, end).replace(/[^\r\n\u2028\u2029]/g, " ");
50
+ cursor = end;
51
+ }
52
+ out += source.slice(cursor);
53
+ return out.trimEnd();
54
+ }
55
+ const TOKENIZER_OPTIONS = {
56
+ ecmaVersion: "latest",
57
+ sourceType: "script",
58
+ allowHashBang: true,
59
+ allowReturnOutsideFunction: true,
60
+ allowAwaitOutsideFunction: true,
61
+ allowImportExportEverywhere: true,
62
+ };
63
+ /**
64
+ * Whether `source` ends with an unterminated single-line comment (so appending `;`
65
+ * on the same line would be swallowed by the comment).
66
+ */
67
+ export function endsWithLineComment(source) {
68
+ if (!source)
69
+ return false;
70
+ let lastLineCommentEnd = -1;
71
+ try {
72
+ const stream = tokenizer(source, {
73
+ ...TOKENIZER_OPTIONS,
74
+ onComment: (block, _text, _start, end) => {
75
+ if (!block)
76
+ lastLineCommentEnd = end;
77
+ },
78
+ });
79
+ for (const _token of stream) {
80
+ // Drain tokenizer so trailing comments are reported.
81
+ }
82
+ return lastLineCommentEnd === source.length;
83
+ }
84
+ catch {
85
+ return /\/\/[^\r\n\u2028\u2029]*$/.test(source);
86
+ }
87
+ }
88
+ // Replace comments with same-length spaces (keeping line breaks) in-process via acorn's tokenizer.
89
+ export function stripJsCommentsInProcess(source, provenance) {
90
+ if (!source)
91
+ return source;
92
+ const comments = [];
93
+ const tokens = [];
94
+ try {
95
+ const stream = tokenizer(source, {
96
+ ...TOKENIZER_OPTIONS,
97
+ locations: Boolean(provenance),
98
+ onComment: (_block, _text, start, end) => {
99
+ comments.push([start, end]);
100
+ },
101
+ });
102
+ for (const token of stream) {
103
+ if (provenance && token.loc) {
104
+ tokens.push({ line: token.loc.start.line, col: token.loc.start.column });
105
+ }
106
+ }
107
+ }
108
+ catch {
109
+ return source;
110
+ }
111
+ const output = replaceCommentSpansWithSpaces(source, comments);
112
+ if (provenance) {
113
+ const sourceURL = `hf-inspect-${createHash("sha256").update(source).digest("hex")}.js`;
114
+ const sourceMap = buildIdentityTokenSourceMap(source, tokens);
115
+ provenance({ input: source, output, sourceMap, sourceURL });
116
+ return `${output}\n//# sourceURL=${sourceURL}`;
117
+ }
118
+ return output;
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/core",
3
- "version": "0.10.6",
3
+ "version": "0.10.7",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -525,9 +525,9 @@
525
525
  "linkedom": "^0.18.12",
526
526
  "postcss": "^8.5.8",
527
527
  "wawoff2": "^2.0.1",
528
- "@hyperframes/studio-server": "0.10.6",
529
- "@hyperframes/lint": "0.10.6",
530
- "@hyperframes/parsers": "0.10.6"
528
+ "@hyperframes/parsers": "0.10.7",
529
+ "@hyperframes/studio-server": "0.10.7",
530
+ "@hyperframes/lint": "0.10.7"
531
531
  },
532
532
  "devDependencies": {
533
533
  "@fontsource/archivo-black": "^5.2.8",