@deot/vc 1.0.51 → 1.0.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -203,7 +203,7 @@
203
203
  return target;
204
204
  };
205
205
 
206
- const getStyle$1 = (el, name) => {
206
+ const getStyle$2 = (el, name) => {
207
207
  if (IS_SERVER$2 || !name) return "";
208
208
  if (name === "float") {
209
209
  name = "cssFloat";
@@ -219,8 +219,8 @@
219
219
  const isScroller = (el, options) => {
220
220
  if (IS_SERVER$2 || !el) return false;
221
221
  const { className, direction } = options || {};
222
- let overflow = getStyle$1(el, `overflow-${direction ? "y" : "x"}`);
223
- overflow = overflow || getStyle$1(el, "overflow");
222
+ let overflow = getStyle$2(el, `overflow-${direction ? "y" : "x"}`);
223
+ overflow = overflow || getStyle$2(el, "overflow");
224
224
  return !!(overflow.match(/(scroll|auto)/) || className?.test(el.className));
225
225
  };
226
226
 
@@ -6615,7 +6615,7 @@
6615
6615
  * @returns {boolean}
6616
6616
  */
6617
6617
 
6618
- function isSafari$1() {
6618
+ function isSafari$2() {
6619
6619
  return !!(navigator.vendor && navigator.vendor.match(/apple/i));
6620
6620
  }
6621
6621
 
@@ -7493,7 +7493,7 @@
7493
7493
  // that's because I want to show image before it's fully loaded,
7494
7494
  // as browser can render parts of image while it is loading.
7495
7495
  // We do not do this in Safari due to partial loading bug.
7496
- if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$1())) {
7496
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$2())) {
7497
7497
  this.isDecoding = true; // purposefully using finally instead of then,
7498
7498
  // as if srcset sizes changes dynamically - it may cause decode error
7499
7499
 
@@ -7524,7 +7524,7 @@
7524
7524
  return;
7525
7525
  }
7526
7526
 
7527
- if (this.isImageContent() && this.isDecoding && !isSafari$1()) {
7527
+ if (this.isImageContent() && this.isDecoding && !isSafari$2()) {
7528
7528
  // add image to slide when it becomes active,
7529
7529
  // even if it's not finished decoding
7530
7530
  this.appendImage();
@@ -9105,6 +9105,10 @@
9105
9105
  },
9106
9106
  TableColumn: {
9107
9107
  line: nil
9108
+ },
9109
+ Snapshot: {
9110
+ source: nil,
9111
+ download: nil
9108
9112
  }
9109
9113
  };
9110
9114
  class Instance {
@@ -11305,7 +11309,7 @@
11305
11309
  ...listeners
11306
11310
  }), {
11307
11311
  prepend: slots.prepend && (() => slots.prepend?.()),
11308
- append: props2.step ? slots.append ? () => slots.append?.() : () => {
11312
+ append: slots.append ? () => slots.append?.() : props2.step ? () => {
11309
11313
  return vue.createVNode("div", {
11310
11314
  "class": "vc-input-number__icon"
11311
11315
  }, [vue.createVNode("div", {
@@ -20542,23 +20546,105 @@
20542
20546
  tag: {
20543
20547
  type: String,
20544
20548
  default: "div"
20549
+ },
20550
+ // useCORS
20551
+ crossOrigin: {
20552
+ type: String,
20553
+ // ''. 'anonymous', 'use-credentials'
20554
+ default: "anonymous",
20555
+ validator: (v) => /^(|anonymous|use-credentials)$/.test(v)
20556
+ },
20557
+ source: Function,
20558
+ download: Function,
20559
+ // 传递给snap-dom的配置项
20560
+ options: {
20561
+ type: Object,
20562
+ default: () => ({})
20545
20563
  }
20546
20564
  };
20547
- const COMPONENT_NAME$Z = "vc-html-to-image";
20548
- const HTMLToImage = /* @__PURE__ */ vue.defineComponent({
20565
+ const COMPONENT_NAME$Z = "vc-snapshot";
20566
+ const Snapshot = /* @__PURE__ */ vue.defineComponent({
20549
20567
  name: COMPONENT_NAME$Z,
20550
20568
  props: props$H,
20569
+ emits: ["ready"],
20551
20570
  setup(props2, {
20552
- slots
20571
+ emit,
20572
+ slots,
20573
+ expose
20553
20574
  }) {
20575
+ const instance = vue.getCurrentInstance();
20576
+ const current = vue.ref();
20577
+ const snapdom = vue.ref();
20578
+ const refresh = async () => {
20579
+ if (!props2.crossOrigin) return;
20580
+ const transformSource = props2.source || VcInstance.options.Snapshot?.source || ((v) => v);
20581
+ return Promise.all(Array.from(current.value.querySelectorAll("img")).map((node) => {
20582
+ return new Promise((resolve) => {
20583
+ (async () => {
20584
+ let url;
20585
+ try {
20586
+ url = await transformSource(node.src, "image");
20587
+ } catch (e) {
20588
+ console.error(e);
20589
+ }
20590
+ const image = new Image();
20591
+ image.crossOrigin = props2.crossOrigin;
20592
+ image.src = `${url}?=${(/* @__PURE__ */ new Date()).getTime()}`;
20593
+ image.onload = () => {
20594
+ node.src = image.src;
20595
+ resolve(1);
20596
+ };
20597
+ image.onerror = () => resolve(0);
20598
+ })();
20599
+ });
20600
+ }));
20601
+ };
20602
+ const toDataURL = async () => {
20603
+ await refresh();
20604
+ return snapdom.value.toRaw();
20605
+ };
20606
+ const download = async (options) => {
20607
+ await refresh();
20608
+ const _download = props2.download || VcInstance.options.Snapshot?.download || (() => false);
20609
+ const allow = _download(instance, options);
20610
+ if (allow && allow.then) {
20611
+ allow.catch(() => {
20612
+ snapdom.value.download(options);
20613
+ });
20614
+ return;
20615
+ }
20616
+ allow || snapdom.value.download(options);
20617
+ };
20618
+ expose({
20619
+ snapdom,
20620
+ refresh,
20621
+ toDataURL,
20622
+ download
20623
+ });
20624
+ vue.onMounted(async () => {
20625
+ try {
20626
+ let snapDOM = window.snapdom || await Promise.resolve().then(() => snapdom$1);
20627
+ snapDOM = snapDOM.snapdom || snapDOM;
20628
+ snapdom.value = await snapDOM(current.value, props2.options);
20629
+ emit("ready", {
20630
+ instance,
20631
+ dependencies: {
20632
+ snapDOM
20633
+ }
20634
+ });
20635
+ } catch (e) {
20636
+ throw new VcError("snapshot", e);
20637
+ }
20638
+ });
20554
20639
  return () => {
20555
20640
  return vue.createVNode("div", {
20556
- "class": "vc-html-to-image"
20641
+ "ref": current,
20642
+ "class": "vc-snapshot"
20557
20643
  }, [slots?.default?.()]);
20558
20644
  };
20559
20645
  }
20560
20646
  });
20561
- const MHTMLToImage = HTMLToImage;
20647
+ const MSnapshot = Snapshot;
20562
20648
  const MIcon = Icon;
20563
20649
  const props$G = {
20564
20650
  src: String,
@@ -26245,7 +26331,7 @@
26245
26331
  let hiddenEl$1;
26246
26332
  const getFitIndex = (options = {}) => {
26247
26333
  const { el: el2, line, value, suffix, indent = 0 } = options;
26248
- let lineHeight = parseInt(getStyle$1(el2, "line-height"), 10);
26334
+ let lineHeight = parseInt(getStyle$2(el2, "line-height"), 10);
26249
26335
  if (!hiddenEl$1) {
26250
26336
  hiddenEl$1 = document.createElement("div");
26251
26337
  document.body.appendChild(hiddenEl$1);
@@ -26257,7 +26343,7 @@
26257
26343
  boxSizing,
26258
26344
  sizingStyle
26259
26345
  } = utils.getComputedStyle(el2, SIZING_STYLE$1);
26260
- const textIndent = `text-indent: ${parseInt(getStyle$1(el2, "text-indent"), 10) + indent}px;`;
26346
+ const textIndent = `text-indent: ${parseInt(getStyle$2(el2, "text-indent"), 10) + indent}px;`;
26261
26347
  hiddenEl$1.setAttribute("style", `${sizingStyle};${textIndent};${HIDDEN_TEXT_STYLE}`);
26262
26348
  let sideHeight = paddingSize || 0;
26263
26349
  boxSizing === "border-box" && (sideHeight += borderSize);
@@ -31839,8 +31925,8 @@
31839
31925
  MFormItem,
31840
31926
  Fragment,
31841
31927
  MFragment,
31842
- HTMLToImage,
31843
- MHTMLToImage,
31928
+ Snapshot,
31929
+ MSnapshot,
31844
31930
  Icon,
31845
31931
  MIcon,
31846
31932
  Image: Image$1$1,
@@ -55035,10 +55121,10 @@
55035
55121
  return styleChanged;
55036
55122
  }
55037
55123
  function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
55038
- var style = getStyle(el, scope.inHover);
55124
+ var style = getStyle$1(el, scope.inHover);
55039
55125
  var prevStyle = forceSetAll
55040
55126
  ? null
55041
- : (prevEl && getStyle(prevEl, scope.inHover) || {});
55127
+ : (prevEl && getStyle$1(prevEl, scope.inHover) || {});
55042
55128
  if (style === prevStyle) {
55043
55129
  return false;
55044
55130
  }
@@ -55089,7 +55175,7 @@
55089
55175
  return styleChanged;
55090
55176
  }
55091
55177
  function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
55092
- return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
55178
+ return bindCommonProps(ctx, getStyle$1(el, scope.inHover), prevEl && getStyle$1(prevEl, scope.inHover), forceSetAll, scope);
55093
55179
  }
55094
55180
  function setContextTransform(ctx, el) {
55095
55181
  var m = el.transform;
@@ -55148,7 +55234,7 @@
55148
55234
  scope.batchFill = '';
55149
55235
  scope.batchStroke = '';
55150
55236
  }
55151
- function getStyle(el, inHover) {
55237
+ function getStyle$1(el, inHover) {
55152
55238
  return inHover ? (el.__hoverStyle || el.style) : el.style;
55153
55239
  }
55154
55240
  function brushSingle(ctx, el) {
@@ -55202,7 +55288,7 @@
55202
55288
  else if (!canBatchPath) {
55203
55289
  flushPathDrawn(ctx, scope);
55204
55290
  }
55205
- var style = getStyle(el, scope.inHover);
55291
+ var style = getStyle$1(el, scope.inHover);
55206
55292
  if (el instanceof Path) {
55207
55293
  if (scope.lastDrawType !== DRAW_TYPE_PATH) {
55208
55294
  forceSetStyle = true;
@@ -72589,7 +72675,7 @@
72589
72675
  if (!coordSys.axisPointerEnabled) {
72590
72676
  return;
72591
72677
  }
72592
- var coordSysKey = makeKey(coordSys.model);
72678
+ var coordSysKey = makeKey$1(coordSys.model);
72593
72679
  var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
72594
72680
  result.coordSysMap[coordSysKey] = coordSys;
72595
72681
  // Set tooltip (like 'cross') is a convenient way to show axisPointer
@@ -72629,7 +72715,7 @@
72629
72715
  axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
72630
72716
  var snap = axisPointerModel.get('snap');
72631
72717
  var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
72632
- var axisKey = makeKey(axis.model);
72718
+ var axisKey = makeKey$1(axis.model);
72633
72719
  var involveSeries = triggerTooltip || snap || axis.type === 'category';
72634
72720
  // If result.axesInfo[key] exist, override it (tooltip has higher priority).
72635
72721
  var axisInfo = result.axesInfo[axisKey] = {
@@ -72701,7 +72787,7 @@
72701
72787
  if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
72702
72788
  return;
72703
72789
  }
72704
- each$f(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
72790
+ each$f(result.coordSysAxesInfo[makeKey$1(coordSys.model)], function (axisInfo) {
72705
72791
  var axis = axisInfo.axis;
72706
72792
  if (coordSys.getAxis(axis.dim) === axis) {
72707
72793
  axisInfo.seriesModels.push(seriesModel);
@@ -72779,7 +72865,7 @@
72779
72865
  }
72780
72866
  function getAxisInfo$1(axisModel) {
72781
72867
  var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
72782
- return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
72868
+ return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey$1(axisModel)];
72783
72869
  }
72784
72870
  function getAxisPointerModel(axisModel) {
72785
72871
  var axisInfo = getAxisInfo$1(axisModel);
@@ -72792,7 +72878,7 @@
72792
72878
  * @param {module:echarts/model/Model} model
72793
72879
  * @return {string} unique key
72794
72880
  */
72795
- function makeKey(model) {
72881
+ function makeKey$1(model) {
72796
72882
  return model.type + '||' + model.id;
72797
72883
  }
72798
72884
 
@@ -95085,7 +95171,7 @@
95085
95171
  return;
95086
95172
  }
95087
95173
  var coordSysModel = axisInfo.coordSys.model;
95088
- var coordSysKey = makeKey(coordSysModel);
95174
+ var coordSysKey = makeKey$1(coordSysModel);
95089
95175
  var coordSysItem = dataByCoordSys.map[coordSysKey];
95090
95176
  if (!coordSysItem) {
95091
95177
  coordSysItem = dataByCoordSys.map[coordSysKey] = {
@@ -112314,7 +112400,7 @@
112314
112400
  * @returns {boolean}
112315
112401
  */
112316
112402
 
112317
- function isSafari() {
112403
+ function isSafari$1() {
112318
112404
  return !!(navigator.vendor && navigator.vendor.match(/apple/i));
112319
112405
  }
112320
112406
 
@@ -117349,7 +117435,7 @@
117349
117435
  // that's because I want to show image before it's fully loaded,
117350
117436
  // as browser can render parts of image while it is loading.
117351
117437
  // We do not do this in Safari due to partial loading bug.
117352
- if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
117438
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$1())) {
117353
117439
  this.isDecoding = true; // purposefully using finally instead of then,
117354
117440
  // as if srcset sizes changes dynamically - it may cause decode error
117355
117441
 
@@ -117380,7 +117466,7 @@
117380
117466
  return;
117381
117467
  }
117382
117468
 
117383
- if (this.isImageContent() && this.isDecoding && !isSafari()) {
117469
+ if (this.isImageContent() && this.isDecoding && !isSafari$1()) {
117384
117470
  // add image to slide when it becomes active,
117385
117471
  // even if it's not finished decoding
117386
117472
  this.appendImage();
@@ -132207,6 +132293,4137 @@
132207
132293
  default: Quill
132208
132294
  }, Symbol.toStringTag, { value: 'Module' }));
132209
132295
 
132296
+ /*
132297
+ * snapdom
132298
+ * v.1.9.14
132299
+ * Author Juan Martin Muda
132300
+ * License MIT
132301
+ **/
132302
+
132303
+
132304
+ // src/core/cache.js
132305
+ var cache = {
132306
+ image: /* @__PURE__ */ new Map(),
132307
+ background: /* @__PURE__ */ new Map(),
132308
+ resource: /* @__PURE__ */ new Map(),
132309
+ defaultStyle: /* @__PURE__ */ new Map(),
132310
+ baseStyle: /* @__PURE__ */ new Map(),
132311
+ computedStyle: /* @__PURE__ */ new WeakMap(),
132312
+ font: /* @__PURE__ */ new Set(),
132313
+ session: {
132314
+ styleMap: /* @__PURE__ */ new Map(),
132315
+ styleCache: /* @__PURE__ */ new WeakMap(),
132316
+ nodeMap: /* @__PURE__ */ new Map()
132317
+ }
132318
+ };
132319
+ function applyCachePolicy(policy = "soft") {
132320
+ switch (policy) {
132321
+ case "auto": {
132322
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132323
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132324
+ return;
132325
+ }
132326
+ case "soft": {
132327
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132328
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132329
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132330
+ return;
132331
+ }
132332
+ case "full": {
132333
+ return;
132334
+ }
132335
+ case "disabled": {
132336
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132337
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132338
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132339
+ cache.computedStyle = /* @__PURE__ */ new WeakMap();
132340
+ cache.baseStyle = /* @__PURE__ */ new Map();
132341
+ cache.defaultStyle = /* @__PURE__ */ new Map();
132342
+ cache.image = /* @__PURE__ */ new Map();
132343
+ cache.background = /* @__PURE__ */ new Map();
132344
+ cache.resource = /* @__PURE__ */ new Map();
132345
+ cache.font = /* @__PURE__ */ new Set();
132346
+ return;
132347
+ }
132348
+ default: {
132349
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132350
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132351
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132352
+ return;
132353
+ }
132354
+ }
132355
+ }
132356
+
132357
+ // src/utils/helpers.js
132358
+ function extractURL(value) {
132359
+ const match = value.match(/url\((['"]?)(.*?)(\1)\)/);
132360
+ if (!match) return null;
132361
+ const url = match[2].trim();
132362
+ if (url.startsWith("#")) return null;
132363
+ return url;
132364
+ }
132365
+ function stripTranslate(transform) {
132366
+ if (!transform || transform === "none") return "";
132367
+ let cleaned = transform.replace(/translate[XY]?\([^)]*\)/g, "");
132368
+ cleaned = cleaned.replace(/matrix\(([^)]+)\)/g, (_, values) => {
132369
+ const parts = values.split(",").map((s) => s.trim());
132370
+ if (parts.length !== 6) return `matrix(${values})`;
132371
+ parts[4] = "0";
132372
+ parts[5] = "0";
132373
+ return `matrix(${parts.join(", ")})`;
132374
+ });
132375
+ cleaned = cleaned.replace(/matrix3d\(([^)]+)\)/g, (_, values) => {
132376
+ const parts = values.split(",").map((s) => s.trim());
132377
+ if (parts.length !== 16) return `matrix3d(${values})`;
132378
+ parts[12] = "0";
132379
+ parts[13] = "0";
132380
+ return `matrix3d(${parts.join(", ")})`;
132381
+ });
132382
+ return cleaned.trim().replace(/\s{2,}/g, " ");
132383
+ }
132384
+ function safeEncodeURI(uri) {
132385
+ if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri;
132386
+ try {
132387
+ return encodeURI(uri);
132388
+ } catch {
132389
+ return uri;
132390
+ }
132391
+ }
132392
+
132393
+ // src/modules/snapFetch.js
132394
+ function createSnapLogger(prefix = "[snapDOM]", { ttlMs = 5 * 6e4, maxEntries = 12 } = {}) {
132395
+ const seen = /* @__PURE__ */ new Map();
132396
+ let emitted = 0;
132397
+ function log(level, key, msg) {
132398
+ if (emitted >= maxEntries) return;
132399
+ const now = Date.now();
132400
+ const until = seen.get(key) || 0;
132401
+ if (until > now) return;
132402
+ seen.set(key, now + ttlMs);
132403
+ emitted++;
132404
+ if (level === "warn" && console && console.warn) console.warn(`${prefix} ${msg}`);
132405
+ else if (console && console.error) console.error(`${prefix} ${msg}`);
132406
+ }
132407
+ return {
132408
+ warnOnce(key, msg) {
132409
+ log("warn", key, msg);
132410
+ },
132411
+ errorOnce(key, msg) {
132412
+ log("error", key, msg);
132413
+ },
132414
+ reset() {
132415
+ seen.clear();
132416
+ emitted = 0;
132417
+ }
132418
+ };
132419
+ }
132420
+ var snapLogger = createSnapLogger("[snapDOM]", { ttlMs: 3 * 6e4, maxEntries: 10 });
132421
+ var _inflight = /* @__PURE__ */ new Map();
132422
+ var _errorCache = /* @__PURE__ */ new Map();
132423
+ function isSpecialURL(url) {
132424
+ return /^data:|^blob:|^about:blank$/i.test(url);
132425
+ }
132426
+ function isAlreadyProxied(url, useProxy) {
132427
+ try {
132428
+ const baseHref = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132429
+ const proxyBaseRaw = useProxy.includes("{url}") ? useProxy.split("{url}")[0] : useProxy;
132430
+ const proxyBase = new URL(proxyBaseRaw || ".", baseHref);
132431
+ const u = new URL(url, baseHref);
132432
+ if (u.origin === proxyBase.origin) return true;
132433
+ const sp = u.searchParams;
132434
+ if (sp && (sp.has("url") || sp.has("target"))) return true;
132435
+ } catch {
132436
+ }
132437
+ return false;
132438
+ }
132439
+ function shouldProxy(url, useProxy) {
132440
+ if (!useProxy) return false;
132441
+ if (isSpecialURL(url)) return false;
132442
+ if (isAlreadyProxied(url, useProxy)) return false;
132443
+ try {
132444
+ const base = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132445
+ const u = new URL(url, base);
132446
+ return typeof location !== "undefined" ? u.origin !== location.origin : true;
132447
+ } catch {
132448
+ return !!useProxy;
132449
+ }
132450
+ }
132451
+ function applyProxy(url, useProxy) {
132452
+ if (!useProxy) return url;
132453
+ if (useProxy.includes("{url}")) {
132454
+ return useProxy.replace("{urlRaw}", safeEncodeURI(url)).replace("{url}", encodeURIComponent(url));
132455
+ }
132456
+ if (/[?&]url=?$/.test(useProxy)) {
132457
+ return `${useProxy}${encodeURIComponent(url)}`;
132458
+ }
132459
+ if (useProxy.endsWith("?")) {
132460
+ return `${useProxy}url=${encodeURIComponent(url)}`;
132461
+ }
132462
+ if (useProxy.endsWith("/")) {
132463
+ return `${useProxy}${safeEncodeURI(url)}`;
132464
+ }
132465
+ const sep = useProxy.includes("?") ? "&" : "?";
132466
+ return `${useProxy}${sep}url=${encodeURIComponent(url)}`;
132467
+ }
132468
+ function blobToDataURL(blob) {
132469
+ return new Promise((res, rej) => {
132470
+ const fr = new FileReader();
132471
+ fr.onload = () => res(String(fr.result || ""));
132472
+ fr.onerror = () => rej(new Error("read_failed"));
132473
+ fr.readAsDataURL(blob);
132474
+ });
132475
+ }
132476
+ function makeKey(url, o) {
132477
+ return [
132478
+ o.as || "blob",
132479
+ o.timeout ?? 3e3,
132480
+ o.useProxy || "",
132481
+ o.errorTTL ?? 8e3,
132482
+ url
132483
+ ].join("|");
132484
+ }
132485
+ async function snapFetch(url, options = {}) {
132486
+ const as = options.as ?? "blob";
132487
+ const timeout = options.timeout ?? 3e3;
132488
+ const useProxy = options.useProxy || "";
132489
+ const errorTTL = options.errorTTL ?? 8e3;
132490
+ const headers = options.headers || {};
132491
+ const silent = !!options.silent;
132492
+ if (/^data:/i.test(url)) {
132493
+ try {
132494
+ if (as === "text") {
132495
+ return { ok: true, data: String(url), status: 200, url, fromCache: false };
132496
+ }
132497
+ if (as === "dataURL") {
132498
+ return {
132499
+ ok: true,
132500
+ data: String(url),
132501
+ status: 200,
132502
+ url,
132503
+ fromCache: false,
132504
+ mime: String(url).slice(5).split(";")[0] || ""
132505
+ };
132506
+ }
132507
+ const [, meta = "", data = ""] = String(url).match(/^data:([^,]*),(.*)$/) || [];
132508
+ const isBase64 = /;base64/i.test(meta);
132509
+ const bin = isBase64 ? atob(data) : decodeURIComponent(data);
132510
+ const bytes = new Uint8Array([...bin].map((c) => c.charCodeAt(0)));
132511
+ const b = new Blob([bytes], { type: (meta || "").split(";")[0] || "" });
132512
+ return { ok: true, data: b, status: 200, url, fromCache: false, mime: b.type || "" };
132513
+ } catch {
132514
+ return { ok: false, data: null, status: 0, url, fromCache: false, reason: "special_url_error" };
132515
+ }
132516
+ }
132517
+ if (/^blob:/i.test(url)) {
132518
+ try {
132519
+ const resp = await fetch(url);
132520
+ if (!resp.ok) {
132521
+ return { ok: false, data: null, status: resp.status, url, fromCache: false, reason: "http_error" };
132522
+ }
132523
+ const blob = await resp.blob();
132524
+ const mime = blob.type || resp.headers.get("content-type") || "";
132525
+ if (as === "dataURL") {
132526
+ const dataURL = await blobToDataURL(blob);
132527
+ return { ok: true, data: dataURL, status: resp.status, url, fromCache: false, mime };
132528
+ }
132529
+ if (as === "text") {
132530
+ const text = await blob.text();
132531
+ return { ok: true, data: text, status: resp.status, url, fromCache: false, mime };
132532
+ }
132533
+ return { ok: true, data: blob, status: resp.status, url, fromCache: false, mime };
132534
+ } catch {
132535
+ return { ok: false, data: null, status: 0, url, fromCache: false, reason: "network" };
132536
+ }
132537
+ }
132538
+ if (/^about:blank$/i.test(url)) {
132539
+ if (as === "dataURL") {
132540
+ return {
132541
+ ok: true,
132542
+ data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==",
132543
+ status: 200,
132544
+ url,
132545
+ fromCache: false,
132546
+ mime: "image/png"
132547
+ };
132548
+ }
132549
+ return { ok: true, data: as === "text" ? "" : new Blob([]), status: 200, url, fromCache: false };
132550
+ }
132551
+ const key = makeKey(url, { as, timeout, useProxy, errorTTL });
132552
+ const e = _errorCache.get(key);
132553
+ if (e && e.until > Date.now()) {
132554
+ return { ...e.result, fromCache: true };
132555
+ } else if (e) {
132556
+ _errorCache.delete(key);
132557
+ }
132558
+ const inflight = _inflight.get(key);
132559
+ if (inflight) return inflight;
132560
+ const finalURL = shouldProxy(url, useProxy) ? applyProxy(url, useProxy) : url;
132561
+ let cred = options.credentials;
132562
+ if (!cred) {
132563
+ try {
132564
+ const base = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132565
+ const u = new URL(url, base);
132566
+ const sameOrigin = typeof location !== "undefined" && u.origin === location.origin;
132567
+ cred = sameOrigin ? "include" : "omit";
132568
+ } catch {
132569
+ cred = "omit";
132570
+ }
132571
+ }
132572
+ const ctrl = new AbortController();
132573
+ const timer = setTimeout(() => ctrl.abort("timeout"), timeout);
132574
+ const p = (async () => {
132575
+ try {
132576
+ const resp = await fetch(finalURL, { signal: ctrl.signal, credentials: cred, headers });
132577
+ if (!resp.ok) {
132578
+ const result = { ok: false, data: null, status: resp.status, url: finalURL, fromCache: false, reason: "http_error" };
132579
+ if (errorTTL > 0) _errorCache.set(key, { until: Date.now() + errorTTL, result });
132580
+ if (!silent) {
132581
+ const short = `${resp.status} ${resp.statusText || ""}`.trim();
132582
+ snapLogger.warnOnce(
132583
+ `http:${resp.status}:${as}:${new URL(url, location?.href ?? "http://localhost/").origin}`,
132584
+ `HTTP error ${short} while fetching ${as} ${url}`
132585
+ );
132586
+ }
132587
+ options.onError && options.onError(result);
132588
+ return result;
132589
+ }
132590
+ if (as === "text") {
132591
+ const text = await resp.text();
132592
+ return { ok: true, data: text, status: resp.status, url: finalURL, fromCache: false };
132593
+ }
132594
+ const blob = await resp.blob();
132595
+ const mime = blob.type || resp.headers.get("content-type") || "";
132596
+ if (as === "dataURL") {
132597
+ const dataURL = await blobToDataURL(blob);
132598
+ return { ok: true, data: dataURL, status: resp.status, url: finalURL, fromCache: false, mime };
132599
+ }
132600
+ return { ok: true, data: blob, status: resp.status, url: finalURL, fromCache: false, mime };
132601
+ } catch (err) {
132602
+ const reason = err && typeof err === "object" && "name" in err && err.name === "AbortError" ? String(err.message || "").includes("timeout") ? "timeout" : "abort" : "network";
132603
+ const result = { ok: false, data: null, status: 0, url: finalURL, fromCache: false, reason };
132604
+ if (!/^blob:/i.test(url) && errorTTL > 0) {
132605
+ _errorCache.set(key, { until: Date.now() + errorTTL, result });
132606
+ }
132607
+ if (!silent) {
132608
+ const k = `${reason}:${as}:${new URL(url, location?.href ?? "http://localhost/").origin}`;
132609
+ const tips = reason === "timeout" ? `Timeout after ${timeout}ms. Consider increasing timeout or using a proxy for ${url}` : reason === "abort" ? `Request aborted while fetching ${as} ${url}` : `Network/CORS issue while fetching ${as} ${url}. A proxy may be required`;
132610
+ snapLogger.errorOnce(k, tips);
132611
+ }
132612
+ options.onError && options.onError(result);
132613
+ return result;
132614
+ } finally {
132615
+ clearTimeout(timer);
132616
+ _inflight.delete(key);
132617
+ }
132618
+ })();
132619
+ _inflight.set(key, p);
132620
+ return p;
132621
+ }
132622
+
132623
+ // src/utils/image.js
132624
+ function createBackground(baseCanvas, backgroundColor) {
132625
+ if (!backgroundColor || !baseCanvas.width || !baseCanvas.height) {
132626
+ return baseCanvas;
132627
+ }
132628
+ const temp = document.createElement("canvas");
132629
+ temp.width = baseCanvas.width;
132630
+ temp.height = baseCanvas.height;
132631
+ const ctx = temp.getContext("2d");
132632
+ ctx.fillStyle = backgroundColor;
132633
+ ctx.fillRect(0, 0, temp.width, temp.height);
132634
+ ctx.drawImage(baseCanvas, 0, 0);
132635
+ return temp;
132636
+ }
132637
+ async function inlineSingleBackgroundEntry(entry, options = {}) {
132638
+ const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\(/i.test(entry);
132639
+ if (isGradient || entry.trim() === "none") {
132640
+ return entry;
132641
+ }
132642
+ const rawUrl = extractURL(entry);
132643
+ if (!rawUrl) {
132644
+ return entry;
132645
+ }
132646
+ const encodedUrl = safeEncodeURI(rawUrl);
132647
+ if (cache.background.has(encodedUrl)) {
132648
+ const dataUrl = cache.background.get(encodedUrl);
132649
+ return dataUrl ? `url("${dataUrl}")` : "none";
132650
+ }
132651
+ try {
132652
+ const dataUrl = await snapFetch(encodedUrl, { as: "dataURL", useProxy: options.useProxy });
132653
+ if (dataUrl.ok) {
132654
+ cache.background.set(encodedUrl, dataUrl.data);
132655
+ return `url("${dataUrl.data}")`;
132656
+ }
132657
+ cache.background.set(encodedUrl, null);
132658
+ return "none";
132659
+ } catch {
132660
+ cache.background.set(encodedUrl, null);
132661
+ return "none";
132662
+ }
132663
+ }
132664
+
132665
+ // src/utils/css.js
132666
+ var NO_CAPTURE_TAGS = /* @__PURE__ */ new Set([
132667
+ "meta",
132668
+ "script",
132669
+ "noscript",
132670
+ "title",
132671
+ "link",
132672
+ "template"
132673
+ ]);
132674
+ var NO_DEFAULTS_TAGS = /* @__PURE__ */ new Set([
132675
+ // non-painting / head stuff
132676
+ "meta",
132677
+ "link",
132678
+ "style",
132679
+ "title",
132680
+ "noscript",
132681
+ "script",
132682
+ "template",
132683
+ // SVG whole namespace (safe for LeaderLine/presentation attrs)
132684
+ "g",
132685
+ "defs",
132686
+ "use",
132687
+ "marker",
132688
+ "mask",
132689
+ "clipPath",
132690
+ "pattern",
132691
+ "path",
132692
+ "polygon",
132693
+ "polyline",
132694
+ "line",
132695
+ "circle",
132696
+ "ellipse",
132697
+ "rect",
132698
+ "filter",
132699
+ "lineargradient",
132700
+ "radialgradient",
132701
+ "stop"
132702
+ ]);
132703
+ var commonTags = [
132704
+ "div",
132705
+ "span",
132706
+ "p",
132707
+ "a",
132708
+ "img",
132709
+ "ul",
132710
+ "li",
132711
+ "button",
132712
+ "input",
132713
+ "select",
132714
+ "textarea",
132715
+ "label",
132716
+ "section",
132717
+ "article",
132718
+ "header",
132719
+ "footer",
132720
+ "nav",
132721
+ "main",
132722
+ "aside",
132723
+ "h1",
132724
+ "h2",
132725
+ "h3",
132726
+ "h4",
132727
+ "h5",
132728
+ "h6",
132729
+ "table",
132730
+ "thead",
132731
+ "tbody",
132732
+ "tr",
132733
+ "td",
132734
+ "th"
132735
+ ];
132736
+ function precacheCommonTags() {
132737
+ for (let tag of commonTags) {
132738
+ const t = String(tag).toLowerCase();
132739
+ if (NO_CAPTURE_TAGS.has(t)) continue;
132740
+ if (NO_DEFAULTS_TAGS.has(t)) continue;
132741
+ getDefaultStyleForTag(t);
132742
+ }
132743
+ }
132744
+ function getDefaultStyleForTag(tagName) {
132745
+ tagName = String(tagName).toLowerCase();
132746
+ if (NO_DEFAULTS_TAGS.has(tagName)) {
132747
+ const empty = {};
132748
+ cache.defaultStyle.set(tagName, empty);
132749
+ return empty;
132750
+ }
132751
+ if (cache.defaultStyle.has(tagName)) {
132752
+ return cache.defaultStyle.get(tagName);
132753
+ }
132754
+ let sandbox = document.getElementById("snapdom-sandbox");
132755
+ if (!sandbox) {
132756
+ sandbox = document.createElement("div");
132757
+ sandbox.id = "snapdom-sandbox";
132758
+ sandbox.setAttribute("data-snapdom-sandbox", "true");
132759
+ sandbox.setAttribute("aria-hidden", "true");
132760
+ sandbox.style.position = "absolute";
132761
+ sandbox.style.left = "-9999px";
132762
+ sandbox.style.top = "-9999px";
132763
+ sandbox.style.width = "0px";
132764
+ sandbox.style.height = "0px";
132765
+ sandbox.style.overflow = "hidden";
132766
+ document.body.appendChild(sandbox);
132767
+ }
132768
+ const el = document.createElement(tagName);
132769
+ el.style.all = "initial";
132770
+ sandbox.appendChild(el);
132771
+ const styles = getComputedStyle(el);
132772
+ const defaults = {};
132773
+ for (let prop of styles) {
132774
+ if (shouldIgnoreProp(prop)) continue;
132775
+ const value = styles.getPropertyValue(prop);
132776
+ defaults[prop] = value;
132777
+ }
132778
+ sandbox.removeChild(el);
132779
+ cache.defaultStyle.set(tagName, defaults);
132780
+ return defaults;
132781
+ }
132782
+ var NO_PAINT_TOKEN = /(?:^|-)(animation|transition)(?:-|$)/i;
132783
+ var NO_PAINT_PREFIX = /^(--|view-timeline|scroll-timeline|animation-trigger|offset-|position-try|app-region|interactivity|overlay|view-transition|-webkit-locale|-webkit-user-(?:drag|modify)|-webkit-tap-highlight-color|-webkit-text-security)$/i;
132784
+ var NO_PAINT_EXACT = /* @__PURE__ */ new Set([
132785
+ // Interaction hints
132786
+ "cursor",
132787
+ "pointer-events",
132788
+ "touch-action",
132789
+ "user-select",
132790
+ // Printing/speech/reading-mode hints
132791
+ "print-color-adjust",
132792
+ "speak",
132793
+ "reading-flow",
132794
+ "reading-order",
132795
+ // Anchoring/container/timeline scopes (metadata for layout queries)
132796
+ "anchor-name",
132797
+ "anchor-scope",
132798
+ "container-name",
132799
+ "container-type",
132800
+ "timeline-scope"
132801
+ ]);
132802
+ function shouldIgnoreProp(prop) {
132803
+ const p = String(prop).toLowerCase();
132804
+ if (NO_PAINT_EXACT.has(p)) return true;
132805
+ if (NO_PAINT_PREFIX.test(p)) return true;
132806
+ if (NO_PAINT_TOKEN.test(p)) return true;
132807
+ return false;
132808
+ }
132809
+ function getStyleKey(snapshot, tagName) {
132810
+ tagName = String(tagName || "").toLowerCase();
132811
+ if (NO_DEFAULTS_TAGS.has(tagName)) {
132812
+ return "";
132813
+ }
132814
+ const entries = [];
132815
+ const defaults = getDefaultStyleForTag(tagName);
132816
+ for (let [prop, value] of Object.entries(snapshot)) {
132817
+ if (shouldIgnoreProp(prop)) continue;
132818
+ const def = defaults[prop];
132819
+ if (value && value !== def) entries.push(`${prop}:${value}`);
132820
+ }
132821
+ entries.sort();
132822
+ return entries.join(";");
132823
+ }
132824
+ function collectUsedTagNames(root) {
132825
+ const tagSet = /* @__PURE__ */ new Set();
132826
+ if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
132827
+ return [];
132828
+ }
132829
+ if (root.tagName) {
132830
+ tagSet.add(root.tagName.toLowerCase());
132831
+ }
132832
+ if (typeof root.querySelectorAll === "function") {
132833
+ root.querySelectorAll("*").forEach((el) => tagSet.add(el.tagName.toLowerCase()));
132834
+ }
132835
+ return Array.from(tagSet);
132836
+ }
132837
+ function generateDedupedBaseCSS(usedTagNames) {
132838
+ const groups = /* @__PURE__ */ new Map();
132839
+ for (let tagName of usedTagNames) {
132840
+ const styles = cache.defaultStyle.get(tagName);
132841
+ if (!styles) continue;
132842
+ const key = Object.entries(styles).map(([k, v]) => `${k}:${v};`).sort().join("");
132843
+ if (!key) continue;
132844
+ if (!groups.has(key)) {
132845
+ groups.set(key, []);
132846
+ }
132847
+ groups.get(key).push(tagName);
132848
+ }
132849
+ let css = "";
132850
+ for (let [styleBlock, tagList] of groups.entries()) {
132851
+ css += `${tagList.join(",")} { ${styleBlock} }
132852
+ `;
132853
+ }
132854
+ return css;
132855
+ }
132856
+ function generateCSSClasses(styleMap) {
132857
+ const keys = Array.from(new Set(styleMap.values())).filter(Boolean).sort();
132858
+ const classMap = /* @__PURE__ */ new Map();
132859
+ let i = 1;
132860
+ for (const k of keys) classMap.set(k, `c${i++}`);
132861
+ return classMap;
132862
+ }
132863
+ function getStyle(el, pseudo = null) {
132864
+ if (!(el instanceof Element)) {
132865
+ return window.getComputedStyle(el, pseudo);
132866
+ }
132867
+ let map = cache.computedStyle.get(el);
132868
+ if (!map) {
132869
+ map = /* @__PURE__ */ new Map();
132870
+ cache.computedStyle.set(el, map);
132871
+ }
132872
+ if (!map.has(pseudo)) {
132873
+ const st = window.getComputedStyle(el, pseudo);
132874
+ map.set(pseudo, st);
132875
+ }
132876
+ return map.get(pseudo);
132877
+ }
132878
+ function snapshotComputedStyle(style) {
132879
+ const snap = {};
132880
+ for (let prop of style) {
132881
+ snap[prop] = style.getPropertyValue(prop);
132882
+ }
132883
+ return snap;
132884
+ }
132885
+ function splitBackgroundImage(bg) {
132886
+ const parts = [];
132887
+ let depth = 0;
132888
+ let lastIndex = 0;
132889
+ for (let i = 0; i < bg.length; i++) {
132890
+ const char = bg[i];
132891
+ if (char === "(") depth++;
132892
+ if (char === ")") depth--;
132893
+ if (char === "," && depth === 0) {
132894
+ parts.push(bg.slice(lastIndex, i).trim());
132895
+ lastIndex = i + 1;
132896
+ }
132897
+ }
132898
+ parts.push(bg.slice(lastIndex).trim());
132899
+ return parts;
132900
+ }
132901
+
132902
+ // src/utils/browser.js
132903
+ function idle(fn, { fast = false } = {}) {
132904
+ if (fast) return fn();
132905
+ if ("requestIdleCallback" in window) {
132906
+ requestIdleCallback(fn, { timeout: 50 });
132907
+ } else {
132908
+ setTimeout(fn, 1);
132909
+ }
132910
+ }
132911
+ function isSafari() {
132912
+ const ua = typeof navigator !== "undefined" && navigator.userAgent ? navigator.userAgent : "";
132913
+ const isSafariUA = /^((?!chrome|android).)*safari/i.test(ua);
132914
+ const isUIWebView = /AppleWebKit/i.test(ua) && /Mobile/i.test(ua) && !/Safari/i.test(ua);
132915
+ const isWeChatUA = /(MicroMessenger|wxwork|WeCom|WindowsWechat|MacWechat)/i.test(ua);
132916
+ return isSafariUA || isUIWebView || isWeChatUA;
132917
+ }
132918
+
132919
+ // src/modules/styles.js
132920
+ var snapshotCache = /* @__PURE__ */ new WeakMap();
132921
+ var snapshotKeyCache = /* @__PURE__ */ new Map();
132922
+ var __epoch = 0;
132923
+ function bumpEpoch() {
132924
+ __epoch++;
132925
+ }
132926
+ var __wired = false;
132927
+ function setupInvalidationOnce(root = document.documentElement) {
132928
+ if (__wired) return;
132929
+ __wired = true;
132930
+ try {
132931
+ const domObs = new MutationObserver(() => bumpEpoch());
132932
+ domObs.observe(root, { subtree: true, childList: true, characterData: true, attributes: true });
132933
+ } catch {
132934
+ }
132935
+ try {
132936
+ const headObs = new MutationObserver(() => bumpEpoch());
132937
+ headObs.observe(document.head, { subtree: true, childList: true, characterData: true, attributes: true });
132938
+ } catch {
132939
+ }
132940
+ try {
132941
+ const f = document.fonts;
132942
+ if (f) {
132943
+ f.addEventListener?.("loadingdone", bumpEpoch);
132944
+ f.ready?.then(() => bumpEpoch()).catch(() => {
132945
+ });
132946
+ }
132947
+ } catch {
132948
+ }
132949
+ }
132950
+ function snapshotComputedStyleFull(style, options = {}) {
132951
+ const out = {};
132952
+ const vis = style.getPropertyValue("visibility");
132953
+ for (let i = 0; i < style.length; i++) {
132954
+ const prop = style[i];
132955
+ let val = style.getPropertyValue(prop);
132956
+ if ((prop === "background-image" || prop === "content") && val.includes("url(") && !val.includes("data:")) {
132957
+ val = "none";
132958
+ }
132959
+ out[prop] = val;
132960
+ }
132961
+ if (options.embedFonts) {
132962
+ const EXTRA_FONT_PROPS = [
132963
+ "font-feature-settings",
132964
+ "font-variation-settings",
132965
+ "font-kerning",
132966
+ "font-variant",
132967
+ "font-variant-ligatures",
132968
+ "font-optical-sizing"
132969
+ ];
132970
+ for (const prop of EXTRA_FONT_PROPS) {
132971
+ if (out[prop]) continue;
132972
+ try {
132973
+ const v = style.getPropertyValue(prop);
132974
+ if (v) out[prop] = v;
132975
+ } catch {
132976
+ }
132977
+ }
132978
+ }
132979
+ if (vis === "hidden") out.opacity = "0";
132980
+ return out;
132981
+ }
132982
+ var __snapshotSig = /* @__PURE__ */ new WeakMap();
132983
+ function styleSignature(snap) {
132984
+ let sig = __snapshotSig.get(snap);
132985
+ if (sig) return sig;
132986
+ const entries = Object.entries(snap).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
132987
+ sig = entries.map(([k, v]) => `${k}:${v}`).join(";");
132988
+ __snapshotSig.set(snap, sig);
132989
+ return sig;
132990
+ }
132991
+ function getSnapshot(el, preStyle = null, options = {}) {
132992
+ const rec = snapshotCache.get(el);
132993
+ if (rec && rec.epoch === __epoch) return rec.snapshot;
132994
+ const style = preStyle || getComputedStyle(el);
132995
+ const snap = snapshotComputedStyleFull(style, options);
132996
+ stripHeightForWrappers(el, style, snap);
132997
+ snapshotCache.set(el, { epoch: __epoch, snapshot: snap });
132998
+ return snap;
132999
+ }
133000
+ function _resolveCtx(sessionOrCtx, opts) {
133001
+ if (sessionOrCtx && sessionOrCtx.session && sessionOrCtx.persist) return sessionOrCtx;
133002
+ if (sessionOrCtx && (sessionOrCtx.styleMap || sessionOrCtx.styleCache || sessionOrCtx.nodeMap)) {
133003
+ return {
133004
+ session: sessionOrCtx,
133005
+ persist: {
133006
+ snapshotKeyCache,
133007
+ defaultStyle: cache.defaultStyle,
133008
+ baseStyle: cache.baseStyle,
133009
+ image: cache.image,
133010
+ resource: cache.resource,
133011
+ background: cache.background,
133012
+ font: cache.font
133013
+ },
133014
+ options: opts || {}
133015
+ };
133016
+ }
133017
+ return {
133018
+ session: cache.session,
133019
+ persist: {
133020
+ snapshotKeyCache,
133021
+ defaultStyle: cache.defaultStyle,
133022
+ baseStyle: cache.baseStyle,
133023
+ image: cache.image,
133024
+ resource: cache.resource,
133025
+ background: cache.background,
133026
+ font: cache.font
133027
+ },
133028
+ options: sessionOrCtx || opts || {}
133029
+ };
133030
+ }
133031
+ async function inlineAllStyles(source, clone, sessionOrCtx, opts) {
133032
+ if (source.tagName === "STYLE") return;
133033
+ const ctx = _resolveCtx(sessionOrCtx, opts);
133034
+ const resetMode = ctx.options && ctx.options.cache || "auto";
133035
+ if (resetMode !== "disabled") setupInvalidationOnce(document.documentElement);
133036
+ if (resetMode === "disabled" && !ctx.session.__bumpedForDisabled) {
133037
+ bumpEpoch();
133038
+ snapshotKeyCache.clear();
133039
+ ctx.session.__bumpedForDisabled = true;
133040
+ }
133041
+ if (NO_DEFAULTS_TAGS.has(source.tagName?.toLowerCase())) {
133042
+ const author = source.getAttribute?.("style");
133043
+ if (author) clone.setAttribute("style", author);
133044
+ }
133045
+ const { session, persist } = ctx;
133046
+ if (!session.styleCache.has(source)) {
133047
+ session.styleCache.set(source, getComputedStyle(source));
133048
+ }
133049
+ const pre = session.styleCache.get(source);
133050
+ const snap = getSnapshot(source, pre, ctx.options);
133051
+ const sig = styleSignature(snap);
133052
+ let key = persist.snapshotKeyCache.get(sig);
133053
+ if (!key) {
133054
+ const tag = source.tagName?.toLowerCase() || "div";
133055
+ key = getStyleKey(snap, tag);
133056
+ persist.snapshotKeyCache.set(sig, key);
133057
+ }
133058
+ session.styleMap.set(clone, key);
133059
+ }
133060
+ function isReplaced(el) {
133061
+ return el instanceof HTMLImageElement || el instanceof HTMLCanvasElement || el instanceof HTMLVideoElement || el instanceof HTMLIFrameElement || el instanceof SVGElement || el instanceof HTMLObjectElement || el instanceof HTMLEmbedElement;
133062
+ }
133063
+ function hasBox(cs) {
133064
+ if (cs.backgroundImage && cs.backgroundImage !== "none") return true;
133065
+ if (cs.backgroundColor && cs.backgroundColor !== "rgba(0, 0, 0, 0)" && cs.backgroundColor !== "transparent") return true;
133066
+ if ((parseFloat(cs.borderTopWidth) || 0) > 0) return true;
133067
+ if ((parseFloat(cs.borderBottomWidth) || 0) > 0) return true;
133068
+ if ((parseFloat(cs.paddingTop) || 0) > 0) return true;
133069
+ if ((parseFloat(cs.paddingBottom) || 0) > 0) return true;
133070
+ const ob = cs.overflowBlock || cs.overflowY || "visible";
133071
+ return ob !== "visible";
133072
+ }
133073
+ function isFlexOrGridItem(el) {
133074
+ const p = el.parentElement;
133075
+ if (!p) return false;
133076
+ const pd = getComputedStyle(p).display || "";
133077
+ return pd.includes("flex") || pd.includes("grid");
133078
+ }
133079
+ function hasFlowFast(el, cs) {
133080
+ if (el.textContent && /\S/.test(el.textContent)) return true;
133081
+ const f = el.firstElementChild, l = el.lastElementChild;
133082
+ if (f && f.tagName === "BR" || l && l.tagName === "BR") return true;
133083
+ const sh = el.scrollHeight;
133084
+ if (sh === 0) return false;
133085
+ const pt = parseFloat(cs.paddingTop) || 0;
133086
+ const pb = parseFloat(cs.paddingBottom) || 0;
133087
+ return sh > pt + pb;
133088
+ }
133089
+ function stripHeightForWrappers(el, cs, snap) {
133090
+ if (el instanceof HTMLElement && el.style && el.style.height) return;
133091
+ const disp = cs.display || "";
133092
+ if (disp.includes("flex") || disp.includes("grid")) return;
133093
+ if (isReplaced(el)) return;
133094
+ const pos = cs.position;
133095
+ if (pos === "absolute" || pos === "fixed" || pos === "sticky") return;
133096
+ if (cs.transform !== "none") return;
133097
+ if (hasBox(cs)) return;
133098
+ if (isFlexOrGridItem(el)) return;
133099
+ if (!hasFlowFast(el, cs)) return;
133100
+ delete snap.height;
133101
+ delete snap["block-size"];
133102
+ }
133103
+
133104
+ // src/modules/CSSVar.js
133105
+ function resolveCSSVars(sourceEl, cloneEl) {
133106
+ if (!(sourceEl instanceof Element) || !(cloneEl instanceof Element)) return;
133107
+ const styleAttr = sourceEl.getAttribute?.("style");
133108
+ let hasVar = !!(styleAttr && styleAttr.includes("var("));
133109
+ if (!hasVar && sourceEl.attributes?.length) {
133110
+ const attrs = sourceEl.attributes;
133111
+ for (let i = 0; i < attrs.length; i++) {
133112
+ const a = attrs[i];
133113
+ if (a && typeof a.value === "string" && a.value.includes("var(")) {
133114
+ hasVar = true;
133115
+ break;
133116
+ }
133117
+ }
133118
+ }
133119
+ if (!hasVar) return;
133120
+ let cs;
133121
+ try {
133122
+ cs = getComputedStyle(sourceEl);
133123
+ } catch {
133124
+ return;
133125
+ }
133126
+ const author = sourceEl.style;
133127
+ if (author && author.length) {
133128
+ for (let i = 0; i < author.length; i++) {
133129
+ const prop = author[i];
133130
+ const val = author.getPropertyValue(prop);
133131
+ if (!val || !val.includes("var(")) continue;
133132
+ const resolved = cs.getPropertyValue(prop);
133133
+ if (resolved) {
133134
+ try {
133135
+ cloneEl.style.setProperty(prop, resolved.trim(), author.getPropertyPriority(prop));
133136
+ } catch {
133137
+ }
133138
+ }
133139
+ }
133140
+ }
133141
+ if (sourceEl.attributes?.length) {
133142
+ const attrs = sourceEl.attributes;
133143
+ for (let i = 0; i < attrs.length; i++) {
133144
+ const a = attrs[i];
133145
+ if (!a || typeof a.value !== "string" || !a.value.includes("var(")) continue;
133146
+ const propName = a.name;
133147
+ let resolved = "";
133148
+ try {
133149
+ resolved = cs.getPropertyValue(propName);
133150
+ } catch {
133151
+ }
133152
+ if (resolved) {
133153
+ try {
133154
+ cloneEl.style.setProperty(propName, resolved.trim());
133155
+ } catch {
133156
+ }
133157
+ }
133158
+ }
133159
+ }
133160
+ }
133161
+
133162
+ // src/core/clone.js
133163
+ function idleCallback(childList, callback, fast) {
133164
+ return Promise.all(childList.map((child) => {
133165
+ return new Promise((resolve) => {
133166
+ function deal() {
133167
+ idle((deadline) => {
133168
+ const hasIdleBudget = deadline && typeof deadline.timeRemaining === "function" ? deadline.timeRemaining() > 0 : true;
133169
+ if (hasIdleBudget) {
133170
+ callback(child, resolve);
133171
+ } else {
133172
+ deal();
133173
+ }
133174
+ }, { fast });
133175
+ }
133176
+ deal();
133177
+ });
133178
+ }));
133179
+ }
133180
+ function addNotSlottedRightmost(sel) {
133181
+ sel = sel.trim();
133182
+ if (!sel) return sel;
133183
+ if (/:not\(\s*\[data-sd-slotted\]\s*\)\s*$/.test(sel)) return sel;
133184
+ return `${sel}:not([data-sd-slotted])`;
133185
+ }
133186
+ function wrapWithScope(selectorList, scopeSelector, excludeSlotted = true) {
133187
+ return selectorList.split(",").map((s) => s.trim()).filter(Boolean).map((s) => {
133188
+ if (s.startsWith(":where(")) return s;
133189
+ if (s.startsWith("@")) return s;
133190
+ const body = excludeSlotted ? addNotSlottedRightmost(s) : s;
133191
+ return `:where(${scopeSelector} ${body})`;
133192
+ }).join(", ");
133193
+ }
133194
+ function rewriteShadowCSS(cssText, scopeSelector) {
133195
+ if (!cssText) return "";
133196
+ cssText = cssText.replace(/:host\(([^)]+)\)/g, (_, sel) => {
133197
+ return `:where(${scopeSelector}:is(${sel.trim()}))`;
133198
+ });
133199
+ cssText = cssText.replace(/:host\b/g, `:where(${scopeSelector})`);
133200
+ cssText = cssText.replace(/:host-context\(([^)]+)\)/g, (_, sel) => {
133201
+ return `:where(:where(${sel.trim()}) ${scopeSelector})`;
133202
+ });
133203
+ cssText = cssText.replace(/::slotted\(([^)]+)\)/g, (_, sel) => {
133204
+ return `:where(${scopeSelector} ${sel.trim()})`;
133205
+ });
133206
+ cssText = cssText.replace(/(^|})(\s*)([^@}{]+){/g, (_, brace, ws, selectorList) => {
133207
+ const wrapped = wrapWithScope(
133208
+ selectorList,
133209
+ scopeSelector,
133210
+ /*excludeSlotted*/
133211
+ true
133212
+ );
133213
+ return `${brace}${ws}${wrapped}{`;
133214
+ });
133215
+ return cssText;
133216
+ }
133217
+ function nextShadowScopeId(sessionCache) {
133218
+ sessionCache.shadowScopeSeq = (sessionCache.shadowScopeSeq || 0) + 1;
133219
+ return `s${sessionCache.shadowScopeSeq}`;
133220
+ }
133221
+ function extractShadowCSS(sr) {
133222
+ let css = "";
133223
+ try {
133224
+ sr.querySelectorAll("style").forEach((s) => {
133225
+ css += (s.textContent || "") + "\n";
133226
+ });
133227
+ const sheets = sr.adoptedStyleSheets || [];
133228
+ for (const sh of sheets) {
133229
+ try {
133230
+ if (sh && sh.cssRules) {
133231
+ for (const rule of sh.cssRules) css += rule.cssText + "\n";
133232
+ }
133233
+ } catch {
133234
+ }
133235
+ }
133236
+ } catch {
133237
+ }
133238
+ return css;
133239
+ }
133240
+ function injectScopedStyle(hostClone, cssText, scopeId) {
133241
+ if (!cssText) return;
133242
+ const style = document.createElement("style");
133243
+ style.setAttribute("data-sd", scopeId);
133244
+ style.textContent = cssText;
133245
+ hostClone.insertBefore(style, hostClone.firstChild || null);
133246
+ }
133247
+ function freezeImgSrcset(original, cloned) {
133248
+ try {
133249
+ const chosen = original.currentSrc || original.src || "";
133250
+ if (!chosen) return;
133251
+ cloned.setAttribute("src", chosen);
133252
+ cloned.removeAttribute("srcset");
133253
+ cloned.removeAttribute("sizes");
133254
+ cloned.loading = "eager";
133255
+ cloned.decoding = "sync";
133256
+ } catch {
133257
+ }
133258
+ }
133259
+ function collectCustomPropsFromCSS(cssText) {
133260
+ const out = /* @__PURE__ */ new Set();
133261
+ if (!cssText) return out;
133262
+ const re = /var\(\s*(--[A-Za-z0-9_-]+)\b/g;
133263
+ let m;
133264
+ while (m = re.exec(cssText)) out.add(m[1]);
133265
+ return out;
133266
+ }
133267
+ function resolveCustomProp(el, name) {
133268
+ try {
133269
+ const cs = getComputedStyle(el);
133270
+ let v = cs.getPropertyValue(name).trim();
133271
+ if (v) return v;
133272
+ } catch {
133273
+ }
133274
+ try {
133275
+ const rootCS = getComputedStyle(document.documentElement);
133276
+ let v = rootCS.getPropertyValue(name).trim();
133277
+ if (v) return v;
133278
+ } catch {
133279
+ }
133280
+ return "";
133281
+ }
133282
+ function buildSeedCustomPropsRule(hostEl, names, scopeSelector) {
133283
+ const decls = [];
133284
+ for (const name of names) {
133285
+ const val = resolveCustomProp(hostEl, name);
133286
+ if (val) decls.push(`${name}: ${val};`);
133287
+ }
133288
+ if (!decls.length) return "";
133289
+ return `${scopeSelector}{${decls.join("")}}
133290
+ `;
133291
+ }
133292
+ function markSlottedSubtree(root) {
133293
+ if (!root) return;
133294
+ if (root.nodeType === Node.ELEMENT_NODE) {
133295
+ root.setAttribute("data-sd-slotted", "");
133296
+ }
133297
+ if (root.querySelectorAll) {
133298
+ root.querySelectorAll("*").forEach((el) => el.setAttribute("data-sd-slotted", ""));
133299
+ }
133300
+ }
133301
+ async function getAccessibleIframeDocument(iframe, attempts = 3) {
133302
+ const probe = () => {
133303
+ try {
133304
+ return iframe.contentDocument || iframe.contentWindow?.document || null;
133305
+ } catch {
133306
+ return null;
133307
+ }
133308
+ };
133309
+ let doc = probe();
133310
+ let i = 0;
133311
+ while (i < attempts && (!doc || !doc.body && !doc.documentElement)) {
133312
+ await new Promise((r) => setTimeout(r, 0));
133313
+ doc = probe();
133314
+ i++;
133315
+ }
133316
+ return doc && (doc.body || doc.documentElement) ? doc : null;
133317
+ }
133318
+ function measureContentBox(el) {
133319
+ const rect = el.getBoundingClientRect();
133320
+ let bl = 0, br = 0, bt = 0, bb = 0;
133321
+ try {
133322
+ const cs = getComputedStyle(el);
133323
+ bl = parseFloat(cs.borderLeftWidth) || 0;
133324
+ br = parseFloat(cs.borderRightWidth) || 0;
133325
+ bt = parseFloat(cs.borderTopWidth) || 0;
133326
+ bb = parseFloat(cs.borderBottomWidth) || 0;
133327
+ } catch {
133328
+ }
133329
+ const contentWidth = Math.max(0, Math.round(rect.width - (bl + br)));
133330
+ const contentHeight = Math.max(0, Math.round(rect.height - (bt + bb)));
133331
+ return { contentWidth, contentHeight, rect };
133332
+ }
133333
+ function pinIframeViewport(doc, w, h) {
133334
+ const style = doc.createElement("style");
133335
+ style.setAttribute("data-sd-iframe-pin", "");
133336
+ style.textContent = `html, body {margin: 0 !important;padding: 0 !important;width: ${w}px !important;height: ${h}px !important;min-width: ${w}px !important;min-height: ${h}px !important;box-sizing: border-box !important;overflow: hidden !important;background-clip: border-box !important;}`;
133337
+ (doc.head || doc.documentElement).appendChild(style);
133338
+ return () => {
133339
+ try {
133340
+ style.remove();
133341
+ } catch {
133342
+ }
133343
+ };
133344
+ }
133345
+ async function rasterizeIframe(iframe, sessionCache, options) {
133346
+ const doc = await getAccessibleIframeDocument(iframe, 3);
133347
+ if (!doc) throw new Error("iframe document not accessible/ready");
133348
+ const { contentWidth, contentHeight, rect } = measureContentBox(iframe);
133349
+ const snap = options?.snap;
133350
+ if (!snap || typeof snap.toPng !== "function") {
133351
+ throw new Error("snapdom.toPng not available in iframe or window");
133352
+ }
133353
+ const nested = { ...options, scale: 1 };
133354
+ const unpin = pinIframeViewport(doc, contentWidth, contentHeight);
133355
+ let imgEl;
133356
+ try {
133357
+ imgEl = await snap.toPng(doc.documentElement, nested);
133358
+ } finally {
133359
+ unpin();
133360
+ }
133361
+ imgEl.style.display = "block";
133362
+ imgEl.style.width = `${contentWidth}px`;
133363
+ imgEl.style.height = `${contentHeight}px`;
133364
+ const wrapper = document.createElement("div");
133365
+ sessionCache.nodeMap.set(wrapper, iframe);
133366
+ inlineAllStyles(iframe, wrapper, sessionCache, options);
133367
+ wrapper.style.overflow = "hidden";
133368
+ wrapper.style.display = "block";
133369
+ if (!wrapper.style.width) wrapper.style.width = `${Math.round(rect.width)}px`;
133370
+ if (!wrapper.style.height) wrapper.style.height = `${Math.round(rect.height)}px`;
133371
+ wrapper.appendChild(imgEl);
133372
+ return wrapper;
133373
+ }
133374
+ async function deepClone(node, sessionCache, options) {
133375
+ if (!node) throw new Error("Invalid node");
133376
+ const clonedAssignedNodes = /* @__PURE__ */ new Set();
133377
+ let pendingSelectValue = null;
133378
+ let pendingTextAreaValue = null;
133379
+ if (node.nodeType === Node.ELEMENT_NODE) {
133380
+ const tag = (node.localName || node.tagName || "").toLowerCase();
133381
+ if (node.id === "snapdom-sandbox" || node.hasAttribute("data-snapdom-sandbox")) {
133382
+ return null;
133383
+ }
133384
+ if (NO_CAPTURE_TAGS.has(tag)) {
133385
+ return null;
133386
+ }
133387
+ }
133388
+ if (node.nodeType === Node.TEXT_NODE) {
133389
+ return node.cloneNode(true);
133390
+ }
133391
+ if (node.nodeType !== Node.ELEMENT_NODE) {
133392
+ return node.cloneNode(true);
133393
+ }
133394
+ if (node.getAttribute("data-capture") === "exclude") {
133395
+ if (options.excludeMode === "hide") {
133396
+ const spacer = document.createElement("div");
133397
+ const rect = node.getBoundingClientRect();
133398
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133399
+ return spacer;
133400
+ } else if (options.excludeMode === "remove") {
133401
+ return null;
133402
+ }
133403
+ }
133404
+ if (options.exclude && Array.isArray(options.exclude)) {
133405
+ for (const selector of options.exclude) {
133406
+ try {
133407
+ if (node.matches?.(selector)) {
133408
+ if (options.excludeMode === "hide") {
133409
+ const spacer = document.createElement("div");
133410
+ const rect = node.getBoundingClientRect();
133411
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133412
+ return spacer;
133413
+ } else if (options.excludeMode === "remove") {
133414
+ return null;
133415
+ }
133416
+ }
133417
+ } catch (err) {
133418
+ console.warn(`Invalid selector in exclude option: ${selector}`, err);
133419
+ }
133420
+ }
133421
+ }
133422
+ if (typeof options.filter === "function") {
133423
+ try {
133424
+ if (!options.filter(node)) {
133425
+ if (options.filterMode === "hide") {
133426
+ const spacer = document.createElement("div");
133427
+ const rect = node.getBoundingClientRect();
133428
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133429
+ return spacer;
133430
+ } else if (options.filterMode === "remove") {
133431
+ return null;
133432
+ }
133433
+ }
133434
+ } catch (err) {
133435
+ console.warn("Error in filter function:", err);
133436
+ }
133437
+ }
133438
+ if (node.tagName === "IFRAME") {
133439
+ let sameOrigin = false;
133440
+ try {
133441
+ sameOrigin = !!(node.contentDocument || node.contentWindow?.document);
133442
+ } catch {
133443
+ sameOrigin = false;
133444
+ }
133445
+ if (sameOrigin) {
133446
+ try {
133447
+ const wrapper = await rasterizeIframe(node, sessionCache, options);
133448
+ return wrapper;
133449
+ } catch (err) {
133450
+ console.warn("[SnapDOM] iframe rasterization failed, fallback:", err);
133451
+ }
133452
+ }
133453
+ if (options.placeholders) {
133454
+ const fallback = document.createElement("div");
133455
+ fallback.style.cssText = `width:${node.offsetWidth}px;height:${node.offsetHeight}px;background-image:repeating-linear-gradient(45deg,#ddd,#ddd 5px,#f9f9f9 5px,#f9f9f9 10px);display:flex;align-items:center;justify-content:center;font-size:12px;color:#555;border:1px solid #aaa;`;
133456
+ inlineAllStyles(node, fallback, sessionCache, options);
133457
+ return fallback;
133458
+ } else {
133459
+ const rect = node.getBoundingClientRect();
133460
+ const spacer = document.createElement("div");
133461
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133462
+ inlineAllStyles(node, spacer, sessionCache, options);
133463
+ return spacer;
133464
+ }
133465
+ }
133466
+ if (node.getAttribute("data-capture") === "placeholder") {
133467
+ const clone2 = node.cloneNode(false);
133468
+ sessionCache.nodeMap.set(clone2, node);
133469
+ inlineAllStyles(node, clone2, sessionCache, options);
133470
+ const placeholder = document.createElement("div");
133471
+ placeholder.textContent = node.getAttribute("data-placeholder-text") || "";
133472
+ placeholder.style.cssText = "color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;";
133473
+ clone2.appendChild(placeholder);
133474
+ return clone2;
133475
+ }
133476
+ if (node.tagName === "CANVAS") {
133477
+ const dataURL = node.toDataURL();
133478
+ const img = document.createElement("img");
133479
+ img.src = dataURL;
133480
+ img.width = node.width;
133481
+ img.height = node.height;
133482
+ sessionCache.nodeMap.set(img, node);
133483
+ inlineAllStyles(node, img, sessionCache, options);
133484
+ return img;
133485
+ }
133486
+ let clone;
133487
+ try {
133488
+ clone = node.cloneNode(false);
133489
+ resolveCSSVars(node, clone);
133490
+ sessionCache.nodeMap.set(clone, node);
133491
+ if (node.tagName === "IMG") {
133492
+ freezeImgSrcset(node, clone);
133493
+ try {
133494
+ const rect = node.getBoundingClientRect();
133495
+ let w = Math.round(rect.width || 0);
133496
+ let h = Math.round(rect.height || 0);
133497
+ if (!w || !h) {
133498
+ const computed = window.getComputedStyle(node);
133499
+ const cssW = parseFloat(computed.width) || 0;
133500
+ const cssH = parseFloat(computed.height) || 0;
133501
+ const attrW = parseInt(node.getAttribute("width") || "", 10) || 0;
133502
+ const attrH = parseInt(node.getAttribute("height") || "", 10) || 0;
133503
+ const propW = node.width || node.naturalWidth || 0;
133504
+ const propH = node.height || node.naturalHeight || 0;
133505
+ w = Math.round(w || cssW || attrW || propW || 0);
133506
+ h = Math.round(h || cssH || attrH || propH || 0);
133507
+ }
133508
+ if (w) clone.dataset.snapdomWidth = String(w);
133509
+ if (h) clone.dataset.snapdomHeight = String(h);
133510
+ } catch {
133511
+ }
133512
+ }
133513
+ } catch (err) {
133514
+ console.error("[Snapdom] Failed to clone node:", node, err);
133515
+ throw err;
133516
+ }
133517
+ if (node instanceof HTMLTextAreaElement) {
133518
+ const rect = node.getBoundingClientRect();
133519
+ clone.style.width = `${rect.width}px`;
133520
+ clone.style.height = `${rect.height}px`;
133521
+ }
133522
+ if (node instanceof HTMLInputElement) {
133523
+ clone.value = node.value;
133524
+ clone.setAttribute("value", node.value);
133525
+ if (node.checked !== void 0) {
133526
+ clone.checked = node.checked;
133527
+ if (node.checked) clone.setAttribute("checked", "");
133528
+ if (node.indeterminate) clone.indeterminate = node.indeterminate;
133529
+ }
133530
+ }
133531
+ if (node instanceof HTMLSelectElement) {
133532
+ pendingSelectValue = node.value;
133533
+ }
133534
+ if (node instanceof HTMLTextAreaElement) {
133535
+ pendingTextAreaValue = node.value;
133536
+ }
133537
+ inlineAllStyles(node, clone, sessionCache, options);
133538
+ if (node.shadowRoot) {
133539
+ let callback2 = function(child, resolve) {
133540
+ if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "STYLE") {
133541
+ return resolve(null);
133542
+ } else {
133543
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133544
+ resolve(clonedChild || null);
133545
+ }).catch(() => {
133546
+ resolve(null);
133547
+ });
133548
+ }
133549
+ };
133550
+ try {
133551
+ const slots = node.shadowRoot.querySelectorAll("slot");
133552
+ for (const s of slots) {
133553
+ let assigned = [];
133554
+ try {
133555
+ assigned = s.assignedNodes?.({ flatten: true }) || s.assignedNodes?.() || [];
133556
+ } catch {
133557
+ assigned = s.assignedNodes?.() || [];
133558
+ }
133559
+ for (const an of assigned) clonedAssignedNodes.add(an);
133560
+ }
133561
+ } catch {
133562
+ }
133563
+ const scopeId = nextShadowScopeId(sessionCache);
133564
+ const scopeSelector = `[data-sd="${scopeId}"]`;
133565
+ try {
133566
+ clone.setAttribute("data-sd", scopeId);
133567
+ } catch {
133568
+ }
133569
+ const rawCSS = extractShadowCSS(node.shadowRoot);
133570
+ const rewritten = rewriteShadowCSS(rawCSS, scopeSelector);
133571
+ const neededVars = collectCustomPropsFromCSS(rawCSS);
133572
+ const seed = buildSeedCustomPropsRule(node, neededVars, scopeSelector);
133573
+ injectScopedStyle(clone, seed + rewritten, scopeId);
133574
+ const shadowFrag = document.createDocumentFragment();
133575
+ const cloneList2 = await idleCallback(Array.from(node.shadowRoot.childNodes), callback2, options.fast);
133576
+ shadowFrag.append(...cloneList2.filter((clonedChild) => !!clonedChild));
133577
+ clone.appendChild(shadowFrag);
133578
+ }
133579
+ if (node.tagName === "SLOT") {
133580
+ let callback2 = function(child, resolve) {
133581
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133582
+ if (clonedChild) {
133583
+ markSlottedSubtree(clonedChild);
133584
+ }
133585
+ resolve(clonedChild || null);
133586
+ }).catch(() => {
133587
+ resolve(null);
133588
+ });
133589
+ };
133590
+ const assigned = node.assignedNodes?.({ flatten: true }) || [];
133591
+ const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);
133592
+ const fragment = document.createDocumentFragment();
133593
+ const cloneList2 = await idleCallback(Array.from(nodesToClone), callback2, options.fast);
133594
+ fragment.append(...cloneList2.filter((clonedChild) => !!clonedChild));
133595
+ return fragment;
133596
+ }
133597
+ function callback(child, resolve) {
133598
+ if (clonedAssignedNodes.has(child)) return resolve(null);
133599
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133600
+ resolve(clonedChild || null);
133601
+ }).catch(() => {
133602
+ resolve(null);
133603
+ });
133604
+ }
133605
+ const cloneList = await idleCallback(Array.from(node.childNodes), callback, options.fast);
133606
+ clone.append(...cloneList.filter((clonedChild) => !!clonedChild));
133607
+ if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {
133608
+ clone.value = pendingSelectValue;
133609
+ for (const opt of clone.options) {
133610
+ if (opt.value === pendingSelectValue) {
133611
+ opt.setAttribute("selected", "");
133612
+ } else {
133613
+ opt.removeAttribute("selected");
133614
+ }
133615
+ }
133616
+ }
133617
+ if (pendingTextAreaValue !== null && clone instanceof HTMLTextAreaElement) {
133618
+ clone.textContent = pendingTextAreaValue;
133619
+ }
133620
+ return clone;
133621
+ }
133622
+
133623
+ // src/modules/iconFonts.js
133624
+ var defaultIconFonts = [
133625
+ // /uicons/i,
133626
+ /font\s*awesome/i,
133627
+ /material\s*icons/i,
133628
+ /ionicons/i,
133629
+ /glyphicons/i,
133630
+ /feather/i,
133631
+ /bootstrap\s*icons/i,
133632
+ /remix\s*icons/i,
133633
+ /heroicons/i,
133634
+ /layui/i,
133635
+ /lucide/i
133636
+ ];
133637
+ var userIconFonts = [];
133638
+ function extendIconFonts(fonts) {
133639
+ const list = Array.isArray(fonts) ? fonts : [fonts];
133640
+ for (const f of list) {
133641
+ if (f instanceof RegExp) {
133642
+ userIconFonts.push(f);
133643
+ } else if (typeof f === "string") {
133644
+ userIconFonts.push(new RegExp(f, "i"));
133645
+ } else {
133646
+ console.warn("[snapdom] Ignored invalid iconFont value:", f);
133647
+ }
133648
+ }
133649
+ }
133650
+ function isIconFont2(input) {
133651
+ const text = typeof input === "string" ? input : "";
133652
+ const candidates = [...defaultIconFonts, ...userIconFonts];
133653
+ for (const rx of candidates) {
133654
+ if (rx instanceof RegExp && rx.test(text)) return true;
133655
+ }
133656
+ if (/icon/i.test(text) || /glyph/i.test(text) || /symbols/i.test(text) || /feather/i.test(text) || /fontawesome/i.test(text)) return true;
133657
+ return false;
133658
+ }
133659
+
133660
+ // src/modules/fonts.js
133661
+ async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = "#000") {
133662
+ fontFamily = fontFamily.replace(/^['"]+|['"]+$/g, "");
133663
+ const dpr = window.devicePixelRatio || 1;
133664
+ try {
133665
+ await document.fonts.ready;
133666
+ } catch {
133667
+ }
133668
+ const span = document.createElement("span");
133669
+ span.textContent = unicodeChar;
133670
+ span.style.position = "absolute";
133671
+ span.style.visibility = "hidden";
133672
+ span.style.fontFamily = `"${fontFamily}"`;
133673
+ span.style.fontWeight = fontWeight || "normal";
133674
+ span.style.fontSize = `${fontSize}px`;
133675
+ span.style.lineHeight = "1";
133676
+ span.style.whiteSpace = "nowrap";
133677
+ span.style.padding = "0";
133678
+ span.style.margin = "0";
133679
+ document.body.appendChild(span);
133680
+ const rect = span.getBoundingClientRect();
133681
+ const width = Math.ceil(rect.width);
133682
+ const height = Math.ceil(rect.height);
133683
+ document.body.removeChild(span);
133684
+ const canvas = document.createElement("canvas");
133685
+ canvas.width = Math.max(1, width * dpr);
133686
+ canvas.height = Math.max(1, height * dpr);
133687
+ const ctx = canvas.getContext("2d");
133688
+ ctx.scale(dpr, dpr);
133689
+ ctx.font = fontWeight ? `${fontWeight} ${fontSize}px "${fontFamily}"` : `${fontSize}px "${fontFamily}"`;
133690
+ ctx.textAlign = "left";
133691
+ ctx.textBaseline = "top";
133692
+ ctx.fillStyle = color;
133693
+ ctx.fillText(unicodeChar, 0, 0);
133694
+ return {
133695
+ dataUrl: canvas.toDataURL(),
133696
+ width,
133697
+ height
133698
+ };
133699
+ }
133700
+ var GENERIC_FAMILIES = /* @__PURE__ */ new Set([
133701
+ "serif",
133702
+ "sans-serif",
133703
+ "monospace",
133704
+ "cursive",
133705
+ "fantasy",
133706
+ "system-ui",
133707
+ "emoji",
133708
+ "math",
133709
+ "fangsong",
133710
+ "ui-serif",
133711
+ "ui-sans-serif",
133712
+ "ui-monospace",
133713
+ "ui-rounded"
133714
+ ]);
133715
+ function pickPrimaryFamily(familyList) {
133716
+ if (!familyList) return "";
133717
+ for (let raw of familyList.split(",")) {
133718
+ let f = raw.trim().replace(/^['"]+|['"]+$/g, "");
133719
+ if (!f) continue;
133720
+ if (!GENERIC_FAMILIES.has(f.toLowerCase())) return f;
133721
+ }
133722
+ return "";
133723
+ }
133724
+ function normWeight(w) {
133725
+ const t = String(w ?? "400").trim().toLowerCase();
133726
+ if (t === "normal") return 400;
133727
+ if (t === "bold") return 700;
133728
+ const n = parseInt(t, 10);
133729
+ return Number.isFinite(n) ? Math.min(900, Math.max(100, n)) : 400;
133730
+ }
133731
+ function normStyle(s) {
133732
+ const t = String(s ?? "normal").trim().toLowerCase();
133733
+ if (t.startsWith("italic")) return "italic";
133734
+ if (t.startsWith("oblique")) return "oblique";
133735
+ return "normal";
133736
+ }
133737
+ function normStretchPct(st) {
133738
+ const m = String(st ?? "100%").match(/(\d+(?:\.\d+)?)\s*%/);
133739
+ return m ? Math.max(50, Math.min(200, parseFloat(m[1]))) : 100;
133740
+ }
133741
+ function parseWeightSpec(spec) {
133742
+ const s = String(spec || "400").trim();
133743
+ const m = s.match(/^(\d{2,3})\s+(\d{2,3})$/);
133744
+ if (m) {
133745
+ const a = normWeight(m[1]), b = normWeight(m[2]);
133746
+ return { min: Math.min(a, b), max: Math.max(a, b) };
133747
+ }
133748
+ const v = normWeight(s);
133749
+ return { min: v, max: v };
133750
+ }
133751
+ function parseStyleSpec(spec) {
133752
+ const t = String(spec || "normal").trim().toLowerCase();
133753
+ if (t === "italic") return { kind: "italic" };
133754
+ if (t.startsWith("oblique")) return { kind: "oblique" };
133755
+ return { kind: "normal" };
133756
+ }
133757
+ function parseStretchSpec(spec) {
133758
+ const s = String(spec || "100%").trim();
133759
+ const mm = s.match(/(\d+(?:\.\d+)?)\s*%\s+(\d+(?:\.\d+)?)\s*%/);
133760
+ if (mm) {
133761
+ const a = parseFloat(mm[1]), b = parseFloat(mm[2]);
133762
+ return { min: Math.min(a, b), max: Math.max(a, b) };
133763
+ }
133764
+ const m = s.match(/(\d+(?:\.\d+)?)\s*%/);
133765
+ const v = m ? parseFloat(m[1]) : 100;
133766
+ return { min: v, max: v };
133767
+ }
133768
+ function isLikelyFontStylesheet(href, requiredFamilies) {
133769
+ if (!href) return false;
133770
+ try {
133771
+ const u = new URL(href, location.href);
133772
+ const sameOrigin = u.origin === location.origin;
133773
+ if (sameOrigin) return true;
133774
+ const host = u.host.toLowerCase();
133775
+ const FONT_HOSTS = [
133776
+ "fonts.googleapis.com",
133777
+ "fonts.gstatic.com",
133778
+ "use.typekit.net",
133779
+ "p.typekit.net",
133780
+ "kit.fontawesome.com",
133781
+ "use.fontawesome.com"
133782
+ ];
133783
+ if (FONT_HOSTS.some((h) => host.endsWith(h))) return true;
133784
+ const path = (u.pathname + u.search).toLowerCase();
133785
+ if (/\bfont(s)?\b/.test(path) || /\.woff2?(\b|$)/.test(path)) return true;
133786
+ for (const fam of requiredFamilies) {
133787
+ const tokenA = fam.toLowerCase().replace(/\s+/g, "+");
133788
+ const tokenB = fam.toLowerCase().replace(/\s+/g, "-");
133789
+ if (path.includes(tokenA) || path.includes(tokenB)) return true;
133790
+ }
133791
+ return false;
133792
+ } catch {
133793
+ return false;
133794
+ }
133795
+ }
133796
+ function familiesFromRequired(required) {
133797
+ const out = /* @__PURE__ */ new Set();
133798
+ for (const k of required || []) {
133799
+ const fam = String(k).split("__")[0]?.trim();
133800
+ if (fam) out.add(fam);
133801
+ }
133802
+ return out;
133803
+ }
133804
+ function rewriteRelativeUrls(cssText, baseHref) {
133805
+ if (!cssText) return cssText;
133806
+ return cssText.replace(
133807
+ /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g,
133808
+ (m, q, u) => {
133809
+ const src = (u || "").trim();
133810
+ if (!src || /^data:|^blob:|^https?:|^file:|^about:/i.test(src)) return m;
133811
+ let abs = src;
133812
+ try {
133813
+ abs = new URL(src, baseHref || location.href).href;
133814
+ } catch {
133815
+ }
133816
+ return `url("${abs}")`;
133817
+ }
133818
+ );
133819
+ }
133820
+ var IMPORT_ANY_RE = /@import\s+(?:url\(\s*(['"]?)([^)"']+)\1\s*\)|(['"])([^"']+)\3)([^;]*);/g;
133821
+ var MAX_IMPORT_DEPTH = 4;
133822
+ async function inlineImportsAndRewrite(cssText, ownerHref, useProxy) {
133823
+ if (!cssText) return cssText;
133824
+ const visited = /* @__PURE__ */ new Set();
133825
+ function normalizeUrl(u, base) {
133826
+ try {
133827
+ return new URL(u, base || location.href).href;
133828
+ } catch {
133829
+ return u;
133830
+ }
133831
+ }
133832
+ async function resolveOnce(text, baseHref, depth = 0) {
133833
+ if (depth > MAX_IMPORT_DEPTH) {
133834
+ console.warn(`[snapDOM] @import depth exceeded (${MAX_IMPORT_DEPTH}) at ${baseHref}`);
133835
+ return text;
133836
+ }
133837
+ let out = "";
133838
+ let last = 0;
133839
+ let m;
133840
+ while (m = IMPORT_ANY_RE.exec(text)) {
133841
+ out += text.slice(last, m.index);
133842
+ last = IMPORT_ANY_RE.lastIndex;
133843
+ const rawUrl = (m[2] || m[4] || "").trim();
133844
+ const absUrl = normalizeUrl(rawUrl, baseHref);
133845
+ if (visited.has(absUrl)) {
133846
+ console.warn(`[snapDOM] Skipping circular @import: ${absUrl}`);
133847
+ continue;
133848
+ }
133849
+ visited.add(absUrl);
133850
+ let imported = "";
133851
+ try {
133852
+ const r = await snapFetch(absUrl, { as: "text", useProxy, silent: true });
133853
+ if (r.ok && typeof r.data === "string") imported = r.data;
133854
+ } catch {
133855
+ }
133856
+ if (imported) {
133857
+ imported = rewriteRelativeUrls(imported, absUrl);
133858
+ imported = await resolveOnce(imported, absUrl, depth + 1);
133859
+ out += `
133860
+ /* inlined: ${absUrl} */
133861
+ ${imported}
133862
+ `;
133863
+ } else {
133864
+ out += m[0];
133865
+ }
133866
+ }
133867
+ out += text.slice(last);
133868
+ return out;
133869
+ }
133870
+ let rewritten = rewriteRelativeUrls(cssText, ownerHref || location.href);
133871
+ rewritten = await resolveOnce(rewritten, ownerHref || location.href, 0);
133872
+ return rewritten;
133873
+ }
133874
+ var URL_RE = /url\((["']?)([^"')]+)\1\)/g;
133875
+ var FACE_RE = /@font-face[^{}]*\{[^}]*\}/g;
133876
+ function parseUnicodeRange(ur) {
133877
+ if (!ur) return [];
133878
+ const ranges = [];
133879
+ const parts = ur.split(",").map((s) => s.trim()).filter(Boolean);
133880
+ for (const p of parts) {
133881
+ const m = p.match(/^U\+([0-9A-Fa-f?]+)(?:-([0-9A-Fa-f?]+))?$/);
133882
+ if (!m) continue;
133883
+ const a = m[1], b = m[2];
133884
+ const expand = (hex) => {
133885
+ if (!hex.includes("?")) return parseInt(hex, 16);
133886
+ const min = parseInt(hex.replace(/\?/g, "0"), 16);
133887
+ const max = parseInt(hex.replace(/\?/g, "F"), 16);
133888
+ return [min, max];
133889
+ };
133890
+ if (b) {
133891
+ const A = expand(a), B = expand(b);
133892
+ const min = Array.isArray(A) ? A[0] : A;
133893
+ const max = Array.isArray(B) ? B[1] : B;
133894
+ ranges.push([Math.min(min, max), Math.max(min, max)]);
133895
+ } else {
133896
+ const X = expand(a);
133897
+ if (Array.isArray(X)) ranges.push([X[0], X[1]]);
133898
+ else ranges.push([X, X]);
133899
+ }
133900
+ }
133901
+ return ranges;
133902
+ }
133903
+ function unicodeIntersects(used, ranges) {
133904
+ if (!ranges.length) return true;
133905
+ if (!used || used.size === 0) return true;
133906
+ for (const cp of used) {
133907
+ for (const [a, b] of ranges) if (cp >= a && cp <= b) return true;
133908
+ }
133909
+ return false;
133910
+ }
133911
+ function extractSrcUrls(srcValue, baseHref) {
133912
+ const urls = [];
133913
+ if (!srcValue) return urls;
133914
+ for (const m of srcValue.matchAll(URL_RE)) {
133915
+ let u = (m[2] || "").trim();
133916
+ if (!u || u.startsWith("data:")) continue;
133917
+ if (!/^https?:/i.test(u)) {
133918
+ try {
133919
+ u = new URL(u, baseHref || location.href).href;
133920
+ } catch {
133921
+ }
133922
+ }
133923
+ urls.push(u);
133924
+ }
133925
+ return urls;
133926
+ }
133927
+ async function inlineUrlsInCssBlock(cssBlock, baseHref, useProxy = "") {
133928
+ let out = cssBlock;
133929
+ for (const m of cssBlock.matchAll(URL_RE)) {
133930
+ const raw = extractURL(m[0]);
133931
+ if (!raw) continue;
133932
+ let abs = raw;
133933
+ if (!abs.startsWith("http") && !abs.startsWith("data:")) {
133934
+ try {
133935
+ abs = new URL(abs, baseHref || location.href).href;
133936
+ } catch {
133937
+ }
133938
+ }
133939
+ if (isIconFont2(abs)) continue;
133940
+ if (cache.resource?.has(abs)) {
133941
+ cache.font?.add(abs);
133942
+ out = out.replace(m[0], `url(${cache.resource.get(abs)})`);
133943
+ continue;
133944
+ }
133945
+ if (cache.font?.has(abs)) continue;
133946
+ try {
133947
+ const r = await snapFetch(abs, { as: "dataURL", useProxy, silent: true });
133948
+ if (r.ok && typeof r.data === "string") {
133949
+ const b64 = r.data;
133950
+ cache.resource?.set(abs, b64);
133951
+ cache.font?.add(abs);
133952
+ out = out.replace(m[0], `url(${b64})`);
133953
+ }
133954
+ } catch {
133955
+ console.warn("[snapDOM] Failed to fetch font resource:", abs);
133956
+ }
133957
+ }
133958
+ return out;
133959
+ }
133960
+ function subsetFromRanges(ranges) {
133961
+ if (!ranges.length) return null;
133962
+ const hit = (a, b) => ranges.some(([x, y]) => !(y < a || x > b));
133963
+ const latin = hit(0, 255) || hit(305, 305);
133964
+ const latinExt = hit(256, 591) || hit(7680, 7935);
133965
+ const greek = hit(880, 1023);
133966
+ const cyr = hit(1024, 1279);
133967
+ const viet = hit(7840, 7929) || hit(258, 259) || hit(416, 417) || hit(431, 432);
133968
+ if (viet) return "vietnamese";
133969
+ if (cyr) return "cyrillic";
133970
+ if (greek) return "greek";
133971
+ if (latinExt) return "latin-ext";
133972
+ if (latin) return "latin";
133973
+ return null;
133974
+ }
133975
+ function buildSimpleExcluder(ex = {}) {
133976
+ const famSet = new Set((ex.families || []).map((s) => String(s).toLowerCase()));
133977
+ const domSet = new Set((ex.domains || []).map((s) => String(s).toLowerCase()));
133978
+ const subSet = new Set((ex.subsets || []).map((s) => String(s).toLowerCase()));
133979
+ return (meta, parsedRanges) => {
133980
+ if (famSet.size && famSet.has(meta.family.toLowerCase())) return true;
133981
+ if (domSet.size) {
133982
+ for (const u of meta.srcUrls) {
133983
+ try {
133984
+ if (domSet.has(new URL(u).host.toLowerCase())) return true;
133985
+ } catch {
133986
+ }
133987
+ }
133988
+ }
133989
+ if (subSet.size) {
133990
+ const label = subsetFromRanges(parsedRanges);
133991
+ if (label && subSet.has(label)) return true;
133992
+ }
133993
+ return false;
133994
+ };
133995
+ }
133996
+ function dedupeFontFaces(cssText) {
133997
+ if (!cssText) return cssText;
133998
+ const FACE_RE_G = /@font-face[^{}]*\{[^}]*\}/gi;
133999
+ const seen = /* @__PURE__ */ new Set();
134000
+ const out = [];
134001
+ for (const block of cssText.match(FACE_RE_G) || []) {
134002
+ const familyRaw = block.match(/font-family:\s*([^;]+);/i)?.[1] || "";
134003
+ const family = pickPrimaryFamily(familyRaw);
134004
+ const weightSpec = (block.match(/font-weight:\s*([^;]+);/i)?.[1] || "400").trim();
134005
+ const styleSpec = (block.match(/font-style:\s*([^;]+);/i)?.[1] || "normal").trim();
134006
+ const stretchSpec = (block.match(/font-stretch:\s*([^;]+);/i)?.[1] || "100%").trim();
134007
+ const urange = (block.match(/unicode-range:\s*([^;]+);/i)?.[1] || "").trim();
134008
+ const srcRaw = (block.match(/src\s*:\s*([^;]+);/i)?.[1] || "").trim();
134009
+ const urls = extractSrcUrls(srcRaw, location.href);
134010
+ const srcPart = urls.length ? urls.map((u) => String(u).toLowerCase()).sort().join("|") : srcRaw.toLowerCase();
134011
+ const key = [
134012
+ String(family || "").toLowerCase(),
134013
+ weightSpec,
134014
+ styleSpec,
134015
+ stretchSpec,
134016
+ urange.toLowerCase(),
134017
+ srcPart
134018
+ ].join("|");
134019
+ if (!seen.has(key)) {
134020
+ seen.add(key);
134021
+ out.push(block);
134022
+ }
134023
+ }
134024
+ if (out.length === 0) return cssText;
134025
+ let i = 0;
134026
+ return cssText.replace(FACE_RE_G, () => out[i++] || "");
134027
+ }
134028
+ function buildFontsCacheKey(required, exclude, localFonts, useProxy) {
134029
+ const req = Array.from(required || []).sort().join("|");
134030
+ const ex = exclude ? JSON.stringify({
134031
+ families: (exclude.families || []).map((s) => String(s).toLowerCase()).sort(),
134032
+ domains: (exclude.domains || []).map((s) => String(s).toLowerCase()).sort(),
134033
+ subsets: (exclude.subsets || []).map((s) => String(s).toLowerCase()).sort()
134034
+ }) : "";
134035
+ const lf = (localFonts || []).map((f) => `${(f.family || "").toLowerCase()}::${f.weight || "normal"}::${f.style || "normal"}::${f.src || ""}`).sort().join("|");
134036
+ const px = useProxy || "";
134037
+ return `fonts-embed-css::req=${req}::ex=${ex}::lf=${lf}::px=${px}`;
134038
+ }
134039
+ async function collectFacesFromSheet(sheet, baseHref, emitFace, ctx) {
134040
+ let rules;
134041
+ try {
134042
+ rules = sheet.cssRules || [];
134043
+ } catch {
134044
+ return;
134045
+ }
134046
+ const normalizeUrl = (u, base) => {
134047
+ try {
134048
+ return new URL(u, base || location.href).href;
134049
+ } catch {
134050
+ return u;
134051
+ }
134052
+ };
134053
+ for (const rule of rules) {
134054
+ if (rule.type === CSSRule.IMPORT_RULE && rule.styleSheet) {
134055
+ const childHref = rule.href ? normalizeUrl(rule.href, baseHref) : baseHref;
134056
+ if (ctx.depth >= MAX_IMPORT_DEPTH) {
134057
+ console.warn(`[snapDOM] CSSOM import depth exceeded (${MAX_IMPORT_DEPTH}) at ${childHref}`);
134058
+ continue;
134059
+ }
134060
+ if (childHref && ctx.visitedSheets.has(childHref)) {
134061
+ console.warn(`[snapDOM] Skipping circular CSSOM import: ${childHref}`);
134062
+ continue;
134063
+ }
134064
+ if (childHref) ctx.visitedSheets.add(childHref);
134065
+ const nextCtx = { ...ctx, depth: (ctx.depth || 0) + 1 };
134066
+ await collectFacesFromSheet(rule.styleSheet, childHref, emitFace, nextCtx);
134067
+ continue;
134068
+ }
134069
+ if (rule.type === CSSRule.FONT_FACE_RULE) {
134070
+ const famRaw = (rule.style.getPropertyValue("font-family") || "").trim();
134071
+ const family = pickPrimaryFamily(famRaw);
134072
+ if (!family || isIconFont2(family)) continue;
134073
+ const weightSpec = (rule.style.getPropertyValue("font-weight") || "400").trim();
134074
+ const styleSpec = (rule.style.getPropertyValue("font-style") || "normal").trim();
134075
+ const stretchSpec = (rule.style.getPropertyValue("font-stretch") || "100%").trim();
134076
+ const srcRaw = (rule.style.getPropertyValue("src") || "").trim();
134077
+ const urange = (rule.style.getPropertyValue("unicode-range") || "").trim();
134078
+ if (!ctx.faceMatchesRequired(family, styleSpec, weightSpec, stretchSpec)) continue;
134079
+ const ranges = parseUnicodeRange(urange);
134080
+ if (!unicodeIntersects(ctx.usedCodepoints, ranges)) continue;
134081
+ const meta = {
134082
+ family,
134083
+ weightSpec,
134084
+ styleSpec,
134085
+ stretchSpec,
134086
+ unicodeRange: urange,
134087
+ srcRaw,
134088
+ srcUrls: extractSrcUrls(srcRaw, baseHref || location.href),
134089
+ href: baseHref || location.href
134090
+ };
134091
+ if (ctx.simpleExcluder && ctx.simpleExcluder(meta, ranges)) continue;
134092
+ if (/url\(/i.test(srcRaw)) {
134093
+ const inlinedSrc = await inlineUrlsInCssBlock(srcRaw, baseHref || location.href, ctx.useProxy);
134094
+ await emitFace(`@font-face{font-family:${family};src:${inlinedSrc};font-style:${styleSpec};font-weight:${weightSpec};font-stretch:${stretchSpec};${urange ? `unicode-range:${urange};` : ""}}`);
134095
+ } else {
134096
+ await emitFace(`@font-face{font-family:${family};src:${srcRaw};font-style:${styleSpec};font-weight:${weightSpec};font-stretch:${stretchSpec};${urange ? `unicode-range:${urange};` : ""}}`);
134097
+ }
134098
+ }
134099
+ }
134100
+ }
134101
+ async function embedCustomFonts({
134102
+ required,
134103
+ usedCodepoints,
134104
+ exclude = void 0,
134105
+ localFonts = [],
134106
+ useProxy = ""
134107
+ } = {}) {
134108
+ if (!(required instanceof Set)) required = /* @__PURE__ */ new Set();
134109
+ if (!(usedCodepoints instanceof Set)) usedCodepoints = /* @__PURE__ */ new Set();
134110
+ const requiredIndex = /* @__PURE__ */ new Map();
134111
+ for (const key of required) {
134112
+ const [fam, w, s, st] = String(key).split("__");
134113
+ if (!fam) continue;
134114
+ const arr = requiredIndex.get(fam) || [];
134115
+ arr.push({ w: parseInt(w, 10), s, st: parseInt(st, 10) });
134116
+ requiredIndex.set(fam, arr);
134117
+ }
134118
+ function faceMatchesRequired(fam, styleSpec, weightSpec, stretchSpec) {
134119
+ if (!requiredIndex.has(fam)) return false;
134120
+ const need = requiredIndex.get(fam);
134121
+ const ws = parseWeightSpec(weightSpec);
134122
+ const ss = parseStyleSpec(styleSpec);
134123
+ const ts = parseStretchSpec(stretchSpec);
134124
+ const faceIsRange = ws.min !== ws.max;
134125
+ const faceSingleW = ws.min;
134126
+ const styleOK = (reqKind) => ss.kind === "normal" && reqKind === "normal" || ss.kind !== "normal" && (reqKind === "italic" || reqKind === "oblique");
134127
+ let exactMatched = false;
134128
+ for (const r of need) {
134129
+ const wOk = faceIsRange ? r.w >= ws.min && r.w <= ws.max : r.w === faceSingleW;
134130
+ const sOk = styleOK(normStyle(r.s));
134131
+ const tOk = r.st >= ts.min && r.st <= ts.max;
134132
+ if (wOk && sOk && tOk) {
134133
+ exactMatched = true;
134134
+ break;
134135
+ }
134136
+ }
134137
+ if (exactMatched) return true;
134138
+ if (!faceIsRange) {
134139
+ for (const r of need) {
134140
+ const sOk = styleOK(normStyle(r.s));
134141
+ const tOk = r.st >= ts.min && r.st <= ts.max;
134142
+ const nearWeight = Math.abs(faceSingleW - r.w) <= 300;
134143
+ if (nearWeight && sOk && tOk) return true;
134144
+ }
134145
+ }
134146
+ return false;
134147
+ }
134148
+ const simpleExcluder = buildSimpleExcluder(exclude);
134149
+ const cacheKey = buildFontsCacheKey(required, exclude, localFonts, useProxy);
134150
+ if (cache.resource?.has(cacheKey)) {
134151
+ return cache.resource.get(cacheKey);
134152
+ }
134153
+ const requiredFamilies = familiesFromRequired(required);
134154
+ const importUrls = [];
134155
+ const IMPORT_ANY_RE_LOCAL = IMPORT_ANY_RE;
134156
+ for (const styleTag of document.querySelectorAll("style")) {
134157
+ const cssText = styleTag.textContent || "";
134158
+ for (const m of cssText.matchAll(IMPORT_ANY_RE_LOCAL)) {
134159
+ const u = (m[2] || m[4] || "").trim();
134160
+ if (!u || isIconFont2(u)) continue;
134161
+ const hasLink = !!document.querySelector(`link[rel="stylesheet"][href="${u}"]`);
134162
+ if (!hasLink) importUrls.push(u);
134163
+ }
134164
+ }
134165
+ if (importUrls.length) {
134166
+ await Promise.all(importUrls.map((u) => new Promise((resolve) => {
134167
+ if (document.querySelector(`link[rel="stylesheet"][href="${u}"]`)) return resolve(null);
134168
+ const link = document.createElement("link");
134169
+ link.rel = "stylesheet";
134170
+ link.href = u;
134171
+ link.setAttribute("data-snapdom", "injected-import");
134172
+ link.onload = () => resolve(link);
134173
+ link.onerror = () => resolve(null);
134174
+ document.head.appendChild(link);
134175
+ })));
134176
+ }
134177
+ let finalCSS = "";
134178
+ const linkNodes = Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter((l) => !!l.href);
134179
+ for (const link of linkNodes) {
134180
+ try {
134181
+ if (isIconFont2(link.href)) continue;
134182
+ let cssText = "";
134183
+ let sameOrigin = false;
134184
+ try {
134185
+ sameOrigin = new URL(link.href, location.href).origin === location.origin;
134186
+ } catch {
134187
+ }
134188
+ if (!sameOrigin) {
134189
+ if (!isLikelyFontStylesheet(link.href, requiredFamilies)) continue;
134190
+ }
134191
+ if (sameOrigin) {
134192
+ const sheet = Array.from(document.styleSheets).find((s) => s.href === link.href);
134193
+ if (sheet) {
134194
+ try {
134195
+ const rules = sheet.cssRules || [];
134196
+ cssText = Array.from(rules).map((r) => r.cssText).join("");
134197
+ } catch {
134198
+ }
134199
+ }
134200
+ }
134201
+ if (!cssText) {
134202
+ const res = await snapFetch(link.href, { as: "text", useProxy });
134203
+ cssText = res.data;
134204
+ if (isIconFont2(link.href)) continue;
134205
+ }
134206
+ cssText = await inlineImportsAndRewrite(cssText, link.href, useProxy);
134207
+ let facesOut = "";
134208
+ for (const face of cssText.match(FACE_RE) || []) {
134209
+ const famRaw = (face.match(/font-family:\s*([^;]+);/i)?.[1] || "").trim();
134210
+ const family = pickPrimaryFamily(famRaw);
134211
+ if (!family || isIconFont2(family)) continue;
134212
+ const weightSpec = (face.match(/font-weight:\s*([^;]+);/i)?.[1] || "400").trim();
134213
+ const styleSpec = (face.match(/font-style:\s*([^;]+);/i)?.[1] || "normal").trim();
134214
+ const stretchSpec = (face.match(/font-stretch:\s*([^;]+);/i)?.[1] || "100%").trim();
134215
+ const urange = (face.match(/unicode-range:\s*([^;]+);/i)?.[1] || "").trim();
134216
+ const srcRaw = (face.match(/src\s*:\s*([^;]+);/i)?.[1] || "").trim();
134217
+ const srcUrls = extractSrcUrls(srcRaw, link.href);
134218
+ if (!faceMatchesRequired(family, styleSpec, weightSpec, stretchSpec)) continue;
134219
+ const ranges = parseUnicodeRange(urange);
134220
+ if (!unicodeIntersects(usedCodepoints, ranges)) continue;
134221
+ const meta = { family, weightSpec, styleSpec, stretchSpec, unicodeRange: urange, srcRaw, srcUrls, href: link.href };
134222
+ if (exclude && simpleExcluder(meta, ranges)) continue;
134223
+ const newFace = /url\(/i.test(srcRaw) ? await inlineUrlsInCssBlock(face, link.href, useProxy) : face;
134224
+ facesOut += newFace;
134225
+ }
134226
+ if (facesOut.trim()) finalCSS += facesOut;
134227
+ } catch {
134228
+ console.warn("[snapDOM] Failed to process stylesheet:", link.href);
134229
+ }
134230
+ }
134231
+ const ctx = {
134232
+ requiredIndex,
134233
+ usedCodepoints,
134234
+ faceMatchesRequired,
134235
+ simpleExcluder: exclude ? buildSimpleExcluder(exclude) : null,
134236
+ useProxy,
134237
+ visitedSheets: /* @__PURE__ */ new Set(),
134238
+ depth: 0
134239
+ };
134240
+ for (const sheet of document.styleSheets) {
134241
+ if (sheet.href && linkNodes.some((l) => l.href === sheet.href)) continue;
134242
+ try {
134243
+ const rootHref = sheet.href || location.href;
134244
+ if (rootHref) ctx.visitedSheets.add(rootHref);
134245
+ await collectFacesFromSheet(
134246
+ sheet,
134247
+ rootHref,
134248
+ async (faceCss) => {
134249
+ finalCSS += faceCss;
134250
+ },
134251
+ ctx
134252
+ );
134253
+ } catch {
134254
+ }
134255
+ }
134256
+ try {
134257
+ for (const f of document.fonts || []) {
134258
+ if (!f || !f.family || f.status !== "loaded" || !f._snapdomSrc) continue;
134259
+ const fam = String(f.family).replace(/^['"]+|['"]+$/g, "");
134260
+ if (isIconFont2(fam)) continue;
134261
+ if (!requiredIndex.has(fam)) continue;
134262
+ if (exclude?.families && exclude.families.some((n) => String(n).toLowerCase() === fam.toLowerCase())) {
134263
+ continue;
134264
+ }
134265
+ let b64 = f._snapdomSrc;
134266
+ if (!String(b64).startsWith("data:")) {
134267
+ if (cache.resource?.has(f._snapdomSrc)) {
134268
+ b64 = cache.resource.get(f._snapdomSrc);
134269
+ cache.font?.add(f._snapdomSrc);
134270
+ } else if (!cache.font?.has(f._snapdomSrc)) {
134271
+ try {
134272
+ const r = await snapFetch(f._snapdomSrc, { as: "dataURL", useProxy, silent: true });
134273
+ if (r.ok && typeof r.data === "string") {
134274
+ b64 = r.data;
134275
+ cache.resource?.set(f._snapdomSrc, b64);
134276
+ cache.font?.add(f._snapdomSrc);
134277
+ } else {
134278
+ continue;
134279
+ }
134280
+ } catch {
134281
+ console.warn("[snapDOM] Failed to fetch dynamic font src:", f._snapdomSrc);
134282
+ continue;
134283
+ }
134284
+ }
134285
+ }
134286
+ finalCSS += `@font-face{font-family:'${fam}';src:url(${b64});font-style:${f.style || "normal"};font-weight:${f.weight || "normal"};}`;
134287
+ }
134288
+ } catch {
134289
+ }
134290
+ for (const font of localFonts) {
134291
+ if (!font || typeof font !== "object") continue;
134292
+ const family = String(font.family || "").replace(/^['"]+|['"]+$/g, "");
134293
+ if (!family || isIconFont2(family)) continue;
134294
+ if (!requiredIndex.has(family)) continue;
134295
+ if (exclude?.families && exclude.families.some((n) => String(n).toLowerCase() === family.toLowerCase())) continue;
134296
+ const weight = font.weight != null ? String(font.weight) : "normal";
134297
+ const style = font.style != null ? String(font.style) : "normal";
134298
+ const stretch = font.stretchPct != null ? `${font.stretchPct}%` : "100%";
134299
+ const src = String(font.src || "");
134300
+ let b64 = src;
134301
+ if (!b64.startsWith("data:")) {
134302
+ if (cache.resource?.has(src)) {
134303
+ b64 = cache.resource.get(src);
134304
+ cache.font?.add(src);
134305
+ } else if (!cache.font?.has(src)) {
134306
+ try {
134307
+ const r = await snapFetch(src, { as: "dataURL", useProxy, silent: true });
134308
+ if (r.ok && typeof r.data === "string") {
134309
+ b64 = r.data;
134310
+ cache.resource?.set(src, b64);
134311
+ cache.font?.add(src);
134312
+ } else {
134313
+ continue;
134314
+ }
134315
+ } catch {
134316
+ console.warn("[snapDOM] Failed to fetch localFonts src:", src);
134317
+ continue;
134318
+ }
134319
+ }
134320
+ }
134321
+ finalCSS += `@font-face{font-family:'${family}';src:url(${b64});font-style:${style};font-weight:${weight};font-stretch:${stretch};}`;
134322
+ }
134323
+ if (finalCSS) {
134324
+ finalCSS = dedupeFontFaces(finalCSS);
134325
+ cache.resource?.set(cacheKey, finalCSS);
134326
+ }
134327
+ return finalCSS;
134328
+ }
134329
+ function collectUsedFontVariants(root) {
134330
+ const req = /* @__PURE__ */ new Set();
134331
+ if (!root) return req;
134332
+ const tw = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null);
134333
+ const addFromStyle = (cs) => {
134334
+ const family = pickPrimaryFamily(cs.fontFamily);
134335
+ if (!family) return;
134336
+ const key = (w, s, st) => `${family}__${normWeight(w)}__${normStyle(s)}__${normStretchPct(st)}`;
134337
+ req.add(key(cs.fontWeight, cs.fontStyle, cs.fontStretch));
134338
+ };
134339
+ addFromStyle(getComputedStyle(root));
134340
+ const csBeforeRoot = getComputedStyle(root, "::before");
134341
+ if (csBeforeRoot && csBeforeRoot.content && csBeforeRoot.content !== "none") addFromStyle(csBeforeRoot);
134342
+ const csAfterRoot = getComputedStyle(root, "::after");
134343
+ if (csAfterRoot && csAfterRoot.content && csAfterRoot.content !== "none") addFromStyle(csAfterRoot);
134344
+ while (tw.nextNode()) {
134345
+ const el = (
134346
+ /** @type {Element} */
134347
+ tw.currentNode
134348
+ );
134349
+ const cs = getComputedStyle(el);
134350
+ addFromStyle(cs);
134351
+ const b = getComputedStyle(el, "::before");
134352
+ if (b && b.content && b.content !== "none") addFromStyle(b);
134353
+ const a = getComputedStyle(el, "::after");
134354
+ if (a && a.content && a.content !== "none") addFromStyle(a);
134355
+ }
134356
+ return req;
134357
+ }
134358
+ function collectUsedCodepoints(root) {
134359
+ const used = /* @__PURE__ */ new Set();
134360
+ const pushText = (txt) => {
134361
+ if (!txt) return;
134362
+ for (const ch of txt) used.add(ch.codePointAt(0));
134363
+ };
134364
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null);
134365
+ while (walker.nextNode()) {
134366
+ const n = walker.currentNode;
134367
+ if (n.nodeType === Node.TEXT_NODE) {
134368
+ pushText(n.nodeValue || "");
134369
+ } else if (n.nodeType === Node.ELEMENT_NODE) {
134370
+ const el = (
134371
+ /** @type {Element} */
134372
+ n
134373
+ );
134374
+ for (const pseudo of ["::before", "::after"]) {
134375
+ const cs = getComputedStyle(el, pseudo);
134376
+ const c = cs?.getPropertyValue("content");
134377
+ if (!c || c === "none") continue;
134378
+ if (/^"/.test(c) || /^'/.test(c)) {
134379
+ pushText(c.slice(1, -1));
134380
+ } else {
134381
+ const matches = c.match(/\\[0-9A-Fa-f]{1,6}/g);
134382
+ if (matches) {
134383
+ for (const m of matches) {
134384
+ try {
134385
+ used.add(parseInt(m.slice(1), 16));
134386
+ } catch {
134387
+ }
134388
+ }
134389
+ }
134390
+ }
134391
+ }
134392
+ }
134393
+ }
134394
+ return used;
134395
+ }
134396
+ async function ensureFontsReady(families, warmupRepetitions = 2) {
134397
+ try {
134398
+ await document.fonts.ready;
134399
+ } catch {
134400
+ }
134401
+ const fams = Array.from(families || []).filter(Boolean);
134402
+ if (fams.length === 0) return;
134403
+ const warmupOnce = () => {
134404
+ const container = document.createElement("div");
134405
+ container.style.cssText = "position:absolute!important;left:-9999px!important;top:0!important;opacity:0!important;pointer-events:none!important;contain:layout size style;";
134406
+ for (const fam of fams) {
134407
+ const span = document.createElement("span");
134408
+ span.textContent = "AaBbGg1234\xC1\xC9\xCD\xD3\xDA\xE7\xF1\u2014\u221E";
134409
+ span.style.fontFamily = `"${fam}"`;
134410
+ span.style.fontWeight = "700";
134411
+ span.style.fontStyle = "italic";
134412
+ span.style.fontSize = "32px";
134413
+ span.style.lineHeight = "1";
134414
+ span.style.whiteSpace = "nowrap";
134415
+ span.style.margin = "0";
134416
+ span.style.padding = "0";
134417
+ container.appendChild(span);
134418
+ }
134419
+ document.body.appendChild(container);
134420
+ container.offsetWidth;
134421
+ document.body.removeChild(container);
134422
+ };
134423
+ for (let i = 0; i < Math.max(1, warmupRepetitions); i++) {
134424
+ warmupOnce();
134425
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
134426
+ }
134427
+ }
134428
+
134429
+ // src/modules/counter.js
134430
+ function hasCounters(input) {
134431
+ return /\bcounter\s*\(|\bcounters\s*\(/.test(input || "");
134432
+ }
134433
+ function unquoteDoubleStrings(s) {
134434
+ return (s || "").replace(/"([^"]*)"/g, "$1");
134435
+ }
134436
+ function alpha(n, upper = false) {
134437
+ let s = "", x = Math.max(1, n);
134438
+ while (x > 0) {
134439
+ x--;
134440
+ s = String.fromCharCode(97 + x % 26) + s;
134441
+ x = Math.floor(x / 26);
134442
+ }
134443
+ return upper ? s.toUpperCase() : s;
134444
+ }
134445
+ function roman(n, upper = true) {
134446
+ const map = [[1e3, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]];
134447
+ let num = Math.max(1, Math.min(3999, n)), out = "";
134448
+ for (const [v, sym] of map) while (num >= v) {
134449
+ out += sym;
134450
+ num -= v;
134451
+ }
134452
+ return upper ? out : out.toLowerCase();
134453
+ }
134454
+ function formatCounter(value, style) {
134455
+ switch ((style || "decimal").toLowerCase()) {
134456
+ case "decimal":
134457
+ return String(Math.max(0, value));
134458
+ case "decimal-leading-zero":
134459
+ return (value < 10 ? "0" : "") + String(Math.max(0, value));
134460
+ case "lower-alpha":
134461
+ return alpha(value, false);
134462
+ case "upper-alpha":
134463
+ return alpha(value, true);
134464
+ case "lower-roman":
134465
+ return roman(value, false);
134466
+ case "upper-roman":
134467
+ return roman(value, true);
134468
+ default:
134469
+ return String(Math.max(0, value));
134470
+ }
134471
+ }
134472
+ function buildCounterContext(root) {
134473
+ const nodeCounters = /* @__PURE__ */ new WeakMap();
134474
+ const rootEl = root instanceof Document ? root.documentElement : root;
134475
+ const isLi = (el) => el && el.tagName === "LI";
134476
+ const countPrevLi = (li) => {
134477
+ let c = 0, p = li?.parentElement;
134478
+ if (!p) return 0;
134479
+ for (const sib of p.children) {
134480
+ if (sib === li) break;
134481
+ if (sib.tagName === "LI") c++;
134482
+ }
134483
+ return c;
134484
+ };
134485
+ const cloneMap = (m) => {
134486
+ const out = /* @__PURE__ */ new Map();
134487
+ for (const [k, arr] of m) out.set(k, arr.slice());
134488
+ return out;
134489
+ };
134490
+ const applyTo = (baseMap, parentMap, el) => {
134491
+ const map = cloneMap(baseMap);
134492
+ let reset;
134493
+ try {
134494
+ reset = el.style?.counterReset || getComputedStyle(el).counterReset;
134495
+ } catch {
134496
+ }
134497
+ if (reset && reset !== "none") {
134498
+ for (const part of reset.split(",")) {
134499
+ const toks = part.trim().split(/\s+/);
134500
+ const name = toks[0];
134501
+ const val = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : 0;
134502
+ if (!name) continue;
134503
+ const parentStack = parentMap.get(name);
134504
+ if (parentStack && parentStack.length) {
134505
+ const s = parentStack.slice();
134506
+ s.push(val);
134507
+ map.set(name, s);
134508
+ } else {
134509
+ map.set(name, [val]);
134510
+ }
134511
+ }
134512
+ }
134513
+ let inc;
134514
+ try {
134515
+ inc = el.style?.counterIncrement || getComputedStyle(el).counterIncrement;
134516
+ } catch {
134517
+ }
134518
+ if (inc && inc !== "none") {
134519
+ for (const part of inc.split(",")) {
134520
+ const toks = part.trim().split(/\s+/);
134521
+ const name = toks[0];
134522
+ const by = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : 1;
134523
+ if (!name) continue;
134524
+ const stack = map.get(name) || [];
134525
+ if (stack.length === 0) stack.push(0);
134526
+ stack[stack.length - 1] += by;
134527
+ map.set(name, stack);
134528
+ }
134529
+ }
134530
+ try {
134531
+ const cs = getComputedStyle(el);
134532
+ if (cs.display === "list-item" && isLi(el)) {
134533
+ const p = el.parentElement;
134534
+ let idx = 1;
134535
+ if (p && p.tagName === "OL") {
134536
+ const startAttr = p.getAttribute("start");
134537
+ const start = Number.isFinite(Number(startAttr)) ? Number(startAttr) : 1;
134538
+ const prev = countPrevLi(el);
134539
+ const ownAttr = el.getAttribute("value");
134540
+ idx = Number.isFinite(Number(ownAttr)) ? Number(ownAttr) : start + prev;
134541
+ } else {
134542
+ idx = 1 + countPrevLi(el);
134543
+ }
134544
+ const s = map.get("list-item") || [];
134545
+ if (s.length === 0) s.push(0);
134546
+ s[s.length - 1] = idx;
134547
+ map.set("list-item", s);
134548
+ }
134549
+ } catch {
134550
+ }
134551
+ return map;
134552
+ };
134553
+ const build = (el, parentMap, carryMap) => {
134554
+ const curr = applyTo(carryMap, parentMap, el);
134555
+ nodeCounters.set(el, curr);
134556
+ let nextCarry = curr;
134557
+ for (const child of el.children) {
134558
+ const childCarry = build(child, curr, nextCarry);
134559
+ nextCarry = childCarry;
134560
+ }
134561
+ return curr;
134562
+ };
134563
+ const empty = /* @__PURE__ */ new Map();
134564
+ build(rootEl, empty, empty);
134565
+ return {
134566
+ /**
134567
+ * Get top value for counter name at given node.
134568
+ * @param {Element} node
134569
+ * @param {string} name
134570
+ */
134571
+ get(node, name) {
134572
+ const s = nodeCounters.get(node)?.get(name);
134573
+ return s && s.length ? s[s.length - 1] : 0;
134574
+ },
134575
+ /**
134576
+ * Get full stack for counter name at given node.
134577
+ * @param {Element} node
134578
+ * @param {string} name
134579
+ */
134580
+ getStack(node, name) {
134581
+ const s = nodeCounters.get(node)?.get(name);
134582
+ return s ? s.slice() : [];
134583
+ }
134584
+ };
134585
+ }
134586
+ function resolveCountersInContent(raw, node, ctx) {
134587
+ if (!raw || raw === "none") return raw;
134588
+ try {
134589
+ const RX = /\b(counter|counters)\s*\(([^)]+)\)/g;
134590
+ let out = raw.replace(RX, (_, fn, args) => {
134591
+ const parts = String(args).split(",").map((s) => s.trim());
134592
+ if (fn === "counter") {
134593
+ const name = parts[0]?.replace(/^["']|["']$/g, "");
134594
+ const style = (parts[1] || "decimal").toLowerCase();
134595
+ const v = ctx.get(node, name);
134596
+ return formatCounter(v, style);
134597
+ } else {
134598
+ const name = parts[0]?.replace(/^["']|["']$/g, "");
134599
+ const sep = parts[1]?.replace(/^["']|["']$/g, "") ?? "";
134600
+ const style = (parts[2] || "decimal").toLowerCase();
134601
+ const stack = ctx.getStack(node, name);
134602
+ if (!stack.length) return "";
134603
+ const pieces = stack.map((v) => formatCounter(v, style));
134604
+ return pieces.join(sep);
134605
+ }
134606
+ });
134607
+ return unquoteDoubleStrings(out);
134608
+ } catch {
134609
+ return "- ";
134610
+ }
134611
+ }
134612
+
134613
+ // src/modules/pseudo.js
134614
+ var counterCtx = null;
134615
+ var __siblingCounters = /* @__PURE__ */ new WeakMap();
134616
+ function unquoteDoubleStrings2(s) {
134617
+ return (s || "").replace(/"([^"]*)"/g, "$1");
134618
+ }
134619
+ function collapseCssContent(raw) {
134620
+ if (!raw) return "";
134621
+ const tokens = [];
134622
+ const rx = /"([^"]*)"/g;
134623
+ let m;
134624
+ while (m = rx.exec(raw)) tokens.push(m[1]);
134625
+ if (tokens.length) return tokens.join("");
134626
+ return unquoteDoubleStrings2(raw);
134627
+ }
134628
+ function withSiblingOverrides(node, base) {
134629
+ const parent = node.parentElement;
134630
+ const map = parent ? __siblingCounters.get(parent) : null;
134631
+ if (!map) return base;
134632
+ return {
134633
+ get(n, name) {
134634
+ const v = base.get(n, name);
134635
+ const ov = map.get(name);
134636
+ return typeof ov === "number" ? Math.max(v, ov) : v;
134637
+ },
134638
+ getStack(n, name) {
134639
+ const s = base.getStack(n, name);
134640
+ if (!s.length) return s;
134641
+ const ov = map.get(name);
134642
+ if (typeof ov === "number") {
134643
+ const out = s.slice();
134644
+ out[out.length - 1] = Math.max(out[out.length - 1], ov);
134645
+ return out;
134646
+ }
134647
+ return s;
134648
+ }
134649
+ };
134650
+ }
134651
+ function deriveCounterCtxForPseudo(node, pseudoStyle, baseCtx) {
134652
+ const modStacks = /* @__PURE__ */ new Map();
134653
+ function parseListDecl(value) {
134654
+ const out = [];
134655
+ if (!value || value === "none") return out;
134656
+ for (const part of String(value).split(",")) {
134657
+ const toks = part.trim().split(/\s+/);
134658
+ const name = toks[0];
134659
+ const num = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : void 0;
134660
+ if (name) out.push({ name, num });
134661
+ }
134662
+ return out;
134663
+ }
134664
+ const resets = parseListDecl(pseudoStyle?.counterReset);
134665
+ const incs = parseListDecl(pseudoStyle?.counterIncrement);
134666
+ function getStackDerived(name) {
134667
+ if (modStacks.has(name)) return modStacks.get(name).slice();
134668
+ let stack = baseCtx.getStack(node, name);
134669
+ stack = stack.length ? stack.slice() : [];
134670
+ const r = resets.find((x) => x.name === name);
134671
+ if (r) {
134672
+ const val = Number.isFinite(r.num) ? r.num : 0;
134673
+ stack = stack.length ? [...stack, val] : [val];
134674
+ }
134675
+ const inc = incs.find((x) => x.name === name);
134676
+ if (inc) {
134677
+ const by = Number.isFinite(inc.num) ? inc.num : 1;
134678
+ if (stack.length === 0) stack = [0];
134679
+ stack[stack.length - 1] += by;
134680
+ }
134681
+ modStacks.set(name, stack.slice());
134682
+ return stack;
134683
+ }
134684
+ return {
134685
+ get(_node, name) {
134686
+ const s = getStackDerived(name);
134687
+ return s.length ? s[s.length - 1] : 0;
134688
+ },
134689
+ getStack(_node, name) {
134690
+ return getStackDerived(name);
134691
+ },
134692
+ /** expone increments del pseudo para que el caller pueda propagar a hermanos */
134693
+ __incs: incs
134694
+ };
134695
+ }
134696
+ function resolvePseudoContentAndIncs(node, pseudo, baseCtx) {
134697
+ let ps;
134698
+ try {
134699
+ ps = getComputedStyle(node, pseudo);
134700
+ } catch {
134701
+ }
134702
+ const raw = ps?.content;
134703
+ if (!raw || raw === "none" || raw === "normal") return { text: "", incs: [] };
134704
+ const baseWithSiblings = withSiblingOverrides(node, baseCtx);
134705
+ const derived = deriveCounterCtxForPseudo(node, ps, baseWithSiblings);
134706
+ let resolved = hasCounters(raw) ? resolveCountersInContent(raw, node, derived) : raw;
134707
+ const text = collapseCssContent(resolved);
134708
+ return { text, incs: derived.__incs || [] };
134709
+ }
134710
+ async function inlinePseudoElements(source, clone, sessionCache, options) {
134711
+ if (!(source instanceof Element) || !(clone instanceof Element)) return;
134712
+ if (!counterCtx) {
134713
+ try {
134714
+ counterCtx = buildCounterContext(source.ownerDocument || document);
134715
+ } catch {
134716
+ }
134717
+ }
134718
+ for (const pseudo of ["::before", "::after", "::first-letter"]) {
134719
+ try {
134720
+ const style = getStyle(source, pseudo);
134721
+ if (!style || typeof style[Symbol.iterator] !== "function") continue;
134722
+ const isEmptyPseudo = style.content === "none" && style.backgroundImage === "none" && style.backgroundColor === "transparent" && (style.borderStyle === "none" || parseFloat(style.borderWidth) === 0) && (!style.transform || style.transform === "none") && style.display === "inline";
134723
+ if (isEmptyPseudo) continue;
134724
+ if (pseudo === "::first-letter") {
134725
+ const normal = getComputedStyle(source);
134726
+ const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;
134727
+ if (!isMeaningful) continue;
134728
+ const textNode = Array.from(clone.childNodes).find(
134729
+ (n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim().length > 0
134730
+ );
134731
+ if (!textNode) continue;
134732
+ const text = textNode.textContent;
134733
+ const match = text.match(/^([^\p{L}\p{N}\s]*[\p{L}\p{N}](?:['’])?)/u);
134734
+ const first = match?.[0];
134735
+ const rest = text.slice(first?.length || 0);
134736
+ if (!first || /[\uD800-\uDFFF]/.test(first)) continue;
134737
+ const span = document.createElement("span");
134738
+ span.textContent = first;
134739
+ span.dataset.snapdomPseudo = "::first-letter";
134740
+ const snapshot2 = snapshotComputedStyle(style);
134741
+ const key2 = getStyleKey(snapshot2, "span");
134742
+ sessionCache.styleMap.set(span, key2);
134743
+ const restNode = document.createTextNode(rest);
134744
+ clone.replaceChild(restNode, textNode);
134745
+ clone.insertBefore(span, restNode);
134746
+ continue;
134747
+ }
134748
+ const rawContent = style.content;
134749
+ const { text: cleanContent, incs } = resolvePseudoContentAndIncs(source, pseudo, counterCtx);
134750
+ const bg = style.backgroundImage;
134751
+ const bgColor = style.backgroundColor;
134752
+ const fontFamily = style.fontFamily;
134753
+ const fontSize = parseInt(style.fontSize) || 32;
134754
+ const fontWeight = parseInt(style.fontWeight) || false;
134755
+ const color = style.color || "#000";
134756
+ const borderStyle = style.borderStyle;
134757
+ const borderWidth = parseFloat(style.borderWidth);
134758
+ const transform = style.transform;
134759
+ const isIconFont22 = isIconFont2(fontFamily);
134760
+ const hasExplicitContent = rawContent !== "none" && cleanContent !== "";
134761
+ const hasBg = bg && bg !== "none";
134762
+ const hasBgColor = bgColor && bgColor !== "transparent" && bgColor !== "rgba(0, 0, 0, 0)";
134763
+ const hasBorder = borderStyle && borderStyle !== "none" && borderWidth > 0;
134764
+ const hasTransform = transform && transform !== "none";
134765
+ const shouldRender = hasExplicitContent || hasBg || hasBgColor || hasBorder || hasTransform;
134766
+ if (!shouldRender) {
134767
+ if (incs && incs.length && source.parentElement) {
134768
+ const map = __siblingCounters.get(source.parentElement) || /* @__PURE__ */ new Map();
134769
+ for (const { name } of incs) {
134770
+ if (!name) continue;
134771
+ const baseWithSibs = withSiblingOverrides(source, counterCtx);
134772
+ const derived = deriveCounterCtxForPseudo(source, getComputedStyle(source, pseudo), baseWithSibs);
134773
+ const finalVal = derived.get(source, name);
134774
+ map.set(name, finalVal);
134775
+ }
134776
+ __siblingCounters.set(source.parentElement, map);
134777
+ }
134778
+ continue;
134779
+ }
134780
+ const pseudoEl = document.createElement("span");
134781
+ pseudoEl.dataset.snapdomPseudo = pseudo;
134782
+ pseudoEl.style.verticalAlign = "middle";
134783
+ pseudoEl.style.pointerEvents = "none";
134784
+ const snapshot = snapshotComputedStyle(style);
134785
+ const key = getStyleKey(snapshot, "span");
134786
+ sessionCache.styleMap.set(pseudoEl, key);
134787
+ if (isIconFont22 && cleanContent && cleanContent.length === 1) {
134788
+ const { dataUrl, width: w, height: h } = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);
134789
+ const imgEl = document.createElement("img");
134790
+ imgEl.src = dataUrl;
134791
+ imgEl.style = `height:${fontSize}px;width:${w / h * fontSize}px;object-fit:contain;`;
134792
+ pseudoEl.appendChild(imgEl);
134793
+ clone.dataset.snapdomHasIcon = "true";
134794
+ } else if (cleanContent && cleanContent.startsWith("url(")) {
134795
+ const rawUrl = extractURL(cleanContent);
134796
+ if (rawUrl?.trim()) {
134797
+ try {
134798
+ const imgEl = document.createElement("img");
134799
+ const dataUrl = await snapFetch(safeEncodeURI(rawUrl), { as: "dataURL", useProxy: options.useProxy });
134800
+ imgEl.src = dataUrl.data;
134801
+ imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;
134802
+ pseudoEl.appendChild(imgEl);
134803
+ } catch (e) {
134804
+ console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);
134805
+ }
134806
+ }
134807
+ } else if (!isIconFont22 && hasExplicitContent) {
134808
+ pseudoEl.textContent = cleanContent;
134809
+ }
134810
+ pseudoEl.style.background = "none";
134811
+ if ("mask" in pseudoEl.style) {
134812
+ pseudoEl.style.mask = "none";
134813
+ }
134814
+ if (hasBg) {
134815
+ try {
134816
+ const bgSplits = splitBackgroundImage(bg);
134817
+ const newBgParts = await Promise.all(bgSplits.map(inlineSingleBackgroundEntry));
134818
+ pseudoEl.style.backgroundImage = newBgParts.join(", ");
134819
+ } catch (e) {
134820
+ console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);
134821
+ }
134822
+ }
134823
+ if (hasBgColor) pseudoEl.style.backgroundColor = bgColor;
134824
+ const hasContent2 = pseudoEl.childNodes.length > 0 || pseudoEl.textContent?.trim() !== "";
134825
+ const hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBorder || hasTransform;
134826
+ if (incs && incs.length && source.parentElement) {
134827
+ const map = __siblingCounters.get(source.parentElement) || /* @__PURE__ */ new Map();
134828
+ const baseWithSibs = withSiblingOverrides(source, counterCtx);
134829
+ const derived = deriveCounterCtxForPseudo(source, getComputedStyle(source, pseudo), baseWithSibs);
134830
+ for (const { name } of incs) {
134831
+ if (!name) continue;
134832
+ const finalVal = derived.get(source, name);
134833
+ map.set(name, finalVal);
134834
+ }
134835
+ __siblingCounters.set(source.parentElement, map);
134836
+ }
134837
+ if (!hasVisibleBox) continue;
134838
+ if (pseudo === "::before") {
134839
+ clone.insertBefore(pseudoEl, clone.firstChild);
134840
+ } else {
134841
+ clone.appendChild(pseudoEl);
134842
+ }
134843
+ } catch (e) {
134844
+ console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);
134845
+ }
134846
+ }
134847
+ const sChildren = Array.from(source.children);
134848
+ const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);
134849
+ for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {
134850
+ await inlinePseudoElements(sChildren[i], cChildren[i], sessionCache, options);
134851
+ }
134852
+ }
134853
+
134854
+ // src/modules/svgDefs.js
134855
+ function inlineExternalDefsAndSymbols(rootElement) {
134856
+ if (!rootElement) return;
134857
+ const usedIds = /* @__PURE__ */ new Set();
134858
+ rootElement.querySelectorAll("use").forEach((use) => {
134859
+ const href = use.getAttribute("xlink:href") || use.getAttribute("href");
134860
+ if (href && href.startsWith("#")) {
134861
+ usedIds.add(href.slice(1));
134862
+ }
134863
+ });
134864
+ if (!usedIds.size) return;
134865
+ const allGlobal = Array.from(document.querySelectorAll("svg > symbol, svg > defs"));
134866
+ const globalSymbols = allGlobal.filter((el) => el.tagName.toLowerCase() === "symbol");
134867
+ const globalDefs = allGlobal.filter((el) => el.tagName.toLowerCase() === "defs");
134868
+ let container = rootElement.querySelector("svg.inline-defs-container");
134869
+ if (!container) {
134870
+ container = document.createElementNS("http://www.w3.org/2000/svg", "svg");
134871
+ container.setAttribute("aria-hidden", "true");
134872
+ container.setAttribute("style", "position: absolute; width: 0; height: 0; overflow: hidden;");
134873
+ container.classList.add("inline-defs-container");
134874
+ rootElement.insertBefore(container, rootElement.firstChild);
134875
+ }
134876
+ const existingIds = /* @__PURE__ */ new Set();
134877
+ rootElement.querySelectorAll("symbol[id], defs > *[id]").forEach((el) => {
134878
+ existingIds.add(el.id);
134879
+ });
134880
+ usedIds.forEach((id) => {
134881
+ if (existingIds.has(id)) return;
134882
+ const symbol = globalSymbols.find((sym) => sym.id === id);
134883
+ if (symbol) {
134884
+ container.appendChild(symbol.cloneNode(true));
134885
+ existingIds.add(id);
134886
+ return;
134887
+ }
134888
+ for (const defs of globalDefs) {
134889
+ const defEl = defs.querySelector(`#${CSS.escape(id)}`);
134890
+ if (defEl) {
134891
+ let defsContainer = container.querySelector("defs");
134892
+ if (!defsContainer) {
134893
+ defsContainer = document.createElementNS("http://www.w3.org/2000/svg", "defs");
134894
+ container.appendChild(defsContainer);
134895
+ }
134896
+ defsContainer.appendChild(defEl.cloneNode(true));
134897
+ existingIds.add(id);
134898
+ break;
134899
+ }
134900
+ }
134901
+ });
134902
+ }
134903
+
134904
+ // src/modules/changeCSS.js
134905
+ function freezeSticky(originalRoot, cloneRoot) {
134906
+ if (!originalRoot || !cloneRoot) return;
134907
+ const scrollTop = originalRoot.scrollTop || 0;
134908
+ if (!scrollTop) return;
134909
+ if (getComputedStyle(cloneRoot).position === "static") {
134910
+ cloneRoot.style.position = "relative";
134911
+ }
134912
+ const rootRect = originalRoot.getBoundingClientRect();
134913
+ const viewportH = originalRoot.clientHeight;
134914
+ const PH_ATTR = "data-snap-ph";
134915
+ const walker = document.createTreeWalker(originalRoot, NodeFilter.SHOW_ELEMENT);
134916
+ while (walker.nextNode()) {
134917
+ const el = (
134918
+ /** @type {HTMLElement} */
134919
+ walker.currentNode
134920
+ );
134921
+ const cs = getComputedStyle(el);
134922
+ const pos = cs.position;
134923
+ if (pos !== "sticky" && pos !== "-webkit-sticky") continue;
134924
+ const topInit = _toPx(cs.top);
134925
+ const bottomInit = _toPx(cs.bottom);
134926
+ if (topInit == null && bottomInit == null) continue;
134927
+ const path = _pathOf(el, originalRoot);
134928
+ const cloneEl = _findByPathIgnoringPlaceholders(cloneRoot, path, PH_ATTR);
134929
+ if (!cloneEl) continue;
134930
+ const elRect = el.getBoundingClientRect();
134931
+ const widthPx = elRect.width;
134932
+ const heightPx = elRect.height;
134933
+ const leftPx = elRect.left - rootRect.left;
134934
+ if (!(widthPx > 0 && heightPx > 0)) continue;
134935
+ if (!Number.isFinite(leftPx)) continue;
134936
+ const topAbsPx = topInit != null ? topInit + scrollTop : scrollTop + (viewportH - heightPx - /** bottomInit non-null */
134937
+ bottomInit);
134938
+ if (!Number.isFinite(topAbsPx)) continue;
134939
+ const zParsed = Number.parseInt(cs.zIndex, 10);
134940
+ const hasZ = Number.isFinite(zParsed);
134941
+ const overlayZ = hasZ ? Math.max(zParsed, 1) + 1 : 2;
134942
+ const placeholderZ = hasZ ? zParsed - 1 : 0;
134943
+ const ph = cloneEl.cloneNode(false);
134944
+ ph.setAttribute(PH_ATTR, "1");
134945
+ ph.style.position = "sticky";
134946
+ ph.style.left = `${leftPx}px`;
134947
+ ph.style.top = `${topAbsPx}px`;
134948
+ ph.style.width = `${widthPx}px`;
134949
+ ph.style.height = `${heightPx}px`;
134950
+ ph.style.visibility = "hidden";
134951
+ ph.style.zIndex = String(placeholderZ);
134952
+ ph.style.overflow = "hidden";
134953
+ ph.style.background = "transparent";
134954
+ ph.style.boxShadow = "none";
134955
+ ph.style.filter = "none";
134956
+ cloneEl.parentElement?.insertBefore(ph, cloneEl);
134957
+ cloneEl.style.position = "absolute";
134958
+ cloneEl.style.left = `${leftPx}px`;
134959
+ cloneEl.style.top = `${topAbsPx}px`;
134960
+ cloneEl.style.bottom = "auto";
134961
+ cloneEl.style.zIndex = String(overlayZ);
134962
+ cloneEl.style.pointerEvents = "none";
134963
+ }
134964
+ }
134965
+ function _toPx(v) {
134966
+ if (!v || v === "auto") return null;
134967
+ const n = Number.parseFloat(v);
134968
+ return Number.isFinite(n) ? n : null;
134969
+ }
134970
+ function _pathOf(el, root) {
134971
+ const path = [];
134972
+ for (let cur = el; cur && cur !== root; ) {
134973
+ const p = cur.parentElement;
134974
+ if (!p) break;
134975
+ path.push(Array.prototype.indexOf.call(p.children, cur));
134976
+ cur = p;
134977
+ }
134978
+ return path.reverse();
134979
+ }
134980
+ function _findByPathIgnoringPlaceholders(root, path, phAttr) {
134981
+ let cur = root;
134982
+ for (let i = 0; i < path.length; i++) {
134983
+ const kids = _childrenWithoutPlaceholders(cur, phAttr);
134984
+ cur = /** @type {HTMLElement|undefined} */
134985
+ kids[path[i]];
134986
+ if (!cur) return null;
134987
+ }
134988
+ return cur instanceof HTMLElement ? cur : null;
134989
+ }
134990
+ function _childrenWithoutPlaceholders(el, phAttr) {
134991
+ const out = [];
134992
+ const ch = el.children;
134993
+ for (let i = 0; i < ch.length; i++) {
134994
+ const c = ch[i];
134995
+ if (!c.hasAttribute(phAttr)) out.push(c);
134996
+ }
134997
+ return out;
134998
+ }
134999
+
135000
+ // src/core/prepare.js
135001
+ async function prepareClone(element, options = {}) {
135002
+ const sessionCache = {
135003
+ styleMap: cache.session.styleMap,
135004
+ styleCache: cache.session.styleCache,
135005
+ nodeMap: cache.session.nodeMap
135006
+ };
135007
+ let clone;
135008
+ let classCSS = "";
135009
+ let shadowScopedCSS = "";
135010
+ stabilizeLayout(element);
135011
+ try {
135012
+ inlineExternalDefsAndSymbols(element);
135013
+ } catch (e) {
135014
+ console.warn("inlineExternal defs or symbol failed:", e);
135015
+ }
135016
+ try {
135017
+ clone = await deepClone(element, sessionCache, options, element);
135018
+ } catch (e) {
135019
+ console.warn("deepClone failed:", e);
135020
+ throw e;
135021
+ }
135022
+ try {
135023
+ await inlinePseudoElements(element, clone, sessionCache, options);
135024
+ } catch (e) {
135025
+ console.warn("inlinePseudoElements failed:", e);
135026
+ }
135027
+ await resolveBlobUrlsInTree(clone);
135028
+ try {
135029
+ const styleNodes = clone.querySelectorAll("style[data-sd]");
135030
+ for (const s of styleNodes) {
135031
+ shadowScopedCSS += s.textContent || "";
135032
+ s.remove();
135033
+ }
135034
+ } catch {
135035
+ }
135036
+ const keyToClass = generateCSSClasses(sessionCache.styleMap);
135037
+ classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join("");
135038
+ classCSS = shadowScopedCSS + classCSS;
135039
+ for (const [node, key] of sessionCache.styleMap.entries()) {
135040
+ if (node.tagName === "STYLE") continue;
135041
+ if (node.getRootNode && node.getRootNode() instanceof ShadowRoot) {
135042
+ node.setAttribute("style", key.replace(/;/g, "; "));
135043
+ continue;
135044
+ }
135045
+ const className = keyToClass.get(key);
135046
+ if (className) node.classList.add(className);
135047
+ const bgImage = node.style?.backgroundImage;
135048
+ const hasIcon = node.dataset?.snapdomHasIcon;
135049
+ if (bgImage && bgImage !== "none") node.style.backgroundImage = bgImage;
135050
+ if (hasIcon) {
135051
+ node.style.verticalAlign = "middle";
135052
+ node.style.display = "inline";
135053
+ }
135054
+ }
135055
+ for (const [cloneNode, originalNode] of sessionCache.nodeMap.entries()) {
135056
+ const scrollX = originalNode.scrollLeft;
135057
+ const scrollY = originalNode.scrollTop;
135058
+ const hasScroll = scrollX || scrollY;
135059
+ if (hasScroll && cloneNode instanceof HTMLElement) {
135060
+ cloneNode.style.overflow = "hidden";
135061
+ cloneNode.style.scrollbarWidth = "none";
135062
+ cloneNode.style.msOverflowStyle = "none";
135063
+ const inner = document.createElement("div");
135064
+ inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;
135065
+ inner.style.willChange = "transform";
135066
+ inner.style.display = "inline-block";
135067
+ inner.style.width = "100%";
135068
+ while (cloneNode.firstChild) {
135069
+ inner.appendChild(cloneNode.firstChild);
135070
+ }
135071
+ cloneNode.appendChild(inner);
135072
+ }
135073
+ }
135074
+ const contentRoot = clone instanceof HTMLElement && clone.firstElementChild instanceof HTMLElement ? clone.firstElementChild : clone;
135075
+ freezeSticky(element, contentRoot);
135076
+ if (element === sessionCache.nodeMap.get(clone)) {
135077
+ const computed = sessionCache.styleCache.get(element) || window.getComputedStyle(element);
135078
+ sessionCache.styleCache.set(element, computed);
135079
+ const transform = stripTranslate(computed.transform);
135080
+ clone.style.margin = "0";
135081
+ clone.style.top = "auto";
135082
+ clone.style.left = "auto";
135083
+ clone.style.right = "auto";
135084
+ clone.style.bottom = "auto";
135085
+ clone.style.animation = "none";
135086
+ clone.style.transition = "none";
135087
+ clone.style.willChange = "auto";
135088
+ clone.style.float = "none";
135089
+ clone.style.clear = "none";
135090
+ clone.style.transform = transform || "";
135091
+ }
135092
+ for (const [cloneNode, originalNode] of sessionCache.nodeMap.entries()) {
135093
+ if (originalNode.tagName === "PRE") {
135094
+ cloneNode.style.marginTop = "0";
135095
+ cloneNode.style.marginBlockStart = "0";
135096
+ }
135097
+ }
135098
+ return { clone, classCSS, styleCache: sessionCache.styleCache };
135099
+ }
135100
+ function stabilizeLayout(element) {
135101
+ const style = getComputedStyle(element);
135102
+ const outlineStyle = style.outlineStyle;
135103
+ const outlineWidth = style.outlineWidth;
135104
+ const borderStyle = style.borderStyle;
135105
+ const borderWidth = style.borderWidth;
135106
+ const outlineVisible = outlineStyle !== "none" && parseFloat(outlineWidth) > 0;
135107
+ const borderAbsent = borderStyle === "none" || parseFloat(borderWidth) === 0;
135108
+ if (outlineVisible && borderAbsent) {
135109
+ element.style.border = `${outlineWidth} solid transparent`;
135110
+ }
135111
+ }
135112
+ var _blobToDataUrlCache = /* @__PURE__ */ new Map();
135113
+ async function blobUrlToDataUrl(blobUrl) {
135114
+ if (cache.resource?.has(blobUrl)) return cache.resource.get(blobUrl);
135115
+ if (_blobToDataUrlCache.has(blobUrl)) return _blobToDataUrlCache.get(blobUrl);
135116
+ const p = (async () => {
135117
+ const r = await snapFetch(blobUrl, { as: "dataURL", silent: true });
135118
+ if (!r.ok || typeof r.data !== "string") {
135119
+ throw new Error(`[snapDOM] Failed to read blob URL: ${blobUrl}`);
135120
+ }
135121
+ cache.resource?.set(blobUrl, r.data);
135122
+ return r.data;
135123
+ })();
135124
+ _blobToDataUrlCache.set(blobUrl, p);
135125
+ try {
135126
+ const data = await p;
135127
+ _blobToDataUrlCache.set(blobUrl, data);
135128
+ return data;
135129
+ } catch (e) {
135130
+ _blobToDataUrlCache.delete(blobUrl);
135131
+ throw e;
135132
+ }
135133
+ }
135134
+ var BLOB_URL_RE = /\bblob:[^)"'\s]+/g;
135135
+ async function replaceBlobUrlsInCssText(cssText) {
135136
+ if (!cssText || cssText.indexOf("blob:") === -1) return cssText;
135137
+ const uniques = Array.from(new Set(cssText.match(BLOB_URL_RE) || []));
135138
+ if (uniques.length === 0) return cssText;
135139
+ let out = cssText;
135140
+ for (const u of uniques) {
135141
+ try {
135142
+ const d = await blobUrlToDataUrl(u);
135143
+ out = out.split(u).join(d);
135144
+ } catch {
135145
+ }
135146
+ }
135147
+ return out;
135148
+ }
135149
+ function isBlobUrl(u) {
135150
+ return typeof u === "string" && u.startsWith("blob:");
135151
+ }
135152
+ function parseSrcset(srcset) {
135153
+ return (srcset || "").split(",").map((s) => s.trim()).filter(Boolean).map((item) => {
135154
+ const m = item.match(/^(\S+)(\s+.+)?$/);
135155
+ return m ? { url: m[1], desc: m[2] || "" } : null;
135156
+ }).filter(Boolean);
135157
+ }
135158
+ function stringifySrcset(parts) {
135159
+ return parts.map((p) => p.desc ? `${p.url} ${p.desc.trim()}` : p.url).join(", ");
135160
+ }
135161
+ async function resolveBlobUrlsInTree(root) {
135162
+ if (!root) return;
135163
+ const imgs = root.querySelectorAll ? root.querySelectorAll("img") : [];
135164
+ for (const img of imgs) {
135165
+ try {
135166
+ const srcAttr = img.getAttribute("src");
135167
+ const effective = srcAttr || img.currentSrc || "";
135168
+ if (isBlobUrl(effective)) {
135169
+ const data = await blobUrlToDataUrl(effective);
135170
+ img.setAttribute("src", data);
135171
+ }
135172
+ const srcset = img.getAttribute("srcset");
135173
+ if (srcset && srcset.includes("blob:")) {
135174
+ const parts = parseSrcset(srcset);
135175
+ let changed = false;
135176
+ for (const p of parts) {
135177
+ if (isBlobUrl(p.url)) {
135178
+ try {
135179
+ p.url = await blobUrlToDataUrl(p.url);
135180
+ changed = true;
135181
+ } catch {
135182
+ }
135183
+ }
135184
+ }
135185
+ if (changed) img.setAttribute("srcset", stringifySrcset(parts));
135186
+ }
135187
+ } catch {
135188
+ }
135189
+ }
135190
+ const svgImages = root.querySelectorAll ? root.querySelectorAll("image") : [];
135191
+ for (const node of svgImages) {
135192
+ try {
135193
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
135194
+ const href = node.getAttribute("href") || node.getAttributeNS?.(XLINK_NS, "href");
135195
+ if (isBlobUrl(href)) {
135196
+ const d = await blobUrlToDataUrl(href);
135197
+ node.setAttribute("href", d);
135198
+ node.removeAttributeNS?.(XLINK_NS, "href");
135199
+ }
135200
+ } catch {
135201
+ }
135202
+ }
135203
+ const styled = root.querySelectorAll ? root.querySelectorAll("[style*='blob:']") : [];
135204
+ for (const el of styled) {
135205
+ try {
135206
+ const styleText = el.getAttribute("style");
135207
+ if (styleText && styleText.includes("blob:")) {
135208
+ const replaced = await replaceBlobUrlsInCssText(styleText);
135209
+ el.setAttribute("style", replaced);
135210
+ }
135211
+ } catch {
135212
+ }
135213
+ }
135214
+ const styleTags = root.querySelectorAll ? root.querySelectorAll("style") : [];
135215
+ for (const s of styleTags) {
135216
+ try {
135217
+ const css = s.textContent || "";
135218
+ if (css.includes("blob:")) {
135219
+ s.textContent = await replaceBlobUrlsInCssText(css);
135220
+ }
135221
+ } catch {
135222
+ }
135223
+ }
135224
+ const urlAttrs = ["poster"];
135225
+ for (const attr of urlAttrs) {
135226
+ const nodes = root.querySelectorAll ? root.querySelectorAll(`[${attr}^='blob:']`) : [];
135227
+ for (const n of nodes) {
135228
+ try {
135229
+ const u = n.getAttribute(attr);
135230
+ if (isBlobUrl(u)) {
135231
+ n.setAttribute(attr, await blobUrlToDataUrl(u));
135232
+ }
135233
+ } catch {
135234
+ }
135235
+ }
135236
+ }
135237
+ }
135238
+
135239
+ // src/modules/images.js
135240
+ async function inlineImages(clone, options = {}) {
135241
+ const imgs = Array.from(clone.querySelectorAll("img"));
135242
+ const processImg = async (img) => {
135243
+ if (!img.getAttribute("src")) {
135244
+ const eff = img.currentSrc || img.src || "";
135245
+ if (eff) img.setAttribute("src", eff);
135246
+ }
135247
+ img.removeAttribute("srcset");
135248
+ img.removeAttribute("sizes");
135249
+ const src = img.src || "";
135250
+ if (!src) return;
135251
+ const r = await snapFetch(src, { as: "dataURL", useProxy: options.useProxy });
135252
+ if (r.ok && typeof r.data === "string" && r.data.startsWith("data:")) {
135253
+ img.src = r.data;
135254
+ if (!img.width) img.width = img.naturalWidth || 100;
135255
+ if (!img.height) img.height = img.naturalHeight || 100;
135256
+ return;
135257
+ }
135258
+ const { fallbackURL } = options || {};
135259
+ if (fallbackURL) {
135260
+ try {
135261
+ const dsW = parseInt(img.dataset?.snapdomWidth || "", 10) || 0;
135262
+ const dsH = parseInt(img.dataset?.snapdomHeight || "", 10) || 0;
135263
+ const attrW = parseInt(img.getAttribute("width") || "", 10) || 0;
135264
+ const attrH = parseInt(img.getAttribute("height") || "", 10) || 0;
135265
+ const styleW = parseFloat(img.style?.width || "") || 0;
135266
+ const styleH = parseFloat(img.style?.height || "") || 0;
135267
+ const fbW = dsW || styleW || attrW || img.width || void 0;
135268
+ const fbH = dsH || styleH || attrH || img.height || void 0;
135269
+ const fallbackUrl = typeof fallbackURL === "function" ? await fallbackURL({ width: fbW, height: fbH, src, element: img }) : fallbackURL;
135270
+ if (fallbackUrl) {
135271
+ const fallbackData = await snapFetch(fallbackUrl, { as: "dataURL", useProxy: options.useProxy });
135272
+ img.src = fallbackData.data;
135273
+ if (!img.width && fbW) img.width = fbW;
135274
+ if (!img.height && fbH) img.height = fbH;
135275
+ if (!img.width) img.width = img.naturalWidth || 100;
135276
+ if (!img.height) img.height = img.naturalHeight || 100;
135277
+ return;
135278
+ }
135279
+ } catch {
135280
+ }
135281
+ }
135282
+ const w = img.width || img.naturalWidth || 100;
135283
+ const h = img.height || img.naturalHeight || 100;
135284
+ if (options.placeholders !== false) {
135285
+ const fallback = document.createElement("div");
135286
+ fallback.style.cssText = [
135287
+ `width:${w}px`,
135288
+ `height:${h}px`,
135289
+ "background:#ccc",
135290
+ "display:inline-block",
135291
+ "text-align:center",
135292
+ `line-height:${h}px`,
135293
+ "color:#666",
135294
+ "font-size:12px",
135295
+ "overflow:hidden"
135296
+ ].join(";");
135297
+ fallback.textContent = "img";
135298
+ img.replaceWith(fallback);
135299
+ } else {
135300
+ const spacer = document.createElement("div");
135301
+ spacer.style.cssText = `display:inline-block;width:${w}px;height:${h}px;visibility:hidden;`;
135302
+ img.replaceWith(spacer);
135303
+ }
135304
+ };
135305
+ for (let i = 0; i < imgs.length; i += 4) {
135306
+ const group = imgs.slice(i, i + 4).map(processImg);
135307
+ await Promise.allSettled(group);
135308
+ }
135309
+ }
135310
+
135311
+ // src/modules/background.js
135312
+ async function inlineBackgroundImages(source, clone, styleCache, options = {}) {
135313
+ const queue = [[source, clone]];
135314
+ const URL_PROPS = [
135315
+ "background-image",
135316
+ // Mask shorthands & images (both standard and WebKit)
135317
+ "mask",
135318
+ "mask-image",
135319
+ "-webkit-mask",
135320
+ "-webkit-mask-image",
135321
+ // Mask sources (rare, but keep)
135322
+ "mask-source",
135323
+ "mask-box-image-source",
135324
+ "mask-border-source",
135325
+ "-webkit-mask-box-image-source",
135326
+ // Border image
135327
+ "border-image",
135328
+ "border-image-source"
135329
+ ];
135330
+ const MASK_LAYOUT_PROPS = [
135331
+ "mask-position",
135332
+ "mask-size",
135333
+ "mask-repeat",
135334
+ // WebKit variants
135335
+ "-webkit-mask-position",
135336
+ "-webkit-mask-size",
135337
+ "-webkit-mask-repeat",
135338
+ // Extra (optional but helpful across engines)
135339
+ "mask-origin",
135340
+ "mask-clip",
135341
+ "-webkit-mask-origin",
135342
+ "-webkit-mask-clip",
135343
+ // Some engines expose X/Y position separately:
135344
+ "-webkit-mask-position-x",
135345
+ "-webkit-mask-position-y"
135346
+ ];
135347
+ const BORDER_AUX_PROPS = [
135348
+ "border-image-slice",
135349
+ "border-image-width",
135350
+ "border-image-outset",
135351
+ "border-image-repeat"
135352
+ ];
135353
+ while (queue.length) {
135354
+ const [srcNode, cloneNode] = queue.shift();
135355
+ const style = styleCache.get(srcNode) || getStyle(srcNode);
135356
+ if (!styleCache.has(srcNode)) styleCache.set(srcNode, style);
135357
+ const hasBorderImage = (() => {
135358
+ const bi = style.getPropertyValue("border-image");
135359
+ const bis = style.getPropertyValue("border-image-source");
135360
+ return bi && bi !== "none" || bis && bis !== "none";
135361
+ })();
135362
+ for (const prop of URL_PROPS) {
135363
+ const val = style.getPropertyValue(prop);
135364
+ if (!val || val === "none") continue;
135365
+ const splits = splitBackgroundImage(val);
135366
+ const inlined = await Promise.all(
135367
+ splits.map((entry) => inlineSingleBackgroundEntry(entry, options))
135368
+ );
135369
+ if (inlined.some((p) => p && p !== "none" && !/^url\(undefined/.test(p))) {
135370
+ cloneNode.style.setProperty(prop, inlined.join(", "));
135371
+ }
135372
+ }
135373
+ for (const prop of MASK_LAYOUT_PROPS) {
135374
+ const val = style.getPropertyValue(prop);
135375
+ if (!val || val === "initial") continue;
135376
+ cloneNode.style.setProperty(prop, val);
135377
+ }
135378
+ if (hasBorderImage) {
135379
+ for (const prop of BORDER_AUX_PROPS) {
135380
+ const val = style.getPropertyValue(prop);
135381
+ if (!val || val === "initial") continue;
135382
+ cloneNode.style.setProperty(prop, val);
135383
+ }
135384
+ }
135385
+ const sChildren = Array.from(srcNode.children);
135386
+ const cChildren = Array.from(cloneNode.children);
135387
+ for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {
135388
+ queue.push([sChildren[i], cChildren[i]]);
135389
+ }
135390
+ }
135391
+ }
135392
+
135393
+ // src/modules/lineClamp.js
135394
+ function lineClamp(el) {
135395
+ if (!el) return () => {
135396
+ };
135397
+ const lines = getClamp(el);
135398
+ if (lines <= 0) return () => {
135399
+ };
135400
+ if (!isPlainTextContainer(el)) return () => {
135401
+ };
135402
+ const cs = getComputedStyle(el);
135403
+ const targetH = Math.round(usedLineHeightPx(cs) * lines + vpad(cs));
135404
+ const original = el.textContent ?? "";
135405
+ const prevText = original;
135406
+ if (el.scrollHeight <= targetH + 0.5) {
135407
+ return () => {
135408
+ };
135409
+ }
135410
+ let lo = 0, hi = original.length, best = -1;
135411
+ while (lo <= hi) {
135412
+ const mid = lo + hi >> 1;
135413
+ el.textContent = original.slice(0, mid) + "\u2026";
135414
+ if (el.scrollHeight <= targetH + 0.5) {
135415
+ best = mid;
135416
+ lo = mid + 1;
135417
+ } else {
135418
+ hi = mid - 1;
135419
+ }
135420
+ }
135421
+ el.textContent = (best >= 0 ? original.slice(0, best) : "") + "\u2026";
135422
+ return () => {
135423
+ el.textContent = prevText;
135424
+ };
135425
+ }
135426
+ function getClamp(el) {
135427
+ const cs = getComputedStyle(el);
135428
+ let v = cs.getPropertyValue("-webkit-line-clamp") || cs.getPropertyValue("line-clamp");
135429
+ v = (v || "").trim();
135430
+ const n = parseInt(v, 10);
135431
+ return Number.isFinite(n) && n > 0 ? n : 0;
135432
+ }
135433
+ function usedLineHeightPx(cs) {
135434
+ const lh = (cs.lineHeight || "").trim();
135435
+ const fs = parseFloat(cs.fontSize) || 16;
135436
+ if (!lh || lh === "normal") return Math.round(fs * 1.2);
135437
+ if (lh.endsWith("px")) return parseFloat(lh);
135438
+ if (/^\d+(\.\d+)?$/.test(lh)) return Math.round(parseFloat(lh) * fs);
135439
+ if (lh.endsWith("%")) return Math.round(parseFloat(lh) / 100 * fs);
135440
+ return Math.round(fs * 1.2);
135441
+ }
135442
+ function vpad(cs) {
135443
+ return (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
135444
+ }
135445
+ function isPlainTextContainer(el) {
135446
+ if (el.childElementCount > 0) return false;
135447
+ return Array.from(el.childNodes).some((n) => n.nodeType === Node.TEXT_NODE);
135448
+ }
135449
+
135450
+ // src/core/capture.js
135451
+ function stripRootShadows(originalEl, cloneRoot) {
135452
+ if (!originalEl || !cloneRoot || !cloneRoot.style) return;
135453
+ const cs = getComputedStyle(originalEl);
135454
+ try {
135455
+ cloneRoot.style.boxShadow = "none";
135456
+ } catch {
135457
+ }
135458
+ try {
135459
+ cloneRoot.style.textShadow = "none";
135460
+ } catch {
135461
+ }
135462
+ try {
135463
+ cloneRoot.style.outline = "none";
135464
+ } catch {
135465
+ }
135466
+ const f = cs.filter || "";
135467
+ const cleaned = f.replace(/\bblur\([^()]*\)\s*/gi, "").replace(/\bdrop-shadow\([^()]*\)\s*/gi, "").trim().replace(/\s+/g, " ");
135468
+ try {
135469
+ cloneRoot.style.filter = cleaned.length ? cleaned : "none";
135470
+ } catch {
135471
+ }
135472
+ }
135473
+ async function captureDOM(element, options) {
135474
+ if (!element) throw new Error("Element cannot be null or undefined");
135475
+ applyCachePolicy(options.cache);
135476
+ const fast = options.fast;
135477
+ const straighten = !!options.straighten;
135478
+ const noShadows = !!options.noShadows;
135479
+ let clone, classCSS, styleCache;
135480
+ let fontsCSS = "";
135481
+ let baseCSS = "";
135482
+ let dataURL;
135483
+ let svgString;
135484
+ let rootTransform2D = null;
135485
+ const undoClamp = lineClamp(element);
135486
+ try {
135487
+ ({ clone, classCSS, styleCache } = await prepareClone(element, options));
135488
+ if (straighten && clone) {
135489
+ rootTransform2D = normalizeRootTransforms(element, clone);
135490
+ }
135491
+ if (noShadows && clone) {
135492
+ stripRootShadows(element, clone);
135493
+ }
135494
+ } finally {
135495
+ undoClamp();
135496
+ }
135497
+ await new Promise((resolve) => {
135498
+ idle(async () => {
135499
+ await inlineImages(clone, options);
135500
+ resolve();
135501
+ }, { fast });
135502
+ });
135503
+ await new Promise((resolve) => {
135504
+ idle(async () => {
135505
+ await inlineBackgroundImages(element, clone, styleCache, options);
135506
+ resolve();
135507
+ }, { fast });
135508
+ });
135509
+ if (options.embedFonts) {
135510
+ await new Promise((resolve) => {
135511
+ idle(async () => {
135512
+ const required = collectUsedFontVariants(element);
135513
+ const usedCodepoints = collectUsedCodepoints(element);
135514
+ if (isSafari()) {
135515
+ const families = new Set(
135516
+ Array.from(required).map((k) => String(k).split("__")[0]).filter(Boolean)
135517
+ );
135518
+ await ensureFontsReady(families, 1);
135519
+ }
135520
+ fontsCSS = await embedCustomFonts({
135521
+ required,
135522
+ usedCodepoints,
135523
+ exclude: options.excludeFonts,
135524
+ useProxy: options.useProxy
135525
+ });
135526
+ resolve();
135527
+ }, { fast });
135528
+ });
135529
+ }
135530
+ const usedTags = collectUsedTagNames(clone).sort();
135531
+ const tagKey = usedTags.join(",");
135532
+ if (cache.baseStyle.has(tagKey)) {
135533
+ baseCSS = cache.baseStyle.get(tagKey);
135534
+ } else {
135535
+ await new Promise((resolve) => {
135536
+ idle(() => {
135537
+ baseCSS = generateDedupedBaseCSS(usedTags);
135538
+ cache.baseStyle.set(tagKey, baseCSS);
135539
+ resolve();
135540
+ }, { fast });
135541
+ });
135542
+ }
135543
+ await new Promise((resolve) => {
135544
+ idle(() => {
135545
+ const csEl = getComputedStyle(element);
135546
+ function parseFilterDropShadows(cs) {
135547
+ const raw = `${cs.filter || ""} ${cs.webkitFilter || ""}`.trim();
135548
+ if (!raw || raw === "none") {
135549
+ return { bleed: { top: 0, right: 0, bottom: 0, left: 0 }, has: false };
135550
+ }
135551
+ const tokens = raw.match(/drop-shadow\((?:[^()]|\([^()]*\))*\)/gi) || [];
135552
+ let t = 0, r = 0, b = 0, l = 0;
135553
+ let found = false;
135554
+ for (const tok of tokens) {
135555
+ found = true;
135556
+ const nums = tok.match(/-?\d+(?:\.\d+)?px/gi)?.map((v) => parseFloat(v)) || [];
135557
+ const [ox = 0, oy = 0, blur = 0] = nums;
135558
+ const extX = Math.abs(ox) + blur;
135559
+ const extY = Math.abs(oy) + blur;
135560
+ r = Math.max(r, extX + Math.max(ox, 0));
135561
+ l = Math.max(l, extX + Math.max(-ox, 0));
135562
+ b = Math.max(b, extY + Math.max(oy, 0));
135563
+ t = Math.max(t, extY + Math.max(-oy, 0));
135564
+ }
135565
+ return { bleed: { top: Math.ceil(t), right: Math.ceil(r), bottom: Math.ceil(b), left: Math.ceil(l) }, has: found };
135566
+ }
135567
+ const rect = element.getBoundingClientRect();
135568
+ const w0 = Math.max(1, Math.ceil(element.offsetWidth || parseFloat(csEl.width) || rect.width || 1));
135569
+ const h0 = Math.max(1, Math.ceil(element.offsetHeight || parseFloat(csEl.height) || rect.height || 1));
135570
+ const coerceNum = (v, def = NaN) => {
135571
+ const n = typeof v === "string" ? parseFloat(v) : v;
135572
+ return Number.isFinite(n) ? n : def;
135573
+ };
135574
+ const optW = coerceNum(options.width);
135575
+ const optH = coerceNum(options.height);
135576
+ let w = w0, h = h0;
135577
+ const hasW = Number.isFinite(optW);
135578
+ const hasH = Number.isFinite(optH);
135579
+ const aspect0 = h0 > 0 ? w0 / h0 : 1;
135580
+ if (hasW && hasH) {
135581
+ w = Math.max(1, Math.ceil(optW));
135582
+ h = Math.max(1, Math.ceil(optH));
135583
+ } else if (hasW) {
135584
+ w = Math.max(1, Math.ceil(optW));
135585
+ h = Math.max(1, Math.ceil(w / (aspect0 || 1)));
135586
+ } else if (hasH) {
135587
+ h = Math.max(1, Math.ceil(optH));
135588
+ w = Math.max(1, Math.ceil(h * (aspect0 || 1)));
135589
+ } else {
135590
+ w = w0;
135591
+ h = h0;
135592
+ }
135593
+ let minX = 0, minY = 0, maxX = w0, maxY = h0;
135594
+ if (straighten && rootTransform2D && Number.isFinite(rootTransform2D.a)) {
135595
+ const M2 = { a: rootTransform2D.a, b: rootTransform2D.b || 0, c: rootTransform2D.c || 0, d: rootTransform2D.d || 1, e: 0, f: 0 };
135596
+ const bb2 = bboxWithOriginFull(w0, h0, M2, 0, 0);
135597
+ minX = bb2.minX;
135598
+ minY = bb2.minY;
135599
+ maxX = bb2.maxX;
135600
+ maxY = bb2.maxY;
135601
+ } else {
135602
+ const useTFBBox = !straighten && hasTFBBox(element);
135603
+ if (useTFBBox) {
135604
+ const baseTransform2 = csEl.transform && csEl.transform !== "none" ? csEl.transform : "";
135605
+ const ind2 = readIndividualTransforms(element);
135606
+ const TOTAL = readTotalTransformMatrix({
135607
+ baseTransform: baseTransform2,
135608
+ rotate: ind2.rotate || "0deg",
135609
+ scale: ind2.scale,
135610
+ translate: ind2.translate
135611
+ });
135612
+ const { ox: ox2, oy: oy2 } = parseTransformOriginPx(csEl, w0, h0);
135613
+ const M = TOTAL.is2D ? TOTAL : new DOMMatrix(TOTAL.toString());
135614
+ const bb = bboxWithOriginFull(w0, h0, M, ox2, oy2);
135615
+ minX = bb.minX;
135616
+ minY = bb.minY;
135617
+ maxX = bb.maxX;
135618
+ maxY = bb.maxY;
135619
+ }
135620
+ }
135621
+ const bleedShadow = parseBoxShadow(csEl);
135622
+ const bleedBlur = parseFilterBlur(csEl);
135623
+ const bleedOutline = parseOutline(csEl);
135624
+ const drop = parseFilterDropShadows(csEl);
135625
+ const bleed = noShadows ? { top: 0, right: 0, bottom: 0, left: 0 } : {
135626
+ top: bleedShadow.top + bleedBlur.top + bleedOutline.top + drop.bleed.top,
135627
+ right: bleedShadow.right + bleedBlur.right + bleedOutline.right + drop.bleed.right,
135628
+ bottom: bleedShadow.bottom + bleedBlur.bottom + bleedOutline.bottom + drop.bleed.bottom,
135629
+ left: bleedShadow.left + bleedBlur.left + bleedOutline.left + drop.bleed.left
135630
+ };
135631
+ minX -= bleed.left;
135632
+ minY -= bleed.top;
135633
+ maxX += bleed.right;
135634
+ maxY += bleed.bottom;
135635
+ const vbW0 = Math.max(1, Math.ceil(maxX - minX));
135636
+ const vbH0 = Math.max(1, Math.ceil(maxY - minY));
135637
+ const outW = Math.max(1, Math.round(vbW0 * (hasW || hasH ? w / w0 : 1)));
135638
+ const outH = Math.max(1, Math.round(vbH0 * (hasH || hasW ? h / h0 : 1)));
135639
+ const svgNS = "http://www.w3.org/2000/svg";
135640
+ const basePad = isSafari() ? 1 : 0;
135641
+ const extraPad = straighten ? 1 : 0;
135642
+ const pad = basePad + extraPad;
135643
+ const fo = document.createElementNS(svgNS, "foreignObject");
135644
+ const vbMinX = Math.floor(minX);
135645
+ const vbMinY = Math.floor(minY);
135646
+ fo.setAttribute("x", String(-(vbMinX - pad)));
135647
+ fo.setAttribute("y", String(-(vbMinY - pad)));
135648
+ fo.setAttribute("width", String(Math.ceil(w0 + pad * 2)));
135649
+ fo.setAttribute("height", String(Math.ceil(h0 + pad * 2)));
135650
+ fo.style.overflow = "visible";
135651
+ const styleTag = document.createElement("style");
135652
+ styleTag.textContent = baseCSS + fontsCSS + "svg{overflow:visible;} foreignObject{overflow:visible;}" + classCSS;
135653
+ fo.appendChild(styleTag);
135654
+ const container = document.createElement("div");
135655
+ container.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
135656
+ container.style.width = `${w0}px`;
135657
+ container.style.height = `${h0}px`;
135658
+ container.style.overflow = "visible";
135659
+ clone.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
135660
+ container.appendChild(clone);
135661
+ fo.appendChild(container);
135662
+ const serializer = new XMLSerializer();
135663
+ const foString = serializer.serializeToString(fo);
135664
+ const vbW = vbW0 + pad * 2;
135665
+ const vbH = vbH0 + pad * 2;
135666
+ const wantsSize = hasW || hasH;
135667
+ options.meta = { w0, h0, vbW, vbH, targetW: w, targetH: h };
135668
+ const svgOutW = isSafari() && wantsSize ? vbW : outW + pad * 2;
135669
+ const svgOutH = isSafari() && wantsSize ? vbH : outH + pad * 2;
135670
+ const svgHeader = `<svg xmlns="${svgNS}" width="${svgOutW}" height="${svgOutH}" viewBox="0 0 ${vbW} ${vbH}">`;
135671
+ const svgFooter = "</svg>";
135672
+ svgString = svgHeader + foString + svgFooter;
135673
+ dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
135674
+ resolve();
135675
+ }, { fast });
135676
+ });
135677
+ const sandbox = document.getElementById("snapdom-sandbox");
135678
+ if (sandbox && sandbox.style.position === "absolute") sandbox.remove();
135679
+ return dataURL;
135680
+ }
135681
+ function normalizeRootTransforms(originalEl, cloneRoot) {
135682
+ if (!originalEl || !cloneRoot || !cloneRoot.style) return null;
135683
+ const cs = getComputedStyle(originalEl);
135684
+ try {
135685
+ cloneRoot.style.transformOrigin = "0 0";
135686
+ } catch {
135687
+ }
135688
+ try {
135689
+ if ("translate" in cloneRoot.style) cloneRoot.style.translate = "none";
135690
+ if ("rotate" in cloneRoot.style) cloneRoot.style.rotate = "none";
135691
+ } catch {
135692
+ }
135693
+ const tr = cs.transform || "none";
135694
+ if (tr === "none") {
135695
+ try {
135696
+ const M = matrixFromComputed(originalEl);
135697
+ if (M.a === 1 && M.b === 0 && M.c === 0 && M.d === 1) {
135698
+ cloneRoot.style.transform = "none";
135699
+ return { a: 1, b: 0, c: 0, d: 1 };
135700
+ }
135701
+ } catch {
135702
+ }
135703
+ }
135704
+ const m2d = tr.match(/^matrix\(\s*([^)]+)\)$/i);
135705
+ if (m2d) {
135706
+ const nums = m2d[1].split(",").map((v) => parseFloat(v.trim()));
135707
+ if (nums.length === 6 && nums.every(Number.isFinite)) {
135708
+ const [a, b, c, d] = nums;
135709
+ const scaleX = Math.sqrt(a * a + b * b) || 0;
135710
+ let a1 = 0, b1 = 0, shear = 0, c2 = 0, d2 = 0, scaleY = 0;
135711
+ if (scaleX > 0) {
135712
+ a1 = a / scaleX;
135713
+ b1 = b / scaleX;
135714
+ shear = a1 * c + b1 * d;
135715
+ c2 = c - a1 * shear;
135716
+ d2 = d - b1 * shear;
135717
+ scaleY = Math.sqrt(c2 * c2 + d2 * d2) || 0;
135718
+ if (scaleY > 0) shear = shear / scaleY;
135719
+ else shear = 0;
135720
+ }
135721
+ const aP = scaleX;
135722
+ const bP = 0;
135723
+ const cP = shear * scaleY;
135724
+ const dP = scaleY;
135725
+ try {
135726
+ cloneRoot.style.transform = `matrix(${aP}, ${bP}, ${cP}, ${dP}, 0, 0)`;
135727
+ } catch {
135728
+ }
135729
+ return { a: aP, b: bP, c: cP, d: dP };
135730
+ }
135731
+ }
135732
+ try {
135733
+ const legacy = String(tr).trim();
135734
+ cloneRoot.style.transform = legacy + " translate(0px, 0px) rotate(0deg)";
135735
+ return null;
135736
+ } catch {
135737
+ return null;
135738
+ }
135739
+ }
135740
+ function parseBoxShadow(cs) {
135741
+ const v = cs.boxShadow || "";
135742
+ if (!v || v === "none") return { top: 0, right: 0, bottom: 0, left: 0 };
135743
+ const parts = v.split(/\),(?=(?:[^()]*\([^()]*\))*[^()]*$)/).map((s) => s.trim());
135744
+ let t = 0, r = 0, b2 = 0, l = 0;
135745
+ for (const part of parts) {
135746
+ const nums = part.match(/-?\d+(\.\d+)?px/g)?.map((n) => parseFloat(n)) || [];
135747
+ if (nums.length < 2) continue;
135748
+ const [ox2, oy2, blur = 0, spread = 0] = nums;
135749
+ const extX = Math.abs(ox2) + blur + spread;
135750
+ const extY = Math.abs(oy2) + blur + spread;
135751
+ r = Math.max(r, extX + Math.max(ox2, 0));
135752
+ l = Math.max(l, extX + Math.max(-ox2, 0));
135753
+ b2 = Math.max(b2, extY + Math.max(oy2, 0));
135754
+ t = Math.max(t, extY + Math.max(-oy2, 0));
135755
+ }
135756
+ return { top: Math.ceil(t), right: Math.ceil(r), bottom: Math.ceil(b2), left: Math.ceil(l) };
135757
+ }
135758
+ function parseFilterBlur(cs) {
135759
+ const m = (cs.filter || "").match(/blur\(\s*([0-9.]+)px\s*\)/);
135760
+ const b2 = m ? Math.ceil(parseFloat(m[1]) || 0) : 0;
135761
+ return { top: b2, right: b2, bottom: b2, left: b2 };
135762
+ }
135763
+ function parseOutline(cs) {
135764
+ if ((cs.outlineStyle || "none") === "none") return { top: 0, right: 0, bottom: 0, left: 0 };
135765
+ const w2 = Math.ceil(parseFloat(cs.outlineWidth || "0") || 0);
135766
+ return { top: w2, right: w2, bottom: w2, left: w2 };
135767
+ }
135768
+ function bboxWithOriginFull(w2, h2, M, ox2, oy2) {
135769
+ const a2 = M.a, b2 = M.b, c2 = M.c, d2 = M.d, e2 = M.e || 0, f2 = M.f || 0;
135770
+ function pt(x, y) {
135771
+ let X = x - ox2, Y = y - oy2;
135772
+ let X2 = a2 * X + c2 * Y, Y2 = b2 * X + d2 * Y;
135773
+ X2 += ox2 + e2;
135774
+ Y2 += oy2 + f2;
135775
+ return [X2, Y2];
135776
+ }
135777
+ const P = [pt(0, 0), pt(w2, 0), pt(0, h2), pt(w2, h2)];
135778
+ let minX2 = Infinity, minY2 = Infinity, maxX2 = -Infinity, maxY2 = -Infinity;
135779
+ for (const [X, Y] of P) {
135780
+ if (X < minX2) minX2 = X;
135781
+ if (Y < minY2) minY2 = Y;
135782
+ if (X > maxX2) maxX2 = X;
135783
+ if (Y > maxY2) maxY2 = Y;
135784
+ }
135785
+ return { minX: minX2, minY: minY2, maxX: maxX2, maxY: maxY2, width: maxX2 - minX2, height: maxY2 - minY2 };
135786
+ }
135787
+ function hasTFBBox(el) {
135788
+ return hasBBoxAffectingTransform(el);
135789
+ }
135790
+ function matrixFromComputed(el) {
135791
+ const tr = getComputedStyle(el).transform;
135792
+ if (!tr || tr === "none") return new DOMMatrix();
135793
+ try {
135794
+ return new DOMMatrix(tr);
135795
+ } catch {
135796
+ return new WebKitCSSMatrix(tr);
135797
+ }
135798
+ }
135799
+ function readIndividualTransforms(el) {
135800
+ const out = { rotate: "0deg", scale: null, translate: null };
135801
+ const map = typeof el.computedStyleMap === "function" ? el.computedStyleMap() : null;
135802
+ if (map) {
135803
+ const safeGet = (prop) => {
135804
+ try {
135805
+ if (typeof map.has === "function" && !map.has(prop)) return null;
135806
+ if (typeof map.get !== "function") return null;
135807
+ return map.get(prop);
135808
+ } catch {
135809
+ return null;
135810
+ }
135811
+ };
135812
+ const rot = safeGet("rotate");
135813
+ if (rot) {
135814
+ if (rot.angle) {
135815
+ const ang = rot.angle;
135816
+ out.rotate = ang.unit === "rad" ? ang.value * 180 / Math.PI + "deg" : ang.value + ang.unit;
135817
+ } else if (rot.unit) {
135818
+ out.rotate = rot.unit === "rad" ? rot.value * 180 / Math.PI + "deg" : rot.value + rot.unit;
135819
+ } else {
135820
+ out.rotate = String(rot);
135821
+ }
135822
+ } else {
135823
+ const cs2 = getComputedStyle(el);
135824
+ out.rotate = cs2.rotate && cs2.rotate !== "none" ? cs2.rotate : "0deg";
135825
+ }
135826
+ const sc = safeGet("scale");
135827
+ if (sc) {
135828
+ const sx = "x" in sc && sc.x?.value != null ? sc.x.value : Array.isArray(sc) ? sc[0]?.value : Number(sc) || 1;
135829
+ const sy = "y" in sc && sc.y?.value != null ? sc.y.value : Array.isArray(sc) ? sc[1]?.value : sx;
135830
+ out.scale = `${sx} ${sy}`;
135831
+ } else {
135832
+ const cs2 = getComputedStyle(el);
135833
+ out.scale = cs2.scale && cs2.scale !== "none" ? cs2.scale : null;
135834
+ }
135835
+ const tr = safeGet("translate");
135836
+ if (tr) {
135837
+ const tx = "x" in tr && "value" in tr.x ? tr.x.value : Array.isArray(tr) ? tr[0]?.value : 0;
135838
+ const ty = "y" in tr && "value" in tr.y ? tr.y.value : Array.isArray(tr) ? tr[1]?.value : 0;
135839
+ const ux = "x" in tr && tr.x?.unit ? tr.x.unit : "px";
135840
+ const uy = "y" in tr && tr.y?.unit ? tr.y.unit : "px";
135841
+ out.translate = `${tx}${ux} ${ty}${uy}`;
135842
+ } else {
135843
+ const cs2 = getComputedStyle(el);
135844
+ out.translate = cs2.translate && cs2.translate !== "none" ? cs2.translate : null;
135845
+ }
135846
+ return out;
135847
+ }
135848
+ const cs = getComputedStyle(el);
135849
+ out.rotate = cs.rotate && cs.rotate !== "none" ? cs.rotate : "0deg";
135850
+ out.scale = cs.scale && cs.scale !== "none" ? cs.scale : null;
135851
+ out.translate = cs.translate && cs.translate !== "none" ? cs.translate : null;
135852
+ return out;
135853
+ }
135854
+ function hasBBoxAffectingTransform(el) {
135855
+ const cs = getComputedStyle(el);
135856
+ const t = cs.transform || "none";
135857
+ const hasMatrix = t !== "none" && !/^matrix\(\s*1\s*,\s*0\s*,\s*0\s*,\s*1\s*,\s*0\s*,\s*0\s*\)$/i.test(t);
135858
+ if (hasMatrix) return true;
135859
+ const r = cs.rotate && cs.rotate !== "none" && cs.rotate !== "0deg";
135860
+ const s = cs.scale && cs.scale !== "none" && cs.scale !== "1";
135861
+ const tr = cs.translate && cs.translate !== "none" && cs.translate !== "0px 0px";
135862
+ return Boolean(r || s || tr);
135863
+ }
135864
+ function parseTransformOriginPx(cs, w, h) {
135865
+ const raw = (cs.transformOrigin || "0 0").trim().split(/\s+/);
135866
+ const [oxRaw, oyRaw] = [raw[0] || "0", raw[1] || "0"];
135867
+ const toPx = (token, size) => {
135868
+ const t = token.toLowerCase();
135869
+ if (t === "left" || t === "top") return 0;
135870
+ if (t === "center") return size / 2;
135871
+ if (t === "right") return size;
135872
+ if (t === "bottom") return size;
135873
+ if (t.endsWith("px")) return parseFloat(t) || 0;
135874
+ if (t.endsWith("%")) return (parseFloat(t) || 0) * size / 100;
135875
+ if (/^-?\d+(\.\d+)?$/.test(t)) return parseFloat(t) || 0;
135876
+ return 0;
135877
+ };
135878
+ return {
135879
+ ox: toPx(oxRaw, w),
135880
+ oy: toPx(oyRaw, h)
135881
+ };
135882
+ }
135883
+ var __measureHost = null;
135884
+ function getMeasureHost() {
135885
+ if (__measureHost) return __measureHost;
135886
+ const n = document.createElement("div");
135887
+ n.id = "snapdom-measure-slot";
135888
+ n.setAttribute("aria-hidden", "true");
135889
+ Object.assign(n.style, {
135890
+ position: "absolute",
135891
+ left: "-99999px",
135892
+ top: "0px",
135893
+ width: "0px",
135894
+ height: "0px",
135895
+ overflow: "hidden",
135896
+ opacity: "0",
135897
+ pointerEvents: "none",
135898
+ contain: "size layout style"
135899
+ });
135900
+ document.documentElement.appendChild(n);
135901
+ __measureHost = n;
135902
+ return n;
135903
+ }
135904
+ function readTotalTransformMatrix(t) {
135905
+ const host = getMeasureHost();
135906
+ const tmp = document.createElement("div");
135907
+ tmp.style.transformOrigin = "0 0";
135908
+ if (t.baseTransform) tmp.style.transform = t.baseTransform;
135909
+ if (t.rotate) tmp.style.rotate = t.rotate;
135910
+ if (t.scale) tmp.style.scale = t.scale;
135911
+ if (t.translate) tmp.style.translate = t.translate;
135912
+ host.appendChild(tmp);
135913
+ const M = matrixFromComputed(tmp);
135914
+ host.removeChild(tmp);
135915
+ return M;
135916
+ }
135917
+
135918
+ // src/core/context.js
135919
+ function normalizeCachePolicy(v) {
135920
+ if (typeof v === "string") {
135921
+ const s = v.toLowerCase().trim();
135922
+ if (s === "disabled" || s === "full" || s === "auto" || s === "soft") return (
135923
+ /** @type {CachePolicy} */
135924
+ s
135925
+ );
135926
+ }
135927
+ return "soft";
135928
+ }
135929
+ function createContext(options = {}) {
135930
+ const resolvedFormat = options.format ?? "png";
135931
+ const cachePolicy = normalizeCachePolicy(options.cache);
135932
+ return {
135933
+ // Debug & perf
135934
+ debug: options.debug ?? false,
135935
+ fast: options.fast ?? true,
135936
+ scale: options.scale ?? 1,
135937
+ // DOM filters
135938
+ exclude: options.exclude ?? [],
135939
+ excludeMode: options.excludeMode ?? "hide",
135940
+ filter: options.filter ?? null,
135941
+ filterMode: options.filterMode ?? "hide",
135942
+ // Placeholders
135943
+ placeholders: options.placeholders !== false,
135944
+ // default true
135945
+ // Fonts
135946
+ embedFonts: options.embedFonts ?? false,
135947
+ iconFonts: Array.isArray(options.iconFonts) ? options.iconFonts : options.iconFonts ? [options.iconFonts] : [],
135948
+ localFonts: Array.isArray(options.localFonts) ? options.localFonts : [],
135949
+ excludeFonts: options.excludeFonts ?? void 0,
135950
+ fallbackURL: options.fallbackURL ?? void 0,
135951
+ /** @type {CachePolicy} */
135952
+ cache: cachePolicy,
135953
+ // Network
135954
+ useProxy: typeof options.useProxy === "string" ? options.useProxy : "",
135955
+ // Output
135956
+ width: options.width ?? null,
135957
+ height: options.height ?? null,
135958
+ format: resolvedFormat,
135959
+ type: options.type ?? "svg",
135960
+ quality: options.quality ?? 0.92,
135961
+ dpr: options.dpr ?? (window.devicePixelRatio || 1),
135962
+ backgroundColor: options.backgroundColor ?? (["jpg", "jpeg", "webp"].includes(resolvedFormat) ? "#ffffff" : null),
135963
+ filename: options.filename ?? "snapDOM",
135964
+ // NEW flags (user-friendly)
135965
+ straighten: options.straighten ?? false,
135966
+ noShadows: options.noShadows ?? false
135967
+ // Plugins (reservado)
135968
+ // plugins: normalizePlugins(...),
135969
+ };
135970
+ }
135971
+
135972
+ // src/exporters/toCanvas.js
135973
+ function isSvgDataURL(u) {
135974
+ return typeof u === "string" && /^data:image\/svg\+xml/i.test(u);
135975
+ }
135976
+ function decodeSvgFromDataURL(u) {
135977
+ const i = u.indexOf(",");
135978
+ return i >= 0 ? decodeURIComponent(u.slice(i + 1)) : "";
135979
+ }
135980
+ function encodeSvgToDataURL(svgText) {
135981
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;
135982
+ }
135983
+ function splitDecls(s) {
135984
+ let parts = [], buf = "", depth = 0;
135985
+ for (let i = 0; i < s.length; i++) {
135986
+ const ch = s[i];
135987
+ if (ch === "(") depth++;
135988
+ if (ch === ")") depth = Math.max(0, depth - 1);
135989
+ if (ch === ";" && depth === 0) {
135990
+ parts.push(buf);
135991
+ buf = "";
135992
+ } else buf += ch;
135993
+ }
135994
+ if (buf.trim()) parts.push(buf);
135995
+ return parts.map((x) => x.trim()).filter(Boolean);
135996
+ }
135997
+ function boxShadowToDropShadow(value) {
135998
+ const layers = [];
135999
+ let buf = "", depth = 0;
136000
+ for (let i = 0; i < value.length; i++) {
136001
+ const ch = value[i];
136002
+ if (ch === "(") depth++;
136003
+ if (ch === ")") depth = Math.max(0, depth - 1);
136004
+ if (ch === "," && depth === 0) {
136005
+ layers.push(buf.trim());
136006
+ buf = "";
136007
+ } else buf += ch;
136008
+ }
136009
+ if (buf.trim()) layers.push(buf.trim());
136010
+ const fns = [];
136011
+ for (const layer of layers) {
136012
+ if (/\binset\b/i.test(layer)) continue;
136013
+ const nums = layer.match(/-?\d+(?:\.\d+)?px/gi) || [];
136014
+ const [ox = "0px", oy = "0px", blur = "0px"] = nums;
136015
+ let color = layer.replace(/-?\d+(?:\.\d+)?px/gi, "").replace(/\binset\b/ig, "").trim().replace(/\s{2,}/g, " ");
136016
+ const hasColor = !!color && color !== ",";
136017
+ fns.push(`drop-shadow(${ox} ${oy} ${blur}${hasColor ? ` ${color}` : ""})`);
136018
+ }
136019
+ return fns.join(" ");
136020
+ }
136021
+ function rewriteDeclList(list) {
136022
+ const decls = splitDecls(list);
136023
+ let filter = null, wfilter = null, box = null;
136024
+ const rest = [];
136025
+ for (const d of decls) {
136026
+ const idx = d.indexOf(":");
136027
+ if (idx < 0) continue;
136028
+ const prop = d.slice(0, idx).trim().toLowerCase();
136029
+ const val = d.slice(idx + 1).trim();
136030
+ if (prop === "box-shadow") box = val;
136031
+ else if (prop === "filter") filter = val;
136032
+ else if (prop === "-webkit-filter") wfilter = val;
136033
+ else rest.push([prop, val]);
136034
+ }
136035
+ if (box) {
136036
+ const ds = boxShadowToDropShadow(box);
136037
+ if (ds) {
136038
+ filter = filter ? `${filter} ${ds}` : ds;
136039
+ wfilter = wfilter ? `${wfilter} ${ds}` : ds;
136040
+ }
136041
+ }
136042
+ const out = [...rest];
136043
+ if (filter) out.push(["filter", filter]);
136044
+ if (wfilter) out.push(["-webkit-filter", wfilter]);
136045
+ return out.map(([k, v]) => `${k}:${v}`).join(";");
136046
+ }
136047
+ function rewriteCssBlock(css) {
136048
+ return css.replace(/([^{}]+)\{([^}]*)\}/g, (_m, sel, body) => `${sel}{${rewriteDeclList(body)}}`);
136049
+ }
136050
+ function rewriteSvgBoxShadowToDropShadow(svgText) {
136051
+ svgText = svgText.replace(
136052
+ /<style[^>]*>([\s\S]*?)<\/style>/gi,
136053
+ (m, css) => m.replace(css, rewriteCssBlock(css))
136054
+ );
136055
+ svgText = svgText.replace(
136056
+ /style=(['"])([\s\S]*?)\1/gi,
136057
+ (m, q, body) => `style=${q}${rewriteDeclList(body)}${q}`
136058
+ );
136059
+ return svgText;
136060
+ }
136061
+ function maybeConvertBoxShadowForSafari(url) {
136062
+ if (!isSafari() || !isSvgDataURL(url)) return url;
136063
+ try {
136064
+ const svg = decodeSvgFromDataURL(url);
136065
+ const fixed = rewriteSvgBoxShadowToDropShadow(svg);
136066
+ return encodeSvgToDataURL(fixed);
136067
+ } catch {
136068
+ return url;
136069
+ }
136070
+ }
136071
+ async function toCanvas(url, options) {
136072
+ let { width: optW, height: optH, scale = 1, dpr = 1, meta = {} } = options;
136073
+ url = maybeConvertBoxShadowForSafari(url);
136074
+ const img = new Image();
136075
+ img.loading = "eager";
136076
+ img.decoding = "sync";
136077
+ img.crossOrigin = "anonymous";
136078
+ img.src = url;
136079
+ await img.decode();
136080
+ const natW = img.naturalWidth;
136081
+ const natH = img.naturalHeight;
136082
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : natW;
136083
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : natH;
136084
+ let outW, outH;
136085
+ const hasW = Number.isFinite(optW);
136086
+ const hasH = Number.isFinite(optH);
136087
+ if (hasW && hasH) {
136088
+ outW = Math.max(1, optW);
136089
+ outH = Math.max(1, optH);
136090
+ } else if (hasW) {
136091
+ const k = optW / Math.max(1, refW);
136092
+ outW = optW;
136093
+ outH = Math.round(refH * k);
136094
+ } else if (hasH) {
136095
+ const k = optH / Math.max(1, refH);
136096
+ outH = optH;
136097
+ outW = Math.round(refW * k);
136098
+ } else {
136099
+ outW = natW;
136100
+ outH = natH;
136101
+ }
136102
+ outW = Math.round(outW * scale);
136103
+ outH = Math.round(outH * scale);
136104
+ const canvas = document.createElement("canvas");
136105
+ canvas.width = Math.ceil(outW * dpr);
136106
+ canvas.height = Math.ceil(outH * dpr);
136107
+ canvas.style.width = `${outW}px`;
136108
+ canvas.style.height = `${outH}px`;
136109
+ const ctx = canvas.getContext("2d");
136110
+ if (dpr !== 1) ctx.scale(dpr, dpr);
136111
+ ctx.drawImage(img, 0, 0, outW, outH);
136112
+ return canvas;
136113
+ }
136114
+
136115
+ // src/modules/rasterize.js
136116
+ async function rasterize(url, options) {
136117
+ const canvas = await toCanvas(url, options);
136118
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136119
+ const img = new Image();
136120
+ img.src = finalCanvas.toDataURL(`image/${options.format}`, options.quality);
136121
+ await img.decode();
136122
+ img.style.width = `${finalCanvas.width / options.dpr}px`;
136123
+ img.style.height = `${finalCanvas.height / options.dpr}px`;
136124
+ return img;
136125
+ }
136126
+
136127
+ // src/exporters/toImg.js
136128
+ async function toImg(url, options) {
136129
+ const { scale = 1, width, height, meta = {} } = options;
136130
+ const hasW = Number.isFinite(width);
136131
+ const hasH = Number.isFinite(height);
136132
+ const wantsScale = Number.isFinite(scale) && scale !== 1 || hasW || hasH;
136133
+ if (isSafari() && wantsScale) {
136134
+ const pngUrl = await rasterize(url, { ...options, format: "png", quality: 1, meta });
136135
+ return pngUrl;
136136
+ }
136137
+ const img = new Image();
136138
+ img.decoding = "sync";
136139
+ img.loading = "eager";
136140
+ img.src = url;
136141
+ await img.decode();
136142
+ if (hasW && hasH) {
136143
+ img.style.width = `${width}px`;
136144
+ img.style.height = `${height}px`;
136145
+ } else if (hasW) {
136146
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : img.naturalWidth;
136147
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : img.naturalHeight;
136148
+ const k = width / Math.max(1, refW);
136149
+ img.style.width = `${width}px`;
136150
+ img.style.height = `${Math.round(refH * k)}px`;
136151
+ } else if (hasH) {
136152
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : img.naturalWidth;
136153
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : img.naturalHeight;
136154
+ const k = height / Math.max(1, refH);
136155
+ img.style.height = `${height}px`;
136156
+ img.style.width = `${Math.round(refW * k)}px`;
136157
+ } else {
136158
+ const cssW = Math.round(img.naturalWidth * scale);
136159
+ const cssH = Math.round(img.naturalHeight * scale);
136160
+ img.style.width = `${cssW}px`;
136161
+ img.style.height = `${cssH}px`;
136162
+ if (typeof url === "string" && url.startsWith("data:image/svg+xml")) {
136163
+ try {
136164
+ const decoded = decodeURIComponent(url.split(",")[1]);
136165
+ const patched = decoded.replace(/width="[^"]*"/, `width="${cssW}"`).replace(/height="[^"]*"/, `height="${cssH}"`);
136166
+ url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(patched)}`;
136167
+ img.src = url;
136168
+ } catch {
136169
+ }
136170
+ }
136171
+ }
136172
+ return img;
136173
+ }
136174
+
136175
+ // src/exporters/toBlob.js
136176
+ async function toBlob(url, options) {
136177
+ const type = options.type;
136178
+ if (type === "svg") {
136179
+ const svgText = decodeURIComponent(url.split(",")[1]);
136180
+ return new Blob([svgText], { type: "image/svg+xml" });
136181
+ }
136182
+ const canvas = await toCanvas(url, options);
136183
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136184
+ return new Promise(
136185
+ (resolve) => finalCanvas.toBlob(
136186
+ (blob) => resolve(blob),
136187
+ `image/${type}`,
136188
+ options.quality
136189
+ )
136190
+ );
136191
+ }
136192
+
136193
+ // src/exporters/download.js
136194
+ async function download(url, options) {
136195
+ options.dpr = 1;
136196
+ if (options.format === "svg") {
136197
+ const blob = await toBlob(url, { ...options, type: "svg" });
136198
+ const objectURL = URL.createObjectURL(blob);
136199
+ const a2 = document.createElement("a");
136200
+ a2.href = objectURL;
136201
+ a2.download = options.filename;
136202
+ a2.click();
136203
+ URL.revokeObjectURL(objectURL);
136204
+ return;
136205
+ }
136206
+ const canvas = await toCanvas(url, options);
136207
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136208
+ const a = document.createElement("a");
136209
+ a.href = finalCanvas.toDataURL(`image/${options.format}`, options.quality);
136210
+ a.download = options.filename;
136211
+ a.click();
136212
+ }
136213
+
136214
+ // src/api/snapdom.js
136215
+ var INTERNAL_TOKEN = Symbol("snapdom.internal");
136216
+ var _safariWarmup = false;
136217
+ async function snapdom(element, userOptions) {
136218
+ if (!element) throw new Error("Element cannot be null or undefined");
136219
+ const context = createContext(userOptions);
136220
+ if (isSafari() && (context.embedFonts === true || hasBackgroundOrMask(element))) {
136221
+ for (let i = 0; i < 3; i++) {
136222
+ try {
136223
+ await safariWarmup(element, userOptions);
136224
+ console.log("Iteraci\xF3n n\xFAmero:", i);
136225
+ _safariWarmup = false;
136226
+ } catch {
136227
+ }
136228
+ }
136229
+ }
136230
+ if (context.iconFonts && context.iconFonts.length > 0) extendIconFonts(context.iconFonts);
136231
+ if (!context.snap) {
136232
+ context.snap = {
136233
+ toPng: (el, opts) => snapdom.toPng(el, opts),
136234
+ toSvg: (el, opts) => snapdom.toSvg(el, opts)
136235
+ };
136236
+ }
136237
+ return snapdom.capture(element, context, INTERNAL_TOKEN);
136238
+ }
136239
+ snapdom.capture = async (el, context, _token) => {
136240
+ if (_token !== INTERNAL_TOKEN) throw new Error("[snapdom.capture] is internal. Use snapdom(...) instead.");
136241
+ const url = await captureDOM(el, context);
136242
+ const ensureContext = (opts) => ({ ...context, ...opts || {} });
136243
+ const withFormat = (format) => (opts) => {
136244
+ const next = ensureContext({ ...opts || {}, format });
136245
+ const wantsJpeg = format === "jpeg" || format === "jpg";
136246
+ const noBg = next.backgroundColor == null || next.backgroundColor === "transparent";
136247
+ if (wantsJpeg && noBg) {
136248
+ next.backgroundColor = "#ffffff";
136249
+ }
136250
+ return rasterize(url, next);
136251
+ };
136252
+ return {
136253
+ url,
136254
+ toRaw: () => url,
136255
+ toImg: (opts) => toImg(url, ensureContext(opts)),
136256
+ toSvg: (opts) => toImg(url, ensureContext(opts)),
136257
+ toCanvas: (opts) => toCanvas(url, ensureContext(opts)),
136258
+ toBlob: (opts) => toBlob(url, ensureContext(opts)),
136259
+ toPng: withFormat("png"),
136260
+ toJpg: withFormat("jpeg"),
136261
+ toWebp: withFormat("webp"),
136262
+ download: (opts) => download(url, ensureContext(opts))
136263
+ };
136264
+ };
136265
+ snapdom.toRaw = (el, options) => snapdom(el, options).then((result) => result.toRaw());
136266
+ snapdom.toImg = (el, options) => snapdom(el, options).then((result) => result.toImg());
136267
+ snapdom.toSvg = (el, options) => snapdom(el, options).then((result) => result.toSvg());
136268
+ snapdom.toCanvas = (el, options) => snapdom(el, options).then((result) => result.toCanvas());
136269
+ snapdom.toBlob = (el, options) => snapdom(el, options).then((result) => result.toBlob());
136270
+ snapdom.toPng = (el, options) => snapdom(el, { ...options, format: "png" }).then((result) => result.toPng());
136271
+ snapdom.toJpg = (el, options) => snapdom(el, { ...options, format: "jpeg" }).then((result) => result.toJpg());
136272
+ snapdom.toWebp = (el, options) => snapdom(el, { ...options, format: "webp" }).then((result) => result.toWebp());
136273
+ snapdom.download = (el, options) => snapdom(el, options).then((result) => result.download());
136274
+ async function safariWarmup(element, baseOptions) {
136275
+ if (_safariWarmup) return;
136276
+ const preflight = {
136277
+ ...baseOptions,
136278
+ fast: true,
136279
+ embedFonts: true,
136280
+ scale: 0.2
136281
+ };
136282
+ let url;
136283
+ try {
136284
+ url = await captureDOM(element, preflight);
136285
+ } catch {
136286
+ return;
136287
+ }
136288
+ await new Promise((resolve) => {
136289
+ const img = new Image();
136290
+ img.decoding = "sync";
136291
+ img.loading = "eager";
136292
+ img.style.position = "fixed";
136293
+ img.style.left = 0;
136294
+ img.style.top = 0;
136295
+ img.style.width = "10px";
136296
+ img.style.height = "10px";
136297
+ img.style.opacity = "0.01";
136298
+ img.style.transform = "translateZ(10px)";
136299
+ img.style.willChange = "transform,opacity;";
136300
+ img.src = url;
136301
+ const cleanup = async () => {
136302
+ await new Promise((r) => setTimeout(r, 100));
136303
+ if (img && img.parentNode) img.parentNode.removeChild(img);
136304
+ _safariWarmup = true;
136305
+ resolve();
136306
+ };
136307
+ document.body.appendChild(img);
136308
+ cleanup();
136309
+ });
136310
+ }
136311
+ function hasBackgroundOrMask(el) {
136312
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT);
136313
+ while (walker.nextNode()) {
136314
+ const node = (
136315
+ /** @type {Element} */
136316
+ walker.currentNode
136317
+ );
136318
+ const cs = getComputedStyle(node);
136319
+ const bg = cs.backgroundImage && cs.backgroundImage !== "none";
136320
+ const mask = cs.maskImage && cs.maskImage !== "none" || cs.webkitMaskImage && cs.webkitMaskImage !== "none";
136321
+ if (bg || mask) return true;
136322
+ }
136323
+ return false;
136324
+ }
136325
+
136326
+ // src/api/preCache.js
136327
+ async function preCache(root = document, options = {}) {
136328
+ const {
136329
+ embedFonts = true,
136330
+ useProxy = ""
136331
+ } = options;
136332
+ const cacheMode = options.cache ?? options.cacheOpt ?? "full";
136333
+ applyCachePolicy(cacheMode);
136334
+ try {
136335
+ await document.fonts?.ready;
136336
+ } catch {
136337
+ }
136338
+ try {
136339
+ precacheCommonTags();
136340
+ } catch {
136341
+ }
136342
+ cache.session = cache.session || {};
136343
+ if (!cache.session.styleCache) {
136344
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
136345
+ }
136346
+ cache.image = cache.image || /* @__PURE__ */ new Map();
136347
+ try {
136348
+ await inlineBackgroundImages(
136349
+ root,
136350
+ /* mirror */
136351
+ void 0,
136352
+ cache.session.styleCache,
136353
+ { useProxy }
136354
+ );
136355
+ } catch {
136356
+ }
136357
+ let imgEls = [], allEls = [];
136358
+ try {
136359
+ if (root?.querySelectorAll) {
136360
+ imgEls = Array.from(root.querySelectorAll("img[src]"));
136361
+ allEls = Array.from(root.querySelectorAll("*"));
136362
+ }
136363
+ } catch {
136364
+ }
136365
+ const promises = [];
136366
+ for (const img of imgEls) {
136367
+ const src = img?.currentSrc || img?.src;
136368
+ if (!src) continue;
136369
+ if (!cache.image.has(src)) {
136370
+ const p = Promise.resolve().then(async () => {
136371
+ const res = await snapFetch(src, { as: "dataURL", useProxy });
136372
+ if (res?.ok && typeof res.data === "string") {
136373
+ cache.image.set(src, res.data);
136374
+ }
136375
+ }).catch(() => {
136376
+ });
136377
+ promises.push(p);
136378
+ }
136379
+ }
136380
+ for (const el of allEls) {
136381
+ let bg = "";
136382
+ try {
136383
+ bg = getStyle(el).backgroundImage;
136384
+ } catch {
136385
+ }
136386
+ if (bg && bg !== "none") {
136387
+ const parts = splitBackgroundImage(bg);
136388
+ for (const entry of parts) {
136389
+ if (entry.startsWith("url(")) {
136390
+ const p = Promise.resolve().then(() => inlineSingleBackgroundEntry(entry, { ...options, useProxy })).catch(() => {
136391
+ });
136392
+ promises.push(p);
136393
+ }
136394
+ }
136395
+ }
136396
+ }
136397
+ if (embedFonts) {
136398
+ try {
136399
+ const required = collectUsedFontVariants(root);
136400
+ const usedCodepoints = collectUsedCodepoints(root);
136401
+ const safari = typeof isSafari === "function" ? isSafari() : !!isSafari;
136402
+ if (safari) {
136403
+ const families = new Set(
136404
+ Array.from(required).map((k) => String(k).split("__")[0]).filter(Boolean)
136405
+ );
136406
+ await ensureFontsReady(families, 3);
136407
+ }
136408
+ await embedCustomFonts({
136409
+ required,
136410
+ usedCodepoints,
136411
+ exclude: options.excludeFonts,
136412
+ localFonts: options.localFonts,
136413
+ useProxy: options.useProxy ?? useProxy
136414
+ });
136415
+ } catch {
136416
+ }
136417
+ }
136418
+ await Promise.allSettled(promises);
136419
+ }
136420
+
136421
+ const snapdom$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
136422
+ __proto__: null,
136423
+ preCache,
136424
+ snapdom
136425
+ }, Symbol.toStringTag, { value: 'Module' }));
136426
+
132210
136427
  exports.ActionSheet = ActionSheet;
132211
136428
  exports.Affix = Affix;
132212
136429
  exports.Alert = Alert;
@@ -132241,7 +136458,6 @@
132241
136458
  exports.Form = Form;
132242
136459
  exports.FormItem = FormItem;
132243
136460
  exports.Fragment = Fragment;
132244
- exports.HTMLToImage = HTMLToImage;
132245
136461
  exports.Icon = Icon;
132246
136462
  exports.IconManager = IconManager;
132247
136463
  exports.Image = Image$1$1;
@@ -132286,7 +136502,6 @@
132286
136502
  exports.MForm = MForm;
132287
136503
  exports.MFormItem = MFormItem;
132288
136504
  exports.MFragment = MFragment;
132289
- exports.MHTMLToImage = MHTMLToImage;
132290
136505
  exports.MIcon = MIcon;
132291
136506
  exports.MImage = MImage;
132292
136507
  exports.MImageCrop = MImageCrop;
@@ -132320,6 +136535,7 @@
132320
136535
  exports.MScroller = MScroller;
132321
136536
  exports.MSelect = MSelect;
132322
136537
  exports.MSlider = MSlider;
136538
+ exports.MSnapshot = MSnapshot;
132323
136539
  exports.MSortList = MSortList;
132324
136540
  exports.MSpin = MSpin;
132325
136541
  exports.MSteps = MSteps;
@@ -132373,6 +136589,7 @@
132373
136589
  exports.ScrollerWheel = ScrollerWheel;
132374
136590
  exports.Select = Select;
132375
136591
  exports.Slider = Slider;
136592
+ exports.Snapshot = Snapshot;
132376
136593
  exports.SortList = SortList;
132377
136594
  exports.Spin = Spin;
132378
136595
  exports.Steps = Steps;