@mediansh/widget 0.7.0 → 0.9.0

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.
@@ -0,0 +1,1658 @@
1
+ "use client";
2
+ import "./chunk-77KIJLPP.js";
3
+
4
+ // ../../node_modules/.bun/modern-screenshot@4.7.0/node_modules/modern-screenshot/dist/index.mjs
5
+ function changeJpegDpi(uint8Array, dpi) {
6
+ uint8Array[13] = 1;
7
+ uint8Array[14] = dpi >> 8;
8
+ uint8Array[15] = dpi & 255;
9
+ uint8Array[16] = dpi >> 8;
10
+ uint8Array[17] = dpi & 255;
11
+ return uint8Array;
12
+ }
13
+ var _P = "p".charCodeAt(0);
14
+ var _H = "H".charCodeAt(0);
15
+ var _Y = "Y".charCodeAt(0);
16
+ var _S = "s".charCodeAt(0);
17
+ var pngDataTable;
18
+ function createPngDataTable() {
19
+ const crcTable = new Int32Array(256);
20
+ for (let n = 0; n < 256; n++) {
21
+ let c = n;
22
+ for (let k = 0; k < 8; k++) {
23
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
24
+ }
25
+ crcTable[n] = c;
26
+ }
27
+ return crcTable;
28
+ }
29
+ function calcCrc(uint8Array) {
30
+ let c = -1;
31
+ if (!pngDataTable)
32
+ pngDataTable = createPngDataTable();
33
+ for (let n = 0; n < uint8Array.length; n++) {
34
+ c = pngDataTable[(c ^ uint8Array[n]) & 255] ^ c >>> 8;
35
+ }
36
+ return c ^ -1;
37
+ }
38
+ function searchStartOfPhys(uint8Array) {
39
+ const length = uint8Array.length - 1;
40
+ for (let i = length; i >= 4; i--) {
41
+ if (uint8Array[i - 4] === 9 && uint8Array[i - 3] === _P && uint8Array[i - 2] === _H && uint8Array[i - 1] === _Y && uint8Array[i] === _S) {
42
+ return i - 3;
43
+ }
44
+ }
45
+ return 0;
46
+ }
47
+ function changePngDpi(uint8Array, dpi, overwritepHYs = false) {
48
+ const physChunk = new Uint8Array(13);
49
+ dpi *= 39.3701;
50
+ physChunk[0] = _P;
51
+ physChunk[1] = _H;
52
+ physChunk[2] = _Y;
53
+ physChunk[3] = _S;
54
+ physChunk[4] = dpi >>> 24;
55
+ physChunk[5] = dpi >>> 16;
56
+ physChunk[6] = dpi >>> 8;
57
+ physChunk[7] = dpi & 255;
58
+ physChunk[8] = physChunk[4];
59
+ physChunk[9] = physChunk[5];
60
+ physChunk[10] = physChunk[6];
61
+ physChunk[11] = physChunk[7];
62
+ physChunk[12] = 1;
63
+ const crc = calcCrc(physChunk);
64
+ const crcChunk = new Uint8Array(4);
65
+ crcChunk[0] = crc >>> 24;
66
+ crcChunk[1] = crc >>> 16;
67
+ crcChunk[2] = crc >>> 8;
68
+ crcChunk[3] = crc & 255;
69
+ if (overwritepHYs) {
70
+ const startingIndex = searchStartOfPhys(uint8Array);
71
+ uint8Array.set(physChunk, startingIndex);
72
+ uint8Array.set(crcChunk, startingIndex + 13);
73
+ return uint8Array;
74
+ } else {
75
+ const chunkLength = new Uint8Array(4);
76
+ chunkLength[0] = 0;
77
+ chunkLength[1] = 0;
78
+ chunkLength[2] = 0;
79
+ chunkLength[3] = 9;
80
+ const finalHeader = new Uint8Array(54);
81
+ finalHeader.set(uint8Array, 0);
82
+ finalHeader.set(chunkLength, 33);
83
+ finalHeader.set(physChunk, 37);
84
+ finalHeader.set(crcChunk, 50);
85
+ return finalHeader;
86
+ }
87
+ }
88
+ var b64PhysSignature1 = "AAlwSFlz";
89
+ var b64PhysSignature2 = "AAAJcEhZ";
90
+ var b64PhysSignature3 = "AAAACXBI";
91
+ function detectPhysChunkFromDataUrl(dataUrl) {
92
+ let b64index = dataUrl.indexOf(b64PhysSignature1);
93
+ if (b64index === -1) {
94
+ b64index = dataUrl.indexOf(b64PhysSignature2);
95
+ }
96
+ if (b64index === -1) {
97
+ b64index = dataUrl.indexOf(b64PhysSignature3);
98
+ }
99
+ return b64index;
100
+ }
101
+ var PREFIX = "[modern-screenshot]";
102
+ var IN_BROWSER = typeof window !== "undefined";
103
+ var SUPPORT_WEB_WORKER = IN_BROWSER && "Worker" in window;
104
+ var SUPPORT_ATOB = IN_BROWSER && "atob" in window;
105
+ var SUPPORT_BTOA = IN_BROWSER && "btoa" in window;
106
+ var USER_AGENT = IN_BROWSER ? window.navigator?.userAgent : "";
107
+ var IN_CHROME = USER_AGENT.includes("Chrome");
108
+ var IN_SAFARI = USER_AGENT.includes("AppleWebKit") && !IN_CHROME;
109
+ var IN_FIREFOX = USER_AGENT.includes("Firefox");
110
+ var isContext = (value) => value && "__CONTEXT__" in value;
111
+ var isCssFontFaceRule = (rule) => rule.constructor.name === "CSSFontFaceRule";
112
+ var isCSSImportRule = (rule) => rule.constructor.name === "CSSImportRule";
113
+ var isLayerBlockRule = (rule) => rule.constructor.name === "CSSLayerBlockRule";
114
+ var isElementNode = (node) => node.nodeType === 1;
115
+ var isSVGElementNode = (node) => typeof node.className === "object";
116
+ var isSVGImageElementNode = (node) => node.tagName === "image";
117
+ var isSVGUseElementNode = (node) => node.tagName === "use";
118
+ var isHTMLElementNode = (node) => isElementNode(node) && typeof node.style !== "undefined" && !isSVGElementNode(node);
119
+ var isCommentNode = (node) => node.nodeType === 8;
120
+ var isTextNode = (node) => node.nodeType === 3;
121
+ var isImageElement = (node) => node.tagName === "IMG";
122
+ var isVideoElement = (node) => node.tagName === "VIDEO";
123
+ var isCanvasElement = (node) => node.tagName === "CANVAS";
124
+ var isTextareaElement = (node) => node.tagName === "TEXTAREA";
125
+ var isInputElement = (node) => node.tagName === "INPUT";
126
+ var isStyleElement = (node) => node.tagName === "STYLE";
127
+ var isScriptElement = (node) => node.tagName === "SCRIPT";
128
+ var isSelectElement = (node) => node.tagName === "SELECT";
129
+ var isSlotElement = (node) => node.tagName === "SLOT";
130
+ var isIFrameElement = (node) => node.tagName === "IFRAME";
131
+ var consoleWarn = (...args) => console.warn(PREFIX, ...args);
132
+ function supportWebp(ownerDocument) {
133
+ const canvas = ownerDocument?.createElement?.("canvas");
134
+ if (canvas) {
135
+ canvas.height = canvas.width = 1;
136
+ }
137
+ return Boolean(canvas) && "toDataURL" in canvas && Boolean(canvas.toDataURL("image/webp").includes("image/webp"));
138
+ }
139
+ var isDataUrl = (url) => url.startsWith("data:");
140
+ function resolveUrl(url, baseUrl) {
141
+ if (url.match(/^[a-z]+:\/\//i))
142
+ return url;
143
+ if (IN_BROWSER && url.match(/^\/\//))
144
+ return window.location.protocol + url;
145
+ if (url.match(/^[a-z]+:/i))
146
+ return url;
147
+ if (!IN_BROWSER)
148
+ return url;
149
+ const doc = getDocument().implementation.createHTMLDocument();
150
+ const base = doc.createElement("base");
151
+ const a = doc.createElement("a");
152
+ doc.head.appendChild(base);
153
+ doc.body.appendChild(a);
154
+ if (baseUrl)
155
+ base.href = baseUrl;
156
+ a.href = url;
157
+ return a.href;
158
+ }
159
+ function getDocument(target) {
160
+ return (target && isElementNode(target) ? target?.ownerDocument : target) ?? window.document;
161
+ }
162
+ var XMLNS = "http://www.w3.org/2000/svg";
163
+ function createSvg(width, height, ownerDocument) {
164
+ const svg = getDocument(ownerDocument).createElementNS(XMLNS, "svg");
165
+ svg.setAttributeNS(null, "width", width.toString());
166
+ svg.setAttributeNS(null, "height", height.toString());
167
+ svg.setAttributeNS(null, "viewBox", `0 0 ${width} ${height}`);
168
+ return svg;
169
+ }
170
+ function svgToDataUrl(svg, removeControlCharacter) {
171
+ let xhtml = new XMLSerializer().serializeToString(svg);
172
+ if (removeControlCharacter) {
173
+ xhtml = xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu, "");
174
+ }
175
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`;
176
+ }
177
+ async function canvasToBlob(canvas, type = "image/png", quality = 1) {
178
+ try {
179
+ return await new Promise((resolve, reject) => {
180
+ canvas.toBlob((blob) => {
181
+ if (blob) {
182
+ resolve(blob);
183
+ } else {
184
+ reject(new Error("Blob is null"));
185
+ }
186
+ }, type, quality);
187
+ });
188
+ } catch (error) {
189
+ if (SUPPORT_ATOB) {
190
+ return dataUrlToBlob(canvas.toDataURL(type, quality));
191
+ }
192
+ throw error;
193
+ }
194
+ }
195
+ function dataUrlToBlob(dataUrl) {
196
+ const [header, base64] = dataUrl.split(",");
197
+ const type = header.match(/data:(.+);/)?.[1] ?? void 0;
198
+ const decoded = window.atob(base64);
199
+ const length = decoded.length;
200
+ const buffer = new Uint8Array(length);
201
+ for (let i = 0; i < length; i += 1) {
202
+ buffer[i] = decoded.charCodeAt(i);
203
+ }
204
+ return new Blob([buffer], { type });
205
+ }
206
+ function readBlob(blob, type) {
207
+ return new Promise((resolve, reject) => {
208
+ const reader = new FileReader();
209
+ reader.onload = () => resolve(reader.result);
210
+ reader.onerror = () => reject(reader.error);
211
+ reader.onabort = () => reject(new Error(`Failed read blob to ${type}`));
212
+ if (type === "dataUrl") {
213
+ reader.readAsDataURL(blob);
214
+ } else if (type === "arrayBuffer") {
215
+ reader.readAsArrayBuffer(blob);
216
+ }
217
+ });
218
+ }
219
+ var blobToDataUrl = (blob) => readBlob(blob, "dataUrl");
220
+ var blobToArrayBuffer = (blob) => readBlob(blob, "arrayBuffer");
221
+ function createImage(url, ownerDocument) {
222
+ const img = getDocument(ownerDocument).createElement("img");
223
+ img.decoding = "sync";
224
+ img.loading = "eager";
225
+ img.src = url;
226
+ return img;
227
+ }
228
+ function loadMedia(media, options) {
229
+ return new Promise((resolve) => {
230
+ const { timeout, ownerDocument, onError: userOnError, onWarn } = options ?? {};
231
+ const node = typeof media === "string" ? createImage(media, getDocument(ownerDocument)) : media;
232
+ let timer = null;
233
+ let removeEventListeners = null;
234
+ function onResolve() {
235
+ resolve(node);
236
+ timer && clearTimeout(timer);
237
+ removeEventListeners?.();
238
+ }
239
+ if (timeout) {
240
+ timer = setTimeout(onResolve, timeout);
241
+ }
242
+ if (isVideoElement(node)) {
243
+ const currentSrc = node.currentSrc || node.src;
244
+ if (!currentSrc) {
245
+ if (node.poster) {
246
+ return loadMedia(node.poster, options).then(resolve);
247
+ }
248
+ return onResolve();
249
+ }
250
+ if (node.readyState >= 2) {
251
+ return onResolve();
252
+ }
253
+ const onLoadeddata = onResolve;
254
+ const onError = (error) => {
255
+ onWarn?.(
256
+ "Failed video load",
257
+ currentSrc,
258
+ error
259
+ );
260
+ userOnError?.(error);
261
+ onResolve();
262
+ };
263
+ removeEventListeners = () => {
264
+ node.removeEventListener("loadeddata", onLoadeddata);
265
+ node.removeEventListener("error", onError);
266
+ };
267
+ node.addEventListener("loadeddata", onLoadeddata, { once: true });
268
+ node.addEventListener("error", onError, { once: true });
269
+ } else {
270
+ const currentSrc = isSVGImageElementNode(node) ? node.href.baseVal : node.currentSrc || node.src;
271
+ if (!currentSrc) {
272
+ return onResolve();
273
+ }
274
+ const onLoad = async () => {
275
+ if (isImageElement(node) && "decode" in node) {
276
+ try {
277
+ await node.decode();
278
+ } catch (error) {
279
+ onWarn?.(
280
+ "Failed to decode image, trying to render anyway",
281
+ node.dataset.originalSrc || currentSrc,
282
+ error
283
+ );
284
+ }
285
+ }
286
+ onResolve();
287
+ };
288
+ const onError = (error) => {
289
+ onWarn?.(
290
+ "Failed image load",
291
+ node.dataset.originalSrc || currentSrc,
292
+ error
293
+ );
294
+ onResolve();
295
+ };
296
+ if (isImageElement(node) && node.complete) {
297
+ return onLoad();
298
+ }
299
+ removeEventListeners = () => {
300
+ node.removeEventListener("load", onLoad);
301
+ node.removeEventListener("error", onError);
302
+ };
303
+ node.addEventListener("load", onLoad, { once: true });
304
+ node.addEventListener("error", onError, { once: true });
305
+ }
306
+ });
307
+ }
308
+ async function waitUntilLoad(node, options) {
309
+ if (isHTMLElementNode(node)) {
310
+ if (isImageElement(node) || isVideoElement(node)) {
311
+ await loadMedia(node, options);
312
+ } else {
313
+ await Promise.all(
314
+ ["img", "video"].flatMap((selectors) => {
315
+ return Array.from(node.querySelectorAll(selectors)).map((el) => loadMedia(el, options));
316
+ })
317
+ );
318
+ }
319
+ }
320
+ }
321
+ var uuid = /* @__PURE__ */ (function uuid2() {
322
+ let counter = 0;
323
+ const random = () => `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4);
324
+ return () => {
325
+ counter += 1;
326
+ return `u${random()}${counter}`;
327
+ };
328
+ })();
329
+ function splitFontFamily(fontFamily) {
330
+ return fontFamily?.split(",").map((val) => val.trim().replace(/"|'/g, "").toLowerCase()).filter(Boolean);
331
+ }
332
+ var uid = 0;
333
+ function createLogger(debug) {
334
+ const prefix = `${PREFIX}[#${uid}]`;
335
+ uid++;
336
+ return {
337
+ // eslint-disable-next-line no-console
338
+ time: (label) => debug && console.time(`${prefix} ${label}`),
339
+ // eslint-disable-next-line no-console
340
+ timeEnd: (label) => debug && console.timeEnd(`${prefix} ${label}`),
341
+ warn: (...args) => debug && consoleWarn(...args)
342
+ };
343
+ }
344
+ function getDefaultRequestInit(bypassingCache) {
345
+ return {
346
+ cache: bypassingCache ? "no-cache" : "force-cache"
347
+ };
348
+ }
349
+ async function orCreateContext(node, options) {
350
+ return isContext(node) ? node : createContext(node, { ...options, autoDestruct: true });
351
+ }
352
+ async function createContext(node, options) {
353
+ const { scale = 1, workerUrl, workerNumber = 1 } = options || {};
354
+ const debug = Boolean(options?.debug);
355
+ const features = options?.features ?? true;
356
+ const ownerDocument = node.ownerDocument ?? (IN_BROWSER ? window.document : void 0);
357
+ const ownerWindow = node.ownerDocument?.defaultView ?? (IN_BROWSER ? window : void 0);
358
+ const requests = /* @__PURE__ */ new Map();
359
+ const context = {
360
+ // Options
361
+ width: 0,
362
+ height: 0,
363
+ quality: 1,
364
+ type: "image/png",
365
+ scale,
366
+ backgroundColor: null,
367
+ style: null,
368
+ filter: null,
369
+ maximumCanvasSize: 0,
370
+ timeout: 3e4,
371
+ progress: null,
372
+ debug,
373
+ fetch: {
374
+ requestInit: getDefaultRequestInit(options?.fetch?.bypassingCache),
375
+ placeholderImage: "data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
376
+ bypassingCache: false,
377
+ ...options?.fetch
378
+ },
379
+ fetchFn: null,
380
+ font: {},
381
+ drawImageInterval: 100,
382
+ workerUrl: null,
383
+ workerNumber,
384
+ onCloneEachNode: null,
385
+ onCloneNode: null,
386
+ onEmbedNode: null,
387
+ onCreateForeignObjectSvg: null,
388
+ includeStyleProperties: null,
389
+ autoDestruct: false,
390
+ ...options,
391
+ // InternalContext
392
+ __CONTEXT__: true,
393
+ log: createLogger(debug),
394
+ node,
395
+ ownerDocument,
396
+ ownerWindow,
397
+ dpi: scale === 1 ? null : 96 * scale,
398
+ svgStyleElement: createStyleElement(ownerDocument),
399
+ svgDefsElement: ownerDocument?.createElementNS(XMLNS, "defs"),
400
+ svgStyles: /* @__PURE__ */ new Map(),
401
+ defaultComputedStyles: /* @__PURE__ */ new Map(),
402
+ workers: [
403
+ ...Array.from({
404
+ length: SUPPORT_WEB_WORKER && workerUrl && workerNumber ? workerNumber : 0
405
+ })
406
+ ].map(() => {
407
+ try {
408
+ const worker = new Worker(workerUrl);
409
+ worker.onmessage = async (event) => {
410
+ const { url, result } = event.data;
411
+ if (result) {
412
+ requests.get(url)?.resolve?.(result);
413
+ } else {
414
+ requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));
415
+ }
416
+ };
417
+ worker.onmessageerror = (event) => {
418
+ const { url } = event.data;
419
+ requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));
420
+ };
421
+ return worker;
422
+ } catch (error) {
423
+ context.log.warn("Failed to new Worker", error);
424
+ return null;
425
+ }
426
+ }).filter(Boolean),
427
+ fontFamilies: /* @__PURE__ */ new Map(),
428
+ fontCssTexts: /* @__PURE__ */ new Map(),
429
+ acceptOfImage: `${[
430
+ supportWebp(ownerDocument) && "image/webp",
431
+ "image/svg+xml",
432
+ "image/*",
433
+ "*/*"
434
+ ].filter(Boolean).join(",")};q=0.8`,
435
+ requests,
436
+ drawImageCount: 0,
437
+ tasks: [],
438
+ features,
439
+ isEnable: (key) => {
440
+ if (key === "restoreScrollPosition") {
441
+ return typeof features === "boolean" ? false : features[key] ?? false;
442
+ }
443
+ if (typeof features === "boolean") {
444
+ return features;
445
+ }
446
+ return features[key] ?? true;
447
+ },
448
+ shadowRoots: []
449
+ };
450
+ context.log.time("wait until load");
451
+ await waitUntilLoad(node, { timeout: context.timeout, onWarn: context.log.warn });
452
+ context.log.timeEnd("wait until load");
453
+ const { width, height } = resolveBoundingBox(node, context);
454
+ context.width = width;
455
+ context.height = height;
456
+ return context;
457
+ }
458
+ function createStyleElement(ownerDocument) {
459
+ if (!ownerDocument)
460
+ return void 0;
461
+ const style = ownerDocument.createElement("style");
462
+ const cssText = style.ownerDocument.createTextNode(`
463
+ .______background-clip--text {
464
+ background-clip: text;
465
+ -webkit-background-clip: text;
466
+ }
467
+ `);
468
+ style.appendChild(cssText);
469
+ return style;
470
+ }
471
+ function resolveBoundingBox(node, context) {
472
+ let { width, height } = context;
473
+ if (isElementNode(node) && (!width || !height)) {
474
+ const box = node.getBoundingClientRect();
475
+ width = width || box.width || Number(node.getAttribute("width")) || 0;
476
+ height = height || box.height || Number(node.getAttribute("height")) || 0;
477
+ }
478
+ return { width, height };
479
+ }
480
+ async function imageToCanvas(image, context) {
481
+ const {
482
+ log,
483
+ timeout,
484
+ drawImageCount,
485
+ drawImageInterval
486
+ } = context;
487
+ log.time("image to canvas");
488
+ const loaded = await loadMedia(image, { timeout, onWarn: context.log.warn });
489
+ const { canvas, context2d } = createCanvas(image.ownerDocument, context);
490
+ const drawImage = () => {
491
+ try {
492
+ context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height);
493
+ } catch (error) {
494
+ context.log.warn("Failed to drawImage", error);
495
+ }
496
+ };
497
+ drawImage();
498
+ if (context.isEnable("fixSvgXmlDecode")) {
499
+ for (let i = 0; i < drawImageCount; i++) {
500
+ await new Promise((resolve) => {
501
+ setTimeout(() => {
502
+ context2d?.clearRect(0, 0, canvas.width, canvas.height);
503
+ drawImage();
504
+ resolve();
505
+ }, i + drawImageInterval);
506
+ });
507
+ }
508
+ }
509
+ context.drawImageCount = 0;
510
+ log.timeEnd("image to canvas");
511
+ return canvas;
512
+ }
513
+ function createCanvas(ownerDocument, context) {
514
+ const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context;
515
+ const canvas = ownerDocument.createElement("canvas");
516
+ canvas.width = Math.floor(width * scale);
517
+ canvas.height = Math.floor(height * scale);
518
+ canvas.style.width = `${width}px`;
519
+ canvas.style.height = `${height}px`;
520
+ if (max) {
521
+ if (canvas.width > max || canvas.height > max) {
522
+ if (canvas.width > max && canvas.height > max) {
523
+ if (canvas.width > canvas.height) {
524
+ canvas.height *= max / canvas.width;
525
+ canvas.width = max;
526
+ } else {
527
+ canvas.width *= max / canvas.height;
528
+ canvas.height = max;
529
+ }
530
+ } else if (canvas.width > max) {
531
+ canvas.height *= max / canvas.width;
532
+ canvas.width = max;
533
+ } else {
534
+ canvas.width *= max / canvas.height;
535
+ canvas.height = max;
536
+ }
537
+ }
538
+ }
539
+ const context2d = canvas.getContext("2d");
540
+ if (context2d && backgroundColor) {
541
+ context2d.fillStyle = backgroundColor;
542
+ context2d.fillRect(0, 0, canvas.width, canvas.height);
543
+ }
544
+ return { canvas, context2d };
545
+ }
546
+ function cloneCanvas(canvas, context) {
547
+ if (canvas.ownerDocument) {
548
+ try {
549
+ const dataURL = canvas.toDataURL();
550
+ if (dataURL !== "data:,") {
551
+ return createImage(dataURL, canvas.ownerDocument);
552
+ }
553
+ } catch (error) {
554
+ context.log.warn("Failed to clone canvas", error);
555
+ }
556
+ }
557
+ const cloned = canvas.cloneNode(false);
558
+ const ctx = canvas.getContext("2d");
559
+ const clonedCtx = cloned.getContext("2d");
560
+ try {
561
+ if (ctx && clonedCtx) {
562
+ clonedCtx.putImageData(
563
+ ctx.getImageData(0, 0, canvas.width, canvas.height),
564
+ 0,
565
+ 0
566
+ );
567
+ }
568
+ return cloned;
569
+ } catch (error) {
570
+ context.log.warn("Failed to clone canvas", error);
571
+ }
572
+ return cloned;
573
+ }
574
+ function cloneIframe(iframe, context) {
575
+ try {
576
+ if (iframe?.contentDocument?.documentElement) {
577
+ return cloneNode(iframe.contentDocument.documentElement, context);
578
+ }
579
+ } catch (error) {
580
+ context.log.warn("Failed to clone iframe", error);
581
+ }
582
+ return iframe.cloneNode(false);
583
+ }
584
+ function cloneImage(image) {
585
+ const cloned = image.cloneNode(false);
586
+ if (image.currentSrc && image.currentSrc !== image.src) {
587
+ cloned.src = image.currentSrc;
588
+ cloned.srcset = "";
589
+ }
590
+ if (cloned.loading === "lazy") {
591
+ cloned.loading = "eager";
592
+ }
593
+ return cloned;
594
+ }
595
+ async function cloneVideo(video, context) {
596
+ if (video.ownerDocument && !video.currentSrc && video.poster) {
597
+ return createImage(video.poster, video.ownerDocument);
598
+ }
599
+ const cloned = video.cloneNode(false);
600
+ cloned.crossOrigin = "anonymous";
601
+ if (video.currentSrc && video.currentSrc !== video.src) {
602
+ cloned.src = video.currentSrc;
603
+ }
604
+ const ownerDocument = cloned.ownerDocument;
605
+ if (ownerDocument) {
606
+ let canPlay = true;
607
+ await loadMedia(cloned, { onError: () => canPlay = false, onWarn: context.log.warn });
608
+ if (!canPlay) {
609
+ if (video.poster) {
610
+ return createImage(video.poster, video.ownerDocument);
611
+ }
612
+ return cloned;
613
+ }
614
+ cloned.currentTime = video.currentTime;
615
+ await new Promise((resolve) => {
616
+ cloned.addEventListener("seeked", resolve, { once: true });
617
+ });
618
+ const canvas = ownerDocument.createElement("canvas");
619
+ canvas.width = video.offsetWidth;
620
+ canvas.height = video.offsetHeight;
621
+ try {
622
+ const ctx = canvas.getContext("2d");
623
+ if (ctx)
624
+ ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height);
625
+ } catch (error) {
626
+ context.log.warn("Failed to clone video", error);
627
+ if (video.poster) {
628
+ return createImage(video.poster, video.ownerDocument);
629
+ }
630
+ return cloned;
631
+ }
632
+ return cloneCanvas(canvas, context);
633
+ }
634
+ return cloned;
635
+ }
636
+ function cloneElement(node, context) {
637
+ if (isCanvasElement(node)) {
638
+ return cloneCanvas(node, context);
639
+ }
640
+ if (isIFrameElement(node)) {
641
+ return cloneIframe(node, context);
642
+ }
643
+ if (isImageElement(node)) {
644
+ return cloneImage(node);
645
+ }
646
+ if (isVideoElement(node)) {
647
+ return cloneVideo(node, context);
648
+ }
649
+ return node.cloneNode(false);
650
+ }
651
+ function getSandBox(context) {
652
+ let sandbox = context.sandbox;
653
+ if (!sandbox) {
654
+ const { ownerDocument } = context;
655
+ try {
656
+ if (ownerDocument) {
657
+ sandbox = ownerDocument.createElement("iframe");
658
+ sandbox.id = `__SANDBOX__${uuid()}`;
659
+ sandbox.width = "0";
660
+ sandbox.height = "0";
661
+ sandbox.style.visibility = "hidden";
662
+ sandbox.style.position = "fixed";
663
+ ownerDocument.body.appendChild(sandbox);
664
+ sandbox.srcdoc = '<!DOCTYPE html><meta charset="UTF-8"><title></title><body>';
665
+ context.sandbox = sandbox;
666
+ }
667
+ } catch (error) {
668
+ context.log.warn("Failed to getSandBox", error);
669
+ }
670
+ }
671
+ return sandbox;
672
+ }
673
+ var ignoredStyles = [
674
+ "width",
675
+ "height",
676
+ "-webkit-text-fill-color"
677
+ ];
678
+ var includedAttributes = [
679
+ "stroke",
680
+ "fill"
681
+ ];
682
+ function getDefaultStyle(node, pseudoElement, context) {
683
+ const { defaultComputedStyles } = context;
684
+ const nodeName = node.nodeName.toLowerCase();
685
+ const isSvgNode = isSVGElementNode(node) && nodeName !== "svg";
686
+ const attributes = isSvgNode ? includedAttributes.map((name) => [name, node.getAttribute(name)]).filter(([, value]) => value !== null) : [];
687
+ const key = [
688
+ isSvgNode && "svg",
689
+ nodeName,
690
+ attributes.map((name, value) => `${name}=${value}`).join(","),
691
+ pseudoElement
692
+ ].filter(Boolean).join(":");
693
+ if (defaultComputedStyles.has(key))
694
+ return defaultComputedStyles.get(key);
695
+ const sandbox = getSandBox(context);
696
+ const sandboxWindow = sandbox?.contentWindow;
697
+ if (!sandboxWindow)
698
+ return /* @__PURE__ */ new Map();
699
+ const sandboxDocument = sandboxWindow?.document;
700
+ let root;
701
+ let el;
702
+ if (isSvgNode) {
703
+ root = sandboxDocument.createElementNS(XMLNS, "svg");
704
+ el = root.ownerDocument.createElementNS(root.namespaceURI, nodeName);
705
+ attributes.forEach(([name, value]) => {
706
+ el.setAttributeNS(null, name, value);
707
+ });
708
+ root.appendChild(el);
709
+ } else {
710
+ root = el = sandboxDocument.createElement(nodeName);
711
+ }
712
+ el.textContent = " ";
713
+ sandboxDocument.body.appendChild(root);
714
+ const computedStyle = sandboxWindow.getComputedStyle(el, pseudoElement);
715
+ const styles = /* @__PURE__ */ new Map();
716
+ for (let len = computedStyle.length, i = 0; i < len; i++) {
717
+ const name = computedStyle.item(i);
718
+ if (ignoredStyles.includes(name))
719
+ continue;
720
+ styles.set(name, computedStyle.getPropertyValue(name));
721
+ }
722
+ sandboxDocument.body.removeChild(root);
723
+ defaultComputedStyles.set(key, styles);
724
+ return styles;
725
+ }
726
+ function getDiffStyle(style, defaultStyle, includeStyleProperties) {
727
+ const diffStyle = /* @__PURE__ */ new Map();
728
+ const prefixs = [];
729
+ const prefixTree = /* @__PURE__ */ new Map();
730
+ if (includeStyleProperties) {
731
+ for (const name of includeStyleProperties) {
732
+ applyTo(name);
733
+ }
734
+ } else {
735
+ for (let len = style.length, i = 0; i < len; i++) {
736
+ const name = style.item(i);
737
+ applyTo(name);
738
+ }
739
+ }
740
+ for (let len = prefixs.length, i = 0; i < len; i++) {
741
+ prefixTree.get(prefixs[i])?.forEach((value, name) => diffStyle.set(name, value));
742
+ }
743
+ function applyTo(name) {
744
+ const value = style.getPropertyValue(name);
745
+ const priority = style.getPropertyPriority(name);
746
+ const subIndex = name.lastIndexOf("-");
747
+ const prefix = subIndex > -1 ? name.substring(0, subIndex) : void 0;
748
+ if (prefix) {
749
+ let map = prefixTree.get(prefix);
750
+ if (!map) {
751
+ map = /* @__PURE__ */ new Map();
752
+ prefixTree.set(prefix, map);
753
+ }
754
+ map.set(name, [value, priority]);
755
+ }
756
+ if (defaultStyle.get(name) === value && !priority)
757
+ return;
758
+ if (prefix) {
759
+ prefixs.push(prefix);
760
+ } else {
761
+ diffStyle.set(name, [value, priority]);
762
+ }
763
+ }
764
+ return diffStyle;
765
+ }
766
+ function copyCssStyles(node, cloned, isRoot, context) {
767
+ const { ownerWindow, includeStyleProperties, currentParentNodeStyle } = context;
768
+ const clonedStyle = cloned.style;
769
+ const computedStyle = ownerWindow.getComputedStyle(node);
770
+ const defaultStyle = getDefaultStyle(node, null, context);
771
+ currentParentNodeStyle?.forEach((_, key) => {
772
+ defaultStyle.delete(key);
773
+ });
774
+ const style = getDiffStyle(computedStyle, defaultStyle, includeStyleProperties);
775
+ style.delete("transition-property");
776
+ style.delete("all");
777
+ style.delete("d");
778
+ style.delete("content");
779
+ if (isRoot) {
780
+ style.delete("position");
781
+ style.delete("margin-top");
782
+ style.delete("margin-right");
783
+ style.delete("margin-bottom");
784
+ style.delete("margin-left");
785
+ style.delete("margin-block-start");
786
+ style.delete("margin-block-end");
787
+ style.delete("margin-inline-start");
788
+ style.delete("margin-inline-end");
789
+ style.set("box-sizing", ["border-box", ""]);
790
+ }
791
+ if (style.get("background-clip")?.[0] === "text") {
792
+ cloned.classList.add("______background-clip--text");
793
+ }
794
+ if (IN_CHROME) {
795
+ if (!style.has("font-kerning"))
796
+ style.set("font-kerning", ["normal", ""]);
797
+ if ((style.get("overflow-x")?.[0] === "hidden" || style.get("overflow-y")?.[0] === "hidden") && style.get("text-overflow")?.[0] === "ellipsis" && node.scrollWidth === node.clientWidth) {
798
+ style.set("text-overflow", ["clip", ""]);
799
+ }
800
+ }
801
+ for (let len = clonedStyle.length, i = 0; i < len; i++) {
802
+ clonedStyle.removeProperty(clonedStyle.item(i));
803
+ }
804
+ style.forEach(([value, priority], name) => {
805
+ clonedStyle.setProperty(name, value, priority);
806
+ });
807
+ return style;
808
+ }
809
+ function copyInputValue(node, cloned) {
810
+ if (isTextareaElement(node) || isInputElement(node) || isSelectElement(node)) {
811
+ cloned.setAttribute("value", node.value);
812
+ }
813
+ }
814
+ var pseudoClasses = [
815
+ "::before",
816
+ "::after"
817
+ // '::placeholder', TODO
818
+ ];
819
+ var scrollbarPseudoClasses = [
820
+ "::-webkit-scrollbar",
821
+ "::-webkit-scrollbar-button",
822
+ // '::-webkit-scrollbar:horizontal', TODO
823
+ "::-webkit-scrollbar-thumb",
824
+ "::-webkit-scrollbar-track",
825
+ "::-webkit-scrollbar-track-piece",
826
+ // '::-webkit-scrollbar:vertical', TODO
827
+ "::-webkit-scrollbar-corner",
828
+ "::-webkit-resizer"
829
+ ];
830
+ function copyPseudoClass(node, cloned, copyScrollbar, context, addWordToFontFamilies) {
831
+ const { ownerWindow, svgStyleElement, svgStyles, currentNodeStyle } = context;
832
+ if (!svgStyleElement || !ownerWindow)
833
+ return;
834
+ function copyBy(pseudoClass) {
835
+ const computedStyle = ownerWindow.getComputedStyle(node, pseudoClass);
836
+ let content = computedStyle.getPropertyValue("content");
837
+ if (!content || content === "none")
838
+ return;
839
+ addWordToFontFamilies?.(content);
840
+ content = content.replace(/(')|(")|(counter\(.+\))/g, "");
841
+ const klasses = [uuid()];
842
+ const defaultStyle = getDefaultStyle(node, pseudoClass, context);
843
+ currentNodeStyle?.forEach((_, key) => {
844
+ defaultStyle.delete(key);
845
+ });
846
+ const style = getDiffStyle(computedStyle, defaultStyle, context.includeStyleProperties);
847
+ style.delete("content");
848
+ style.delete("-webkit-locale");
849
+ if (style.get("background-clip")?.[0] === "text") {
850
+ cloned.classList.add("______background-clip--text");
851
+ }
852
+ const cloneStyle = [
853
+ `content: '${content}';`
854
+ ];
855
+ style.forEach(([value, priority], name) => {
856
+ cloneStyle.push(`${name}: ${value}${priority ? " !important" : ""};`);
857
+ });
858
+ if (cloneStyle.length === 1)
859
+ return;
860
+ try {
861
+ cloned.className = [cloned.className, ...klasses].join(" ");
862
+ } catch (err) {
863
+ context.log.warn("Failed to copyPseudoClass", err);
864
+ return;
865
+ }
866
+ const cssText = cloneStyle.join("\n ");
867
+ let allClasses = svgStyles.get(cssText);
868
+ if (!allClasses) {
869
+ allClasses = [];
870
+ svgStyles.set(cssText, allClasses);
871
+ }
872
+ allClasses.push(`.${klasses[0]}${pseudoClass}`);
873
+ }
874
+ pseudoClasses.forEach(copyBy);
875
+ if (copyScrollbar)
876
+ scrollbarPseudoClasses.forEach(copyBy);
877
+ }
878
+ var excludeParentNodes = /* @__PURE__ */ new Set([
879
+ "symbol"
880
+ // test/fixtures/svg.symbol.html
881
+ ]);
882
+ async function appendChildNode(node, cloned, child, context, addWordToFontFamilies) {
883
+ if (isElementNode(child) && (isStyleElement(child) || isScriptElement(child)))
884
+ return;
885
+ if (context.filter && !context.filter(child))
886
+ return;
887
+ if (excludeParentNodes.has(cloned.nodeName) || excludeParentNodes.has(child.nodeName)) {
888
+ context.currentParentNodeStyle = void 0;
889
+ } else {
890
+ context.currentParentNodeStyle = context.currentNodeStyle;
891
+ }
892
+ const childCloned = await cloneNode(child, context, false, addWordToFontFamilies);
893
+ if (context.isEnable("restoreScrollPosition")) {
894
+ restoreScrollPosition(node, childCloned);
895
+ }
896
+ cloned.appendChild(childCloned);
897
+ }
898
+ async function cloneChildNodes(node, cloned, context, addWordToFontFamilies) {
899
+ let firstChild = node.firstChild;
900
+ if (isElementNode(node)) {
901
+ if (node.shadowRoot) {
902
+ firstChild = node.shadowRoot?.firstChild;
903
+ context.shadowRoots.push(node.shadowRoot);
904
+ }
905
+ }
906
+ for (let child = firstChild; child; child = child.nextSibling) {
907
+ if (isCommentNode(child))
908
+ continue;
909
+ if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === "function") {
910
+ const nodes = child.assignedNodes();
911
+ for (let i = 0; i < nodes.length; i++) {
912
+ await appendChildNode(node, cloned, nodes[i], context, addWordToFontFamilies);
913
+ }
914
+ } else {
915
+ await appendChildNode(node, cloned, child, context, addWordToFontFamilies);
916
+ }
917
+ }
918
+ }
919
+ function restoreScrollPosition(node, chlidCloned) {
920
+ if (!isHTMLElementNode(node) || !isHTMLElementNode(chlidCloned))
921
+ return;
922
+ const { scrollTop, scrollLeft } = node;
923
+ if (!scrollTop && !scrollLeft) {
924
+ return;
925
+ }
926
+ const { transform } = chlidCloned.style;
927
+ const matrix = new DOMMatrix(transform);
928
+ const { a, b, c, d } = matrix;
929
+ matrix.a = 1;
930
+ matrix.b = 0;
931
+ matrix.c = 0;
932
+ matrix.d = 1;
933
+ matrix.translateSelf(-scrollLeft, -scrollTop);
934
+ matrix.a = a;
935
+ matrix.b = b;
936
+ matrix.c = c;
937
+ matrix.d = d;
938
+ chlidCloned.style.transform = matrix.toString();
939
+ }
940
+ function applyCssStyleWithOptions(cloned, context) {
941
+ const { backgroundColor, width, height, style: styles } = context;
942
+ const clonedStyle = cloned.style;
943
+ if (backgroundColor)
944
+ clonedStyle.setProperty("background-color", backgroundColor, "important");
945
+ if (width)
946
+ clonedStyle.setProperty("width", `${width}px`, "important");
947
+ if (height)
948
+ clonedStyle.setProperty("height", `${height}px`, "important");
949
+ if (styles) {
950
+ for (const name in styles) clonedStyle[name] = styles[name];
951
+ }
952
+ }
953
+ var NORMAL_ATTRIBUTE_RE = /^[\w-:]+$/;
954
+ async function cloneNode(node, context, isRoot = false, addWordToFontFamilies) {
955
+ const { ownerDocument, ownerWindow, fontFamilies, onCloneEachNode } = context;
956
+ if (ownerDocument && isTextNode(node)) {
957
+ if (addWordToFontFamilies && /\S/.test(node.data)) {
958
+ addWordToFontFamilies(node.data);
959
+ }
960
+ return ownerDocument.createTextNode(node.data);
961
+ }
962
+ if (ownerDocument && ownerWindow && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
963
+ const cloned2 = await cloneElement(node, context);
964
+ if (context.isEnable("removeAbnormalAttributes")) {
965
+ const names = cloned2.getAttributeNames();
966
+ for (let len = names.length, i = 0; i < len; i++) {
967
+ const name = names[i];
968
+ if (!NORMAL_ATTRIBUTE_RE.test(name)) {
969
+ cloned2.removeAttribute(name);
970
+ }
971
+ }
972
+ }
973
+ const style = context.currentNodeStyle = copyCssStyles(node, cloned2, isRoot, context);
974
+ if (isRoot)
975
+ applyCssStyleWithOptions(cloned2, context);
976
+ let copyScrollbar = false;
977
+ if (context.isEnable("copyScrollbar")) {
978
+ const overflow = [
979
+ style.get("overflow-x")?.[0],
980
+ style.get("overflow-y")?.[0]
981
+ ];
982
+ copyScrollbar = overflow.includes("scroll") || (overflow.includes("auto") || overflow.includes("overlay")) && (node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth);
983
+ }
984
+ const textTransform = style.get("text-transform")?.[0];
985
+ const families = splitFontFamily(style.get("font-family")?.[0]);
986
+ const addWordToFontFamilies2 = families ? (word) => {
987
+ if (textTransform === "uppercase") {
988
+ word = word.toUpperCase();
989
+ } else if (textTransform === "lowercase") {
990
+ word = word.toLowerCase();
991
+ } else if (textTransform === "capitalize") {
992
+ word = word[0].toUpperCase() + word.substring(1);
993
+ }
994
+ families.forEach((family) => {
995
+ let fontFamily = fontFamilies.get(family);
996
+ if (!fontFamily) {
997
+ fontFamilies.set(family, fontFamily = /* @__PURE__ */ new Set());
998
+ }
999
+ word.split("").forEach((text) => fontFamily.add(text));
1000
+ });
1001
+ } : void 0;
1002
+ copyPseudoClass(
1003
+ node,
1004
+ cloned2,
1005
+ copyScrollbar,
1006
+ context,
1007
+ addWordToFontFamilies2
1008
+ );
1009
+ copyInputValue(node, cloned2);
1010
+ if (!isVideoElement(node)) {
1011
+ await cloneChildNodes(
1012
+ node,
1013
+ cloned2,
1014
+ context,
1015
+ addWordToFontFamilies2
1016
+ );
1017
+ }
1018
+ await onCloneEachNode?.(cloned2);
1019
+ return cloned2;
1020
+ }
1021
+ const cloned = node.cloneNode(false);
1022
+ await cloneChildNodes(node, cloned, context);
1023
+ await onCloneEachNode?.(cloned);
1024
+ return cloned;
1025
+ }
1026
+ function destroyContext(context) {
1027
+ context.ownerDocument = void 0;
1028
+ context.ownerWindow = void 0;
1029
+ context.svgStyleElement = void 0;
1030
+ context.svgDefsElement = void 0;
1031
+ context.svgStyles.clear();
1032
+ context.defaultComputedStyles.clear();
1033
+ if (context.sandbox) {
1034
+ try {
1035
+ context.sandbox.remove();
1036
+ } catch (err) {
1037
+ context.log.warn("Failed to destroyContext", err);
1038
+ }
1039
+ context.sandbox = void 0;
1040
+ }
1041
+ context.workers = [];
1042
+ context.fontFamilies.clear();
1043
+ context.fontCssTexts.clear();
1044
+ context.requests.clear();
1045
+ context.tasks = [];
1046
+ context.shadowRoots = [];
1047
+ }
1048
+ function baseFetch(options) {
1049
+ const { url, timeout, responseType, ...requestInit } = options;
1050
+ const controller = new AbortController();
1051
+ const timer = timeout ? setTimeout(() => controller.abort(), timeout) : void 0;
1052
+ return fetch(url, { signal: controller.signal, ...requestInit }).then((response) => {
1053
+ if (!response.ok) {
1054
+ throw new Error("Failed fetch, not 2xx response", { cause: response });
1055
+ }
1056
+ switch (responseType) {
1057
+ case "arrayBuffer":
1058
+ return response.arrayBuffer();
1059
+ case "dataUrl":
1060
+ return response.blob().then(blobToDataUrl);
1061
+ case "text":
1062
+ default:
1063
+ return response.text();
1064
+ }
1065
+ }).finally(() => clearTimeout(timer));
1066
+ }
1067
+ function contextFetch(context, options) {
1068
+ const { url: rawUrl, requestType = "text", responseType = "text", imageDom } = options;
1069
+ let url = rawUrl;
1070
+ const {
1071
+ timeout,
1072
+ acceptOfImage,
1073
+ requests,
1074
+ fetchFn,
1075
+ fetch: {
1076
+ requestInit,
1077
+ bypassingCache,
1078
+ placeholderImage
1079
+ },
1080
+ font,
1081
+ workers,
1082
+ fontFamilies
1083
+ } = context;
1084
+ if (requestType === "image" && (IN_SAFARI || IN_FIREFOX)) {
1085
+ context.drawImageCount++;
1086
+ }
1087
+ let request = requests.get(rawUrl);
1088
+ if (!request) {
1089
+ if (bypassingCache) {
1090
+ if (bypassingCache instanceof RegExp && bypassingCache.test(url)) {
1091
+ url += (/\?/.test(url) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime();
1092
+ }
1093
+ }
1094
+ const canFontMinify = requestType.startsWith("font") && font && font.minify;
1095
+ const fontTexts = /* @__PURE__ */ new Set();
1096
+ if (canFontMinify) {
1097
+ const families = requestType.split(";")[1].split(",");
1098
+ families.forEach((family) => {
1099
+ if (!fontFamilies.has(family))
1100
+ return;
1101
+ fontFamilies.get(family).forEach((text) => fontTexts.add(text));
1102
+ });
1103
+ }
1104
+ const needFontMinify = canFontMinify && fontTexts.size;
1105
+ const baseFetchOptions = {
1106
+ url,
1107
+ timeout,
1108
+ responseType: needFontMinify ? "arrayBuffer" : responseType,
1109
+ headers: requestType === "image" ? { accept: acceptOfImage } : void 0,
1110
+ ...requestInit
1111
+ };
1112
+ request = {
1113
+ type: requestType,
1114
+ resolve: void 0,
1115
+ reject: void 0,
1116
+ response: null
1117
+ };
1118
+ request.response = (async () => {
1119
+ if (fetchFn && requestType === "image") {
1120
+ const result = await fetchFn(rawUrl);
1121
+ if (result)
1122
+ return result;
1123
+ }
1124
+ if (!IN_SAFARI && rawUrl.startsWith("http") && workers.length) {
1125
+ return new Promise((resolve, reject) => {
1126
+ const worker = workers[requests.size & workers.length - 1];
1127
+ worker.postMessage({ rawUrl, ...baseFetchOptions });
1128
+ request.resolve = resolve;
1129
+ request.reject = reject;
1130
+ });
1131
+ }
1132
+ return baseFetch(baseFetchOptions);
1133
+ })().catch((error) => {
1134
+ requests.delete(rawUrl);
1135
+ if (requestType === "image" && placeholderImage) {
1136
+ context.log.warn("Failed to fetch image base64, trying to use placeholder image", url);
1137
+ return typeof placeholderImage === "string" ? placeholderImage : placeholderImage(imageDom);
1138
+ }
1139
+ throw error;
1140
+ });
1141
+ requests.set(rawUrl, request);
1142
+ }
1143
+ return request.response;
1144
+ }
1145
+ async function replaceCssUrlToDataUrl(cssText, baseUrl, context, isImage) {
1146
+ if (!hasCssUrl(cssText))
1147
+ return cssText;
1148
+ for (const [rawUrl, url] of parseCssUrls(cssText, baseUrl)) {
1149
+ try {
1150
+ const dataUrl = await contextFetch(
1151
+ context,
1152
+ {
1153
+ url,
1154
+ requestType: isImage ? "image" : "text",
1155
+ responseType: "dataUrl"
1156
+ }
1157
+ );
1158
+ cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`);
1159
+ } catch (error) {
1160
+ context.log.warn("Failed to fetch css data url", rawUrl, error);
1161
+ }
1162
+ }
1163
+ return cssText;
1164
+ }
1165
+ function hasCssUrl(cssText) {
1166
+ return /url\((['"]?)([^'"]+?)\1\)/.test(cssText);
1167
+ }
1168
+ var URL_RE = /url\((['"]?)([^'"]+?)\1\)/g;
1169
+ function parseCssUrls(cssText, baseUrl) {
1170
+ const result = [];
1171
+ cssText.replace(URL_RE, (raw, quotation, url) => {
1172
+ result.push([url, resolveUrl(url, baseUrl)]);
1173
+ return raw;
1174
+ });
1175
+ return result.filter(([url]) => !isDataUrl(url));
1176
+ }
1177
+ function toRE(url) {
1178
+ const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
1179
+ return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g");
1180
+ }
1181
+ var properties = [
1182
+ "background-image",
1183
+ "border-image-source",
1184
+ "-webkit-border-image",
1185
+ "-webkit-mask-image",
1186
+ "list-style-image"
1187
+ ];
1188
+ function embedCssStyleImage(style, context) {
1189
+ return properties.map((property) => {
1190
+ const value = style.getPropertyValue(property);
1191
+ if (!value || value === "none") {
1192
+ return null;
1193
+ }
1194
+ if (IN_SAFARI || IN_FIREFOX) {
1195
+ context.drawImageCount++;
1196
+ }
1197
+ return replaceCssUrlToDataUrl(value, null, context, true).then((newValue) => {
1198
+ if (!newValue || value === newValue)
1199
+ return;
1200
+ style.setProperty(
1201
+ property,
1202
+ newValue,
1203
+ style.getPropertyPriority(property)
1204
+ );
1205
+ });
1206
+ }).filter(Boolean);
1207
+ }
1208
+ function embedImageElement(cloned, context) {
1209
+ if (isImageElement(cloned)) {
1210
+ const originalSrc = cloned.currentSrc || cloned.src;
1211
+ if (!isDataUrl(originalSrc)) {
1212
+ return [
1213
+ contextFetch(context, {
1214
+ url: originalSrc,
1215
+ imageDom: cloned,
1216
+ requestType: "image",
1217
+ responseType: "dataUrl"
1218
+ }).then((url) => {
1219
+ if (!url)
1220
+ return;
1221
+ cloned.srcset = "";
1222
+ cloned.dataset.originalSrc = originalSrc;
1223
+ cloned.src = url || "";
1224
+ })
1225
+ ];
1226
+ }
1227
+ if (IN_SAFARI || IN_FIREFOX) {
1228
+ context.drawImageCount++;
1229
+ }
1230
+ } else if (isSVGElementNode(cloned) && !isDataUrl(cloned.href.baseVal)) {
1231
+ const originalSrc = cloned.href.baseVal;
1232
+ return [
1233
+ contextFetch(context, {
1234
+ url: originalSrc,
1235
+ imageDom: cloned,
1236
+ requestType: "image",
1237
+ responseType: "dataUrl"
1238
+ }).then((url) => {
1239
+ if (!url)
1240
+ return;
1241
+ cloned.dataset.originalSrc = originalSrc;
1242
+ cloned.href.baseVal = url || "";
1243
+ })
1244
+ ];
1245
+ }
1246
+ return [];
1247
+ }
1248
+ function embedSvgUse(cloned, context) {
1249
+ const { ownerDocument, svgDefsElement } = context;
1250
+ const href = cloned.getAttribute("href") ?? cloned.getAttribute("xlink:href");
1251
+ if (!href)
1252
+ return [];
1253
+ const [svgUrl, id] = href.split("#");
1254
+ if (id) {
1255
+ const query = `#${id}`;
1256
+ const definition = context.shadowRoots.reduce(
1257
+ (res, root) => {
1258
+ return res ?? root.querySelector(`svg ${query}`);
1259
+ },
1260
+ ownerDocument?.querySelector(`svg ${query}`)
1261
+ );
1262
+ if (svgUrl) {
1263
+ cloned.setAttribute("href", query);
1264
+ }
1265
+ if (svgDefsElement?.querySelector(query))
1266
+ return [];
1267
+ if (definition) {
1268
+ svgDefsElement?.appendChild(definition.cloneNode(true));
1269
+ return [];
1270
+ } else if (svgUrl) {
1271
+ return [
1272
+ contextFetch(context, {
1273
+ url: svgUrl,
1274
+ responseType: "text"
1275
+ }).then((svgData) => {
1276
+ svgDefsElement?.insertAdjacentHTML("beforeend", svgData);
1277
+ })
1278
+ ];
1279
+ }
1280
+ }
1281
+ return [];
1282
+ }
1283
+ function embedNode(cloned, context) {
1284
+ const { tasks } = context;
1285
+ if (isElementNode(cloned)) {
1286
+ if (isImageElement(cloned) || isSVGImageElementNode(cloned)) {
1287
+ tasks.push(...embedImageElement(cloned, context));
1288
+ }
1289
+ if (isSVGUseElementNode(cloned)) {
1290
+ tasks.push(...embedSvgUse(cloned, context));
1291
+ }
1292
+ }
1293
+ if (isHTMLElementNode(cloned)) {
1294
+ tasks.push(...embedCssStyleImage(cloned.style, context));
1295
+ }
1296
+ cloned.childNodes.forEach((child) => {
1297
+ embedNode(child, context);
1298
+ });
1299
+ }
1300
+ async function embedWebFont(clone, context) {
1301
+ const {
1302
+ ownerDocument,
1303
+ svgStyleElement,
1304
+ fontFamilies,
1305
+ fontCssTexts,
1306
+ tasks,
1307
+ font
1308
+ } = context;
1309
+ if (!ownerDocument || !svgStyleElement || !fontFamilies.size) {
1310
+ return;
1311
+ }
1312
+ if (font && font.cssText) {
1313
+ const cssText = filterPreferredFormat(font.cssText, context);
1314
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
1315
+ `));
1316
+ } else {
1317
+ const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => {
1318
+ try {
1319
+ return "cssRules" in styleSheet && Boolean(styleSheet.cssRules.length);
1320
+ } catch (error) {
1321
+ context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error);
1322
+ return false;
1323
+ }
1324
+ });
1325
+ const tempDoc = ownerDocument.implementation.createHTMLDocument("");
1326
+ const tempStyleEl = tempDoc.createElement("style");
1327
+ tempDoc.head.appendChild(tempStyleEl);
1328
+ const tempStyleSheet = tempStyleEl.sheet;
1329
+ await Promise.all(
1330
+ styleSheets.flatMap((styleSheet) => {
1331
+ return Array.from(styleSheet.cssRules).map(async (cssRule) => {
1332
+ if (isCSSImportRule(cssRule)) {
1333
+ const baseUrl = cssRule.href;
1334
+ let cssText = "";
1335
+ try {
1336
+ cssText = await contextFetch(context, {
1337
+ url: baseUrl,
1338
+ requestType: "text",
1339
+ responseType: "text"
1340
+ });
1341
+ } catch (error) {
1342
+ context.log.warn(`Error fetch remote css import from ${baseUrl}`, error);
1343
+ }
1344
+ const replacedCssText = cssText.replace(
1345
+ URL_RE,
1346
+ (raw, quotation, url) => raw.replace(url, resolveUrl(url, baseUrl))
1347
+ );
1348
+ for (const rule of parseCss(replacedCssText)) {
1349
+ try {
1350
+ tempStyleSheet.insertRule(rule, tempStyleSheet.cssRules.length);
1351
+ } catch (error) {
1352
+ context.log.warn("Error inserting rule from remote css import", { rule, error });
1353
+ }
1354
+ }
1355
+ }
1356
+ });
1357
+ })
1358
+ );
1359
+ if (tempStyleSheet.cssRules.length)
1360
+ styleSheets.push(tempStyleSheet);
1361
+ const cssRules = [];
1362
+ styleSheets.forEach((sheet) => {
1363
+ unwrapCssLayers(sheet.cssRules, cssRules);
1364
+ });
1365
+ cssRules.filter((cssRule) => isCssFontFaceRule(cssRule) && hasCssUrl(cssRule.style.getPropertyValue("src")) && splitFontFamily(cssRule.style.getPropertyValue("font-family"))?.some((val) => fontFamilies.has(val))).forEach((value) => {
1366
+ const rule = value;
1367
+ const cssText = fontCssTexts.get(rule.cssText);
1368
+ if (cssText) {
1369
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
1370
+ `));
1371
+ } else {
1372
+ tasks.push(
1373
+ replaceCssUrlToDataUrl(
1374
+ rule.cssText,
1375
+ rule.parentStyleSheet ? rule.parentStyleSheet.href : null,
1376
+ context
1377
+ ).then((cssText2) => {
1378
+ cssText2 = filterPreferredFormat(cssText2, context);
1379
+ fontCssTexts.set(rule.cssText, cssText2);
1380
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2}
1381
+ `));
1382
+ })
1383
+ );
1384
+ }
1385
+ });
1386
+ }
1387
+ }
1388
+ var COMMENTS_RE = /(\/\*[\s\S]*?\*\/)/g;
1389
+ var KEYFRAMES_RE = /((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;
1390
+ function parseCss(source) {
1391
+ if (source == null)
1392
+ return [];
1393
+ const result = [];
1394
+ let cssText = source.replace(COMMENTS_RE, "");
1395
+ while (true) {
1396
+ const matches = KEYFRAMES_RE.exec(cssText);
1397
+ if (!matches)
1398
+ break;
1399
+ result.push(matches[0]);
1400
+ }
1401
+ cssText = cssText.replace(KEYFRAMES_RE, "");
1402
+ const IMPORT_RE = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi;
1403
+ const UNIFIED_RE = new RegExp(
1404
+ // eslint-disable-next-line
1405
+ "((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",
1406
+ "gi"
1407
+ );
1408
+ while (true) {
1409
+ let matches = IMPORT_RE.exec(cssText);
1410
+ if (!matches) {
1411
+ matches = UNIFIED_RE.exec(cssText);
1412
+ if (!matches) {
1413
+ break;
1414
+ } else {
1415
+ IMPORT_RE.lastIndex = UNIFIED_RE.lastIndex;
1416
+ }
1417
+ } else {
1418
+ UNIFIED_RE.lastIndex = IMPORT_RE.lastIndex;
1419
+ }
1420
+ result.push(matches[0]);
1421
+ }
1422
+ return result;
1423
+ }
1424
+ var URL_WITH_FORMAT_RE = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g;
1425
+ var FONT_SRC_RE = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;
1426
+ function filterPreferredFormat(str, context) {
1427
+ const { font } = context;
1428
+ const preferredFormat = font ? font?.preferredFormat : void 0;
1429
+ return preferredFormat ? str.replace(FONT_SRC_RE, (match) => {
1430
+ while (true) {
1431
+ const [src, , format] = URL_WITH_FORMAT_RE.exec(match) || [];
1432
+ if (!format)
1433
+ return "";
1434
+ if (format === preferredFormat)
1435
+ return `src: ${src};`;
1436
+ }
1437
+ }) : str;
1438
+ }
1439
+ function unwrapCssLayers(rules, out = []) {
1440
+ for (const rule of Array.from(rules)) {
1441
+ if (isLayerBlockRule(rule)) {
1442
+ out.push(...unwrapCssLayers(rule.cssRules));
1443
+ } else if ("cssRules" in rule) {
1444
+ unwrapCssLayers(rule.cssRules, out);
1445
+ } else {
1446
+ out.push(rule);
1447
+ }
1448
+ }
1449
+ return out;
1450
+ }
1451
+ var SVG_EXTERNAL_RESOURCE_REGEX = /\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;
1452
+ function svgHasExternalResources(svg) {
1453
+ return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML);
1454
+ }
1455
+ async function domToForeignObjectSvg(node, options) {
1456
+ const context = await orCreateContext(node, options);
1457
+ if (isElementNode(context.node) && isSVGElementNode(context.node) && !svgHasExternalResources(context.node))
1458
+ return context.node;
1459
+ const {
1460
+ ownerDocument,
1461
+ log,
1462
+ tasks,
1463
+ svgStyleElement,
1464
+ svgDefsElement,
1465
+ svgStyles,
1466
+ font,
1467
+ progress,
1468
+ autoDestruct,
1469
+ onCloneNode,
1470
+ onEmbedNode,
1471
+ onCreateForeignObjectSvg
1472
+ } = context;
1473
+ log.time("clone node");
1474
+ const clone = await cloneNode(context.node, context, true);
1475
+ if (svgStyleElement && ownerDocument) {
1476
+ let allCssText = "";
1477
+ svgStyles.forEach((klasses, cssText) => {
1478
+ allCssText += `${klasses.join(",\n")} {
1479
+ ${cssText}
1480
+ }
1481
+ `;
1482
+ });
1483
+ svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText));
1484
+ }
1485
+ log.timeEnd("clone node");
1486
+ await onCloneNode?.(clone);
1487
+ if (font !== false && isElementNode(clone)) {
1488
+ log.time("embed web font");
1489
+ await embedWebFont(clone, context);
1490
+ log.timeEnd("embed web font");
1491
+ }
1492
+ log.time("embed node");
1493
+ embedNode(clone, context);
1494
+ const count = tasks.length;
1495
+ let current = 0;
1496
+ const runTask = async () => {
1497
+ while (true) {
1498
+ const task = tasks.pop();
1499
+ if (!task)
1500
+ break;
1501
+ try {
1502
+ await task;
1503
+ } catch (error) {
1504
+ context.log.warn("Failed to run task", error);
1505
+ }
1506
+ progress?.(++current, count);
1507
+ }
1508
+ };
1509
+ progress?.(current, count);
1510
+ await Promise.all([...Array.from({ length: 4 })].map(runTask));
1511
+ log.timeEnd("embed node");
1512
+ await onEmbedNode?.(clone);
1513
+ const svg = createForeignObjectSvg(clone, context);
1514
+ svgDefsElement && svg.insertBefore(svgDefsElement, svg.children[0]);
1515
+ svgStyleElement && svg.insertBefore(svgStyleElement, svg.children[0]);
1516
+ autoDestruct && destroyContext(context);
1517
+ await onCreateForeignObjectSvg?.(svg);
1518
+ return svg;
1519
+ }
1520
+ function createForeignObjectSvg(clone, context) {
1521
+ const { width, height } = context;
1522
+ const svg = createSvg(width, height, clone.ownerDocument);
1523
+ const foreignObject = svg.ownerDocument.createElementNS(svg.namespaceURI, "foreignObject");
1524
+ foreignObject.setAttributeNS(null, "x", "0%");
1525
+ foreignObject.setAttributeNS(null, "y", "0%");
1526
+ foreignObject.setAttributeNS(null, "width", "100%");
1527
+ foreignObject.setAttributeNS(null, "height", "100%");
1528
+ foreignObject.append(clone);
1529
+ svg.appendChild(foreignObject);
1530
+ return svg;
1531
+ }
1532
+ async function domToCanvas(node, options) {
1533
+ const context = await orCreateContext(node, options);
1534
+ const svg = await domToForeignObjectSvg(context);
1535
+ const dataUrl = svgToDataUrl(svg, context.isEnable("removeControlCharacter"));
1536
+ if (!context.autoDestruct) {
1537
+ context.svgStyleElement = createStyleElement(context.ownerDocument);
1538
+ context.svgDefsElement = context.ownerDocument?.createElementNS(XMLNS, "defs");
1539
+ context.svgStyles.clear();
1540
+ }
1541
+ const image = createImage(dataUrl, svg.ownerDocument);
1542
+ return await imageToCanvas(image, context);
1543
+ }
1544
+ async function domToBlob(node, options) {
1545
+ const context = await orCreateContext(node, options);
1546
+ const { log, type, quality, dpi } = context;
1547
+ const canvas = await domToCanvas(context);
1548
+ log.time("canvas to blob");
1549
+ const blob = await canvasToBlob(canvas, type, quality);
1550
+ if (["image/png", "image/jpeg"].includes(type) && dpi) {
1551
+ const arrayBuffer = await blobToArrayBuffer(blob.slice(0, 33));
1552
+ let uint8Array = new Uint8Array(arrayBuffer);
1553
+ if (type === "image/png") {
1554
+ uint8Array = changePngDpi(uint8Array, dpi);
1555
+ } else if (type === "image/jpeg") {
1556
+ uint8Array = changeJpegDpi(uint8Array, dpi);
1557
+ }
1558
+ log.timeEnd("canvas to blob");
1559
+ return new Blob([uint8Array, blob.slice(33)], { type });
1560
+ }
1561
+ log.timeEnd("canvas to blob");
1562
+ return blob;
1563
+ }
1564
+ async function domToDataUrl(node, options) {
1565
+ const context = await orCreateContext(node, options);
1566
+ const { log, quality, type, dpi } = context;
1567
+ const canvas = await domToCanvas(context);
1568
+ log.time("canvas to data url");
1569
+ let dataUrl = canvas.toDataURL(type, quality);
1570
+ if (["image/png", "image/jpeg"].includes(type) && dpi && SUPPORT_ATOB && SUPPORT_BTOA) {
1571
+ const [format, body] = dataUrl.split(",");
1572
+ let headerLength = 0;
1573
+ let overwritepHYs = false;
1574
+ if (type === "image/png") {
1575
+ const b64Index = detectPhysChunkFromDataUrl(body);
1576
+ if (b64Index >= 0) {
1577
+ headerLength = Math.ceil((b64Index + 28) / 3) * 4;
1578
+ overwritepHYs = true;
1579
+ } else {
1580
+ headerLength = 33 / 3 * 4;
1581
+ }
1582
+ } else if (type === "image/jpeg") {
1583
+ headerLength = 18 / 3 * 4;
1584
+ }
1585
+ const stringHeader = body.substring(0, headerLength);
1586
+ const restOfData = body.substring(headerLength);
1587
+ const headerBytes = window.atob(stringHeader);
1588
+ const uint8Array = new Uint8Array(headerBytes.length);
1589
+ for (let i = 0; i < uint8Array.length; i++) {
1590
+ uint8Array[i] = headerBytes.charCodeAt(i);
1591
+ }
1592
+ const finalArray = type === "image/png" ? changePngDpi(uint8Array, dpi, overwritepHYs) : changeJpegDpi(uint8Array, dpi);
1593
+ const base64Header = window.btoa(String.fromCharCode(...finalArray));
1594
+ dataUrl = [format, ",", base64Header, restOfData].join("");
1595
+ }
1596
+ log.timeEnd("canvas to data url");
1597
+ return dataUrl;
1598
+ }
1599
+ async function domToSvg(node, options) {
1600
+ const context = await orCreateContext(node, options);
1601
+ const { width, height, ownerDocument } = context;
1602
+ const dataUrl = await domToDataUrl(context);
1603
+ const svg = createSvg(width, height, ownerDocument);
1604
+ const svgImage = svg.ownerDocument.createElementNS(svg.namespaceURI, "image");
1605
+ svgImage.setAttributeNS(null, "href", dataUrl);
1606
+ svgImage.setAttributeNS(null, "height", "100%");
1607
+ svgImage.setAttributeNS(null, "width", "100%");
1608
+ svg.appendChild(svgImage);
1609
+ return svgToDataUrl(svg, context.isEnable("removeControlCharacter"));
1610
+ }
1611
+ async function domToImage(node, options) {
1612
+ const context = await orCreateContext(node, options);
1613
+ const { ownerDocument, width, height, scale, type } = context;
1614
+ const url = type === "image/svg+xml" ? await domToSvg(context) : await domToDataUrl(context);
1615
+ const image = createImage(url, ownerDocument);
1616
+ image.width = Math.floor(width * scale);
1617
+ image.height = Math.floor(height * scale);
1618
+ image.style.width = `${width}px`;
1619
+ image.style.height = `${height}px`;
1620
+ return image;
1621
+ }
1622
+ async function domToJpeg(node, options) {
1623
+ return domToDataUrl(
1624
+ await orCreateContext(node, { ...options, type: "image/jpeg" })
1625
+ );
1626
+ }
1627
+ async function domToPixel(node, options) {
1628
+ const context = await orCreateContext(node, options);
1629
+ const canvas = await domToCanvas(context);
1630
+ return canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
1631
+ }
1632
+ async function domToPng(node, options) {
1633
+ return domToDataUrl(
1634
+ await orCreateContext(node, { ...options, type: "image/png" })
1635
+ );
1636
+ }
1637
+ async function domToWebp(node, options) {
1638
+ return domToDataUrl(
1639
+ await orCreateContext(node, { ...options, type: "image/webp" })
1640
+ );
1641
+ }
1642
+ export {
1643
+ createContext,
1644
+ destroyContext,
1645
+ domToBlob,
1646
+ domToCanvas,
1647
+ domToDataUrl,
1648
+ domToForeignObjectSvg,
1649
+ domToImage,
1650
+ domToJpeg,
1651
+ domToPixel,
1652
+ domToPng,
1653
+ domToSvg,
1654
+ domToWebp,
1655
+ loadMedia,
1656
+ waitUntilLoad
1657
+ };
1658
+ //# sourceMappingURL=dist-VC6ZVTA2.js.map