@mushi-mushi/web 1.26.0 → 1.27.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.
- package/README.md +1 -1
- package/SECURITY.md +49 -0
- package/dist/headless.cjs +1206 -0
- package/dist/headless.cjs.map +1 -0
- package/dist/headless.d.cts +88 -0
- package/dist/headless.d.ts +88 -0
- package/dist/headless.js +1194 -0
- package/dist/headless.js.map +1 -0
- package/dist/index.cjs +228 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -62
- package/dist/index.d.ts +3 -62
- package/dist/index.js +229 -75
- package/dist/index.js.map +1 -1
- package/dist/mushi.loader.global.js +439 -439
- package/dist/mushi.loader.global.js.map +1 -1
- package/dist/otel.cjs +60 -0
- package/dist/otel.cjs.map +1 -0
- package/dist/otel.d.cts +80 -0
- package/dist/otel.d.ts +80 -0
- package/dist/otel.js +58 -0
- package/dist/otel.js.map +1 -0
- package/dist/timeline-BuqAn2FH.d.cts +63 -0
- package/dist/timeline-BuqAn2FH.d.ts +63 -0
- package/package.json +25 -3
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@mushi-mushi/core');
|
|
4
|
+
|
|
5
|
+
// src/headless.ts
|
|
6
|
+
var DEFAULT_INTERNAL_URL_MATCHERS = [
|
|
7
|
+
/\/v1\/sdk(?:\/|$)/,
|
|
8
|
+
/\/v1\/reports(?:\/|$)/,
|
|
9
|
+
/\/v1\/notifications(?:\/|$)/,
|
|
10
|
+
/\/v1\/reputation(?:\/|$)/
|
|
11
|
+
];
|
|
12
|
+
function getRequestUrl(input) {
|
|
13
|
+
if (typeof input === "string") return input;
|
|
14
|
+
if (input instanceof URL) return input.href;
|
|
15
|
+
return input.url;
|
|
16
|
+
}
|
|
17
|
+
function getInternalRequestKind(input, init) {
|
|
18
|
+
const marker = init?.[core.MUSHI_INTERNAL_INIT_MARKER];
|
|
19
|
+
if (marker) return marker;
|
|
20
|
+
const initHeader = readHeader(init?.headers, core.MUSHI_INTERNAL_HEADER);
|
|
21
|
+
if (initHeader) return initHeader;
|
|
22
|
+
if (typeof Request !== "undefined" && input instanceof Request) {
|
|
23
|
+
const requestHeader = input.headers.get(core.MUSHI_INTERNAL_HEADER);
|
|
24
|
+
if (requestHeader) return requestHeader;
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
function shouldIgnoreMushiUrl(url, options = {}) {
|
|
29
|
+
const matchers = [...DEFAULT_INTERNAL_URL_MATCHERS, ...options.ignoreUrls ?? []];
|
|
30
|
+
if (matchers.some((matcher) => matchesUrl(url, matcher))) return true;
|
|
31
|
+
const endpoint = normalizeUrlPrefix(options.apiEndpoint);
|
|
32
|
+
return endpoint ? normalizeComparableUrl(url).startsWith(endpoint) : false;
|
|
33
|
+
}
|
|
34
|
+
function matchesUrl(url, matcher) {
|
|
35
|
+
if (typeof matcher === "string") {
|
|
36
|
+
return normalizeComparableUrl(url).includes(matcher);
|
|
37
|
+
}
|
|
38
|
+
matcher.lastIndex = 0;
|
|
39
|
+
return matcher.test(url);
|
|
40
|
+
}
|
|
41
|
+
function normalizeUrlPrefix(url) {
|
|
42
|
+
if (!url) return null;
|
|
43
|
+
const normalized = normalizeComparableUrl(url);
|
|
44
|
+
let end = normalized.length;
|
|
45
|
+
while (end > 0 && normalized.charCodeAt(end - 1) === 47) end--;
|
|
46
|
+
return normalized.slice(0, end);
|
|
47
|
+
}
|
|
48
|
+
function normalizeComparableUrl(url) {
|
|
49
|
+
try {
|
|
50
|
+
return new URL(url, typeof location !== "undefined" ? location.href : "http://localhost").href;
|
|
51
|
+
} catch {
|
|
52
|
+
return url;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function readHeader(headers, name) {
|
|
56
|
+
if (!headers) return null;
|
|
57
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
58
|
+
return headers.get(name);
|
|
59
|
+
}
|
|
60
|
+
if (Array.isArray(headers)) {
|
|
61
|
+
const found = headers.find(([key]) => key.toLowerCase() === name.toLowerCase());
|
|
62
|
+
return found?.[1] ?? null;
|
|
63
|
+
}
|
|
64
|
+
const record = headers;
|
|
65
|
+
return record[name] ?? record[name.toLowerCase()] ?? null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/capture/network.ts
|
|
69
|
+
var MAX_ENTRIES = 30;
|
|
70
|
+
var TRACEPARENT_VERSION = "00";
|
|
71
|
+
function generateTraceparent() {
|
|
72
|
+
const traceBytes = crypto.getRandomValues(new Uint8Array(16));
|
|
73
|
+
const spanBytes = crypto.getRandomValues(new Uint8Array(8));
|
|
74
|
+
const toHex = (bytes) => Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
75
|
+
const traceId = toHex(traceBytes);
|
|
76
|
+
const spanId = toHex(spanBytes);
|
|
77
|
+
return {
|
|
78
|
+
traceparent: `${TRACEPARENT_VERSION}-${traceId}-${spanId}-01`,
|
|
79
|
+
traceId,
|
|
80
|
+
spanId
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function matchesCorsUrls(url, corsUrls) {
|
|
84
|
+
for (const pattern of corsUrls) {
|
|
85
|
+
if (typeof pattern === "string") {
|
|
86
|
+
if (url.includes(pattern)) return true;
|
|
87
|
+
} else {
|
|
88
|
+
if (pattern.test(url)) return true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
var _activeCorrelationStack = [];
|
|
94
|
+
function getActiveCorrelationId() {
|
|
95
|
+
return _activeCorrelationStack[_activeCorrelationStack.length - 1];
|
|
96
|
+
}
|
|
97
|
+
function generateCorrelationId() {
|
|
98
|
+
const bytes = crypto.getRandomValues(new Uint8Array(4));
|
|
99
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
100
|
+
}
|
|
101
|
+
function createNetworkCapture(options = {}) {
|
|
102
|
+
const entries = [];
|
|
103
|
+
const originalFetch = globalThis.fetch;
|
|
104
|
+
const OriginalXHR = typeof XMLHttpRequest !== "undefined" ? XMLHttpRequest : null;
|
|
105
|
+
const originalXhrOpen = OriginalXHR ? XMLHttpRequest.prototype.open : null;
|
|
106
|
+
const originalXhrSend = OriginalXHR ? XMLHttpRequest.prototype.send : null;
|
|
107
|
+
const originalXhrSetRequestHeader = OriginalXHR ? XMLHttpRequest.prototype.setRequestHeader : null;
|
|
108
|
+
let activeOptions = options;
|
|
109
|
+
let fetchWrapper;
|
|
110
|
+
globalThis.fetch = fetchWrapper = async function mushiFetchInterceptor(input, init) {
|
|
111
|
+
const startTime = Date.now();
|
|
112
|
+
const method = init?.method?.toUpperCase() ?? "GET";
|
|
113
|
+
const url = getRequestUrl(input);
|
|
114
|
+
const internalKind = getInternalRequestKind(input, init);
|
|
115
|
+
const shouldRecord = !internalKind && !shouldIgnoreMushiUrl(url, activeOptions);
|
|
116
|
+
const correlationId = shouldRecord ? generateCorrelationId() : void 0;
|
|
117
|
+
let traceId;
|
|
118
|
+
let patchedInit = init;
|
|
119
|
+
const tp = activeOptions.tracePropagation;
|
|
120
|
+
if (shouldRecord && tp?.enabled && tp.corsUrls?.length && matchesCorsUrls(url, tp.corsUrls)) {
|
|
121
|
+
const { traceparent, traceId: tid } = generateTraceparent();
|
|
122
|
+
traceId = tid;
|
|
123
|
+
const existingHeaders = init?.headers ? new Headers(init.headers) : new Headers();
|
|
124
|
+
existingHeaders.set("traceparent", traceparent);
|
|
125
|
+
if (activeOptions.sessionId) {
|
|
126
|
+
existingHeaders.set("x-mushi-session", activeOptions.sessionId);
|
|
127
|
+
}
|
|
128
|
+
patchedInit = { ...init, headers: existingHeaders };
|
|
129
|
+
}
|
|
130
|
+
if (correlationId) _activeCorrelationStack.push(correlationId);
|
|
131
|
+
try {
|
|
132
|
+
const response = await originalFetch.call(globalThis, input, patchedInit);
|
|
133
|
+
if (shouldRecord) {
|
|
134
|
+
addEntry({
|
|
135
|
+
method,
|
|
136
|
+
url: truncateUrl(url),
|
|
137
|
+
status: response.status,
|
|
138
|
+
duration: Date.now() - startTime,
|
|
139
|
+
timestamp: startTime,
|
|
140
|
+
captureMethod: "fetch",
|
|
141
|
+
...traceId ? { traceId } : {},
|
|
142
|
+
...correlationId ? { correlationId } : {}
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return response;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (shouldRecord) {
|
|
148
|
+
addEntry({
|
|
149
|
+
method,
|
|
150
|
+
url: truncateUrl(url),
|
|
151
|
+
status: 0,
|
|
152
|
+
duration: Date.now() - startTime,
|
|
153
|
+
timestamp: startTime,
|
|
154
|
+
error: error instanceof Error ? error.message : "Network error",
|
|
155
|
+
captureMethod: "fetch",
|
|
156
|
+
...traceId ? { traceId } : {},
|
|
157
|
+
...correlationId ? { correlationId } : {}
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
throw error;
|
|
161
|
+
} finally {
|
|
162
|
+
if (correlationId) {
|
|
163
|
+
const idx = _activeCorrelationStack.lastIndexOf(correlationId);
|
|
164
|
+
if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const xhrStateMap = typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : null;
|
|
169
|
+
if (OriginalXHR && originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader && xhrStateMap) {
|
|
170
|
+
const _originalOpen = originalXhrOpen;
|
|
171
|
+
XMLHttpRequest.prototype.open = function mushiXhrOpen(...args) {
|
|
172
|
+
const [method, url] = args;
|
|
173
|
+
const urlStr = typeof url === "string" ? url : String(url);
|
|
174
|
+
const shouldRecord = !shouldIgnoreMushiUrl(urlStr, activeOptions);
|
|
175
|
+
const correlationId = shouldRecord ? generateCorrelationId() : void 0;
|
|
176
|
+
let traceId;
|
|
177
|
+
let storedTraceparent;
|
|
178
|
+
const tp = activeOptions.tracePropagation;
|
|
179
|
+
if (shouldRecord && tp?.enabled && tp.corsUrls?.length && matchesCorsUrls(urlStr, tp.corsUrls)) {
|
|
180
|
+
const generated = generateTraceparent();
|
|
181
|
+
traceId = generated.traceId;
|
|
182
|
+
storedTraceparent = generated.traceparent;
|
|
183
|
+
}
|
|
184
|
+
const _prevXhrState = xhrStateMap.get(this);
|
|
185
|
+
if (_prevXhrState?._listener) {
|
|
186
|
+
this.removeEventListener("readystatechange", _prevXhrState._listener);
|
|
187
|
+
}
|
|
188
|
+
xhrStateMap.set(this, {
|
|
189
|
+
method: String(method).toUpperCase(),
|
|
190
|
+
url: truncateUrl(urlStr),
|
|
191
|
+
startTime: 0,
|
|
192
|
+
// set in .send()
|
|
193
|
+
shouldRecord,
|
|
194
|
+
...traceId ? { traceId } : {},
|
|
195
|
+
...correlationId ? { correlationId } : {},
|
|
196
|
+
// Attach the traceparent string as an extra prop for injection in .send().
|
|
197
|
+
...storedTraceparent ? { _traceparent: storedTraceparent } : {}
|
|
198
|
+
});
|
|
199
|
+
_originalOpen.apply(this, args);
|
|
200
|
+
};
|
|
201
|
+
XMLHttpRequest.prototype.send = function mushiXhrSend(body) {
|
|
202
|
+
const state = xhrStateMap.get(this);
|
|
203
|
+
if (state) {
|
|
204
|
+
state.startTime = Date.now();
|
|
205
|
+
const xhrTraceparent = state._traceparent;
|
|
206
|
+
if (xhrTraceparent) {
|
|
207
|
+
originalXhrSetRequestHeader.call(this, "traceparent", xhrTraceparent);
|
|
208
|
+
if (activeOptions.sessionId) {
|
|
209
|
+
originalXhrSetRequestHeader.call(this, "x-mushi-session", activeOptions.sessionId);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (state.correlationId) _activeCorrelationStack.push(state.correlationId);
|
|
213
|
+
const _readystateHandler = () => {
|
|
214
|
+
if (this.readyState !== 4) return;
|
|
215
|
+
if (state.shouldRecord) {
|
|
216
|
+
const duration = Date.now() - state.startTime;
|
|
217
|
+
const entry = {
|
|
218
|
+
method: state.method,
|
|
219
|
+
url: state.url,
|
|
220
|
+
status: this.status,
|
|
221
|
+
duration,
|
|
222
|
+
timestamp: state.startTime,
|
|
223
|
+
captureMethod: "xhr",
|
|
224
|
+
...state.traceId ? { traceId: state.traceId } : {},
|
|
225
|
+
...state.correlationId ? { correlationId: state.correlationId } : {}
|
|
226
|
+
};
|
|
227
|
+
if (this.status === 0) {
|
|
228
|
+
entry.error = "XHR network error or aborted";
|
|
229
|
+
}
|
|
230
|
+
addEntry(entry);
|
|
231
|
+
}
|
|
232
|
+
if (state.correlationId) {
|
|
233
|
+
const idx = _activeCorrelationStack.lastIndexOf(state.correlationId);
|
|
234
|
+
if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
state._listener = _readystateHandler;
|
|
238
|
+
this.addEventListener("readystatechange", _readystateHandler);
|
|
239
|
+
}
|
|
240
|
+
originalXhrSend.call(this, body);
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const xhrOpenWrapper = OriginalXHR ? XMLHttpRequest.prototype.open : null;
|
|
244
|
+
const xhrSendWrapper = OriginalXHR ? XMLHttpRequest.prototype.send : null;
|
|
245
|
+
function addEntry(entry) {
|
|
246
|
+
entries.push(entry);
|
|
247
|
+
if (entries.length > MAX_ENTRIES) {
|
|
248
|
+
entries.shift();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
getEntries() {
|
|
253
|
+
return [...entries];
|
|
254
|
+
},
|
|
255
|
+
clear() {
|
|
256
|
+
entries.length = 0;
|
|
257
|
+
},
|
|
258
|
+
updateOptions(nextOptions) {
|
|
259
|
+
activeOptions = nextOptions;
|
|
260
|
+
},
|
|
261
|
+
destroy() {
|
|
262
|
+
if (globalThis.fetch === fetchWrapper) {
|
|
263
|
+
globalThis.fetch = originalFetch;
|
|
264
|
+
}
|
|
265
|
+
if (OriginalXHR && originalXhrOpen && originalXhrSend) {
|
|
266
|
+
if (xhrOpenWrapper && XMLHttpRequest.prototype.open === xhrOpenWrapper) {
|
|
267
|
+
XMLHttpRequest.prototype.open = originalXhrOpen;
|
|
268
|
+
}
|
|
269
|
+
if (xhrSendWrapper && XMLHttpRequest.prototype.send === xhrSendWrapper) {
|
|
270
|
+
XMLHttpRequest.prototype.send = originalXhrSend;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function truncateUrl(url) {
|
|
277
|
+
const scrubbed = core.scrubUrl(url);
|
|
278
|
+
try {
|
|
279
|
+
const parsed = new URL(scrubbed);
|
|
280
|
+
const path = parsed.pathname + parsed.search;
|
|
281
|
+
if (path.length > 200) {
|
|
282
|
+
return parsed.origin + path.slice(0, 200) + "...";
|
|
283
|
+
}
|
|
284
|
+
return parsed.origin + path;
|
|
285
|
+
} catch {
|
|
286
|
+
return scrubbed.slice(0, 200);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/capture/console.ts
|
|
291
|
+
var MAX_ENTRIES2 = 50;
|
|
292
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
293
|
+
function createConsoleCapture() {
|
|
294
|
+
const entries = [];
|
|
295
|
+
const originals = {};
|
|
296
|
+
const wrappers = {};
|
|
297
|
+
const levels = ["log", "warn", "error", "info", "debug"];
|
|
298
|
+
for (const level of levels) {
|
|
299
|
+
const original = console[level];
|
|
300
|
+
originals[level] = original;
|
|
301
|
+
const wrapper = (...args) => {
|
|
302
|
+
const message = args.map((arg) => {
|
|
303
|
+
try {
|
|
304
|
+
return typeof arg === "string" ? arg : JSON.stringify(arg);
|
|
305
|
+
} catch {
|
|
306
|
+
return String(arg);
|
|
307
|
+
}
|
|
308
|
+
}).join(" ").slice(0, MAX_MESSAGE_LENGTH);
|
|
309
|
+
const correlationId = getActiveCorrelationId();
|
|
310
|
+
const entry = {
|
|
311
|
+
level,
|
|
312
|
+
message,
|
|
313
|
+
timestamp: Date.now(),
|
|
314
|
+
...correlationId ? { correlationId } : {}
|
|
315
|
+
};
|
|
316
|
+
if (level === "error" && args[0] instanceof Error) {
|
|
317
|
+
entry.stack = args[0].stack?.slice(0, 1e3);
|
|
318
|
+
}
|
|
319
|
+
entries.push(entry);
|
|
320
|
+
if (entries.length > MAX_ENTRIES2) {
|
|
321
|
+
entries.shift();
|
|
322
|
+
}
|
|
323
|
+
original.call(console, ...args);
|
|
324
|
+
};
|
|
325
|
+
wrappers[level] = wrapper;
|
|
326
|
+
console[level] = wrapper;
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
getEntries() {
|
|
330
|
+
return [...entries];
|
|
331
|
+
},
|
|
332
|
+
clear() {
|
|
333
|
+
entries.length = 0;
|
|
334
|
+
},
|
|
335
|
+
destroy() {
|
|
336
|
+
for (const level of levels) {
|
|
337
|
+
if (originals[level] && console[level] === wrappers[level]) {
|
|
338
|
+
console[level] = originals[level];
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// src/capture/screenshot.ts
|
|
346
|
+
function createScreenshotCapture(options = {}) {
|
|
347
|
+
let activeOptions = options;
|
|
348
|
+
async function take() {
|
|
349
|
+
try {
|
|
350
|
+
if (typeof document === "undefined") return null;
|
|
351
|
+
const canvas = document.createElement("canvas");
|
|
352
|
+
const ctx = canvas.getContext("2d");
|
|
353
|
+
if (!ctx) return null;
|
|
354
|
+
const width = window.innerWidth;
|
|
355
|
+
const height = window.innerHeight;
|
|
356
|
+
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
|
357
|
+
canvas.width = width * dpr;
|
|
358
|
+
canvas.height = height * dpr;
|
|
359
|
+
ctx.scale(dpr, dpr);
|
|
360
|
+
const safeDocument = buildPrivacySafeDocument(activeOptions.privacy);
|
|
361
|
+
const svgData = `
|
|
362
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
|
|
363
|
+
<foreignObject width="100%" height="100%">
|
|
364
|
+
<div xmlns="http://www.w3.org/1999/xhtml">
|
|
365
|
+
${new XMLSerializer().serializeToString(safeDocument)}
|
|
366
|
+
</div>
|
|
367
|
+
</foreignObject>
|
|
368
|
+
</svg>
|
|
369
|
+
`;
|
|
370
|
+
const img = new Image();
|
|
371
|
+
const blob = new Blob([svgData], { type: "image/svg+xml;charset=utf-8" });
|
|
372
|
+
const url = URL.createObjectURL(blob);
|
|
373
|
+
return new Promise((resolve) => {
|
|
374
|
+
let settled = false;
|
|
375
|
+
const settle = (value, reason) => {
|
|
376
|
+
if (settled) return;
|
|
377
|
+
settled = true;
|
|
378
|
+
clearTimeout(timer);
|
|
379
|
+
URL.revokeObjectURL(url);
|
|
380
|
+
if (reason) {
|
|
381
|
+
activeOptions.onFailed?.(reason);
|
|
382
|
+
emitScreenshotFailed(reason);
|
|
383
|
+
}
|
|
384
|
+
resolve(value);
|
|
385
|
+
};
|
|
386
|
+
const timer = setTimeout(() => settle(null, "error"), 5e3);
|
|
387
|
+
img.onload = () => {
|
|
388
|
+
try {
|
|
389
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
390
|
+
if (isCanvasBlank(ctx, width, height)) {
|
|
391
|
+
settle(null, "error");
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
settle(canvas.toDataURL("image/jpeg", 0.7));
|
|
395
|
+
} catch {
|
|
396
|
+
settle(null, "taint");
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
img.onerror = () => settle(null, "error");
|
|
400
|
+
img.src = url;
|
|
401
|
+
});
|
|
402
|
+
} catch {
|
|
403
|
+
activeOptions.onFailed?.("error");
|
|
404
|
+
emitScreenshotFailed("error");
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return {
|
|
409
|
+
take,
|
|
410
|
+
updateOptions(nextOptions) {
|
|
411
|
+
activeOptions = nextOptions;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function emitScreenshotFailed(reason) {
|
|
416
|
+
try {
|
|
417
|
+
document.dispatchEvent(new CustomEvent("mushi:screenshot_failed", { detail: { reason }, bubbles: false }));
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
var DEFAULT_REDACT_SELECTORS = [
|
|
422
|
+
'input[type="password"]',
|
|
423
|
+
"[data-mushi-redact]"
|
|
424
|
+
];
|
|
425
|
+
function buildPrivacySafeDocument(privacy) {
|
|
426
|
+
const clone = document.documentElement.cloneNode(true);
|
|
427
|
+
clone.querySelector("#mushi-mushi-widget")?.remove();
|
|
428
|
+
stripTaintSources(clone);
|
|
429
|
+
inlineDocumentStyles(clone);
|
|
430
|
+
const redactSelectors = privacy?.redactSelectors !== void 0 ? privacy.redactSelectors : DEFAULT_REDACT_SELECTORS;
|
|
431
|
+
for (const selector of redactSelectors) {
|
|
432
|
+
for (const el of safeQueryAll(clone, selector)) {
|
|
433
|
+
redactElement(el);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
for (const selector of privacy?.blockSelectors ?? []) {
|
|
437
|
+
for (const el of safeQueryAll(clone, selector)) {
|
|
438
|
+
el.remove();
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
for (const selector of privacy?.maskSelectors ?? []) {
|
|
442
|
+
for (const el of safeQueryAll(clone, selector)) {
|
|
443
|
+
maskElement(el);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return clone;
|
|
447
|
+
}
|
|
448
|
+
function safeQueryAll(root, selector) {
|
|
449
|
+
try {
|
|
450
|
+
return Array.from(root.querySelectorAll(selector));
|
|
451
|
+
} catch {
|
|
452
|
+
return [];
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function redactElement(el) {
|
|
456
|
+
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
|
|
457
|
+
el.value = "";
|
|
458
|
+
el.setAttribute("value", "");
|
|
459
|
+
}
|
|
460
|
+
el.textContent = "";
|
|
461
|
+
el.setAttribute(
|
|
462
|
+
"style",
|
|
463
|
+
`${el.getAttribute("style") ?? ""};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`
|
|
464
|
+
);
|
|
465
|
+
el.setAttribute("data-mushi-redacted", "true");
|
|
466
|
+
while (el.firstChild) el.removeChild(el.firstChild);
|
|
467
|
+
}
|
|
468
|
+
function stripTaintSources(root) {
|
|
469
|
+
const pageOrigin = typeof location !== "undefined" ? location.origin : "";
|
|
470
|
+
for (const el of root.querySelectorAll("img, video, iframe, object, embed, picture")) {
|
|
471
|
+
el.remove();
|
|
472
|
+
}
|
|
473
|
+
for (const link of root.querySelectorAll('link[rel="stylesheet"], link[as="style"]')) {
|
|
474
|
+
link.remove();
|
|
475
|
+
}
|
|
476
|
+
for (const styleEl of root.querySelectorAll("style")) {
|
|
477
|
+
const cleaned = stripCssUrlRefs(styleEl.textContent ?? "", pageOrigin);
|
|
478
|
+
if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;
|
|
479
|
+
}
|
|
480
|
+
for (const el of root.querySelectorAll("[style]")) {
|
|
481
|
+
const s = el.getAttribute("style");
|
|
482
|
+
if (!s) continue;
|
|
483
|
+
const cleaned = stripCssUrlRefs(s, pageOrigin);
|
|
484
|
+
if (cleaned !== s) el.setAttribute("style", cleaned);
|
|
485
|
+
}
|
|
486
|
+
for (const script of root.querySelectorAll("script")) {
|
|
487
|
+
script.remove();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function stripCssUrlRefs(css, pageOrigin) {
|
|
491
|
+
return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (_match, _q, href) => {
|
|
492
|
+
const trimmed = href.trim();
|
|
493
|
+
if (!trimmed || trimmed.startsWith("data:") || trimmed.startsWith("#")) return _match;
|
|
494
|
+
if (isCrossOriginUrl(trimmed, pageOrigin)) return "none";
|
|
495
|
+
return _match;
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
function inlineDocumentStyles(clone) {
|
|
499
|
+
const pageOrigin = typeof location !== "undefined" ? location.origin : "";
|
|
500
|
+
const chunks = [];
|
|
501
|
+
const sheets = [
|
|
502
|
+
...Array.from(document.styleSheets),
|
|
503
|
+
...document.adoptedStyleSheets ?? []
|
|
504
|
+
];
|
|
505
|
+
for (const sheet of sheets) {
|
|
506
|
+
const owner = sheet.ownerNode;
|
|
507
|
+
if (owner instanceof Element && owner.tagName === "STYLE") continue;
|
|
508
|
+
chunks.push(serializeSheet(sheet));
|
|
509
|
+
}
|
|
510
|
+
const css = stripCssUrlRefs(chunks.filter(Boolean).join("\n"), pageOrigin);
|
|
511
|
+
if (!css) return;
|
|
512
|
+
const styleEl = document.createElement("style");
|
|
513
|
+
styleEl.textContent = css;
|
|
514
|
+
(clone.querySelector("head") ?? clone).appendChild(styleEl);
|
|
515
|
+
}
|
|
516
|
+
function serializeSheet(sheet) {
|
|
517
|
+
let rules;
|
|
518
|
+
try {
|
|
519
|
+
rules = sheet.cssRules;
|
|
520
|
+
} catch {
|
|
521
|
+
return "";
|
|
522
|
+
}
|
|
523
|
+
let text = "";
|
|
524
|
+
for (const rule of Array.from(rules)) {
|
|
525
|
+
if (rule instanceof CSSImportRule) {
|
|
526
|
+
if (rule.styleSheet) text += serializeSheet(rule.styleSheet);
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
text += `${rule.cssText}
|
|
530
|
+
`;
|
|
531
|
+
}
|
|
532
|
+
return text;
|
|
533
|
+
}
|
|
534
|
+
function isCanvasBlank(ctx, width, height) {
|
|
535
|
+
try {
|
|
536
|
+
const stepX = Math.max(1, Math.floor(width / 8));
|
|
537
|
+
const stepY = Math.max(1, Math.floor(height / 8));
|
|
538
|
+
for (let y = 0; y < height; y += stepY) {
|
|
539
|
+
for (let x = 0; x < width; x += stepX) {
|
|
540
|
+
if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return true;
|
|
544
|
+
} catch {
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function isCrossOriginUrl(raw, pageOrigin) {
|
|
549
|
+
if (!raw || raw.startsWith("data:") || raw.startsWith("blob:")) return false;
|
|
550
|
+
try {
|
|
551
|
+
const resolved = new URL(raw, typeof location !== "undefined" ? location.href : "http://localhost/");
|
|
552
|
+
return Boolean(pageOrigin) && resolved.origin !== pageOrigin;
|
|
553
|
+
} catch {
|
|
554
|
+
return true;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function maskElement(el) {
|
|
558
|
+
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
|
|
559
|
+
el.value = "";
|
|
560
|
+
el.setAttribute("value", "");
|
|
561
|
+
el.setAttribute("placeholder", "\u2022\u2022\u2022\u2022");
|
|
562
|
+
}
|
|
563
|
+
el.textContent = el.children.length === 0 ? "\u2022\u2022\u2022\u2022" : el.textContent;
|
|
564
|
+
el.setAttribute(
|
|
565
|
+
"style",
|
|
566
|
+
`${el.getAttribute("style") ?? ""};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`
|
|
567
|
+
);
|
|
568
|
+
el.setAttribute("data-mushi-masked", "true");
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// src/capture/performance.ts
|
|
572
|
+
var INP_DURATION_THRESHOLD_MS = 40;
|
|
573
|
+
function describeElement(target) {
|
|
574
|
+
if (!target || !target.tagName) return void 0;
|
|
575
|
+
const el = target;
|
|
576
|
+
const tag = el.tagName.toLowerCase();
|
|
577
|
+
const id = el.id ? `#${el.id}` : "";
|
|
578
|
+
const cls = el.classList && el.classList.length > 0 ? `.${el.classList[0]}` : "";
|
|
579
|
+
return `${tag}${id}${cls}`;
|
|
580
|
+
}
|
|
581
|
+
function createPerformanceCapture() {
|
|
582
|
+
const metrics = {};
|
|
583
|
+
const observers = [];
|
|
584
|
+
if (typeof PerformanceObserver !== "undefined") {
|
|
585
|
+
try {
|
|
586
|
+
const paintObserver = new PerformanceObserver((list) => {
|
|
587
|
+
for (const entry of list.getEntries()) {
|
|
588
|
+
if (entry.name === "first-contentful-paint") {
|
|
589
|
+
metrics.fcp = entry.startTime;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
paintObserver.observe({ type: "paint", buffered: true });
|
|
594
|
+
observers.push(paintObserver);
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
try {
|
|
598
|
+
const lcpObserver = new PerformanceObserver((list) => {
|
|
599
|
+
const entries = list.getEntries();
|
|
600
|
+
if (entries.length > 0) {
|
|
601
|
+
metrics.lcp = entries[entries.length - 1].startTime;
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
lcpObserver.observe({ type: "largest-contentful-paint", buffered: true });
|
|
605
|
+
observers.push(lcpObserver);
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
let clsValue = 0;
|
|
610
|
+
const clsObserver = new PerformanceObserver((list) => {
|
|
611
|
+
for (const entry of list.getEntries()) {
|
|
612
|
+
if (!entry.hadRecentInput) {
|
|
613
|
+
clsValue += entry.value ?? 0;
|
|
614
|
+
metrics.cls = clsValue;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
clsObserver.observe({ type: "layout-shift", buffered: true });
|
|
619
|
+
observers.push(clsObserver);
|
|
620
|
+
} catch {
|
|
621
|
+
}
|
|
622
|
+
try {
|
|
623
|
+
let longTaskCount = 0;
|
|
624
|
+
const longTaskObserver = new PerformanceObserver((list) => {
|
|
625
|
+
longTaskCount += list.getEntries().length;
|
|
626
|
+
metrics.longTasks = longTaskCount;
|
|
627
|
+
});
|
|
628
|
+
longTaskObserver.observe({ type: "longtask", buffered: true });
|
|
629
|
+
observers.push(longTaskObserver);
|
|
630
|
+
} catch {
|
|
631
|
+
}
|
|
632
|
+
try {
|
|
633
|
+
const seenInteractions = /* @__PURE__ */ new Map();
|
|
634
|
+
const inpObserver = new PerformanceObserver((list) => {
|
|
635
|
+
for (const entry of list.getEntries()) {
|
|
636
|
+
const interactionId = entry.interactionId;
|
|
637
|
+
if (!interactionId) continue;
|
|
638
|
+
const prev = seenInteractions.get(interactionId) ?? 0;
|
|
639
|
+
if (entry.duration > prev) {
|
|
640
|
+
seenInteractions.set(interactionId, entry.duration);
|
|
641
|
+
}
|
|
642
|
+
if (entry.duration > (metrics.inp ?? 0)) {
|
|
643
|
+
metrics.inp = entry.duration;
|
|
644
|
+
const inputDelay = entry.processingStart - entry.startTime;
|
|
645
|
+
const processingDuration = entry.processingEnd - entry.processingStart;
|
|
646
|
+
const presentationDelay = entry.startTime + entry.duration - entry.processingEnd;
|
|
647
|
+
metrics.inpAttribution = {
|
|
648
|
+
eventType: entry.name,
|
|
649
|
+
targetSelector: describeElement(entry.target),
|
|
650
|
+
inputDelay: Math.max(0, inputDelay),
|
|
651
|
+
processingDuration: Math.max(0, processingDuration),
|
|
652
|
+
presentationDelay: Math.max(0, presentationDelay)
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
inpObserver.observe({
|
|
658
|
+
type: "event",
|
|
659
|
+
// `durationThreshold` filters out fast (< 40 ms) interactions
|
|
660
|
+
// that sit below human perception. Spec-recommended floor.
|
|
661
|
+
durationThreshold: INP_DURATION_THRESHOLD_MS,
|
|
662
|
+
buffered: true
|
|
663
|
+
});
|
|
664
|
+
observers.push(inpObserver);
|
|
665
|
+
} catch {
|
|
666
|
+
}
|
|
667
|
+
try {
|
|
668
|
+
const fidObserver = new PerformanceObserver((list) => {
|
|
669
|
+
for (const entry of list.getEntries()) {
|
|
670
|
+
if (metrics.fid === void 0) {
|
|
671
|
+
metrics.fid = entry.processingStart - entry.startTime;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
fidObserver.observe({ type: "first-input", buffered: true });
|
|
676
|
+
observers.push(fidObserver);
|
|
677
|
+
} catch {
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (typeof performance !== "undefined" && performance.getEntriesByType) {
|
|
681
|
+
try {
|
|
682
|
+
const navEntries = performance.getEntriesByType("navigation");
|
|
683
|
+
if (navEntries.length > 0 && navEntries[0]) {
|
|
684
|
+
metrics.ttfb = navEntries[0].responseStart - navEntries[0].requestStart;
|
|
685
|
+
}
|
|
686
|
+
} catch {
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return {
|
|
690
|
+
getMetrics() {
|
|
691
|
+
return { ...metrics };
|
|
692
|
+
},
|
|
693
|
+
destroy() {
|
|
694
|
+
for (const obs of observers) {
|
|
695
|
+
obs.disconnect();
|
|
696
|
+
}
|
|
697
|
+
observers.length = 0;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function createElementSelector() {
|
|
702
|
+
let active = false;
|
|
703
|
+
let overlay = null;
|
|
704
|
+
let captureLayer = null;
|
|
705
|
+
let hoveredElement = null;
|
|
706
|
+
let resolvePromise = null;
|
|
707
|
+
function findNearestTestid(el) {
|
|
708
|
+
let cur = el;
|
|
709
|
+
let hops = 0;
|
|
710
|
+
while (cur && hops < 20) {
|
|
711
|
+
const tid = cur.getAttribute?.("data-testid");
|
|
712
|
+
if (tid) return tid;
|
|
713
|
+
cur = cur.parentElement;
|
|
714
|
+
hops++;
|
|
715
|
+
}
|
|
716
|
+
return null;
|
|
717
|
+
}
|
|
718
|
+
function getXPath(el) {
|
|
719
|
+
const parts = [];
|
|
720
|
+
let current = el;
|
|
721
|
+
while (current && current !== document.body) {
|
|
722
|
+
let index = 1;
|
|
723
|
+
let sibling = current.previousElementSibling;
|
|
724
|
+
while (sibling) {
|
|
725
|
+
if (sibling.tagName === current.tagName) index++;
|
|
726
|
+
sibling = sibling.previousElementSibling;
|
|
727
|
+
}
|
|
728
|
+
const tag = current.tagName.toLowerCase();
|
|
729
|
+
parts.unshift(index > 1 ? `${tag}[${index}]` : tag);
|
|
730
|
+
current = current.parentElement;
|
|
731
|
+
}
|
|
732
|
+
return "//" + parts.join("/");
|
|
733
|
+
}
|
|
734
|
+
function captureElement(el) {
|
|
735
|
+
const rect = el.getBoundingClientRect();
|
|
736
|
+
const className = typeof el.className === "string" ? el.className : el.getAttribute("class") ?? "";
|
|
737
|
+
return {
|
|
738
|
+
tagName: el.tagName.toLowerCase(),
|
|
739
|
+
id: el.id || void 0,
|
|
740
|
+
className: className || void 0,
|
|
741
|
+
textContent: el.textContent?.trim().slice(0, 200) || void 0,
|
|
742
|
+
xpath: getXPath(el),
|
|
743
|
+
rect: {
|
|
744
|
+
x: Math.round(rect.x),
|
|
745
|
+
y: Math.round(rect.y),
|
|
746
|
+
width: Math.round(rect.width),
|
|
747
|
+
height: Math.round(rect.height)
|
|
748
|
+
},
|
|
749
|
+
// v2 (whitepaper §4.7): the closest ancestor's `data-testid` lets the
|
|
750
|
+
// server map this report → an Action node in the inventory graph
|
|
751
|
+
// without a fuzzy NLP guess. We walk to the body so a deeply nested
|
|
752
|
+
// span inside a button-with-testid still resolves correctly.
|
|
753
|
+
nearestTestid: findNearestTestid(el) || void 0,
|
|
754
|
+
route: typeof window !== "undefined" ? window.location.pathname : void 0
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
function createOverlay() {
|
|
758
|
+
const el = document.createElement("div");
|
|
759
|
+
el.style.cssText = `
|
|
760
|
+
position: fixed;
|
|
761
|
+
pointer-events: none;
|
|
762
|
+
z-index: 2147483647;
|
|
763
|
+
border: 2px solid ${core.MUSHI_COLORS_LIGHT.accent};
|
|
764
|
+
background: ${core.MUSHI_COLORS_LIGHT.accentWash};
|
|
765
|
+
border-radius: 4px;
|
|
766
|
+
transition: all 0.1s ease;
|
|
767
|
+
display: none;
|
|
768
|
+
`;
|
|
769
|
+
document.body.appendChild(el);
|
|
770
|
+
return el;
|
|
771
|
+
}
|
|
772
|
+
function createCaptureLayer() {
|
|
773
|
+
const el = document.createElement("div");
|
|
774
|
+
el.style.cssText = `
|
|
775
|
+
position: fixed;
|
|
776
|
+
inset: 0;
|
|
777
|
+
z-index: 2147483647;
|
|
778
|
+
cursor: crosshair;
|
|
779
|
+
background: transparent;
|
|
780
|
+
`;
|
|
781
|
+
document.body.appendChild(el);
|
|
782
|
+
return el;
|
|
783
|
+
}
|
|
784
|
+
function resolveTargetAt(x, y) {
|
|
785
|
+
const stack = document.elementsFromPoint(x, y);
|
|
786
|
+
let target = null;
|
|
787
|
+
for (const el of stack) {
|
|
788
|
+
if (el === captureLayer || el === overlay) continue;
|
|
789
|
+
if (el.id === "mushi-mushi-widget" || el.closest("#mushi-mushi-widget")) return null;
|
|
790
|
+
target = el;
|
|
791
|
+
break;
|
|
792
|
+
}
|
|
793
|
+
let hops = 0;
|
|
794
|
+
while (target?.shadowRoot && hops < 20) {
|
|
795
|
+
const inner = target.shadowRoot.elementFromPoint(x, y);
|
|
796
|
+
if (!inner || inner === target) break;
|
|
797
|
+
target = inner;
|
|
798
|
+
hops++;
|
|
799
|
+
}
|
|
800
|
+
return target;
|
|
801
|
+
}
|
|
802
|
+
function positionOverlay(target) {
|
|
803
|
+
if (!overlay) return;
|
|
804
|
+
const rect = target.getBoundingClientRect();
|
|
805
|
+
overlay.style.left = `${rect.left}px`;
|
|
806
|
+
overlay.style.top = `${rect.top}px`;
|
|
807
|
+
overlay.style.width = `${rect.width}px`;
|
|
808
|
+
overlay.style.height = `${rect.height}px`;
|
|
809
|
+
overlay.style.display = "block";
|
|
810
|
+
}
|
|
811
|
+
function handleMouseMove(e) {
|
|
812
|
+
const target = resolveTargetAt(e.clientX, e.clientY);
|
|
813
|
+
if (!target) {
|
|
814
|
+
hoveredElement = null;
|
|
815
|
+
if (overlay) overlay.style.display = "none";
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
hoveredElement = target;
|
|
819
|
+
positionOverlay(target);
|
|
820
|
+
}
|
|
821
|
+
function swallow(e) {
|
|
822
|
+
e.preventDefault();
|
|
823
|
+
e.stopPropagation();
|
|
824
|
+
}
|
|
825
|
+
function handleClick(e) {
|
|
826
|
+
e.preventDefault();
|
|
827
|
+
e.stopPropagation();
|
|
828
|
+
const target = resolveTargetAt(e.clientX, e.clientY);
|
|
829
|
+
if (!target) return;
|
|
830
|
+
finish(captureElement(target));
|
|
831
|
+
}
|
|
832
|
+
function handleKeyDown(e) {
|
|
833
|
+
if (e.key === "Escape") {
|
|
834
|
+
finish(null);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
function handleScroll() {
|
|
838
|
+
if (hoveredElement?.isConnected) positionOverlay(hoveredElement);
|
|
839
|
+
}
|
|
840
|
+
function finish(result) {
|
|
841
|
+
deactivate();
|
|
842
|
+
resolvePromise?.(result);
|
|
843
|
+
resolvePromise = null;
|
|
844
|
+
}
|
|
845
|
+
function activate() {
|
|
846
|
+
if (active) deactivate();
|
|
847
|
+
return new Promise((resolve) => {
|
|
848
|
+
resolvePromise = resolve;
|
|
849
|
+
active = true;
|
|
850
|
+
overlay = createOverlay();
|
|
851
|
+
captureLayer = createCaptureLayer();
|
|
852
|
+
captureLayer.addEventListener("mousemove", handleMouseMove);
|
|
853
|
+
captureLayer.addEventListener("click", handleClick);
|
|
854
|
+
captureLayer.addEventListener("pointerdown", swallow);
|
|
855
|
+
captureLayer.addEventListener("mousedown", swallow);
|
|
856
|
+
captureLayer.addEventListener("mouseup", swallow);
|
|
857
|
+
document.addEventListener("keydown", handleKeyDown, true);
|
|
858
|
+
window.addEventListener("scroll", handleScroll, { capture: true, passive: true });
|
|
859
|
+
});
|
|
860
|
+
}
|
|
861
|
+
function deactivate() {
|
|
862
|
+
if (!active) return;
|
|
863
|
+
active = false;
|
|
864
|
+
hoveredElement = null;
|
|
865
|
+
document.removeEventListener("keydown", handleKeyDown, true);
|
|
866
|
+
window.removeEventListener("scroll", handleScroll, { capture: true });
|
|
867
|
+
if (captureLayer) {
|
|
868
|
+
captureLayer.remove();
|
|
869
|
+
captureLayer = null;
|
|
870
|
+
}
|
|
871
|
+
if (overlay) {
|
|
872
|
+
overlay.remove();
|
|
873
|
+
overlay = null;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return { activate, deactivate, isActive: () => active };
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// src/history-patch.ts
|
|
880
|
+
var capturedPushState = null;
|
|
881
|
+
var capturedReplaceState = null;
|
|
882
|
+
var nativePushState = null;
|
|
883
|
+
var nativeReplaceState = null;
|
|
884
|
+
var pushWrapper = null;
|
|
885
|
+
var replaceWrapper = null;
|
|
886
|
+
var popListener = null;
|
|
887
|
+
var patched = false;
|
|
888
|
+
var subscribers = /* @__PURE__ */ new Set();
|
|
889
|
+
function notifyPush() {
|
|
890
|
+
for (const sub of subscribers) {
|
|
891
|
+
try {
|
|
892
|
+
sub.onPush?.();
|
|
893
|
+
} catch {
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
function notifyReplace() {
|
|
898
|
+
for (const sub of subscribers) {
|
|
899
|
+
try {
|
|
900
|
+
sub.onReplace?.();
|
|
901
|
+
} catch {
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
function notifyPop() {
|
|
906
|
+
for (const sub of subscribers) {
|
|
907
|
+
try {
|
|
908
|
+
sub.onPop?.();
|
|
909
|
+
} catch {
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
function ensurePatch() {
|
|
914
|
+
if (patched || typeof window === "undefined") return;
|
|
915
|
+
nativePushState = History.prototype.pushState;
|
|
916
|
+
nativeReplaceState = History.prototype.replaceState;
|
|
917
|
+
capturedPushState = nativePushState.bind(history);
|
|
918
|
+
capturedReplaceState = nativeReplaceState.bind(history);
|
|
919
|
+
pushWrapper = function historyPatchPushState(...args) {
|
|
920
|
+
const call = capturedPushState ?? History.prototype.pushState.bind(history);
|
|
921
|
+
const ret = call(...args);
|
|
922
|
+
notifyPush();
|
|
923
|
+
return ret;
|
|
924
|
+
};
|
|
925
|
+
replaceWrapper = function historyPatchReplaceState(...args) {
|
|
926
|
+
const call = capturedReplaceState ?? History.prototype.replaceState.bind(history);
|
|
927
|
+
const ret = call(...args);
|
|
928
|
+
notifyReplace();
|
|
929
|
+
return ret;
|
|
930
|
+
};
|
|
931
|
+
history.pushState = pushWrapper;
|
|
932
|
+
history.replaceState = replaceWrapper;
|
|
933
|
+
popListener = () => notifyPop();
|
|
934
|
+
window.addEventListener("popstate", popListener);
|
|
935
|
+
patched = true;
|
|
936
|
+
}
|
|
937
|
+
function uninstallPatch() {
|
|
938
|
+
if (!patched || typeof window === "undefined") return;
|
|
939
|
+
if (popListener) {
|
|
940
|
+
window.removeEventListener("popstate", popListener);
|
|
941
|
+
popListener = null;
|
|
942
|
+
}
|
|
943
|
+
if (pushWrapper && history.pushState === pushWrapper && nativePushState) {
|
|
944
|
+
history.pushState = nativePushState;
|
|
945
|
+
}
|
|
946
|
+
if (replaceWrapper && history.replaceState === replaceWrapper && nativeReplaceState) {
|
|
947
|
+
history.replaceState = nativeReplaceState;
|
|
948
|
+
}
|
|
949
|
+
pushWrapper = null;
|
|
950
|
+
replaceWrapper = null;
|
|
951
|
+
capturedPushState = null;
|
|
952
|
+
capturedReplaceState = null;
|
|
953
|
+
nativePushState = null;
|
|
954
|
+
nativeReplaceState = null;
|
|
955
|
+
patched = false;
|
|
956
|
+
}
|
|
957
|
+
function subscribeHistory(sub) {
|
|
958
|
+
ensurePatch();
|
|
959
|
+
subscribers.add(sub);
|
|
960
|
+
return () => {
|
|
961
|
+
subscribers.delete(sub);
|
|
962
|
+
if (subscribers.size === 0) {
|
|
963
|
+
uninstallPatch();
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// src/capture/timeline.ts
|
|
969
|
+
var MAX_TIMELINE_ENTRIES = 120;
|
|
970
|
+
function createTimelineCapture() {
|
|
971
|
+
const entries = [];
|
|
972
|
+
const handleHashChange = () => recordRoute("hashchange");
|
|
973
|
+
recordRoute("initial");
|
|
974
|
+
function record(entry) {
|
|
975
|
+
entries.push(entry);
|
|
976
|
+
if (entries.length > MAX_TIMELINE_ENTRIES) entries.shift();
|
|
977
|
+
}
|
|
978
|
+
function recordRoute(source) {
|
|
979
|
+
if (typeof location === "undefined") return;
|
|
980
|
+
record({
|
|
981
|
+
ts: Date.now(),
|
|
982
|
+
kind: "route",
|
|
983
|
+
payload: {
|
|
984
|
+
source,
|
|
985
|
+
// Query VALUES are a PII channel (`?token=…`, `?email=…`) — scrub
|
|
986
|
+
// them at capture, both in the search string and inside hash-router
|
|
987
|
+
// fragments (`#/path?query`). Keys and paths are preserved.
|
|
988
|
+
route: core.scrubUrl(`${location.pathname}${location.search}${location.hash}`),
|
|
989
|
+
href: core.scrubUrl(location.href)
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
function handleClick(event) {
|
|
994
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
995
|
+
if (!target) return;
|
|
996
|
+
const el = target.closest('button,a,[role="button"],input,textarea,select,[data-mushi-track]') ?? target;
|
|
997
|
+
record({
|
|
998
|
+
ts: Date.now(),
|
|
999
|
+
kind: "click",
|
|
1000
|
+
payload: {
|
|
1001
|
+
tag: el.tagName.toLowerCase(),
|
|
1002
|
+
id: el.id || void 0,
|
|
1003
|
+
text: textSnippet(el)
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
const unsubHistory = subscribeHistory({
|
|
1008
|
+
onPush: () => recordRoute("pushState"),
|
|
1009
|
+
onReplace: () => recordRoute("replaceState"),
|
|
1010
|
+
onPop: () => recordRoute("popstate")
|
|
1011
|
+
});
|
|
1012
|
+
window.addEventListener("hashchange", handleHashChange);
|
|
1013
|
+
document.addEventListener("click", handleClick, true);
|
|
1014
|
+
return {
|
|
1015
|
+
setScreen(screen) {
|
|
1016
|
+
record({
|
|
1017
|
+
ts: Date.now(),
|
|
1018
|
+
kind: "screen",
|
|
1019
|
+
payload: screen
|
|
1020
|
+
});
|
|
1021
|
+
},
|
|
1022
|
+
getEntries(input = {}) {
|
|
1023
|
+
const merged = [
|
|
1024
|
+
...entries,
|
|
1025
|
+
...(input.consoleLogs ?? []).map((log) => ({
|
|
1026
|
+
ts: log.timestamp,
|
|
1027
|
+
kind: "log",
|
|
1028
|
+
payload: {
|
|
1029
|
+
level: log.level,
|
|
1030
|
+
message: log.message
|
|
1031
|
+
}
|
|
1032
|
+
})),
|
|
1033
|
+
...(input.networkLogs ?? []).map((network) => ({
|
|
1034
|
+
ts: network.timestamp,
|
|
1035
|
+
kind: "request",
|
|
1036
|
+
payload: {
|
|
1037
|
+
method: network.method,
|
|
1038
|
+
url: network.url,
|
|
1039
|
+
status: network.status,
|
|
1040
|
+
duration: network.duration,
|
|
1041
|
+
error: network.error
|
|
1042
|
+
}
|
|
1043
|
+
}))
|
|
1044
|
+
].sort((a, b) => a.ts - b.ts);
|
|
1045
|
+
return merged.slice(-MAX_TIMELINE_ENTRIES);
|
|
1046
|
+
},
|
|
1047
|
+
clear() {
|
|
1048
|
+
entries.length = 0;
|
|
1049
|
+
},
|
|
1050
|
+
destroy() {
|
|
1051
|
+
unsubHistory();
|
|
1052
|
+
window.removeEventListener("hashchange", handleHashChange);
|
|
1053
|
+
document.removeEventListener("click", handleClick, true);
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
function textSnippet(el) {
|
|
1058
|
+
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
1059
|
+
return text ? text.slice(0, 80) : void 0;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// src/otel.ts
|
|
1063
|
+
var SPAN_STATUS_ERROR = 2;
|
|
1064
|
+
var warnedMissing = false;
|
|
1065
|
+
function createBrowserOtelSpanProcessor(mushi, options = {}) {
|
|
1066
|
+
const errorsOnly = options.errorsOnly ?? true;
|
|
1067
|
+
const noOp = {
|
|
1068
|
+
// mushi-mushi-allowlist: OTel SpanProcessor requires onStart/onEnd; this no-op processor intentionally does nothing
|
|
1069
|
+
onStart: () => {
|
|
1070
|
+
},
|
|
1071
|
+
// mushi-mushi-allowlist: no-op processor — nothing to forward
|
|
1072
|
+
onEnd: () => {
|
|
1073
|
+
},
|
|
1074
|
+
shutdown: () => Promise.resolve(),
|
|
1075
|
+
forceFlush: () => Promise.resolve()
|
|
1076
|
+
};
|
|
1077
|
+
if (!options.otelPresent) {
|
|
1078
|
+
if (!warnedMissing) {
|
|
1079
|
+
warnedMissing = true;
|
|
1080
|
+
console.warn(
|
|
1081
|
+
"[mushi-mushi/web] createBrowserOtelSpanProcessor: `otelPresent` was not provided. Pass a value from your @opentelemetry/api import (e.g. `{ otelPresent: context }`) to enable OTel span \u2192 Mushi error forwarding. A no-op SpanProcessor has been returned."
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
return noOp;
|
|
1085
|
+
}
|
|
1086
|
+
return {
|
|
1087
|
+
// mushi-mushi-allowlist: OTel SpanProcessor requires onStart; this processor only acts on onEnd
|
|
1088
|
+
onStart: () => {
|
|
1089
|
+
},
|
|
1090
|
+
onEnd(span) {
|
|
1091
|
+
try {
|
|
1092
|
+
const isError = span.status.code === SPAN_STATUS_ERROR;
|
|
1093
|
+
if (!isError && errorsOnly) return;
|
|
1094
|
+
if (isError) {
|
|
1095
|
+
const message = span.attributes["exception.message"] ?? span.attributes["error.message"] ?? `OTel error span: ${span.name}`;
|
|
1096
|
+
const ctx = span.spanContext();
|
|
1097
|
+
const traceparent = `00-${ctx.traceId}-${ctx.spanId}-01`;
|
|
1098
|
+
void mushi.captureEvent({
|
|
1099
|
+
description: message,
|
|
1100
|
+
category: "bug",
|
|
1101
|
+
component: `otel:${span.name}`,
|
|
1102
|
+
metadata: {
|
|
1103
|
+
otelSpanName: span.name,
|
|
1104
|
+
otelAttributes: span.attributes,
|
|
1105
|
+
traceparent
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
} catch {
|
|
1110
|
+
}
|
|
1111
|
+
},
|
|
1112
|
+
shutdown: () => Promise.resolve(),
|
|
1113
|
+
forceFlush: () => Promise.resolve()
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
var warnedOnce = false;
|
|
1117
|
+
function warnOnce(msg) {
|
|
1118
|
+
if (!warnedOnce) {
|
|
1119
|
+
warnedOnce = true;
|
|
1120
|
+
console.warn(msg);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
function createHeadlessCapture(opts) {
|
|
1124
|
+
const endpoint = (opts.apiEndpoint ?? core.DEFAULT_API_ENDPOINT).replace(/\/$/, "");
|
|
1125
|
+
const timeout = opts.timeout ?? 1e4;
|
|
1126
|
+
async function submitRaw(event) {
|
|
1127
|
+
const controller = new AbortController();
|
|
1128
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
1129
|
+
try {
|
|
1130
|
+
const res = await fetch(`${endpoint}/v1/reports`, {
|
|
1131
|
+
method: "POST",
|
|
1132
|
+
signal: controller.signal,
|
|
1133
|
+
headers: {
|
|
1134
|
+
"Content-Type": "application/json",
|
|
1135
|
+
"X-Mushi-Api-Key": opts.apiKey,
|
|
1136
|
+
"X-Mushi-Project": opts.projectId,
|
|
1137
|
+
"User-Agent": "@mushi-mushi/web:headless"
|
|
1138
|
+
},
|
|
1139
|
+
body: JSON.stringify({
|
|
1140
|
+
projectId: opts.projectId,
|
|
1141
|
+
category: event.category ?? "bug",
|
|
1142
|
+
description: event.description,
|
|
1143
|
+
...event.severity ? { severity: event.severity } : {},
|
|
1144
|
+
environment: {
|
|
1145
|
+
url: typeof window !== "undefined" ? window.location.href : void 0,
|
|
1146
|
+
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0
|
|
1147
|
+
},
|
|
1148
|
+
metadata: {
|
|
1149
|
+
...event.metadata ?? {},
|
|
1150
|
+
...event.error ? { error: event.error } : {},
|
|
1151
|
+
...event.tags ? { tags: event.tags } : {},
|
|
1152
|
+
...event.component ? { component: event.component } : {}
|
|
1153
|
+
},
|
|
1154
|
+
// Browser sessions don't have a crypto-signed reporter token —
|
|
1155
|
+
// use a project-scoped placeholder that the backend treats as
|
|
1156
|
+
// a programmatic (non-widget) submission.
|
|
1157
|
+
reporterToken: `headless-${opts.projectId}`,
|
|
1158
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1159
|
+
sdkPackage: "@mushi-mushi/web"
|
|
1160
|
+
})
|
|
1161
|
+
});
|
|
1162
|
+
if (!res.ok) {
|
|
1163
|
+
warnOnce(`[mushi-mushi/web:headless] submit failed: HTTP ${res.status}`);
|
|
1164
|
+
return { ok: false };
|
|
1165
|
+
}
|
|
1166
|
+
const body = await res.json().catch(() => ({}));
|
|
1167
|
+
return { ok: true, reportId: body.data?.reportId };
|
|
1168
|
+
} catch (err) {
|
|
1169
|
+
warnOnce(`[mushi-mushi/web:headless] submit threw: ${err.message}`);
|
|
1170
|
+
return { ok: false };
|
|
1171
|
+
} finally {
|
|
1172
|
+
clearTimeout(timer);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
return {
|
|
1176
|
+
captureEvent(event) {
|
|
1177
|
+
return submitRaw(event);
|
|
1178
|
+
},
|
|
1179
|
+
captureException(error, options = {}) {
|
|
1180
|
+
const e = error instanceof Error ? error : new Error(String(error));
|
|
1181
|
+
return submitRaw({
|
|
1182
|
+
description: e.message,
|
|
1183
|
+
category: "bug",
|
|
1184
|
+
severity: "critical",
|
|
1185
|
+
component: "headless:captureException",
|
|
1186
|
+
error: { name: e.name, message: e.message, stack: e.stack },
|
|
1187
|
+
...options
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
Object.defineProperty(exports, "DEFAULT_API_ENDPOINT", {
|
|
1194
|
+
enumerable: true,
|
|
1195
|
+
get: function () { return core.DEFAULT_API_ENDPOINT; }
|
|
1196
|
+
});
|
|
1197
|
+
exports.createBrowserOtelSpanProcessor = createBrowserOtelSpanProcessor;
|
|
1198
|
+
exports.createConsoleCapture = createConsoleCapture;
|
|
1199
|
+
exports.createElementSelector = createElementSelector;
|
|
1200
|
+
exports.createHeadlessCapture = createHeadlessCapture;
|
|
1201
|
+
exports.createNetworkCapture = createNetworkCapture;
|
|
1202
|
+
exports.createPerformanceCapture = createPerformanceCapture;
|
|
1203
|
+
exports.createScreenshotCapture = createScreenshotCapture;
|
|
1204
|
+
exports.createTimelineCapture = createTimelineCapture;
|
|
1205
|
+
//# sourceMappingURL=headless.cjs.map
|
|
1206
|
+
//# sourceMappingURL=headless.cjs.map
|