@vvfx/svg2ir 0.0.1-beta.0 → 0.0.1-beta.12

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 (57) hide show
  1. package/README.md +86 -48
  2. package/dist/{svg2ge-adapter → adapter/svg2ge}/assemble.d.ts +2 -2
  3. package/dist/adapter/svg2ge/convert.d.ts +7 -0
  4. package/dist/{svg2ge-adapter → adapter/svg2ge}/normalize-shape-animation.d.ts +1 -1
  5. package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/apply-shape-geometry-animation.d.ts +1 -1
  6. package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/apply-shape-paint-animation.d.ts +1 -1
  7. package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/rewrite-text-components.d.ts +1 -1
  8. package/dist/{svg2ge-adapter → adapter/svg2ge}/pre-process.d.ts +1 -1
  9. package/dist/{svg2ge-adapter → adapter/svg2ge}/types.d.ts +2 -2
  10. package/dist/adapter/svg2layers/assemble.d.ts +23 -0
  11. package/dist/adapter/svg2layers/baking/build-baked-layers.d.ts +13 -0
  12. package/dist/adapter/svg2layers/baking/normalize-layer-blending.d.ts +10 -0
  13. package/dist/adapter/svg2layers/baking/plan-graphic-baking.d.ts +18 -0
  14. package/dist/adapter/svg2layers/baking/resolve-baking-warnings.d.ts +4 -0
  15. package/dist/adapter/svg2layers/convert.d.ts +4 -0
  16. package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/diagnostics/collect-warnings.d.ts +1 -1
  17. package/dist/adapter/svg2layers/converter/image/inspect-mask.d.ts +3 -0
  18. package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/layers/build-layers.d.ts +1 -1
  19. package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/layers/conversion-session.d.ts +2 -2
  20. package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/text/parse-text-runs.d.ts +1 -1
  21. package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/text/text-layout.d.ts +2 -2
  22. package/dist/{svg2layers-adapter → adapter/svg2layers}/matrix.d.ts +1 -1
  23. package/dist/adapter/svg2layers/strip-layer-animation.d.ts +5 -0
  24. package/dist/{svg2layers-adapter → adapter/svg2layers}/types.d.ts +8 -1
  25. package/dist/common/types.d.ts +7 -3
  26. package/dist/index.d.ts +6 -6
  27. package/dist/index.js +1324 -103
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +1323 -103
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/node.js +1326 -105
  32. package/dist/node.js.map +1 -1
  33. package/dist/node.mjs +1325 -105
  34. package/dist/node.mjs.map +1 -1
  35. package/dist/parse-svg/build-element-tree-path.d.ts +2 -0
  36. package/dist/svg-rasterizer/prepare-snapshot.d.ts +9 -0
  37. package/dist/svg-rasterizer/rasterize-svg.d.ts +11 -0
  38. package/dist/svg2ir/assemble.d.ts +3 -1
  39. package/dist/svg2ir/convert.d.ts +5 -2
  40. package/dist/svg2ir/converter/layers/conversion-session.d.ts +2 -0
  41. package/dist/svg2ir/converter/text/font-metrics.d.ts +2 -0
  42. package/package.json +5 -5
  43. package/dist/convert.d.ts +0 -19
  44. package/dist/svg2ge-adapter/convert.d.ts +0 -5
  45. package/dist/svg2layers-adapter/assemble.d.ts +0 -8
  46. package/dist/svg2layers-adapter/convert.d.ts +0 -4
  47. /package/dist/{svg2ge-adapter → adapter/svg2ge}/converter/animation.d.ts +0 -0
  48. /package/dist/{svg2ge-adapter → adapter/svg2ge}/converter/data-path.d.ts +0 -0
  49. /package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/apply-fonts.d.ts +0 -0
  50. /package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/paint-animation-sampling.d.ts +0 -0
  51. /package/dist/{svg2ge-adapter → adapter/svg2ge}/post-process/restore-gradient-uv.d.ts +0 -0
  52. /package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/image/convert-image-layer.d.ts +0 -0
  53. /package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/layers/registry.d.ts +0 -0
  54. /package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/layers/resolve-visual-state.d.ts +0 -0
  55. /package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/text/convert-text-layer.d.ts +0 -0
  56. /package/dist/{svg2layers-adapter → adapter/svg2layers}/converter/transform/build-transform.d.ts +0 -0
  57. /package/dist/{svg2layers-adapter → adapter/svg2layers}/post-process/inline-image-resources.d.ts +0 -0
package/dist/node.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * Description: SVG to Animation IR and Galacean Effects conversion engine
4
4
  * Author: Ant Group CO., Ltd.
5
5
  * Contributors: 鳞息
6
- * Version: v0.0.1-beta.0
6
+ * Version: v0.0.1-beta.12
7
7
  */
8
8
 
9
9
  'use strict';
@@ -81,11 +81,10 @@ function readInlineStyleProperty(style, propertyName) {
81
81
 
82
82
  var ParseableSVG = /*#__PURE__*/ function() {
83
83
  function ParseableSVG(svgStr, _options) {
84
- var _ref, _SVG;
85
- var _svgStr_match;
86
- // 从字符串里抠出首个 <svg>...</svg> 再交给 svg.js(兼容前导注释/doctype)。
84
+ var _SVG;
85
+ // svg.js parses a fragment; remove only the prolog and let the DOM handle nested markup.
86
+ var content = svgStr.replace(/^\uFEFF/, '').replace(/^(?:\s|<\?xml\b[\s\S]*?\?>|<!DOCTYPE\b[^>]*>|<!--[\s\S]*?-->)+/i, '');
87
87
  // svg.js SVG(string) 的 d.ts 标为 Element,但对完整 <svg> 文档运行时返回根 SVG 文档实例。
88
- var content = typeof svgStr === 'string' ? (_ref = (_svgStr_match = svgStr.match(RegExp("<svg\\s+.*?>.*?<\\/svg>", "s"))) == null ? void 0 : _svgStr_match[0]) != null ? _ref : svgStr : svgStr;
89
88
  // svg.js 对非 SVG 字符串(如 'not svg')解析返 null。兜底空 svg:让 svg2ir 上层
90
89
  // hasSVGRootElement 检查(非 svg 抛 INVALID_SVG)生效,而非在构造期抛错。
91
90
  this.svg = (_SVG = svg_js.SVG(content)) != null ? _SVG : svg_js.SVG('<svg xmlns="http://www.w3.org/2000/svg"/>');
@@ -227,10 +226,10 @@ var editableSVGModule = /*#__PURE__*/Object.freeze({
227
226
  default: ParseableSVG
228
227
  });
229
228
 
230
- var window = svgdom.createSVGWindow();
229
+ var window$1 = svgdom.createSVGWindow();
231
230
  // svgdom 的 window 是最小 DOM stub(非完整 Window),运行时被 svg.js registerWindow 接受;
232
231
  // d.ts 标 Window 类型过严,svgdom 的 window 是最小 DOM stub,这里断言对齐运行时用法。
233
- svg_js.registerWindow(window, window.document);
232
+ svg_js.registerWindow(window$1, window$1.document);
234
233
 
235
234
  var editableSVGNodeModule = /*#__PURE__*/Object.freeze({
236
235
  __proto__: null,
@@ -1727,7 +1726,7 @@ function parseHexColor(raw) {
1727
1726
  return null;
1728
1727
  }
1729
1728
  var hex = match[1];
1730
- var expanded = hex.length <= 4 ? [].concat(hex).map(function(char) {
1729
+ var expanded = hex.length <= 4 ? Array.from(hex).map(function(char) {
1731
1730
  return "" + char + char;
1732
1731
  }).join('') : hex;
1733
1732
  var r = parseInt(expanded.slice(0, 2), 16) / 255;
@@ -2828,7 +2827,24 @@ function parseSMILTag(tag, root, beginCache, comparisonDuration, valueParser, un
2828
2827
  return maxEnd;
2829
2828
  }
2830
2829
 
2831
- /** SVG 转换诊断码。不支持的特性按降级和 warning 处理。 */ var SVG2IR_WARNING_CODES = {
2830
+ /** Structural source identity, independent of optional or duplicate SVG IDs. */ function buildElementTreePath(element) {
2831
+ var indices = [];
2832
+ var current = element;
2833
+ while(isElementNode(current.parentNode)){
2834
+ var parent = current.parentNode;
2835
+ indices.unshift(Array.from(parent.children).indexOf(current));
2836
+ current = parent;
2837
+ }
2838
+ return indices.join('/');
2839
+ }
2840
+ function isElementNode(node) {
2841
+ return (node == null ? void 0 : node.nodeType) === 1;
2842
+ }
2843
+
2844
+ /** SVG 转换诊断码;用于报告烘焙、降级和不支持的特性。 */ var SVG2IR_WARNING_CODES = {
2845
+ /** 图形或图形组已栅格化,矢量编辑能力变化通过 warning 报告。 */ LAYERS_GRAPHIC_BAKED: 'svg2ge_layers_graphic_baked',
2846
+ LAYERS_BLEND_MODE_DOWNGRADED: 'svg2ge_layers_blend_mode_downgraded',
2847
+ LAYERS_ANIMATION_STRIPPED: 'svg2ge_layers_animation_stripped',
2832
2848
  LAYERS_UNSUPPORTED_TYPE: 'svg2ge_layers_unsupported_type',
2833
2849
  LAYERS_UNSUPPORTED_FEATURE: 'svg2ge_layers_unsupported_feature',
2834
2850
  LAYERS_INVALID_DATA: 'svg2ge_layers_invalid_data',
@@ -4183,7 +4199,7 @@ function distPointToSegment(p, a, b) {
4183
4199
  return transformVector(gChain, t);
4184
4200
  });
4185
4201
  return {
4186
- mode: "add",
4202
+ mode: 'add',
4187
4203
  path: {
4188
4204
  points: pts,
4189
4205
  inTangents: inTangents,
@@ -6110,12 +6126,16 @@ function applyClipMask(es, el, layer, clipMasks) {
6110
6126
  }
6111
6127
  if (isClip) {
6112
6128
  return _extends({}, layer, {
6113
- mask: baseMask
6129
+ masks: [
6130
+ baseMask
6131
+ ]
6114
6132
  });
6115
6133
  }
6116
6134
  var rebased = rebaseMaskToLocal(baseMask, layer);
6117
6135
  return rebased ? _extends({}, layer, {
6118
- mask: rebased
6136
+ masks: [
6137
+ rebased
6138
+ ]
6119
6139
  }) : layer;
6120
6140
  }
6121
6141
  /** 将 SVG 绝对 mask 点转换为 image 的 asset-local 坐标。 */ function rebaseMaskToLocal(mask, layer) {
@@ -6153,7 +6173,7 @@ function applyClipMask(es, el, layer, clipMasks) {
6153
6173
  outTangents: mask.path.outTangents,
6154
6174
  closed: mask.path.closed
6155
6175
  },
6156
- mode: "add"
6176
+ mode: 'add'
6157
6177
  };
6158
6178
  }
6159
6179
  // shape 没有 asset 尺寸,mask 需要转换到以 layer anchor 为基准的 element-local 空间。
@@ -6183,7 +6203,7 @@ function applyClipMask(es, el, layer, clipMasks) {
6183
6203
  outTangents: mask.path.outTangents,
6184
6204
  closed: mask.path.closed
6185
6205
  },
6186
- mode: "add"
6206
+ mode: 'add'
6187
6207
  };
6188
6208
  }
6189
6209
  /** shape layer 的 element-local bbox(以 layer.transform.anchor=localCenter 为原点)。
@@ -6318,8 +6338,9 @@ function readVec3(channel) {
6318
6338
  node
6319
6339
  ], Array.from(node.querySelectorAll('*')));
6320
6340
  var hasUnsupportedRule = ruleNodes.some(function(candidate) {
6341
+ var _ref, _ref1;
6321
6342
  var _candidate_getAttribute, _candidate_getAttribute1;
6322
- return ((_candidate_getAttribute = candidate.getAttribute('clip-rule')) == null ? void 0 : _candidate_getAttribute.trim()) !== '' || ((_candidate_getAttribute1 = candidate.getAttribute('fill-rule')) == null ? void 0 : _candidate_getAttribute1.trim()) !== '';
6343
+ return ((_ref = (_candidate_getAttribute = candidate.getAttribute('clip-rule')) == null ? void 0 : _candidate_getAttribute.trim()) != null ? _ref : '') !== '' || ((_ref1 = (_candidate_getAttribute1 = candidate.getAttribute('fill-rule')) == null ? void 0 : _candidate_getAttribute1.trim()) != null ? _ref1 : '') !== '';
6323
6344
  });
6324
6345
  if (hasUnsupportedRule) {
6325
6346
  warn(SVG2IR_WARNING_CODES.CLIP_RULE_DROPPED, "" + tag + " 内显式 clip-rule/fill-rule 未映射,IR 只保留 mask 几何,不保留该规则。");
@@ -7151,7 +7172,7 @@ function createSVGConversionSession(es, options) {
7151
7172
  };
7152
7173
  var withGroupParent = function withGroupParent(layer, element) {
7153
7174
  var parentIndex = nearestMaskedGroupAncestor(element);
7154
- if (parentIndex == null || layer.mask != null) {
7175
+ if (parentIndex == null) {
7155
7176
  return layer;
7156
7177
  }
7157
7178
  return _extends({}, layer, {
@@ -7160,8 +7181,10 @@ function createSVGConversionSession(es, options) {
7160
7181
  };
7161
7182
  var appendLayer = function appendLayer(layer, element, applyElementClip) {
7162
7183
  if (applyElementClip === void 0) applyElementClip = true;
7184
+ var _options_layerSourceCollector;
7163
7185
  var clippedLayer = applyElementClip ? applyClipMask(es, element, layer, clipMasks) : layer;
7164
7186
  layers.push(withGroupParent(clippedLayer, element));
7187
+ (_options_layerSourceCollector = options.layerSourceCollector) == null ? void 0 : _options_layerSourceCollector.set(layer.id, buildElementTreePath(element.node));
7165
7188
  };
7166
7189
  var appendAsset = function appendAsset(asset) {
7167
7190
  if (registeredAssetIds.has(asset.id)) {
@@ -7504,7 +7527,9 @@ function convertGroupElement(element, context) {
7504
7527
  value: 1
7505
7528
  }
7506
7529
  },
7507
- mask: groupMask
7530
+ masks: [
7531
+ groupMask
7532
+ ]
7508
7533
  };
7509
7534
  context.appendLayer(nullLayer, element, false);
7510
7535
  context.groupMaskGNodeToIndex.set(element.node, layerIndex);
@@ -10569,7 +10594,7 @@ function mapFontWeight(raw, fontFamily) {
10569
10594
  seen.set(Math.round(w * 100), ch);
10570
10595
  }
10571
10596
  }
10572
- return [].concat(seen.entries()).map(function(param) {
10597
+ return Array.from(seen.entries()).map(function(param) {
10573
10598
  var k = param[0], ch = param[1];
10574
10599
  return {
10575
10600
  ch: ch,
@@ -10619,6 +10644,9 @@ function mapFontWeight(raw, fontFamily) {
10619
10644
  // latin / digit / 标点:典型比例字体 sans-serif 大写字母约 0.65em,数字稍窄。
10620
10645
  return /[0-9]/.test(ch) ? 0.55 : 0.62;
10621
10646
  }
10647
+ /** 去除单个字体族名的 CSS 字符串引号。 */ function normalizeFontFamilyName(fontFamily) {
10648
+ return fontFamily.trim().replace(/^(['"])(.*)\1$/, '$2');
10649
+ }
10622
10650
  /** 构造与 Effects Runtime getFontDesc 一致的 CSS font 简写字符串,用于 Canvas measureText。 */ function buildCanvasFontDesc(fontSize, fontFamily, fontWeight, fontStyle) {
10623
10651
  var weightStr = String(fontWeight);
10624
10652
  var genericFamilies = [
@@ -10627,7 +10655,8 @@ function mapFontWeight(raw, fontFamily) {
10627
10655
  'monospace',
10628
10656
  'courier'
10629
10657
  ];
10630
- var familyName = genericFamilies.includes(fontFamily) ? fontFamily : '"' + fontFamily + '"';
10658
+ var family = normalizeFontFamilyName(fontFamily);
10659
+ var familyName = genericFamilies.includes(family) ? family : '"' + family + '"';
10631
10660
  var desc = fontSize + "px " + familyName;
10632
10661
  if (weightStr !== 'normal' && weightStr !== '') {
10633
10662
  desc = weightStr + " " + desc;
@@ -10638,13 +10667,13 @@ function mapFontWeight(raw, fontFamily) {
10638
10667
  return desc;
10639
10668
  }
10640
10669
  /** 文本宽度估算。优先使用调用方提供的 Canvas measureText,否则使用字符级启发式系数。 */ function estimateTextWidth(content, fontSize, letterSpacing, measureText, fontFamily, fontWeight, fontStyle) {
10641
- var len = [].concat(content).length;
10670
+ var chars = Array.from(content);
10671
+ var len = chars.length;
10642
10672
  if (measureText != null && fontFamily !== '') {
10643
10673
  var fontDesc = buildCanvasFontDesc(fontSize, fontFamily, fontWeight, fontStyle);
10644
10674
  var width = measureText(fontDesc, content).width;
10645
10675
  return width + letterSpacing * Math.max(len - 1, 0);
10646
10676
  }
10647
- var chars = [].concat(content);
10648
10677
  var width1 = chars.reduce(function(s, ch) {
10649
10678
  return s + charWidthCoef(ch) * fontSize;
10650
10679
  }, 0);
@@ -12241,7 +12270,16 @@ function createSVGElementConverterRegistry(session) {
12241
12270
  }
12242
12271
 
12243
12272
  function buildSVGLayers(es, options) {
12244
- var session = createSVGConversionSession(es, options);
12273
+ var currentPath;
12274
+ var warningSourceCollector = options.warningSourceCollector;
12275
+ var session = createSVGConversionSession(es, warningSourceCollector == null ? options : _extends({}, options, {
12276
+ emit: function emit(warning) {
12277
+ if (currentPath != null) {
12278
+ warningSourceCollector.set(warning, currentPath);
12279
+ }
12280
+ options.emit(warning);
12281
+ }
12282
+ }));
12245
12283
  var converters = createSVGElementConverterRegistry(session);
12246
12284
  for(var _iterator = _create_for_of_iterator_helper_loose(session.all), _step; !(_step = _iterator()).done;){
12247
12285
  var element = _step.value;
@@ -12249,6 +12287,9 @@ function buildSVGLayers(es, options) {
12249
12287
  var _element_node_tagName, _element_node;
12250
12288
  var tag = (_ref = (_element_node = element.node) == null ? void 0 : (_element_node_tagName = _element_node.tagName) == null ? void 0 : _element_node_tagName.toLowerCase()) != null ? _ref : '';
12251
12289
  var selector = describeElement(element);
12290
+ if (warningSourceCollector != null) {
12291
+ currentPath = buildElementTreePath(element.node);
12292
+ }
12252
12293
  if (isInInactiveSwitchBranch(element)) {
12253
12294
  continue;
12254
12295
  }
@@ -12314,6 +12355,8 @@ function parseSVGToIRScene(svgString, options) {
12314
12355
  value: scannedSmilDuration
12315
12356
  };
12316
12357
  var layerBuildOptions = {
12358
+ layerSourceCollector: options == null ? void 0 : options.layerSourceCollector,
12359
+ warningSourceCollector: options == null ? void 0 : options.warningSourceCollector,
12317
12360
  frameRate: frameRate,
12318
12361
  durationSeconds: effectiveDuration,
12319
12362
  emit: emit,
@@ -12493,6 +12536,8 @@ function parseSVGToIRWithPreservedData(source, options, collectors) {
12493
12536
  var svgString = readSVGString(source);
12494
12537
  var irScene = parseSVGToIRScene(svgString, _extends({}, options, {
12495
12538
  onWarning: emitWarning,
12539
+ layerSourceCollector: collectors == null ? void 0 : collectors.layerSourceCollector,
12540
+ warningSourceCollector: collectors == null ? void 0 : collectors.warningSourceCollector,
12496
12541
  textDataCollector: collectors == null ? void 0 : collectors.textDataByLayerId,
12497
12542
  paintAnimationsCollector: collectors == null ? void 0 : collectors.paintAnimationsByLayerId,
12498
12543
  shapeAnimationCollector: collectors == null ? void 0 : collectors.shapeAnimationsByLayerId
@@ -12668,7 +12713,8 @@ function collectLayerWarning(warnings, options, code, message, selector) {
12668
12713
  });
12669
12714
  warnings.push(warning);
12670
12715
  options.onWarning == null ? void 0 : options.onWarning.call(options, warning);
12671
- if (options.strict === true && code !== SVG2IR_WARNING_CODES.LAYERS_TEXT_BOUNDS_ESTIMATED) {
12716
+ var advisory = code === SVG2IR_WARNING_CODES.LAYERS_TEXT_BOUNDS_ESTIMATED || code === SVG2IR_WARNING_CODES.LAYERS_GRAPHIC_BAKED;
12717
+ if (options.strict === true && !advisory) {
12672
12718
  throw new SVGConverterError(SVG_CONVERTER_ERROR_CODES.LAYERS_CONVERSION_FAILED, warning.message, {
12673
12719
  stage: 'layers',
12674
12720
  sourceId: selector,
@@ -12712,21 +12758,36 @@ function transformBoxCorners(matrix, box) {
12712
12758
  transformPoint(matrix, box[0], box[3])
12713
12759
  ];
12714
12760
  }
12715
- function mapPointsToBBox(points) {
12761
+ function mapPointsToBBox(points, roundCoordinates) {
12762
+ if (roundCoordinates === void 0) roundCoordinates = true;
12716
12763
  var _Math, _Math1, _Math2, _Math3;
12717
- return [
12718
- roundPixel((_Math = Math).min.apply(_Math, [].concat(points.map(function(point) {
12764
+ var bbox = [
12765
+ (_Math = Math).min.apply(_Math, [].concat(points.map(function(point) {
12719
12766
  return point[0];
12720
- })))),
12721
- roundPixel((_Math1 = Math).min.apply(_Math1, [].concat(points.map(function(point) {
12767
+ }))),
12768
+ (_Math1 = Math).min.apply(_Math1, [].concat(points.map(function(point) {
12722
12769
  return point[1];
12723
- })))),
12724
- roundPixel((_Math2 = Math).max.apply(_Math2, [].concat(points.map(function(point) {
12770
+ }))),
12771
+ (_Math2 = Math).max.apply(_Math2, [].concat(points.map(function(point) {
12725
12772
  return point[0];
12726
- })))),
12727
- roundPixel((_Math3 = Math).max.apply(_Math3, [].concat(points.map(function(point) {
12773
+ }))),
12774
+ (_Math3 = Math).max.apply(_Math3, [].concat(points.map(function(point) {
12728
12775
  return point[1];
12729
- }))))
12776
+ })))
12777
+ ];
12778
+ if (bbox.some(function(value) {
12779
+ return !Number.isFinite(value);
12780
+ })) {
12781
+ throwInvalidLayerData('Non-finite pixel geometry.');
12782
+ }
12783
+ if (!roundCoordinates) {
12784
+ return bbox;
12785
+ }
12786
+ return [
12787
+ roundPixel(bbox[0]),
12788
+ roundPixel(bbox[1]),
12789
+ roundPixel(bbox[2]),
12790
+ roundPixel(bbox[3])
12730
12791
  ];
12731
12792
  }
12732
12793
  function roundPixel(value) {
@@ -12934,7 +12995,7 @@ function parseTextRuns(layer, font, preserved) {
12934
12995
  return spans.filter(function(span) {
12935
12996
  return span.text !== '' || span.newLine;
12936
12997
  }).map(function(span) {
12937
- var fontSize = span.fontSize == null || span.fontSize === '' ? base.fontSize : Number.parseInt(span.fontSize, 10);
12998
+ var fontSize = span.fontSize == null || span.fontSize === '' ? base.fontSize : Number.parseFloat(span.fontSize);
12938
12999
  if (!Number.isFinite(fontSize) || fontSize <= 0) {
12939
13000
  throwInvalidLayerData('Invalid text fragment font size.');
12940
13001
  }
@@ -12963,7 +13024,7 @@ function mapTextColor(color) {
12963
13024
  };
12964
13025
  }
12965
13026
 
12966
- function buildTextRunLayout(runs, family, spacing, content, size, conversionOptions, warnings, id, segmented) {
13027
+ function buildTextRunLayout(runs, family, spacing, content, size, conversionOptions, warnings, id, segmented, renderScale) {
12967
13028
  var _loop = function() {
12968
13029
  var run = _step.value;
12969
13030
  run.text.split('\n').forEach(function(text, index) {
@@ -12978,6 +13039,10 @@ function buildTextRunLayout(runs, family, spacing, content, size, conversionOpti
12978
13039
  });
12979
13040
  };
12980
13041
  if (segmented === void 0) segmented = false;
13042
+ if (renderScale === void 0) renderScale = [
13043
+ 1,
13044
+ 1
13045
+ ];
12981
13046
  var _Math;
12982
13047
  var rows = [
12983
13048
  []
@@ -12990,33 +13055,44 @@ function buildTextRunLayout(runs, family, spacing, content, size, conversionOpti
12990
13055
  }).map(function(row) {
12991
13056
  var _Math, _Math1;
12992
13057
  var parts = row.map(function(run) {
12993
- // 分段文字使用统一参考字号度量字宽和字体边界,再按片段字号缩放。
13058
+ // 基线沿用参考字号指标,字宽按实际输出字号单独测量。
12994
13059
  var measurementSize = segmented ? 10 : run.fontSize;
12995
13060
  var scale = run.fontSize / measurementSize;
12996
- var font = (run.italic ? 'italic' : 'normal') + " " + (run.bold ? 'bold' : 'normal') + " " + measurementSize + "px" + (' "' + family + '"');
13061
+ var weight = run.bold ? 'bold' : 'normal';
13062
+ var style = run.italic ? 'italic' : 'normal';
13063
+ var font = buildCanvasFontDesc(measurementSize, family, weight, style);
12997
13064
  var metrics = conversionOptions.measureText == null ? void 0 : conversionOptions.measureText.call(conversionOptions, font, segmented ? 'x' : run.text);
12998
- var chunks = segmented ? run.text.split('') : [
12999
- run.text
13000
- ];
13001
- var advance = 0;
13002
- for(var _iterator = _create_for_of_iterator_helper_loose(chunks), _step; !(_step = _iterator()).done;){
13003
- var chunk = _step.value;
13004
- var width = segmented ? conversionOptions.measureText == null ? void 0 : conversionOptions.measureText.call(conversionOptions, font, chunk).width : metrics == null ? void 0 : metrics.width;
13005
- var valid = width != null && Number.isFinite(width) && width >= 0;
13006
- estimated || (estimated = !valid);
13007
- advance += valid ? width : Array.from(chunk).length * measurementSize * 0.6;
13008
- }
13009
- var characterCount = segmented ? run.text.length : Array.from(run.text).length;
13010
- var width1 = advance * scale + Math.max(0, characterCount - 1) * spacing;
13011
- var ascent = (metrics == null ? void 0 : metrics.fontBoundingBoxAscent) == null ? run.fontSize * 0.8 : metrics.fontBoundingBoxAscent * scale;
13012
- var descent = (metrics == null ? void 0 : metrics.fontBoundingBoxDescent) == null ? run.fontSize * 0.2 : metrics.fontBoundingBoxDescent * scale;
13065
+ var characters = Array.from(run.text);
13066
+ // 片段协议不输出额外字重和斜体,测宽使用同样的普通样式。
13067
+ var widthFontSize = run.fontSize * renderScale[1];
13068
+ var widthFont = buildCanvasFontDesc(widthFontSize, family, 'normal', 'normal');
13069
+ var measureWidth = function measureWidth(text) {
13070
+ var width = conversionOptions.measureText == null ? void 0 : conversionOptions.measureText.call(conversionOptions, widthFont, text).width;
13071
+ if (width != null && Number.isFinite(width) && width >= 0) {
13072
+ return width;
13073
+ }
13074
+ estimated = true;
13075
+ return estimateTextWidth(text, widthFontSize, 0, undefined, family, 'normal', 'normal');
13076
+ };
13077
+ // 字距和字宽交替累加,保持与 Artis 逐字测宽的计算顺序一致。
13078
+ var renderedWidth = 0;
13079
+ characters.forEach(function(character, index) {
13080
+ if (index > 0) {
13081
+ renderedWidth += spacing * renderScale[0];
13082
+ }
13083
+ renderedWidth += measureWidth(character);
13084
+ });
13085
+ var width = renderedWidth / renderScale[0];
13086
+ var fallback = resolveFontMetrics(undefined, family, weight, style, run.fontSize);
13087
+ var ascent = (metrics == null ? void 0 : metrics.fontBoundingBoxAscent) == null ? fallback.asc : metrics.fontBoundingBoxAscent * scale;
13088
+ var descent = (metrics == null ? void 0 : metrics.fontBoundingBoxDescent) == null ? fallback.desc : metrics.fontBoundingBoxDescent * scale;
13013
13089
  estimated || (estimated = (metrics == null ? void 0 : metrics.fontBoundingBoxAscent) == null || metrics.fontBoundingBoxDescent == null);
13014
- if (!Number.isFinite(width1) || width1 < 0 || !Number.isFinite(ascent) || !Number.isFinite(descent)) {
13090
+ if (!Number.isFinite(width) || width < 0 || !Number.isFinite(ascent) || !Number.isFinite(descent)) {
13015
13091
  throwInvalidLayerData('Text measurement returned invalid metrics.');
13016
13092
  }
13017
13093
  return {
13018
13094
  run: run,
13019
- width: width1,
13095
+ width: width,
13020
13096
  ascent: ascent,
13021
13097
  descent: descent
13022
13098
  };
@@ -13129,7 +13205,10 @@ function convertIRTextLayer(layer, state, session, id) {
13129
13205
  var positioned = buildTextRunLayout(runs, font.family, layer.content.letterSpacing, layer.content, [
13130
13206
  bounds.width,
13131
13207
  height
13132
- ], options, warnings, id, preserved != null);
13208
+ ], options, warnings, id, preserved != null, [
13209
+ scaleX,
13210
+ scaleY
13211
+ ]);
13133
13212
  if (positioned.length === 0) {
13134
13213
  return undefined;
13135
13214
  }
@@ -13143,25 +13222,25 @@ function convertIRTextLayer(layer, state, session, id) {
13143
13222
  part.box[3] + centerY
13144
13223
  ]);
13145
13224
  });
13146
- var bbox = mapPointsToBBox(polygons.flat());
13147
- var rotation = roundPixel(Math.atan2(matrix.b, matrix.a) * 180 / Math.PI);
13225
+ var bbox = mapPointsToBBox(polygons.flat(), false);
13226
+ var rotation = Math.atan2(matrix.b, matrix.a) * 180 / Math.PI;
13148
13227
  var fragments = positioned.map(function(part, index) {
13149
13228
  var polygon = polygons[index].map(function(point) {
13150
13229
  return [
13151
- roundPixel(point[0] - bbox[0]),
13152
- roundPixel(point[1] - bbox[1])
13230
+ point[0] - bbox[0],
13231
+ point[1] - bbox[1]
13153
13232
  ];
13154
13233
  });
13155
13234
  return {
13156
13235
  content: part.run.text,
13157
- bbox: mapPointsToBBox(polygon),
13236
+ bbox: mapPointsToBBox(polygon, false),
13158
13237
  polygon: polygon,
13159
- font_family: font.family,
13160
- font_size: roundPixel(part.run.fontSize * scaleY),
13238
+ font_family: normalizeFontFamilyName(font.family),
13239
+ font_size: part.run.fontSize * scaleY,
13161
13240
  color: part.run.color,
13162
- letter_spacing: roundPixel(layer.content.letterSpacing * scaleX),
13241
+ letter_spacing: layer.content.letterSpacing * scaleX,
13163
13242
  direction: 'horizontal',
13164
- rotation: rotation
13243
+ rotation: rotation === 0 ? 0 : rotation
13165
13244
  };
13166
13245
  });
13167
13246
  return {
@@ -13200,7 +13279,43 @@ function createLayerConverterRegistry(session) {
13200
13279
  ]);
13201
13280
  }
13202
13281
 
13282
+ /** 完全覆盖图片的直边矩形 mask 不改变可见内容。 */ function maskCoversImage(mask, bounds) {
13283
+ var _Math, _Math1, _Math2, _Math3;
13284
+ var path = mask.path;
13285
+ var epsilon = 1e-6;
13286
+ if (mask.mode === 'subtract' || mask.inverted === true || !path.closed || path.points.length !== 4) {
13287
+ return false;
13288
+ }
13289
+ if (path.inTangents.length !== 4 || path.outTangents.length !== 4 || [].concat(path.inTangents, path.outTangents).some(function(tangent) {
13290
+ return tangent.x !== 0 || tangent.y !== 0;
13291
+ })) {
13292
+ return false;
13293
+ }
13294
+ var straightEdges = path.points.every(function(point, index) {
13295
+ var next = path.points[(index + 1) % 4];
13296
+ var opposite = path.points[(index + 2) % 4];
13297
+ var dx = Math.abs(next.x - point.x);
13298
+ var dy = Math.abs(next.y - point.y);
13299
+ return Number.isFinite(point.x) && Number.isFinite(point.y) && Math.abs(opposite.x - point.x) > epsilon && Math.abs(opposite.y - point.y) > epsilon && (dx <= epsilon && dy > epsilon || dy <= epsilon && dx > epsilon);
13300
+ });
13301
+ if (!straightEdges) {
13302
+ return false;
13303
+ }
13304
+ var xs = path.points.map(function(point) {
13305
+ return point.x;
13306
+ });
13307
+ var ys = path.points.map(function(point) {
13308
+ return point.y;
13309
+ });
13310
+ var left = (_Math = Math).min.apply(_Math, [].concat(xs));
13311
+ var right = (_Math1 = Math).max.apply(_Math1, [].concat(xs));
13312
+ var top = (_Math2 = Math).min.apply(_Math2, [].concat(ys));
13313
+ var bottom = (_Math3 = Math).max.apply(_Math3, [].concat(ys));
13314
+ return bounds.width > 0 && bounds.height > 0 && left <= bounds.x + epsilon && right >= bounds.x + bounds.width - epsilon && top <= bounds.y + epsilon && bottom >= bounds.y + bounds.height - epsilon;
13315
+ }
13316
+
13203
13317
  function resolveIRVisualState(layer, session) {
13318
+ var _layer_masks;
13204
13319
  if (!layer.visible) {
13205
13320
  return undefined;
13206
13321
  }
@@ -13208,19 +13323,22 @@ function resolveIRVisualState(layer, session) {
13208
13323
  if (!state.visible || state.opacity <= 0) {
13209
13324
  return undefined;
13210
13325
  }
13211
- if (layer.mask != null || layer.matte != null) {
13326
+ var unsupportedMask = ((_layer_masks = layer.masks) != null ? _layer_masks : []).some(function(mask) {
13327
+ return layer.type !== 'image' || !maskCoversImage(mask, layer.localBounds);
13328
+ });
13329
+ if (unsupportedMask || layer.matte != null) {
13212
13330
  throwUnsupportedLayerFeature('Mask or clipping is not supported by the flat layer protocol.');
13213
13331
  }
13214
13332
  if (Math.abs(state.opacity - 1) > 1e-6) {
13215
13333
  throwUnsupportedLayerFeature('Layer opacity cannot be expressed by the target protocol.');
13216
13334
  }
13217
13335
  if (layer.blendMode != null && layer.blendMode !== animationIr.IRBlendMode.Normal) {
13218
- throwUnsupportedLayerFeature('Non-default blending cannot be expressed by the target protocol.');
13336
+ collectLayerWarning(session.warnings, session.options, SVG2IR_WARNING_CODES.LAYERS_BLEND_MODE_DOWNGRADED, 'Blend mode "' + String(layer.blendMode) + '" was downgraded to "normal"; the layer is retained.', layer.id);
13219
13337
  }
13220
13338
  return state;
13221
13339
  }
13222
13340
 
13223
- function buildIRStaticLayers(session) {
13341
+ function buildIRStaticLayers(session, sourceIds) {
13224
13342
  var composition = session.composition, maskSourceIds = session.maskSourceIds, options = session.options, warnings = session.warnings;
13225
13343
  var registry = createLayerConverterRegistry(session);
13226
13344
  var result = [];
@@ -13245,6 +13363,7 @@ function buildIRStaticLayers(session) {
13245
13363
  var converted = converter.convert(layer, state, converter.layerType + "_" + String(index).padStart(4, '0'));
13246
13364
  if (converted != null) {
13247
13365
  result.push(converted);
13366
+ sourceIds == null ? void 0 : sourceIds.set(converted, layer.id);
13248
13367
  layerCounts.set(converter.layerType, index);
13249
13368
  }
13250
13369
  } catch (error) {
@@ -13257,9 +13376,9 @@ function buildIRStaticLayers(session) {
13257
13376
  return result;
13258
13377
  }
13259
13378
 
13260
- function assembleSVGStaticLayers(scene, options, warnings, preservedData) {
13379
+ function assembleSVGStaticLayers(scene, options, warnings, preservedData, sourceIds) {
13261
13380
  var session = buildLayerConversionSession(scene, options, warnings, preservedData);
13262
- var data = buildIRStaticLayers(session);
13381
+ var data = buildIRStaticLayers(session, sourceIds);
13263
13382
  var composition = session.composition;
13264
13383
  if (composition.backgroundColor != null) {
13265
13384
  collectLayerWarning(warnings, options, SVG2IR_WARNING_CODES.LAYERS_UNSUPPORTED_TYPE, 'Composition background color is not an image or text layer.');
@@ -13272,6 +13391,1035 @@ function assembleSVGStaticLayers(scene, options, warnings, preservedData) {
13272
13391
  data: data
13273
13392
  };
13274
13393
  }
13394
+ /** Replace baked sources, combine native and raster layers in painter order, then report final diagnostics. */ function assembleSVGLayers(input) {
13395
+ var _warnings, _ordered;
13396
+ var _input_context = input.context, scene = _input_context.ir, contextWarnings = _input_context.warnings, preservedData = _input_context.preservedData, layerSources = _input_context.layerSources, warningSources = _input_context.warningSources;
13397
+ var options = input.options, baking = input.baking;
13398
+ var warnings = contextWarnings.filter(function(warning) {
13399
+ return !baking.resolvesWarning(warning, warningSources.get(warning));
13400
+ });
13401
+ var composition = adapter.getIRSceneEntryComposition(scene);
13402
+ var nativeScene = _extends({}, scene, {
13403
+ compositions: scene.compositions.map(function(candidate) {
13404
+ return candidate === composition ? _extends({}, candidate, {
13405
+ layers: candidate.layers.filter(function(layer) {
13406
+ return !baking.replacesSource(layerSources.get(layer.id));
13407
+ })
13408
+ }) : candidate;
13409
+ })
13410
+ });
13411
+ var sourceIds = new Map();
13412
+ (_warnings = warnings).push.apply(_warnings, [].concat(baking.warnings));
13413
+ var native = assembleSVGStaticLayers(nativeScene, _extends({}, options, {
13414
+ strict: false,
13415
+ onWarning: undefined
13416
+ }), warnings, preservedData, sourceIds);
13417
+ var ordered = native.data.map(function(layer) {
13418
+ var _layerSources_get, _sourceIds_get;
13419
+ return {
13420
+ path: (_layerSources_get = layerSources.get((_sourceIds_get = sourceIds.get(layer)) != null ? _sourceIds_get : '')) != null ? _layerSources_get : '',
13421
+ layer: layer
13422
+ };
13423
+ });
13424
+ (_ordered = ordered).push.apply(_ordered, [].concat(baking.layers));
13425
+ ordered.sort(function(left, right) {
13426
+ return comparePaths(left.path, right.path);
13427
+ });
13428
+ var counts = {
13429
+ image: 0,
13430
+ text: 0
13431
+ };
13432
+ var data = ordered.map(function(param) {
13433
+ var layer = param.layer;
13434
+ return _extends({}, layer, {
13435
+ id: layer.type + "_" + String(++counts[layer.type]).padStart(4, '0')
13436
+ });
13437
+ });
13438
+ for(var _iterator = _create_for_of_iterator_helper_loose(warnings), _step; !(_step = _iterator()).done;){
13439
+ var warning = _step.value;
13440
+ options.onWarning == null ? void 0 : options.onWarning.call(options, warning);
13441
+ if (options.strict === true) {
13442
+ var message = warning.message.replace(/^\[svg2ge:layers\] /, '');
13443
+ collectLayerWarning([], _extends({}, options, {
13444
+ onWarning: undefined
13445
+ }), warning.code, message, warning.elementSelector);
13446
+ }
13447
+ }
13448
+ return {
13449
+ size: native.size,
13450
+ data: data,
13451
+ warnings: warnings
13452
+ };
13453
+ }
13454
+ function comparePaths(left, right) {
13455
+ var a = left.split('/').map(Number);
13456
+ var b = right.split('/').map(Number);
13457
+ for(var index = 0; index < Math.min(a.length, b.length); index++){
13458
+ if (a[index] !== b[index]) {
13459
+ return a[index] - b[index];
13460
+ }
13461
+ }
13462
+ return a.length - b.length;
13463
+ }
13464
+
13465
+ var animatedElements = new Set([
13466
+ 'animate',
13467
+ 'animatetransform',
13468
+ 'animatemotion',
13469
+ 'set'
13470
+ ]);
13471
+ var declarations$1 = new Set([
13472
+ 'defs',
13473
+ 'style',
13474
+ 'title',
13475
+ 'desc',
13476
+ 'metadata',
13477
+ 'symbol',
13478
+ 'clippath',
13479
+ 'mask',
13480
+ 'filter',
13481
+ 'lineargradient',
13482
+ 'radialgradient',
13483
+ 'pattern',
13484
+ 'marker'
13485
+ ]);
13486
+ /** Preserve selector context until styles are frozen, then isolate the requested paint subtree. */ function prepareSVGSnapshot(source, path, size, inspect) {
13487
+ var parsed = new DOMParser().parseFromString(source, 'image/svg+xml');
13488
+ if (parsed.querySelector('parsererror') != null) {
13489
+ throw new Error('Invalid SVG document.');
13490
+ }
13491
+ var root = parsed.documentElement;
13492
+ var elements = [].concat([
13493
+ root
13494
+ ], Array.from(root.querySelectorAll('*')));
13495
+ var selected = elements.find(function(element) {
13496
+ return buildElementTreePath(element) === path;
13497
+ });
13498
+ if (selected == null) {
13499
+ throw new Error('The graphic source element could not be located.');
13500
+ }
13501
+ if (root.querySelector('script, foreignObject') != null) {
13502
+ throw new Error('Scripts and foreignObject are outside static graphic baking support.');
13503
+ }
13504
+ if (Array.from(root.querySelectorAll('style')).some(function(element) {
13505
+ var _element_textContent;
13506
+ return /@import|@font-face/i.test((_element_textContent = element.textContent) != null ? _element_textContent : '');
13507
+ })) {
13508
+ throw new Error('External stylesheets and fonts require explicit resource preparation.');
13509
+ }
13510
+ for(var _iterator = _create_for_of_iterator_helper_loose(elements), _step; !(_step = _iterator()).done;){
13511
+ var element = _step.value;
13512
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(element.attributes)), _step1; !(_step1 = _iterator1()).done;){
13513
+ var attribute = _step1.value;
13514
+ if (/^on/i.test(attribute.name)) {
13515
+ element.removeAttributeNode(attribute);
13516
+ }
13517
+ }
13518
+ }
13519
+ var frame = document.createElement('iframe');
13520
+ frame.setAttribute('sandbox', 'allow-same-origin');
13521
+ frame.style.cssText = "position:fixed;left:-100000px;top:0;width:" + size[0] + "px;height:" + size[1] + "px;border:0;";
13522
+ document.body.appendChild(frame);
13523
+ try {
13524
+ var _loop = function() {
13525
+ var element = _step3.value;
13526
+ var _element_getAttribute;
13527
+ var computed = frameWindow.getComputedStyle(element);
13528
+ var inside = target.contains(element);
13529
+ var ancestor = element !== target && element.contains(target);
13530
+ if ((inside || ancestor) && (computed.animationName !== 'none' || hasAnimationChildren(element))) {
13531
+ throw new Error('Animated graphics require an explicit sampling policy.');
13532
+ }
13533
+ // Freezing inherited defaults on a definition changes <use> instance inheritance.
13534
+ // Freeze only authored declarations, after matching selectors in the intact source tree.
13535
+ var authored = frameDocument.createElement('div').style;
13536
+ authored.cssText = (_element_getAttribute = element.getAttribute('style')) != null ? _element_getAttribute : '';
13537
+ var names = new Set(Array.from(authored));
13538
+ for(var _iterator = _create_for_of_iterator_helper_loose(styleRules), _step; !(_step = _iterator()).done;){
13539
+ var rule = _step.value;
13540
+ if (element.matches(rule.selectorText)) {
13541
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(rule.style)), _step1; !(_step1 = _iterator1()).done;){
13542
+ var name = _step1.value;
13543
+ names.add(name);
13544
+ }
13545
+ }
13546
+ }
13547
+ var properties = Array.from(names, function(name) {
13548
+ var value = computed.getPropertyValue(name);
13549
+ value = value.replace(/url\(["']?([^)'"\s]+)["']?\)/g, function(_match, url) {
13550
+ return 'url("' + normalizeReference(url) + '")';
13551
+ });
13552
+ return name + ":" + value + " !important;";
13553
+ });
13554
+ var isTemplate = templateRoots.some(function(template) {
13555
+ return template.contains(element);
13556
+ });
13557
+ frozenStyles.push(isTemplate ? null : properties.join(''));
13558
+ };
13559
+ var frameDocument = frame.contentDocument;
13560
+ var frameWindow = frame.contentWindow;
13561
+ if (frameDocument == null || frameWindow == null) {
13562
+ throw new Error('Unable to create isolated SVG context.');
13563
+ }
13564
+ frameDocument.body.style.cssText = 'margin:0;';
13565
+ var mounted = frameDocument.importNode(root, true);
13566
+ mounted.setAttribute('width', String(size[0]));
13567
+ mounted.setAttribute('height', String(size[1]));
13568
+ frameDocument.body.appendChild(mounted);
13569
+ var mountedElements = [].concat([
13570
+ mounted
13571
+ ], Array.from(mounted.querySelectorAll('*')));
13572
+ var selectedIndex = elements.indexOf(selected);
13573
+ var target = mountedElements[selectedIndex];
13574
+ var normalizeReference = function normalizeReference(url) {
13575
+ if (url.startsWith('#')) {
13576
+ return url;
13577
+ }
13578
+ var hash = url.indexOf('#');
13579
+ if (hash >= 0 && url.slice(0, hash) === frameDocument.baseURI.split('#')[0]) {
13580
+ return url.slice(hash);
13581
+ }
13582
+ throw new Error('External paint resources require explicit resource preparation.');
13583
+ };
13584
+ var frozenStyles = [];
13585
+ var templateRoots = Array.from(mounted.querySelectorAll('use')).flatMap(function(element) {
13586
+ var _ref, _element_getAttribute;
13587
+ var href = (_ref = (_element_getAttribute = element.getAttribute('href')) != null ? _element_getAttribute : element.getAttribute('xlink:href')) != null ? _ref : '';
13588
+ var template = href.startsWith('#') ? mountedElements.find(function(candidate) {
13589
+ return candidate.id === href.slice(1);
13590
+ }) : null;
13591
+ return template == null ? [] : [
13592
+ template
13593
+ ];
13594
+ });
13595
+ var styleRules = [];
13596
+ var collectRules = function collectRules1(rules) {
13597
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(rules)), _step; !(_step = _iterator()).done;){
13598
+ var rule = _step.value;
13599
+ if (isStyleRule$2(rule)) {
13600
+ styleRules.push(rule);
13601
+ } else if (hasNestedRules$1(rule)) {
13602
+ if (isMediaRule(rule) && !frameWindow.matchMedia(rule.conditionText).matches) {
13603
+ continue;
13604
+ }
13605
+ collectRules(rule.cssRules);
13606
+ }
13607
+ }
13608
+ };
13609
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(Array.from(frameDocument.styleSheets)), _step2; !(_step2 = _iterator2()).done;){
13610
+ var sheet = _step2.value;
13611
+ collectRules(sheet.cssRules);
13612
+ }
13613
+ for(var _iterator3 = _create_for_of_iterator_helper_loose(mountedElements), _step3; !(_step3 = _iterator3()).done;)_loop();
13614
+ for(var index = 0; index < mountedElements.length; index++){
13615
+ var style = frozenStyles[index];
13616
+ if (style != null) {
13617
+ mountedElements[index].setAttribute('style', style);
13618
+ }
13619
+ }
13620
+ var byId = new Map(mountedElements.filter(function(element) {
13621
+ return element.id !== '';
13622
+ }).map(function(element) {
13623
+ return [
13624
+ element.id,
13625
+ element
13626
+ ];
13627
+ }));
13628
+ var seen = new Set();
13629
+ var checkDependencies = function checkDependencies1(element) {
13630
+ if (seen.has(element)) {
13631
+ return;
13632
+ }
13633
+ seen.add(element);
13634
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(element.attributes)), _step; !(_step = _iterator()).done;){
13635
+ var attribute = _step.value;
13636
+ if (attribute.localName === 'href' && element.tagName.toLowerCase() === 'a') {
13637
+ continue;
13638
+ }
13639
+ if (attribute.localName === 'href' && !attribute.value.startsWith('#') && !([
13640
+ 'image',
13641
+ 'feimage'
13642
+ ].includes(element.tagName.toLowerCase()) && /^data:image\//i.test(attribute.value))) {
13643
+ throw new Error('External SVG references require explicit resource preparation.');
13644
+ }
13645
+ var normalized = attribute.value.replace(/url\(\s*["']?([^)'"\s]+)["']?\s*\)/g, function(_match, url) {
13646
+ return 'url("' + normalizeReference(url) + '")';
13647
+ });
13648
+ var ids = Array.from(normalized.matchAll(/url\(["']?#([^)'"\s]+)["']?\)/g), function(match) {
13649
+ return match[1];
13650
+ });
13651
+ if (normalized !== attribute.value) {
13652
+ element.setAttribute(attribute.name, normalized);
13653
+ }
13654
+ if (attribute.localName === 'href' && attribute.value.startsWith('#')) {
13655
+ ids.push(attribute.value.slice(1));
13656
+ }
13657
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(ids), _step1; !(_step1 = _iterator1()).done;){
13658
+ var id = _step1.value;
13659
+ var dependency = byId.get(id);
13660
+ if (dependency == null) {
13661
+ throw new Error("Missing SVG reference: #" + id + ".");
13662
+ }
13663
+ checkDependencies(dependency);
13664
+ }
13665
+ }
13666
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(Array.from(element.children)), _step2; !(_step2 = _iterator2()).done;){
13667
+ var child = _step2.value;
13668
+ if (!declarations$1.has(child.tagName.toLowerCase())) {
13669
+ checkDependencies(child);
13670
+ }
13671
+ }
13672
+ };
13673
+ checkDependencies(target);
13674
+ for(var _iterator4 = _create_for_of_iterator_helper_loose(seen), _step4; !(_step4 = _iterator4()).done;){
13675
+ var dependency = _step4.value;
13676
+ if (frameWindow.getComputedStyle(dependency).animationName !== 'none' || hasAnimationChildren(dependency)) {
13677
+ throw new Error('Animated graphics require an explicit sampling policy.');
13678
+ }
13679
+ }
13680
+ inspect == null ? void 0 : inspect({
13681
+ root: mounted,
13682
+ target: target,
13683
+ elements: mountedElements,
13684
+ dependencies: seen,
13685
+ readStyle: function readStyle(element) {
13686
+ return frameWindow.getComputedStyle(element);
13687
+ }
13688
+ });
13689
+ var isolate = function isolate1(element) {
13690
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(element.children)), _step; !(_step = _iterator()).done;){
13691
+ var child = _step.value;
13692
+ var tag = child.tagName.toLowerCase();
13693
+ if (declarations$1.has(tag) || child === target || target.contains(child)) {
13694
+ continue;
13695
+ }
13696
+ if (child.contains(target)) {
13697
+ isolate(child);
13698
+ } else {
13699
+ var definitions = frameDocument.createElementNS('http://www.w3.org/2000/svg', 'defs');
13700
+ child.replaceWith(definitions);
13701
+ definitions.appendChild(child);
13702
+ }
13703
+ }
13704
+ };
13705
+ if (target !== mounted) {
13706
+ isolate(mounted);
13707
+ }
13708
+ return new XMLSerializer().serializeToString(mounted);
13709
+ } finally{
13710
+ frame.remove();
13711
+ }
13712
+ }
13713
+ /** Only animations attached to this element reject its own bake scope, not unrelated subtrees. */ function hasAnimationChildren(element) {
13714
+ return Array.from(element.children).some(function(child) {
13715
+ return animatedElements.has(child.tagName.toLowerCase());
13716
+ });
13717
+ }
13718
+ function isStyleRule$2(rule) {
13719
+ return rule.type === 1;
13720
+ }
13721
+ function hasNestedRules$1(rule) {
13722
+ return 'cssRules' in rule;
13723
+ }
13724
+ function isMediaRule(rule) {
13725
+ return rule.type === 4;
13726
+ }
13727
+
13728
+ /** Render an SVG subtree as a cropped PNG, or return null if it has no visible pixels. */ function rasterizeSVG(source, path, size, scale, inspect) {
13729
+ if (scale === void 0) scale = 2;
13730
+ return _async_to_generator(function() {
13731
+ var snapshot, canvas;
13732
+ return _ts_generator(this, function(_state) {
13733
+ switch(_state.label){
13734
+ case 0:
13735
+ if (!Number.isFinite(scale) || scale <= 0) {
13736
+ throw new RangeError('rasterScale must be finite and positive.');
13737
+ }
13738
+ if (Math.ceil(size[0] * scale) * Math.ceil(size[1] * scale) > 16777216) {
13739
+ throw new RangeError('SVG rasterization exceeds the 16 megapixel working limit; reduce rasterScale.');
13740
+ }
13741
+ snapshot = prepareSVGSnapshot(source, path, size, inspect);
13742
+ return [
13743
+ 4,
13744
+ renderSVG(snapshot, size, scale)
13745
+ ];
13746
+ case 1:
13747
+ canvas = _state.sent();
13748
+ return [
13749
+ 2,
13750
+ cropRasterImage(canvas, scale)
13751
+ ];
13752
+ }
13753
+ });
13754
+ })();
13755
+ }
13756
+ /** No DOM access at module initialization: the Node entry also imports this module. */ function canRasterizeSVG() {
13757
+ return typeof window !== 'undefined' && typeof document !== 'undefined' && typeof window.HTMLCanvasElement === 'function' && typeof window.Image === 'function' && typeof window.getComputedStyle === 'function';
13758
+ }
13759
+ function renderSVG(svg, size, scale) {
13760
+ return _async_to_generator(function() {
13761
+ var canvas, context, image, url;
13762
+ return _ts_generator(this, function(_state) {
13763
+ switch(_state.label){
13764
+ case 0:
13765
+ canvas = document.createElement('canvas');
13766
+ canvas.width = Math.ceil(size[0] * scale);
13767
+ canvas.height = Math.ceil(size[1] * scale);
13768
+ context = canvas.getContext('2d');
13769
+ if (context == null) {
13770
+ throw new Error('A 2D canvas context is required for SVG rasterization.');
13771
+ }
13772
+ image = new Image();
13773
+ url = URL.createObjectURL(new Blob([
13774
+ svg
13775
+ ], {
13776
+ type: 'image/svg+xml'
13777
+ }));
13778
+ _state.label = 1;
13779
+ case 1:
13780
+ _state.trys.push([
13781
+ 1,
13782
+ ,
13783
+ 3,
13784
+ 4
13785
+ ]);
13786
+ return [
13787
+ 4,
13788
+ new Promise(function(resolve, reject) {
13789
+ image.onload = function() {
13790
+ return resolve();
13791
+ };
13792
+ image.onerror = function() {
13793
+ return reject(new Error('The prepared SVG could not be decoded.'));
13794
+ };
13795
+ image.src = url;
13796
+ })
13797
+ ];
13798
+ case 2:
13799
+ _state.sent();
13800
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
13801
+ return [
13802
+ 2,
13803
+ canvas
13804
+ ];
13805
+ case 3:
13806
+ URL.revokeObjectURL(url);
13807
+ return [
13808
+ 7
13809
+ ];
13810
+ case 4:
13811
+ return [
13812
+ 2
13813
+ ];
13814
+ }
13815
+ });
13816
+ })();
13817
+ }
13818
+ /** Trim transparent pixels after rendering, retaining strokes, blur and filter extents. */ function cropRasterImage(canvas, scale) {
13819
+ var context = canvas.getContext('2d');
13820
+ if (context == null) {
13821
+ throw new Error('A 2D canvas context is required for SVG rasterization.');
13822
+ }
13823
+ var data = context.getImageData(0, 0, canvas.width, canvas.height).data;
13824
+ var left = canvas.width;
13825
+ var top = canvas.height;
13826
+ var right = 0;
13827
+ var bottom = 0;
13828
+ for(var y = 0; y < canvas.height; y++){
13829
+ for(var x = 0; x < canvas.width; x++){
13830
+ if (data[(y * canvas.width + x) * 4 + 3] === 0) {
13831
+ continue;
13832
+ }
13833
+ left = Math.min(left, x);
13834
+ top = Math.min(top, y);
13835
+ right = Math.max(right, x + 1);
13836
+ bottom = Math.max(bottom, y + 1);
13837
+ }
13838
+ }
13839
+ if (right <= left || bottom <= top) {
13840
+ return null;
13841
+ }
13842
+ var cropped = document.createElement('canvas');
13843
+ cropped.width = right - left;
13844
+ cropped.height = bottom - top;
13845
+ var croppedContext = cropped.getContext('2d');
13846
+ if (croppedContext == null) {
13847
+ throw new Error('A 2D canvas context is required for SVG rasterization.');
13848
+ }
13849
+ croppedContext.drawImage(canvas, left, top, cropped.width, cropped.height, 0, 0, cropped.width, cropped.height);
13850
+ return {
13851
+ url: cropped.toDataURL('image/png'),
13852
+ bbox: [
13853
+ left / scale,
13854
+ top / scale,
13855
+ right / scale,
13856
+ bottom / scale
13857
+ ]
13858
+ };
13859
+ }
13860
+
13861
+ var normalValues = new Set([
13862
+ 'normal',
13863
+ 'initial',
13864
+ 'inherit',
13865
+ 'unset',
13866
+ 'revert',
13867
+ 'revert-layer'
13868
+ ]);
13869
+ /** Replace non-normal mix-blend-mode declarations with normal and report each downgrade. */ function normalizeLayerBlending(source) {
13870
+ var _loop = function() {
13871
+ var element = _step.value;
13872
+ var _element_getAttribute;
13873
+ var _readPresentationAttribute;
13874
+ var tag = element.tagName.toLowerCase();
13875
+ var id = (_element_getAttribute = element.getAttribute('id')) != null ? _element_getAttribute : '';
13876
+ var selector = id === '' ? tag : tag + "#" + id;
13877
+ var mode = (_readPresentationAttribute = readPresentationAttribute(element, 'mix-blend-mode')) == null ? void 0 : _readPresentationAttribute.replace(/\/\*[\s\S]*?\*\//g, '').trim();
13878
+ if (mode != null && !normalValues.has(mode.toLowerCase())) {
13879
+ downgrades.push({
13880
+ mode: mode,
13881
+ selector: selector
13882
+ });
13883
+ }
13884
+ var style = element.getAttribute('style');
13885
+ if (style != null) {
13886
+ var normalized = normalizeBlendDeclarations(style);
13887
+ if (normalized !== style) {
13888
+ element.setAttribute('style', normalized);
13889
+ changed = true;
13890
+ }
13891
+ }
13892
+ var attribute = element.getAttribute('mix-blend-mode');
13893
+ if (attribute != null && !normalValues.has(attribute.trim().toLowerCase())) {
13894
+ element.setAttribute('mix-blend-mode', 'normal');
13895
+ changed = true;
13896
+ }
13897
+ if (tag === 'style') {
13898
+ var _element_textContent;
13899
+ var text = (_element_textContent = element.textContent) != null ? _element_textContent : '';
13900
+ var normalized1 = normalizeBlendDeclarations(text, function(value) {
13901
+ return downgrades.push({
13902
+ mode: value,
13903
+ selector: selector
13904
+ });
13905
+ });
13906
+ if (normalized1 !== text) {
13907
+ element.textContent = normalized1;
13908
+ changed = true;
13909
+ }
13910
+ }
13911
+ };
13912
+ var svg = svg_js.SVG(source);
13913
+ var downgrades = [];
13914
+ var changed = false;
13915
+ for(var _iterator = _create_for_of_iterator_helper_loose([].concat([
13916
+ svg.node
13917
+ ], Array.from(svg.node.querySelectorAll('*')))), _step; !(_step = _iterator()).done;)_loop();
13918
+ return {
13919
+ source: changed ? svg.svg() : source,
13920
+ downgrades: downgrades
13921
+ };
13922
+ }
13923
+ /** Match declaration boundaries without changing strings, comments or function arguments. */ function normalizeBlendDeclarations(source, onDowngrade) {
13924
+ var replacements = [];
13925
+ var start = 0;
13926
+ var colon = -1;
13927
+ var parentheses = 0;
13928
+ var quote;
13929
+ var comment = false;
13930
+ var finish = function finish(end) {
13931
+ if (colon < start) {
13932
+ return;
13933
+ }
13934
+ var name = source.slice(start, colon).replace(/\/\*[\s\S]*?\*\//g, '').trim().toLowerCase();
13935
+ if (name !== 'mix-blend-mode') {
13936
+ return;
13937
+ }
13938
+ var value = source.slice(colon + 1, end).replace(/\/\*[\s\S]*?\*\//g, '').trim();
13939
+ var mode = value.replace(/\s*!important\s*$/i, '').trim();
13940
+ if (mode === '' || normalValues.has(mode.toLowerCase())) {
13941
+ return;
13942
+ }
13943
+ onDowngrade == null ? void 0 : onDowngrade(mode);
13944
+ replacements.push({
13945
+ start: colon + 1,
13946
+ end: end,
13947
+ value: /!important\s*$/i.test(value) ? ' normal !important' : ' normal'
13948
+ });
13949
+ };
13950
+ for(var index = 0; index < source.length; index++){
13951
+ var character = source[index];
13952
+ var next = source[index + 1];
13953
+ if (comment) {
13954
+ if (character === '*' && next === '/') {
13955
+ comment = false;
13956
+ index++;
13957
+ }
13958
+ continue;
13959
+ }
13960
+ if (quote != null) {
13961
+ if (character === '\\') {
13962
+ index++;
13963
+ } else if (character === quote) {
13964
+ quote = undefined;
13965
+ }
13966
+ continue;
13967
+ }
13968
+ if (character === '/' && next === '*') {
13969
+ comment = true;
13970
+ index++;
13971
+ continue;
13972
+ }
13973
+ if (character === '"' || character === "'") {
13974
+ quote = character;
13975
+ continue;
13976
+ }
13977
+ if (character === '(') {
13978
+ parentheses++;
13979
+ continue;
13980
+ }
13981
+ if (character === ')') {
13982
+ parentheses = Math.max(0, parentheses - 1);
13983
+ continue;
13984
+ }
13985
+ if (parentheses > 0) {
13986
+ continue;
13987
+ }
13988
+ if (character === ':' && colon < start) {
13989
+ colon = index;
13990
+ }
13991
+ if (character === ';' || character === '}' || character === '{') {
13992
+ if (character !== '{') {
13993
+ finish(index);
13994
+ }
13995
+ start = index + 1;
13996
+ colon = -1;
13997
+ }
13998
+ }
13999
+ finish(source.length);
14000
+ var result = '';
14001
+ var cursor = 0;
14002
+ for(var _iterator = _create_for_of_iterator_helper_loose(replacements), _step; !(_step = _iterator()).done;){
14003
+ var replacement = _step.value;
14004
+ result += source.slice(cursor, replacement.start) + replacement.value;
14005
+ cursor = replacement.end;
14006
+ }
14007
+ return result + source.slice(cursor);
14008
+ }
14009
+
14010
+ var declarations = new Set([
14011
+ 'defs',
14012
+ 'style',
14013
+ 'title',
14014
+ 'desc',
14015
+ 'metadata',
14016
+ 'symbol',
14017
+ 'clippath',
14018
+ 'mask',
14019
+ 'filter',
14020
+ 'lineargradient',
14021
+ 'radialgradient',
14022
+ 'pattern',
14023
+ 'marker'
14024
+ ]);
14025
+ var graphics = new Set([
14026
+ 'path',
14027
+ 'rect',
14028
+ 'circle',
14029
+ 'ellipse',
14030
+ 'line',
14031
+ 'polyline',
14032
+ 'polygon',
14033
+ 'use'
14034
+ ]);
14035
+ var containers = new Set([
14036
+ 'svg',
14037
+ 'g',
14038
+ 'a',
14039
+ 'switch'
14040
+ ]);
14041
+ var groupEffects = [
14042
+ 'opacity',
14043
+ 'filter',
14044
+ 'mask',
14045
+ 'clip-path'
14046
+ ];
14047
+ var native = new Set([
14048
+ 'text',
14049
+ 'image',
14050
+ 'foreignobject'
14051
+ ]);
14052
+ /** Select graphic-only subtrees; keep native text and images as separate layers. */ function planGraphicBaking(source) {
14053
+ var root = svg_js.SVG(source).node;
14054
+ var scopes = [];
14055
+ var warnings = [];
14056
+ var effectRules = collectGroupEffectRules(root);
14057
+ var byId = new Map(Array.from(root.querySelectorAll('[id]')).map(function(element) {
14058
+ var _element_getAttribute;
14059
+ return [
14060
+ (_element_getAttribute = element.getAttribute('id')) != null ? _element_getAttribute : '',
14061
+ element
14062
+ ];
14063
+ }));
14064
+ var tagOf = function tagOf(element) {
14065
+ return element.tagName.toLowerCase();
14066
+ };
14067
+ var selectorOf = function selectorOf(element) {
14068
+ var _element_getAttribute;
14069
+ var id = (_element_getAttribute = element.getAttribute('id')) != null ? _element_getAttribute : '';
14070
+ return "" + tagOf(element) + (id === '' ? '' : "#" + id);
14071
+ };
14072
+ var references = function references(element) {
14073
+ var ids = Array.from(element.attributes).flatMap(function(attribute) {
14074
+ var values = Array.from(attribute.value.matchAll(/url\(\s*['"]?#([^)'"\s]+)['"]?\s*\)/g), function(match) {
14075
+ return match[1];
14076
+ });
14077
+ if (attribute.localName === 'href' && attribute.value.startsWith('#')) {
14078
+ values.push(attribute.value.slice(1));
14079
+ }
14080
+ return values;
14081
+ });
14082
+ return ids.flatMap(function(id) {
14083
+ var target = byId.get(id);
14084
+ return target == null ? [] : [
14085
+ target
14086
+ ];
14087
+ });
14088
+ };
14089
+ var containsNative = function containsNative1(element, seen) {
14090
+ if (seen === void 0) seen = new Set();
14091
+ if (seen.has(element)) {
14092
+ return false;
14093
+ }
14094
+ seen.add(element);
14095
+ if (native.has(tagOf(element))) {
14096
+ return true;
14097
+ }
14098
+ return Array.from(element.children).some(function(child) {
14099
+ return !declarations.has(tagOf(child)) && containsNative(child, seen);
14100
+ }) || references(element).some(function(target) {
14101
+ return containsNative(target, seen);
14102
+ });
14103
+ };
14104
+ var hasGraphics = function hasGraphics1(element) {
14105
+ return graphics.has(tagOf(element)) || Array.from(element.children).some(function(child) {
14106
+ return !declarations.has(tagOf(child)) && hasGraphics(child);
14107
+ });
14108
+ };
14109
+ var hasGroupEffect = function hasGroupEffect(element) {
14110
+ var _element_getAttribute;
14111
+ var style = (_element_getAttribute = element.getAttribute('style')) != null ? _element_getAttribute : '';
14112
+ return effectRules.some(function(rule) {
14113
+ return element.matches(rule.selectorText);
14114
+ }) || hasGraphicGroupEffect(function(name) {
14115
+ var _element_getAttribute;
14116
+ var _exec_, _exec;
14117
+ return (_element_getAttribute = element.getAttribute(name)) != null ? _element_getAttribute : (_exec = new RegExp("(?:^|;)\\s*" + name + "\\s*:\\s*([^;]+)").exec(style)) == null ? void 0 : (_exec_ = _exec[1]) == null ? void 0 : _exec_.trim();
14118
+ });
14119
+ };
14120
+ var visit = function visit1(element) {
14121
+ var _element_getAttribute, _ref;
14122
+ var _exec_, _exec;
14123
+ var tag = tagOf(element);
14124
+ var style = (_element_getAttribute = element.getAttribute('style')) != null ? _element_getAttribute : '';
14125
+ var display = (_ref = (_exec = /(?:^|;)\s*display\s*:\s*([^;]+)/.exec(style)) == null ? void 0 : (_exec_ = _exec[1]) == null ? void 0 : _exec_.trim()) != null ? _ref : element.getAttribute('display');
14126
+ if (display === 'none') {
14127
+ return;
14128
+ }
14129
+ if (declarations.has(tag) || native.has(tag)) {
14130
+ return;
14131
+ }
14132
+ if (!containers.has(tag) && !graphics.has(tag)) {
14133
+ return;
14134
+ }
14135
+ if (!hasGraphics(element)) {
14136
+ return;
14137
+ }
14138
+ if ((graphics.has(tag) || tag === 'switch') && !containsNative(element)) {
14139
+ scopes.push({
14140
+ path: buildElementTreePath(element),
14141
+ selector: selectorOf(element),
14142
+ isGroup: containers.has(tag)
14143
+ });
14144
+ return;
14145
+ }
14146
+ if (hasGroupEffect(element) && !containsNative(element)) {
14147
+ scopes.push({
14148
+ path: buildElementTreePath(element),
14149
+ selector: selectorOf(element),
14150
+ isGroup: containers.has(tag)
14151
+ });
14152
+ return;
14153
+ }
14154
+ if (hasGroupEffect(element)) {
14155
+ warnings.push({
14156
+ message: 'A compositing group contains native text or images; its graphics cannot be baked separately.',
14157
+ selector: selectorOf(element)
14158
+ });
14159
+ return;
14160
+ }
14161
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(element.children)), _step; !(_step = _iterator()).done;){
14162
+ var child = _step.value;
14163
+ visit(child);
14164
+ }
14165
+ };
14166
+ visit(root);
14167
+ return {
14168
+ scopes: scopes,
14169
+ warnings: warnings
14170
+ };
14171
+ }
14172
+ function collectGroupEffectRules(root) {
14173
+ var result = [];
14174
+ if (typeof CSSStyleSheet !== 'function') {
14175
+ return result;
14176
+ }
14177
+ var visit = function visit1(rules) {
14178
+ var _loop = function() {
14179
+ var rule = _step.value;
14180
+ if (isStyleRule$1(rule)) {
14181
+ var affectsGroup = hasGraphicGroupEffect(function(name) {
14182
+ var value = rule.style.getPropertyValue(name).trim();
14183
+ return value === '' || value === 'initial' || value === 'unset' ? undefined : value;
14184
+ });
14185
+ if (affectsGroup) {
14186
+ result.push(rule);
14187
+ }
14188
+ } else if (hasNestedRules(rule)) {
14189
+ visit(rule.cssRules);
14190
+ }
14191
+ };
14192
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(rules)), _step; !(_step = _iterator()).done;)_loop();
14193
+ };
14194
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(root.querySelectorAll('style'))), _step; !(_step = _iterator()).done;){
14195
+ var style = _step.value;
14196
+ var _style_textContent;
14197
+ var sheet = new CSSStyleSheet();
14198
+ sheet.replaceSync((_style_textContent = style.textContent) != null ? _style_textContent : '');
14199
+ visit(sheet.cssRules);
14200
+ }
14201
+ return result;
14202
+ }
14203
+ /** Reject text/image dependencies and effects that cannot be rendered independently. */ function validateGraphicSnapshot(context) {
14204
+ var _loop = function() {
14205
+ var element = _step1.value;
14206
+ var computed = readStyle(element);
14207
+ var ancestor = element !== target && element.contains(target);
14208
+ var groupEffect = ancestor && hasGraphicGroupEffect(function(name) {
14209
+ return name === 'mask' ? computed.maskImage : computed.getPropertyValue(name);
14210
+ });
14211
+ if (ancestor && (groupEffect || computed.mixBlendMode !== 'normal')) {
14212
+ throw new Error('A mixed group effect cannot be applied independently to its graphics.');
14213
+ }
14214
+ if (target.contains(element) && target !== root && computed.mixBlendMode !== 'normal') {
14215
+ throw new Error('Blend modes that depend on an external backdrop cannot be baked independently.');
14216
+ }
14217
+ };
14218
+ var root = context.root, target = context.target, elements = context.elements, dependencies = context.dependencies, readStyle = context.readStyle;
14219
+ for(var _iterator = _create_for_of_iterator_helper_loose(dependencies), _step; !(_step = _iterator()).done;){
14220
+ var element = _step.value;
14221
+ if ([
14222
+ 'text',
14223
+ 'image',
14224
+ 'foreignobject'
14225
+ ].includes(element.tagName.toLowerCase())) {
14226
+ throw new Error('Graphic dependencies contain native text or images; they must remain editable.');
14227
+ }
14228
+ }
14229
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(elements), _step1; !(_step1 = _iterator1()).done;)_loop();
14230
+ }
14231
+ function isStyleRule$1(rule) {
14232
+ return rule.type === 1;
14233
+ }
14234
+ function hasNestedRules(rule) {
14235
+ return 'cssRules' in rule;
14236
+ }
14237
+ function hasGraphicGroupEffect(readValue) {
14238
+ return groupEffects.some(function(name) {
14239
+ var value = readValue(name);
14240
+ return value != null && value !== 'none' && value !== 'normal' && value !== '1';
14241
+ });
14242
+ }
14243
+
14244
+ /** Mask and clipPath definitions do not produce visible layers. */ function collectNonRenderingDeclarationPaths(source) {
14245
+ var root = svg_js.SVG(source).node;
14246
+ var elements = Array.from(root.querySelectorAll('*')).filter(function(element) {
14247
+ var tag = element.tagName.toLowerCase();
14248
+ return tag === 'mask' || tag === 'clippath';
14249
+ });
14250
+ return new Set(elements.map(buildElementTreePath));
14251
+ }
14252
+ /** A stylesheet diagnostic is resolved only when every element it can affect was baked. */ function collectBakedStylesheetPaths(source, isBaked) {
14253
+ var resolved = new Set();
14254
+ if (typeof DOMParser === 'undefined' || typeof CSSStyleSheet !== 'function') {
14255
+ return resolved;
14256
+ }
14257
+ var root = new DOMParser().parseFromString(source, 'image/svg+xml').documentElement;
14258
+ var allUsesBaked = Array.from(root.querySelectorAll('use')).every(function(element) {
14259
+ return isBaked(buildElementTreePath(element));
14260
+ });
14261
+ var isHandled = function isHandled(element) {
14262
+ if (isBaked(buildElementTreePath(element))) {
14263
+ return true;
14264
+ }
14265
+ if (element.closest('defs, symbol, marker, pattern, clipPath, mask, filter') != null) {
14266
+ return allUsesBaked;
14267
+ }
14268
+ return false;
14269
+ };
14270
+ for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(root.querySelectorAll('style'))), _step; !(_step = _iterator()).done;){
14271
+ var style = _step.value;
14272
+ var _style_textContent;
14273
+ var sheet = new CSSStyleSheet();
14274
+ sheet.replaceSync((_style_textContent = style.textContent) != null ? _style_textContent : '');
14275
+ var rules = Array.from(sheet.cssRules);
14276
+ var handled = rules.every(function(rule) {
14277
+ if (!isStyleRule(rule)) {
14278
+ return false;
14279
+ }
14280
+ if (Array.from(rule.style).every(function(name) {
14281
+ return name === 'mix-blend-mode';
14282
+ })) {
14283
+ return true;
14284
+ }
14285
+ var matched = [].concat([
14286
+ root
14287
+ ], Array.from(root.querySelectorAll('*'))).filter(function(element) {
14288
+ return element.matches(rule.selectorText);
14289
+ });
14290
+ return matched.every(isHandled);
14291
+ });
14292
+ if (handled) {
14293
+ resolved.add(buildElementTreePath(style));
14294
+ }
14295
+ }
14296
+ return resolved;
14297
+ }
14298
+ function isStyleRule(rule) {
14299
+ return rule.type === 1;
14300
+ }
14301
+
14302
+ /** Rasterize graphics and track the source layers and warnings they replace. */ function buildBakedLayers(source, size, options, rasterScale) {
14303
+ return _async_to_generator(function() {
14304
+ var deferredOptions, bakedPaths, baked, bakingWarnings, blending, plan, _iterator, _step, downgrade, _iterator1, _step1, warning, _iterator2, _step2, scope, image, message, _image_bbox, left, top, right, bottom, width, height, error, reason, replacesSource, handledStyles, declarations;
14305
+ return _ts_generator(this, function(_state) {
14306
+ switch(_state.label){
14307
+ case 0:
14308
+ deferredOptions = _extends({}, options, {
14309
+ strict: false,
14310
+ onWarning: undefined
14311
+ });
14312
+ bakedPaths = [];
14313
+ baked = [];
14314
+ bakingWarnings = [];
14315
+ blending = normalizeLayerBlending(source);
14316
+ plan = planGraphicBaking(blending.source);
14317
+ for(_iterator = _create_for_of_iterator_helper_loose(blending.downgrades); !(_step = _iterator()).done;){
14318
+ downgrade = _step.value;
14319
+ collectLayerWarning(bakingWarnings, deferredOptions, SVG2IR_WARNING_CODES.LAYERS_BLEND_MODE_DOWNGRADED, 'mix-blend-mode "' + downgrade.mode + '" was downgraded to "normal"; the layer is retained.', downgrade.selector);
14320
+ }
14321
+ for(_iterator1 = _create_for_of_iterator_helper_loose(plan.warnings); !(_step1 = _iterator1()).done;){
14322
+ warning = _step1.value;
14323
+ collectLayerWarning(bakingWarnings, deferredOptions, SVG2IR_WARNING_CODES.LAYERS_UNSUPPORTED_FEATURE, warning.message, warning.selector);
14324
+ }
14325
+ _iterator2 = _create_for_of_iterator_helper_loose(plan.scopes);
14326
+ _state.label = 1;
14327
+ case 1:
14328
+ if (!!(_step2 = _iterator2()).done) return [
14329
+ 3,
14330
+ 6
14331
+ ];
14332
+ scope = _step2.value;
14333
+ _state.label = 2;
14334
+ case 2:
14335
+ _state.trys.push([
14336
+ 2,
14337
+ 4,
14338
+ ,
14339
+ 5
14340
+ ]);
14341
+ if (!canRasterizeSVG()) {
14342
+ throw new Error('Graphic baking requires a browser with SVG and Canvas support.');
14343
+ }
14344
+ return [
14345
+ 4,
14346
+ rasterizeSVG(blending.source, scope.path, size, rasterScale, validateGraphicSnapshot)
14347
+ ];
14348
+ case 3:
14349
+ image = _state.sent();
14350
+ bakedPaths.push(scope.path);
14351
+ message = image == null ? 'Graphic rasterization produced no visible pixels; no image layer was emitted.' : scope.isGroup ? 'Graphic group baked into a single PNG; child graphics and paint/effect parameters are no longer editable.' : 'Graphic baked into a PNG; vector geometry and paint/effect parameters are no longer editable.';
14352
+ collectLayerWarning(bakingWarnings, deferredOptions, SVG2IR_WARNING_CODES.LAYERS_GRAPHIC_BAKED, message, scope.selector);
14353
+ if (image == null) {
14354
+ return [
14355
+ 3,
14356
+ 5
14357
+ ];
14358
+ }
14359
+ _image_bbox = image.bbox, left = _image_bbox[0], top = _image_bbox[1], right = _image_bbox[2], bottom = _image_bbox[3];
14360
+ width = right - left;
14361
+ height = bottom - top;
14362
+ baked.push({
14363
+ path: scope.path,
14364
+ layer: {
14365
+ id: '',
14366
+ type: 'image',
14367
+ role: 'content',
14368
+ bbox: image.bbox,
14369
+ size: [
14370
+ width,
14371
+ height
14372
+ ],
14373
+ rotation: [
14374
+ 0,
14375
+ 0,
14376
+ 0
14377
+ ],
14378
+ url: image.url,
14379
+ width: width,
14380
+ height: height
14381
+ }
14382
+ });
14383
+ return [
14384
+ 3,
14385
+ 5
14386
+ ];
14387
+ case 4:
14388
+ error = _state.sent();
14389
+ reason = _instanceof(error, Error) ? error.message : String(error);
14390
+ collectLayerWarning(bakingWarnings, deferredOptions, SVG2IR_WARNING_CODES.LAYERS_UNSUPPORTED_FEATURE, "Graphic baking failed: " + reason, scope.selector);
14391
+ return [
14392
+ 3,
14393
+ 5
14394
+ ];
14395
+ case 5:
14396
+ return [
14397
+ 3,
14398
+ 1
14399
+ ];
14400
+ case 6:
14401
+ replacesSource = function replacesSource(path) {
14402
+ return path != null && bakedPaths.some(function(scope) {
14403
+ return scope === '' || path === scope || path.startsWith("" + scope + "/");
14404
+ });
14405
+ };
14406
+ handledStyles = collectBakedStylesheetPaths(blending.source, replacesSource);
14407
+ declarations = collectNonRenderingDeclarationPaths(source);
14408
+ return [
14409
+ 2,
14410
+ {
14411
+ layers: baked,
14412
+ warnings: bakingWarnings,
14413
+ replacesSource: replacesSource,
14414
+ resolvesWarning: function resolvesWarning(warning, path) {
14415
+ return replacesSource(path) || warning.code === SVG2IR_WARNING_CODES.ELEMENT_DROPPED && path != null && (handledStyles.has(path) || declarations.has(path));
14416
+ }
14417
+ }
14418
+ ];
14419
+ }
14420
+ });
14421
+ })();
14422
+ }
13275
14423
 
13276
14424
  function encodeBase64(data) {
13277
14425
  var chunks = [];
@@ -13460,30 +14608,115 @@ function fetchImageResource(url) {
13460
14608
  }).apply(this, arguments);
13461
14609
  }
13462
14610
 
13463
- function convertSVGToLayers(source, options, loadImage, preservedData) {
13464
- return _async_to_generator(function() {
13465
- var splitResult, parsed, _assembleSVGStaticLayers, size, data, _tmp;
14611
+ var animatedTags = new Set([
14612
+ 'animate',
14613
+ 'animatetransform',
14614
+ 'animatemotion',
14615
+ 'set'
14616
+ ]);
14617
+ /** Static layers cannot sample animation; drop SMIL nodes so elements keep their authored state. */ function stripLayerAnimation(source) {
14618
+ var svg = svg_js.SVG(source);
14619
+ if ((svg == null ? void 0 : svg.node) == null) {
14620
+ return {
14621
+ source: source,
14622
+ removed: 0
14623
+ };
14624
+ }
14625
+ var elements = Array.from(svg.node.querySelectorAll('*')).filter(function(element) {
14626
+ return animatedTags.has(element.tagName.toLowerCase());
14627
+ });
14628
+ if (elements.length === 0) {
14629
+ return {
14630
+ source: source,
14631
+ removed: 0
14632
+ };
14633
+ }
14634
+ for(var _iterator = _create_for_of_iterator_helper_loose(elements), _step; !(_step = _iterator()).done;){
14635
+ var element = _step.value;
14636
+ element.remove();
14637
+ }
14638
+ return {
14639
+ source: svg.svg(),
14640
+ removed: elements.length
14641
+ };
14642
+ }
14643
+
14644
+ function convertSVGToLayers() {
14645
+ return _async_to_generator(function(source, options, preservedData) {
14646
+ var loadImage, _options_rasterScale, rasterScale, conversionOptions, layerSources, warningSources, collected, stripped, staticSource, parsed, context, composition, baking, assembled, _tmp, _tmp1;
13466
14647
  return _ts_generator(this, function(_state) {
13467
14648
  switch(_state.label){
13468
14649
  case 0:
13469
- splitResult = preservedData == null ? splitSVG(source, options) : undefined;
13470
- parsed = splitResult != null ? splitResult : parseSVGToIRWithPreservedData(source, options);
13471
- _assembleSVGStaticLayers = assembleSVGStaticLayers(parsed.ir, options, parsed.warnings, preservedData != null ? preservedData : splitResult == null ? void 0 : splitResult.preservedData), size = _assembleSVGStaticLayers.size, data = _assembleSVGStaticLayers.data;
13472
- _tmp = {
13473
- size: size
14650
+ if (options === void 0) options = {};
14651
+ loadImage = options.loadImage, _options_rasterScale = options.rasterScale, rasterScale = _options_rasterScale === void 0 ? 2 : _options_rasterScale, conversionOptions = _object_without_properties_loose(options, [
14652
+ "loadImage",
14653
+ "rasterScale"
14654
+ ]);
14655
+ layerSources = new Map();
14656
+ warningSources = new Map();
14657
+ collected = {
14658
+ textDataByLayerId: new Map(),
14659
+ paintAnimationsByLayerId: new Map(),
14660
+ shapeAnimationsByLayerId: new Map()
14661
+ };
14662
+ stripped = stripLayerAnimation(source);
14663
+ staticSource = stripped.source;
14664
+ // Preserve original layer IDs while gathering the source identities required by baking and assembly.
14665
+ parsed = parseSVGToIRWithPreservedData(staticSource, _extends({}, conversionOptions, {
14666
+ strict: false,
14667
+ onWarning: undefined
14668
+ }), _extends({}, collected, {
14669
+ layerSourceCollector: layerSources,
14670
+ warningSourceCollector: warningSources
14671
+ }));
14672
+ context = {
14673
+ source: staticSource,
14674
+ ir: parsed.ir,
14675
+ warnings: parsed.warnings,
14676
+ preservedData: preservedData != null ? preservedData : collected,
14677
+ layerSources: layerSources,
14678
+ warningSources: warningSources
13474
14679
  };
14680
+ if (stripped.removed > 0) {
14681
+ collectLayerWarning(context.warnings, _extends({}, conversionOptions, {
14682
+ strict: false,
14683
+ onWarning: undefined
14684
+ }), SVG2IR_WARNING_CODES.LAYERS_ANIMATION_STRIPPED, "" + stripped.removed + " animated element(s) were removed; static layers output does not sample animation.");
14685
+ }
14686
+ composition = context.ir.compositions[0];
13475
14687
  return [
13476
14688
  4,
13477
- inlineImageResources(data, loadImage)
14689
+ buildBakedLayers(context.source, [
14690
+ composition.width,
14691
+ composition.height
14692
+ ], conversionOptions, rasterScale)
13478
14693
  ];
13479
14694
  case 1:
14695
+ baking = _state.sent();
14696
+ assembled = assembleSVGLayers({
14697
+ context: context,
14698
+ options: conversionOptions,
14699
+ baking: baking
14700
+ });
14701
+ _tmp = [
14702
+ {},
14703
+ assembled
14704
+ ];
14705
+ _tmp1 = {};
14706
+ return [
14707
+ 4,
14708
+ inlineImageResources(assembled.data, loadImage)
14709
+ ];
14710
+ case 2:
13480
14711
  return [
13481
14712
  2,
13482
- (_tmp.data = _state.sent(), _tmp.warnings = parsed.warnings, _tmp)
14713
+ _extends.apply(void 0, _tmp.concat([
14714
+ (_tmp1.data = _state.sent(), _tmp1)
14715
+ ]))
13483
14716
  ];
13484
14717
  }
13485
14718
  });
13486
- })();
14719
+ }).apply(this, arguments);
13487
14720
  }
13488
14721
 
13489
14722
  /**
@@ -13508,7 +14741,8 @@ function convertSVGToLayers(source, options, loadImage, preservedData) {
13508
14741
  JSONSceneVersion["3_4"] = "3.4";
13509
14742
  JSONSceneVersion["3_5"] = "3.5";
13510
14743
  JSONSceneVersion["3_6"] = "3.6";
13511
- JSONSceneVersion["LATEST"] = "3.6";
14744
+ JSONSceneVersion["3_7"] = "3.7";
14745
+ JSONSceneVersion["LATEST"] = "3.7";
13512
14746
  })(JSONSceneVersion || (JSONSceneVersion = {}));
13513
14747
 
13514
14748
  /*********************************************/ /* 元素属性参数类型 */ /*********************************************/ /**
@@ -13823,10 +15057,12 @@ var CameraClipMode;
13823
15057
  * 直线
13824
15058
  */ ValueType[ValueType["LINE"] = 5] = "LINE";
13825
15059
  /**
13826
- * 曲线
15060
+ * 曲线(Hermite 曲线)
15061
+ * @deprecated 使用 BEZIER_CURVE 替代,此类型仅用于旧数据迁移兼容
13827
15062
  */ ValueType[ValueType["CURVE"] = 6] = "CURVE";
13828
15063
  /**
13829
15064
  * 贝塞尔路径
15065
+ * @deprecated 使用 BEZIER_CURVE_PATH 替代,此类型仅用于旧数据迁移兼容
13830
15066
  */ ValueType[ValueType["BEZIER_PATH"] = 7] = "BEZIER_PATH";
13831
15067
  /**
13832
15068
  * 颜色
@@ -14263,6 +15499,7 @@ var DataType;
14263
15499
  DataType["AnimationGraphAsset"] = "AnimationGraphAsset";
14264
15500
  DataType["CompositionComponent"] = "CompositionComponent";
14265
15501
  DataType["FFDComponent"] = "FFDComponent";
15502
+ DataType["FrameComponent"] = "FrameComponent";
14266
15503
  DataType["Animator"] = "Animator";
14267
15504
  // Non-EffectObject
14268
15505
  DataType["TimelineClip"] = "TimelineClip";
@@ -15887,7 +17124,8 @@ function asRecordArray(value) {
15887
17124
  }
15888
17125
 
15889
17126
  /** 从已解析的 IR 和 SVG 保留数据生成 GE 场景。 */ function assembleSVGGE(parsed, options, preservedData) {
15890
- var ir = parsed.ir, warnings = parsed.warnings;
17127
+ var ir = parsed.ir;
17128
+ var warnings = [].concat(parsed.warnings);
15891
17129
  var fonts = (options != null ? options : {}).fonts;
15892
17130
  var irForGE = expandIRHoldTransitions(ir);
15893
17131
  if ((preservedData == null ? void 0 : preservedData.shapeAnimationsByLayerId) != null) {
@@ -15995,36 +17233,19 @@ function cleanFontName(raw) {
15995
17233
  return value;
15996
17234
  }
15997
17235
 
15998
- /** SVG→GE 显式入口。传入 preservedData 时应用 SVG 专属后处理。 */ function convertSVGToGE(source, options, preservedData) {
17236
+ function convertSVGToGE(sourceOrContext, options, preservedData) {
15999
17237
  var _ref = options != null ? options : {}; _ref.fonts; var parserOptions = _object_without_properties_loose(_ref, [
16000
17238
  "fonts"
16001
17239
  ]);
16002
- var parsed = parseSVGToIRWithPreservedData(source, parserOptions);
16003
- return assembleSVGGE(parsed, options, preservedData);
16004
- }
16005
-
16006
- function convertSVG(source, options, preservedData) {
16007
- var _ref = options != null ? options : {}, _ref_outputFormat = _ref.outputFormat, outputFormat = _ref_outputFormat === void 0 ? 'ge' : _ref_outputFormat;
16008
- if (outputFormat !== 'ge' && outputFormat !== 'layers') {
16009
- throw new TypeError('[svg2ir] outputFormat must be ge or layers.');
16010
- }
16011
- if ((options == null ? void 0 : options.outputFormat) === 'layers') {
16012
- options.outputFormat; var loadImage = options.loadImage, parserOptions = _object_without_properties_loose(options, [
16013
- "outputFormat",
16014
- "loadImage"
16015
- ]);
16016
- return convertSVGToLayers(source, parserOptions, loadImage, preservedData);
16017
- }
16018
- var _ref1 = options != null ? options : {}; _ref1.outputFormat; var geOptions = _object_without_properties_loose(_ref1, [
16019
- "outputFormat"
16020
- ]);
16021
- return convertSVGToGE(source, geOptions, preservedData);
17240
+ var context = typeof sourceOrContext === 'string' ? parseSVGToIRWithPreservedData(sourceOrContext, parserOptions) : sourceOrContext;
17241
+ return assembleSVGGE(context, options, preservedData != null ? preservedData : typeof sourceOrContext === 'string' ? undefined : sourceOrContext.preservedData);
16022
17242
  }
16023
17243
 
16024
17244
  setEditableSVGConstructor(resolveEditableSVGConstructor(editableSVGNodeModule));
16025
17245
 
16026
- exports.convertSVG = convertSVG;
16027
17246
  exports.convertSVGToGE = convertSVGToGE;
16028
17247
  exports.convertSVGToIR = convertSVGToIR;
17248
+ exports.convertSVGToLayers = convertSVGToLayers;
17249
+ exports.inferNumericWeightFromFamily = inferNumericWeightFromFamily;
16029
17250
  exports.splitSVG = splitSVG;
16030
17251
  //# sourceMappingURL=node.js.map