@hyperframes/core 0.9.64 → 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.
Files changed (39) hide show
  1. package/dist/canary.d.ts +15 -0
  2. package/dist/canary.js +1 -1
  3. package/dist/compiler/compositionScoping.d.ts +2 -0
  4. package/dist/compiler/compositionScoping.js +44 -14
  5. package/dist/compiler/htmlBundler.d.ts +5 -1
  6. package/dist/compiler/htmlBundler.js +48 -13
  7. package/dist/compiler/index.d.ts +1 -1
  8. package/dist/compiler/index.js +1 -1
  9. package/dist/compiler/inlineSubCompositions.d.ts +7 -0
  10. package/dist/compiler/inlineSubCompositions.js +36 -17
  11. package/dist/compiler/selectorIdTokens.d.ts +2 -0
  12. package/dist/compiler/selectorIdTokens.js +17 -0
  13. package/dist/compiler/svgIdNamespacing.d.ts +4 -2
  14. package/dist/compiler/svgIdNamespacing.js +58 -18
  15. package/dist/figma/bindings.js +7 -6
  16. package/dist/figma/index.d.ts +2 -1
  17. package/dist/figma/index.js +2 -1
  18. package/dist/figma/manifest.d.ts +2 -0
  19. package/dist/figma/manifest.js +13 -4
  20. package/dist/figma/mediaIndex.d.ts +2 -3
  21. package/dist/figma/mediaIndex.js +17 -17
  22. package/dist/figma/projectFiles.d.ts +16 -0
  23. package/dist/figma/projectFiles.js +81 -0
  24. package/dist/generated/runtime-inline.js +1 -1
  25. package/dist/generated/svg-selector-aliases-inline.js +1 -1
  26. package/dist/hyperframe.runtime.iife.js +72 -71
  27. package/dist/runtime/editing/editElement.d.ts +18 -0
  28. package/dist/runtime/editing/editElement.js +72 -0
  29. package/dist/runtime/editing/gsapSnapshot.d.ts +43 -0
  30. package/dist/runtime/editing/gsapSnapshot.js +169 -0
  31. package/dist/runtime/editing/gsapSnapshotLimits.d.ts +6 -0
  32. package/dist/runtime/editing/gsapSnapshotLimits.js +6 -0
  33. package/dist/runtime/editing/motionPathHome.d.ts +19 -0
  34. package/dist/runtime/editing/motionPathHome.js +85 -0
  35. package/dist/runtime/editingHandles.js +34 -10
  36. package/dist/runtime/editingPort.d.ts +36 -1
  37. package/dist/runtime/editingPort.js +20 -1
  38. package/dist/safePath.js +3 -1
  39. package/package.json +4 -4
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);
@@ -1,6 +1,8 @@
1
1
  type ScopeOptions = {
2
2
  compoundAuthoredRoot?: boolean;
3
3
  scopeRootSelectors?: boolean;
4
+ /** Told the sheet's size, an upper bound for each rule before it is scoped, then the correction. */
5
+ charge?: (bytes: number) => void;
4
6
  };
5
7
  export declare function scopeCssToComposition(css: string, compositionId: string, scopeSelectorOverride?: string, authoredRootId?: string | null, options?: ScopeOptions): string;
6
8
  /** `scopeCssToComposition` for sheets mounted many times: each sheet is scoped once around a
@@ -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) {
@@ -151,7 +151,21 @@ export function scopeCssToComposition(css, compositionId, scopeSelectorOverride,
151
151
  const scope = scopeSelectorOverride ||
152
152
  `[data-composition-id="${escapeCssAttributeValue(trimmedCompositionId)}"]`;
153
153
  const root = parseCss(css);
154
- return root ? scopeParsedCss(root, scope, trimmedCompositionId, authoredRootId, options) : "";
154
+ return root
155
+ ? scopeParsedCss(root, css.length, scope, trimmedCompositionId, authoredRootId, options)
156
+ : "";
157
+ }
158
+ /** Up to two forms per selector, each with the scope per id mention plus twice, and an attribute per `#`. */
159
+ function scopedSelectorsBound(selectors, scope, authoredRootId) {
160
+ const authoredAttribute = 26 + 2 * (authoredRootId?.trim().length ?? 0);
161
+ let bound = 0;
162
+ for (const selector of selectors) {
163
+ const mentions = selector.split("data-composition-id").length - 1;
164
+ const hashes = selector.split("#").length - 1;
165
+ const form = selector.length + hashes * authoredAttribute + (mentions + 2) * scope.length + 64;
166
+ bound += 2 * form + 2;
167
+ }
168
+ return bound;
155
169
  }
156
170
  function parseCss(css) {
157
171
  try {
@@ -170,9 +184,20 @@ function forEachScopedRule(root, visit) {
170
184
  visit(rule);
171
185
  });
172
186
  }
173
- function scopeParsedCss(root, scope, compositionId, authoredRootId, options) {
187
+ function scopeParsedCss(root, cssLength, scope, compositionId, authoredRootId, options) {
188
+ const charge = options?.charge;
189
+ charge?.(cssLength);
174
190
  forEachScopedRule(root, (rule) => {
175
- rule.selectors = rule.selectors.map((selector) => scopeSelector(selector, scope, compositionId, authoredRootId, options?.compoundAuthoredRoot, options?.scopeRootSelectors));
191
+ const authored = rule.selector.length;
192
+ const selectors = rule.selectors;
193
+ // postcss re-joins the list with the first separator in the authored selector.
194
+ const separator = selectors.length > 1 ? (rule.selector.match(/,\s*/)?.[0].length ?? 1) : 0;
195
+ const reserved = charge
196
+ ? scopedSelectorsBound(selectors, scope, authoredRootId) + (selectors.length - 1) * separator
197
+ : 0;
198
+ charge?.(reserved);
199
+ rule.selectors = selectors.map((selector) => scopeSelector(selector, scope, compositionId, authoredRootId, options?.compoundAuthoredRoot, options?.scopeRootSelectors));
200
+ charge?.(rule.selector.length - authored - reserved);
176
201
  });
177
202
  return root.toResult({ map: false }).css;
178
203
  }
@@ -208,9 +233,12 @@ export function createCompositionCssScoper() {
208
233
  template = scopeTemplate(css, trimmedId, authoredRootId, options);
209
234
  templates.set(key, template);
210
235
  }
211
- return template === null
212
- ? scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options)
213
- : template.split(PLACEHOLDER_SCOPE).join(scope);
236
+ if (template === null) {
237
+ return scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options);
238
+ }
239
+ const pieces = template.split(PLACEHOLDER_SCOPE);
240
+ options?.charge?.(template.length + (pieces.length - 1) * (scope.length - PLACEHOLDER_SCOPE.length));
241
+ return pieces.join(scope);
214
242
  };
215
243
  }
216
244
  /** Null when the placeholder is already in the sheet, or a selector keeps its raw text (it holds a comment). */
@@ -228,7 +256,8 @@ function scopeTemplate(css, compositionId, authoredRootId, options) {
228
256
  });
229
257
  return rawSelector
230
258
  ? null
231
- : scopeParsedCss(root, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
259
+ : // The cached template stays in memory for the render, so it is charged as well as each join.
260
+ scopeParsedCss(root, css.length, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
232
261
  }
233
262
  function isFontFaceAtRule(node) {
234
263
  return node.type === "atrule" && node.name.toLowerCase() === "font-face";
@@ -357,14 +386,15 @@ export function wrapScopedCompositionScript(source, compositionId, errorLabel =
357
386
  var __hfAuthoredRootEntries = __hfAuthoredRootSelector
358
387
  ? [{ id: __hfAuthoredRootId, replacement: __hfAuthoredRootSelector }]
359
388
  : [];
389
+ var __hfRootSelectorText = function() { return __hfRootSelector; };
360
390
  var __hfNormalizeSelector = function(selector) {
361
391
  if (!__hfCompId || typeof selector !== "string") return selector;
362
392
  var normalized = selector
363
- .replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelector)
364
- .replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelector)
365
- .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);
366
396
  if (__hfTimelineCompId !== __hfCompId) {
367
- normalized = normalized.replace(new RegExp(__hfTimelineRootSelectorPattern, 'g'), __hfRootSelector);
397
+ normalized = normalized.replace(new RegExp(__hfTimelineRootSelectorPattern, 'g'), __hfRootSelectorText);
368
398
  }
369
399
  return window.__hfSvgSelectorAliases.rewrite(normalized, __hfAuthoredRootEntries);
370
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.).
@@ -100,6 +102,11 @@ export interface InlineSubCompositionsOptions {
100
102
  /** Tag each top-level host with `data-hf-scene` and report every part's scene, for preview swaps. */
101
103
  tagScenes?: boolean;
102
104
  readProjectScript?: (path: string) => string | null;
105
+ /**
106
+ * Told the size of each script and stylesheet generated for a mount: each wrapped script once
107
+ * built, and each scoped sheet rule by rule as `scopeCssToComposition` reports it. May throw.
108
+ */
109
+ chargeEmitted?: (srcPath: string, bytes: number) => void;
103
110
  }
104
111
  export interface ExternalLink {
105
112
  href: string;
@@ -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, } = 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,15 +360,18 @@ 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
- return scopeCompId
365
- ? scopeCssToComposition(css, scopeCompId, runtimeScope || undefined, authoredRootId, {
366
- compoundAuthoredRoot: compoundAuthoredRoot === true,
367
- scopeRootSelectors: true,
368
- })
369
- : css;
366
+ if (!scopeCompId) {
367
+ chargeEmitted?.(src, css.length);
368
+ return css;
369
+ }
370
+ return scopeCssToComposition(css, scopeCompId, runtimeScope || undefined, authoredRootId, {
371
+ compoundAuthoredRoot: compoundAuthoredRoot === true,
372
+ scopeRootSelectors: true,
373
+ ...(chargeEmitted ? { charge: (bytes) => chargeEmitted(src, bytes) } : {}),
374
+ });
370
375
  };
371
376
  // <link> hoisting is unconditional. A templated sub-composition's webfont
372
377
  // link is as load-bearing as a non-templated one's, and the mount path has
@@ -432,7 +437,9 @@ export function inlineSubCompositions(document, hosts, options) {
432
437
  const prelude = scriptCompositionId
433
438
  ? scopedModulePrelude(runtimeCompId || scopeCompId || scriptCompositionId, src)
434
439
  : "";
435
- moduleScripts.push(`${prelude}${AUTHORED_SOURCE_BEGIN}\n${scriptEl.textContent || ""}\n${AUTHORED_SOURCE_END}`);
440
+ const moduleScript = `${prelude}${AUTHORED_SOURCE_BEGIN}\n${scriptEl.textContent || ""}\n${AUTHORED_SOURCE_END}`;
441
+ chargeEmitted?.(src, moduleScript.length);
442
+ moduleScripts.push(moduleScript);
436
443
  }
437
444
  else if (externalSrc) {
438
445
  if (!externalScriptSrcs.includes(externalSrc)) {
@@ -449,6 +456,7 @@ export function inlineSubCompositions(document, hosts, options) {
449
456
  const wrappedScript = scriptCompositionId
450
457
  ? wrapScopedCompositionScript(scriptEl.textContent || "", scriptCompositionId, scriptErrorLabel, runtimeScope || undefined, runtimeCompId || scopeCompId || scriptCompositionId, authoredRootId, src)
451
458
  : wrapInlineScriptWithErrorBoundary(scriptEl.textContent || "", scriptErrorLabel);
459
+ chargeEmitted?.(src, wrappedScript.length);
452
460
  scripts.push(wrappedScript);
453
461
  scriptItems.push({ kind: "inline", content: wrappedScript, ...(scene ? { scene } : {}) });
454
462
  }
@@ -459,16 +467,16 @@ export function inlineSubCompositions(document, hosts, options) {
459
467
  const assetEls = innerRoot
460
468
  ? innerRoot.querySelectorAll("[src], [href], [srcset]")
461
469
  : contentDoc.querySelectorAll("[src], [href], [srcset]");
462
- rewriteAssetPaths(assetEls, src, (el, attr) => el.getAttribute(attr), (el, attr, val) => {
470
+ rewriteAssetPaths(assetEls, filePath, (el, attr) => el.getAttribute(attr), (el, attr, val) => {
463
471
  el.setAttribute(attr, val);
464
- }, assetExists);
472
+ }, assetExists, chargeRebase);
465
473
  if (rewriteInlineStyles) {
466
474
  const styledEls = innerRoot
467
475
  ? innerRoot.querySelectorAll("[style]")
468
476
  : contentDoc.querySelectorAll("[style]");
469
- rewriteInlineStyleAssetUrls(styledEls, src, (el) => el.getAttribute("style"), (el, val) => {
477
+ rewriteInlineStyleAssetUrls(styledEls, filePath, (el) => el.getAttribute("style"), (el, val) => {
470
478
  el.setAttribute("style", val);
471
- }, assetExists);
479
+ }, assetExists, chargeRebase);
472
480
  }
473
481
  if (innerRoot?.hasAttribute("data-timeline-locked")) {
474
482
  hostEl.setAttribute("data-timeline-locked", "");
@@ -542,6 +550,7 @@ export function inlineSubCompositions(document, hosts, options) {
542
550
  // scoping and script scoping already key on. Nested hosts are excluded
543
551
  // because each of them is recorded as its own scope when dequeued.
544
552
  svgIdScopes.push({
553
+ src,
545
554
  root: hostEl,
546
555
  namespace: runtimeCompId || scopeCompId,
547
556
  exclude: nested.hosts.map((nestedHost) => nestedHost.host),
@@ -578,17 +587,27 @@ export function inlineSubCompositions(document, hosts, options) {
578
587
  namespace: `clip-${index}`,
579
588
  exclude: hostRoots.filter((host) => root.contains(host)),
580
589
  })),
581
- ]);
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
+ };
582
596
  svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
583
597
  const { styleStart, styleEnd } = svgIdScopes[index];
584
598
  const references = readSvgReferenceAliases(svgIdScopes[index].root, SVG_REFERENCE_ALIASES_ATTR);
585
599
  for (let i = styleStart; i < styleEnd; i += 1) {
586
- 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;
587
603
  }
588
604
  });
589
605
  const rootReferences = readSvgReferenceAliases(document.documentElement, SVG_REFERENCE_ALIASES_ATTR);
590
606
  for (const style of rootStyles) {
591
- 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;
592
611
  }
593
612
  return {
594
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 {};