@hyperframes/core 0.9.65 → 0.9.66

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/canary.d.ts CHANGED
@@ -60,6 +60,21 @@ export interface CanaryInput {
60
60
  */
61
61
  exclude?: boolean | undefined;
62
62
  }
63
+ /**
64
+ * FNV-1a (32-bit). Chosen over `node:crypto` deliberately: this module has to
65
+ * run in the browser-side studio bundle and the embeddable player too, and a
66
+ * six-line hash beats shipping a polyfill or maintaining two code paths.
67
+ * Distribution is uniform enough for bucketing (pinned by a test).
68
+ *
69
+ * ASCII-only by contract. `charCodeAt` yields UTF-16 code units — two
70
+ * surrogate halves for an astral character — whereas reference FNV-1a is
71
+ * byte-oriented, so the two agree only on ASCII. Both inputs are constrained
72
+ * to satisfy that: canary names by the registry's kebab-case assertion in
73
+ * `canary.test.ts`, unit ids by being UUIDs. Widening either means switching
74
+ * to a UTF-8 encoding here first, which is not free in the browser bundle
75
+ * (`TextEncoder` is fine; `Buffer` is not).
76
+ */
77
+ export declare function fnv1a32(input: string): number;
63
78
  /** The 0-99 slot a unit occupies for a given feature. Exported for tests and diagnostics. */
64
79
  export declare function canaryBucket(feature: string, unitId: string): number;
65
80
  /**
package/dist/canary.js CHANGED
@@ -44,7 +44,7 @@
44
44
  * to a UTF-8 encoding here first, which is not free in the browser bundle
45
45
  * (`TextEncoder` is fine; `Buffer` is not).
46
46
  */
47
- function fnv1a32(input) {
47
+ export function fnv1a32(input) {
48
48
  let hash = 0x811c9dc5;
49
49
  for (let i = 0; i < input.length; i++) {
50
50
  hash ^= input.charCodeAt(i);
@@ -89,7 +89,7 @@ function scopeSelectorOnce(selector, scope, compositionId, authoredRootId, compo
89
89
  // sits nested inside the host and would inherit the effect twice.
90
90
  return compositionBoxSelector(scope);
91
91
  }
92
- return selectorWithoutRootTiming.replace(compositionIdPattern, scope);
92
+ return selectorWithoutRootTiming.replace(compositionIdPattern, () => scope);
93
93
  }
94
94
  const leading = selectorWithoutRootTiming.match(/^\s*/)?.[0] ?? "";
95
95
  const trailing = selectorWithoutRootTiming.match(/\s*$/)?.[0] ?? "";
@@ -109,8 +109,8 @@ function normalizeCompositionRootSelector(selector, scope, compositionId) {
109
109
  const compAttr = String.raw `\[\s*data-composition-id\s*=\s*(?:"${quotedCompId}"|'${quotedCompId}')\s*\]`;
110
110
  const timingAttr = String.raw `\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`;
111
111
  return selector
112
- .replace(new RegExp(`${compAttr}(?:${timingAttr})+`, "g"), scope)
113
- .replace(new RegExp(`(?:${timingAttr})+${compAttr}`, "g"), scope);
112
+ .replace(new RegExp(`${compAttr}(?:${timingAttr})+`, "g"), () => scope)
113
+ .replace(new RegExp(`(?:${timingAttr})+${compAttr}`, "g"), () => scope);
114
114
  }
115
115
  const GLOBAL_AT_RULES = new Set(["keyframes", "-webkit-keyframes", "font-face"]);
116
116
  function isAtRuleNode(node) {
@@ -386,14 +386,15 @@ export function wrapScopedCompositionScript(source, compositionId, errorLabel =
386
386
  var __hfAuthoredRootEntries = __hfAuthoredRootSelector
387
387
  ? [{ id: __hfAuthoredRootId, replacement: __hfAuthoredRootSelector }]
388
388
  : [];
389
+ var __hfRootSelectorText = function() { return __hfRootSelector; };
389
390
  var __hfNormalizeSelector = function(selector) {
390
391
  if (!__hfCompId || typeof selector !== "string") return selector;
391
392
  var normalized = selector
392
- .replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelector)
393
- .replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelector)
394
- .replace(new RegExp(__hfRootSelectorPattern, 'g'), __hfRootSelector);
393
+ .replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelectorText)
394
+ .replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelectorText)
395
+ .replace(new RegExp(__hfRootSelectorPattern, 'g'), __hfRootSelectorText);
395
396
  if (__hfTimelineCompId !== __hfCompId) {
396
- normalized = normalized.replace(new RegExp(__hfTimelineRootSelectorPattern, 'g'), __hfRootSelector);
397
+ normalized = normalized.replace(new RegExp(__hfTimelineRootSelectorPattern, 'g'), __hfRootSelectorText);
397
398
  }
398
399
  return window.__hfSvgSelectorAliases.rewrite(normalized, __hfAuthoredRootEntries);
399
400
  };
@@ -80,4 +80,8 @@ export declare function bundleToSingleHtml(projectDir: string, options?: BundleO
80
80
  * through the shared module rather than this bundler.
81
81
  * Returns whether a style element was appended.
82
82
  */
83
- export declare function emitRootCompositionVariableStyles(document: Document, variablesByComp?: Record<string, Record<string, unknown>>, overrides?: Record<string, unknown>): boolean;
83
+ export declare function emitRootCompositionVariableStyles(document: Document, variablesByComp?: Record<string, Record<string, unknown>>, overrides?: Record<string, unknown>, options?: {
84
+ chargeBytes?: (bytes: number) => void;
85
+ }): boolean;
86
+ /** The most CSS the compile-time composition-variable rules may add up to when the caller sets no budget of its own. */
87
+ export declare const MAX_COMPOSITION_VARIABLE_STYLE_BYTES: number;
@@ -1310,13 +1310,14 @@ function compositionVariablesCssBlock(variables, selector) {
1310
1310
  * through the shared module rather than this bundler.
1311
1311
  * Returns whether a style element was appended.
1312
1312
  */
1313
- export function emitRootCompositionVariableStyles(document, variablesByComp = {}, overrides = {}) {
1313
+ export function emitRootCompositionVariableStyles(document, variablesByComp = {}, overrides = {}, options = {}) {
1314
+ const charge = options.chargeBytes ?? defaultVariableStyleCharge();
1314
1315
  const authoredDefines = authoredDefinesPredicate(document);
1315
1316
  const layerFor = makeVariableLayer(authoredDefines, overrides);
1316
1317
  const rules = [
1317
- ...hostScopedVariableRules(variablesByComp, overrides, authoredDefines),
1318
- ...rootDeclaredVariableRules(document, layerFor),
1319
- ...declarerVariableRules(document, layerFor),
1318
+ ...hostScopedVariableRules(variablesByComp, overrides, authoredDefines, charge),
1319
+ ...rootDeclaredVariableRules(document, layerFor, charge),
1320
+ ...declarerVariableRules(document, layerFor, charge),
1320
1321
  ];
1321
1322
  if (rules.length === 0)
1322
1323
  return false;
@@ -1326,6 +1327,26 @@ export function emitRootCompositionVariableStyles(document, variablesByComp = {}
1326
1327
  document.head.appendChild(style);
1327
1328
  return true;
1328
1329
  }
1330
+ /** The most CSS the compile-time composition-variable rules may add up to when the caller sets no budget of its own. */
1331
+ export const MAX_COMPOSITION_VARIABLE_STYLE_BYTES = 32 * 1024 * 1024;
1332
+ class CompositionVariableStylesTooLargeError extends Error {
1333
+ code = "COMPOSITION_TOO_LARGE";
1334
+ constructor(bytes) {
1335
+ super(`Composition variable styles add up to ${(bytes / (1024 * 1024)).toFixed(1)} MB, over the ` +
1336
+ `${MAX_COMPOSITION_VARIABLE_STYLE_BYTES / (1024 * 1024)} MB limit. Shorten the variable ` +
1337
+ "values or declare them on fewer elements.");
1338
+ this.name = "CompositionVariableStylesTooLargeError";
1339
+ }
1340
+ }
1341
+ function defaultVariableStyleCharge() {
1342
+ let total = 0;
1343
+ return (bytes) => {
1344
+ total += bytes;
1345
+ if (total > MAX_COMPOSITION_VARIABLE_STYLE_BYTES) {
1346
+ throw new CompositionVariableStylesTooLargeError(total);
1347
+ }
1348
+ };
1349
+ }
1329
1350
  function authoredDefinesPredicate(document) {
1330
1351
  const authoredCss = [...document.querySelectorAll("style:not([data-hf-composition-variables])")]
1331
1352
  .map((s) => s.textContent || "")
@@ -1379,7 +1400,7 @@ function makeVariableLayer(authoredDefines, overrides) {
1379
1400
  * another part of the document. Render-time --variables overrides remain
1380
1401
  * explicit user intent and always win.
1381
1402
  */
1382
- function hostScopedVariableRules(variablesByComp, overrides, authoredDefines) {
1403
+ function hostScopedVariableRules(variablesByComp, overrides, authoredDefines, charge) {
1383
1404
  const rules = [];
1384
1405
  for (const [compId, vars] of Object.entries(variablesByComp)) {
1385
1406
  const withOverrides = {};
@@ -1392,15 +1413,20 @@ function hostScopedVariableRules(variablesByComp, overrides, authoredDefines) {
1392
1413
  withOverrides[id] = value;
1393
1414
  }
1394
1415
  const rule = compositionVariablesCssBlock(withOverrides, cssAttributeSelector("data-composition-id", compId));
1395
- if (rule)
1396
- rules.push(rule);
1416
+ if (!rule)
1417
+ continue;
1418
+ charge(rule.length);
1419
+ rules.push(rule);
1397
1420
  }
1398
1421
  return rules;
1399
1422
  }
1400
- function rootDeclaredVariableRules(document, layerFor) {
1423
+ function rootDeclaredVariableRules(document, layerFor, charge) {
1401
1424
  const htmlDeclared = readDeclaredDefaults(document.documentElement);
1402
1425
  const htmlRule = compositionVariablesCssBlock(layerFor(htmlDeclared, {}), ":root");
1403
- return htmlRule ? [htmlRule] : [];
1426
+ if (!htmlRule)
1427
+ return [];
1428
+ charge(htmlRule.length);
1429
+ return [htmlRule];
1404
1430
  }
1405
1431
  /**
1406
1432
  * Declarer rules anchor on a per-instance marker attribute, not the
@@ -1409,21 +1435,30 @@ function rootDeclaredVariableRules(document, layerFor) {
1409
1435
  * restyle instance B. The nearest ancestor host's data-variable-values
1410
1436
  * layer over the declared defaults (mirrors the runtime loader).
1411
1437
  */
1412
- function declarerVariableRules(document, layerFor) {
1438
+ function declarerVariableRules(document, layerFor, charge) {
1413
1439
  const rules = [];
1440
+ const hostValuesByEl = new Map();
1414
1441
  let markerSeq = 0;
1415
1442
  for (const el of [...document.querySelectorAll("[data-composition-variables]")]) {
1416
1443
  const declared = readDeclaredDefaults(el);
1417
1444
  const hostEl = typeof el.closest === "function" ? el.parentElement?.closest("[data-variable-values]") : null;
1418
- const hostValues = hostEl ? parseHostVariableValues(hostEl) : {};
1445
+ let hostValues = {};
1446
+ if (hostEl) {
1447
+ const cached = hostValuesByEl.get(hostEl);
1448
+ hostValues = cached ?? parseHostVariableValues(hostEl);
1449
+ if (!cached)
1450
+ hostValuesByEl.set(hostEl, hostValues);
1451
+ }
1419
1452
  const vars = layerFor(declared, hostValues);
1420
1453
  if (Object.keys(vars).length === 0)
1421
1454
  continue;
1422
1455
  markerSeq += 1;
1423
1456
  el.setAttribute("data-hf-var-scope", String(markerSeq));
1424
1457
  const rule = compositionVariablesCssBlock(vars, `[data-hf-var-scope="${markerSeq}"]`);
1425
- if (rule)
1426
- rules.push(rule);
1458
+ if (!rule)
1459
+ continue;
1460
+ charge(rule.length);
1461
+ rules.push(rule);
1427
1462
  }
1428
1463
  return rules;
1429
1464
  }
@@ -1,7 +1,7 @@
1
1
  export { resolveTimings, type WordTiming, type ElementAnchor, type AuthoredTiming, type ResolvedTiming, type ResolveTimingsInput, type ResolveTimingsResult, } from "./timingResolver.js";
2
2
  export { compileTimingAttrs, injectDurations, extractResolvedMedia, clampDurations, shouldClampMediaDuration, shouldClampResolvedMediaDuration, type UnresolvedElement, type ResolvedDuration, type ResolvedMediaElement, type CompilationResult, } from "./timingCompiler.js";
3
3
  export { compileHtml, type MediaDurationProber } from "./htmlCompiler.js";
4
- export { assignBundledRuntimeCompositionIds, type BundledHostCompositionIdentity, bundleToSingleHtml, type BundleOptions, type BundlePrivateFiles, type BundleScriptProvenance, prepareFlattenedInnerRoot, FLATTENED_INNER_ROOT_STRIP_ATTRS, emitRootCompositionVariableStyles, parsesAsScript, } from "./htmlBundler.js";
4
+ export { assignBundledRuntimeCompositionIds, type BundledHostCompositionIdentity, bundleToSingleHtml, type BundleOptions, type BundlePrivateFiles, type BundleScriptProvenance, prepareFlattenedInnerRoot, FLATTENED_INNER_ROOT_STRIP_ATTRS, emitRootCompositionVariableStyles, MAX_COMPOSITION_VARIABLE_STYLE_BYTES, parsesAsScript, } from "./htmlBundler.js";
5
5
  export { readDeclaredDefaults, parseHostVariableValues } from "../runtime/getVariables.js";
6
6
  export { boundMediaSrc } from "../runtime/applyVariableBindings.js";
7
7
  export { extractCompiledHtmlParityContract, type CompiledHtmlParityContract, type HtmlParityComposition, type HtmlParityResource, type HtmlParityTimedElement, } from "./htmlParityContract.js";
@@ -6,7 +6,7 @@ export { compileTimingAttrs, injectDurations, extractResolvedMedia, clampDuratio
6
6
  // HTML compiler (Node.js — requires fs)
7
7
  export { compileHtml } from "./htmlCompiler.js";
8
8
  // HTML bundler (Node.js — requires fs, linkedom, esbuild)
9
- export { assignBundledRuntimeCompositionIds, bundleToSingleHtml, prepareFlattenedInnerRoot, FLATTENED_INNER_ROOT_STRIP_ATTRS, emitRootCompositionVariableStyles, parsesAsScript, } from "./htmlBundler.js";
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 { boundMediaSrc } from "../runtime/applyVariableBindings.js";
12
12
  export { extractCompiledHtmlParityContract, } from "./htmlParityContract.js";
@@ -20,6 +20,8 @@ export interface InlineSubCompositionsOptions {
20
20
  * Return `null` when the file cannot be found.
21
21
  */
22
22
  resolveHtml: (srcPath: string) => string | null;
23
+ /** The project-relative file `resolveHtml` read for a src; asset paths rebase from its folder. */
24
+ resolveFilePath?: (srcPath: string) => string | null;
23
25
  /**
24
26
  * Parse an HTML string into a Document. The returned object must expose
25
27
  * standard DOM APIs (querySelector, querySelectorAll, body, head, etc.).
@@ -195,7 +195,7 @@ function defaultBuildScopeSelector(compId) {
195
195
  */
196
196
  // fallow-ignore-next-line complexity
197
197
  export function inlineSubCompositions(document, hosts, options) {
198
- const { resolveHtml, parseHtml, hostIdentityMap, rewriteInlineStyles = false, flattenInnerRoot, compoundAuthoredRoot, readVariableDefaults, parseHostVariables, buildScopeSelector = defaultBuildScopeSelector, scriptErrorLabel = "[HyperFrames] composition script error:", onMissingComposition, assetExists, tagScenes = false, readProjectScript, chargeEmitted, } = options;
198
+ const { resolveHtml, resolveFilePath, parseHtml, hostIdentityMap, rewriteInlineStyles = false, flattenInnerRoot, compoundAuthoredRoot, readVariableDefaults, parseHostVariables, buildScopeSelector = defaultBuildScopeSelector, scriptErrorLabel = "[HyperFrames] composition script error:", onMissingComposition, assetExists, tagScenes = false, readProjectScript, chargeEmitted, } = options;
199
199
  const rootStyles = [...document.querySelectorAll("style")];
200
200
  const styles = [];
201
201
  const styleScenes = [];
@@ -347,10 +347,12 @@ export function inlineSubCompositions(document, hosts, options) {
347
347
  warnUnknownEnumValues(compDoc.documentElement, mergedVariables, variablesCompId);
348
348
  warnUnknownEnumValues(innerRoot, mergedVariables, variablesCompId);
349
349
  }
350
+ const filePath = resolveFilePath?.(src) ?? src;
351
+ const chargeRebase = chargeEmitted && ((bytes) => chargeEmitted(src, bytes));
350
352
  // `<head>` <link>/<script src> are hoisted into the ROOT document, so they
351
353
  // need the same directory rewrite the body's [src]/[href] pass applies —
352
354
  // without it even the documented `../` form escapes the project and 404s.
353
- const resolveSubAssetPath = (raw) => rewriteAssetPath(src, (raw || "").trim(), assetExists);
355
+ const resolveSubAssetPath = (raw) => rewriteAssetPath(filePath, (raw || "").trim(), assetExists, chargeRebase);
354
356
  // Scope one sub-composition <style> body. scopeRootSelectors keeps the
355
357
  // sub-comp's html/body/:root rules from clobbering the host document (they
356
358
  // are remapped to the composition box); see compositionScoping.
@@ -358,7 +360,7 @@ export function inlineSubCompositions(document, hosts, options) {
358
360
  const sheetKey = JSON.stringify([src, raw]);
359
361
  let css = sheetsWithAssetUrls.get(sheetKey);
360
362
  if (css === undefined) {
361
- css = rewriteCssAssetUrls(raw, src, assetExists);
363
+ css = rewriteCssAssetUrls(raw, filePath, assetExists, chargeRebase);
362
364
  sheetsWithAssetUrls.set(sheetKey, css);
363
365
  }
364
366
  if (!scopeCompId) {
@@ -465,16 +467,16 @@ export function inlineSubCompositions(document, hosts, options) {
465
467
  const assetEls = innerRoot
466
468
  ? innerRoot.querySelectorAll("[src], [href], [srcset]")
467
469
  : contentDoc.querySelectorAll("[src], [href], [srcset]");
468
- rewriteAssetPaths(assetEls, src, (el, attr) => el.getAttribute(attr), (el, attr, val) => {
470
+ rewriteAssetPaths(assetEls, filePath, (el, attr) => el.getAttribute(attr), (el, attr, val) => {
469
471
  el.setAttribute(attr, val);
470
- }, assetExists);
472
+ }, assetExists, chargeRebase);
471
473
  if (rewriteInlineStyles) {
472
474
  const styledEls = innerRoot
473
475
  ? innerRoot.querySelectorAll("[style]")
474
476
  : contentDoc.querySelectorAll("[style]");
475
- rewriteInlineStyleAssetUrls(styledEls, src, (el) => el.getAttribute("style"), (el, val) => {
477
+ rewriteInlineStyleAssetUrls(styledEls, filePath, (el) => el.getAttribute("style"), (el, val) => {
476
478
  el.setAttribute("style", val);
477
- }, assetExists);
479
+ }, assetExists, chargeRebase);
478
480
  }
479
481
  if (innerRoot?.hasAttribute("data-timeline-locked")) {
480
482
  hostEl.setAttribute("data-timeline-locked", "");
@@ -548,6 +550,7 @@ export function inlineSubCompositions(document, hosts, options) {
548
550
  // scoping and script scoping already key on. Nested hosts are excluded
549
551
  // because each of them is recorded as its own scope when dequeued.
550
552
  svgIdScopes.push({
553
+ src,
551
554
  root: hostEl,
552
555
  namespace: runtimeCompId || scopeCompId,
553
556
  exclude: nested.hosts.map((nestedHost) => nestedHost.host),
@@ -584,17 +587,27 @@ export function inlineSubCompositions(document, hosts, options) {
584
587
  namespace: `clip-${index}`,
585
588
  exclude: hostRoots.filter((host) => root.contains(host)),
586
589
  })),
587
- ]);
590
+ ], undefined, chargeEmitted &&
591
+ ((index, bytes) => chargeEmitted(svgIdScopes[index]?.src ?? "the page", bytes)));
592
+ const chargeGrowth = (src, before, after) => {
593
+ if (after.length > before.length)
594
+ chargeEmitted?.(src, after.length - before.length);
595
+ };
588
596
  svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
589
597
  const { styleStart, styleEnd } = svgIdScopes[index];
590
598
  const references = readSvgReferenceAliases(svgIdScopes[index].root, SVG_REFERENCE_ALIASES_ATTR);
591
599
  for (let i = styleStart; i < styleEnd; i += 1) {
592
- styles[i].css = rewriteSvgIdReferencesInCss(styles[i].css, idMap, references);
600
+ const rewritten = rewriteSvgIdReferencesInCss(styles[i].css, idMap, references);
601
+ chargeGrowth(svgIdScopes[index].src, styles[i].css, rewritten);
602
+ styles[i].css = rewritten;
593
603
  }
594
604
  });
595
605
  const rootReferences = readSvgReferenceAliases(document.documentElement, SVG_REFERENCE_ALIASES_ATTR);
596
606
  for (const style of rootStyles) {
597
- style.textContent = rewriteSvgIdReferencesInCss(style.textContent ?? "", svgIdMaps[svgIdScopes.length], rootReferences);
607
+ const css = style.textContent ?? "";
608
+ const rewritten = rewriteSvgIdReferencesInCss(css, svgIdMaps[svgIdScopes.length], rootReferences);
609
+ chargeGrowth("the page", css, rewritten);
610
+ style.textContent = rewritten;
598
611
  }
599
612
  return {
600
613
  styles,
@@ -48,6 +48,8 @@ export declare function escapeCssIdentifier(value: string): string;
48
48
  * full replacement text (including its own leading `#`, if any) to splice
49
49
  * in.
50
50
  */
51
+ /** The `#id` values a selector names, read as `replaceSelectorIdTokens` reads them. */
52
+ export declare function selectorIdTokens(selector: string): string[];
51
53
  export declare function replaceSelectorIdTokens(selector: string, candidateIds: readonly string[], resolveReplacement: (matchedId: string) => string): string;
52
54
  export declare function escapeCssAttributeValue(value: string): string;
53
55
  type AttributeNamespace = {
@@ -193,6 +193,23 @@ function markUnguardedOffsets(selector) {
193
193
  * full replacement text (including its own leading `#`, if any) to splice
194
194
  * in.
195
195
  */
196
+ /** The `#id` values a selector names, read as `replaceSelectorIdTokens` reads them. */
197
+ export function selectorIdTokens(selector) {
198
+ const ids = [];
199
+ if (!selector.includes("#"))
200
+ return ids;
201
+ const unguarded = markUnguardedOffsets(selector);
202
+ for (let index = 0; index < selector.length; index += 1) {
203
+ if (!unguarded[index] || selector[index] !== "#")
204
+ continue;
205
+ const token = decodeCssIdentifierAt(selector, index + 1);
206
+ if (!token)
207
+ continue;
208
+ ids.push(token.value);
209
+ index = token.end - 1;
210
+ }
211
+ return ids;
212
+ }
196
213
  export function replaceSelectorIdTokens(selector, candidateIds, resolveReplacement) {
197
214
  if (candidateIds.length === 0 || !selector.includes("#"))
198
215
  return selector;
@@ -45,6 +45,8 @@ export interface SvgIdScope {
45
45
  */
46
46
  cssTexts?: readonly string[];
47
47
  }
48
+ /** What reads a scope's renames: a plain `Map`, or a `ScopedIdMap`. */
49
+ export type SvgIdMap = Pick<ReadonlyMap<string, string>, "get" | "has" | "size">;
48
50
  /** The outermost timed clips holding an `<svg>` outside every composition host. Each is its own id scope, as an
49
51
  * inlined composition is, so two scenes drawn with the same ids each resolve their own `url(#id)` and `href`. */
50
52
  export declare function sceneClipRoots(document: SvgIdQueryable, hosts: readonly Element[]): Element[];
@@ -65,7 +67,7 @@ export declare function sceneClipRoots(document: SvgIdQueryable, hosts: readonly
65
67
  * document declares itself, since those collide with an inlined instance's
66
68
  * ids just as two instances collide with each other.
67
69
  */
68
- export declare function namespaceCollidingSvgIds(document: SvgIdQueryable, scopes: readonly SvgIdScope[], finalizedIds?: Set<Element>): Map<string, string>[];
70
+ export declare function namespaceCollidingSvgIds(document: SvgIdQueryable, scopes: readonly SvgIdScope[], finalizedIds?: Set<Element>, charge?: (scopeIndex: number, bytes: number) => void): SvgIdMap[];
69
71
  /**
70
72
  * Apply the same id substitution `namespaceCollidingSvgIds` computed to a
71
73
  * composition's `<style>` text.
@@ -79,5 +81,5 @@ export declare function namespaceCollidingSvgIds(document: SvgIdQueryable, scope
79
81
  * same-composition stylesheet rule silently stops matching the element whose
80
82
  * id this module just changed.
81
83
  */
82
- export declare function rewriteSvgIdReferencesInCss(css: string, idMap: ReadonlyMap<string, string>, references?: readonly SvgReferenceAlias[]): string;
84
+ export declare function rewriteSvgIdReferencesInCss(css: string, idMap: SvgIdMap, references?: readonly SvgReferenceAlias[]): string;
83
85
  export {};
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import { replaceMatches, urlHashRefMatches } from "@hyperframes/parsers/css-url-scans";
9
9
  import postcss from "postcss";
10
- import { escapeCssIdentifier } from "./selectorIdTokens.js";
10
+ import { fnv1a32 } from "../canary.js";
11
+ import { escapeCssIdentifier, selectorIdTokens } from "./selectorIdTokens.js";
11
12
  import { SVG_REFERENCE_ALIASES_ATTR, readSvgReferenceAliases, rewriteSvgSelectors, } from "./svgSelectorAliases.js";
12
13
  const ID_ATTR = "id";
13
14
  /** Reused from `compositionScoping.ts`'s `AUTHORED_ROOT_ID_ATTR` in spirit —
@@ -23,8 +24,13 @@ export const SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";
23
24
  function isHrefAttrName(name) {
24
25
  return name === "href" || name.endsWith(":href");
25
26
  }
27
+ const MAX_NAMESPACE_PREFIX = 48;
28
+ /** A namespace this long keeps its head and a hash of the whole, so a renamed id's length never depends on it. */
26
29
  function sanitizeNamespaceSegment(value) {
27
- return value.replace(/[^a-zA-Z0-9_-]/g, "-");
30
+ const segment = value.replace(/[^a-zA-Z0-9_-]/g, "-");
31
+ if (segment.length <= MAX_NAMESPACE_PREFIX)
32
+ return segment;
33
+ return `${segment.slice(0, 32)}-${fnv1a32(value).toString(16).padStart(8, "0")}`;
28
34
  }
29
35
  /**
30
36
  * Rewrites each `url(#id)` funcref, quoted or bare, in a property value: `clip-path`, `filter`,
@@ -218,8 +224,8 @@ function buildIdCensus(document) {
218
224
  return { elementsById, usedIds };
219
225
  }
220
226
  /** A namespaced id that is not already taken anywhere in the document. */
221
- function mintNamespacedId(namespace, originalId, usedIds) {
222
- const base = `${sanitizeNamespaceSegment(namespace)}--${originalId}`;
227
+ function mintNamespacedId(prefix, originalId, usedIds) {
228
+ const base = `${prefix}--${originalId}`;
223
229
  let candidate = base;
224
230
  for (let n = 2; usedIds.has(candidate); n += 1)
225
231
  candidate = `${base}-${n}`;
@@ -240,11 +246,13 @@ function collisionScopes(id, elements, scopeIndexByRenamable) {
240
246
  */
241
247
  function planRenames(census, scopes, scopeIndexByRenamable) {
242
248
  const idMaps = scopes.map(() => new Map());
249
+ const prefixes = [];
243
250
  for (const [id, elements] of census.elementsById) {
244
251
  if (elements.length < 2)
245
252
  continue;
246
253
  for (const index of collisionScopes(id, elements, scopeIndexByRenamable)) {
247
- idMaps[index].set(id, mintNamespacedId(scopes[index].namespace, id, census.usedIds));
254
+ prefixes[index] ??= sanitizeNamespaceSegment(scopes[index].namespace);
255
+ idMaps[index].set(id, mintNamespacedId(prefixes[index], id, census.usedIds));
248
256
  }
249
257
  }
250
258
  return idMaps;
@@ -278,10 +286,39 @@ function localReferenceBindings(elements) {
278
286
  }
279
287
  return { ids, renamed };
280
288
  }
289
+ /** One scope's renames read through to the document's shared table, never copied per scope. */
290
+ class ScopedIdMap {
291
+ own;
292
+ shared;
293
+ hidden;
294
+ constructor(own, shared, hidden) {
295
+ this.own = own;
296
+ this.shared = shared;
297
+ this.hidden = hidden;
298
+ }
299
+ get(id) {
300
+ return this.own.get(id) ?? (this.hidden.has(id) ? undefined : this.shared.get(id));
301
+ }
302
+ has(id) {
303
+ return this.get(id) !== undefined;
304
+ }
305
+ get size() {
306
+ let size = this.own.size + this.shared.size;
307
+ for (const id of this.own.keys())
308
+ if (this.shared.has(id))
309
+ size -= 1;
310
+ for (const id of this.hidden)
311
+ if (id !== null && !this.own.has(id) && this.shared.has(id))
312
+ size -= 1;
313
+ return size;
314
+ }
315
+ }
316
+ const attributeBytes = (el) => Array.from(el.attributes ?? [], (attr) => attr.name.length + attr.value.length + 4).reduce((sum, bytes) => sum + bytes, 0);
281
317
  /** Rename the planned elements in one scope and rewrite every reference in
282
- * that scope's attributes to match. */
283
- function applyRenames(resolved, idMap) {
318
+ * that scope's attributes to match. `charge` gets each element's added bytes. */
319
+ function applyRenames(resolved, idMap, charge) {
284
320
  for (const el of resolved.elements) {
321
+ const before = charge ? attributeBytes(el) : 0;
285
322
  const currentId = el.getAttribute(ID_ATTR);
286
323
  if (currentId && resolved.renamable.has(el) && idMap.has(currentId)) {
287
324
  if (!el.hasAttribute(SVG_AUTHORED_ID_ATTR))
@@ -299,6 +336,8 @@ function applyRenames(resolved, idMap) {
299
336
  el.setAttribute(ID_ATTR, after);
300
337
  }
301
338
  rewriteElementIdReferences(el, idMap);
339
+ if (charge)
340
+ charge(attributeBytes(el) - before);
302
341
  }
303
342
  }
304
343
  const CLIP_SELECTOR = "[data-start]:not([data-composition-id]):not([data-composition-src])";
@@ -327,7 +366,7 @@ export function sceneClipRoots(document, hosts) {
327
366
  * document declares itself, since those collide with an inlined instance's
328
367
  * ids just as two instances collide with each other.
329
368
  */
330
- export function namespaceCollidingSvgIds(document, scopes, finalizedIds) {
369
+ export function namespaceCollidingSvgIds(document, scopes, finalizedIds, charge) {
331
370
  if (scopes.length === 0)
332
371
  return [];
333
372
  const census = buildIdCensus(document);
@@ -349,11 +388,10 @@ export function namespaceCollidingSvgIds(document, scopes, finalizedIds) {
349
388
  const documentTargets = documentReferenceTargets(census, idMaps, scopeIndexByRenamable);
350
389
  const referenceMaps = resolved.map((scope, index) => {
351
390
  const local = localReferenceBindings(scopes[index].referenceTarget === "document" ? [] : scope.elements);
352
- const inherited = [...documentTargets].filter(([id]) => !local.ids.has(id));
353
- return new Map([...inherited, ...local.renamed, ...idMaps[index]]);
391
+ return new ScopedIdMap(new Map([...local.renamed, ...idMaps[index]]), documentTargets, local.ids);
354
392
  });
355
393
  referenceMaps.forEach((idMap, index) => {
356
- applyRenames(resolved[index], idMap);
394
+ applyRenames(resolved[index], idMap, charge && ((bytes) => charge(index, bytes)));
357
395
  });
358
396
  for (const el of newlyEligible)
359
397
  finalizedIds?.add(el);
@@ -388,14 +426,16 @@ export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
388
426
  }
389
427
  let mutated = false;
390
428
  const recordedIds = new Set(references.filter((alias) => alias.name === ID_ATTR).map((alias) => alias.before));
391
- const ids = [...idMap]
392
- .filter(([id]) => !recordedIds.has(id))
393
- .map(([id, renamed]) => ({
394
- id,
395
- replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})`,
396
- }));
429
+ const idsNamedBy = (selector) => selectorIdTokens(selector).flatMap((id) => {
430
+ const renamed = recordedIds.has(id) ? undefined : idMap.get(id);
431
+ if (!renamed)
432
+ return [];
433
+ return [
434
+ { id, replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})` },
435
+ ];
436
+ });
397
437
  root.walkRules((rule) => {
398
- const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, ids, references));
438
+ const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, idsNamedBy(selector), references));
399
439
  if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
400
440
  rule.selectors = rewritten;
401
441
  mutated = true;
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { join } from "node:path";
10
10
  import { replaceFileAtomically } from "../atomicFile.js";
11
+ import { terminalText } from "../terminalText.js";
11
12
  import { readJsonlValues } from "./jsonl.js";
12
13
  import { manifestPath, mediaDir, ownMediaDir } from "./manifest.js";
13
14
  function isRow(value) {
@@ -16,8 +17,9 @@ function isRow(value) {
16
17
  export function indexPath(projectDir) {
17
18
  return join(mediaDir(projectDir), "index.md");
18
19
  }
20
+ const LINE_BREAKS = /\s*[\r\n\v\f\u0085\u2028\u2029]+\s*/g;
19
21
  function singleLineCell(value) {
20
- return String(value ?? "").replace(/\s*[\r\n]+\s*/g, " ");
22
+ return terminalText(String(value ?? "").replace(LINE_BREAKS, " "));
21
23
  }
22
24
  function pad(str, len) {
23
25
  return singleLineCell(str).padEnd(len);