@maple-dev/browser 0.9.0 → 0.10.1
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 +86 -3
- package/dist/console-BrjBnOiX.mjs +73 -0
- package/dist/deferred-BDp5NC7U.mjs +723 -0
- package/dist/index.d.mts +165 -14
- package/dist/index.mjs +1 -854
- package/dist/react.d.mts +88 -0
- package/dist/react.mjs +130 -0
- package/dist/replay-session-DdVYdHc_.mjs +527 -0
- package/dist/{sink-DHPiMgU0.mjs → sink-BOR9_z4b.mjs} +293 -104
- package/dist/src-D4e1o0x4.mjs +1719 -0
- package/package.json +32 -10
- package/dist/replay-session-gSlAYwqV.mjs +0 -360
|
@@ -0,0 +1,1719 @@
|
|
|
1
|
+
import { A as setActiveTraceIdProvider, F as scrubUrl, M as configureVisitorCookie, N as setVisitorTracking, P as addUrlSanitizer, _ as rotateSession, a as recordTraceId, c as getActiveSink, d as startEventSink, f as claimReplayMode, i as readSessionSink, n as getObservedTraceIds, o as startSessionLifecycle, p as getSession, r as publishSessionSink, s as clearPendingEvents, t as clearSessionSink, u as queuePending, v as postSessionMetaRow, w as sdkHint, x as ingestHeaders, y as isLikelyBot } from "./sink-BOR9_z4b.mjs";
|
|
2
|
+
import { ProxyTracerProvider, SpanKind, SpanStatusCode, TraceFlags, context, createContextKey, createTraceState, isSpanContextValid, propagation, trace } from "@opentelemetry/api";
|
|
3
|
+
import { BatchSpanProcessor, SamplingDecision } from "@opentelemetry/sdk-trace-base";
|
|
4
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
5
|
+
import { registerInstrumentations } from "@opentelemetry/instrumentation";
|
|
6
|
+
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
|
|
7
|
+
import { XMLHttpRequestInstrumentation } from "@opentelemetry/instrumentation-xml-http-request";
|
|
8
|
+
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
9
|
+
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
|
|
10
|
+
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
|
|
11
|
+
//#region ../browser-session/src/identity/consent.ts
|
|
12
|
+
/**
|
|
13
|
+
* Consent gating for session capture.
|
|
14
|
+
*
|
|
15
|
+
* The posture, deliberately:
|
|
16
|
+
*
|
|
17
|
+
* - `requireConsent` defaults to **false**. Flipping that default would
|
|
18
|
+
* silently stop telemetry for every existing install — an availability
|
|
19
|
+
* incident dressed up as a privacy win. Apps that need a consent gate opt in.
|
|
20
|
+
* - Global Privacy Control **is** honored by default, but only against the
|
|
21
|
+
* persistent visitor id, not the session itself. GPC is a legally recognized
|
|
22
|
+
* signal in several US states and it maps exactly onto the one cross-session
|
|
23
|
+
* identifier this SDK stores; the session-scoped capture that powers replay
|
|
24
|
+
* and error triage is unaffected.
|
|
25
|
+
* - `doNotTrack` is **not** honored by default. It is deprecated, removed from
|
|
26
|
+
* Safari, and ignored across the industry, so respecting it would mostly mean
|
|
27
|
+
* dropping data from users who never intended to opt out. Apps can turn it on.
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* Consent lives on `globalThis`, for the same reason the event sink does
|
|
31
|
+
* (`events/events-sink.ts`): an app that bundles both `@maple-dev/browser` and the
|
|
32
|
+
* Effect SDK gets **two copies** of this module, and per-copy state would mean
|
|
33
|
+
* `setConsent(true)` on one never releases the other copy's exporters — or, the
|
|
34
|
+
* other way round, one copy capturing while the other believes consent is
|
|
35
|
+
* required. There is one user and one decision, so there is one state.
|
|
36
|
+
*/
|
|
37
|
+
const CONSENT_KEY = "__MAPLE_BROWSER_CONSENT__";
|
|
38
|
+
function consentState() {
|
|
39
|
+
const owner = globalThis;
|
|
40
|
+
const existing = owner[CONSENT_KEY];
|
|
41
|
+
if (existing) return existing;
|
|
42
|
+
const fresh = {
|
|
43
|
+
allowedSince: 0,
|
|
44
|
+
granted: false,
|
|
45
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
46
|
+
requireConsent: false,
|
|
47
|
+
respectDoNotTrack: false
|
|
48
|
+
};
|
|
49
|
+
owner[CONSENT_KEY] = fresh;
|
|
50
|
+
return fresh;
|
|
51
|
+
}
|
|
52
|
+
/** When consent was last withdrawn, on any page of this origin. Persisted: the grant time resets every load. */
|
|
53
|
+
const REVOKED_AT_KEY = "maple-consent-revoked-at";
|
|
54
|
+
function writeRevokedAt(at) {
|
|
55
|
+
try {
|
|
56
|
+
localStorage.setItem(REVOKED_AT_KEY, String(at));
|
|
57
|
+
} catch {}
|
|
58
|
+
}
|
|
59
|
+
/** Epoch ms of the last consent withdrawal on this origin, 0 if never. Data kept from before it must not be sent. */
|
|
60
|
+
function consentRevokedAt() {
|
|
61
|
+
try {
|
|
62
|
+
return Number(localStorage.getItem(REVOKED_AT_KEY)) || 0;
|
|
63
|
+
} catch {
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function updateEffectiveConsent(previous) {
|
|
68
|
+
const state = consentState();
|
|
69
|
+
const allowed = hasConsent();
|
|
70
|
+
if (allowed === previous) return;
|
|
71
|
+
state.allowedSince = allowed ? Date.now() : Number.POSITIVE_INFINITY;
|
|
72
|
+
for (const listener of state.listeners) try {
|
|
73
|
+
listener(allowed);
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Apply the host app's privacy config. Call before anything captures.
|
|
78
|
+
*
|
|
79
|
+
* Both SDKs call this at startup, and an app can init one of them without a
|
|
80
|
+
* `privacy` block — so the gates only ever **tighten**. Letting the second
|
|
81
|
+
* caller's absent option reset `requireConsent` back to false would silently
|
|
82
|
+
* disable a gate the first caller asked for, and the resulting
|
|
83
|
+
* denied→allowed transition would start capture on a user who never consented.
|
|
84
|
+
* To genuinely relax a gate, reload without it.
|
|
85
|
+
*/
|
|
86
|
+
function configurePrivacy(options) {
|
|
87
|
+
const state = consentState();
|
|
88
|
+
const previous = hasConsent();
|
|
89
|
+
state.requireConsent = state.requireConsent || (options?.requireConsent ?? false);
|
|
90
|
+
state.respectDoNotTrack = state.respectDoNotTrack || (options?.respectDoNotTrack ?? false);
|
|
91
|
+
configureVisitorCookie({
|
|
92
|
+
crossSubdomainCookie: options?.crossSubdomainCookie,
|
|
93
|
+
cookieDomain: options?.cookieDomain
|
|
94
|
+
});
|
|
95
|
+
if (options?.sanitizeUrl) addUrlSanitizer(options.sanitizeUrl);
|
|
96
|
+
updateEffectiveConsent(previous);
|
|
97
|
+
}
|
|
98
|
+
/** Record the user's consent decision. No-op unless `requireConsent` is set. */
|
|
99
|
+
function setConsent(nextGranted) {
|
|
100
|
+
const previous = hasConsent();
|
|
101
|
+
const state = consentState();
|
|
102
|
+
if (state.granted && !nextGranted) writeRevokedAt(Date.now());
|
|
103
|
+
state.granted = nextGranted;
|
|
104
|
+
updateEffectiveConsent(previous);
|
|
105
|
+
}
|
|
106
|
+
/** Whether capture may proceed at all. */
|
|
107
|
+
function hasConsent() {
|
|
108
|
+
const state = consentState();
|
|
109
|
+
return !state.requireConsent || state.granted;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Subscribe to effective capture permission changes. The listener is invoked
|
|
113
|
+
* only when capture actually transitions between allowed and denied; changing
|
|
114
|
+
* the stored decision while `requireConsent` is off is deliberately silent.
|
|
115
|
+
*/
|
|
116
|
+
function onConsentChange(listener) {
|
|
117
|
+
const { listeners } = consentState();
|
|
118
|
+
listeners.add(listener);
|
|
119
|
+
return () => listeners.delete(listener);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Earliest epoch-ms timestamp telemetry may export for the current grant.
|
|
123
|
+
* `Infinity` means capture is denied. Exporters use this to discard anything
|
|
124
|
+
* buffered before a late grant or across a revoke/re-grant cycle.
|
|
125
|
+
*/
|
|
126
|
+
function consentAllowedSince() {
|
|
127
|
+
return hasConsent() ? consentState().allowedSince : Number.POSITIVE_INFINITY;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether a *persistent* identifier may be stored. Separate from `hasConsent`
|
|
131
|
+
* because GPC/DNT suppress the cross-session id without suppressing capture.
|
|
132
|
+
*/
|
|
133
|
+
function mayPersistIdentifier() {
|
|
134
|
+
if (!hasConsent()) return false;
|
|
135
|
+
if (typeof navigator === "undefined") return true;
|
|
136
|
+
const nav = navigator;
|
|
137
|
+
if (nav.globalPrivacyControl === true) return false;
|
|
138
|
+
if (consentState().respectDoNotTrack && nav.doNotTrack === "1") return false;
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region ../browser-session/src/identity/identity.ts
|
|
143
|
+
/**
|
|
144
|
+
* Trait caps. The warehouse column is `Map(String, String)` — plain keys
|
|
145
|
+
* precisely because they are arbitrary — so the cost of a unique key per user
|
|
146
|
+
* is row size and query-time map width rather than a churned dictionary. The
|
|
147
|
+
* cap bounds one row's damage; `warnOnIdLikeTraitKey` surfaces the pattern to
|
|
148
|
+
* whoever wrote it, since an id in a trait key is nearly always a mistake.
|
|
149
|
+
*/
|
|
150
|
+
const MAX_TRAITS = 24;
|
|
151
|
+
const MAX_TRAIT_KEY_LENGTH = 64;
|
|
152
|
+
const MAX_TRAIT_VALUE_LENGTH = 256;
|
|
153
|
+
let warnedAboutTraitKeys = false;
|
|
154
|
+
/** Heuristic: a trait *key* that looks like an id is almost always a mistake. */
|
|
155
|
+
function looksLikeId(key) {
|
|
156
|
+
return /^[0-9a-f]{8,}$/i.test(key) || /^(usr|user|org|cus|acct)_/i.test(key);
|
|
157
|
+
}
|
|
158
|
+
function coerceTraitValue(value) {
|
|
159
|
+
if (value === null || value === void 0) return void 0;
|
|
160
|
+
return (typeof value === "string" ? value : String(value)).slice(0, MAX_TRAIT_VALUE_LENGTH);
|
|
161
|
+
}
|
|
162
|
+
function normalizeTraits(traits) {
|
|
163
|
+
if (!traits) return {};
|
|
164
|
+
const out = {};
|
|
165
|
+
for (const [rawKey, rawValue] of Object.entries(traits)) {
|
|
166
|
+
if (Object.keys(out).length >= MAX_TRAITS) break;
|
|
167
|
+
const value = coerceTraitValue(rawValue);
|
|
168
|
+
if (value === void 0) continue;
|
|
169
|
+
const key = rawKey.slice(0, MAX_TRAIT_KEY_LENGTH);
|
|
170
|
+
if (!key) continue;
|
|
171
|
+
if (!warnedAboutTraitKeys && looksLikeId(key)) {
|
|
172
|
+
warnedAboutTraitKeys = true;
|
|
173
|
+
console.warn(`[maple] identity trait key "${key}" looks like an id. A key per user widens every session row's trait map; put ids in the value, or in id/groupId, not the key.`);
|
|
174
|
+
}
|
|
175
|
+
out[key] = value;
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
function trimmed(value) {
|
|
180
|
+
const text = value?.trim();
|
|
181
|
+
return text ? text : void 0;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Normalize whatever a host app passed into the shape the metadata row wants.
|
|
185
|
+
*
|
|
186
|
+
* Each call *replaces* the identity rather than merging into the previous one.
|
|
187
|
+
* Merging would leak a signed-out user's email into the next person to use a
|
|
188
|
+
* shared device, and replacement is what the existing string-only `identify`
|
|
189
|
+
* already did.
|
|
190
|
+
*/
|
|
191
|
+
function normalizeIdentity(input) {
|
|
192
|
+
if (input === null || input === void 0) return void 0;
|
|
193
|
+
if (typeof input === "string") {
|
|
194
|
+
const id = trimmed(input);
|
|
195
|
+
return id ? {
|
|
196
|
+
id,
|
|
197
|
+
traits: {}
|
|
198
|
+
} : void 0;
|
|
199
|
+
}
|
|
200
|
+
const resolved = {
|
|
201
|
+
id: trimmed(input.id),
|
|
202
|
+
email: trimmed(input.email),
|
|
203
|
+
username: trimmed(input.username),
|
|
204
|
+
groupId: trimmed(input.groupId),
|
|
205
|
+
groupName: trimmed(input.groupName),
|
|
206
|
+
traits: normalizeTraits(input.traits)
|
|
207
|
+
};
|
|
208
|
+
return resolved.id || resolved.email || resolved.username || resolved.groupId || resolved.groupName || Object.keys(resolved.traits).length > 0 ? resolved : void 0;
|
|
209
|
+
}
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region ../browser-session/src/session/metadata-session.ts
|
|
212
|
+
/**
|
|
213
|
+
* Metadata-only session lifecycle used whenever rrweb is disabled or unsampled.
|
|
214
|
+
* It is the shared lifecycle driver with no capture of its own: the distilled
|
|
215
|
+
* event sink runs on every page load regardless, so this owner only has to post
|
|
216
|
+
* rows and flush that sink on the way out.
|
|
217
|
+
*/
|
|
218
|
+
function startMetadataSession(options) {
|
|
219
|
+
return startSessionLifecycle(options, {
|
|
220
|
+
recorded: false,
|
|
221
|
+
post: (row, keepalive) => {
|
|
222
|
+
postSessionMetaRow(options, row, keepalive);
|
|
223
|
+
},
|
|
224
|
+
onSuspend: ({ flush, keepalive }) => {
|
|
225
|
+
if (flush && keepalive) getActiveSink()?.flush(true);
|
|
226
|
+
},
|
|
227
|
+
onSessionChange: options.onSessionChange
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
//#endregion
|
|
231
|
+
//#region ../browser-session/src/events/props.ts
|
|
232
|
+
const MAX_PROPS = 32;
|
|
233
|
+
const MAX_PROP_KEY_LENGTH = 64;
|
|
234
|
+
const MAX_PROP_VALUE_LENGTH = 1024;
|
|
235
|
+
const MAX_TOTAL_PROP_BYTES = 8192;
|
|
236
|
+
/**
|
|
237
|
+
* Coerce one property value to the string the warehouse column holds.
|
|
238
|
+
*
|
|
239
|
+
* `null`/`undefined`/functions/symbols are dropped rather than stringified —
|
|
240
|
+
* `"undefined"` as a stored value is worse than an absent key.
|
|
241
|
+
*/
|
|
242
|
+
function coerce(value) {
|
|
243
|
+
if (value === null || value === void 0) return void 0;
|
|
244
|
+
switch (typeof value) {
|
|
245
|
+
case "string": return value.slice(0, MAX_PROP_VALUE_LENGTH);
|
|
246
|
+
case "number":
|
|
247
|
+
case "boolean":
|
|
248
|
+
case "bigint": return String(value);
|
|
249
|
+
case "function":
|
|
250
|
+
case "symbol": return;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
if (value instanceof Date) return value.toISOString();
|
|
254
|
+
return JSON.stringify(value)?.slice(0, MAX_PROP_VALUE_LENGTH);
|
|
255
|
+
} catch {
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** Coerce and cap a `track()` property bag to the `Map(String, String)` the warehouse stores. */
|
|
260
|
+
function coerceTrackProps(props) {
|
|
261
|
+
if (!props) return {};
|
|
262
|
+
const out = {};
|
|
263
|
+
let bytes = 0;
|
|
264
|
+
for (const [rawKey, rawValue] of Object.entries(props)) {
|
|
265
|
+
if (Object.keys(out).length >= MAX_PROPS) break;
|
|
266
|
+
const value = coerce(rawValue);
|
|
267
|
+
if (value === void 0) continue;
|
|
268
|
+
const key = rawKey.slice(0, MAX_PROP_KEY_LENGTH);
|
|
269
|
+
if (!key) continue;
|
|
270
|
+
bytes += key.length + value.length;
|
|
271
|
+
if (bytes > MAX_TOTAL_PROP_BYTES) break;
|
|
272
|
+
out[key] = value;
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
//#endregion
|
|
277
|
+
//#region ../browser-session/src/events/track.ts
|
|
278
|
+
let warnedAboutName = false;
|
|
279
|
+
/**
|
|
280
|
+
* Record a custom product event against the current session.
|
|
281
|
+
*
|
|
282
|
+
* Stored as a `session_events` row with `Type='custom'`, so it shows up inline
|
|
283
|
+
* in the session transcript alongside the clicks and network calls that
|
|
284
|
+
* surround it — not in a separate analytics silo.
|
|
285
|
+
*
|
|
286
|
+
* Safe to call before the SDK finishes initializing: events are queued (capped)
|
|
287
|
+
* and drained once the sink starts. Never throws.
|
|
288
|
+
*/
|
|
289
|
+
function track(name, props) {
|
|
290
|
+
if (!hasConsent()) return;
|
|
291
|
+
if (typeof name !== "string" || name.trim().length === 0) {
|
|
292
|
+
if (!warnedAboutName) {
|
|
293
|
+
warnedAboutName = true;
|
|
294
|
+
console.warn("[maple] track() needs a non-empty event name; the call was ignored.");
|
|
295
|
+
}
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const ev = {
|
|
299
|
+
type: "custom",
|
|
300
|
+
message: name.trim().slice(0, 128),
|
|
301
|
+
attrs: coerceTrackProps(props),
|
|
302
|
+
timestamp: Date.now(),
|
|
303
|
+
url: typeof location !== "undefined" ? location.href : void 0
|
|
304
|
+
};
|
|
305
|
+
const sink = getActiveSink();
|
|
306
|
+
if (sink) sink.emit(ev);
|
|
307
|
+
else queuePending(ev);
|
|
308
|
+
}
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region ../browser-session/src/platform/region.ts
|
|
311
|
+
const MAPLE_REGIONS = ["us", "eu"];
|
|
312
|
+
const INGEST_ENDPOINTS = {
|
|
313
|
+
us: "https://ingest.maple.dev",
|
|
314
|
+
eu: "https://ingest.eu.maple.dev"
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Narrow an untyped region (an env var, or a JS caller outside the type
|
|
318
|
+
* checker) to a known one. Case and surrounding whitespace are ignored;
|
|
319
|
+
* anything else is `undefined`.
|
|
320
|
+
*/
|
|
321
|
+
function parseRegion(raw) {
|
|
322
|
+
if (typeof raw !== "string") return void 0;
|
|
323
|
+
const value = raw.trim().toLowerCase();
|
|
324
|
+
return MAPLE_REGIONS.find((region) => region === value);
|
|
325
|
+
}
|
|
326
|
+
let warnedRegions = /* @__PURE__ */ new Set();
|
|
327
|
+
/**
|
|
328
|
+
* The ingest base URL for a region. An unrecognized value falls back to the
|
|
329
|
+
* default region with a console warning rather than throwing: the ingest key
|
|
330
|
+
* belongs to one instance, so the other one rejects it and no data lands in
|
|
331
|
+
* the wrong place.
|
|
332
|
+
*/
|
|
333
|
+
function ingestEndpointForRegion(region) {
|
|
334
|
+
if (region === void 0 || region === null || region === "") return INGEST_ENDPOINTS["us"];
|
|
335
|
+
const parsed = parseRegion(region);
|
|
336
|
+
if (parsed) return INGEST_ENDPOINTS[parsed];
|
|
337
|
+
const label = String(region);
|
|
338
|
+
if (!warnedRegions.has(label)) {
|
|
339
|
+
warnedRegions.add(label);
|
|
340
|
+
console.warn(`[maple] unknown region "${label}"; expected one of ${MAPLE_REGIONS.join(", ")}. Using "us".`);
|
|
341
|
+
}
|
|
342
|
+
return INGEST_ENDPOINTS["us"];
|
|
343
|
+
}
|
|
344
|
+
/** Loop rather than `/\/+$/`: that pattern backtracks polynomially on a long run of slashes. */
|
|
345
|
+
function trimTrailingSlashes(value) {
|
|
346
|
+
let end = value.length;
|
|
347
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
|
|
348
|
+
return value.slice(0, end);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Resolve the ingest base URL. An explicit URL always beats a region, whichever
|
|
352
|
+
* source each came from, so a collector or proxy endpoint is never bypassed by
|
|
353
|
+
* a region set elsewhere. Candidates are tried in order; the first non-empty
|
|
354
|
+
* one wins.
|
|
355
|
+
*/
|
|
356
|
+
function resolveIngestEndpoint(options) {
|
|
357
|
+
for (const endpoint of options.endpoints) if (endpoint) return trimTrailingSlashes(endpoint);
|
|
358
|
+
return ingestEndpointForRegion(options.regions.find((value) => value !== void 0 && value !== null && value !== ""));
|
|
359
|
+
}
|
|
360
|
+
/** Maple's hosted ingest, which rejects every write that carries no ingest key. */
|
|
361
|
+
function isMapleIngestEndpoint(endpoint) {
|
|
362
|
+
let parsed;
|
|
363
|
+
try {
|
|
364
|
+
parsed = new URL(endpoint);
|
|
365
|
+
} catch {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
if (trimTrailingSlashes(parsed.pathname) !== "") return false;
|
|
369
|
+
return MAPLE_REGIONS.some((region) => INGEST_ENDPOINTS[region] === parsed.origin);
|
|
370
|
+
}
|
|
371
|
+
let keylessWarned = /* @__PURE__ */ new Set();
|
|
372
|
+
/**
|
|
373
|
+
* Warn once per SDK about the one keyless setup that cannot work. The ingest
|
|
374
|
+
* key is auth only, so every SDK still sends without one (a proxy or local sink
|
|
375
|
+
* in front of a custom endpoint completes it), but Maple's hosted ingest 401s.
|
|
376
|
+
*/
|
|
377
|
+
function warnIfKeylessMapleIngest(options) {
|
|
378
|
+
if (options.hasIngestKey || !isMapleIngestEndpoint(options.endpoint)) return;
|
|
379
|
+
if (keylessWarned.has(options.logPrefix)) return;
|
|
380
|
+
keylessWarned.add(options.logPrefix);
|
|
381
|
+
console.warn(`${options.logPrefix} sending to the public Maple ingest without an ingest key; every request will be rejected with 401. ${options.hint}`);
|
|
382
|
+
}
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region ../sdk-core/src/errors.ts
|
|
385
|
+
/** Deep enough for real wrapping chains, bounded against a cause cycle or a huge aggregate. */
|
|
386
|
+
const MAX_LINKED = 5;
|
|
387
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
388
|
+
/** Error-shaped: an `Error`, or a copy with its fields (Effect's pretty errors, a structured clone). */
|
|
389
|
+
const isErrorLike = (value) => value instanceof Error || isRecord(value) && typeof value.name === "string" && typeof value.message === "string" && (value.stack === void 0 || typeof value.stack === "string");
|
|
390
|
+
/**
|
|
391
|
+
* BOUNDARY: a thrown value is unparsed by definition, JavaScript can throw anything.
|
|
392
|
+
* Narrow it into an `Error` without ever throwing from the error path.
|
|
393
|
+
*/
|
|
394
|
+
function asError(value) {
|
|
395
|
+
if (value instanceof Error) return value;
|
|
396
|
+
if (typeof value === "string") return new Error(value);
|
|
397
|
+
if (isRecord(value) && typeof value.message === "string") return new Error(value.message);
|
|
398
|
+
try {
|
|
399
|
+
return new Error(String(value));
|
|
400
|
+
} catch {
|
|
401
|
+
return /* @__PURE__ */ new Error("Unknown error");
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/** What an error links to: its `cause`, and its `errors` list (duck-typed, so copies qualify). */
|
|
405
|
+
const linksOf = (value) => {
|
|
406
|
+
if (!isErrorLike(value)) return [];
|
|
407
|
+
const next = [];
|
|
408
|
+
try {
|
|
409
|
+
if ("errors" in value && Array.isArray(value.errors)) next.push(...value.errors);
|
|
410
|
+
if (value.cause !== void 0) next.push(value.cause);
|
|
411
|
+
} catch {}
|
|
412
|
+
return next;
|
|
413
|
+
};
|
|
414
|
+
/** A null-prototype object or a throwing `toString` must not break the error path. */
|
|
415
|
+
function render(value) {
|
|
416
|
+
if (isRecord(value) && typeof value.message === "string") return value.message;
|
|
417
|
+
try {
|
|
418
|
+
return String(value);
|
|
419
|
+
} catch {
|
|
420
|
+
return Object.prototype.toString.call(value);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function linkedErrors(error) {
|
|
424
|
+
const linked = [];
|
|
425
|
+
const seen = /* @__PURE__ */ new Set([error]);
|
|
426
|
+
const queue = [error];
|
|
427
|
+
while (queue.length > 0 && linked.length < MAX_LINKED) for (const candidate of linksOf(queue.shift())) {
|
|
428
|
+
if (seen.has(candidate) || linked.length >= MAX_LINKED) continue;
|
|
429
|
+
seen.add(candidate);
|
|
430
|
+
linked.push(candidate);
|
|
431
|
+
queue.push(candidate);
|
|
432
|
+
}
|
|
433
|
+
return linked;
|
|
434
|
+
}
|
|
435
|
+
/** V8 starts a stack with a `Name: message` header; the other engines start at the first frame. */
|
|
436
|
+
function framesOf(error) {
|
|
437
|
+
const stack = typeof error.stack === "string" ? error.stack : "";
|
|
438
|
+
const header = error.message ? `${error.name}: ${error.message}` : error.name;
|
|
439
|
+
return stack.startsWith(header) ? stack.slice(header.length).replace(/^\n/, "") : stack;
|
|
440
|
+
}
|
|
441
|
+
function describe(value) {
|
|
442
|
+
if (!isErrorLike(value)) return `Caused by: ${render(value)}`;
|
|
443
|
+
const frames = framesOf(value);
|
|
444
|
+
const header = `Caused by: ${value.name}: ${value.message}`;
|
|
445
|
+
return frames ? `${header}\n${frames}` : header;
|
|
446
|
+
}
|
|
447
|
+
/** The stack trace to record for `error`, with its linked errors appended. */
|
|
448
|
+
function stackWithCauses(error) {
|
|
449
|
+
const linked = linkedErrors(error);
|
|
450
|
+
if (linked.length === 0) return error.stack;
|
|
451
|
+
return [error.stack ?? `${error.name}: ${error.message}`, ...linked.map(describe)].join("\n");
|
|
452
|
+
}
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region ../sdk-core/src/error-filters.ts
|
|
455
|
+
const EXTENSION_URL = /^(?:chrome|moz|safari(?:-web)?|ms-browser)-extension:\/\//;
|
|
456
|
+
const BENIGN_MESSAGES = [/^ResizeObserver loop (?:limit exceeded|completed with undelivered notifications)/];
|
|
457
|
+
const URL_SCHEME = /^[a-z][\w+.-]*:\/\//i;
|
|
458
|
+
const DIGITS = /^\d+$/;
|
|
459
|
+
/**
|
|
460
|
+
* The script URL of one frame: `at fn (url:1:2)`, `at url:1:2` (V8) or `fn@url:1:2`
|
|
461
|
+
* (SpiderMonkey, JavaScriptCore). Parsed by position, not one regex: a stack is page
|
|
462
|
+
* data, and a backtracking pattern over it can be made to run in polynomial time.
|
|
463
|
+
*/
|
|
464
|
+
function frameUrl(line) {
|
|
465
|
+
let frame = line.trim();
|
|
466
|
+
if (frame.endsWith(")")) {
|
|
467
|
+
const open = frame.lastIndexOf("(");
|
|
468
|
+
if (open === -1) return void 0;
|
|
469
|
+
frame = frame.slice(open + 1, -1);
|
|
470
|
+
} else if (frame.startsWith("at ")) frame = frame.slice(3);
|
|
471
|
+
else {
|
|
472
|
+
const at = frame.lastIndexOf("@");
|
|
473
|
+
if (at === -1) return void 0;
|
|
474
|
+
frame = frame.slice(at + 1);
|
|
475
|
+
}
|
|
476
|
+
for (let parts = 0; parts < 2; parts++) {
|
|
477
|
+
const colon = frame.lastIndexOf(":");
|
|
478
|
+
if (colon === -1 || !DIGITS.test(frame.slice(colon + 1))) {
|
|
479
|
+
if (parts === 0) return void 0;
|
|
480
|
+
break;
|
|
481
|
+
}
|
|
482
|
+
frame = frame.slice(0, colon);
|
|
483
|
+
}
|
|
484
|
+
if (!URL_SCHEME.test(frame) || /[\s()]/.test(frame)) return void 0;
|
|
485
|
+
return frame;
|
|
486
|
+
}
|
|
487
|
+
/** The script URL of each stack frame, top first. */
|
|
488
|
+
function frameUrls(stack) {
|
|
489
|
+
if (!stack) return [];
|
|
490
|
+
const urls = [];
|
|
491
|
+
for (const line of stack.split("\n")) {
|
|
492
|
+
const url = frameUrl(line);
|
|
493
|
+
if (url) urls.push(url);
|
|
494
|
+
}
|
|
495
|
+
return urls;
|
|
496
|
+
}
|
|
497
|
+
const matches = (value, patterns) => patterns.some((pattern) => {
|
|
498
|
+
if (typeof pattern === "string") return value.includes(pattern);
|
|
499
|
+
pattern.lastIndex = 0;
|
|
500
|
+
return pattern.test(value);
|
|
501
|
+
});
|
|
502
|
+
/**
|
|
503
|
+
* Build the filter for `options`. Without a `frameUrl`, only a thrown `Error`
|
|
504
|
+
* has frames of its own: an `Error` wrapped around anything else points at the
|
|
505
|
+
* SDK, so no URL list applies to it.
|
|
506
|
+
*/
|
|
507
|
+
function makeErrorFilter(options = {}) {
|
|
508
|
+
return (error, hint, frameUrl) => {
|
|
509
|
+
const text = `${error.name}: ${error.message}`;
|
|
510
|
+
const topUrl = frameUrl ?? (hint.originalError instanceof Error ? frameUrls(error.stack)[0] : void 0);
|
|
511
|
+
if (options.defaultFilters !== false) {
|
|
512
|
+
if (matches(error.message, BENIGN_MESSAGES)) return false;
|
|
513
|
+
if (topUrl && EXTENSION_URL.test(topUrl)) return false;
|
|
514
|
+
}
|
|
515
|
+
if (options.ignore && matches(text, options.ignore)) return false;
|
|
516
|
+
if (topUrl && options.denyUrls && matches(topUrl, options.denyUrls)) return false;
|
|
517
|
+
if (topUrl && options.allowUrls?.length && !matches(topUrl, options.allowUrls)) return false;
|
|
518
|
+
if (!options.beforeCapture) return true;
|
|
519
|
+
try {
|
|
520
|
+
return options.beforeCapture(error, hint) !== false;
|
|
521
|
+
} catch {
|
|
522
|
+
return true;
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
//#endregion
|
|
527
|
+
//#region ../sdk-core/src/http-headers.ts
|
|
528
|
+
/** Never recorded, even when listed: they carry credentials. */
|
|
529
|
+
const CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
530
|
+
"authorization",
|
|
531
|
+
"proxy-authorization",
|
|
532
|
+
"cookie",
|
|
533
|
+
"set-cookie",
|
|
534
|
+
"x-api-key"
|
|
535
|
+
]);
|
|
536
|
+
function resolveHeaderCapture(raw) {
|
|
537
|
+
const clean = (names) => (names ?? []).map((name) => name.toLowerCase()).filter((name) => !CREDENTIAL_HEADERS.has(name));
|
|
538
|
+
return {
|
|
539
|
+
request: clean(raw?.request),
|
|
540
|
+
response: clean(raw?.response)
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
//#endregion
|
|
544
|
+
//#region ../sdk-core/src/http-status.ts
|
|
545
|
+
/** The statuses the HTTP semantic conventions make a client span Error for: every 4xx and 5xx. */
|
|
546
|
+
const DEFAULT_ERROR_STATUS = [[400, 599]];
|
|
547
|
+
const inStatusRanges = (status, ranges) => ranges.some((range) => typeof range === "number" ? range === status : status >= range[0] && status <= range[1]);
|
|
548
|
+
/** The status on a span's attributes, current or pre-1.23 semconv key. */
|
|
549
|
+
function responseStatus(read) {
|
|
550
|
+
const value = read("http.response.status_code") ?? read("http.status_code");
|
|
551
|
+
if (typeof value === "number") return value;
|
|
552
|
+
if (typeof value === "string" && /^\d{3}$/.test(value)) return Number(value);
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* The `error.type` for a counted status or a network failure (`TypeError`,
|
|
556
|
+
* `timeout`), per the HTTP semantic conventions. No message: `error.message` is
|
|
557
|
+
* deprecated, and the status code already says what went wrong.
|
|
558
|
+
*/
|
|
559
|
+
function httpErrorType(status) {
|
|
560
|
+
return { "error.type": String(status) };
|
|
561
|
+
}
|
|
562
|
+
//#endregion
|
|
563
|
+
//#region ../sdk-core/src/log-record.ts
|
|
564
|
+
/** OTel severity numbers for the levels the SDKs emit. */
|
|
565
|
+
const Severity = {
|
|
566
|
+
DEBUG: 5,
|
|
567
|
+
INFO: 9,
|
|
568
|
+
WARN: 13,
|
|
569
|
+
ERROR: 17
|
|
570
|
+
};
|
|
571
|
+
/** A `Map`, not an object: a level string like `"constructor"` must not reach the prototype. */
|
|
572
|
+
const LEVELS = /* @__PURE__ */ new Map([
|
|
573
|
+
["error", "ERROR"],
|
|
574
|
+
["warn", "WARN"],
|
|
575
|
+
["debug", "DEBUG"]
|
|
576
|
+
]);
|
|
577
|
+
/** Severity for a console level: `log` and `info` are INFO. */
|
|
578
|
+
function severityOf(level) {
|
|
579
|
+
const text = (level !== void 0 ? LEVELS.get(level) : void 0) ?? "INFO";
|
|
580
|
+
return {
|
|
581
|
+
number: Severity[text],
|
|
582
|
+
text
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
//#endregion
|
|
586
|
+
//#region ../sdk-core/src/sampling.ts
|
|
587
|
+
/** FNV-1a over the session id, mapped to [0, 1). */
|
|
588
|
+
function sessionRoll(sessionId) {
|
|
589
|
+
let hash = 2166136261;
|
|
590
|
+
for (let i = 0; i < sessionId.length; i++) {
|
|
591
|
+
hash ^= sessionId.charCodeAt(i);
|
|
592
|
+
hash = Math.imul(hash, 16777619);
|
|
593
|
+
}
|
|
594
|
+
return (hash >>> 0) / 2 ** 32;
|
|
595
|
+
}
|
|
596
|
+
const MAX_56 = 2 ** 56;
|
|
597
|
+
/** 56 bits as the 14-hex-digit form `ot=th`/`ot=rv` use; `th` drops trailing zeros. */
|
|
598
|
+
const hex56 = (value) => value.toString(16).padStart(14, "0");
|
|
599
|
+
/**
|
|
600
|
+
* The W3C `ot=th:` rejection threshold for a sampling probability: 56 bits,
|
|
601
|
+
* hex, trailing zeros dropped. Ingest reads it back as the span's weight.
|
|
602
|
+
*/
|
|
603
|
+
function rejectionThreshold(probability) {
|
|
604
|
+
return hex56(Math.round((1 - probability) * MAX_56)).replace(/0+$/, "") || "0";
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* The session's randomness as the W3C `ot=rv:` value. The decision is `rv >= th`,
|
|
608
|
+
* so a downstream consistent-probability sampler reaches the same answer.
|
|
609
|
+
*/
|
|
610
|
+
function randomnessValue(roll) {
|
|
611
|
+
return Math.min(MAX_56 - 1, Math.floor((1 - roll) * MAX_56));
|
|
612
|
+
}
|
|
613
|
+
const KEEP$1 = { sampled: true };
|
|
614
|
+
const DROP = { sampled: false };
|
|
615
|
+
/**
|
|
616
|
+
* Whether a new root trace in `sessionId` is exported at `rate`. Without a
|
|
617
|
+
* session (SSR, consent withheld) the roll is per trace.
|
|
618
|
+
*/
|
|
619
|
+
function sampleSession(sessionId, rate) {
|
|
620
|
+
if (rate >= 1) return KEEP$1;
|
|
621
|
+
if (rate <= 0) return DROP;
|
|
622
|
+
const rv = randomnessValue(sessionId ? sessionRoll(sessionId) : Math.random());
|
|
623
|
+
if (rv < Math.round((1 - rate) * MAX_56)) return DROP;
|
|
624
|
+
return {
|
|
625
|
+
sampled: true,
|
|
626
|
+
traceState: `ot=th:${rejectionThreshold(rate)};rv:${hex56(rv)}`
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
/** A rate outside 0 to 1 is a typo, not a policy: clamp it and say so. */
|
|
630
|
+
function resolveSampleRate(option, raw, fallback = 1) {
|
|
631
|
+
if (raw === void 0) return fallback;
|
|
632
|
+
if (typeof raw !== "number" || Number.isNaN(raw)) {
|
|
633
|
+
console.warn(`[maple] ${option} must be a number between 0 and 1; got ${String(raw)}. Using ${fallback}.`);
|
|
634
|
+
return fallback;
|
|
635
|
+
}
|
|
636
|
+
if (raw < 0 || raw > 1) {
|
|
637
|
+
const clamped = Math.min(1, Math.max(0, raw));
|
|
638
|
+
console.warn(`[maple] ${option} must be between 0 and 1; got ${raw}. Using ${clamped}.`);
|
|
639
|
+
return clamped;
|
|
640
|
+
}
|
|
641
|
+
return raw;
|
|
642
|
+
}
|
|
643
|
+
//#endregion
|
|
644
|
+
//#region ../sdk-core/src/options.ts
|
|
645
|
+
function resolveSignalOptions(options) {
|
|
646
|
+
return {
|
|
647
|
+
tracingSampleRate: resolveSampleRate("tracing.sampleRate", options.tracing?.sampleRate),
|
|
648
|
+
captureHeaders: resolveHeaderCapture(options.tracing?.captureHeaders),
|
|
649
|
+
longFrames: options.tracing?.longFrames ?? false,
|
|
650
|
+
slowInteractions: options.tracing?.slowInteractions ?? false,
|
|
651
|
+
errorFilters: options.errors ?? {},
|
|
652
|
+
webVitals: options.webVitals ?? true,
|
|
653
|
+
breadcrumbs: options.breadcrumbs ?? true,
|
|
654
|
+
captureConsole: options.logs?.captureConsole ?? [],
|
|
655
|
+
reportCsp: options.reporting?.csp ?? true,
|
|
656
|
+
reportBrowser: options.reporting?.browserReports ?? false,
|
|
657
|
+
offlineQueue: options.transport?.offline ?? false
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
/** Ingest keeps 1,024 bytes of a session-event attribute; this leaves room for the cut marker. */
|
|
661
|
+
const MAX_BODY_LENGTH = 1e3;
|
|
662
|
+
function resolveReplayOptions(replay) {
|
|
663
|
+
return {
|
|
664
|
+
enabled: replay?.enabled ?? true,
|
|
665
|
+
sampleRate: resolveSampleRate("replay.sampleRate", replay?.sampleRate),
|
|
666
|
+
onErrorSampleRate: resolveSampleRate("replay.onErrorSampleRate", replay?.onErrorSampleRate, 0),
|
|
667
|
+
canvasFps: replay?.canvasFps,
|
|
668
|
+
networkBodies: replay?.networkBodies?.urls.length ? {
|
|
669
|
+
urls: replay.networkBodies.urls,
|
|
670
|
+
maxLength: Math.min(MAX_BODY_LENGTH, replay.networkBodies.maxLength ?? MAX_BODY_LENGTH)
|
|
671
|
+
} : void 0
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
//#region ../sdk-core/src/page.ts
|
|
676
|
+
/** Versioned: a copy with another layout gets its own slot instead of overwriting this one. */
|
|
677
|
+
const KEY = "__MAPLE_SDK_PAGE_V1__";
|
|
678
|
+
/** This bundled copy: instances of one copy share a lease, another copy does not. */
|
|
679
|
+
const COPY = Symbol("maple-sdk-copy");
|
|
680
|
+
const isPageState = (value) => typeof value === "object" && value !== null && "version" in value && value.version === 1;
|
|
681
|
+
function page() {
|
|
682
|
+
const owner = globalThis;
|
|
683
|
+
const existing = owner[KEY];
|
|
684
|
+
if (isPageState(existing)) return existing;
|
|
685
|
+
const fresh = {
|
|
686
|
+
version: 1,
|
|
687
|
+
reported: /* @__PURE__ */ new WeakSet(),
|
|
688
|
+
errorListeners: /* @__PURE__ */ new Set(),
|
|
689
|
+
leases: /* @__PURE__ */ new Map()
|
|
690
|
+
};
|
|
691
|
+
owner[KEY] = fresh;
|
|
692
|
+
return fresh;
|
|
693
|
+
}
|
|
694
|
+
/** Whether this exact error object was already recorded, by either SDK. */
|
|
695
|
+
function wasReported(error) {
|
|
696
|
+
return typeof error === "object" && error !== null && page().reported.has(error);
|
|
697
|
+
}
|
|
698
|
+
/** Claim `error` as recorded, so a rethrow or a second handler does not record it again. */
|
|
699
|
+
function markReported(error) {
|
|
700
|
+
if (typeof error === "object" && error !== null) page().reported.add(error);
|
|
701
|
+
}
|
|
702
|
+
/** Told about every recorded error: breadcrumbs export their trail, a buffered replay keeps itself. */
|
|
703
|
+
function onErrorRecorded(listener) {
|
|
704
|
+
page().errorListeners.add(listener);
|
|
705
|
+
return () => page().errorListeners.delete(listener);
|
|
706
|
+
}
|
|
707
|
+
function notifyErrorRecorded(link) {
|
|
708
|
+
for (const listener of page().errorListeners) try {
|
|
709
|
+
listener(link);
|
|
710
|
+
} catch {}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Lease one page collector for this bundled copy. `undefined` means another
|
|
714
|
+
* copy already runs it, and starting it again would report everything twice.
|
|
715
|
+
*/
|
|
716
|
+
function claimPageSignal(signal) {
|
|
717
|
+
const leases = page().leases;
|
|
718
|
+
const lease = leases.get(signal);
|
|
719
|
+
if (lease && lease.owner !== COPY) return void 0;
|
|
720
|
+
const held = lease ?? {
|
|
721
|
+
owner: COPY,
|
|
722
|
+
count: 0
|
|
723
|
+
};
|
|
724
|
+
held.count++;
|
|
725
|
+
leases.set(signal, held);
|
|
726
|
+
let released = false;
|
|
727
|
+
return () => {
|
|
728
|
+
if (released) return;
|
|
729
|
+
released = true;
|
|
730
|
+
held.count--;
|
|
731
|
+
if (held.count <= 0 && leases.get(signal) === held) leases.delete(signal);
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
//#endregion
|
|
735
|
+
//#region src/error-causes.ts
|
|
736
|
+
/**
|
|
737
|
+
* What to hand `span.recordException`: the error itself when nothing is linked,
|
|
738
|
+
* otherwise a copy carrying the longer stack. `code` is kept because OTel
|
|
739
|
+
* prefers it over `name` for `exception.type`.
|
|
740
|
+
*/
|
|
741
|
+
function exceptionOf(error) {
|
|
742
|
+
const stack = stackWithCauses(error);
|
|
743
|
+
if (stack === error.stack) return error;
|
|
744
|
+
const code = "code" in error ? error.code : void 0;
|
|
745
|
+
const base = {
|
|
746
|
+
name: error.name,
|
|
747
|
+
message: error.message,
|
|
748
|
+
stack
|
|
749
|
+
};
|
|
750
|
+
return typeof code === "string" || typeof code === "number" ? {
|
|
751
|
+
...base,
|
|
752
|
+
code
|
|
753
|
+
} : base;
|
|
754
|
+
}
|
|
755
|
+
//#endregion
|
|
756
|
+
//#region src/error-filters.ts
|
|
757
|
+
let filter = makeErrorFilter();
|
|
758
|
+
function configureErrorFilters(next) {
|
|
759
|
+
filter = makeErrorFilter(next);
|
|
760
|
+
}
|
|
761
|
+
const shouldCapture = (error, hint, frameUrl) => filter(error, hint, frameUrl);
|
|
762
|
+
//#endregion
|
|
763
|
+
//#region src/sampling.ts
|
|
764
|
+
const KEEP = createContextKey("maple.sampling.keep");
|
|
765
|
+
/**
|
|
766
|
+
* A context whose next span is always sampled, for errors. An unsampled parent
|
|
767
|
+
* is dropped first, so the error exports as a root rather than an orphan.
|
|
768
|
+
*/
|
|
769
|
+
function keepContext(ctx) {
|
|
770
|
+
const parent = trace.getSpanContext(ctx);
|
|
771
|
+
return (parent && (parent.traceFlags & TraceFlags.SAMPLED) === 0 ? trace.deleteSpan(ctx) : ctx).setValue(KEEP, true);
|
|
772
|
+
}
|
|
773
|
+
var SessionSampler = class {
|
|
774
|
+
rate;
|
|
775
|
+
constructor(rate) {
|
|
776
|
+
this.rate = rate;
|
|
777
|
+
}
|
|
778
|
+
shouldSample(ctx) {
|
|
779
|
+
if (ctx.getValue(KEEP) === true) return { decision: SamplingDecision.RECORD_AND_SAMPLED };
|
|
780
|
+
const parent = trace.getSpanContext(ctx);
|
|
781
|
+
if (parent && isSpanContextValid(parent)) return { decision: (parent.traceFlags & TraceFlags.SAMPLED) === 0 ? SamplingDecision.NOT_RECORD : SamplingDecision.RECORD_AND_SAMPLED };
|
|
782
|
+
const decision = sampleSession(readSessionSink()?.sessionId, this.rate);
|
|
783
|
+
if (!decision.sampled) return { decision: SamplingDecision.NOT_RECORD };
|
|
784
|
+
return {
|
|
785
|
+
decision: SamplingDecision.RECORD_AND_SAMPLED,
|
|
786
|
+
...decision.traceState ? { traceState: createTraceState(decision.traceState) } : void 0
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
toString() {
|
|
790
|
+
return `MapleSessionSampler{${this.rate}}`;
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
//#endregion
|
|
794
|
+
//#region src/http-headers.ts
|
|
795
|
+
/** `getAllResponseHeaders()` text as a lower-cased map: only the headers CORS exposes are in it. */
|
|
796
|
+
function responseHeaders(raw) {
|
|
797
|
+
const headers = /* @__PURE__ */ new Map();
|
|
798
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
799
|
+
const colon = line.indexOf(":");
|
|
800
|
+
if (colon > 0) headers.set(line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim());
|
|
801
|
+
}
|
|
802
|
+
return headers;
|
|
803
|
+
}
|
|
804
|
+
/** Stamp the listed headers that `read` finds. Cross-origin responses expose only CORS-safelisted headers unless the server lists more in `Access-Control-Expose-Headers`. */
|
|
805
|
+
function setHeaderAttributes(span, direction, names, read) {
|
|
806
|
+
for (const name of names) {
|
|
807
|
+
const value = read(name);
|
|
808
|
+
if (value) span.setAttribute(`http.${direction}.header.${name}`, [value]);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
//#endregion
|
|
812
|
+
//#region src/http-status.ts
|
|
813
|
+
const HTTP_STATUS = /^\d{3}$/;
|
|
814
|
+
/** An Error set only because of the response status: `error.type` is the status code itself. */
|
|
815
|
+
function isStatusOnlyError(span) {
|
|
816
|
+
return span.kind === SpanKind.CLIENT && span.status.code === SpanStatusCode.ERROR && HTTP_STATUS.test(String(span.attributes["error.type"] ?? "")) && !span.events.some((event) => event.name === "exception");
|
|
817
|
+
}
|
|
818
|
+
function withStatus(span, status, attributes) {
|
|
819
|
+
return {
|
|
820
|
+
name: span.name,
|
|
821
|
+
kind: span.kind,
|
|
822
|
+
spanContext: () => span.spanContext(),
|
|
823
|
+
parentSpanContext: span.parentSpanContext,
|
|
824
|
+
startTime: span.startTime,
|
|
825
|
+
endTime: span.endTime,
|
|
826
|
+
status,
|
|
827
|
+
attributes,
|
|
828
|
+
links: span.links,
|
|
829
|
+
events: span.events,
|
|
830
|
+
duration: span.duration,
|
|
831
|
+
ended: span.ended,
|
|
832
|
+
resource: span.resource,
|
|
833
|
+
instrumentationScope: span.instrumentationScope,
|
|
834
|
+
droppedAttributesCount: span.droppedAttributesCount,
|
|
835
|
+
droppedEventsCount: span.droppedEventsCount,
|
|
836
|
+
droppedLinksCount: span.droppedLinksCount
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
var HttpStatusExporter = class {
|
|
840
|
+
inner;
|
|
841
|
+
captureStatus;
|
|
842
|
+
constructor(inner, captureStatus = DEFAULT_ERROR_STATUS) {
|
|
843
|
+
this.inner = inner;
|
|
844
|
+
this.captureStatus = captureStatus;
|
|
845
|
+
}
|
|
846
|
+
apply(span) {
|
|
847
|
+
const read = (key) => span.attributes[key];
|
|
848
|
+
const status = responseStatus(read);
|
|
849
|
+
if (span.kind === SpanKind.CLIENT && status !== void 0 && inStatusRanges(status, this.captureStatus)) {
|
|
850
|
+
if (span.events.some((event) => event.name === "exception")) return span;
|
|
851
|
+
return withStatus(span, { code: SpanStatusCode.ERROR }, {
|
|
852
|
+
...span.attributes,
|
|
853
|
+
...httpErrorType(status)
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
if (!isStatusOnlyError(span)) return span;
|
|
857
|
+
const { "error.type": _errorType, ...attributes } = span.attributes;
|
|
858
|
+
return withStatus(span, { code: SpanStatusCode.UNSET }, attributes);
|
|
859
|
+
}
|
|
860
|
+
export(spans, callback) {
|
|
861
|
+
this.inner.export(spans.map((span) => this.apply(span)), callback);
|
|
862
|
+
}
|
|
863
|
+
forceFlush() {
|
|
864
|
+
return this.inner.forceFlush?.() ?? Promise.resolve();
|
|
865
|
+
}
|
|
866
|
+
shutdown() {
|
|
867
|
+
return this.inner.shutdown();
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
//#endregion
|
|
871
|
+
//#region src/offline.ts
|
|
872
|
+
/** Failed batches held until the deferred chunk lands. */
|
|
873
|
+
const MAX_HELD = 20;
|
|
874
|
+
let stash;
|
|
875
|
+
let held = [];
|
|
876
|
+
function attachSpanStash(next) {
|
|
877
|
+
stash = next;
|
|
878
|
+
if (!next) return;
|
|
879
|
+
const pending = held;
|
|
880
|
+
held = [];
|
|
881
|
+
for (const spans of pending) next(spans);
|
|
882
|
+
}
|
|
883
|
+
var OfflineSpanExporter = class {
|
|
884
|
+
inner;
|
|
885
|
+
constructor(inner) {
|
|
886
|
+
this.inner = inner;
|
|
887
|
+
}
|
|
888
|
+
export(spans, callback) {
|
|
889
|
+
this.inner.export(spans, (result) => {
|
|
890
|
+
if (result.code !== 0) {
|
|
891
|
+
if (stash) stash(spans);
|
|
892
|
+
else {
|
|
893
|
+
held.push(spans);
|
|
894
|
+
if (held.length > MAX_HELD) held.shift();
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
callback(result);
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
forceFlush() {
|
|
901
|
+
return this.inner.forceFlush?.() ?? Promise.resolve();
|
|
902
|
+
}
|
|
903
|
+
shutdown() {
|
|
904
|
+
return this.inner.shutdown();
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
//#endregion
|
|
908
|
+
//#region src/version.ts
|
|
909
|
+
const SDK_VERSION = "0.10.1";
|
|
910
|
+
/** The `x-maple-sdk` value this build sends. */
|
|
911
|
+
const SDK_NAME = "maple-browser";
|
|
912
|
+
//#endregion
|
|
913
|
+
//#region src/tracing.ts
|
|
914
|
+
/** Span attributes that carry a page or request URL. */
|
|
915
|
+
const URL_ATTRIBUTES = ["url.full", "http.url"];
|
|
916
|
+
/**
|
|
917
|
+
* Captures every span's trace id into the session sink, and redacts URL
|
|
918
|
+
* attributes before anything can export them. Lightweight: runs alongside the
|
|
919
|
+
* BatchSpanProcessor, does no export of its own.
|
|
920
|
+
*/
|
|
921
|
+
var TraceIdCollector = class {
|
|
922
|
+
getUserId;
|
|
923
|
+
constructor(getUserId = () => void 0) {
|
|
924
|
+
this.getUserId = getUserId;
|
|
925
|
+
}
|
|
926
|
+
onStart(span) {
|
|
927
|
+
for (const key of URL_ATTRIBUTES) {
|
|
928
|
+
const value = span.attributes[key];
|
|
929
|
+
if (typeof value === "string") span.setAttribute(key, scrubUrl(value));
|
|
930
|
+
}
|
|
931
|
+
if (!hasConsent()) return;
|
|
932
|
+
recordTraceId(span.spanContext().traceId);
|
|
933
|
+
const sessionId = readSessionSink()?.sessionId;
|
|
934
|
+
if (sessionId !== void 0) span.setAttribute("session.id", sessionId);
|
|
935
|
+
const userId = this.getUserId();
|
|
936
|
+
if (userId !== void 0) span.setAttribute("user.id", userId);
|
|
937
|
+
}
|
|
938
|
+
onEnd(_span) {}
|
|
939
|
+
forceFlush() {
|
|
940
|
+
return Promise.resolve();
|
|
941
|
+
}
|
|
942
|
+
shutdown() {
|
|
943
|
+
return Promise.resolve();
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
/**
|
|
947
|
+
* Drops buffered spans captured while consent was absent. Checking start time,
|
|
948
|
+
* rather than only permission at flush time, also prevents a late grant from
|
|
949
|
+
* releasing spans that began before that grant.
|
|
950
|
+
*/
|
|
951
|
+
var ConsentSpanExporter = class {
|
|
952
|
+
inner;
|
|
953
|
+
constructor(inner) {
|
|
954
|
+
this.inner = inner;
|
|
955
|
+
}
|
|
956
|
+
export(spans, callback) {
|
|
957
|
+
const since = consentAllowedSince();
|
|
958
|
+
if (!hasConsent() || !Number.isFinite(since)) {
|
|
959
|
+
callback({ code: 0 });
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
const eligible = spans.filter((span) => span.startTime[0] * 1e3 + span.startTime[1] / 1e6 >= since);
|
|
963
|
+
if (eligible.length === 0) {
|
|
964
|
+
callback({ code: 0 });
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
this.inner.export(eligible, callback);
|
|
968
|
+
}
|
|
969
|
+
forceFlush() {
|
|
970
|
+
return this.inner.forceFlush?.() ?? Promise.resolve();
|
|
971
|
+
}
|
|
972
|
+
shutdown() {
|
|
973
|
+
return this.inner.shutdown();
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
/**
|
|
977
|
+
* How long a span may sit in the batch queue before export.
|
|
978
|
+
*
|
|
979
|
+
* Shorter than OTel's 5s default: in a browser the queue is only as durable as
|
|
980
|
+
* the tab, and the unload flush below is a best-effort catch rather than a
|
|
981
|
+
* guarantee (a crashed or killed tab fires neither event). 2s trades a few more
|
|
982
|
+
* requests for a materially smaller loss window.
|
|
983
|
+
*/
|
|
984
|
+
const EXPORT_INTERVAL_MS = 2e3;
|
|
985
|
+
/**
|
|
986
|
+
* The provider this SDK registered, while it is live. Everything Maple spans
|
|
987
|
+
* goes through it directly: the global provider may belong to the host app,
|
|
988
|
+
* which registered first and so kept the global.
|
|
989
|
+
*/
|
|
990
|
+
let mapleProvider;
|
|
991
|
+
/** A tracer on Maple's provider while tracing is live, with no global fallback. */
|
|
992
|
+
function liveMapleTracer(name, version) {
|
|
993
|
+
return mapleProvider?.getTracer(name, version);
|
|
994
|
+
}
|
|
995
|
+
/** Resource attributes shared by every signal this SDK exports. */
|
|
996
|
+
function resourceAttributes(config) {
|
|
997
|
+
const attributes = {
|
|
998
|
+
[ATTR_SERVICE_NAME]: config.serviceName,
|
|
999
|
+
"maple.sdk.type": "browser"
|
|
1000
|
+
};
|
|
1001
|
+
if (config.serviceNamespace) attributes["service.namespace"] = config.serviceNamespace;
|
|
1002
|
+
if (config.serviceVersion) {
|
|
1003
|
+
attributes[ATTR_SERVICE_VERSION] = config.serviceVersion;
|
|
1004
|
+
if (/^[0-9a-f]{7,40}$/i.test(config.serviceVersion)) attributes["vcs.ref.head.revision"] = config.serviceVersion;
|
|
1005
|
+
}
|
|
1006
|
+
if (config.environment) {
|
|
1007
|
+
attributes["deployment.environment"] = config.environment;
|
|
1008
|
+
attributes["deployment.environment.name"] = config.environment;
|
|
1009
|
+
}
|
|
1010
|
+
return attributes;
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Set up browser OTel tracing exporting to Maple's ingest. When
|
|
1014
|
+
* `tracingInstrumentFetch` is true, fetch() calls are auto-instrumented and
|
|
1015
|
+
* their trace ids feed the session. Disable it when an external tracer (e.g.
|
|
1016
|
+
* the Effect client SDK) already instruments requests — that tracer feeds the
|
|
1017
|
+
* session via the published sink instead, and this avoids redundant duplicate
|
|
1018
|
+
* network spans. Returns a shutdown function.
|
|
1019
|
+
*
|
|
1020
|
+
* `session.id` is deliberately **not** a resource attribute: the resource is
|
|
1021
|
+
* fixed for the provider's lifetime, but sessions rotate under it (idle
|
|
1022
|
+
* rotation, consent revoke→re-grant), so a resource-level id would attribute
|
|
1023
|
+
* every post-rotation span to the ended session. `TraceIdCollector` stamps the
|
|
1024
|
+
* live id per span instead.
|
|
1025
|
+
*/
|
|
1026
|
+
function setupTracing(config) {
|
|
1027
|
+
const otlp = new OTLPTraceExporter({
|
|
1028
|
+
url: `${config.endpoint}/v1/traces`,
|
|
1029
|
+
headers: ingestHeaders({
|
|
1030
|
+
ingestKey: config.ingestKey,
|
|
1031
|
+
sdk: sdkHint(SDK_NAME, SDK_VERSION)
|
|
1032
|
+
})
|
|
1033
|
+
});
|
|
1034
|
+
const exporter = new ConsentSpanExporter(new HttpStatusExporter(config.offlineQueue ? new OfflineSpanExporter(otlp) : otlp, config.errorFilters.captureHttpStatus));
|
|
1035
|
+
const provider = new WebTracerProvider({
|
|
1036
|
+
resource: resourceFromAttributes(resourceAttributes(config)),
|
|
1037
|
+
sampler: new SessionSampler(config.tracingSampleRate),
|
|
1038
|
+
spanProcessors: [new TraceIdCollector(() => config.identity?.id), new BatchSpanProcessor(exporter, { scheduledDelayMillis: EXPORT_INTERVAL_MS })]
|
|
1039
|
+
});
|
|
1040
|
+
provider.register();
|
|
1041
|
+
mapleProvider = provider;
|
|
1042
|
+
const globalProvider = trace.getTracerProvider();
|
|
1043
|
+
const ownsGlobals = globalProvider === provider || globalProvider instanceof ProxyTracerProvider && globalProvider.getDelegate() === provider;
|
|
1044
|
+
const onExit = () => {
|
|
1045
|
+
provider.forceFlush().catch(() => {});
|
|
1046
|
+
};
|
|
1047
|
+
const onVisibilityChange = () => {
|
|
1048
|
+
if (document.visibilityState === "hidden") onExit();
|
|
1049
|
+
};
|
|
1050
|
+
const settledRequests = /* @__PURE__ */ new Map();
|
|
1051
|
+
const onPageHide = () => {
|
|
1052
|
+
for (const [span, endTime] of settledRequests) if (span.isRecording()) span.end(endTime);
|
|
1053
|
+
settledRequests.clear();
|
|
1054
|
+
onExit();
|
|
1055
|
+
};
|
|
1056
|
+
const noteSettled = (span) => {
|
|
1057
|
+
for (const settled of settledRequests.keys()) if (!settled.isRecording()) settledRequests.delete(settled);
|
|
1058
|
+
settledRequests.set(span, Date.now());
|
|
1059
|
+
};
|
|
1060
|
+
const canListen = typeof document !== "undefined" && typeof document.addEventListener === "function";
|
|
1061
|
+
if (canListen) {
|
|
1062
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
1063
|
+
window.addEventListener("pagehide", onPageHide);
|
|
1064
|
+
}
|
|
1065
|
+
const requestOptions = {
|
|
1066
|
+
ignoreUrls: [new RegExp(`${escapeRegExp(config.endpoint)}/v1/`)],
|
|
1067
|
+
propagateTraceHeaderCorsUrls: [...config.propagateTraceHeaderCorsUrls]
|
|
1068
|
+
};
|
|
1069
|
+
const headers = config.captureHeaders;
|
|
1070
|
+
const instrumentations = [...config.tracingInstrumentFetch ? [new FetchInstrumentation({
|
|
1071
|
+
...requestOptions,
|
|
1072
|
+
applyCustomAttributesOnSpan: (span, request, result) => {
|
|
1073
|
+
noteSettled(span);
|
|
1074
|
+
const sent = request instanceof Request ? request.headers : new Headers(request.headers);
|
|
1075
|
+
setHeaderAttributes(span, "request", headers.request, (name) => sent.get(name));
|
|
1076
|
+
if (result instanceof Response) setHeaderAttributes(span, "response", headers.response, (name) => result.headers.get(name));
|
|
1077
|
+
else if (result instanceof Error && (isTimeout(result, request.signal) || result.name !== "AbortError" && !request.signal?.aborted)) {
|
|
1078
|
+
span.setStatus({
|
|
1079
|
+
code: SpanStatusCode.ERROR,
|
|
1080
|
+
message: result.message
|
|
1081
|
+
});
|
|
1082
|
+
span.setAttribute("error.type", result.name);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
})] : [], ...config.tracingInstrumentXhr ? [new XMLHttpRequestInstrumentation({
|
|
1086
|
+
...requestOptions,
|
|
1087
|
+
applyCustomAttributesOnSpan: (span, xhr) => {
|
|
1088
|
+
noteSettled(span);
|
|
1089
|
+
if (headers.response.length === 0) return;
|
|
1090
|
+
const exposed = responseHeaders(xhr.getAllResponseHeaders());
|
|
1091
|
+
setHeaderAttributes(span, "response", headers.response, (name) => exposed.get(name));
|
|
1092
|
+
}
|
|
1093
|
+
})] : []];
|
|
1094
|
+
const unregisterInstrumentations = instrumentations.length > 0 ? registerInstrumentations({
|
|
1095
|
+
tracerProvider: provider,
|
|
1096
|
+
instrumentations
|
|
1097
|
+
}) : void 0;
|
|
1098
|
+
return async () => {
|
|
1099
|
+
if (canListen) {
|
|
1100
|
+
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
1101
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
1102
|
+
}
|
|
1103
|
+
unregisterInstrumentations?.();
|
|
1104
|
+
if (mapleProvider === provider) mapleProvider = void 0;
|
|
1105
|
+
await provider.shutdown();
|
|
1106
|
+
if (ownsGlobals) {
|
|
1107
|
+
trace.disable();
|
|
1108
|
+
context.disable();
|
|
1109
|
+
propagation.disable();
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
/** `AbortSignal.timeout()` aborts with, and rejects the fetch with, a `TimeoutError` DOMException. */
|
|
1114
|
+
function isTimeout(error, signal) {
|
|
1115
|
+
const reason = signal?.reason;
|
|
1116
|
+
return error.name === "TimeoutError" || reason instanceof DOMException && reason.name === "TimeoutError";
|
|
1117
|
+
}
|
|
1118
|
+
function escapeRegExp(value) {
|
|
1119
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1120
|
+
}
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/errors.ts
|
|
1123
|
+
/**
|
|
1124
|
+
* Errors already reported, by identity, page-wide: a framework boundary that
|
|
1125
|
+
* reports an error and then rethrows it, or both Maple SDKs on one page, would
|
|
1126
|
+
* otherwise produce two issues for one crash.
|
|
1127
|
+
*/
|
|
1128
|
+
const alreadyReported = wasReported;
|
|
1129
|
+
/**
|
|
1130
|
+
* Mark `span` as failed by `error`. The exception event goes on the first span
|
|
1131
|
+
* that records this error object; a later one (an outer `traced`, say) only
|
|
1132
|
+
* takes the Error status, so one error stays one issue. The error is claimed
|
|
1133
|
+
* only when the span is recording: before `init()` the tracer is a no-op, and
|
|
1134
|
+
* claiming it then would swallow the same error reported again once tracing is
|
|
1135
|
+
* live. Without consent the span is never exported, so the error is not claimed either.
|
|
1136
|
+
*/
|
|
1137
|
+
function recordFailure(span, error) {
|
|
1138
|
+
const normalized = asError(error);
|
|
1139
|
+
if (!alreadyReported(error)) {
|
|
1140
|
+
const exported = span.isRecording() && hasConsent();
|
|
1141
|
+
if (exported) markReported(error);
|
|
1142
|
+
span.recordException(exceptionOf(normalized));
|
|
1143
|
+
if (exported) notifyErrorRecorded(span.spanContext());
|
|
1144
|
+
}
|
|
1145
|
+
span.setStatus({
|
|
1146
|
+
code: SpanStatusCode.ERROR,
|
|
1147
|
+
message: normalized.message
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Record `error` on a one-off span, exported whatever the session's trace
|
|
1152
|
+
* sampling, unless the app's error filters drop it.
|
|
1153
|
+
*/
|
|
1154
|
+
function recordException(error, options, source, filename, filtered = false) {
|
|
1155
|
+
if (!hasConsent()) return;
|
|
1156
|
+
if (!filtered && !shouldCapture(asError(error), {
|
|
1157
|
+
source,
|
|
1158
|
+
originalError: error
|
|
1159
|
+
}, filename)) return;
|
|
1160
|
+
const tracer = liveMapleTracer(SDK_NAME, SDK_VERSION);
|
|
1161
|
+
if (!tracer) return;
|
|
1162
|
+
const span = tracer.startSpan(options.name ?? "exception", {
|
|
1163
|
+
kind: SpanKind.INTERNAL,
|
|
1164
|
+
attributes: {
|
|
1165
|
+
...typeof location !== "undefined" ? { "url.full": scrubUrl(location.href) } : void 0,
|
|
1166
|
+
...options.attributes
|
|
1167
|
+
}
|
|
1168
|
+
}, keepContext(context.active()));
|
|
1169
|
+
recordFailure(span, error);
|
|
1170
|
+
span.end();
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Record an error that no span was watching. Safe before `init()`, where it
|
|
1174
|
+
* does nothing. Reporting the same error object twice records it once.
|
|
1175
|
+
*/
|
|
1176
|
+
function captureException(error, options = {}) {
|
|
1177
|
+
if (alreadyReported(error)) return;
|
|
1178
|
+
recordException(error, options, "captureException");
|
|
1179
|
+
}
|
|
1180
|
+
/** Whether the app's error filters keep `error`, for failures recorded on an existing span. */
|
|
1181
|
+
function passesErrorFilters(error) {
|
|
1182
|
+
return shouldCapture(asError(error), {
|
|
1183
|
+
source: "captureException",
|
|
1184
|
+
originalError: error
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
/** `captureException` for an error `passesErrorFilters` already let through: `beforeCapture` runs once. */
|
|
1188
|
+
function captureFilteredException(error, options = {}) {
|
|
1189
|
+
if (alreadyReported(error)) return;
|
|
1190
|
+
recordException(error, options, "captureException", void 0, true);
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* Register global handlers for uncaught errors and unhandled rejections.
|
|
1194
|
+
* Returns a teardown that removes them.
|
|
1195
|
+
*/
|
|
1196
|
+
function setupErrorCapture() {
|
|
1197
|
+
if (typeof window === "undefined" || typeof window.addEventListener !== "function") return () => {};
|
|
1198
|
+
const onError = (event) => {
|
|
1199
|
+
const error = event.error ?? (event.message && event.filename ? new Error(event.message) : void 0);
|
|
1200
|
+
if (error === void 0 || alreadyReported(error)) return;
|
|
1201
|
+
recordException(error, {
|
|
1202
|
+
name: "browser.uncaught_error",
|
|
1203
|
+
attributes: {
|
|
1204
|
+
"maple.exception.source": "window.onerror",
|
|
1205
|
+
...event.filename ? { "code.file.path": event.filename } : void 0,
|
|
1206
|
+
...event.lineno ? { "code.line.number": event.lineno } : void 0,
|
|
1207
|
+
...event.colno ? { "code.column.number": event.colno } : void 0
|
|
1208
|
+
}
|
|
1209
|
+
}, "window.onerror", event.error instanceof Error ? void 0 : event.filename || void 0);
|
|
1210
|
+
};
|
|
1211
|
+
const onUnhandledRejection = (event) => {
|
|
1212
|
+
if (alreadyReported(event.reason)) return;
|
|
1213
|
+
recordException(event.reason, {
|
|
1214
|
+
name: "browser.unhandled_rejection",
|
|
1215
|
+
attributes: { "maple.exception.source": "unhandledrejection" }
|
|
1216
|
+
}, "unhandledrejection");
|
|
1217
|
+
};
|
|
1218
|
+
window.addEventListener("error", onError);
|
|
1219
|
+
window.addEventListener("unhandledrejection", onUnhandledRejection);
|
|
1220
|
+
return () => {
|
|
1221
|
+
window.removeEventListener("error", onError);
|
|
1222
|
+
window.removeEventListener("unhandledrejection", onUnhandledRejection);
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
//#endregion
|
|
1226
|
+
//#region src/config.ts
|
|
1227
|
+
/**
|
|
1228
|
+
* Resolve the identity from either the new `user` object or the legacy
|
|
1229
|
+
* `userId` string. `user` wins when both are set.
|
|
1230
|
+
*/
|
|
1231
|
+
function resolveIdentity(config) {
|
|
1232
|
+
return normalizeIdentity(config.user ?? config.userId);
|
|
1233
|
+
}
|
|
1234
|
+
function resolveConfig(config) {
|
|
1235
|
+
const endpoint = resolveIngestEndpoint({
|
|
1236
|
+
endpoints: [config.endpoint],
|
|
1237
|
+
regions: [config.region]
|
|
1238
|
+
});
|
|
1239
|
+
warnIfKeylessMapleIngest({
|
|
1240
|
+
logPrefix: "[maple]",
|
|
1241
|
+
endpoint,
|
|
1242
|
+
hasIngestKey: Boolean(config.ingestKey),
|
|
1243
|
+
hint: "Pass `ingestKey`, or point `endpoint` at a proxy that adds it."
|
|
1244
|
+
});
|
|
1245
|
+
const replay = resolveReplayOptions(config.replay);
|
|
1246
|
+
return {
|
|
1247
|
+
...resolveSignalOptions(config),
|
|
1248
|
+
ingestKey: config.ingestKey,
|
|
1249
|
+
serviceName: config.serviceName,
|
|
1250
|
+
endpoint,
|
|
1251
|
+
serviceNamespace: config.serviceNamespace,
|
|
1252
|
+
serviceVersion: config.serviceVersion,
|
|
1253
|
+
environment: config.environment,
|
|
1254
|
+
identity: resolveIdentity(config),
|
|
1255
|
+
tracingEnabled: config.tracing?.enabled ?? true,
|
|
1256
|
+
tracingInstrumentFetch: config.tracing?.instrumentFetch ?? true,
|
|
1257
|
+
tracingInstrumentXhr: config.tracing?.instrumentXhr ?? true,
|
|
1258
|
+
tracingCaptureErrors: config.tracing?.captureErrors ?? true,
|
|
1259
|
+
propagateTraceHeaderCorsUrls: config.tracing?.propagateTraceHeaderCorsUrls ?? [],
|
|
1260
|
+
replayEnabled: replay.enabled,
|
|
1261
|
+
replaySampleRate: replay.sampleRate,
|
|
1262
|
+
replayOnErrorSampleRate: replay.onErrorSampleRate,
|
|
1263
|
+
canvasFps: replay.canvasFps,
|
|
1264
|
+
networkBodies: replay.networkBodies,
|
|
1265
|
+
maskAllInputs: config.privacy?.maskAllInputs ?? true,
|
|
1266
|
+
maskAllText: config.privacy?.maskAllText ?? false,
|
|
1267
|
+
persistVisitorId: config.privacy?.persistVisitorId ?? true,
|
|
1268
|
+
crossSubdomainCookie: config.privacy?.crossSubdomainCookie ?? true,
|
|
1269
|
+
cookieDomain: config.privacy?.cookieDomain,
|
|
1270
|
+
requireConsent: config.privacy?.requireConsent ?? false,
|
|
1271
|
+
captureUserEmail: config.privacy?.captureUserEmail ?? true,
|
|
1272
|
+
respectDoNotTrack: config.privacy?.respectDoNotTrack ?? false,
|
|
1273
|
+
sanitizeUrl: config.privacy?.sanitizeUrl
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
//#endregion
|
|
1277
|
+
//#region src/logs.ts
|
|
1278
|
+
/** Held until the deferred chunk lands; beyond this, a page logging in a loop drops the oldest. */
|
|
1279
|
+
const MAX_QUEUED = 200;
|
|
1280
|
+
let queue = [];
|
|
1281
|
+
let sink;
|
|
1282
|
+
let getUserId = () => void 0;
|
|
1283
|
+
function emitLog(record) {
|
|
1284
|
+
if (!hasConsent()) return;
|
|
1285
|
+
const sessionId = readSessionSink()?.sessionId;
|
|
1286
|
+
const userId = getUserId();
|
|
1287
|
+
const attributes = {
|
|
1288
|
+
...record.attributes,
|
|
1289
|
+
...sessionId !== void 0 ? { "session.id": sessionId } : void 0,
|
|
1290
|
+
...userId !== void 0 ? { "user.id": userId } : void 0
|
|
1291
|
+
};
|
|
1292
|
+
const queued = {
|
|
1293
|
+
...record,
|
|
1294
|
+
attributes,
|
|
1295
|
+
timestamp: record.timestamp ?? Date.now(),
|
|
1296
|
+
link: record.link ?? trace.getSpanContext(context.active())
|
|
1297
|
+
};
|
|
1298
|
+
if (sink) {
|
|
1299
|
+
sink(queued);
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
queue.push(queued);
|
|
1303
|
+
if (queue.length > MAX_QUEUED) queue.shift();
|
|
1304
|
+
}
|
|
1305
|
+
/** Called by `init()`: where `user.id` comes from. */
|
|
1306
|
+
function setLogIdentity(read) {
|
|
1307
|
+
getUserId = read;
|
|
1308
|
+
}
|
|
1309
|
+
/** Called by the deferred chunk: drains the queue into `next`, then sends straight to it. */
|
|
1310
|
+
function attachLogSink(next) {
|
|
1311
|
+
sink = next;
|
|
1312
|
+
const pending = queue;
|
|
1313
|
+
queue = [];
|
|
1314
|
+
for (const record of pending) next(record);
|
|
1315
|
+
}
|
|
1316
|
+
function detachLogSink() {
|
|
1317
|
+
sink = void 0;
|
|
1318
|
+
getUserId = () => void 0;
|
|
1319
|
+
}
|
|
1320
|
+
//#endregion
|
|
1321
|
+
//#region src/navigation.ts
|
|
1322
|
+
/**
|
|
1323
|
+
* The navigation in flight. Only ever set in a browser: a server shares module
|
|
1324
|
+
* state across requests.
|
|
1325
|
+
*/
|
|
1326
|
+
let navigation;
|
|
1327
|
+
/**
|
|
1328
|
+
* Whether the next navigation is a `pageload`: the first since the document
|
|
1329
|
+
* loaded, or since `shutdown()`. Consumed even when nothing is spanned (tracing
|
|
1330
|
+
* not live yet, consent pending): a later click is not the page load. Router
|
|
1331
|
+
* adapters must therefore be attached after `init()`.
|
|
1332
|
+
*/
|
|
1333
|
+
let firstLoad = true;
|
|
1334
|
+
/**
|
|
1335
|
+
* Whether the document's own page load is still to come. Unlike `firstLoad`,
|
|
1336
|
+
* never reset: a `pageload` after `shutdown()` and a new `init()` is long past
|
|
1337
|
+
* the server render, and must not join its trace.
|
|
1338
|
+
*/
|
|
1339
|
+
let documentLoad = true;
|
|
1340
|
+
/** Set by the deferred chunk, which spans the document's own load under `pageload`. */
|
|
1341
|
+
let pageloadListener;
|
|
1342
|
+
/** A document page load that began before the deferred chunk landed. */
|
|
1343
|
+
let pendingPageload;
|
|
1344
|
+
function onDocumentPageload(listener) {
|
|
1345
|
+
pageloadListener = listener;
|
|
1346
|
+
if (listener && pendingPageload) listener(pendingPageload.tracer, pendingPageload.span);
|
|
1347
|
+
pendingPageload = void 0;
|
|
1348
|
+
}
|
|
1349
|
+
/** Spans `traced` opened, which a nested `traced` may parent to instead of the navigation. */
|
|
1350
|
+
const tracedSpans = /* @__PURE__ */ new WeakSet();
|
|
1351
|
+
/**
|
|
1352
|
+
* Maple's tracer, while tracing is live and consent is given. A consent revoke
|
|
1353
|
+
* leaves the provider up but drops what it spans: an error recorded then would
|
|
1354
|
+
* be claimed without ever being exported.
|
|
1355
|
+
*/
|
|
1356
|
+
const tracer = () => hasConsent() ? liveMapleTracer(SDK_NAME, SDK_VERSION) : void 0;
|
|
1357
|
+
/** The open navigation span, if it had already started at `epochMs`: a child must not begin before its parent. */
|
|
1358
|
+
function navigationSpanAt(epochMs) {
|
|
1359
|
+
return navigation && navigation.startedAt <= epochMs ? navigation.span : void 0;
|
|
1360
|
+
}
|
|
1361
|
+
/** End the open navigation as interrupted: something other than its route finishing ended it. */
|
|
1362
|
+
function interruptNavigation() {
|
|
1363
|
+
navigation?.span.setAttribute("app.navigation.interrupted", true);
|
|
1364
|
+
navigation?.span.end();
|
|
1365
|
+
navigation = void 0;
|
|
1366
|
+
}
|
|
1367
|
+
function startNavigation(path) {
|
|
1368
|
+
if (typeof window === "undefined") return;
|
|
1369
|
+
interruptNavigation();
|
|
1370
|
+
const kind = firstLoad ? "pageload" : "navigate";
|
|
1371
|
+
const joinServer = documentLoad;
|
|
1372
|
+
firstLoad = false;
|
|
1373
|
+
documentLoad = false;
|
|
1374
|
+
const live = tracer();
|
|
1375
|
+
if (!live) return;
|
|
1376
|
+
const parent = (joinServer ? serverContext() : void 0) ?? context.active();
|
|
1377
|
+
const startTime = joinServer ? Math.max(performance.timeOrigin, consentAllowedSince()) : void 0;
|
|
1378
|
+
const span = live.startSpan(kind, {
|
|
1379
|
+
startTime,
|
|
1380
|
+
attributes: { "url.path": scrubUrl(path) }
|
|
1381
|
+
}, parent);
|
|
1382
|
+
navigation = {
|
|
1383
|
+
kind,
|
|
1384
|
+
span,
|
|
1385
|
+
startedAt: startTime ?? Date.now()
|
|
1386
|
+
};
|
|
1387
|
+
if (joinServer) {
|
|
1388
|
+
if (pageloadListener) pageloadListener(live, span);
|
|
1389
|
+
else pendingPageload = {
|
|
1390
|
+
tracer: live,
|
|
1391
|
+
span
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
window.addEventListener("pagehide", interruptNavigation, { capture: true });
|
|
1395
|
+
}
|
|
1396
|
+
function endNavigation(route) {
|
|
1397
|
+
if (!navigation) return;
|
|
1398
|
+
if (route) navigation.span.updateName(`${navigation.kind} ${scrubUrl(route)}`);
|
|
1399
|
+
navigation.span.end();
|
|
1400
|
+
navigation = void 0;
|
|
1401
|
+
}
|
|
1402
|
+
async function traced(name, fn, options = {}) {
|
|
1403
|
+
const live = tracer();
|
|
1404
|
+
if (!live) return fn();
|
|
1405
|
+
return live.startActiveSpan(name, {}, parentContext(), async (span) => {
|
|
1406
|
+
tracedSpans.add(span);
|
|
1407
|
+
try {
|
|
1408
|
+
return await fn();
|
|
1409
|
+
} catch (error) {
|
|
1410
|
+
if (isFailure(options, error) && passesErrorFilters(error)) {
|
|
1411
|
+
if (span.isRecording()) recordFailure(span, error);
|
|
1412
|
+
else captureFilteredException(error, { name });
|
|
1413
|
+
}
|
|
1414
|
+
throw error;
|
|
1415
|
+
} finally {
|
|
1416
|
+
span.end();
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* The open navigation, unless a `traced` span is active: a `traced` inside
|
|
1422
|
+
* another `traced` nests under that one.
|
|
1423
|
+
*/
|
|
1424
|
+
function parentContext() {
|
|
1425
|
+
const active = context.active();
|
|
1426
|
+
const activeSpan = trace.getSpan(active);
|
|
1427
|
+
if (!navigation || activeSpan && tracedSpans.has(activeSpan)) return active;
|
|
1428
|
+
return trace.setSpan(active, navigation.span);
|
|
1429
|
+
}
|
|
1430
|
+
/** `isFailure` is the app's code: if it throws, the original error still propagates. */
|
|
1431
|
+
function isFailure(options, error) {
|
|
1432
|
+
try {
|
|
1433
|
+
return options.isFailure?.(error) ?? true;
|
|
1434
|
+
} catch {
|
|
1435
|
+
return true;
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* End the open navigation so it exports with the provider's last flush, and
|
|
1440
|
+
* start the next `init()` at a page load. Called by `shutdown()`.
|
|
1441
|
+
*/
|
|
1442
|
+
function resetNavigation() {
|
|
1443
|
+
interruptNavigation();
|
|
1444
|
+
firstLoad = true;
|
|
1445
|
+
pendingPageload = void 0;
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* The trace the server rendered this page under: a `Server-Timing:
|
|
1449
|
+
* traceparent;desc="…"` entry on the document response, else a `<meta
|
|
1450
|
+
* name="traceparent">` tag.
|
|
1451
|
+
*/
|
|
1452
|
+
function serverContext() {
|
|
1453
|
+
const [page] = performance.getEntriesByType("navigation");
|
|
1454
|
+
const spanContext = parseTraceparent(page?.serverTiming?.find((entry) => entry.name === "traceparent")?.description) ?? parseTraceparent(document.querySelector("meta[name=\"traceparent\"]")?.content);
|
|
1455
|
+
return spanContext && trace.setSpanContext(context.active(), spanContext);
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* W3C `version-traceid-parentid-flags`. Parsed here rather than through the
|
|
1459
|
+
* global propagator, which the host app may own, or may not have registered.
|
|
1460
|
+
*/
|
|
1461
|
+
const TRACEPARENT = /^([\da-f]{2})-([\da-f]{32})-([\da-f]{16})-([\da-f]{2})(-.*)?$/;
|
|
1462
|
+
function parseTraceparent(value) {
|
|
1463
|
+
const match = value?.trim().match(TRACEPARENT);
|
|
1464
|
+
if (!match || match[1] === "ff" || match[1] === "00" && match[5] !== void 0) return void 0;
|
|
1465
|
+
const spanContext = {
|
|
1466
|
+
traceId: match[2],
|
|
1467
|
+
spanId: match[3],
|
|
1468
|
+
traceFlags: Number.parseInt(match[4], 16),
|
|
1469
|
+
isRemote: true
|
|
1470
|
+
};
|
|
1471
|
+
return isSpanContextValid(spanContext) ? spanContext : void 0;
|
|
1472
|
+
}
|
|
1473
|
+
//#endregion
|
|
1474
|
+
//#region src/init.ts
|
|
1475
|
+
/** `x-maple-sdk` value for every request this build makes to ingest. */
|
|
1476
|
+
const SDK_HINT = sdkHint(SDK_NAME, SDK_VERSION);
|
|
1477
|
+
let active;
|
|
1478
|
+
let activeConfig;
|
|
1479
|
+
/**
|
|
1480
|
+
* An `identify()` made before `init()`, applied when it runs. Auth callbacks
|
|
1481
|
+
* routinely resolve before the SDK is initialized; dropping the call meant the
|
|
1482
|
+
* whole first session went anonymous. Wrapped so a pending *clear* (`undefined`)
|
|
1483
|
+
* is distinguishable from no call at all.
|
|
1484
|
+
*/
|
|
1485
|
+
let pendingIdentity;
|
|
1486
|
+
/**
|
|
1487
|
+
* Initialize Maple browser telemetry. With consent gating enabled the returned
|
|
1488
|
+
* handle remains live while denied: granting starts capture, revoking detaches
|
|
1489
|
+
* it without flushing, and a later grant starts cleanly again.
|
|
1490
|
+
*/
|
|
1491
|
+
function init(rawConfig) {
|
|
1492
|
+
if (active) return active;
|
|
1493
|
+
if (typeof window === "undefined") return {
|
|
1494
|
+
sessionId: "",
|
|
1495
|
+
shutdown: () => Promise.resolve()
|
|
1496
|
+
};
|
|
1497
|
+
const config = resolveConfig(rawConfig);
|
|
1498
|
+
if (pendingIdentity) config.identity = normalizeIdentity(pendingIdentity.input);
|
|
1499
|
+
pendingIdentity = void 0;
|
|
1500
|
+
activeConfig = config;
|
|
1501
|
+
configurePrivacy(config);
|
|
1502
|
+
configureErrorFilters(config.errorFilters);
|
|
1503
|
+
if (!hasConsent()) clearPendingEvents();
|
|
1504
|
+
setActiveTraceIdProvider(() => trace.getActiveSpan()?.spanContext().traceId);
|
|
1505
|
+
const replayEligible = config.replayEnabled && !isLikelyBot(navigator.userAgent);
|
|
1506
|
+
let runtime;
|
|
1507
|
+
let stopped = false;
|
|
1508
|
+
let rotateOnNextStart = false;
|
|
1509
|
+
let shutdownTracing;
|
|
1510
|
+
let stopErrorCapture;
|
|
1511
|
+
let deferredPending;
|
|
1512
|
+
let stopDeferred;
|
|
1513
|
+
let generation = 0;
|
|
1514
|
+
const startRuntime = () => {
|
|
1515
|
+
if (stopped || runtime || !hasConsent()) return;
|
|
1516
|
+
setVisitorTracking(config.persistVisitorId && mayPersistIdentifier());
|
|
1517
|
+
const session = (rotateOnNextStart ? rotateSession() : void 0) ?? getSession();
|
|
1518
|
+
rotateOnNextStart = false;
|
|
1519
|
+
const replayMode = replayEligible ? claimReplayMode(config.replaySampleRate, config.replayOnErrorSampleRate) : "off";
|
|
1520
|
+
publishSessionSink(session.id);
|
|
1521
|
+
const sink = startEventSink({
|
|
1522
|
+
endpoint: config.endpoint,
|
|
1523
|
+
ingestKey: config.ingestKey,
|
|
1524
|
+
sdk: SDK_HINT,
|
|
1525
|
+
maskAllInputs: config.maskAllInputs,
|
|
1526
|
+
maskAllText: config.maskAllText,
|
|
1527
|
+
getIdentity: () => activeConfig?.identity
|
|
1528
|
+
}, session.id);
|
|
1529
|
+
if (config.tracingEnabled && !shutdownTracing) shutdownTracing = setupTracing(config);
|
|
1530
|
+
if (config.tracingEnabled && config.tracingCaptureErrors && !stopErrorCapture) stopErrorCapture = setupErrorCapture();
|
|
1531
|
+
if (!deferredPending) {
|
|
1532
|
+
setLogIdentity(() => activeConfig?.identity?.id);
|
|
1533
|
+
deferredPending = import("./deferred-BDp5NC7U.mjs").then(({ startDeferred }) => {
|
|
1534
|
+
stopDeferred = startDeferred(config);
|
|
1535
|
+
}).catch(() => {});
|
|
1536
|
+
}
|
|
1537
|
+
const shared = {
|
|
1538
|
+
endpoint: config.endpoint,
|
|
1539
|
+
ingestKey: config.ingestKey,
|
|
1540
|
+
sdk: SDK_HINT,
|
|
1541
|
+
serviceName: config.serviceName,
|
|
1542
|
+
environment: config.environment,
|
|
1543
|
+
serviceVersion: config.serviceVersion,
|
|
1544
|
+
getIdentity: () => activeConfig?.identity,
|
|
1545
|
+
captureUserEmail: config.captureUserEmail
|
|
1546
|
+
};
|
|
1547
|
+
const startMetadata = () => startMetadataSession({
|
|
1548
|
+
...shared,
|
|
1549
|
+
getTraceIds: getObservedTraceIds,
|
|
1550
|
+
onSessionChange: publishSessionSink
|
|
1551
|
+
});
|
|
1552
|
+
if (replayMode === "off") {
|
|
1553
|
+
runtime = {
|
|
1554
|
+
initialSessionId: session.id,
|
|
1555
|
+
sink,
|
|
1556
|
+
metadata: startMetadata()
|
|
1557
|
+
};
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1560
|
+
const next = {
|
|
1561
|
+
initialSessionId: session.id,
|
|
1562
|
+
sink
|
|
1563
|
+
};
|
|
1564
|
+
runtime = next;
|
|
1565
|
+
const ownGeneration = ++generation;
|
|
1566
|
+
const stale = () => stopped || !hasConsent() || generation !== ownGeneration || runtime !== next;
|
|
1567
|
+
next.replayPending = import("./replay-session-DdVYdHc_.mjs").then(({ startReplaySession }) => {
|
|
1568
|
+
if (stale()) return;
|
|
1569
|
+
next.replay = startReplaySession({
|
|
1570
|
+
...shared,
|
|
1571
|
+
maskAllInputs: config.maskAllInputs,
|
|
1572
|
+
maskAllText: config.maskAllText,
|
|
1573
|
+
mode: replayMode,
|
|
1574
|
+
canvasFps: config.canvasFps,
|
|
1575
|
+
networkBodies: config.networkBodies
|
|
1576
|
+
});
|
|
1577
|
+
}).catch(() => {
|
|
1578
|
+
if (stale()) return;
|
|
1579
|
+
next.metadata = startMetadata();
|
|
1580
|
+
});
|
|
1581
|
+
};
|
|
1582
|
+
const stopRuntime = async (flush) => {
|
|
1583
|
+
generation++;
|
|
1584
|
+
const previous = runtime;
|
|
1585
|
+
runtime = void 0;
|
|
1586
|
+
if (!previous) return;
|
|
1587
|
+
const replayShutdown = previous.replay?.shutdown({ flush });
|
|
1588
|
+
const metadataShutdown = previous.metadata?.shutdown({ flush });
|
|
1589
|
+
const currentSessionId = previous.replay?.sessionId ?? previous.metadata?.sessionId;
|
|
1590
|
+
const liveSink = getActiveSink();
|
|
1591
|
+
const sink = liveSink && currentSessionId && liveSink.sessionId === currentSessionId ? liveSink : previous.sink;
|
|
1592
|
+
if (flush) await sink.flush(true);
|
|
1593
|
+
sink.stop();
|
|
1594
|
+
if (sink !== previous.sink) previous.sink.stop();
|
|
1595
|
+
clearSessionSink(currentSessionId ?? previous.initialSessionId);
|
|
1596
|
+
await Promise.all([
|
|
1597
|
+
replayShutdown,
|
|
1598
|
+
metadataShutdown,
|
|
1599
|
+
previous.replayPending
|
|
1600
|
+
]);
|
|
1601
|
+
};
|
|
1602
|
+
const stopReplayTrigger = onErrorRecorded(() => {
|
|
1603
|
+
runtime?.replay?.trigger();
|
|
1604
|
+
});
|
|
1605
|
+
startRuntime();
|
|
1606
|
+
const stopConsentListener = config.requireConsent ? onConsentChange((allowed) => {
|
|
1607
|
+
if (allowed) {
|
|
1608
|
+
startRuntime();
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
rotateOnNextStart = runtime !== void 0;
|
|
1612
|
+
clearPendingEvents();
|
|
1613
|
+
setVisitorTracking(false);
|
|
1614
|
+
stopRuntime(false);
|
|
1615
|
+
}) : () => {};
|
|
1616
|
+
const handle = {
|
|
1617
|
+
get sessionId() {
|
|
1618
|
+
return runtime?.replay?.sessionId ?? runtime?.metadata?.sessionId ?? runtime?.initialSessionId ?? "";
|
|
1619
|
+
},
|
|
1620
|
+
shutdown: async () => {
|
|
1621
|
+
if (stopped) return;
|
|
1622
|
+
stopped = true;
|
|
1623
|
+
stopConsentListener();
|
|
1624
|
+
stopReplayTrigger();
|
|
1625
|
+
await stopRuntime(true);
|
|
1626
|
+
stopErrorCapture?.();
|
|
1627
|
+
stopErrorCapture = void 0;
|
|
1628
|
+
configureErrorFilters(void 0);
|
|
1629
|
+
resetNavigation();
|
|
1630
|
+
await deferredPending;
|
|
1631
|
+
await shutdownTracing?.();
|
|
1632
|
+
shutdownTracing = void 0;
|
|
1633
|
+
await stopDeferred?.();
|
|
1634
|
+
stopDeferred = void 0;
|
|
1635
|
+
setActiveTraceIdProvider(() => void 0);
|
|
1636
|
+
active = void 0;
|
|
1637
|
+
activeConfig = void 0;
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
active = handle;
|
|
1641
|
+
return handle;
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Attach, replace, or clear the end-user identity on the active session.
|
|
1645
|
+
* Idempotent and safe to call on every render. Future browser-created spans
|
|
1646
|
+
* read the id when they start, and future session metadata rows read the whole
|
|
1647
|
+
* identity when they post.
|
|
1648
|
+
*
|
|
1649
|
+
* Accepts a bare user id or the full object:
|
|
1650
|
+
*
|
|
1651
|
+
* ```ts
|
|
1652
|
+
* MapleBrowser.identify("user_123")
|
|
1653
|
+
* MapleBrowser.identify({ id: "user_123", email: "a@b.com", groupId: "org_1", groupName: "Acme" })
|
|
1654
|
+
* ```
|
|
1655
|
+
*
|
|
1656
|
+
* Each call replaces the identity rather than merging — merging would leak a
|
|
1657
|
+
* signed-out user's email into whoever signs in next on a shared device.
|
|
1658
|
+
*
|
|
1659
|
+
* Safe before `init()`: the latest call is held and applied when `init()` runs,
|
|
1660
|
+
* taking precedence over the `user` passed to it.
|
|
1661
|
+
*/
|
|
1662
|
+
function identify(input) {
|
|
1663
|
+
if (typeof window === "undefined") return;
|
|
1664
|
+
if (!activeConfig) {
|
|
1665
|
+
pendingIdentity = { input };
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
activeConfig.identity = normalizeIdentity(input);
|
|
1669
|
+
}
|
|
1670
|
+
//#endregion
|
|
1671
|
+
//#region src/logger.ts
|
|
1672
|
+
const method = (level) => (message, attributes) => {
|
|
1673
|
+
try {
|
|
1674
|
+
emitLog({
|
|
1675
|
+
severityNumber: Severity[level],
|
|
1676
|
+
severityText: level,
|
|
1677
|
+
body: String(message),
|
|
1678
|
+
attributes
|
|
1679
|
+
});
|
|
1680
|
+
} catch {}
|
|
1681
|
+
};
|
|
1682
|
+
//#endregion
|
|
1683
|
+
//#region src/index.ts
|
|
1684
|
+
/**
|
|
1685
|
+
* Maple browser SDK. One call wires up OpenTelemetry tracing and rrweb session
|
|
1686
|
+
* replay, both tagged with a shared session id.
|
|
1687
|
+
*
|
|
1688
|
+
* @example
|
|
1689
|
+
* ```ts
|
|
1690
|
+
* import { MapleBrowser } from "@maple-dev/browser"
|
|
1691
|
+
*
|
|
1692
|
+
* MapleBrowser.init({
|
|
1693
|
+
* ingestKey: "maple_pk_...",
|
|
1694
|
+
* serviceName: "acme-web",
|
|
1695
|
+
* region: "eu", // omit for the US region
|
|
1696
|
+
* })
|
|
1697
|
+
*
|
|
1698
|
+
* MapleBrowser.identify({ id: user.id, email: user.email, groupId: org.id, groupName: org.name })
|
|
1699
|
+
* MapleBrowser.track("checkout_completed", { plan: "pro", seats: 5 })
|
|
1700
|
+
* ```
|
|
1701
|
+
*/
|
|
1702
|
+
const MapleBrowser = {
|
|
1703
|
+
init,
|
|
1704
|
+
identify,
|
|
1705
|
+
track,
|
|
1706
|
+
captureException,
|
|
1707
|
+
setConsent,
|
|
1708
|
+
startNavigation,
|
|
1709
|
+
endNavigation,
|
|
1710
|
+
traced,
|
|
1711
|
+
logger: {
|
|
1712
|
+
debug: method("DEBUG"),
|
|
1713
|
+
info: method("INFO"),
|
|
1714
|
+
warn: method("WARN"),
|
|
1715
|
+
error: method("ERROR")
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
//#endregion
|
|
1719
|
+
export { consentRevokedAt as _, detachLogSink as a, resourceAttributes as c, attachSpanStash as d, claimPageSignal as f, consentAllowedSince as g, severityOf as h, attachLogSink as i, SDK_NAME as l, Severity as m, navigationSpanAt as n, emitLog as o, onErrorRecorded as p, onDocumentPageload as r, liveMapleTracer as s, MapleBrowser as t, SDK_VERSION as u, hasConsent as v, onConsentChange as y };
|