@mushi-mushi/web 1.37.0 → 1.37.3

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.
package/dist/headless.cjs CHANGED
@@ -2,7 +2,710 @@
2
2
 
3
3
  var core = require('@mushi-mushi/core');
4
4
 
5
- // src/headless.ts
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+
15
+ // src/capture/screenshot-dom.ts
16
+ var screenshot_dom_exports = {};
17
+ __export(screenshot_dom_exports, {
18
+ captureDomScreenshot: () => captureDomScreenshot
19
+ });
20
+ async function captureDomScreenshot(privacy, fail) {
21
+ const canvas = document.createElement("canvas");
22
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
23
+ if (!ctx) {
24
+ fail("unsupported");
25
+ return null;
26
+ }
27
+ const width = window.innerWidth;
28
+ const height = window.innerHeight;
29
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
30
+ canvas.width = width * dpr;
31
+ canvas.height = height * dpr;
32
+ ctx.scale(dpr, dpr);
33
+ const safeDocument = await buildPrivacySafeDocument(privacy);
34
+ const markup = new XMLSerializer().serializeToString(safeDocument).replace(XML_INVALID_CHARS, "");
35
+ const svgData = `
36
+ <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
37
+ <foreignObject width="100%" height="100%">
38
+ <div xmlns="http://www.w3.org/1999/xhtml">
39
+ ${markup}
40
+ </div>
41
+ </foreignObject>
42
+ </svg>
43
+ `;
44
+ const img = new Image();
45
+ const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgData)}`;
46
+ let cspBlocked = false;
47
+ const onViolation = (e) => {
48
+ const v = e;
49
+ if (/^img-src|^default-src/.test(v.violatedDirective ?? "") && /^data/.test(v.blockedURI ?? "")) cspBlocked = true;
50
+ };
51
+ document.addEventListener("securitypolicyviolation", onViolation);
52
+ return new Promise((resolve) => {
53
+ let settled = false;
54
+ const settle = (value, reason) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ document.removeEventListener("securitypolicyviolation", onViolation);
59
+ if (reason) fail(reason);
60
+ resolve(value);
61
+ };
62
+ const timer = setTimeout(() => settle(null, "timeout"), 5e3);
63
+ img.onload = () => {
64
+ try {
65
+ ctx.drawImage(img, 0, 0, width, height);
66
+ if (isCanvasBlank(ctx, width, height)) {
67
+ settle(null, "unsupported");
68
+ return;
69
+ }
70
+ settle(canvas.toDataURL("image/jpeg", 0.7));
71
+ } catch {
72
+ settle(null, "taint");
73
+ }
74
+ };
75
+ img.onerror = () => setTimeout(() => settle(null, cspBlocked ? "csp" : "error"), 0);
76
+ img.src = url;
77
+ });
78
+ }
79
+ async function buildPrivacySafeDocument(privacy) {
80
+ const live = document.documentElement;
81
+ const clone = live.cloneNode(true);
82
+ const liveLinks = live.querySelectorAll("link");
83
+ const cloneLinks = clone.querySelectorAll("link");
84
+ const linkSlots = /* @__PURE__ */ new Map();
85
+ if (liveLinks.length === cloneLinks.length) liveLinks.forEach((l, i) => linkSlots.set(l, cloneLinks[i]));
86
+ const { offscreen, pins, backgrounds } = replayLiveState(live, clone);
87
+ fillScriptedStyleElements(live, clone);
88
+ const hidden = [
89
+ ALWAYS_REDACT_SELECTORS,
90
+ ...privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS,
91
+ ...privacy?.maskSelectors ?? [],
92
+ ...privacy?.blockSelectors ?? []
93
+ ];
94
+ inlineMedia(
95
+ Array.from(live.querySelectorAll(MEDIA_SELECTOR)),
96
+ Array.from(clone.querySelectorAll(MEDIA_SELECTOR)),
97
+ (el) => offscreen.has(el) || hidden.some((selector) => matchesOrInside(el, selector))
98
+ );
99
+ pinOffscreen(pins);
100
+ await inlineBackgrounds(backgrounds.filter((bg) => !hidden.some((selector) => matchesOrInside(bg.live, selector))));
101
+ clone.querySelector("#mushi-mushi-widget")?.remove();
102
+ await inlineDocumentStyles(clone, linkSlots);
103
+ stripTaintSources(clone);
104
+ makeXmlSafe(clone);
105
+ freezeMotion(clone);
106
+ fillViewport(clone);
107
+ const redactSelectors = [
108
+ ALWAYS_REDACT_SELECTORS,
109
+ ...privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS
110
+ ];
111
+ for (const selector of redactSelectors) {
112
+ for (const el of safeQueryAll(clone, selector)) {
113
+ redactElement(el);
114
+ }
115
+ }
116
+ for (const selector of privacy?.blockSelectors ?? []) {
117
+ for (const el of safeQueryAll(clone, selector)) {
118
+ el.remove();
119
+ }
120
+ }
121
+ for (const selector of privacy?.maskSelectors ?? []) {
122
+ for (const el of safeQueryAll(clone, selector)) {
123
+ maskElement(el);
124
+ }
125
+ }
126
+ return clone;
127
+ }
128
+ function replayLiveState(live, clone) {
129
+ const offscreen = /* @__PURE__ */ new Set();
130
+ const pins = [];
131
+ const backgrounds = [];
132
+ const liveAll = [live, ...Array.from(live.querySelectorAll("*"))];
133
+ const cloneAll = [clone, ...Array.from(clone.querySelectorAll("*"))];
134
+ if (liveAll.length !== cloneAll.length) return { offscreen, pins, backgrounds };
135
+ const animated = animationTargets();
136
+ const styles = [];
137
+ const scroller = document.scrollingElement;
138
+ const pending = /* @__PURE__ */ new Map();
139
+ const set = (el, prop, value) => {
140
+ let decls = pending.get(el);
141
+ if (!decls) pending.set(el, decls = /* @__PURE__ */ new Map());
142
+ decls.set(prop, value);
143
+ };
144
+ const scrolled = [];
145
+ const withBackground = [];
146
+ let inBody = false;
147
+ for (let i = 0; i < liveAll.length; i++) {
148
+ const liveEl = liveAll[i];
149
+ const cloneEl = cloneAll[i];
150
+ const computed = getComputedStyle(liveEl);
151
+ styles.push(computed);
152
+ if (liveEl === document.body) inBody = true;
153
+ if (inBody) {
154
+ if (computed.display === "none") set(cloneEl, "display", "none");
155
+ else {
156
+ const parent = liveEl.parentElement;
157
+ if (computed.visibility !== "visible" && parent && getComputedStyle(parent).visibility === "visible") {
158
+ set(cloneEl, "visibility", computed.visibility);
159
+ }
160
+ if (computed.opacity === "0") set(cloneEl, "opacity", "0");
161
+ if (computed.backgroundImage.includes("url(")) withBackground.push(i);
162
+ }
163
+ }
164
+ if (animated.has(liveEl)) {
165
+ for (const p of ANIMATED_PROPERTIES) set(cloneEl, p, computed.getPropertyValue(p));
166
+ }
167
+ if (computed.position === "sticky" && liveEl instanceof HTMLElement) {
168
+ const offset = stickyOffset(liveEl);
169
+ if (offset) {
170
+ set(cloneEl, "position", "relative");
171
+ set(cloneEl, "top", `${offset.top}px`);
172
+ set(cloneEl, "left", `${offset.left}px`);
173
+ set(cloneEl, "bottom", "auto");
174
+ set(cloneEl, "right", "auto");
175
+ }
176
+ }
177
+ if (liveEl !== scroller && (liveEl.scrollTop > 0 || liveEl.scrollLeft > 0)) scrolled.push(i);
178
+ }
179
+ for (const i of scrolled) {
180
+ const liveEl = liveAll[i];
181
+ const liveKids = liveEl.children;
182
+ const cloneKids = cloneAll[i].children;
183
+ for (let j = 0; j < liveKids.length && j < cloneKids.length; j++) {
184
+ const kid = getComputedStyle(liveKids[j]);
185
+ if (kid.position === "fixed") continue;
186
+ const own = pending.get(cloneKids[j])?.get("transform") ?? kid.transform;
187
+ const shift = `translate(${-liveEl.scrollLeft}px, ${-liveEl.scrollTop}px)`;
188
+ set(cloneKids[j], "transform", own && own !== "none" ? `${shift} ${own}` : shift);
189
+ }
190
+ }
191
+ if (window.scrollX || window.scrollY) {
192
+ set(clone, "position", "relative");
193
+ set(clone, "top", `${-window.scrollY}px`);
194
+ set(clone, "left", `${-window.scrollX}px`);
195
+ }
196
+ for (const [el, decls] of pending) {
197
+ const held = Array.from(decls, ([p, v]) => `${p}:${v}!important`).join(";");
198
+ el.setAttribute("style", `${el.getAttribute("style") ?? ""};${held}`);
199
+ }
200
+ findOffscreen(liveAll, cloneAll, styles, offscreen, pins);
201
+ for (const i of withBackground) {
202
+ if (!offscreen.has(liveAll[i])) {
203
+ backgrounds.push({ live: liveAll[i], clone: cloneAll[i], value: styles[i].backgroundImage });
204
+ }
205
+ }
206
+ return { offscreen, pins, backgrounds };
207
+ }
208
+ async function inlineBackgrounds(backgrounds) {
209
+ const urls = /* @__PURE__ */ new Map();
210
+ let bytes = 0;
211
+ const load = (url) => {
212
+ let pending = urls.get(url);
213
+ if (!pending) {
214
+ pending = urls.size >= MAX_BACKGROUND_URLS ? Promise.resolve(null) : readAsDataUrl(url).then((data) => {
215
+ if (!data || bytes + data.length > MAX_BACKGROUND_BYTES) return null;
216
+ bytes += data.length;
217
+ return data;
218
+ });
219
+ urls.set(url, pending);
220
+ }
221
+ return pending;
222
+ };
223
+ await Promise.all(
224
+ backgrounds.map(async (bg) => {
225
+ const refs = Array.from(bg.value.matchAll(CSS_URL), (m) => m[2].trim()).filter((u) => !u.startsWith("data:"));
226
+ if (refs.length === 0) return;
227
+ const data = await Promise.all(refs.map(load));
228
+ let value = bg.value;
229
+ refs.forEach((ref, k) => {
230
+ if (data[k]) value = value.split(ref).join(data[k]);
231
+ });
232
+ if (value !== bg.value) {
233
+ bg.clone.setAttribute("style", `${bg.clone.getAttribute("style") ?? ""};background-image:${value}!important`);
234
+ }
235
+ })
236
+ );
237
+ }
238
+ async function readAsDataUrl(url) {
239
+ if (typeof fetch !== "function") return null;
240
+ const abort = typeof AbortController === "function" ? new AbortController() : null;
241
+ const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);
242
+ try {
243
+ const res = await fetch(url, { cache: "force-cache", signal: abort?.signal });
244
+ if (!res.ok) return null;
245
+ const blob = await res.blob();
246
+ if (blob.size > MAX_BACKGROUND_IMAGE_BYTES || !blob.type.startsWith("image/")) return null;
247
+ const bytes = new Uint8Array(await blob.arrayBuffer());
248
+ let binary = "";
249
+ for (let i = 0; i < bytes.length; i += 32768) {
250
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
251
+ }
252
+ return `data:${blob.type};base64,${btoa(binary)}`;
253
+ } catch {
254
+ return null;
255
+ } finally {
256
+ clearTimeout(timer);
257
+ }
258
+ }
259
+ function findOffscreen(liveAll, cloneAll, styles, offscreen, pins) {
260
+ const bodyIndex = document.body ? liveAll.indexOf(document.body) : -1;
261
+ if (bodyIndex < 0) return;
262
+ const vw = window.innerWidth;
263
+ const vh = window.innerHeight;
264
+ const index = /* @__PURE__ */ new Map();
265
+ const visible = new Array(liveAll.length).fill(false);
266
+ const outside = new Array(liveAll.length).fill(false);
267
+ for (let i = bodyIndex; i < liveAll.length; i++) index.set(liveAll[i], i);
268
+ visible[bodyIndex] = true;
269
+ for (let i = liveAll.length - 1; i > bodyIndex; i--) {
270
+ const el = liveAll[i];
271
+ const r = el.getBoundingClientRect();
272
+ if (r.width > 0 || r.height > 0) {
273
+ if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) visible[i] = true;
274
+ else outside[i] = true;
275
+ }
276
+ if (styles[i].position === "fixed") visible[i] = true;
277
+ if (visible[i]) {
278
+ outside[i] = false;
279
+ const parent = el.parentElement ? index.get(el.parentElement) : void 0;
280
+ if (parent !== void 0) visible[parent] = true;
281
+ } else if (outside[i]) {
282
+ offscreen.add(el);
283
+ }
284
+ }
285
+ const covered = new Array(liveAll.length).fill(false);
286
+ for (let i = bodyIndex + 1; i < liveAll.length; i++) {
287
+ const el = liveAll[i];
288
+ const parentIndex = el.parentElement ? index.get(el.parentElement) : void 0;
289
+ if (parentIndex === void 0) continue;
290
+ if (covered[parentIndex]) {
291
+ covered[i] = true;
292
+ continue;
293
+ }
294
+ if (!outside[i] || !(el instanceof HTMLElement)) continue;
295
+ const s = styles[i];
296
+ if (!PINNABLE_DISPLAY.test(s.display)) continue;
297
+ covered[i] = true;
298
+ const inFlow = BLOCK_FLOW.test(styles[parentIndex].display) && s.float === "none" && (s.position === "static" || s.position === "relative");
299
+ pins.push({
300
+ clone: cloneAll[i],
301
+ width: el.offsetWidth,
302
+ height: el.offsetHeight,
303
+ marginTop: inFlow ? gapAbove(el) : null,
304
+ marginBottom: inFlow ? gapBelow(el) : null
305
+ });
306
+ }
307
+ }
308
+ function gapAbove(el) {
309
+ const prev = el.previousElementSibling;
310
+ if (!(prev instanceof HTMLElement) || prev.offsetParent !== el.offsetParent) return null;
311
+ return Math.max(0, el.offsetTop - (prev.offsetTop + prev.offsetHeight));
312
+ }
313
+ function gapBelow(el) {
314
+ const next = el.nextElementSibling;
315
+ if (!(next instanceof HTMLElement) || next.offsetParent !== el.offsetParent) return null;
316
+ return Math.max(0, next.offsetTop - (el.offsetTop + el.offsetHeight));
317
+ }
318
+ function pinOffscreen(pins) {
319
+ for (const pin of pins) {
320
+ pin.clone.replaceChildren();
321
+ let pinned = `width:${pin.width}px!important;height:${pin.height}px!important;box-sizing:border-box!important;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;content-visibility:visible!important;contain:none!important;`;
322
+ if (pin.marginTop !== null) pinned += `margin-top:${pin.marginTop}px!important;`;
323
+ if (pin.marginBottom !== null) pinned += `margin-bottom:${pin.marginBottom}px!important;`;
324
+ pin.clone.setAttribute("style", `${pin.clone.getAttribute("style") ?? ""};${pinned}`);
325
+ }
326
+ }
327
+ function animationTargets() {
328
+ try {
329
+ return new Set(
330
+ document.getAnimations().map((a) => a.effect?.target).filter((t) => t instanceof Element && !t.pseudoElement)
331
+ );
332
+ } catch {
333
+ return /* @__PURE__ */ new Set();
334
+ }
335
+ }
336
+ function stickyOffset(el) {
337
+ const stuck = el.getBoundingClientRect();
338
+ const value = el.style.getPropertyValue("position");
339
+ const priority = el.style.getPropertyPriority("position");
340
+ el.style.setProperty("position", "static", "important");
341
+ const flow = el.getBoundingClientRect();
342
+ el.style.removeProperty("position");
343
+ if (value) el.style.setProperty("position", value, priority);
344
+ const top = stuck.top - flow.top;
345
+ const left = stuck.left - flow.left;
346
+ return top || left ? { top, left } : null;
347
+ }
348
+ function inlineMedia(liveMedia, clonedMedia, isHidden) {
349
+ let count = 0;
350
+ let bytes = 0;
351
+ for (let i = 0; i < clonedMedia.length; i++) {
352
+ const cloned = clonedMedia[i];
353
+ const liveEl = liveMedia[i];
354
+ const rect = liveEl?.getBoundingClientRect();
355
+ const layout = liveEl instanceof HTMLElement && liveEl.offsetWidth > 0 ? { width: liveEl.offsetWidth, height: liveEl.offsetHeight } : rect && { width: rect.width, height: rect.height };
356
+ let pixels = null;
357
+ if (liveEl && layout && layout.width > 0 && layout.height > 0 && count < MAX_INLINED_MEDIA && bytes < MAX_INLINED_BYTES && !isHidden(liveEl)) {
358
+ pixels = readPixels(liveEl);
359
+ if (pixels) {
360
+ count++;
361
+ bytes += pixels.url.length;
362
+ }
363
+ }
364
+ replaceMedia(cloned, pixels, layout);
365
+ }
366
+ }
367
+ function readPixels(el) {
368
+ try {
369
+ let source = null;
370
+ let width = 0;
371
+ let height = 0;
372
+ if (el instanceof HTMLCanvasElement) {
373
+ [source, width, height] = [el, el.width, el.height];
374
+ } else if (el instanceof HTMLImageElement && el.complete && el.naturalWidth > 0) {
375
+ [source, width, height] = [el, el.naturalWidth, el.naturalHeight];
376
+ } else if (el instanceof HTMLVideoElement && el.readyState >= 2) {
377
+ [source, width, height] = [el, el.videoWidth, el.videoHeight];
378
+ }
379
+ if (!source || width <= 0 || height <= 0) return null;
380
+ const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(width, height));
381
+ const canvas = document.createElement("canvas");
382
+ canvas.width = Math.max(1, Math.round(width * scale));
383
+ canvas.height = Math.max(1, Math.round(height * scale));
384
+ const ctx = canvas.getContext("2d");
385
+ if (!ctx) return null;
386
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
387
+ const url = canvas.toDataURL("image/webp", 0.85);
388
+ return url === "data:," ? null : { url, width, height };
389
+ } catch {
390
+ return null;
391
+ }
392
+ }
393
+ function matchesOrInside(el, selector) {
394
+ try {
395
+ return el.closest(selector) !== null;
396
+ } catch {
397
+ return false;
398
+ }
399
+ }
400
+ function replaceMedia(cloned, pixels, layout) {
401
+ const box = cloned.ownerDocument.createElement(pixels ? "img" : "div");
402
+ for (const name of cloned.getAttributeNames()) {
403
+ if (!SOURCE_ATTRIBUTES.has(name)) box.setAttribute(name, cloned.getAttribute(name) ?? "");
404
+ }
405
+ const size = layout ? `width:${layout.width}px;height:${layout.height}px;` : "";
406
+ if (pixels) {
407
+ box.setAttribute("src", pixels.url);
408
+ box.setAttribute("alt", "");
409
+ if (!box.hasAttribute("width")) box.setAttribute("width", String(pixels.width));
410
+ if (!box.hasAttribute("height")) box.setAttribute("height", String(pixels.height));
411
+ box.setAttribute("style", `${box.getAttribute("style") ?? ""};${size}`);
412
+ } else {
413
+ box.setAttribute(
414
+ "style",
415
+ `${box.getAttribute("style") ?? ""};${size}background:#d4d4d4!important;display:${cloned.tagName === "IMG" || cloned.tagName === "CANVAS" ? "inline-block" : "block"};`
416
+ );
417
+ }
418
+ const parent = cloned.parentElement;
419
+ const target = parent && parent.tagName === "PICTURE" ? parent : cloned;
420
+ target.replaceWith(box);
421
+ }
422
+ function makeXmlSafe(root) {
423
+ const doc = root.ownerDocument;
424
+ const walker = doc.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
425
+ const comments = [];
426
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) comments.push(n);
427
+ for (const c of comments) c.parentNode?.removeChild(c);
428
+ for (const el of [root, ...Array.from(root.querySelectorAll("*"))]) {
429
+ for (const name of el.getAttributeNames()) {
430
+ if (!XML_ATTRIBUTE_NAME.test(name)) el.removeAttribute(name);
431
+ }
432
+ }
433
+ }
434
+ function safeQueryAll(root, selector) {
435
+ try {
436
+ return Array.from(root.querySelectorAll(selector));
437
+ } catch {
438
+ return [];
439
+ }
440
+ }
441
+ function redactElement(el) {
442
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
443
+ el.value = "";
444
+ el.setAttribute("value", "");
445
+ }
446
+ el.textContent = "";
447
+ el.setAttribute(
448
+ "style",
449
+ `${el.getAttribute("style") ?? ""};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`
450
+ );
451
+ el.setAttribute("data-mushi-redacted", "true");
452
+ while (el.firstChild) el.removeChild(el.firstChild);
453
+ }
454
+ function stripTaintSources(root) {
455
+ const pageOrigin = typeof location !== "undefined" ? location.origin : "";
456
+ for (const link of root.querySelectorAll('link[rel="stylesheet"], link[as="style"]')) {
457
+ link.remove();
458
+ }
459
+ for (const styleEl of root.querySelectorAll("style")) {
460
+ const cleaned = stripCssUrlRefs(styleEl.textContent ?? "", pageOrigin);
461
+ if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;
462
+ }
463
+ for (const el of root.querySelectorAll("[style]")) {
464
+ const s = el.getAttribute("style");
465
+ if (!s) continue;
466
+ const cleaned = stripCssUrlRefs(s, pageOrigin);
467
+ if (cleaned !== s) el.setAttribute("style", cleaned);
468
+ }
469
+ for (const script of root.querySelectorAll("script, noscript, template")) {
470
+ script.remove();
471
+ }
472
+ }
473
+ function stripCssUrlRefs(css, pageOrigin) {
474
+ return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (_match, _q, href) => {
475
+ const trimmed = href.trim();
476
+ if (!trimmed || trimmed.startsWith("data:") || trimmed.startsWith("#")) return _match;
477
+ if (isCrossOriginUrl(trimmed, pageOrigin)) return "none";
478
+ return _match;
479
+ });
480
+ }
481
+ async function inlineDocumentStyles(clone, linkSlots) {
482
+ const sheets = [
483
+ ...Array.from(document.styleSheets),
484
+ ...document.adoptedStyleSheets ?? []
485
+ ];
486
+ const texts = await Promise.all(
487
+ sheets.map(async (sheet) => {
488
+ const owner = sheet.ownerNode;
489
+ if (sheet.disabled || owner instanceof Element && owner.tagName === "STYLE") return "";
490
+ return withMedia(await sheetSource(sheet) ?? serializeSheet(sheet), sheet);
491
+ })
492
+ );
493
+ const head = clone.querySelector("head") ?? clone;
494
+ sheets.forEach((sheet, i) => {
495
+ if (!texts[i]) return;
496
+ const styleEl = document.createElement("style");
497
+ styleEl.textContent = texts[i];
498
+ const slot = sheet.ownerNode ? linkSlots.get(sheet.ownerNode) : void 0;
499
+ if (slot && clone.contains(slot)) slot.replaceWith(styleEl);
500
+ else head.appendChild(styleEl);
501
+ });
502
+ }
503
+ async function sheetSource(sheet, depth = 0) {
504
+ const href = sheet.href;
505
+ if (!href || depth > 3 || typeof fetch !== "function") return null;
506
+ const abort = typeof AbortController === "function" ? new AbortController() : null;
507
+ const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);
508
+ try {
509
+ const res = await fetch(href, { cache: "force-cache", signal: abort?.signal });
510
+ if (!res.ok) return null;
511
+ let imported = "";
512
+ for (const rule of readableRules(sheet)) {
513
+ if (!(rule instanceof CSSImportRule) || !rule.styleSheet) continue;
514
+ const text = await sheetSource(rule.styleSheet, depth + 1) ?? serializeSheet(rule.styleSheet);
515
+ imported += wrapImport(text, rule);
516
+ }
517
+ const own = absolutizeCssUrls((await res.text()).replace(/@import\s[^;]*;/gi, ""), href);
518
+ return `${imported}
519
+ ${own}`;
520
+ } catch {
521
+ return null;
522
+ } finally {
523
+ clearTimeout(timer);
524
+ }
525
+ }
526
+ function readableRules(sheet) {
527
+ try {
528
+ return Array.from(sheet.cssRules);
529
+ } catch {
530
+ return [];
531
+ }
532
+ }
533
+ function wrapImport(text, rule) {
534
+ const layer = rule.layerName;
535
+ let out = layer == null ? text : `@layer ${layer}{${text}}`;
536
+ const media = rule.media?.mediaText;
537
+ if (media && media !== "all") out = `@media ${media}{${out}}`;
538
+ return `${out}
539
+ `;
540
+ }
541
+ function withMedia(text, sheet) {
542
+ const media = sheet.media?.mediaText;
543
+ return text && media && media !== "all" ? `@media ${media}{${text}}` : text;
544
+ }
545
+ function absolutizeCssUrls(css, base) {
546
+ return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (match, quote, ref) => {
547
+ const trimmed = ref.trim();
548
+ if (!trimmed || /^(data:|#|[a-z][a-z\d+.-]*:)/i.test(trimmed)) return match;
549
+ try {
550
+ return `url(${quote}${new URL(trimmed, base).href}${quote})`;
551
+ } catch {
552
+ return match;
553
+ }
554
+ });
555
+ }
556
+ function fillScriptedStyleElements(live, clone) {
557
+ const liveStyles = live.querySelectorAll("style");
558
+ const cloneStyles = clone.querySelectorAll("style");
559
+ if (liveStyles.length !== cloneStyles.length) return;
560
+ liveStyles.forEach((el, i) => {
561
+ if ((el.textContent ?? "").trim() || !el.sheet) return;
562
+ const text = serializeSheet(el.sheet);
563
+ if (text) cloneStyles[i].textContent = text;
564
+ });
565
+ }
566
+ function fillViewport(clone) {
567
+ const clear = (c) => !c || c === "transparent" || /^rgba\(.*,\s*0\)$/.test(c);
568
+ let bg = getComputedStyle(document.documentElement).backgroundColor;
569
+ if (clear(bg) && document.body) bg = getComputedStyle(document.body).backgroundColor;
570
+ const root = clone;
571
+ root.style.setProperty("background-color", clear(bg) ? "Canvas" : bg);
572
+ root.style.setProperty("min-height", `${window.innerHeight}px`);
573
+ }
574
+ function freezeMotion(clone) {
575
+ const styleEl = document.createElement("style");
576
+ styleEl.textContent = FREEZE_MOTION_CSS;
577
+ (clone.querySelector("head") ?? clone).appendChild(styleEl);
578
+ }
579
+ function serializeSheet(sheet) {
580
+ let rules;
581
+ try {
582
+ rules = sheet.cssRules;
583
+ } catch {
584
+ return "";
585
+ }
586
+ let text = "";
587
+ for (const rule of Array.from(rules)) {
588
+ if (rule instanceof CSSImportRule) {
589
+ if (rule.styleSheet) text += serializeSheet(rule.styleSheet);
590
+ continue;
591
+ }
592
+ text += `${rule.cssText}
593
+ `;
594
+ }
595
+ return text;
596
+ }
597
+ function isCanvasBlank(ctx, width, height) {
598
+ try {
599
+ const stepX = Math.max(1, Math.floor(width / 8));
600
+ const stepY = Math.max(1, Math.floor(height / 8));
601
+ for (let y = 0; y < height; y += stepY) {
602
+ for (let x = 0; x < width; x += stepX) {
603
+ if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;
604
+ }
605
+ }
606
+ return true;
607
+ } catch {
608
+ return false;
609
+ }
610
+ }
611
+ function isCrossOriginUrl(raw, pageOrigin) {
612
+ if (!raw || raw.startsWith("data:") || raw.startsWith("blob:")) return false;
613
+ try {
614
+ const resolved = new URL(raw, typeof location !== "undefined" ? location.href : "http://localhost/");
615
+ return Boolean(pageOrigin) && resolved.origin !== pageOrigin;
616
+ } catch {
617
+ return true;
618
+ }
619
+ }
620
+ function maskElement(el) {
621
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
622
+ el.value = "";
623
+ el.setAttribute("value", "");
624
+ el.setAttribute("placeholder", "\u2022\u2022\u2022\u2022");
625
+ }
626
+ el.textContent = el.children.length === 0 ? "\u2022\u2022\u2022\u2022" : el.textContent;
627
+ el.setAttribute(
628
+ "style",
629
+ `${el.getAttribute("style") ?? ""};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`
630
+ );
631
+ el.setAttribute("data-mushi-masked", "true");
632
+ }
633
+ var XML_INVALID_CHARS, XML_ATTRIBUTE_NAME, MAX_INLINED_MEDIA, MAX_INLINED_BYTES, MEDIA_SELECTOR, DEFAULT_REDACT_SELECTORS, ANIMATED_PROPERTIES, MAX_BACKGROUND_URLS, MAX_BACKGROUND_BYTES, MAX_BACKGROUND_IMAGE_BYTES, CSS_URL, PINNABLE_DISPLAY, BLOCK_FLOW, MAX_IMAGE_SIDE, SOURCE_ATTRIBUTES, SHEET_FETCH_TIMEOUT_MS, FREEZE_MOTION_CSS;
634
+ var init_screenshot_dom = __esm({
635
+ "src/capture/screenshot-dom.ts"() {
636
+ init_screenshot();
637
+ XML_INVALID_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
638
+ XML_ATTRIBUTE_NAME = /^[A-Za-z_][\w.:-]*$/;
639
+ MAX_INLINED_MEDIA = 60;
640
+ MAX_INLINED_BYTES = 12 * 1024 * 1024;
641
+ MEDIA_SELECTOR = "img, video, canvas, iframe, object, embed";
642
+ DEFAULT_REDACT_SELECTORS = ["[data-mushi-redact]"];
643
+ ANIMATED_PROPERTIES = [
644
+ "transform",
645
+ "translate",
646
+ "scale",
647
+ "rotate",
648
+ "opacity",
649
+ "visibility",
650
+ "clip-path",
651
+ "object-position",
652
+ "background-position",
653
+ "left",
654
+ "top",
655
+ "width",
656
+ "height",
657
+ "color",
658
+ "background-color"
659
+ ];
660
+ MAX_BACKGROUND_URLS = 40;
661
+ MAX_BACKGROUND_BYTES = 6 * 1024 * 1024;
662
+ MAX_BACKGROUND_IMAGE_BYTES = 2 * 1024 * 1024;
663
+ CSS_URL = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi;
664
+ PINNABLE_DISPLAY = /^(block|flow-root|flex|grid|list-item|inline-block|inline-flex|inline-grid|table)$/;
665
+ BLOCK_FLOW = /^(block|flow-root|list-item)$/;
666
+ MAX_IMAGE_SIDE = 2048;
667
+ SOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "srcset", "sizes", "poster", "data", "loading", "decoding"]);
668
+ SHEET_FETCH_TIMEOUT_MS = 2500;
669
+ FREEZE_MOTION_CSS = "*,*::before,*::after{animation:none!important;transition:none!important}";
670
+ }
671
+ });
672
+
673
+ // src/capture/screenshot.ts
674
+ function createScreenshotCapture(options = {}) {
675
+ let activeOptions = options;
676
+ const fail = (reason) => {
677
+ activeOptions.onFailed?.(reason);
678
+ emitScreenshotFailed(reason);
679
+ };
680
+ async function take() {
681
+ try {
682
+ if (typeof document === "undefined") return null;
683
+ const { captureDomScreenshot: captureDomScreenshot2 } = await Promise.resolve().then(() => (init_screenshot_dom(), screenshot_dom_exports));
684
+ return await captureDomScreenshot2(activeOptions.privacy, fail);
685
+ } catch {
686
+ fail("error");
687
+ return null;
688
+ }
689
+ }
690
+ return {
691
+ take,
692
+ updateOptions(nextOptions) {
693
+ activeOptions = nextOptions;
694
+ }
695
+ };
696
+ }
697
+ function emitScreenshotFailed(reason) {
698
+ try {
699
+ document.dispatchEvent(new CustomEvent("mushi:screenshot_failed", { detail: { reason }, bubbles: false }));
700
+ } catch {
701
+ }
702
+ }
703
+ var ALWAYS_REDACT_SELECTORS;
704
+ var init_screenshot = __esm({
705
+ "src/capture/screenshot.ts"() {
706
+ ALWAYS_REDACT_SELECTORS = 'input[type="password"],input[autocomplete^="cc-"],[data-private],[data-mushi-mask]';
707
+ }
708
+ });
6
709
  var DEFAULT_INTERNAL_URL_MATCHERS = [
7
710
  /\/v1\/sdk(?:\/|$)/,
8
711
  /\/v1\/reports(?:\/|$)/,
@@ -313,36 +1016,51 @@ function createConsoleCapture() {
313
1016
  const originals = {};
314
1017
  const wrappers = {};
315
1018
  const levels = ["log", "warn", "error", "info", "debug"];
1019
+ const str = (arg) => {
1020
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
1021
+ try {
1022
+ return typeof arg === "string" ? arg : JSON.stringify(arg);
1023
+ } catch {
1024
+ return String(arg);
1025
+ }
1026
+ };
1027
+ const record = (level, message, err, extra) => {
1028
+ const entry = { level, message: message.slice(0, MAX_MESSAGE_LENGTH), timestamp: Date.now(), ...extra };
1029
+ if (err instanceof Error && err.stack) entry.stack = err.stack.slice(0, 1e3);
1030
+ entries.push(entry);
1031
+ if (entries.length > MAX_ENTRIES2) entries.shift();
1032
+ };
316
1033
  for (const level of levels) {
317
1034
  const original = console[level];
318
1035
  originals[level] = original;
319
1036
  const wrapper = (...args) => {
320
- const message = args.map((arg) => {
321
- try {
322
- return typeof arg === "string" ? arg : JSON.stringify(arg);
323
- } catch {
324
- return String(arg);
325
- }
326
- }).join(" ").slice(0, MAX_MESSAGE_LENGTH);
327
1037
  const correlationId = getActiveCorrelationId();
328
- const entry = {
1038
+ record(
329
1039
  level,
330
- message,
331
- timestamp: Date.now(),
332
- ...correlationId ? { correlationId } : {}
333
- };
334
- if (level === "error" && args[0] instanceof Error) {
335
- entry.stack = args[0].stack?.slice(0, 1e3);
336
- }
337
- entries.push(entry);
338
- if (entries.length > MAX_ENTRIES2) {
339
- entries.shift();
340
- }
1040
+ args.map(str).join(" "),
1041
+ level === "error" ? args.find((a) => a instanceof Error) : void 0,
1042
+ correlationId ? { correlationId } : void 0
1043
+ );
341
1044
  original.call(console, ...args);
342
1045
  };
343
1046
  wrappers[level] = wrapper;
344
1047
  console[level] = wrapper;
345
1048
  }
1049
+ const onUncaught = (event) => {
1050
+ if (event.type === "unhandledrejection") {
1051
+ const reason = event.reason;
1052
+ record("error", `Unhandled rejection: ${str(reason)}`, reason);
1053
+ } else {
1054
+ const e = event;
1055
+ const where = e.filename ? ` (${e.filename}:${e.lineno}:${e.colno})` : "";
1056
+ record("error", `Uncaught ${str(e.error ?? (e.message || "error"))}${where}`, e.error);
1057
+ }
1058
+ };
1059
+ const canListen = typeof window !== "undefined" && typeof window.addEventListener === "function";
1060
+ if (canListen) {
1061
+ window.addEventListener("error", onUncaught);
1062
+ window.addEventListener("unhandledrejection", onUncaught);
1063
+ }
346
1064
  return {
347
1065
  getEntries() {
348
1066
  return [...entries];
@@ -356,261 +1074,16 @@ function createConsoleCapture() {
356
1074
  console[level] = originals[level];
357
1075
  }
358
1076
  }
359
- }
360
- };
361
- }
362
-
363
- // src/capture/screenshot.ts
364
- function createScreenshotCapture(options = {}) {
365
- let activeOptions = options;
366
- async function take() {
367
- try {
368
- if (typeof document === "undefined") return null;
369
- const canvas = document.createElement("canvas");
370
- const ctx = canvas.getContext("2d", { willReadFrequently: true });
371
- if (!ctx) {
372
- activeOptions.onFailed?.("unsupported");
373
- emitScreenshotFailed("unsupported");
374
- return null;
1077
+ if (canListen) {
1078
+ window.removeEventListener("error", onUncaught);
1079
+ window.removeEventListener("unhandledrejection", onUncaught);
375
1080
  }
376
- const width = window.innerWidth;
377
- const height = window.innerHeight;
378
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
379
- canvas.width = width * dpr;
380
- canvas.height = height * dpr;
381
- ctx.scale(dpr, dpr);
382
- const safeDocument = buildPrivacySafeDocument(activeOptions.privacy);
383
- const svgData = `
384
- <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
385
- <foreignObject width="100%" height="100%">
386
- <div xmlns="http://www.w3.org/1999/xhtml">
387
- ${new XMLSerializer().serializeToString(safeDocument)}
388
- </div>
389
- </foreignObject>
390
- </svg>
391
- `;
392
- const img = new Image();
393
- const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgData)}`;
394
- let cspBlocked = false;
395
- const onViolation = (e) => {
396
- const v = e;
397
- if (/^img-src|^default-src/.test(v.violatedDirective ?? "") && /^data/.test(v.blockedURI ?? "")) cspBlocked = true;
398
- };
399
- document.addEventListener("securitypolicyviolation", onViolation);
400
- return new Promise((resolve) => {
401
- let settled = false;
402
- const settle = (value, reason) => {
403
- if (settled) return;
404
- settled = true;
405
- clearTimeout(timer);
406
- document.removeEventListener("securitypolicyviolation", onViolation);
407
- if (reason) {
408
- activeOptions.onFailed?.(reason);
409
- emitScreenshotFailed(reason);
410
- }
411
- resolve(value);
412
- };
413
- const timer = setTimeout(() => settle(null, "timeout"), 5e3);
414
- img.onload = () => {
415
- try {
416
- ctx.drawImage(img, 0, 0, width, height);
417
- if (isCanvasBlank(ctx, width, height)) {
418
- settle(null, "unsupported");
419
- return;
420
- }
421
- settle(canvas.toDataURL("image/jpeg", 0.7));
422
- } catch {
423
- settle(null, "taint");
424
- }
425
- };
426
- img.onerror = () => setTimeout(() => settle(null, cspBlocked ? "csp" : "error"), 0);
427
- img.src = url;
428
- });
429
- } catch {
430
- activeOptions.onFailed?.("error");
431
- emitScreenshotFailed("error");
432
- return null;
433
- }
434
- }
435
- return {
436
- take,
437
- updateOptions(nextOptions) {
438
- activeOptions = nextOptions;
439
1081
  }
440
1082
  };
441
1083
  }
442
- function emitScreenshotFailed(reason) {
443
- try {
444
- document.dispatchEvent(new CustomEvent("mushi:screenshot_failed", { detail: { reason }, bubbles: false }));
445
- } catch {
446
- }
447
- }
448
- var ALWAYS_REDACT_SELECTORS = 'input[type="password"],input[autocomplete^="cc-"],[data-private],[data-mushi-mask]';
449
- var DEFAULT_REDACT_SELECTORS = ["[data-mushi-redact]"];
450
- function buildPrivacySafeDocument(privacy) {
451
- const clone = document.documentElement.cloneNode(true);
452
- clone.querySelector("#mushi-mushi-widget")?.remove();
453
- stripTaintSources(clone);
454
- inlineDocumentStyles(clone);
455
- freezeMotion(clone);
456
- fillViewport(clone);
457
- const redactSelectors = [
458
- ALWAYS_REDACT_SELECTORS,
459
- ...privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS
460
- ];
461
- for (const selector of redactSelectors) {
462
- for (const el of safeQueryAll(clone, selector)) {
463
- redactElement(el);
464
- }
465
- }
466
- for (const selector of privacy?.blockSelectors ?? []) {
467
- for (const el of safeQueryAll(clone, selector)) {
468
- el.remove();
469
- }
470
- }
471
- for (const selector of privacy?.maskSelectors ?? []) {
472
- for (const el of safeQueryAll(clone, selector)) {
473
- maskElement(el);
474
- }
475
- }
476
- return clone;
477
- }
478
- function safeQueryAll(root, selector) {
479
- try {
480
- return Array.from(root.querySelectorAll(selector));
481
- } catch {
482
- return [];
483
- }
484
- }
485
- function redactElement(el) {
486
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
487
- el.value = "";
488
- el.setAttribute("value", "");
489
- }
490
- el.textContent = "";
491
- el.setAttribute(
492
- "style",
493
- `${el.getAttribute("style") ?? ""};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`
494
- );
495
- el.setAttribute("data-mushi-redacted", "true");
496
- while (el.firstChild) el.removeChild(el.firstChild);
497
- }
498
- function stripTaintSources(root) {
499
- const pageOrigin = typeof location !== "undefined" ? location.origin : "";
500
- for (const el of root.querySelectorAll("img, video, iframe, object, embed, picture")) {
501
- el.remove();
502
- }
503
- for (const link of root.querySelectorAll('link[rel="stylesheet"], link[as="style"]')) {
504
- link.remove();
505
- }
506
- for (const styleEl of root.querySelectorAll("style")) {
507
- const cleaned = stripCssUrlRefs(styleEl.textContent ?? "", pageOrigin);
508
- if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;
509
- }
510
- for (const el of root.querySelectorAll("[style]")) {
511
- const s = el.getAttribute("style");
512
- if (!s) continue;
513
- const cleaned = stripCssUrlRefs(s, pageOrigin);
514
- if (cleaned !== s) el.setAttribute("style", cleaned);
515
- }
516
- for (const script of root.querySelectorAll("script")) {
517
- script.remove();
518
- }
519
- }
520
- function stripCssUrlRefs(css, pageOrigin) {
521
- return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (_match, _q, href) => {
522
- const trimmed = href.trim();
523
- if (!trimmed || trimmed.startsWith("data:") || trimmed.startsWith("#")) return _match;
524
- if (isCrossOriginUrl(trimmed, pageOrigin)) return "none";
525
- return _match;
526
- });
527
- }
528
- function inlineDocumentStyles(clone) {
529
- const pageOrigin = typeof location !== "undefined" ? location.origin : "";
530
- const chunks = [];
531
- const sheets = [
532
- ...Array.from(document.styleSheets),
533
- ...document.adoptedStyleSheets ?? []
534
- ];
535
- for (const sheet of sheets) {
536
- const owner = sheet.ownerNode;
537
- if (owner instanceof Element && owner.tagName === "STYLE") continue;
538
- chunks.push(serializeSheet(sheet));
539
- }
540
- const css = stripCssUrlRefs(chunks.filter(Boolean).join("\n"), pageOrigin);
541
- if (!css) return;
542
- const styleEl = document.createElement("style");
543
- styleEl.textContent = css;
544
- (clone.querySelector("head") ?? clone).appendChild(styleEl);
545
- }
546
- var FREEZE_MOTION_CSS = "*,*::before,*::after{animation:none!important;transition:none!important}";
547
- function fillViewport(clone) {
548
- const clear = (c) => !c || c === "transparent" || /^rgba\(.*,\s*0\)$/.test(c);
549
- let bg = getComputedStyle(document.documentElement).backgroundColor;
550
- if (clear(bg) && document.body) bg = getComputedStyle(document.body).backgroundColor;
551
- const root = clone;
552
- root.style.setProperty("background-color", clear(bg) ? "Canvas" : bg);
553
- root.style.setProperty("min-height", `${window.innerHeight}px`);
554
- }
555
- function freezeMotion(clone) {
556
- const styleEl = document.createElement("style");
557
- styleEl.textContent = FREEZE_MOTION_CSS;
558
- (clone.querySelector("head") ?? clone).appendChild(styleEl);
559
- }
560
- function serializeSheet(sheet) {
561
- let rules;
562
- try {
563
- rules = sheet.cssRules;
564
- } catch {
565
- return "";
566
- }
567
- let text = "";
568
- for (const rule of Array.from(rules)) {
569
- if (rule instanceof CSSImportRule) {
570
- if (rule.styleSheet) text += serializeSheet(rule.styleSheet);
571
- continue;
572
- }
573
- text += `${rule.cssText}
574
- `;
575
- }
576
- return text;
577
- }
578
- function isCanvasBlank(ctx, width, height) {
579
- try {
580
- const stepX = Math.max(1, Math.floor(width / 8));
581
- const stepY = Math.max(1, Math.floor(height / 8));
582
- for (let y = 0; y < height; y += stepY) {
583
- for (let x = 0; x < width; x += stepX) {
584
- if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;
585
- }
586
- }
587
- return true;
588
- } catch {
589
- return false;
590
- }
591
- }
592
- function isCrossOriginUrl(raw, pageOrigin) {
593
- if (!raw || raw.startsWith("data:") || raw.startsWith("blob:")) return false;
594
- try {
595
- const resolved = new URL(raw, typeof location !== "undefined" ? location.href : "http://localhost/");
596
- return Boolean(pageOrigin) && resolved.origin !== pageOrigin;
597
- } catch {
598
- return true;
599
- }
600
- }
601
- function maskElement(el) {
602
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
603
- el.value = "";
604
- el.setAttribute("value", "");
605
- el.setAttribute("placeholder", "\u2022\u2022\u2022\u2022");
606
- }
607
- el.textContent = el.children.length === 0 ? "\u2022\u2022\u2022\u2022" : el.textContent;
608
- el.setAttribute(
609
- "style",
610
- `${el.getAttribute("style") ?? ""};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`
611
- );
612
- el.setAttribute("data-mushi-masked", "true");
613
- }
1084
+
1085
+ // src/capture/index.ts
1086
+ init_screenshot();
614
1087
 
615
1088
  // src/capture/performance.ts
616
1089
  var INP_DURATION_THRESHOLD_MS = 40;