@zharp/electron 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +63 -3
- package/dist/main.d.mts +129 -0
- package/dist/main.d.ts +129 -0
- package/dist/main.js +778 -0
- package/dist/main.js.map +1 -0
- package/dist/main.mjs +750 -0
- package/dist/main.mjs.map +1 -0
- package/dist/preload.d.ts +2 -0
- package/dist/preload.js +84 -0
- package/dist/preload.js.map +1 -0
- package/dist/recorder-GORYW5VD.mjs +3 -0
- package/dist/recorder-GORYW5VD.mjs.map +1 -0
- package/dist/renderer.d.mts +315 -0
- package/dist/renderer.d.ts +315 -0
- package/dist/renderer.js +1841 -0
- package/dist/renderer.js.map +1 -0
- package/dist/renderer.min.js +6 -0
- package/dist/renderer.min.js.map +1 -0
- package/dist/renderer.mjs +1822 -0
- package/dist/renderer.mjs.map +1 -0
- package/package.json +91 -3
|
@@ -0,0 +1,1822 @@
|
|
|
1
|
+
// ../../internal/src/bodies.ts
|
|
2
|
+
var DEFAULT_MAX_BODY = 32 * 1024;
|
|
3
|
+
var MAX_BODY = 128 * 1024;
|
|
4
|
+
var FILTERED = "[Filtered]";
|
|
5
|
+
function rawLimit(settings) {
|
|
6
|
+
return Math.max(64 * 1024, settings.maxSize * 2);
|
|
7
|
+
}
|
|
8
|
+
var BODY_ATTRIBUTES = {
|
|
9
|
+
request: "http.request.body",
|
|
10
|
+
requestTruncated: "http.request.body.truncated",
|
|
11
|
+
requestType: "http.request.header.content-type",
|
|
12
|
+
response: "http.response.body",
|
|
13
|
+
responseTruncated: "http.response.body.truncated",
|
|
14
|
+
responseType: "http.response.header.content-type"
|
|
15
|
+
};
|
|
16
|
+
function bodySettings(option, env) {
|
|
17
|
+
let value = option;
|
|
18
|
+
if (!value) return null;
|
|
19
|
+
const o = value === true ? {} : typeof value === "string" ? { mode: value } : value;
|
|
20
|
+
const size = typeof o.maxSize === "number" && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;
|
|
21
|
+
return { mode: o.mode === "all" ? "all" : "errors", maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };
|
|
22
|
+
}
|
|
23
|
+
function wanted(settings, status) {
|
|
24
|
+
return settings.mode === "all" || !status || status >= 400;
|
|
25
|
+
}
|
|
26
|
+
var mime = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
27
|
+
function isEventStream(contentType) {
|
|
28
|
+
return mime(contentType) === "text/event-stream";
|
|
29
|
+
}
|
|
30
|
+
function isMultipart(contentType) {
|
|
31
|
+
return mime(contentType) === "multipart/form-data";
|
|
32
|
+
}
|
|
33
|
+
function isTextual(contentType) {
|
|
34
|
+
const type = mime(contentType);
|
|
35
|
+
if (!type) return true;
|
|
36
|
+
if (type === "text/event-stream") return false;
|
|
37
|
+
return type.startsWith("text/") || type.endsWith("+json") || type.endsWith("+xml") || /^application\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\+json)$/.test(type);
|
|
38
|
+
}
|
|
39
|
+
function isForm(contentType) {
|
|
40
|
+
return mime(contentType) === "application/x-www-form-urlencoded";
|
|
41
|
+
}
|
|
42
|
+
function formatSize(bytes) {
|
|
43
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
44
|
+
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
45
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
46
|
+
}
|
|
47
|
+
function fileLabel(name, type, size, partial = false) {
|
|
48
|
+
const parts = [`file ${name || "blob"}`];
|
|
49
|
+
if (type) parts.push(type);
|
|
50
|
+
if (size !== void 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
51
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
52
|
+
}
|
|
53
|
+
function describeBody(contentType, size, partial = false) {
|
|
54
|
+
if (isEventStream(contentType)) return "[event stream]";
|
|
55
|
+
const parts = ["binary"];
|
|
56
|
+
const type = mime(contentType);
|
|
57
|
+
if (type) parts.push(type);
|
|
58
|
+
if (size !== void 0 && size > 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
59
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
60
|
+
}
|
|
61
|
+
var CONTAINS = [
|
|
62
|
+
"password",
|
|
63
|
+
"passwd",
|
|
64
|
+
"passphrase",
|
|
65
|
+
"secret",
|
|
66
|
+
"token",
|
|
67
|
+
"apikey",
|
|
68
|
+
"accesskey",
|
|
69
|
+
"privatekey",
|
|
70
|
+
"authorization",
|
|
71
|
+
"cookie",
|
|
72
|
+
"creditcard",
|
|
73
|
+
"cardnumber",
|
|
74
|
+
"cvv",
|
|
75
|
+
"cvc",
|
|
76
|
+
"ssn",
|
|
77
|
+
"iban",
|
|
78
|
+
"sessionid",
|
|
79
|
+
"signature",
|
|
80
|
+
"credential"
|
|
81
|
+
];
|
|
82
|
+
var EXACT = ["auth", "pin", "pwd", "otp", "card", "pan", "jwt", "sid", "codeverifier"];
|
|
83
|
+
var URL_EXACT = ["key", "sig", "code", "state", "session"];
|
|
84
|
+
var normalize = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
85
|
+
function isSecretKey(key, extra = []) {
|
|
86
|
+
const k = normalize(key);
|
|
87
|
+
if (!k) return false;
|
|
88
|
+
if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;
|
|
89
|
+
return extra.some((p) => p instanceof RegExp ? p.test(key) : normalize(p) === k);
|
|
90
|
+
}
|
|
91
|
+
var DATA_URI = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[\w=.+-]+)*;base64,([A-Za-z0-9+/=\s]*)$/;
|
|
92
|
+
var BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;
|
|
93
|
+
function shorten(value) {
|
|
94
|
+
if (value.length < 256) return value;
|
|
95
|
+
const uri = DATA_URI.exec(value);
|
|
96
|
+
if (uri) return `[${uri[1] || "data"} \xB7 ${formatSize(Math.floor(uri[2].length * 3 / 4))}]`;
|
|
97
|
+
if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
function filterAll(value, depth) {
|
|
101
|
+
if (depth > 20) return FILTERED;
|
|
102
|
+
if (value === null || value === "") return value;
|
|
103
|
+
if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));
|
|
104
|
+
if (typeof value === "object") {
|
|
105
|
+
const out = {};
|
|
106
|
+
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth + 1);
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
return FILTERED;
|
|
110
|
+
}
|
|
111
|
+
function redactValue(value, extra, depth = 0) {
|
|
112
|
+
if (typeof value === "string") return shorten(value);
|
|
113
|
+
if (depth > 20 || value === null || typeof value !== "object") return value;
|
|
114
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));
|
|
115
|
+
const out = {};
|
|
116
|
+
for (const [k, v] of Object.entries(value)) {
|
|
117
|
+
out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
function redactLoose(text, extra) {
|
|
122
|
+
const runs = /"((?:data:[\w.+-]+\/[\w.+-]+(?:;[\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})("?)/g;
|
|
123
|
+
return text.replace(runs, (match, run, close) => {
|
|
124
|
+
const short = shorten(run);
|
|
125
|
+
if (short === run) return match;
|
|
126
|
+
return close ? `"${short}"` : `"${short.slice(0, -1)}+]"`;
|
|
127
|
+
}).replace(
|
|
128
|
+
/("([^"\\]{1,100})"\s*:\s*)("(?:[^"\\]|\\.)*"?|-?\d[\d.eE+-]*|true|false)/g,
|
|
129
|
+
(match, prefix, key) => isSecretKey(key, extra) ? `${prefix}"${FILTERED}"` : match
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
function redactForm(text, extra) {
|
|
133
|
+
return text.split("&").map((pair) => {
|
|
134
|
+
const eq = pair.indexOf("=");
|
|
135
|
+
if (eq < 0) return pair;
|
|
136
|
+
let key = pair.slice(0, eq);
|
|
137
|
+
try {
|
|
138
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;
|
|
142
|
+
const value = pair.slice(eq + 1);
|
|
143
|
+
return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;
|
|
144
|
+
}).join("&");
|
|
145
|
+
}
|
|
146
|
+
function shortenEncoded(value) {
|
|
147
|
+
try {
|
|
148
|
+
const decoded = decodeURIComponent(value.replace(/\+/g, " "));
|
|
149
|
+
const short = shorten(decoded);
|
|
150
|
+
return short === decoded ? value : short;
|
|
151
|
+
} catch {
|
|
152
|
+
return value;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function formatBody(text, contentType, settings, cut = false) {
|
|
156
|
+
if (text == null) return null;
|
|
157
|
+
let body = String(text);
|
|
158
|
+
if (!body.trim()) return null;
|
|
159
|
+
if (isForm(contentType)) body = redactForm(body, settings.extraKeys);
|
|
160
|
+
else {
|
|
161
|
+
let parsed2;
|
|
162
|
+
let ok = false;
|
|
163
|
+
const trimmed = body.trim();
|
|
164
|
+
if (!cut && (trimmed[0] === "{" || trimmed[0] === "[")) {
|
|
165
|
+
try {
|
|
166
|
+
parsed2 = JSON.parse(trimmed);
|
|
167
|
+
ok = true;
|
|
168
|
+
} catch {
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
body = ok ? JSON.stringify(redactValue(parsed2, settings.extraKeys)) : redactLoose(body, settings.extraKeys);
|
|
172
|
+
}
|
|
173
|
+
const truncated = cut || body.length > settings.maxSize;
|
|
174
|
+
return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };
|
|
175
|
+
}
|
|
176
|
+
function typeKey(side) {
|
|
177
|
+
return side === "request" ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;
|
|
178
|
+
}
|
|
179
|
+
function bodyAttributes(side, text, contentType, settings, cut = false) {
|
|
180
|
+
if (!isTextual(contentType) && !isMultipart(contentType)) return {};
|
|
181
|
+
const formatted = formatBody(text, contentType, settings, cut);
|
|
182
|
+
if (!formatted) return {};
|
|
183
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: formatted.value };
|
|
184
|
+
if (formatted.truncated) attributes[side === "request" ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;
|
|
185
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
186
|
+
return attributes;
|
|
187
|
+
}
|
|
188
|
+
function describedAttributes(side, contentType, size, partial = false) {
|
|
189
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };
|
|
190
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
191
|
+
return attributes;
|
|
192
|
+
}
|
|
193
|
+
function redactUrl(url, extra = []) {
|
|
194
|
+
if (!url) return url;
|
|
195
|
+
let out = url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
|
|
196
|
+
const q = out.indexOf("?");
|
|
197
|
+
if (q < 0) return out;
|
|
198
|
+
const hash = out.indexOf("#", q);
|
|
199
|
+
const query = out.slice(q + 1, hash < 0 ? void 0 : hash);
|
|
200
|
+
const redacted = redactQuery(query, extra);
|
|
201
|
+
if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? "" : out.slice(hash));
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
function redactQuery(query, extra = []) {
|
|
205
|
+
if (!query) return query;
|
|
206
|
+
return query.split("&").map((pair) => {
|
|
207
|
+
const eq = pair.indexOf("=");
|
|
208
|
+
if (eq < 0) return pair;
|
|
209
|
+
let key = pair.slice(0, eq);
|
|
210
|
+
try {
|
|
211
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
212
|
+
} catch {
|
|
213
|
+
}
|
|
214
|
+
const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));
|
|
215
|
+
return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;
|
|
216
|
+
}).join("&");
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ../../internal/src/headers.ts
|
|
220
|
+
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
221
|
+
var MAX_HEADERS = 40;
|
|
222
|
+
var MAX_VALUE = 512;
|
|
223
|
+
function headerSettings(option, env) {
|
|
224
|
+
if (option === false || env === "false" || env === "0") return null;
|
|
225
|
+
return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
|
|
226
|
+
}
|
|
227
|
+
function shown(name, value, settings) {
|
|
228
|
+
if (value === void 0 || value === null) return null;
|
|
229
|
+
if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
|
|
230
|
+
const text = Array.isArray(value) ? value.join(", ") : String(value);
|
|
231
|
+
return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
|
|
232
|
+
}
|
|
233
|
+
function headerAttributes(side, headers, settings) {
|
|
234
|
+
const out = {};
|
|
235
|
+
if (!headers) return out;
|
|
236
|
+
const entries = typeof headers[Symbol.iterator] === "function" ? [...headers] : Object.entries(headers);
|
|
237
|
+
let count = 0;
|
|
238
|
+
for (const [rawName, value] of entries) {
|
|
239
|
+
if (count >= MAX_HEADERS) break;
|
|
240
|
+
const name = rawName.toLowerCase();
|
|
241
|
+
const text = shown(name, value, settings);
|
|
242
|
+
if (text === null) continue;
|
|
243
|
+
out[`http.${side}.header.${name}`] = text;
|
|
244
|
+
count++;
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
function parseHeaderBlock(text) {
|
|
249
|
+
const out = [];
|
|
250
|
+
for (const line of (text ?? "").split(/\r?\n/)) {
|
|
251
|
+
const at = line.indexOf(":");
|
|
252
|
+
if (at > 0) out.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ../browser/src/environment.ts
|
|
258
|
+
var BROWSERS = [
|
|
259
|
+
["Edge", /Edg(?:e|A|iOS)?\/([\d.]+)/],
|
|
260
|
+
["Opera", /(?:OPR|Opera)\/([\d.]+)/],
|
|
261
|
+
["Samsung Internet", /SamsungBrowser\/([\d.]+)/],
|
|
262
|
+
["Firefox", /(?:Firefox|FxiOS)\/([\d.]+)/],
|
|
263
|
+
["Chrome", /(?:Chrome|CriOS)\/([\d.]+)/],
|
|
264
|
+
["Safari", /Version\/([\d.]+).*Safari\//]
|
|
265
|
+
];
|
|
266
|
+
function parseUserAgent(ua) {
|
|
267
|
+
const out = {};
|
|
268
|
+
for (const [name, pattern] of BROWSERS) {
|
|
269
|
+
const match2 = pattern.exec(ua);
|
|
270
|
+
if (match2) {
|
|
271
|
+
out.browserName = name;
|
|
272
|
+
out.browserVersion = match2[1].split(".")[0];
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
let match;
|
|
277
|
+
if (match = /Windows NT ([\d.]+)/.exec(ua)) {
|
|
278
|
+
out.osName = "Windows";
|
|
279
|
+
out.osVersion = { "10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7" }[match[1]] ?? match[1];
|
|
280
|
+
} else if (match = /(?:iPhone|iPad|iPod).*? OS ([\d_]+)/.exec(ua)) {
|
|
281
|
+
out.osName = "iOS";
|
|
282
|
+
out.osVersion = match[1].replace(/_/g, ".");
|
|
283
|
+
} else if (match = /Android ([\d.]+)/.exec(ua)) {
|
|
284
|
+
out.osName = "Android";
|
|
285
|
+
out.osVersion = match[1];
|
|
286
|
+
} else if (match = /Mac OS X ([\d_.]+)/.exec(ua)) {
|
|
287
|
+
out.osName = "macOS";
|
|
288
|
+
out.osVersion = match[1].replace(/_/g, ".");
|
|
289
|
+
} else if (/CrOS/.test(ua)) {
|
|
290
|
+
out.osName = "ChromeOS";
|
|
291
|
+
} else if (/Linux/.test(ua)) {
|
|
292
|
+
out.osName = "Linux";
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ../../internal/src/debug-ids.ts
|
|
298
|
+
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
299
|
+
var files = /* @__PURE__ */ new Map();
|
|
300
|
+
var parsed = /* @__PURE__ */ new Set();
|
|
301
|
+
function registry() {
|
|
302
|
+
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
303
|
+
const value = g2 && g2.__zharpDebugIds;
|
|
304
|
+
return value && typeof value === "object" ? value : void 0;
|
|
305
|
+
}
|
|
306
|
+
function frameFile(line) {
|
|
307
|
+
const text = line.trim();
|
|
308
|
+
if (!text) return void 0;
|
|
309
|
+
let match = /^at (?:async )?(?:.*? \()?(.+?):\d+:\d+\)?$/.exec(text);
|
|
310
|
+
if (match) return clean(match[1]);
|
|
311
|
+
if (text.startsWith("at ")) return void 0;
|
|
312
|
+
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
313
|
+
return match ? clean(match[1]) : void 0;
|
|
314
|
+
}
|
|
315
|
+
function clean(raw) {
|
|
316
|
+
const file = raw.replace(/^address at /, "");
|
|
317
|
+
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
318
|
+
return file;
|
|
319
|
+
}
|
|
320
|
+
function stackFiles(stack) {
|
|
321
|
+
const out = [];
|
|
322
|
+
for (const line of stack.split("\n")) {
|
|
323
|
+
const file = frameFile(line);
|
|
324
|
+
if (file && !out.includes(file)) out.push(file);
|
|
325
|
+
}
|
|
326
|
+
return out;
|
|
327
|
+
}
|
|
328
|
+
function refresh() {
|
|
329
|
+
const entries = registry();
|
|
330
|
+
if (!entries) return;
|
|
331
|
+
for (const stack in entries) {
|
|
332
|
+
if (parsed.has(stack)) continue;
|
|
333
|
+
parsed.add(stack);
|
|
334
|
+
const id = entries[stack];
|
|
335
|
+
if (typeof id !== "string") continue;
|
|
336
|
+
for (const line of stack.split("\n")) {
|
|
337
|
+
const file = frameFile(line);
|
|
338
|
+
if (file) {
|
|
339
|
+
files.set(file, id);
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function debugIdsFor(stack) {
|
|
346
|
+
if (!stack) return void 0;
|
|
347
|
+
try {
|
|
348
|
+
refresh();
|
|
349
|
+
if (files.size === 0) return void 0;
|
|
350
|
+
let out;
|
|
351
|
+
for (const file of stackFiles(stack)) {
|
|
352
|
+
const id = files.get(file);
|
|
353
|
+
if (id) (out ??= {})[file] = id;
|
|
354
|
+
}
|
|
355
|
+
return out;
|
|
356
|
+
} catch {
|
|
357
|
+
return void 0;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function debugIdAttributes(stack) {
|
|
361
|
+
const ids = debugIdsFor(stack);
|
|
362
|
+
return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ../browser/src/util.ts
|
|
366
|
+
function randomHex(bytes) {
|
|
367
|
+
const buf = new Uint8Array(bytes);
|
|
368
|
+
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
369
|
+
if (c && c.getRandomValues) c.getRandomValues(buf);
|
|
370
|
+
else for (let i = 0; i < bytes; i++) buf[i] = Math.random() * 256 | 0;
|
|
371
|
+
let out = "";
|
|
372
|
+
for (let i = 0; i < bytes; i++) out += (buf[i] < 16 ? "0" : "") + buf[i].toString(16);
|
|
373
|
+
return /^0+$/.test(out) ? randomHex(bytes) : out;
|
|
374
|
+
}
|
|
375
|
+
var newTraceId = () => randomHex(16);
|
|
376
|
+
var newSpanId = () => randomHex(8);
|
|
377
|
+
function now() {
|
|
378
|
+
const perf = typeof performance !== "undefined" ? performance : void 0;
|
|
379
|
+
return perf && perf.timeOrigin ? perf.timeOrigin + perf.now() : Date.now();
|
|
380
|
+
}
|
|
381
|
+
function toNanos(ms) {
|
|
382
|
+
const whole = Math.floor(ms);
|
|
383
|
+
const fraction = Math.round((ms - whole) * 1e6);
|
|
384
|
+
return fraction >= 1e6 ? `${whole + 1}000000` : `${whole}${String(fraction).padStart(6, "0")}`;
|
|
385
|
+
}
|
|
386
|
+
function anyValue(value, depth = 0) {
|
|
387
|
+
if (typeof value === "string") return { stringValue: value };
|
|
388
|
+
if (typeof value === "boolean") return { boolValue: value };
|
|
389
|
+
if (typeof value === "number") return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };
|
|
390
|
+
if (value instanceof Error) return { stringValue: `${value.name}: ${value.message}` };
|
|
391
|
+
if (value === null || value === void 0) return { stringValue: "" };
|
|
392
|
+
if (depth < 4 && Array.isArray(value)) return { arrayValue: { values: value.map((v) => anyValue(v, depth + 1)) } };
|
|
393
|
+
if (depth < 4 && typeof value === "object") return { kvlistValue: { values: keyValues(value, depth + 1) } };
|
|
394
|
+
return { stringValue: safeString(value) };
|
|
395
|
+
}
|
|
396
|
+
function keyValues(attributes, depth = 0) {
|
|
397
|
+
const out = [];
|
|
398
|
+
for (const key in attributes) {
|
|
399
|
+
const value = attributes[key];
|
|
400
|
+
if (value !== void 0) out.push({ key, value: anyValue(value, depth) });
|
|
401
|
+
}
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
function safeString(value) {
|
|
405
|
+
if (typeof value === "string") return value;
|
|
406
|
+
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
407
|
+
try {
|
|
408
|
+
const json = JSON.stringify(value);
|
|
409
|
+
return json === void 0 ? String(value) : json;
|
|
410
|
+
} catch {
|
|
411
|
+
return String(value);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function safely(fn) {
|
|
415
|
+
try {
|
|
416
|
+
return fn();
|
|
417
|
+
} catch {
|
|
418
|
+
return void 0;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
|
|
422
|
+
function byteLength(text) {
|
|
423
|
+
return typeof TextEncoder !== "undefined" ? new TextEncoder().encode(text).length : text.length * 2;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ../browser/src/instrument/errors.ts
|
|
427
|
+
function asError(value) {
|
|
428
|
+
if (value instanceof Error) return value;
|
|
429
|
+
if (value && typeof value === "object" && typeof value.message === "string") {
|
|
430
|
+
const error = new Error(value.message);
|
|
431
|
+
error.name = typeof value.name === "string" ? value.name : "Error";
|
|
432
|
+
if (typeof value.stack === "string") error.stack = value.stack;
|
|
433
|
+
return error;
|
|
434
|
+
}
|
|
435
|
+
return new Error(typeof value === "string" ? value : `Non-Error thrown: ${safeString(value)}`);
|
|
436
|
+
}
|
|
437
|
+
function exceptionAttributes(error, handled) {
|
|
438
|
+
const type = (error.name && error.name !== "Error" ? error.name : error.constructor?.name) || "Error";
|
|
439
|
+
const message = error.message || "";
|
|
440
|
+
const head = `${type}: ${message}`;
|
|
441
|
+
let stack = typeof error.stack === "string" ? error.stack : "";
|
|
442
|
+
if (!stack.startsWith(error.name || type)) stack = stack ? `${head}
|
|
443
|
+
${stack}` : head;
|
|
444
|
+
return {
|
|
445
|
+
"exception.type": type,
|
|
446
|
+
"exception.message": message,
|
|
447
|
+
"exception.stacktrace": stack,
|
|
448
|
+
"zharp.handled": handled ? "true" : "false",
|
|
449
|
+
...debugIdAttributes(stack)
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
function watchErrors(report) {
|
|
453
|
+
const onError = (event) => safely(() => {
|
|
454
|
+
if (event.error !== void 0 && event.error !== null) report(event.error, "onerror");
|
|
455
|
+
else if (event.message) {
|
|
456
|
+
const error = new Error(event.message);
|
|
457
|
+
error.stack = `Error: ${event.message}
|
|
458
|
+
at ${event.filename || "<anonymous>"}:${event.lineno || 0}:${event.colno || 0}`;
|
|
459
|
+
report(error, "onerror");
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
const onRejection = (event) => safely(() => report(event.reason, "onunhandledrejection"));
|
|
463
|
+
window.addEventListener("error", onError);
|
|
464
|
+
window.addEventListener("unhandledrejection", onRejection);
|
|
465
|
+
return () => {
|
|
466
|
+
window.removeEventListener("error", onError);
|
|
467
|
+
window.removeEventListener("unhandledrejection", onRejection);
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
var CONSOLE_LEVELS = { debug: "debug", log: "info", info: "info", warn: "warn", error: "error" };
|
|
471
|
+
function watchConsole(methods, log) {
|
|
472
|
+
const originals = {};
|
|
473
|
+
let inside = false;
|
|
474
|
+
for (const method of methods) {
|
|
475
|
+
const original = console[method];
|
|
476
|
+
if (typeof original !== "function" || original.__zharp) continue;
|
|
477
|
+
originals[method] = original;
|
|
478
|
+
const patched = function(...args) {
|
|
479
|
+
original.apply(this ?? console, args);
|
|
480
|
+
if (inside) return;
|
|
481
|
+
inside = true;
|
|
482
|
+
safely(() => {
|
|
483
|
+
const message = args.map((arg) => arg instanceof Error ? arg.stack || String(arg) : safeString(arg)).join(" ");
|
|
484
|
+
if (!message.startsWith("[Zharp]")) log(CONSOLE_LEVELS[method], message);
|
|
485
|
+
});
|
|
486
|
+
inside = false;
|
|
487
|
+
};
|
|
488
|
+
patched.__zharp = true;
|
|
489
|
+
console[method] = patched;
|
|
490
|
+
}
|
|
491
|
+
return () => Object.assign(console, originals);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// ../browser/src/tracing.ts
|
|
495
|
+
var Span = class {
|
|
496
|
+
constructor(tracer, name, kind, parent, startTime = now()) {
|
|
497
|
+
this.tracer = tracer;
|
|
498
|
+
this.name = name;
|
|
499
|
+
this.kind = kind;
|
|
500
|
+
this.startTime = startTime;
|
|
501
|
+
this.traceId = parent ? parent.traceId : newTraceId();
|
|
502
|
+
this.parentSpanId = parent?.spanId;
|
|
503
|
+
this.sampled = parent ? parent.sampled : Math.random() < tracer.sampleRate;
|
|
504
|
+
}
|
|
505
|
+
tracer;
|
|
506
|
+
name;
|
|
507
|
+
kind;
|
|
508
|
+
startTime;
|
|
509
|
+
spanId = newSpanId();
|
|
510
|
+
traceId;
|
|
511
|
+
parentSpanId;
|
|
512
|
+
sampled;
|
|
513
|
+
attributes = {};
|
|
514
|
+
status = { code: 0 /* Unset */ };
|
|
515
|
+
endTime = 0;
|
|
516
|
+
get ended() {
|
|
517
|
+
return this.endTime !== 0;
|
|
518
|
+
}
|
|
519
|
+
setAttribute(key, value) {
|
|
520
|
+
this.attributes[key] = value;
|
|
521
|
+
return this;
|
|
522
|
+
}
|
|
523
|
+
setAttributes(attributes) {
|
|
524
|
+
Object.assign(this.attributes, attributes);
|
|
525
|
+
return this;
|
|
526
|
+
}
|
|
527
|
+
setStatus(code, message) {
|
|
528
|
+
this.status = { code, message };
|
|
529
|
+
return this;
|
|
530
|
+
}
|
|
531
|
+
/** W3C `traceparent` for a request made inside this span. */
|
|
532
|
+
get traceparent() {
|
|
533
|
+
return `00-${this.traceId}-${this.spanId}-${this.sampled ? "01" : "00"}`;
|
|
534
|
+
}
|
|
535
|
+
end(time = now()) {
|
|
536
|
+
if (this.endTime) return;
|
|
537
|
+
this.endTime = Math.max(time, this.startTime);
|
|
538
|
+
this.tracer.finished(this);
|
|
539
|
+
}
|
|
540
|
+
/** As an OTLP/JSON span, with the context attributes as they are now. */
|
|
541
|
+
toOtlp(context) {
|
|
542
|
+
return {
|
|
543
|
+
traceId: this.traceId,
|
|
544
|
+
spanId: this.spanId,
|
|
545
|
+
parentSpanId: this.parentSpanId,
|
|
546
|
+
name: this.name,
|
|
547
|
+
kind: this.kind,
|
|
548
|
+
startTimeUnixNano: toNanos(this.startTime),
|
|
549
|
+
endTimeUnixNano: toNanos(this.endTime),
|
|
550
|
+
attributes: keyValues({ ...context, ...this.attributes }),
|
|
551
|
+
status: this.status.message ? this.status : { code: this.status.code }
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
var IdleSpan = class {
|
|
556
|
+
constructor(span, idleMs, maxMs, onEnd) {
|
|
557
|
+
this.span = span;
|
|
558
|
+
this.idleMs = idleMs;
|
|
559
|
+
this.onEnd = onEnd;
|
|
560
|
+
this.maxTimer = setTimeout(() => this.finish(), Math.max(0, span.startTime + maxMs - now()));
|
|
561
|
+
this.arm();
|
|
562
|
+
}
|
|
563
|
+
span;
|
|
564
|
+
idleMs;
|
|
565
|
+
onEnd;
|
|
566
|
+
inflight = 0;
|
|
567
|
+
idleTimer = null;
|
|
568
|
+
maxTimer;
|
|
569
|
+
/** A page load is not finished before the load event, however quiet the network is. */
|
|
570
|
+
held = false;
|
|
571
|
+
begin() {
|
|
572
|
+
this.inflight++;
|
|
573
|
+
this.disarm();
|
|
574
|
+
}
|
|
575
|
+
done() {
|
|
576
|
+
this.inflight = Math.max(0, this.inflight - 1);
|
|
577
|
+
this.arm();
|
|
578
|
+
}
|
|
579
|
+
/** Do not end on idle until `release()`; the hard limit still applies. */
|
|
580
|
+
hold() {
|
|
581
|
+
this.held = true;
|
|
582
|
+
this.disarm();
|
|
583
|
+
}
|
|
584
|
+
release() {
|
|
585
|
+
this.held = false;
|
|
586
|
+
this.arm();
|
|
587
|
+
}
|
|
588
|
+
finish() {
|
|
589
|
+
if (this.span.ended) return;
|
|
590
|
+
this.disarm();
|
|
591
|
+
clearTimeout(this.maxTimer);
|
|
592
|
+
this.span.end();
|
|
593
|
+
this.onEnd(this);
|
|
594
|
+
}
|
|
595
|
+
arm() {
|
|
596
|
+
this.disarm();
|
|
597
|
+
if (this.inflight === 0 && !this.held) this.idleTimer = setTimeout(() => this.finish(), this.idleMs);
|
|
598
|
+
}
|
|
599
|
+
disarm() {
|
|
600
|
+
if (this.idleTimer) clearTimeout(this.idleTimer);
|
|
601
|
+
this.idleTimer = null;
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
var ROOT_IDLE_MS = 1e3;
|
|
605
|
+
var INTERACTION_IDLE_MS = 500;
|
|
606
|
+
var MAX_ROOT_MS = 3e4;
|
|
607
|
+
var CLICK_WINDOW_MS = 1e3;
|
|
608
|
+
var Tracer = class {
|
|
609
|
+
constructor(hooks) {
|
|
610
|
+
this.hooks = hooks;
|
|
611
|
+
}
|
|
612
|
+
hooks;
|
|
613
|
+
sampleRate = 1;
|
|
614
|
+
root = null;
|
|
615
|
+
interaction = null;
|
|
616
|
+
click = null;
|
|
617
|
+
stack = [];
|
|
618
|
+
finished(span) {
|
|
619
|
+
this.hooks.export(span);
|
|
620
|
+
}
|
|
621
|
+
/** The span new work belongs to, if any is open. */
|
|
622
|
+
activeSpan() {
|
|
623
|
+
if (this.stack.length) return this.stack[this.stack.length - 1];
|
|
624
|
+
if (this.interaction && !this.interaction.span.ended) return this.interaction.span;
|
|
625
|
+
if (this.root && !this.root.span.ended) return this.root.span;
|
|
626
|
+
return null;
|
|
627
|
+
}
|
|
628
|
+
startSpan(name, kind = 1 /* Internal */, parent = this.activeSpan(), startTime) {
|
|
629
|
+
const span = new Span(this, name, kind, parent, startTime);
|
|
630
|
+
if (!parent) this.hooks.traceStarted(span.traceId);
|
|
631
|
+
return span;
|
|
632
|
+
}
|
|
633
|
+
/** Run `fn` with `span` as the active span for its synchronous part. */
|
|
634
|
+
withSpan(span, fn) {
|
|
635
|
+
this.stack.push(span);
|
|
636
|
+
try {
|
|
637
|
+
return fn();
|
|
638
|
+
} finally {
|
|
639
|
+
const index = this.stack.lastIndexOf(span);
|
|
640
|
+
if (index >= 0) this.stack.splice(index, 1);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
/** A page load or navigation: ends whatever root and interaction were open, and starts the new root. */
|
|
644
|
+
startRoot(type, path, attributes, startTime) {
|
|
645
|
+
this.interaction?.finish();
|
|
646
|
+
this.root?.finish();
|
|
647
|
+
const span = this.startSpan(`${type} ${path}`, 1 /* Internal */, null, startTime);
|
|
648
|
+
span.setAttributes({ "zharp.span.type": type, ...attributes });
|
|
649
|
+
this.root = new IdleSpan(span, ROOT_IDLE_MS, MAX_ROOT_MS, (idle) => {
|
|
650
|
+
if (this.root === idle) this.root = null;
|
|
651
|
+
});
|
|
652
|
+
return this.root;
|
|
653
|
+
}
|
|
654
|
+
/** A click happened; it becomes an interaction span only if it leads to a request. */
|
|
655
|
+
noteClick(label, target) {
|
|
656
|
+
this.click = { label, target, time: now() };
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* A request is starting. Returns the span it belongs under and the idle spans to tell when it
|
|
660
|
+
* is done — after opening the interaction span if a click just led to it.
|
|
661
|
+
*/
|
|
662
|
+
requestStarting() {
|
|
663
|
+
const click = this.click;
|
|
664
|
+
if (click && now() - click.time < CLICK_WINDOW_MS && !this.stack.length) {
|
|
665
|
+
this.click = null;
|
|
666
|
+
this.interaction?.finish();
|
|
667
|
+
const span = this.startSpan(`click \u201C${click.label}\u201D`, 1 /* Internal */, null, click.time);
|
|
668
|
+
span.setAttributes({ "zharp.span.type": "interaction", "zharp.interaction.target": click.target });
|
|
669
|
+
this.interaction = new IdleSpan(span, INTERACTION_IDLE_MS, MAX_ROOT_MS, (idle) => {
|
|
670
|
+
if (this.interaction === idle) this.interaction = null;
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
const waiters = [this.interaction, this.root].filter((s) => !!s && !s.span.ended);
|
|
674
|
+
return { parent: this.activeSpan(), waiters };
|
|
675
|
+
}
|
|
676
|
+
/** The page is going away: end everything that is open, so it can still be sent. */
|
|
677
|
+
endAll() {
|
|
678
|
+
this.interaction?.finish();
|
|
679
|
+
this.root?.finish();
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
// ../browser/src/instrument/http.ts
|
|
684
|
+
var BODY_WAIT_MS = 3e3;
|
|
685
|
+
function begin(hooks, method, url) {
|
|
686
|
+
const { parent, waiters } = hooks.tracer.requestStarting();
|
|
687
|
+
const full = absolute(url);
|
|
688
|
+
const span = hooks.tracer.startSpan(`${method} ${pathOf(full)}`, 3 /* Client */, parent);
|
|
689
|
+
span.setAttributes({ "http.request.method": method, "url.full": redactUrl(full), "server.address": hostOf(full) });
|
|
690
|
+
for (const waiter of waiters) waiter.begin();
|
|
691
|
+
return {
|
|
692
|
+
span,
|
|
693
|
+
done(status, error, bodies) {
|
|
694
|
+
const end = now();
|
|
695
|
+
if (status) span.setAttribute("http.response.status_code", status);
|
|
696
|
+
if (error !== void 0 || !status) {
|
|
697
|
+
span.setAttribute("error.type", error instanceof Error ? error.name : "network");
|
|
698
|
+
span.setStatus(2 /* Error */, error instanceof Error ? error.message : "Request failed");
|
|
699
|
+
} else if (status >= 400) {
|
|
700
|
+
span.setAttribute("error.type", String(status));
|
|
701
|
+
span.setStatus(2 /* Error */, `HTTP ${status}`);
|
|
702
|
+
}
|
|
703
|
+
for (const waiter of waiters) waiter.done();
|
|
704
|
+
const read = bodies && safely(() => bodies(status));
|
|
705
|
+
if (!read || typeof read.then !== "function") {
|
|
706
|
+
if (read) span.setAttributes(read);
|
|
707
|
+
span.end(end);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const timer = setTimeout(() => span.end(end), BODY_WAIT_MS);
|
|
711
|
+
read.then(
|
|
712
|
+
(attributes) => {
|
|
713
|
+
clearTimeout(timer);
|
|
714
|
+
if (!span.ended) span.setAttributes(attributes);
|
|
715
|
+
span.end(end);
|
|
716
|
+
},
|
|
717
|
+
() => {
|
|
718
|
+
clearTimeout(timer);
|
|
719
|
+
span.end(end);
|
|
720
|
+
}
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function requestAttributes(body, contentType, settings) {
|
|
726
|
+
if (body == null) return {};
|
|
727
|
+
const text = (t, type, cut = false) => isTextual(type) ? bodyAttributes("request", t, type, settings, cut) : describedAttributes("request", type, t.length);
|
|
728
|
+
if (typeof body === "string") return text(body, contentType);
|
|
729
|
+
if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return text(body.toString(), "application/x-www-form-urlencoded");
|
|
730
|
+
if (typeof FormData !== "undefined" && body instanceof FormData) {
|
|
731
|
+
const fields = {};
|
|
732
|
+
body.forEach((value, key) => {
|
|
733
|
+
const shown2 = typeof value === "string" ? value : fileLabel(value.name, value.type || void 0, value.size);
|
|
734
|
+
const existing = fields[key];
|
|
735
|
+
fields[key] = existing === void 0 ? shown2 : Array.isArray(existing) ? [...existing, shown2] : [existing, shown2];
|
|
736
|
+
});
|
|
737
|
+
return bodyAttributes("request", JSON.stringify(fields), "multipart/form-data", settings);
|
|
738
|
+
}
|
|
739
|
+
if (typeof Blob !== "undefined" && body instanceof Blob) {
|
|
740
|
+
const type = body.type || contentType;
|
|
741
|
+
if (!isTextual(type)) return describedAttributes("request", type, body.size);
|
|
742
|
+
const limit = rawLimit(settings);
|
|
743
|
+
return body.slice(0, limit).text().then((t) => text(t, type, body.size > limit), () => ({}));
|
|
744
|
+
}
|
|
745
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
|
|
746
|
+
const size = body.byteLength;
|
|
747
|
+
if (!contentType || !isTextual(contentType)) return describedAttributes("request", contentType, size);
|
|
748
|
+
return text(new TextDecoder().decode(body), contentType);
|
|
749
|
+
}
|
|
750
|
+
if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return describedAttributes("request", contentType);
|
|
751
|
+
return {};
|
|
752
|
+
}
|
|
753
|
+
async function readLimited(response, limit) {
|
|
754
|
+
const reader = response.body?.getReader();
|
|
755
|
+
if (!reader) {
|
|
756
|
+
const text2 = await response.text();
|
|
757
|
+
return { text: text2.slice(0, limit), cut: text2.length > limit };
|
|
758
|
+
}
|
|
759
|
+
const decoder = new TextDecoder();
|
|
760
|
+
let text = "";
|
|
761
|
+
for (; ; ) {
|
|
762
|
+
const { done, value } = await reader.read();
|
|
763
|
+
if (done) break;
|
|
764
|
+
text += decoder.decode(value, { stream: true });
|
|
765
|
+
if (text.length > limit) {
|
|
766
|
+
reader.cancel().catch(() => {
|
|
767
|
+
});
|
|
768
|
+
return { text: text.slice(0, limit), cut: true };
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return { text: text + decoder.decode(), cut: false };
|
|
772
|
+
}
|
|
773
|
+
function implicitType(body) {
|
|
774
|
+
if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return "application/x-www-form-urlencoded";
|
|
775
|
+
if (typeof FormData !== "undefined" && body instanceof FormData) return "multipart/form-data";
|
|
776
|
+
if (typeof Blob !== "undefined" && body instanceof Blob) return body.type || null;
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
var contentLength = (headers) => {
|
|
780
|
+
const n = Number(headers?.get("content-length"));
|
|
781
|
+
return Number.isFinite(n) && n > 0 ? n : void 0;
|
|
782
|
+
};
|
|
783
|
+
function headerOf(headers, name) {
|
|
784
|
+
if (!headers) return null;
|
|
785
|
+
return safely(() => new Headers(headers).get(name)) ?? null;
|
|
786
|
+
}
|
|
787
|
+
function mergeBaggage(existing, ours) {
|
|
788
|
+
return existing ? `${existing},${ours}` : ours;
|
|
789
|
+
}
|
|
790
|
+
function instrumentFetch(hooks) {
|
|
791
|
+
const g2 = globalThis;
|
|
792
|
+
const original = g2.fetch;
|
|
793
|
+
if (typeof original !== "function" || original.__zharp) return () => {
|
|
794
|
+
};
|
|
795
|
+
const patched = function(input, init) {
|
|
796
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url;
|
|
797
|
+
if (!url || !hooks.shouldTrace(url)) return original.call(this, input, init);
|
|
798
|
+
const method = String(init?.method ?? input?.method ?? "GET").toUpperCase();
|
|
799
|
+
const request = safely(() => begin(hooks, method, url));
|
|
800
|
+
if (!request) return original.call(this, input, init);
|
|
801
|
+
const bodies = hooks.bodies && hooks.shouldCaptureBodies(url) ? hooks.bodies : null;
|
|
802
|
+
let sent;
|
|
803
|
+
let sentType = null;
|
|
804
|
+
if (bodies) {
|
|
805
|
+
safely(() => {
|
|
806
|
+
const isRequest = typeof Request !== "undefined" && input instanceof Request;
|
|
807
|
+
sentType = headerOf(init?.headers, "content-type") ?? (isRequest ? input.headers.get("content-type") : null);
|
|
808
|
+
if (init?.body != null) {
|
|
809
|
+
const body = init.body;
|
|
810
|
+
sentType = (body instanceof FormData ? null : sentType) ?? implicitType(body);
|
|
811
|
+
sent = () => requestAttributes(body, sentType, bodies);
|
|
812
|
+
} else if (isRequest && input.body) {
|
|
813
|
+
const type = sentType;
|
|
814
|
+
if (isTextual(type)) {
|
|
815
|
+
const copy = input.clone();
|
|
816
|
+
sent = () => copy.text().then((t) => requestAttributes(t, type, bodies));
|
|
817
|
+
} else {
|
|
818
|
+
sent = () => describedAttributes("request", type, contentLength(input.headers));
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
let nextInit = init;
|
|
824
|
+
if (hooks.shouldPropagate(url)) {
|
|
825
|
+
nextInit = safely(() => {
|
|
826
|
+
const headers2 = new Headers(init?.headers ?? (typeof Request !== "undefined" && input instanceof Request ? input.headers : void 0));
|
|
827
|
+
if (!headers2.has("traceparent")) headers2.set("traceparent", request.span.traceparent);
|
|
828
|
+
const baggage = hooks.baggage();
|
|
829
|
+
if (baggage) headers2.set("baggage", mergeBaggage(headers2.get("baggage"), baggage));
|
|
830
|
+
return { ...init, headers: headers2 };
|
|
831
|
+
}) ?? init;
|
|
832
|
+
}
|
|
833
|
+
const headers = hooks.headers;
|
|
834
|
+
if (headers) {
|
|
835
|
+
safely(() => {
|
|
836
|
+
const sentHeaders = new Headers(nextInit?.headers ?? (typeof Request !== "undefined" && input instanceof Request ? input.headers : void 0));
|
|
837
|
+
request.span.setAttributes(headerAttributes("request", sentHeaders, headers));
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
const readBodies = (response) => bodies ? (status) => {
|
|
841
|
+
if (!wanted(bodies, status)) return void 0;
|
|
842
|
+
const responseType = response?.headers.get("content-type") ?? null;
|
|
843
|
+
const hasBody = !!response?.body && response.status !== 204 && response.status !== 304;
|
|
844
|
+
const copy = hasBody && isTextual(responseType) ? safely(() => response.clone()) : void 0;
|
|
845
|
+
return (async () => {
|
|
846
|
+
const attributes = {};
|
|
847
|
+
Object.assign(attributes, await Promise.resolve(sent?.()).catch(() => void 0) ?? {});
|
|
848
|
+
if (copy) {
|
|
849
|
+
const read = await readLimited(copy, rawLimit(bodies)).catch(() => null);
|
|
850
|
+
if (read) Object.assign(attributes, bodyAttributes("response", read.text, responseType, bodies, read.cut));
|
|
851
|
+
} else if (hasBody && response) {
|
|
852
|
+
Object.assign(attributes, describedAttributes("response", responseType, contentLength(response.headers)));
|
|
853
|
+
}
|
|
854
|
+
return attributes;
|
|
855
|
+
})();
|
|
856
|
+
} : void 0;
|
|
857
|
+
return original.call(this, input, nextInit).then(
|
|
858
|
+
(response) => {
|
|
859
|
+
if (headers) safely(() => request.span.setAttributes(headerAttributes("response", response.headers, headers)));
|
|
860
|
+
safely(() => request.done(response.status, void 0, readBodies(response)));
|
|
861
|
+
return response;
|
|
862
|
+
},
|
|
863
|
+
(error) => {
|
|
864
|
+
safely(() => request.done(0, error, readBodies()));
|
|
865
|
+
throw error;
|
|
866
|
+
}
|
|
867
|
+
);
|
|
868
|
+
};
|
|
869
|
+
patched.__zharp = true;
|
|
870
|
+
g2.fetch = patched;
|
|
871
|
+
return () => {
|
|
872
|
+
if (g2.fetch === patched) g2.fetch = original;
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
function instrumentXhr(hooks) {
|
|
876
|
+
if (typeof XMLHttpRequest === "undefined") return () => {
|
|
877
|
+
};
|
|
878
|
+
const proto = XMLHttpRequest.prototype;
|
|
879
|
+
if (proto.__zharp) return () => {
|
|
880
|
+
};
|
|
881
|
+
const { open, send, setRequestHeader } = proto;
|
|
882
|
+
proto.open = function(method, url, ...rest) {
|
|
883
|
+
this.__zharp = { method: String(method || "GET").toUpperCase(), url: String(url), traceparent: false, baggage: null, headers: [] };
|
|
884
|
+
return open.call(this, method, url, ...rest);
|
|
885
|
+
};
|
|
886
|
+
proto.setRequestHeader = function(name, value) {
|
|
887
|
+
const state = this.__zharp;
|
|
888
|
+
const lower = String(name).toLowerCase();
|
|
889
|
+
if (state && lower === "traceparent") state.traceparent = true;
|
|
890
|
+
if (state && lower === "content-type") state.contentType = String(value);
|
|
891
|
+
if (state && !state.own) state.headers.push([String(name), String(value)]);
|
|
892
|
+
if (state && lower === "baggage" && !state.own) {
|
|
893
|
+
state.baggage = value;
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
return setRequestHeader.call(this, name, value);
|
|
897
|
+
};
|
|
898
|
+
proto.send = function(body) {
|
|
899
|
+
const state = this.__zharp;
|
|
900
|
+
if (!state || !hooks.shouldTrace(state.url)) return send.call(this, body);
|
|
901
|
+
const request = safely(() => begin(hooks, state.method, state.url));
|
|
902
|
+
if (request) {
|
|
903
|
+
safely(() => {
|
|
904
|
+
if (hooks.shouldPropagate(state.url)) {
|
|
905
|
+
state.own = true;
|
|
906
|
+
if (!state.traceparent) setRequestHeader.call(this, "traceparent", request.span.traceparent);
|
|
907
|
+
const baggage = hooks.baggage();
|
|
908
|
+
if (baggage || state.baggage) setRequestHeader.call(this, "baggage", baggage ? mergeBaggage(state.baggage, baggage) : state.baggage);
|
|
909
|
+
} else if (state.baggage) {
|
|
910
|
+
setRequestHeader.call(this, "baggage", state.baggage);
|
|
911
|
+
}
|
|
912
|
+
});
|
|
913
|
+
const bodies = hooks.bodies && hooks.shouldCaptureBodies(state.url) ? hooks.bodies : null;
|
|
914
|
+
const xhr = this;
|
|
915
|
+
const headers = hooks.headers;
|
|
916
|
+
if (headers) {
|
|
917
|
+
safely(() => {
|
|
918
|
+
const sent = state.headers.filter(([n]) => n.toLowerCase() !== "baggage");
|
|
919
|
+
if (state.own && !state.traceparent) sent.push(["traceparent", request.span.traceparent]);
|
|
920
|
+
const baggage = state.own ? hooks.baggage() ? mergeBaggage(state.baggage, hooks.baggage()) : state.baggage : state.baggage;
|
|
921
|
+
if (baggage) sent.push(["baggage", baggage]);
|
|
922
|
+
request.span.setAttributes(headerAttributes("request", sent, headers));
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
const reader = bodies ? (status) => {
|
|
926
|
+
if (!wanted(bodies, status)) return void 0;
|
|
927
|
+
const sentType = (body instanceof FormData ? null : state.contentType) ?? implicitType(body);
|
|
928
|
+
const responseType = safely(() => xhr.getResponseHeader("content-type")) ?? null;
|
|
929
|
+
const attributes = safely(() => {
|
|
930
|
+
const kind = xhr.responseType;
|
|
931
|
+
const response = xhr.response;
|
|
932
|
+
if (response == null || response === "") return {};
|
|
933
|
+
if (kind === "blob") return describedAttributes("response", responseType, response.size);
|
|
934
|
+
if (kind === "arraybuffer") return describedAttributes("response", responseType, response.byteLength);
|
|
935
|
+
if (kind === "document") return {};
|
|
936
|
+
const text = kind === "json" ? JSON.stringify(response) : xhr.responseText;
|
|
937
|
+
const limit = rawLimit(bodies);
|
|
938
|
+
if (!isTextual(responseType)) return describedAttributes("response", responseType, text.length);
|
|
939
|
+
return bodyAttributes("response", text.slice(0, limit), responseType, bodies, text.length > limit);
|
|
940
|
+
}) ?? {};
|
|
941
|
+
const sentAttributes = requestAttributes(body, sentType, bodies);
|
|
942
|
+
if (sentAttributes && typeof sentAttributes.then === "function") {
|
|
943
|
+
return sentAttributes.then((a) => ({ ...attributes, ...a }), () => attributes);
|
|
944
|
+
}
|
|
945
|
+
return { ...attributes, ...sentAttributes };
|
|
946
|
+
} : void 0;
|
|
947
|
+
this.addEventListener("loadend", () => {
|
|
948
|
+
if (headers) safely(() => request.span.setAttributes(headerAttributes("response", parseHeaderBlock(xhr.getAllResponseHeaders()), headers)));
|
|
949
|
+
safely(() => request.done(this.status, void 0, reader));
|
|
950
|
+
});
|
|
951
|
+
} else if (state.baggage) {
|
|
952
|
+
safely(() => setRequestHeader.call(this, "baggage", state.baggage));
|
|
953
|
+
}
|
|
954
|
+
return send.call(this, body);
|
|
955
|
+
};
|
|
956
|
+
proto.__zharp = true;
|
|
957
|
+
return () => {
|
|
958
|
+
Object.assign(proto, { open, send, setRequestHeader });
|
|
959
|
+
delete proto.__zharp;
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
var base = () => typeof location !== "undefined" ? location.href : "http://localhost/";
|
|
963
|
+
function absolute(url) {
|
|
964
|
+
return safely(() => new URL(url, base()).href) ?? url;
|
|
965
|
+
}
|
|
966
|
+
function pathOf(url) {
|
|
967
|
+
return safely(() => new URL(url).pathname) ?? url.split("?")[0];
|
|
968
|
+
}
|
|
969
|
+
function hostOf(url) {
|
|
970
|
+
return safely(() => new URL(url).hostname) ?? "";
|
|
971
|
+
}
|
|
972
|
+
function matches(url, patterns) {
|
|
973
|
+
const parsed2 = safely(() => new URL(url, base()));
|
|
974
|
+
if (!parsed2) return false;
|
|
975
|
+
return patterns.some((pattern) => {
|
|
976
|
+
if (pattern instanceof RegExp) return pattern.test(parsed2.href);
|
|
977
|
+
if (!pattern) return false;
|
|
978
|
+
if (pattern.includes("://")) return parsed2.href.startsWith(pattern);
|
|
979
|
+
return parsed2.host === pattern || parsed2.hostname === pattern;
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
function sameOrigin(url) {
|
|
983
|
+
return safely(() => typeof location !== "undefined" && new URL(url, base()).origin === location.origin) ?? false;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// ../browser/src/instrument/page.ts
|
|
987
|
+
function currentRoute() {
|
|
988
|
+
const hash = location.hash.startsWith("#/") ? location.hash : "";
|
|
989
|
+
return location.pathname + hash;
|
|
990
|
+
}
|
|
991
|
+
function watchNavigation(onNavigate) {
|
|
992
|
+
let last = currentRoute();
|
|
993
|
+
const check = () => safely(() => {
|
|
994
|
+
const route = currentRoute();
|
|
995
|
+
if (route === last) return;
|
|
996
|
+
last = route;
|
|
997
|
+
onNavigate(route);
|
|
998
|
+
});
|
|
999
|
+
const history = window.history;
|
|
1000
|
+
const originals = {};
|
|
1001
|
+
for (const method of ["pushState", "replaceState"]) {
|
|
1002
|
+
const original = history[method];
|
|
1003
|
+
if (typeof original !== "function" || original.__zharp) continue;
|
|
1004
|
+
originals[method] = original;
|
|
1005
|
+
const patched = function(...args) {
|
|
1006
|
+
const result = original.apply(this, args);
|
|
1007
|
+
check();
|
|
1008
|
+
return result;
|
|
1009
|
+
};
|
|
1010
|
+
patched.__zharp = true;
|
|
1011
|
+
history[method] = patched;
|
|
1012
|
+
}
|
|
1013
|
+
window.addEventListener("popstate", check);
|
|
1014
|
+
window.addEventListener("hashchange", check);
|
|
1015
|
+
return () => {
|
|
1016
|
+
Object.assign(history, originals);
|
|
1017
|
+
window.removeEventListener("popstate", check);
|
|
1018
|
+
window.removeEventListener("hashchange", check);
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
var CLICKABLE = "button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=option],[role=checkbox],[role=switch],input[type=button],input[type=submit],input[type=checkbox],input[type=radio],summary,label,select,[data-zharp-name]";
|
|
1022
|
+
function describeTarget(target) {
|
|
1023
|
+
const start = target instanceof Element ? target : null;
|
|
1024
|
+
if (!start) return null;
|
|
1025
|
+
const element = start.closest(CLICKABLE) ?? start;
|
|
1026
|
+
const attr = (name) => element.getAttribute(name)?.trim();
|
|
1027
|
+
const tag = element.tagName.toLowerCase();
|
|
1028
|
+
let label = attr("data-zharp-name") || attr("aria-label") || (tag === "input" ? element.value || attr("name") : "") || (element.textContent || "").replace(/\s+/g, " ").trim() || attr("title") || attr("alt") || tag;
|
|
1029
|
+
if (label.length > 40) label = `${label.slice(0, 39)}\u2026`;
|
|
1030
|
+
const id = element.id ? `#${element.id}` : "";
|
|
1031
|
+
const classes = typeof element.className === "string" && element.className.trim() ? `.${element.className.trim().split(/\s+/).slice(0, 2).join(".")}` : "";
|
|
1032
|
+
return { label, selector: `${tag}${id}${classes}` };
|
|
1033
|
+
}
|
|
1034
|
+
function watchClicks(onClick) {
|
|
1035
|
+
const listener = (event) => safely(() => {
|
|
1036
|
+
const described = describeTarget(event.target);
|
|
1037
|
+
if (described) onClick(described.label, described.selector);
|
|
1038
|
+
});
|
|
1039
|
+
document.addEventListener("click", listener, true);
|
|
1040
|
+
return () => document.removeEventListener("click", listener, true);
|
|
1041
|
+
}
|
|
1042
|
+
function watchActivity(onActivity) {
|
|
1043
|
+
const events = ["click", "keydown", "scroll", "touchstart", "pointerdown"];
|
|
1044
|
+
let last = 0;
|
|
1045
|
+
const listener = () => {
|
|
1046
|
+
const time = Date.now();
|
|
1047
|
+
if (time - last < 1e3) return;
|
|
1048
|
+
last = time;
|
|
1049
|
+
safely(onActivity);
|
|
1050
|
+
};
|
|
1051
|
+
for (const name of events) document.addEventListener(name, listener, { capture: true, passive: true });
|
|
1052
|
+
return () => {
|
|
1053
|
+
for (const name of events) document.removeEventListener(name, listener, { capture: true });
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
function watchHide(onHide) {
|
|
1057
|
+
const onVisibility = () => {
|
|
1058
|
+
if (document.visibilityState === "hidden") safely(onHide);
|
|
1059
|
+
};
|
|
1060
|
+
const onPageHide = () => safely(onHide);
|
|
1061
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
1062
|
+
window.addEventListener("pagehide", onPageHide);
|
|
1063
|
+
return () => {
|
|
1064
|
+
document.removeEventListener("visibilitychange", onVisibility);
|
|
1065
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
function navigationTimings() {
|
|
1069
|
+
const entry = safely(() => performance.getEntriesByType("navigation")[0]);
|
|
1070
|
+
if (!entry) return {};
|
|
1071
|
+
const out = {};
|
|
1072
|
+
const put = (key, value) => {
|
|
1073
|
+
if (value > 0) out[key] = Math.round(value);
|
|
1074
|
+
};
|
|
1075
|
+
put("browser.timing.ttfb_ms", entry.responseStart);
|
|
1076
|
+
put("browser.timing.dom_content_loaded_ms", entry.domContentLoadedEventEnd);
|
|
1077
|
+
put("browser.timing.load_ms", entry.loadEventEnd);
|
|
1078
|
+
return out;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// ../browser/src/replay/controller.ts
|
|
1082
|
+
function loadRecorder(options) {
|
|
1083
|
+
return import('./recorder-GORYW5VD.mjs');
|
|
1084
|
+
}
|
|
1085
|
+
var ReplayController = class {
|
|
1086
|
+
constructor(session, options, endpoint, service) {
|
|
1087
|
+
this.session = session;
|
|
1088
|
+
this.options = options;
|
|
1089
|
+
this.endpoint = endpoint;
|
|
1090
|
+
this.service = service;
|
|
1091
|
+
session.onRenew(() => {
|
|
1092
|
+
const mode = this.decide();
|
|
1093
|
+
if (this.recorder) this.recorder.renew(mode);
|
|
1094
|
+
else if (mode !== "off") this.load(mode);
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
session;
|
|
1098
|
+
options;
|
|
1099
|
+
endpoint;
|
|
1100
|
+
service;
|
|
1101
|
+
recorder = null;
|
|
1102
|
+
loading = false;
|
|
1103
|
+
/** Traces and errors that happened while the recorder was downloading. */
|
|
1104
|
+
early = { traces: [], error: false };
|
|
1105
|
+
start() {
|
|
1106
|
+
const mode = this.decide();
|
|
1107
|
+
if (mode !== "off") this.load(mode);
|
|
1108
|
+
}
|
|
1109
|
+
linkTrace(traceId) {
|
|
1110
|
+
if (this.recorder) this.recorder.linkTrace(traceId);
|
|
1111
|
+
else if (this.loading && this.early.traces.length < 50) this.early.traces.push(traceId);
|
|
1112
|
+
}
|
|
1113
|
+
onError() {
|
|
1114
|
+
if (this.recorder) this.recorder.onError();
|
|
1115
|
+
else if (this.loading) this.early.error = true;
|
|
1116
|
+
}
|
|
1117
|
+
flush() {
|
|
1118
|
+
return this.recorder ? this.recorder.flush() : Promise.resolve();
|
|
1119
|
+
}
|
|
1120
|
+
flushOnHide() {
|
|
1121
|
+
this.recorder?.flushOnHide();
|
|
1122
|
+
}
|
|
1123
|
+
stop() {
|
|
1124
|
+
const recorder = this.recorder;
|
|
1125
|
+
this.recorder = null;
|
|
1126
|
+
return recorder ? recorder.stop() : Promise.resolve();
|
|
1127
|
+
}
|
|
1128
|
+
/** This session's mode, decided once and kept with the session. */
|
|
1129
|
+
decide() {
|
|
1130
|
+
const state = this.session.current;
|
|
1131
|
+
if (state.replay) return state.replay;
|
|
1132
|
+
const rate = (value) => typeof value === "number" ? Math.min(1, Math.max(0, value)) : 0;
|
|
1133
|
+
const mode = Math.random() < rate(this.options.sampleRate) ? "session" : Math.random() < rate(this.options.onErrorSampleRate) ? "buffer" : "off";
|
|
1134
|
+
this.session.update({ replay: mode });
|
|
1135
|
+
return mode;
|
|
1136
|
+
}
|
|
1137
|
+
load(mode) {
|
|
1138
|
+
if (this.loading) return;
|
|
1139
|
+
this.loading = true;
|
|
1140
|
+
const host = {
|
|
1141
|
+
endpoint: this.endpoint,
|
|
1142
|
+
service: this.service,
|
|
1143
|
+
options: this.options,
|
|
1144
|
+
session: () => this.session.current,
|
|
1145
|
+
saveSequence: (id, next) => {
|
|
1146
|
+
if (this.session.current.id === id) this.session.update({ seq: next });
|
|
1147
|
+
},
|
|
1148
|
+
saveMode: (id, replay) => {
|
|
1149
|
+
if (this.session.current.id === id) this.session.update({ replay });
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
loadRecorder(this.options).then((module) => {
|
|
1153
|
+
this.recorder = module.createRecorder(host, mode);
|
|
1154
|
+
for (const id of this.early.traces) this.recorder.linkTrace(id);
|
|
1155
|
+
if (this.early.error) this.recorder.onError();
|
|
1156
|
+
}).catch(() => {
|
|
1157
|
+
}).finally(() => {
|
|
1158
|
+
this.loading = false;
|
|
1159
|
+
this.early = { traces: [], error: false };
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
|
|
1164
|
+
// ../browser/src/session.ts
|
|
1165
|
+
var STORAGE_KEY = "zharp.session";
|
|
1166
|
+
var WRITE_EVERY_MS = 5e3;
|
|
1167
|
+
function newState(user = null) {
|
|
1168
|
+
const time = Date.now();
|
|
1169
|
+
const hex = randomHex(16);
|
|
1170
|
+
const id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${(parseInt(hex[16], 16) & 3 | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20)}`;
|
|
1171
|
+
return { id, started: time, lastActive: time, user };
|
|
1172
|
+
}
|
|
1173
|
+
var tabStorage = {
|
|
1174
|
+
get: (key) => sessionStorage.getItem(key),
|
|
1175
|
+
set: (key, value) => sessionStorage.setItem(key, value)
|
|
1176
|
+
};
|
|
1177
|
+
var Session = class {
|
|
1178
|
+
constructor(timeoutMs, store = tabStorage) {
|
|
1179
|
+
this.timeoutMs = timeoutMs;
|
|
1180
|
+
this.store = store;
|
|
1181
|
+
const stored = this.read();
|
|
1182
|
+
this.state = stored && Date.now() - stored.lastActive < timeoutMs ? stored : newState(stored?.user);
|
|
1183
|
+
this.write();
|
|
1184
|
+
}
|
|
1185
|
+
timeoutMs;
|
|
1186
|
+
store;
|
|
1187
|
+
state;
|
|
1188
|
+
lastWrite = 0;
|
|
1189
|
+
listeners = [];
|
|
1190
|
+
/** The current session, after starting a new one if this one has expired. */
|
|
1191
|
+
get current() {
|
|
1192
|
+
if (Date.now() - this.state.lastActive >= this.timeoutMs) this.renew();
|
|
1193
|
+
return this.state;
|
|
1194
|
+
}
|
|
1195
|
+
get id() {
|
|
1196
|
+
return this.current.id;
|
|
1197
|
+
}
|
|
1198
|
+
/** Something happened: the session is still going. */
|
|
1199
|
+
touch() {
|
|
1200
|
+
const state = this.current;
|
|
1201
|
+
state.lastActive = Date.now();
|
|
1202
|
+
if (state.lastActive - this.lastWrite > WRITE_EVERY_MS) this.write();
|
|
1203
|
+
}
|
|
1204
|
+
/** Start a new session now. The user carries over unless `user` is given. */
|
|
1205
|
+
renew(user) {
|
|
1206
|
+
this.state = newState(user === void 0 ? this.state.user : user);
|
|
1207
|
+
this.write();
|
|
1208
|
+
for (const listener of this.listeners) listener(this.state);
|
|
1209
|
+
}
|
|
1210
|
+
update(patch) {
|
|
1211
|
+
Object.assign(this.state, patch);
|
|
1212
|
+
this.write();
|
|
1213
|
+
}
|
|
1214
|
+
/** Called with the new state whenever a session ends and another begins. */
|
|
1215
|
+
onRenew(listener) {
|
|
1216
|
+
this.listeners.push(listener);
|
|
1217
|
+
}
|
|
1218
|
+
read() {
|
|
1219
|
+
try {
|
|
1220
|
+
const raw = this.store.get(STORAGE_KEY);
|
|
1221
|
+
const parsed2 = raw ? JSON.parse(raw) : null;
|
|
1222
|
+
return parsed2 && typeof parsed2.id === "string" && typeof parsed2.lastActive === "number" ? parsed2 : null;
|
|
1223
|
+
} catch {
|
|
1224
|
+
return null;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
write() {
|
|
1228
|
+
this.lastWrite = Date.now();
|
|
1229
|
+
try {
|
|
1230
|
+
this.store.set(STORAGE_KEY, JSON.stringify(this.state));
|
|
1231
|
+
} catch {
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
// ../browser/src/transport.ts
|
|
1237
|
+
var BATCH_SIZE = 100;
|
|
1238
|
+
var FLUSH_MS = 5e3;
|
|
1239
|
+
var MAX_QUEUE = 1e3;
|
|
1240
|
+
var MAX_BACKOFF_MS = 5 * 6e4;
|
|
1241
|
+
var MAX_BODY_BYTES = 1e6;
|
|
1242
|
+
var MAX_KEEPALIVE_BYTES = 6e4;
|
|
1243
|
+
var keyRejected = false;
|
|
1244
|
+
async function post(endpoint, signal, body, keepalive = false) {
|
|
1245
|
+
if (keyRejected) return 401;
|
|
1246
|
+
const headers = {
|
|
1247
|
+
"Content-Type": "application/json",
|
|
1248
|
+
Authorization: `Bearer ${endpoint.key}`
|
|
1249
|
+
};
|
|
1250
|
+
let payload = body;
|
|
1251
|
+
if (!keepalive && endpoint.compress !== false && body.length > 2048 && typeof CompressionStream !== "undefined") {
|
|
1252
|
+
try {
|
|
1253
|
+
payload = await new Response(new Blob([body]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
|
|
1254
|
+
headers["Content-Encoding"] = "gzip";
|
|
1255
|
+
} catch {
|
|
1256
|
+
payload = body;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
try {
|
|
1260
|
+
const response = await endpoint.fetch.call(globalThis, `${endpoint.url}/v1/${signal}`, {
|
|
1261
|
+
method: "POST",
|
|
1262
|
+
headers,
|
|
1263
|
+
body: payload,
|
|
1264
|
+
keepalive,
|
|
1265
|
+
credentials: "omit"
|
|
1266
|
+
});
|
|
1267
|
+
if (response.status === 401 || response.status === 403) {
|
|
1268
|
+
if (!keyRejected) {
|
|
1269
|
+
keyRejected = true;
|
|
1270
|
+
console.warn(`[Zharp] The key was rejected (HTTP ${response.status}); ${endpoint.rejectedHint ?? "nothing more will be sent from this page. Check Zharp.init({ key }) and the app's allowed origins."}`);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
return response.status;
|
|
1274
|
+
} catch {
|
|
1275
|
+
return 0;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
var keepaliveInFlight = 0;
|
|
1279
|
+
function sendOnHide(endpoint, signal, body) {
|
|
1280
|
+
const size = byteLength(body);
|
|
1281
|
+
if (keepaliveInFlight + size <= MAX_KEEPALIVE_BYTES) {
|
|
1282
|
+
keepaliveInFlight += size;
|
|
1283
|
+
void post(endpoint, signal, body, true).finally(() => {
|
|
1284
|
+
keepaliveInFlight -= size;
|
|
1285
|
+
});
|
|
1286
|
+
} else {
|
|
1287
|
+
void post(endpoint, signal, body);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
var retryable = (status) => status === 0 || status === 429 || status >= 500;
|
|
1291
|
+
function split(items, limit, wrap) {
|
|
1292
|
+
const overhead = byteLength(JSON.stringify(wrap([])));
|
|
1293
|
+
const out = [];
|
|
1294
|
+
let group = [];
|
|
1295
|
+
let size = overhead;
|
|
1296
|
+
for (const item of items) {
|
|
1297
|
+
const itemSize = byteLength(JSON.stringify(item)) + 1;
|
|
1298
|
+
if (group.length && size + itemSize > limit) {
|
|
1299
|
+
out.push({ body: JSON.stringify(wrap(group)), items: group });
|
|
1300
|
+
group = [];
|
|
1301
|
+
size = overhead;
|
|
1302
|
+
}
|
|
1303
|
+
group.push(item);
|
|
1304
|
+
size += itemSize;
|
|
1305
|
+
}
|
|
1306
|
+
if (group.length) out.push({ body: JSON.stringify(wrap(group)), items: group });
|
|
1307
|
+
return out;
|
|
1308
|
+
}
|
|
1309
|
+
var Exporter = class {
|
|
1310
|
+
constructor(endpoint, signal, wrap, timers = true) {
|
|
1311
|
+
this.endpoint = endpoint;
|
|
1312
|
+
this.signal = signal;
|
|
1313
|
+
this.wrap = wrap;
|
|
1314
|
+
this.timers = timers;
|
|
1315
|
+
}
|
|
1316
|
+
endpoint;
|
|
1317
|
+
signal;
|
|
1318
|
+
wrap;
|
|
1319
|
+
timers;
|
|
1320
|
+
queue = [];
|
|
1321
|
+
timer = null;
|
|
1322
|
+
sending = null;
|
|
1323
|
+
failures = 0;
|
|
1324
|
+
add(record) {
|
|
1325
|
+
this.queue.push(record);
|
|
1326
|
+
if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
|
|
1327
|
+
if (this.queue.length >= BATCH_SIZE && !this.failures) this.flush();
|
|
1328
|
+
else this.schedule(FLUSH_MS);
|
|
1329
|
+
}
|
|
1330
|
+
/** Send everything queued. One send at a time; a call during one waits and then sends what is left. */
|
|
1331
|
+
async flush() {
|
|
1332
|
+
while (this.sending) await this.sending;
|
|
1333
|
+
if (!this.queue.length) return;
|
|
1334
|
+
this.sending = this.send().finally(() => this.sending = null);
|
|
1335
|
+
return this.sending;
|
|
1336
|
+
}
|
|
1337
|
+
/** The page is going away: everything left, now, with keepalive. Nothing to wait for. */
|
|
1338
|
+
flushOnHide() {
|
|
1339
|
+
if (!this.queue.length) return;
|
|
1340
|
+
const records = this.queue;
|
|
1341
|
+
this.queue = [];
|
|
1342
|
+
for (const { body } of split(records, MAX_KEEPALIVE_BYTES, this.wrap)) sendOnHide(this.endpoint, this.signal, body);
|
|
1343
|
+
}
|
|
1344
|
+
schedule(ms) {
|
|
1345
|
+
if (this.timer || !this.timers) return;
|
|
1346
|
+
this.timer = setTimeout(() => {
|
|
1347
|
+
this.timer = null;
|
|
1348
|
+
this.flush();
|
|
1349
|
+
}, ms);
|
|
1350
|
+
}
|
|
1351
|
+
async send() {
|
|
1352
|
+
if (this.timer) {
|
|
1353
|
+
clearTimeout(this.timer);
|
|
1354
|
+
this.timer = null;
|
|
1355
|
+
}
|
|
1356
|
+
const records = this.queue;
|
|
1357
|
+
this.queue = [];
|
|
1358
|
+
const batches = split(records, MAX_BODY_BYTES, this.wrap);
|
|
1359
|
+
for (let i = 0; i < batches.length; i++) {
|
|
1360
|
+
const status = await post(this.endpoint, this.signal, batches[i].body);
|
|
1361
|
+
if (retryable(status)) {
|
|
1362
|
+
const unsent = batches.slice(i).flatMap((b) => b.items);
|
|
1363
|
+
this.queue = unsent.concat(this.queue).slice(-MAX_QUEUE);
|
|
1364
|
+
this.failures++;
|
|
1365
|
+
this.schedule(Math.min(FLUSH_MS * 2 ** this.failures, MAX_BACKOFF_MS));
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
this.failures = 0;
|
|
1369
|
+
}
|
|
1370
|
+
if (this.queue.length) this.schedule(FLUSH_MS);
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
// ../browser/src/version.ts
|
|
1375
|
+
var VERSION = "0.5.1";
|
|
1376
|
+
|
|
1377
|
+
// ../browser/src/client.ts
|
|
1378
|
+
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
1379
|
+
var SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
|
|
1380
|
+
var ZharpBrowser = class {
|
|
1381
|
+
constructor(host) {
|
|
1382
|
+
this.host = host;
|
|
1383
|
+
}
|
|
1384
|
+
host;
|
|
1385
|
+
running = null;
|
|
1386
|
+
user = null;
|
|
1387
|
+
tags = {};
|
|
1388
|
+
/** Errors already reported, so one caught by the app and then rethrown is sent once. */
|
|
1389
|
+
reported = /* @__PURE__ */ new WeakSet();
|
|
1390
|
+
log = {
|
|
1391
|
+
trace: (m, a) => this.emit("trace", m, a),
|
|
1392
|
+
debug: (m, a) => this.emit("debug", m, a),
|
|
1393
|
+
info: (m, a) => this.emit("info", m, a),
|
|
1394
|
+
warn: (m, a) => this.emit("warn", m, a),
|
|
1395
|
+
error: (m, a) => this.emit("error", m, a),
|
|
1396
|
+
fatal: (m, a) => this.emit("fatal", m, a)
|
|
1397
|
+
};
|
|
1398
|
+
get isActive() {
|
|
1399
|
+
return this.running !== null;
|
|
1400
|
+
}
|
|
1401
|
+
/** The current session's ID, e.g. to show on a support page. */
|
|
1402
|
+
get sessionId() {
|
|
1403
|
+
return this.running?.session.id;
|
|
1404
|
+
}
|
|
1405
|
+
init(options) {
|
|
1406
|
+
try {
|
|
1407
|
+
if (this.running) {
|
|
1408
|
+
console.warn("[Zharp] Zharp.init() was called again \u2014 the first call's settings stay in effect.");
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
if (!options || !options.key) {
|
|
1412
|
+
console.warn("[Zharp] Zharp.init({ key }) needs the app key from the Zharp dashboard. Nothing will be sent.");
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (!isBrowser()) return;
|
|
1416
|
+
this.start(options);
|
|
1417
|
+
} catch {
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
start(options) {
|
|
1421
|
+
const endpointUrl = (options.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
1422
|
+
const host = this.host;
|
|
1423
|
+
const endpoint = host ? { url: endpointUrl, key: options.key, fetch: host.fetch, compress: false } : { url: endpointUrl, key: options.key, fetch: globalThis.fetch };
|
|
1424
|
+
const service = options.service || "web";
|
|
1425
|
+
const session = host?.session ?? new Session((options.sessionTimeoutMinutes ?? 30) * 6e4);
|
|
1426
|
+
if (this.user) session.update({ user: this.user });
|
|
1427
|
+
else this.user = session.current.user ?? null;
|
|
1428
|
+
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
|
|
1429
|
+
const platform = parseUserAgent(ua);
|
|
1430
|
+
const resource = keyValues({
|
|
1431
|
+
"service.name": service,
|
|
1432
|
+
"service.version": options.release,
|
|
1433
|
+
"deployment.environment.name": options.environment,
|
|
1434
|
+
"telemetry.sdk.name": "zharp",
|
|
1435
|
+
"telemetry.sdk.language": "webjs",
|
|
1436
|
+
"telemetry.sdk.version": VERSION,
|
|
1437
|
+
"browser.name": platform.browserName,
|
|
1438
|
+
"browser.version": platform.browserVersion,
|
|
1439
|
+
"os.name": platform.osName,
|
|
1440
|
+
"os.version": platform.osVersion,
|
|
1441
|
+
"user_agent.original": ua || void 0,
|
|
1442
|
+
...host?.resource
|
|
1443
|
+
});
|
|
1444
|
+
const scope = host?.scope ?? { name: "@zharp/browser", version: VERSION };
|
|
1445
|
+
const spans = new Exporter(endpoint, "traces", (records) => ({
|
|
1446
|
+
resourceSpans: [{ resource: { attributes: resource }, scopeSpans: [{ scope, spans: records }] }]
|
|
1447
|
+
}));
|
|
1448
|
+
const logs = new Exporter(endpoint, "logs", (records) => ({
|
|
1449
|
+
resourceLogs: [{ resource: { attributes: resource }, scopeLogs: [{ scope, logRecords: records }] }]
|
|
1450
|
+
}));
|
|
1451
|
+
const replayOptions = options.replay;
|
|
1452
|
+
const replay = replayOptions && ((replayOptions.sampleRate ?? 0) > 0 || (replayOptions.onErrorSampleRate ?? 0) > 0) ? new ReplayController(session, replayOptions, endpoint, service) : null;
|
|
1453
|
+
const tracer = new Tracer({
|
|
1454
|
+
export: (span) => {
|
|
1455
|
+
if (span.sampled) spans.add(span.toOtlp(this.contextAttributes()));
|
|
1456
|
+
},
|
|
1457
|
+
traceStarted: (traceId) => replay?.linkTrace(traceId)
|
|
1458
|
+
});
|
|
1459
|
+
tracer.sampleRate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
1460
|
+
const tracing = options.tracing !== false;
|
|
1461
|
+
const running = { options, endpoint, session, tracer, tracing, spans, logs, replay, teardowns: [] };
|
|
1462
|
+
this.running = running;
|
|
1463
|
+
const ignore = options.ignoreUrls ?? [];
|
|
1464
|
+
const tracingOrigins = options.tracingOrigins ?? [];
|
|
1465
|
+
const bodies = bodySettings(options.captureBodies);
|
|
1466
|
+
const httpHooks = {
|
|
1467
|
+
tracer,
|
|
1468
|
+
shouldTrace: (url) => {
|
|
1469
|
+
const full = absolute(url);
|
|
1470
|
+
return !full.startsWith(endpointUrl) && !matches(full, ignore);
|
|
1471
|
+
},
|
|
1472
|
+
shouldPropagate: (url) => sameOrigin(url) || matches(url, tracingOrigins),
|
|
1473
|
+
baggage: () => this.baggage(),
|
|
1474
|
+
bodies,
|
|
1475
|
+
headers: headerSettings(options.captureHeaders),
|
|
1476
|
+
// The app's own APIs only, unless the app names the URLs itself.
|
|
1477
|
+
shouldCaptureBodies: (url) => bodies?.urls ? matches(url, bodies.urls) : sameOrigin(url) || matches(url, tracingOrigins)
|
|
1478
|
+
};
|
|
1479
|
+
const t = running.teardowns;
|
|
1480
|
+
if (tracing) t.push(instrumentFetch(httpHooks), instrumentXhr(httpHooks));
|
|
1481
|
+
t.push(watchErrors((error, mechanism) => this.report(error, false, { "zharp.mechanism": mechanism })));
|
|
1482
|
+
t.push(watchActivity(() => session.touch()));
|
|
1483
|
+
t.push(
|
|
1484
|
+
watchNavigation((route) => {
|
|
1485
|
+
session.touch();
|
|
1486
|
+
if (tracing) tracer.startRoot("navigation", route, { "url.full": redactUrl(location.href) });
|
|
1487
|
+
})
|
|
1488
|
+
);
|
|
1489
|
+
if (tracing && options.interactions !== false) t.push(watchClicks((label, selector) => tracer.noteClick(label, selector)));
|
|
1490
|
+
if (options.captureConsole || options.logs) {
|
|
1491
|
+
const methods = Array.isArray(options.captureConsole) ? options.captureConsole : ["debug", "log", "info", "warn", "error"];
|
|
1492
|
+
t.push(watchConsole(methods, (level, message) => this.emit(level, message, { "log.source": "console" })));
|
|
1493
|
+
}
|
|
1494
|
+
t.push(
|
|
1495
|
+
watchHide(() => {
|
|
1496
|
+
tracer.endAll();
|
|
1497
|
+
spans.flushOnHide();
|
|
1498
|
+
logs.flushOnHide();
|
|
1499
|
+
replay?.flushOnHide();
|
|
1500
|
+
})
|
|
1501
|
+
);
|
|
1502
|
+
replay?.start();
|
|
1503
|
+
if (tracing) this.startPageLoad(tracer);
|
|
1504
|
+
}
|
|
1505
|
+
/** The page load span: from navigation start until the load event, its requests, and a quiet second. */
|
|
1506
|
+
startPageLoad(tracer) {
|
|
1507
|
+
const timeOrigin = typeof performance !== "undefined" && performance.timeOrigin ? performance.timeOrigin : now();
|
|
1508
|
+
const root = tracer.startRoot("pageload", currentRoute(), { "url.full": redactUrl(location.href), "document.referrer": document.referrer || void 0 }, timeOrigin);
|
|
1509
|
+
const loaded = () => {
|
|
1510
|
+
root.span.setAttributes(navigationTimings());
|
|
1511
|
+
root.release();
|
|
1512
|
+
};
|
|
1513
|
+
if (document.readyState === "complete") loaded();
|
|
1514
|
+
else {
|
|
1515
|
+
root.hold();
|
|
1516
|
+
window.addEventListener("load", () => setTimeout(loaded, 0), { once: true });
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Who is using the page: `enduser.id` (and `enduser.email`, `enduser.name`) on everything sent
|
|
1521
|
+
* from now on, and in the `baggage` header so the back end's spans and logs carry it too.
|
|
1522
|
+
* Call it after login and on every page load while logged in.
|
|
1523
|
+
*/
|
|
1524
|
+
setUser(user) {
|
|
1525
|
+
safely(() => {
|
|
1526
|
+
this.user = user && user.id !== void 0 && user.id !== null && user.id !== "" ? { id: user.id, email: user.email, name: user.name } : null;
|
|
1527
|
+
this.running?.session.update({ user: this.user });
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
/** Forget the user and start a new session — call it on logout. */
|
|
1531
|
+
clearUser() {
|
|
1532
|
+
safely(() => {
|
|
1533
|
+
this.user = null;
|
|
1534
|
+
this.running?.session.renew(null);
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
/** An attribute on every span and log from now on. `null` removes it. */
|
|
1538
|
+
setTag(key, value) {
|
|
1539
|
+
if (value === null || value === void 0) delete this.tags[key];
|
|
1540
|
+
else this.tags[key] = value;
|
|
1541
|
+
}
|
|
1542
|
+
/** Report an error you caught. Sent as handled, and grouped into an issue with its other occurrences. */
|
|
1543
|
+
captureError(error, attributes) {
|
|
1544
|
+
this.report(error, true, attributes);
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* React 19: the handler for createRoot's (or hydrateRoot's) error options. Each error a render
|
|
1548
|
+
* throws is reported once, as a crash, with the component stack — which components were
|
|
1549
|
+
* rendering — next to its own stack:
|
|
1550
|
+
*
|
|
1551
|
+
* createRoot(el, {
|
|
1552
|
+
* onUncaughtError: Zharp.reactErrorHandler(),
|
|
1553
|
+
* onCaughtError: Zharp.reactErrorHandler(),
|
|
1554
|
+
* });
|
|
1555
|
+
*
|
|
1556
|
+
* React's own reporting (the console) carries on as before; `callback` runs after, for an app
|
|
1557
|
+
* that had its own handler there. For React 18, use ZharpErrorBoundary from @zharp/browser/react.
|
|
1558
|
+
*/
|
|
1559
|
+
reactErrorHandler(callback) {
|
|
1560
|
+
return (error, errorInfo) => {
|
|
1561
|
+
this.reportReactError(error, errorInfo?.componentStack);
|
|
1562
|
+
if (callback) {
|
|
1563
|
+
callback(error, errorInfo ?? {});
|
|
1564
|
+
} else {
|
|
1565
|
+
safely(() => typeof reportError === "function" ? reportError(error) : console.error(error));
|
|
1566
|
+
}
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
/** @internal An error React caught, with the stack of components that were rendering. */
|
|
1570
|
+
reportReactError(error, componentStack) {
|
|
1571
|
+
const stack = typeof componentStack === "string" ? componentStack.trim().slice(0, 4e3) : "";
|
|
1572
|
+
this.report(error, false, { "zharp.mechanism": "react", ...stack ? { "react.component_stack": stack } : {} });
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Run `fn` in a span named `name`. Requests and logs from its synchronous part belong to it;
|
|
1576
|
+
* a promise it returns ends the span when it settles. Errors pass through unchanged.
|
|
1577
|
+
*/
|
|
1578
|
+
startSpan(name, fn, attributes) {
|
|
1579
|
+
const running = this.running;
|
|
1580
|
+
let span;
|
|
1581
|
+
if (running?.tracing) span = safely(() => running.tracer.startSpan(name, 1 /* Internal */));
|
|
1582
|
+
if (!running || !span) return fn(noopSpan);
|
|
1583
|
+
const s = span;
|
|
1584
|
+
if (attributes) s.setAttributes(attributes);
|
|
1585
|
+
const fail = (error) => safely(() => s.setStatus(2 /* Error */, asError(error).message).end());
|
|
1586
|
+
try {
|
|
1587
|
+
const result = running.tracer.withSpan(s, () => fn(s));
|
|
1588
|
+
if (result && typeof result.then === "function") {
|
|
1589
|
+
return result.then(
|
|
1590
|
+
(value) => {
|
|
1591
|
+
s.end();
|
|
1592
|
+
return value;
|
|
1593
|
+
},
|
|
1594
|
+
(error) => {
|
|
1595
|
+
fail(error);
|
|
1596
|
+
throw error;
|
|
1597
|
+
}
|
|
1598
|
+
);
|
|
1599
|
+
}
|
|
1600
|
+
s.end();
|
|
1601
|
+
return result;
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
fail(error);
|
|
1604
|
+
throw error;
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
/** Send everything waiting now. */
|
|
1608
|
+
async flush() {
|
|
1609
|
+
const running = this.running;
|
|
1610
|
+
if (!running) return;
|
|
1611
|
+
await Promise.all([running.spans.flush(), running.logs.flush(), running.replay?.flush()]).catch(() => {
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
/** Flush and stop: every patch is undone and nothing more is recorded. */
|
|
1615
|
+
async close() {
|
|
1616
|
+
const running = this.running;
|
|
1617
|
+
if (!running) return;
|
|
1618
|
+
running.tracer.endAll();
|
|
1619
|
+
await this.flush();
|
|
1620
|
+
await running.replay?.stop().catch(() => {
|
|
1621
|
+
});
|
|
1622
|
+
for (const undo of running.teardowns) safely(undo);
|
|
1623
|
+
this.running = null;
|
|
1624
|
+
}
|
|
1625
|
+
// ── internals ─────────────────────────────────────────────────────────
|
|
1626
|
+
/** Session, user and tags: on every span and log, as they are when it is sent. */
|
|
1627
|
+
contextAttributes() {
|
|
1628
|
+
const running = this.running;
|
|
1629
|
+
const user = this.user;
|
|
1630
|
+
return {
|
|
1631
|
+
...this.tags,
|
|
1632
|
+
"session.id": running?.session.id,
|
|
1633
|
+
"enduser.id": user ? String(user.id) : void 0,
|
|
1634
|
+
"enduser.email": user?.email,
|
|
1635
|
+
"enduser.name": user?.name
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
/** The `baggage` header value: session and user, for the back end to copy onto its spans. */
|
|
1639
|
+
baggage() {
|
|
1640
|
+
const parts = [];
|
|
1641
|
+
const session = this.running?.session.id;
|
|
1642
|
+
if (session) parts.push(`session.id=${encodeURIComponent(session)}`);
|
|
1643
|
+
if (this.user) parts.push(`enduser.id=${encodeURIComponent(String(this.user.id))}`);
|
|
1644
|
+
return parts.join(",");
|
|
1645
|
+
}
|
|
1646
|
+
emit(level, message, attributes, exception) {
|
|
1647
|
+
safely(() => {
|
|
1648
|
+
const running = this.running;
|
|
1649
|
+
if (!running) return;
|
|
1650
|
+
const span = running.tracer.activeSpan();
|
|
1651
|
+
const time = toNanos(now());
|
|
1652
|
+
const attrs = { ...this.contextAttributes(), "url.full": redactUrl(location.href) };
|
|
1653
|
+
for (const key in attributes) {
|
|
1654
|
+
const value = attributes[key];
|
|
1655
|
+
if (value instanceof Error && !exception && (level === "error" || level === "fatal")) {
|
|
1656
|
+
exception = exceptionAttributes(value, true);
|
|
1657
|
+
this.reported.add(value);
|
|
1658
|
+
} else attrs[key] = value;
|
|
1659
|
+
}
|
|
1660
|
+
running.logs.add({
|
|
1661
|
+
timeUnixNano: time,
|
|
1662
|
+
observedTimeUnixNano: time,
|
|
1663
|
+
severityNumber: SEVERITY[level],
|
|
1664
|
+
severityText: level.toUpperCase(),
|
|
1665
|
+
body: { stringValue: typeof message === "string" ? message : message instanceof Error ? message.message : safeString(message) },
|
|
1666
|
+
attributes: keyValues({ ...attrs, ...exception }),
|
|
1667
|
+
traceId: span?.traceId,
|
|
1668
|
+
spanId: span?.spanId
|
|
1669
|
+
});
|
|
1670
|
+
if (exception) running.replay?.onError();
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
1673
|
+
report(value, handled, attributes) {
|
|
1674
|
+
safely(() => {
|
|
1675
|
+
if (value && typeof value === "object") {
|
|
1676
|
+
if (this.reported.has(value)) return;
|
|
1677
|
+
this.reported.add(value);
|
|
1678
|
+
}
|
|
1679
|
+
const error = asError(value);
|
|
1680
|
+
const exception = exceptionAttributes(error, handled);
|
|
1681
|
+
this.emit("error", `${exception["exception.type"]}: ${exception["exception.message"]}`, attributes, exception);
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
var noopSpan = {
|
|
1686
|
+
traceId: "",
|
|
1687
|
+
spanId: "",
|
|
1688
|
+
setAttribute() {
|
|
1689
|
+
return noopSpan;
|
|
1690
|
+
},
|
|
1691
|
+
setAttributes() {
|
|
1692
|
+
return noopSpan;
|
|
1693
|
+
}
|
|
1694
|
+
};
|
|
1695
|
+
|
|
1696
|
+
// src/shared.ts
|
|
1697
|
+
var BRIDGE_GLOBAL = "__zharpElectron";
|
|
1698
|
+
|
|
1699
|
+
// src/version.ts
|
|
1700
|
+
var VERSION2 = "0.1.0";
|
|
1701
|
+
|
|
1702
|
+
// src/renderer/index.ts
|
|
1703
|
+
var SharedSession = class extends Session {
|
|
1704
|
+
constructor(bridge2, context) {
|
|
1705
|
+
super(Number.MAX_SAFE_INTEGER, { get: () => null, set: () => {
|
|
1706
|
+
} });
|
|
1707
|
+
this.bridge = bridge2;
|
|
1708
|
+
this.shared = { id: context.sessionId, started: context.sessionStarted, lastActive: Date.now(), user: context.user };
|
|
1709
|
+
}
|
|
1710
|
+
bridge;
|
|
1711
|
+
shared;
|
|
1712
|
+
follow(context) {
|
|
1713
|
+
this.shared = { ...this.shared, id: context.sessionId, started: context.sessionStarted, user: context.user };
|
|
1714
|
+
}
|
|
1715
|
+
get current() {
|
|
1716
|
+
return this.shared;
|
|
1717
|
+
}
|
|
1718
|
+
get id() {
|
|
1719
|
+
return this.shared.id;
|
|
1720
|
+
}
|
|
1721
|
+
touch() {
|
|
1722
|
+
this.shared.lastActive = Date.now();
|
|
1723
|
+
this.bridge.activity();
|
|
1724
|
+
}
|
|
1725
|
+
/** Logout in one window: main starts a new session and tells every window. */
|
|
1726
|
+
renew(user) {
|
|
1727
|
+
if (user === null) this.bridge.setUser(null);
|
|
1728
|
+
this.bridge.renew();
|
|
1729
|
+
}
|
|
1730
|
+
update(patch) {
|
|
1731
|
+
if ("user" in patch && !sameUser(patch.user ?? null, this.shared.user ?? null)) {
|
|
1732
|
+
this.shared.user = patch.user ?? null;
|
|
1733
|
+
this.bridge.setUser(patch.user ?? null);
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
onRenew() {
|
|
1737
|
+
}
|
|
1738
|
+
};
|
|
1739
|
+
function sameUser(a, b) {
|
|
1740
|
+
if (!a || !b) return a === b;
|
|
1741
|
+
return String(a.id) === String(b.id) && a.email === b.email && a.name === b.name;
|
|
1742
|
+
}
|
|
1743
|
+
function bridge() {
|
|
1744
|
+
const value = globalThis[BRIDGE_GLOBAL];
|
|
1745
|
+
return value && typeof value.send === "function" ? value : null;
|
|
1746
|
+
}
|
|
1747
|
+
function sendThrough(b) {
|
|
1748
|
+
return (async (input, init) => {
|
|
1749
|
+
const url = String(input);
|
|
1750
|
+
const signal = /\/v1\/(traces|logs)$/.exec(url)?.[1];
|
|
1751
|
+
if (!signal || typeof init?.body !== "string") return { status: 400 };
|
|
1752
|
+
const status = await b.send(signal, init.body);
|
|
1753
|
+
return { status };
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
var ZharpElectronRenderer = class extends ZharpBrowser {
|
|
1757
|
+
bridged;
|
|
1758
|
+
session;
|
|
1759
|
+
startContext;
|
|
1760
|
+
constructor() {
|
|
1761
|
+
const b = bridge();
|
|
1762
|
+
const context = b ? safeContext(b) : null;
|
|
1763
|
+
const session = b && context ? new SharedSession(b, context) : null;
|
|
1764
|
+
super(
|
|
1765
|
+
b && session ? {
|
|
1766
|
+
fetch: sendThrough(b),
|
|
1767
|
+
session,
|
|
1768
|
+
resource: { ...context.resource, "zharp.sdk.platform": "electron", "electron.process.type": "renderer" },
|
|
1769
|
+
scope: { name: "@zharp/electron", version: VERSION2 }
|
|
1770
|
+
} : void 0
|
|
1771
|
+
);
|
|
1772
|
+
this.bridged = b;
|
|
1773
|
+
this.session = session;
|
|
1774
|
+
this.startContext = context;
|
|
1775
|
+
}
|
|
1776
|
+
/** Starts the SDK in this window, with the main process's key, service, release and session. */
|
|
1777
|
+
init(options = {}) {
|
|
1778
|
+
try {
|
|
1779
|
+
const b = this.bridged;
|
|
1780
|
+
const context = this.startContext;
|
|
1781
|
+
if (!b || !context) {
|
|
1782
|
+
console.warn(
|
|
1783
|
+
"[Zharp] @zharp/electron/renderer can't reach the main process: start Zharp in main (Zharp.init from '@zharp/electron/main'), and if main is bundled, add import '@zharp/electron/preload' to your preload. Nothing will be sent from this window."
|
|
1784
|
+
);
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
const settings = { ...context.renderer, ...options };
|
|
1788
|
+
super.init({
|
|
1789
|
+
...settings,
|
|
1790
|
+
key: context.key,
|
|
1791
|
+
endpoint: context.endpoint,
|
|
1792
|
+
service: settings.service ?? context.service,
|
|
1793
|
+
release: settings.release ?? context.release,
|
|
1794
|
+
environment: settings.environment ?? context.environment
|
|
1795
|
+
});
|
|
1796
|
+
if (context.user) super.setUser(context.user);
|
|
1797
|
+
b.onChange((next) => {
|
|
1798
|
+
this.session?.follow(next);
|
|
1799
|
+
super.setUser(next.user);
|
|
1800
|
+
});
|
|
1801
|
+
} catch {
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
/** The device ID main keeps for this installation. */
|
|
1805
|
+
get deviceId() {
|
|
1806
|
+
return this.startContext?.deviceId;
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
function safeContext(b) {
|
|
1810
|
+
try {
|
|
1811
|
+
return b.context();
|
|
1812
|
+
} catch {
|
|
1813
|
+
return null;
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
var g = globalThis;
|
|
1817
|
+
var Zharp = g.__ZHARP_BROWSER__ instanceof ZharpElectronRenderer ? g.__ZHARP_BROWSER__ : g.__ZHARP_BROWSER__ = new ZharpElectronRenderer();
|
|
1818
|
+
var renderer_default = Zharp;
|
|
1819
|
+
|
|
1820
|
+
export { VERSION2 as VERSION, Zharp, ZharpElectronRenderer, renderer_default as default };
|
|
1821
|
+
//# sourceMappingURL=renderer.mjs.map
|
|
1822
|
+
//# sourceMappingURL=renderer.mjs.map
|