@hyperframes/core 0.9.70 → 0.9.72

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.
@@ -8,7 +8,7 @@ function escapeRegExp(value) {
8
8
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
9
  }
10
10
  function escapeCssAttributeValue(value) {
11
- return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
11
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/</g, "\\3c ");
12
12
  }
13
13
  function getAuthoredRootIdSelectorForms(authoredRootId) {
14
14
  const trimmed = authoredRootId.trim();
@@ -30,6 +30,7 @@ import { ensureExternalLinkTag, inlineSubCompositions, isLibraryCopy, refuseSwap
30
30
  import { isPrivateFileUnder, isSafePath, isStudioPrivatePath, isVcsOrSecretPath, resolveWithinProject, } from "../safePath.js";
31
31
  import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
32
32
  import { readTextFile } from "@hyperframes/parsers/asset-resolution";
33
+ import { isHtmlTemplate, templateContent } from "@hyperframes/parsers/sub-composition-validity";
33
34
  import { HF_COLOR_GRADING_ATTR } from "../colorGrading.js";
34
35
  import { assignMediaRenderIds } from "./mediaRenderIds.js";
35
36
  import { terminalText } from "../terminalText.js";
@@ -450,6 +451,10 @@ function getBundledHostCompositionIdentity(host) {
450
451
  runtimeCompositionId: currentCompositionId,
451
452
  };
452
453
  }
454
+ function hasInlineTemplate(document, compositionId) {
455
+ const template = document.getElementById(`${compositionId}-template`);
456
+ return !!template && isHtmlTemplate(template);
457
+ }
453
458
  function getBundledTrackedCompositionHosts(document) {
454
459
  const hosts = Array.from(document.querySelectorAll("[data-composition-src], [data-composition-id]"));
455
460
  return hosts.filter((host) => {
@@ -458,7 +463,7 @@ function getBundledTrackedCompositionHosts(document) {
458
463
  const authoredCompositionId = getBundledHostCompositionIdentity(host).authoredCompositionId;
459
464
  if (!authoredCompositionId)
460
465
  return false;
461
- return !!document.getElementById(`${authoredCompositionId}-template`);
466
+ return hasInlineTemplate(document, authoredCompositionId);
462
467
  });
463
468
  }
464
469
  function shouldAssignBundledRuntimeCompositionId(host, document) {
@@ -467,7 +472,7 @@ function shouldAssignBundledRuntimeCompositionId(host, document) {
467
472
  const authoredCompositionId = getBundledHostCompositionIdentity(host).authoredCompositionId;
468
473
  if (!authoredCompositionId)
469
474
  return false;
470
- if (!document.getElementById(`${authoredCompositionId}-template`))
475
+ if (!hasInlineTemplate(document, authoredCompositionId))
471
476
  return false;
472
477
  return host.children.length === 0;
473
478
  }
@@ -931,7 +936,7 @@ async function bundleProject(projectDir, options) {
931
936
  ? [
932
937
  ...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`),
933
938
  ...[...document.querySelectorAll("template")].flatMap((t) => [
934
- ...t.content.querySelectorAll("script"),
939
+ ...(templateContent(t)?.querySelectorAll("script") ?? []),
935
940
  ]),
936
941
  ].map((el) => {
937
942
  const src = el.getAttribute("src");
@@ -1035,6 +1040,8 @@ async function bundleProject(projectDir, options) {
1035
1040
  // matching empty host elements with data-composition-id="X" (no data-composition-src)
1036
1041
  const candidateInlineHosts = trackedCompositionHosts.filter((host) => !host.hasAttribute("data-composition-src"));
1037
1042
  for (const templateEl of [...document.querySelectorAll("template[id]")]) {
1043
+ if (!isHtmlTemplate(templateEl))
1044
+ continue;
1038
1045
  const templateId = templateEl.getAttribute("id") || "";
1039
1046
  const match = templateId.match(/^(.+)-template$/);
1040
1047
  if (!match)
@@ -1,5 +1,5 @@
1
1
  import { acceleratedCanvasTrackerSource } from "../pageMotionBlur.js";
2
- import { findSceneTemplate } from "@hyperframes/parsers/sub-composition-validity";
2
+ import { findSceneTemplate, templateContent } from "@hyperframes/parsers/sub-composition-validity";
3
3
  import { parseHTML } from "linkedom";
4
4
  export const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime";
5
5
  const RUNTIME_FILES = [
@@ -16,7 +16,8 @@ export function locateSceneRoot(html) {
16
16
  const { document } = parseHTML(html);
17
17
  const liveRoot = document.querySelector("[data-composition-id]");
18
18
  const templates = Array.from(document.querySelectorAll("template"));
19
- const sceneRoot = findSceneTemplate(templates)?.content.querySelector("[data-composition-id]") ?? null;
19
+ const scene = findSceneTemplate(templates);
20
+ const sceneRoot = (scene && templateContent(scene)?.querySelector("[data-composition-id]")) ?? null;
20
21
  return {
21
22
  root: sceneRoot,
22
23
  hasTemplate: templates.length > 0,
@@ -17,4 +17,5 @@ export { checkSubCompositionUsability, type ParsableDocumentLike, type SubCompos
17
17
  export { CSS_URL_RE, PATH_ATTRS, isNonRelativeUrl, isPathInside } from "./assetPaths.js";
18
18
  export { AUDIO_GROUP_RENDER_ID_ATTR, MEDIA_RENDER_ID_ATTR, assignMediaRenderIds, } from "./mediaRenderIds.js";
19
19
  export { ensureExternalScriptTag } from "./externalScripts.js";
20
+ export { dropAuthoredSvgReferenceAliases } from "./svgSelectorAliases.js";
20
21
  export { emitMountedModuleScripts } from "./importMaps.js";
@@ -30,4 +30,5 @@ export { checkSubCompositionUsability, } from "./subCompositionValidity.js";
30
30
  export { CSS_URL_RE, PATH_ATTRS, isNonRelativeUrl, isPathInside } from "./assetPaths.js";
31
31
  export { AUDIO_GROUP_RENDER_ID_ATTR, MEDIA_RENDER_ID_ATTR, assignMediaRenderIds, } from "./mediaRenderIds.js";
32
32
  export { ensureExternalScriptTag } from "./externalScripts.js";
33
+ export { dropAuthoredSvgReferenceAliases } from "./svgSelectorAliases.js";
33
34
  export { emitMountedModuleScripts } from "./importMaps.js";
@@ -1,4 +1,4 @@
1
- import { SVG_REFERENCE_ALIASES_ATTR, readSvgReferenceAliases } from "./svgSelectorAliases.js";
1
+ import { SVG_REFERENCE_ALIASES_ATTR, dropAuthoredSvgReferenceAliases, readSvgReferenceAliases, } from "./svgSelectorAliases.js";
2
2
  import { readExternalScriptAttributes } from "./externalScripts.js";
3
3
  import { parseImportMap } from "./importMaps.js";
4
4
  import { compositionStyle, cssStyleMergeKey, hasSameLink, } from "./scriptRuns.js";
@@ -172,7 +172,7 @@ export function ensureExternalLinkTag(doc, link) {
172
172
  // ---------------------------------------------------------------------------
173
173
  const isDocument = (node) => node.nodeType === 9;
174
174
  function defaultBuildScopeSelector(compId) {
175
- const escaped = compId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
175
+ const escaped = compId.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/</g, "\\3c ");
176
176
  return `[data-composition-id="${escaped}"]`;
177
177
  }
178
178
  // ---------------------------------------------------------------------------
@@ -566,6 +566,7 @@ export function inlineSubCompositions(document, hosts, options) {
566
566
  // `<style>` text gets the same substitution its DOM just received. See
567
567
  // svgIdNamespacing.ts for why this is a rename, unlike the sibling
568
568
  // getElementById/media-id fixes.
569
+ dropAuthoredSvgReferenceAliases(document);
569
570
  const hostRoots = svgIdScopes.map(({ root }) => root);
570
571
  const clips = sceneClipRoots(document, hostRoots);
571
572
  const svgIdMaps = namespaceCollidingSvgIds(document, [
@@ -589,25 +590,18 @@ export function inlineSubCompositions(document, hosts, options) {
589
590
  })),
590
591
  ], undefined, chargeEmitted &&
591
592
  ((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
- };
593
+ const rewriteCss = (src, css, idMap, references) => rewriteSvgIdReferencesInCss(css, idMap, references, chargeEmitted && ((bytes) => chargeEmitted(src, bytes)));
596
594
  svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
597
595
  const { styleStart, styleEnd } = svgIdScopes[index];
598
596
  const references = readSvgReferenceAliases(svgIdScopes[index].root, SVG_REFERENCE_ALIASES_ATTR);
599
597
  for (let i = styleStart; i < styleEnd; i += 1) {
600
- const rewritten = rewriteSvgIdReferencesInCss(styles[i].css, idMap, references);
601
- chargeGrowth(svgIdScopes[index].src, styles[i].css, rewritten);
602
- styles[i].css = rewritten;
598
+ styles[i].css = rewriteCss(svgIdScopes[index].src, styles[i].css, idMap, references);
603
599
  }
604
600
  });
605
601
  const rootReferences = readSvgReferenceAliases(document.documentElement, SVG_REFERENCE_ALIASES_ATTR);
606
602
  for (const style of rootStyles) {
607
603
  const css = style.textContent ?? "";
608
- const rewritten = rewriteSvgIdReferencesInCss(css, svgIdMaps[svgIdScopes.length], rootReferences);
609
- chargeGrowth("the page", css, rewritten);
610
- style.textContent = rewritten;
604
+ style.textContent = rewriteCss("the page", css, svgIdMaps[svgIdScopes.length], rootReferences);
611
605
  }
612
606
  return {
613
607
  styles,
@@ -50,7 +50,7 @@ export declare function escapeCssIdentifier(value: string): string;
50
50
  */
51
51
  /** The `#id` values a selector names, read as `replaceSelectorIdTokens` reads them. */
52
52
  export declare function selectorIdTokens(selector: string): string[];
53
- export declare function replaceSelectorIdTokens(selector: string, candidateIds: readonly string[], resolveReplacement: (matchedId: string) => string): string;
53
+ export declare function replaceSelectorIdTokens(selector: string, candidateIds: readonly string[], resolveReplacement: (matchedId: string, matchedToken: string) => string): string;
54
54
  export declare function escapeCssAttributeValue(value: string): string;
55
55
  type AttributeNamespace = {
56
56
  kind: "any";
@@ -158,17 +158,114 @@ export function escapeCssIdentifier(value) {
158
158
  }
159
159
  return result;
160
160
  }
161
- /**
162
- * A full attribute-selector bracket (`[data-x="a"]`, quotes optional, `]`
163
- * inside a quoted value tolerated) or a bare quoted string. Either is a
164
- * region where a literal `#` is never an id-selector prefix — the CSS parser
165
- * itself never looks for one there — so `markUnguardedOffsets` below can
166
- * find every such region with one pass of `matchAll` instead of a hand-rolled
167
- * character-by-character state machine. Inside the bracket alternative, bare
168
- * characters exclude the quote marks so each position matches exactly one
169
- * branch (no ambiguous backtracking).
170
- */
171
- const GUARDED_SELECTOR_SEGMENT_RE = /\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\r\n\f])?|[\s\S])|"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|\[(?:\/\*(?:[^*]|\*(?!\/))*\*\/|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|[^\]"'\\/]|\/(?!\*))*\]/g;
161
+ const NO_MATCH = -1;
162
+ const UNKNOWN = -2;
163
+ // One CSS escape, anchored where it is tried: at most nine characters, so each try costs a constant.
164
+ const ESCAPE_AT = /\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\r\n\f])?|[\s\S])/y;
165
+ /** Regions of `selector` where `#` is never an id prefix: a closed comment, an escape, a closed quoted string,
166
+ * or a whole attribute bracket. Each opener's closer is memoized, so an unclosed opener costs one read:
167
+ * linear on any input. */
168
+ function guardedSelectorSegments(selector) {
169
+ const n = selector.length;
170
+ // commentClose[i]: where the first "*/" at or after i starts.
171
+ const commentClose = new Int32Array(n + 2).fill(NO_MATCH);
172
+ for (let i = n - 2; i >= 0; i -= 1) {
173
+ commentClose[i] = selector[i] === "*" && selector[i + 1] === "/" ? i : commentClose[i + 1];
174
+ }
175
+ const commentEnd = (start) => {
176
+ const close = commentClose[start + 2];
177
+ return close === NO_MATCH ? NO_MATCH : close + 2;
178
+ };
179
+ // Each walk reads from i to its closer, steps 1 or 2 at a time; its answer is memoized for every
180
+ // position it passed, so a later walk from any of them stops at once.
181
+ const walk = (memo, from, step) => {
182
+ const passed = [];
183
+ let i = from;
184
+ let found;
185
+ for (;;) {
186
+ if (i >= n) {
187
+ found = NO_MATCH;
188
+ break;
189
+ }
190
+ if (memo[i] !== UNKNOWN) {
191
+ found = memo[i];
192
+ break;
193
+ }
194
+ passed.push(i);
195
+ const next = step(i);
196
+ if (typeof next !== "number") {
197
+ found = next[0];
198
+ break;
199
+ }
200
+ i = next;
201
+ }
202
+ for (const at of passed)
203
+ memo[at] = found;
204
+ return found;
205
+ };
206
+ const quoteClose = { '"': new Int32Array(n).fill(UNKNOWN), "'": new Int32Array(n).fill(UNKNOWN) };
207
+ // Index of the quote that closes a string whose body starts at `from`, or NO_MATCH.
208
+ const closeQuote = (quote, from) => walk(quoteClose[quote], from, (i) => {
209
+ if (selector[i] === quote)
210
+ return [i];
211
+ if (selector[i] === "\\")
212
+ return i + 1 < n ? i + 2 : [NO_MATCH];
213
+ return i + 1;
214
+ });
215
+ const quoteEnd = (start) => {
216
+ const close = closeQuote(selector[start], start + 1);
217
+ return close === NO_MATCH ? NO_MATCH : close + 1;
218
+ };
219
+ // Where the token at `i` inside a bracket ends, or NO_MATCH when it can't close (an unclosed comment or quote).
220
+ const bracketTokenEnd = (i) => {
221
+ const char = selector[i];
222
+ if (char === "/" && selector[i + 1] === "*")
223
+ return commentEnd(i);
224
+ if (char === '"' || char === "'")
225
+ return quoteEnd(i);
226
+ if (char !== "\\")
227
+ return i + 1;
228
+ return i + 1 < n ? i + 2 : NO_MATCH;
229
+ };
230
+ const bracketClose = new Int32Array(n).fill(UNKNOWN);
231
+ // Index of the `]` that closes a bracket whose body starts at `from`, or NO_MATCH.
232
+ const closeBracket = (from) => walk(bracketClose, from, (i) => {
233
+ if (selector[i] === "]")
234
+ return [i];
235
+ const end = bracketTokenEnd(i);
236
+ return end === NO_MATCH ? [NO_MATCH] : end;
237
+ });
238
+ const escapeEnd = (start) => {
239
+ ESCAPE_AT.lastIndex = start;
240
+ return ESCAPE_AT.test(selector) ? ESCAPE_AT.lastIndex : NO_MATCH;
241
+ };
242
+ const bracketEnd = (start) => {
243
+ const close = closeBracket(start + 1);
244
+ return close === NO_MATCH ? NO_MATCH : close + 1;
245
+ };
246
+ const segmentEnd = (start) => {
247
+ const char = selector[start];
248
+ if (char === "/")
249
+ return selector[start + 1] === "*" ? commentEnd(start) : NO_MATCH;
250
+ if (char === "\\")
251
+ return escapeEnd(start);
252
+ if (char === '"' || char === "'")
253
+ return quoteEnd(start);
254
+ return char === "[" ? bracketEnd(start) : NO_MATCH;
255
+ };
256
+ const segments = [];
257
+ for (let start = 0; start < n;) {
258
+ const end = segmentEnd(start);
259
+ if (end === NO_MATCH) {
260
+ start += 1;
261
+ }
262
+ else {
263
+ segments.push([start, end]);
264
+ start = end;
265
+ }
266
+ }
267
+ return segments;
268
+ }
172
269
  /**
173
270
  * `mask[i]` is `true` when `selector[i]` sits outside both a quoted string
174
271
  * and an attribute-selector bracket — the two places a literal `#` is never
@@ -176,10 +273,8 @@ const GUARDED_SELECTOR_SEGMENT_RE = /\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:[0-9a-fA-F]
176
273
  */
177
274
  function markUnguardedOffsets(selector) {
178
275
  const mask = new Array(selector.length).fill(true);
179
- for (const match of selector.matchAll(GUARDED_SELECTOR_SEGMENT_RE)) {
180
- const start = match.index;
181
- mask.fill(false, start, start + match[0].length);
182
- }
276
+ for (const [start, end] of guardedSelectorSegments(selector))
277
+ mask.fill(false, start, end);
183
278
  return mask;
184
279
  }
185
280
  /**
@@ -222,7 +317,7 @@ export function replaceSelectorIdTokens(selector, candidateIds, resolveReplaceme
222
317
  ? decodeCssIdentifierAt(selector, index + 1)
223
318
  : null;
224
319
  if (token && candidates.has(token.value)) {
225
- result += resolveReplacement(token.value);
320
+ result += resolveReplacement(token.value, selector.slice(index, token.end));
226
321
  index = token.end;
227
322
  }
228
323
  else {
@@ -257,7 +352,7 @@ export function escapeCssAttributeValue(value) {
257
352
  const code = char.charCodeAt(0);
258
353
  if (code === 0)
259
354
  return "\uFFFD";
260
- if (code < 0x20 || code === 0x7f)
355
+ if (code < 0x20 || code === 0x7f || char === "<")
261
356
  return `\\${code.toString(16)} `;
262
357
  return char === '"' || char === "\\" ? `\\${char}` : char;
263
358
  }).join("");
@@ -342,5 +437,13 @@ export function parseAttributeSelector(predicate) {
342
437
  };
343
438
  }
344
439
  export function replaceSelectorAttributeTokens(selector, rewrite) {
345
- return selector.replace(GUARDED_SELECTOR_SEGMENT_RE, (segment) => segment.startsWith("[") ? rewrite(segment) : segment);
440
+ let result = "";
441
+ let copied = 0;
442
+ for (const [start, end] of guardedSelectorSegments(selector)) {
443
+ if (selector[start] !== "[")
444
+ continue;
445
+ result += selector.slice(copied, start) + rewrite(selector.slice(start, end));
446
+ copied = end;
447
+ }
448
+ return result + selector.slice(copied);
346
449
  }
@@ -81,5 +81,5 @@ export declare function namespaceCollidingSvgIds(document: SvgIdQueryable, scope
81
81
  * same-composition stylesheet rule silently stops matching the element whose
82
82
  * id this module just changed.
83
83
  */
84
- export declare function rewriteSvgIdReferencesInCss(css: string, idMap: SvgIdMap, references?: readonly SvgReferenceAlias[]): string;
84
+ export declare function rewriteSvgIdReferencesInCss(css: string, idMap: SvgIdMap, references?: readonly SvgReferenceAlias[], charge?: (bytes: number) => void): string;
85
85
  export {};
@@ -409,7 +409,7 @@ export function namespaceCollidingSvgIds(document, scopes, finalizedIds, charge)
409
409
  * same-composition stylesheet rule silently stops matching the element whose
410
410
  * id this module just changed.
411
411
  */
412
- export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
412
+ export function rewriteSvgIdReferencesInCss(css, idMap, references = [], charge) {
413
413
  if (!css || (idMap.size === 0 && references.length === 0))
414
414
  return css;
415
415
  if (!css.includes("#") && !css.includes("[") && !css.toLowerCase().includes("url("))
@@ -424,6 +424,12 @@ export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
424
424
  return css;
425
425
  }
426
426
  let mutated = false;
427
+ let charged = 0;
428
+ const chargeSelector = charge &&
429
+ ((bytes) => {
430
+ charged += bytes;
431
+ charge(bytes);
432
+ });
427
433
  const recordedIds = recordedSvgIds(references);
428
434
  const idsNamedBy = (selector) => selectorIdTokens(selector).flatMap((id) => {
429
435
  const renamed = recordedIds.has(id) ? undefined : idMap.get(id);
@@ -434,7 +440,7 @@ export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
434
440
  ];
435
441
  });
436
442
  root.walkRules((rule) => {
437
- const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, idsNamedBy(selector), references));
443
+ const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, idsNamedBy(selector), references, undefined, chargeSelector));
438
444
  if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
439
445
  rule.selectors = rewritten;
440
446
  mutated = true;
@@ -456,5 +462,10 @@ export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
456
462
  mutated = true;
457
463
  }
458
464
  });
459
- return mutated ? root.toResult({ map: false }).css : css;
465
+ const rewritten = mutated ? root.toResult({ map: false }).css : css;
466
+ // Selector growth was charged as it was built; settle to the sheet's real growth.
467
+ const settle = Math.max(0, rewritten.length - css.length) - charged;
468
+ if (charge && settle !== 0)
469
+ charge(settle);
470
+ return rewritten;
460
471
  }
@@ -16,7 +16,8 @@ type Namespaces = ReadonlyMap<string, string | null>;
16
16
  * With `namespaces` (a live sheet's bindings) only prefixed attribute selectors are
17
17
  * rewritten; without it they stay as authored and everything else is rewritten.
18
18
  */
19
- export declare function rewriteSvgSelectors(selector: string, ids: readonly IdSelectorAlias[], references: readonly SvgReferenceAlias[], namespaces?: Namespaces): string;
19
+ export declare function rewriteSvgSelectors(selector: string, ids: readonly IdSelectorAlias[], references: readonly SvgReferenceAlias[], namespaces?: Namespaces, charge?: (bytes: number) => void): string;
20
+ export declare function dropAuthoredSvgReferenceAliases(root: ParentNode): boolean;
20
21
  /** Metadata records actual writes; selectors still match current native attribute values. */
21
22
  export declare function readSvgReferenceAliases(root: {
22
23
  querySelectorAll(selector: string): Iterable<Element>;
@@ -94,7 +94,7 @@ function aliasesFor(index, parsed, namespaces) {
94
94
  * With `namespaces` (a live sheet's bindings) only prefixed attribute selectors are
95
95
  * rewritten; without it they stay as authored and everything else is rewritten.
96
96
  */
97
- export function rewriteSvgSelectors(selector, ids, references, namespaces) {
97
+ export function rewriteSvgSelectors(selector, ids, references, namespaces, charge) {
98
98
  const index = aliasIndex(references);
99
99
  const rewriteAttribute = (predicate) => {
100
100
  const parsed = tokens.parseAttributeSelector(predicate);
@@ -104,7 +104,11 @@ export function rewriteSvgSelectors(selector, ids, references, namespaces) {
104
104
  const { rawName, flag } = parsed;
105
105
  const alternatives = new Set([predicate]);
106
106
  for (const alias of aliasesFor(index, parsed, namespaces)) {
107
- alternatives.add(`[${rawName}="${tokens.escapeCssAttributeValue(alias.after)}"${flag ? ` ${flag}` : ""}]`);
107
+ const alternative = `[${rawName}="${tokens.escapeCssAttributeValue(alias.after)}"${flag ? ` ${flag}` : ""}]`;
108
+ if (alternatives.has(alternative))
109
+ continue;
110
+ charge?.(alternative.length + (alternatives.size === 1 ? ":is(, )".length : ", ".length));
111
+ alternatives.add(alternative);
108
112
  }
109
113
  return alternatives.size === 1 ? predicate : `:is(${[...alternatives].join(", ")})`;
110
114
  };
@@ -114,9 +118,28 @@ export function rewriteSvgSelectors(selector, ids, references, namespaces) {
114
118
  const namedIds = tokens
115
119
  .selectorIdTokens(selector)
116
120
  .filter((id) => replacements.has(id) || index.renamedIdAlternatives.has(id));
117
- const rewrittenIds = tokens.replaceSelectorIdTokens(selector, namedIds, (id) => replacements.get(id) ?? index.renamedIdAlternatives.get(id));
121
+ const rewrittenIds = tokens.replaceSelectorIdTokens(selector, namedIds, (id, token) => {
122
+ const replacement = replacements.get(id) ?? index.renamedIdAlternatives.get(id);
123
+ charge?.(replacement.length - token.length);
124
+ return replacement;
125
+ });
118
126
  return tokens.replaceSelectorAttributeTokens(rewrittenIds, rewriteAttribute);
119
127
  }
128
+ export function dropAuthoredSvgReferenceAliases(root) {
129
+ let dropped = false;
130
+ const pending = [root];
131
+ for (let node = pending.pop(); node; node = pending.pop()) {
132
+ for (const el of Array.from(node.children)) {
133
+ if (el.hasAttribute(SVG_REFERENCE_ALIASES_ATTR)) {
134
+ el.removeAttribute(SVG_REFERENCE_ALIASES_ATTR);
135
+ dropped = true;
136
+ }
137
+ const html = el.localName === "template" && !el.firstElementChild && "content" in el;
138
+ pending.push(html ? el.content : el);
139
+ }
140
+ }
141
+ return dropped;
142
+ }
120
143
  /** Metadata records actual writes; selectors still match current native attribute values. */
121
144
  export function readSvgReferenceAliases(root, attribute, includeDescendants = true) {
122
145
  const aliases = [];