@hyperframes/core 0.9.51 → 0.9.53

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,5 +1,6 @@
1
1
  export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot.js";
2
2
  import { type MediaDurationProber } from "./htmlCompiler.js";
3
+ export declare function restoreCssPlaceholders(css: string, texts: ReadonlyMap<string, string>): string;
3
4
  export type BundledHostCompositionIdentity = {
4
5
  authoredCompositionId: string | null;
5
6
  runtimeCompositionId: string | null;
@@ -16,7 +16,8 @@ import { parse as parseJs } from "acorn";
16
16
  import { resolve, relative, dirname, isAbsolute, sep } from "path";
17
17
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "./standaloneEntry.js";
18
18
  import { decodeCssEscapes, decodeWellFormedEscapes, encodeUrlPath, decodedUrlPath, splitUrlSuffix, } from "@hyperframes/parsers/asset-paths";
19
- import { CSS_URL_RE, isNonRelativeUrl } from "./assetPaths.js";
19
+ import { blockCommentMatches, cssImportMatches, cssUrlMatches, rawCssUrlMatches, replaceMatches, } from "@hyperframes/parsers/css-url-scans";
20
+ import { isNonRelativeUrl } from "./assetPaths.js";
20
21
  import { rewriteSrcsetUrls } from "./srcset.js";
21
22
  import { compileHtml } from "./htmlCompiler.js";
22
23
  import { RUNTIME_BOOTSTRAP_ATTR, escapeInlineScriptSource, insertRuntimeTag, parseHTMLContent, stripEmbeddedRuntimeScripts, } from "./htmlDocument.js";
@@ -85,24 +86,18 @@ function safeReadFile(filePath) {
85
86
  return null;
86
87
  }
87
88
  }
88
- const CSS_IMPORT_RE = /@import\s+(?:url\(\s*(["']?)([^)"']+)\1\s*\)|(["'])([^"']+)\3)\s*([^;]*);\s*/g;
89
- const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
90
- function withCommentsStripped(css, fn) {
91
- const comments = [];
92
- const stripped = css.replace(CSS_COMMENT_RE, (m) => {
93
- const idx = comments.length;
94
- comments.push(m);
95
- return `/*__hf_c${idx}__*/`;
89
+ const CSS_PLACEHOLDER_RE = /\/\*__hf_(?:c|import_)\d+__\*\//g;
90
+ export function restoreCssPlaceholders(css, texts) {
91
+ return css.replace(CSS_PLACEHOLDER_RE, (placeholder) => texts.get(placeholder) ?? placeholder);
92
+ }
93
+ function withCommentsStripped(css) {
94
+ const comments = new Map();
95
+ const stripped = replaceMatches(css, blockCommentMatches(css), (m) => {
96
+ const placeholder = `/*__hf_c${comments.size}__*/`;
97
+ comments.set(placeholder, m);
98
+ return placeholder;
96
99
  });
97
- const result = fn(stripped);
98
- const restore = (s) => {
99
- let out = s;
100
- for (let i = 0; i < comments.length; i++) {
101
- out = out.replace(`/*__hf_c${i}__*/`, comments[i]);
102
- }
103
- return out;
104
- };
105
- return { result, restore };
100
+ return { stripped, comments };
106
101
  }
107
102
  function resolveRelativeUrlPath(fromDir, basePath) {
108
103
  return resolve(fromDir, decodeWellFormedEscapes(basePath.replaceAll("\\", "/")));
@@ -112,7 +107,7 @@ function rebaseCssUrls(css, cssFileDir, projectDir) {
112
107
  const resolvedDir = resolve(cssFileDir);
113
108
  if (resolvedDir === resolvedRoot)
114
109
  return css;
115
- return css.replace(CSS_URL_RE, (full, quote, urlValue) => {
110
+ return replaceMatches(css, cssUrlMatches(css), (full, quote, urlValue) => {
116
111
  const decoded = decodeCssEscapes(urlValue);
117
112
  if (!decoded || !isRelativeUrl(decoded))
118
113
  return full;
@@ -195,9 +190,8 @@ function rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir) {
195
190
  }
196
191
  }
197
192
  function inlineCssFile(css, cssFileDir, projectDir, activeImports) {
198
- const { result: strippedCss, restore: restoreComments } = withCommentsStripped(css, (s) => s);
199
- const importPlaceholders = [];
200
- const withPlaceholders = strippedCss.replace(CSS_IMPORT_RE, (full, _q1, urlPath, _q2, barePath, mediaQuery) => {
193
+ const { stripped: strippedCss, comments: placeholders } = withCommentsStripped(css);
194
+ const withPlaceholders = replaceMatches(strippedCss, cssImportMatches(strippedCss), (full, _q1, urlPath, _q2, barePath, mediaQuery) => {
201
195
  const importPath = urlPath ?? barePath;
202
196
  if (!importPath || !isRelativeUrl(importPath))
203
197
  return full;
@@ -216,16 +210,11 @@ function inlineCssFile(css, cssFileDir, projectDir, activeImports) {
216
210
  activeImports.delete(resolved);
217
211
  const trimmedMedia = (mediaQuery || "").trim();
218
212
  const block = trimmedMedia ? `@media ${trimmedMedia} {\n${inlined}\n}\n` : inlined + "\n";
219
- const idx = importPlaceholders.length;
220
- importPlaceholders.push(block);
221
- return `/*__hf_import_${idx}__*/`;
213
+ const placeholder = `/*__hf_import_${placeholders.size}__*/`;
214
+ placeholders.set(placeholder, block);
215
+ return placeholder;
222
216
  });
223
- let rebased = rebaseCssUrls(withPlaceholders, cssFileDir, projectDir);
224
- rebased = restoreComments(rebased);
225
- for (let i = 0; i < importPlaceholders.length; i++) {
226
- rebased = rebased.replace(`/*__hf_import_${i}__*/`, importPlaceholders[i]);
227
- }
228
- return rebased;
217
+ return restoreCssPlaceholders(rebaseCssUrls(withPlaceholders, cssFileDir, projectDir), placeholders);
229
218
  }
230
219
  function safeReadFileBuffer(filePath) {
231
220
  noteRead(filePath);
@@ -428,7 +417,7 @@ function rewriteColorGradingLutWithInlinedAssets(value, inlineAsset) {
428
417
  function rewriteCssUrlsWithInlinedAssets(cssText, inlineAsset) {
429
418
  if (!cssText)
430
419
  return cssText;
431
- return cssText.replace(/\burl\(\s*(["']?)([^)"']+)\1\s*\)/g, (_full, quote, rawUrl) => {
420
+ return replaceMatches(cssText, rawCssUrlMatches(cssText), (_full, quote, rawUrl) => {
432
421
  const maybeInlined = inlineAsset((rawUrl || "").trim());
433
422
  if (!maybeInlined)
434
423
  return _full;
@@ -619,7 +608,8 @@ function joinCssHoistingImports(sheets) {
619
608
  const imports = new Set();
620
609
  const cssParts = [];
621
610
  for (const sheet of sheets) {
622
- const rest = sheet.trim().replace(CSS_IMPORT_RE, (match) => {
611
+ const trimmed = sheet.trim();
612
+ const rest = replaceMatches(trimmed, cssImportMatches(trimmed), (match) => {
623
613
  imports.add(match.trim());
624
614
  return "";
625
615
  });
@@ -633,9 +623,11 @@ function placeSceneStylesLikeRender(document) {
633
623
  const styles = [...document.querySelectorAll("head style")];
634
624
  const imports = new Set();
635
625
  for (const el of styles) {
636
- el.textContent = (el.textContent || "")
637
- .replace(CSS_IMPORT_RE, (match) => (imports.add(match.trim()), ""))
638
- .trim();
626
+ const css = el.textContent || "";
627
+ el.textContent = replaceMatches(css, cssImportMatches(css), (match) => {
628
+ imports.add(match.trim());
629
+ return "";
630
+ }).trim();
639
631
  }
640
632
  styles.slice(1).reduce((previous, el) => (previous.after(el), el), styles[0]);
641
633
  if (imports.size === 0)
@@ -5,6 +5,7 @@
5
5
  * keeps the authored id (otherwise the first element does). Renamed elements retain
6
6
  * data-hf-authored-id for script lookup compatibility.
7
7
  */
8
+ import { replaceMatches, urlHashRefMatches } from "@hyperframes/parsers/css-url-scans";
8
9
  import postcss from "postcss";
9
10
  import { escapeCssIdentifier } from "./selectorIdTokens.js";
10
11
  import { SVG_REFERENCE_ALIASES_ATTR, readSvgReferenceAliases, rewriteSvgSelectors, } from "./svgSelectorAliases.js";
@@ -13,20 +14,6 @@ const ID_ATTR = "id";
13
14
  * same purpose (let a renamed id still resolve by its authored name), now
14
15
  * generalized from "the composition root" to any renamed descendant. */
15
16
  export const SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";
16
- /**
17
- * Matches a `url(#id)` funcref value — quoted or bare — as used by
18
- * `clip-path`, `filter`, `mask`, `fill`, `stroke`, `marker-start/mid/end`,
19
- * `cursor`, `mask-image`, and equally by any of those written into an inline
20
- * `style` attribute or a `<style>` declaration value. One pattern covers all
21
- * of them because CSS only ever spells an id reference this way in a
22
- * property VALUE — a bare `#id` (no `url()`) is exclusively a *selector*.
23
- *
24
- * The captured id is the literal fragment text. A fragment is a URL, not a
25
- * CSS identifier, so it carries no CSS escapes; the replacement keeps the
26
- * original quoting and only swaps the id, which stays a valid fragment
27
- * because the namespace prefix is restricted to `[A-Za-z0-9_-]`.
28
- */
29
- const URL_HASH_REF_RE = /(url\(\s*)(["']?)#([^"')\s]+)\2(\s*\))/gi;
30
17
  /**
31
18
  * Attributes carrying a bare `#id` fragment reference rather than a
32
19
  * `url(#id)` funcref — SVG's `<use>`, `<a>`, `<pattern>`, `<textPath>`,
@@ -39,10 +26,17 @@ function isHrefAttrName(name) {
39
26
  function sanitizeNamespaceSegment(value) {
40
27
  return value.replace(/[^a-zA-Z0-9_-]/g, "-");
41
28
  }
29
+ /**
30
+ * Rewrites each `url(#id)` funcref, quoted or bare, in a property value: `clip-path`, `filter`,
31
+ * `mask`, `fill`, `stroke`, markers, `cursor` and `mask-image`, inline or in a `<style>`. CSS
32
+ * spells an id reference this way only in a value; a bare `#id` is a selector. A fragment is a
33
+ * URL, not a CSS identifier, so it carries no escapes; the replacement keeps the quoting and
34
+ * swaps only the id, which stays a valid fragment because the prefix is `[A-Za-z0-9_-]`.
35
+ */
42
36
  function rewriteUrlHashRefs(value, idMap) {
43
37
  if (!value || !value.toLowerCase().includes("url("))
44
38
  return value;
45
- return value.replace(URL_HASH_REF_RE, (full, pre, quote, id, post) => {
39
+ return replaceMatches(value, urlHashRefMatches(value), (full, pre, quote, id, post) => {
46
40
  const mapped = idMap.get(id);
47
41
  return mapped ? `${pre}${quote}#${mapped}${quote}${post}` : full;
48
42
  });
@@ -52,9 +46,7 @@ function nativeReferenceValue(name, value, idMap) {
52
46
  const mapped = idMap.get(value.slice(1));
53
47
  return mapped ? `#${mapped}` : value;
54
48
  }
55
- URL_HASH_REF_RE.lastIndex = 0;
56
- const hasUrl = URL_HASH_REF_RE.test(value);
57
- URL_HASH_REF_RE.lastIndex = 0;
49
+ const hasUrl = !urlHashRefMatches(value).next().done;
58
50
  return hasUrl ? rewriteUrlHashRefs(value, idMap) : null;
59
51
  }
60
52
  function decideReferenceWrite(attr, previous, idMap) {
@@ -105,12 +97,9 @@ function rewriteElementIdReferences(el, idMap) {
105
97
  el.setAttribute(SVG_REFERENCE_ALIASES_ATTR, JSON.stringify(aliases));
106
98
  }
107
99
  function collectUrlHashRefsFromText(text, filter, out) {
108
- let m;
109
- URL_HASH_REF_RE.lastIndex = 0;
110
- while ((m = URL_HASH_REF_RE.exec(text))) {
111
- const refId = m[3];
112
- if (filter.has(refId))
113
- out.add(refId);
100
+ for (const { parts } of urlHashRefMatches(text)) {
101
+ if (filter.has(parts[3]))
102
+ out.add(parts[3]);
114
103
  }
115
104
  }
116
105
  function collectHrefFragmentRef(attr, filter, out) {
@@ -1252,6 +1252,37 @@ function declaredFaceFamily(block) {
1252
1252
  const found = /font-family:\s*['"]([^'"]+)['"]/i.exec(block);
1253
1253
  return found?.[1];
1254
1254
  }
1255
+ function unicodeRangeOf(text) {
1256
+ const points = [...new Set(Array.from(text, (character) => character.codePointAt(0)))].sort((a, b) => a - b);
1257
+ const hex = (point) => point.toString(16).toUpperCase().padStart(4, "0");
1258
+ const ranges = [];
1259
+ for (let start = 0; start < points.length;) {
1260
+ let end = start;
1261
+ while (end + 1 < points.length && points[end + 1] === points[end] + 1)
1262
+ end += 1;
1263
+ ranges.push(start === end ? `U+${hex(points[start])}` : `U+${hex(points[start])}-${hex(points[end])}`);
1264
+ start = end + 1;
1265
+ }
1266
+ return ranges.join(", ");
1267
+ }
1268
+ /**
1269
+ * One request per chunk. Each response holds at most its chunk's glyphs, so with several chunks
1270
+ * every face claims exactly its chunk's codepoints; same-weight faces would otherwise shadow each other.
1271
+ */
1272
+ async function fetchTextChunks(chunks, urlFor, fetchUrl) {
1273
+ const urls = chunks.map(urlFor);
1274
+ if (new Set(urls).size === 1)
1275
+ return fetchUrl(urls[0]);
1276
+ const faces = [];
1277
+ let status;
1278
+ for (const [index, url] of urls.entries()) {
1279
+ const result = await fetchUrl(url);
1280
+ const range = unicodeRangeOf(chunks[index]);
1281
+ faces.push(...result.faces.map((face) => ({ ...face, unicodeRange: range })));
1282
+ status ??= result.status;
1283
+ }
1284
+ return { faces, status };
1285
+ }
1255
1286
  // fallow-ignore-next-line complexity
1256
1287
  async function fetchGoogleFont(familyName, path, options, fontText) {
1257
1288
  // Agents sometimes copy the `family=` value from a Google Fonts URL into
@@ -1261,7 +1292,6 @@ async function fetchGoogleFont(familyName, path, options, fontText) {
1261
1292
  // authored CSS still matches it.
1262
1293
  const googleFamilyName = familyName.replace(/\+/g, " ");
1263
1294
  const encodedFamily = encodeURIComponent(googleFamilyName);
1264
- const textParam = fontText ? `&text=${encodeURIComponent(fontText)}` : "";
1265
1295
  // Bundled families need the full supplement, including italics a page's
1266
1296
  // link may omit. Other families need the authored URL to preserve axes
1267
1297
  // such as optical size instead of replacing them with a weight-only face.
@@ -1271,22 +1301,23 @@ async function fetchGoogleFont(familyName, path, options, fontText) {
1271
1301
  : options.authoredStylesheets.get(normalizedFamily);
1272
1302
  // `text=` asks Google for only the characters on the page. A CJK family
1273
1303
  // without it is a hundred files, and the compile's font budget is 20s.
1274
- const defaultUrl = `https://fonts.googleapis.com/css2?family=${encodedFamily}:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,400;1,700${textParam}`;
1304
+ const defaultUrl = (text) => `https://fonts.googleapis.com/css2?family=${encodedFamily}:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,400;1,700${text ? `&text=${encodeURIComponent(text)}` : ""}`;
1275
1305
  const fetchStylesheet = (url, urlSource) => fetchGoogleFontStylesheet(googleFamilyName, url, options, options.diag.startAttempt(path, urlSource, /[?&]text=/.test(url) ? "present" : "absent"));
1306
+ const fetchPageText = (urlFor, urlSource) => fetchTextChunks(fontText ?? [undefined], urlFor, (url) => fetchStylesheet(url, urlSource));
1276
1307
  if (!authoredStylesheet) {
1277
- return (await fetchStylesheet(defaultUrl, "default")).faces;
1308
+ return (await fetchPageText(defaultUrl, "default")).faces;
1278
1309
  }
1279
1310
  const faces = [];
1280
1311
  const outcomes = [];
1281
1312
  for (const url of authoredStylesheet) {
1282
- const result = await fetchStylesheet(withPageText(url, fontText), "authored");
1313
+ const result = await fetchPageText((text) => withPageText(url, text), "authored");
1283
1314
  faces.push(...result.faces);
1284
1315
  if (result.faces.length === 0)
1285
1316
  outcomes.push(result.status ? `http_${result.status}` : "no_faces");
1286
1317
  }
1287
1318
  if (faces.length > 0)
1288
1319
  return faces;
1289
- const fallback = (await fetchStylesheet(defaultUrl, "default")).faces;
1320
+ const fallback = (await fetchPageText(defaultUrl, "default")).faces;
1290
1321
  options.log.warn(`[Compiler] google_font_link_fallback family="${familyName}" link_outcomes=${outcomes.join(",")} ` +
1291
1322
  `fallback_faces=${fallback.length}`);
1292
1323
  return fallback;
@@ -1384,6 +1415,62 @@ const STDERR_LOGGER = {
1384
1415
  // static text, strings authored in scripts, and CSS case transforms while
1385
1416
  // collapsing repeated prose and base64 assets to a tiny set.
1386
1417
  const GOOGLE_FONTS_TEXT_MAX_ENCODED_LENGTH = 1_700;
1418
+ // One glyph per character, so these may go to any run. Everything else (joining scripts, kerning
1419
+ // pairs, combining marks) stays in the first run, so text that shapes together shares one face.
1420
+ const STANDALONE_CHARACTER_RE = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\uAC00-\uD7A3]$/u;
1421
+ const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: "grapheme" });
1422
+ function encodedLength(text) {
1423
+ return encodeURIComponent(text).length;
1424
+ }
1425
+ /** Characters of every cluster that composes (가+ᆨ, a+◌́, ガ), with each form the browser may draw it with. */
1426
+ function composingCharacters(sources, locales) {
1427
+ const pinned = new Set();
1428
+ for (const text of sources) {
1429
+ for (const { segment } of GRAPHEMES.segment(text)) {
1430
+ const composed = segment.normalize("NFC");
1431
+ if (composed === segment && [...segment].length === 1)
1432
+ continue;
1433
+ for (const character of segment + composed + segment.normalize("NFD")) {
1434
+ addCaseClosure(pinned, character, locales);
1435
+ }
1436
+ }
1437
+ }
1438
+ return pinned;
1439
+ }
1440
+ function packRuns(first, rest) {
1441
+ const runs = [];
1442
+ let run = first;
1443
+ let length = encodedLength(run);
1444
+ for (const character of rest) {
1445
+ const size = encodedLength(character);
1446
+ if (run && length + size > GOOGLE_FONTS_TEXT_MAX_ENCODED_LENGTH) {
1447
+ runs.push(run);
1448
+ run = "";
1449
+ length = 0;
1450
+ }
1451
+ run += character;
1452
+ length += size;
1453
+ }
1454
+ runs.push(run);
1455
+ return runs;
1456
+ }
1457
+ /** Undefined when the characters that must share one face do not fit one request: the whole family, as before. */
1458
+ function pageTextRuns(characters, sources, locales, transformed) {
1459
+ if (characters.length === 0)
1460
+ return undefined;
1461
+ const whole = characters.join("");
1462
+ if (encodedLength(whole) <= GOOGLE_FONTS_TEXT_MAX_ENCODED_LENGTH)
1463
+ return [whole];
1464
+ // A text-transform draws characters the page source does not contain, so no split is safe.
1465
+ if (transformed)
1466
+ return undefined;
1467
+ const pinned = composingCharacters(sources, locales);
1468
+ const isLoose = (character) => STANDALONE_CHARACTER_RE.test(character) && !pinned.has(character);
1469
+ const first = [...new Set([...characters.filter((c) => !isLoose(c)), ...pinned])].join("");
1470
+ if (encodedLength(first) > GOOGLE_FONTS_TEXT_MAX_ENCODED_LENGTH)
1471
+ return undefined;
1472
+ return packRuns(first, characters.filter(isLoose));
1473
+ }
1387
1474
  const SMALL_TO_FULL_KANA = new Map([
1388
1475
  ["ぁ", "あ"],
1389
1476
  ["ぃ", "い"],
@@ -1489,7 +1576,7 @@ function extractGoogleFontsText(html) {
1489
1576
  const decodedBodyText = document.body?.textContent ?? "";
1490
1577
  const locales = collectLangAttributes(document);
1491
1578
  // Intentional over-approximation: raw html includes base64, scripts, and
1492
- // class names, but they collapse in the Set and the budget gate catches bloat.
1579
+ // class names, but they collapse in the Set; text past one request is split by pageTextRuns.
1493
1580
  const uniqueCharacters = new Set();
1494
1581
  const seen = new Set();
1495
1582
  for (const text of [html, decodedBodyText]) {
@@ -1500,14 +1587,13 @@ function extractGoogleFontsText(html) {
1500
1587
  addCaseClosure(uniqueCharacters, character, locales);
1501
1588
  }
1502
1589
  }
1503
- if (hasTextTransformKeyword(html, FULL_WIDTH_KEYWORD_RE))
1590
+ const fullWidth = hasTextTransformKeyword(html, FULL_WIDTH_KEYWORD_RE);
1591
+ const fullSizeKana = hasTextTransformKeyword(html, FULL_SIZE_KANA_KEYWORD_RE);
1592
+ if (fullWidth)
1504
1593
  addFullwidthVariants(uniqueCharacters);
1505
- if (hasTextTransformKeyword(html, FULL_SIZE_KANA_KEYWORD_RE))
1594
+ if (fullSizeKana)
1506
1595
  addFullSizeKanaVariants(uniqueCharacters);
1507
- const fontText = [...uniqueCharacters].join("");
1508
- return encodeURIComponent(fontText).length <= GOOGLE_FONTS_TEXT_MAX_ENCODED_LENGTH
1509
- ? fontText
1510
- : undefined;
1596
+ return pageTextRuns([...uniqueCharacters], [html, decodedBodyText], locales, fullWidth || fullSizeKana);
1511
1597
  }
1512
1598
  function resolveFontFetchRetryPolicy(configured) {
1513
1599
  return {