@libo11y/rum 0.0.0-stage → 0.6.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.
Files changed (129) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +478 -2
  3. package/dist/actions/collector.d.ts +29 -0
  4. package/dist/actions/collector.js +260 -0
  5. package/dist/actions/naming.d.ts +15 -0
  6. package/dist/actions/naming.js +65 -0
  7. package/dist/actions/record.d.ts +13 -0
  8. package/dist/actions/record.js +28 -0
  9. package/dist/actions/settle.d.ts +28 -0
  10. package/dist/actions/settle.js +53 -0
  11. package/dist/attrs.d.ts +10 -0
  12. package/dist/attrs.js +12 -0
  13. package/dist/bind.d.ts +23 -0
  14. package/dist/bind.js +55 -0
  15. package/dist/bootstrap/buffer.d.ts +72 -0
  16. package/dist/bootstrap/buffer.js +95 -0
  17. package/dist/bootstrap/replay.d.ts +10 -0
  18. package/dist/bootstrap/replay.js +11 -0
  19. package/dist/bootstrap.d.ts +17 -0
  20. package/dist/bootstrap.js +33 -0
  21. package/dist/bus.d.ts +3 -0
  22. package/dist/bus.js +21 -0
  23. package/dist/config/clamp.d.ts +34 -0
  24. package/dist/config/clamp.js +79 -0
  25. package/dist/config/remote.d.ts +103 -0
  26. package/dist/config/remote.js +241 -0
  27. package/dist/context-manager.d.ts +8 -0
  28. package/dist/context-manager.js +29 -0
  29. package/dist/contracts/binding.d.ts +82 -0
  30. package/dist/contracts/binding.js +1 -0
  31. package/dist/contracts/retention.d.ts +32 -0
  32. package/dist/contracts/retention.js +1 -0
  33. package/dist/contracts/runtime.d.ts +164 -0
  34. package/dist/contracts/runtime.js +1 -0
  35. package/dist/contracts/session.d.ts +68 -0
  36. package/dist/contracts/session.js +1 -0
  37. package/dist/contracts/summary.d.ts +28 -0
  38. package/dist/contracts/summary.js +1 -0
  39. package/dist/contracts/views.d.ts +71 -0
  40. package/dist/contracts/views.js +1 -0
  41. package/dist/core-setup.d.ts +121 -0
  42. package/dist/core-setup.js +1117 -0
  43. package/dist/core.d.ts +46 -0
  44. package/dist/core.js +36 -0
  45. package/dist/errors/breadcrumbs.d.ts +16 -0
  46. package/dist/errors/breadcrumbs.js +27 -0
  47. package/dist/errors/collector.d.ts +17 -0
  48. package/dist/errors/collector.js +186 -0
  49. package/dist/errors/normalize.d.ts +7 -0
  50. package/dist/errors/normalize.js +31 -0
  51. package/dist/errors/record.d.ts +20 -0
  52. package/dist/errors/record.js +46 -0
  53. package/dist/frustration/detect.d.ts +38 -0
  54. package/dist/frustration/detect.js +62 -0
  55. package/dist/ids.d.ts +2 -0
  56. package/dist/ids.js +2 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +12 -0
  59. package/dist/internal.d.ts +34 -0
  60. package/dist/internal.js +25 -0
  61. package/dist/loaf.d.ts +15 -0
  62. package/dist/loaf.js +27 -0
  63. package/dist/options.d.ts +84 -0
  64. package/dist/options.js +1 -0
  65. package/dist/pending-spans.d.ts +29 -0
  66. package/dist/pending-spans.js +92 -0
  67. package/dist/query.d.ts +2 -0
  68. package/dist/query.js +19 -0
  69. package/dist/resources/collector.d.ts +76 -0
  70. package/dist/resources/collector.js +270 -0
  71. package/dist/resources/server-timing.d.ts +18 -0
  72. package/dist/resources/server-timing.js +21 -0
  73. package/dist/retention/buffer.d.ts +29 -0
  74. package/dist/retention/buffer.js +130 -0
  75. package/dist/retention/exporters.d.ts +71 -0
  76. package/dist/retention/exporters.js +281 -0
  77. package/dist/retention/sessions.d.ts +4 -0
  78. package/dist/retention/sessions.js +30 -0
  79. package/dist/session/local-store.d.ts +25 -0
  80. package/dist/session/local-store.js +91 -0
  81. package/dist/session/manager.d.ts +36 -0
  82. package/dist/session/manager.js +169 -0
  83. package/dist/session/sampling.d.ts +4 -0
  84. package/dist/session/sampling.js +20 -0
  85. package/dist/session/state.d.ts +4 -0
  86. package/dist/session/state.js +28 -0
  87. package/dist/settings.d.ts +8 -0
  88. package/dist/settings.js +36 -0
  89. package/dist/setup.d.ts +42 -0
  90. package/dist/setup.js +57 -0
  91. package/dist/span-processor.d.ts +38 -0
  92. package/dist/span-processor.js +125 -0
  93. package/dist/summary/accumulator.d.ts +30 -0
  94. package/dist/summary/accumulator.js +128 -0
  95. package/dist/version.d.ts +2 -0
  96. package/dist/version.js +2 -0
  97. package/dist/views/collector.d.ts +40 -0
  98. package/dist/views/collector.js +286 -0
  99. package/dist/views/history.d.ts +18 -0
  100. package/dist/views/history.js +42 -0
  101. package/dist/views/naming.d.ts +6 -0
  102. package/dist/views/naming.js +12 -0
  103. package/dist/views/paint.d.ts +12 -0
  104. package/dist/views/paint.js +15 -0
  105. package/dist/views/tracker.d.ts +37 -0
  106. package/dist/views/tracker.js +114 -0
  107. package/dist/vitals/attribution.d.ts +14 -0
  108. package/dist/vitals/attribution.js +60 -0
  109. package/dist/vitals/collector.d.ts +24 -0
  110. package/dist/vitals/collector.js +232 -0
  111. package/dist/vitals/lcp.d.ts +32 -0
  112. package/dist/vitals/lcp.js +49 -0
  113. package/dist/webext/chrome.d.ts +45 -0
  114. package/dist/webext/chrome.js +13 -0
  115. package/dist/webext/config-storage.d.ts +18 -0
  116. package/dist/webext/config-storage.js +98 -0
  117. package/dist/webext/scope.d.ts +22 -0
  118. package/dist/webext/scope.js +50 -0
  119. package/dist/webext/session-access.d.ts +13 -0
  120. package/dist/webext/session-access.js +9 -0
  121. package/dist/webext/session-store.d.ts +5 -0
  122. package/dist/webext/session-store.js +104 -0
  123. package/dist/webext/setup.d.ts +74 -0
  124. package/dist/webext/setup.js +206 -0
  125. package/dist/webext.d.ts +10 -0
  126. package/dist/webext.js +8 -0
  127. package/dist/wire.d.ts +13 -0
  128. package/dist/wire.js +30 -0
  129. package/package.json +60 -4
@@ -0,0 +1,1117 @@
1
+ /**
2
+ * setupRumCore: RUM over a platform binding. In order: settings, the
3
+ * retention buffer (opened lazily), the session manager, the bus, the summary accumulator, the
4
+ * view tracker, the span processor, then the binding, which runs the platform's setup with RUM's
5
+ * wrappers. After setup: consent wiring (collectors run only while granted), session events, hide
6
+ * handling and activity from the platform's lifecycle. The returned handle is the platform's
7
+ * telemetry extended in place with rum. setupRumWith (setup.ts) binds it to the web.
8
+ *
9
+ * Nothing here imports a browser-only module or reads a browser global; every platform part is a
10
+ * dependency (core.test.ts enforces the imports), so a platform without a DOM, such as React
11
+ * Native, can bind it.
12
+ *
13
+ * The span processor reaches core as options.spanProcessor. Core treats an injected processor as
14
+ * the traces route ("injected") and then uses no span exporter the platform builds, so RUM also
15
+ * injects a forwarding span exporter. When the binding hands RUM its platform's delivery (before
16
+ * core builds anything), RUM builds the span exporter for the route traces would have had without
17
+ * RUM: none in hermetic mode, else OTEL_TRACES_EXPORTER from the platform's env. An app that
18
+ * injects its own spanExporter keeps it, routed by session; one that injects only a spanProcessor
19
+ * keeps sole charge of span export.
20
+ *
21
+ * Only spans and log records routed to OTLP wait in the retention buffer, which sends through the
22
+ * platform's delivery. Those of the console route, and those of an exporter the app injected, wait
23
+ * in memory instead (holdingSpanExporter, holdingLogExporter) and go to their own exporter once
24
+ * their session is kept.
25
+ *
26
+ * Consent. Closing the gate stops RUM at once, in the gate listener, so a grant that follows a
27
+ * revoke before the revoke hooks finish starts RUM again. The revoke hook then removes the stored
28
+ * session, the configuration cache and the retention buffer, and waits for stores that write
29
+ * asynchronously. A start that is denied (consent.initial, or a respected privacy signal) removes
30
+ * them too, before setup resolves, so a later grant never resumes what an earlier page stored. A
31
+ * pending start touches no RUM storage.
32
+ *
33
+ * OTEL_SDK_DISABLED=true (outside hermetic mode) disables RUM as core disables its providers: no
34
+ * session, collector, remote configuration or bootstrap replay starts, on a grant or otherwise. A
35
+ * denied start and a revoke still remove what an earlier page stored.
36
+ */
37
+ import { O11yError } from "@libo11y/core";
38
+ import { ATTR_RUM_CONFIG_VERSION, ATTR_RUM_CONNECTION_EFFECTIVE, ATTR_RUM_PLATFORM, ATTR_RUM_SESSION_RETAINED, ATTR_RUM_VIEW_ID, EVENT_NAME_KEY, EVENT_RUM_SESSION_END, EVENT_RUM_SESSION_START, EVENT_RUM_VIEW_SUMMARY, RUM_CONNECTION_EFFECTIVE_VALUES, } from "@libo11y/spec";
39
+ import { createContextManager, createSpanExporter, isIgnored, OTLP_SIGNALS, pristineFetch, reportFlush, } from "@libo11y/web/portable";
40
+ import { diag, ROOT_CONTEXT, SeverityNumber } from "@opentelemetry/api";
41
+ import { ExportResultCode } from "@opentelemetry/core";
42
+ import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
43
+ import { recordInstantAction } from "./actions/record.js";
44
+ import { ATTR_SESSION_ID, ATTR_USER_ID } from "./attrs.js";
45
+ import { createBus } from "./bus.js";
46
+ import { CONFIG_PINNED_STORAGE_KEY, CONFIG_STORAGE_KEY, } from "./config/remote.js";
47
+ import { rumContextManager } from "./context-manager.js";
48
+ import { createBreadcrumbs } from "./errors/breadcrumbs.js";
49
+ import { recordError } from "./errors/record.js";
50
+ import { createPendingSpans } from "./pending-spans.js";
51
+ import { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.js";
52
+ import { holdingLogExporter, holdingSpanExporter, retainingLogExporter, retainingSpanExporter, } from "./retention/exporters.js";
53
+ import { sessionsIn } from "./retention/sessions.js";
54
+ import { createSessionManager } from "./session/manager.js";
55
+ import { resolveSettings } from "./settings.js";
56
+ import { rumSpanProcessor } from "./span-processor.js";
57
+ import { createSummaryAccumulator } from "./summary/accumulator.js";
58
+ import { VERSION } from "./version.js";
59
+ import { createViewTracker } from "./views/tracker.js";
60
+ import { gatewayTransportOptions } from "./wire.js";
61
+ const runtimes = new WeakMap();
62
+ /** The RUM runtime behind a RUM telemetry, for the adapter packages and the browser fixtures. */
63
+ export function runtimeOf(telemetry) {
64
+ return runtimes.get(telemetry);
65
+ }
66
+ function composeProcessors(first, second) {
67
+ if (second === undefined)
68
+ return first;
69
+ const composed = {
70
+ onStart: (s, c) => {
71
+ first.onStart(s, c);
72
+ second.onStart(s, c);
73
+ },
74
+ onEnd: (s) => {
75
+ first.onEnd(s);
76
+ second.onEnd(s);
77
+ },
78
+ forceFlush: async () => {
79
+ await Promise.all([first.forceFlush(), second.forceFlush()]);
80
+ },
81
+ shutdown: async () => {
82
+ await Promise.all([first.shutdown(), second.shutdown()]);
83
+ },
84
+ };
85
+ if (first.onEnding !== undefined || second.onEnding !== undefined) {
86
+ const a = first.onEnding?.bind(first);
87
+ const b = second.onEnding?.bind(second);
88
+ composed.onEnding = (span) => {
89
+ a?.(span);
90
+ b?.(span);
91
+ };
92
+ }
93
+ return composed;
94
+ }
95
+ const SUCCESS = { code: ExportResultCode.SUCCESS };
96
+ /** How long a tab that ended a session waits to hear whether another tab's rotation won. */
97
+ export const SESSION_END_ELECTION_MILLIS = 500;
98
+ /**
99
+ * A span exporter that hands every batch to the target set later, and succeeds while there is none.
100
+ * A batch with a span that waits for the session goes on once the session is known.
101
+ */
102
+ function forwardingSpanExporter(target, pending) {
103
+ return {
104
+ export(spans, done) {
105
+ const go = (batch) => {
106
+ const t = target();
107
+ if (t === undefined)
108
+ done(SUCCESS);
109
+ else
110
+ t.export(batch, done);
111
+ };
112
+ const send = (batch) => {
113
+ try {
114
+ go(batch);
115
+ }
116
+ catch (err) {
117
+ done({ code: ExportResultCode.FAILED, error: err instanceof Error ? err : new Error(String(err)) });
118
+ }
119
+ };
120
+ const ready = pending.prepare(spans);
121
+ if (Array.isArray(ready))
122
+ send(ready);
123
+ else
124
+ ready.then(send, () => done(SUCCESS));
125
+ },
126
+ forceFlush: async () => {
127
+ await target()?.forceFlush?.();
128
+ },
129
+ shutdown: async () => {
130
+ await target()?.shutdown();
131
+ },
132
+ };
133
+ }
134
+ /** LifecycleOptions.timeoutMillis when none is given, as in core. */
135
+ const DEFAULT_SHUTDOWN_MILLIS = 5000;
136
+ /** The longest a timer can wait. */
137
+ const MAX_TIMER_MILLIS = 2_147_483_647;
138
+ /** The caller's shutdown deadline, read as core and web read it. */
139
+ function shutdownMillis(given) {
140
+ const ms = typeof given === "string" && given.trim() !== "" ? Number(given) : given;
141
+ if (typeof ms !== "number" || Number.isNaN(ms))
142
+ return DEFAULT_SHUTDOWN_MILLIS;
143
+ return Math.min(Math.max(ms, 0), MAX_TIMER_MILLIS);
144
+ }
145
+ /** True when work settles within ms, false when the deadline passes first. The timer never holds a process open. */
146
+ async function within(ms, work) {
147
+ let timer;
148
+ const expired = new Promise((resolve) => {
149
+ timer = setTimeout(() => resolve(false), ms);
150
+ timer.unref?.();
151
+ });
152
+ try {
153
+ return await Promise.race([work.then(() => true), expired]);
154
+ }
155
+ finally {
156
+ clearTimeout(timer);
157
+ }
158
+ }
159
+ /** OTEL_SDK_DISABLED as core reads it: ignored in hermetic mode, else true when it is "true" in any case. */
160
+ function sdkDisabledIn(hermetic, env) {
161
+ return !hermetic && (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true";
162
+ }
163
+ /**
164
+ * The OTLP protocol of traces: OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, else OTEL_EXPORTER_OTLP_PROTOCOL,
165
+ * else http/json. Throws O11yError UNSUPPORTED_PROTOCOL for anything but http/json, the only
166
+ * protocol of the span exporter RUM builds.
167
+ */
168
+ function checkTracesProtocol(env) {
169
+ const protocol = (env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL ?? "").trim() ||
170
+ (env.OTEL_EXPORTER_OTLP_PROTOCOL ?? "").trim() ||
171
+ "http/json";
172
+ if (protocol !== "http/json") {
173
+ throw new O11yError("UNSUPPORTED_PROTOCOL", `o11y: unsupported OTLP protocol ${JSON.stringify(protocol)} for traces: RUM exports http/json only`);
174
+ }
175
+ }
176
+ /** The traces route core would have resolved without RUM's injected processor and exporter. */
177
+ function naturalTracesRoute(hermetic, env) {
178
+ if (hermetic || (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true")
179
+ return "none";
180
+ const first = (env.OTEL_TRACES_EXPORTER ?? "")
181
+ .split(",")
182
+ .map((v) => v.trim().toLowerCase())
183
+ .find((v) => v !== "");
184
+ const value = first ?? "otlp";
185
+ if (value === "otlp" || value === "console" || value === "none")
186
+ return value;
187
+ throw new O11yError("EXPORTER", `o11y: building span exporter: unknown exporter ${value}`);
188
+ }
189
+ /**
190
+ * The logs route core resolves: none in hermetic mode or with the SDK disabled, else the first
191
+ * value of OTEL_LOGS_EXPORTER, default otlp. Core refuses an unknown value itself.
192
+ */
193
+ function naturalLogsRoute(hermetic, env) {
194
+ if (hermetic || (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true")
195
+ return "none";
196
+ const first = (env.OTEL_LOGS_EXPORTER ?? "")
197
+ .split(",")
198
+ .map((v) => v.trim().toLowerCase())
199
+ .find((v) => v !== "");
200
+ return first ?? "otlp";
201
+ }
202
+ /** The remote configuration URL: base, else the export endpoint next to /v1/<signal>, with the service and client token. */
203
+ function configUrl(base, endpoints, page, service, clientToken) {
204
+ let raw = base;
205
+ if (raw === undefined && endpoints !== undefined) {
206
+ for (const [signal, u] of Object.entries(endpoints)) {
207
+ const suffix = `/v1/${signal}`;
208
+ if (u?.endsWith(suffix) === true) {
209
+ raw = `${u.slice(0, -suffix.length)}/v1/config`;
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ if (raw === undefined || typeof service !== "string" || service === "")
215
+ return undefined;
216
+ let url;
217
+ try {
218
+ url = new URL(raw, page);
219
+ }
220
+ catch {
221
+ return undefined;
222
+ }
223
+ url.searchParams.set("service", service);
224
+ if (clientToken !== undefined)
225
+ url.searchParams.set("client_token", clientToken);
226
+ return url.href;
227
+ }
228
+ /**
229
+ * RUM over deps.bind: options are the platform's setup options, rumOptions RUM's own. Resolves with
230
+ * the platform's telemetry, with rum added.
231
+ */
232
+ export async function setupRumCore(options, rumOptions, deps) {
233
+ const resolved = resolveSettings(rumOptions);
234
+ const platform = deps.platform;
235
+ // Remote configuration. The connection opens on the first grant. settings
236
+ // are those of the current session: the document it started under, within the code's limits. A
237
+ // new session takes the newest document. killed is the kill switch of the newest document.
238
+ const rc = rumOptions?.remoteConfig;
239
+ let remote;
240
+ let killed = false;
241
+ let settings = resolved;
242
+ /**
243
+ * The document the current session started under, once known. Newer documents push it out of the
244
+ * cache's newest two while the session runs, so it is kept here and pinned in the cache, where a
245
+ * reload or another tab resuming the session finds it.
246
+ */
247
+ let pinned;
248
+ const sessionDocument = (s) => {
249
+ if (remote === undefined || s === undefined)
250
+ return undefined;
251
+ if (pinned?.id === s.id && pinned.doc.version === s.configVersion)
252
+ return pinned.doc;
253
+ const doc = remote.find(s.configVersion);
254
+ if (doc !== undefined) {
255
+ pinned = { id: s.id, doc };
256
+ remote.pin?.(doc);
257
+ }
258
+ return doc;
259
+ };
260
+ /**
261
+ * A session started under a document this context has not got yet runs under the newest one until
262
+ * its own arrives, when onRemote reapplies. One started without a version keeps the code settings.
263
+ */
264
+ const forSession = (s) => remote === undefined
265
+ ? resolved
266
+ : remote.apply(resolved, sessionDocument(s) ?? (s?.configVersion === undefined ? undefined : remote.current()));
267
+ const newest = () => remote === undefined ? resolved : remote.apply(resolved, remote.current());
268
+ const retention = createRetentionBuffer({
269
+ open: () => deps.openRetentionQueue({
270
+ ...RETENTION_QUEUE_DEFAULTS,
271
+ maxBytes: rumOptions?.retention?.maxBytes ?? RETENTION_QUEUE_DEFAULTS.maxBytes,
272
+ maxAgeMillis: rumOptions?.retention?.maxAgeMillis ?? RETENTION_QUEUE_DEFAULTS.maxAgeMillis,
273
+ }),
274
+ now: deps.now,
275
+ sendTimeoutMillis: options.transport?.timeoutMillis,
276
+ });
277
+ const sessionStore = deps.sessionStore();
278
+ const session = createSessionManager({
279
+ store: sessionStore,
280
+ sampleRate: () => newest().sessionSampleRate,
281
+ idleMillis: resolved.sessionIdleMillis,
282
+ maxMillis: resolved.sessionMaxMillis,
283
+ configVersion: () => newest().configVersion,
284
+ now: deps.now,
285
+ });
286
+ const bus = createBus();
287
+ // The breadcrumb ring every error carries: actions, view starts and requests.
288
+ const crumbs = createBreadcrumbs();
289
+ // A request that ends after a revoke must not leave a breadcrumb for the next grant.
290
+ bus.subscribe((s) => {
291
+ if (s.type === "breadcrumb" && controller?.recording() === true)
292
+ crumbs.add(s.kind, s.label, s.at, s.key);
293
+ });
294
+ /** The open action, so requests started meanwhile become its children. */
295
+ let active;
296
+ const hooks = new Set();
297
+ let userId;
298
+ let telemetry;
299
+ let controller;
300
+ let delivery;
301
+ let endpoints;
302
+ /** OTEL_SDK_DISABLED is true in the platform's env: RUM starts nothing. */
303
+ let sdkDisabled = false;
304
+ const lifecycle = deps.lifecycle;
305
+ const shown = lifecycle.visible;
306
+ const summary = createSummaryAccumulator({
307
+ platform,
308
+ emit: (attrs) => telemetry?.event(EVENT_RUM_VIEW_SUMMARY, attrs),
309
+ now: deps.perfNow,
310
+ visible: shown,
311
+ context: () => {
312
+ const c = deps.connection();
313
+ return c !== undefined && RUM_CONNECTION_EFFECTIVE_VALUES.includes(c)
314
+ ? { [ATTR_RUM_CONNECTION_EFFECTIVE]: c }
315
+ : {};
316
+ },
317
+ // The version of the session a view opens in, so a late vital of a view whose session has
318
+ // rotated since never carries the newer session's version.
319
+ origin: () => {
320
+ const v = session.current()?.configVersion;
321
+ return v === undefined ? {} : { [ATTR_RUM_CONFIG_VERSION]: v };
322
+ },
323
+ });
324
+ // Every client request counts toward the current view's summary (o11y.rum.summary.requests).
325
+ bus.subscribe((s) => {
326
+ if (s.type === "request-start")
327
+ summary.count("requests");
328
+ });
329
+ const views = createViewTracker({
330
+ session,
331
+ summary,
332
+ viewName: (u) => settings.viewName(u),
333
+ location: deps.location,
334
+ now: deps.perfNow,
335
+ prerendered: deps.prerendered,
336
+ window: deps.window,
337
+ initialStart: deps.scope?.fixedView === true ? deps.perfNow : deps.initialViewStart,
338
+ viewKind: deps.viewKind,
339
+ });
340
+ views.subscribe((e) => {
341
+ if (e.type === "start") {
342
+ bus.publish({
343
+ type: "breadcrumb",
344
+ kind: "view",
345
+ label: e.view.name,
346
+ at: e.view.startTime,
347
+ key: e.view.id,
348
+ });
349
+ }
350
+ else if (e.type === "rename")
351
+ crumbs.relabel(e.view.id, e.view.name);
352
+ });
353
+ /**
354
+ * What the router adapter last reported, kept while consent is not granted too: the path it was
355
+ * on, the name it gave the view and when the view rendered. A grant applies it to the view RUM
356
+ * starts then, so a route that rendered before consent is named and rendered, not left to the
357
+ * view span cap. It applies only while the URL path is still the one reported.
358
+ */
359
+ let routed;
360
+ const pathNow = () => {
361
+ try {
362
+ return new URL(deps.location()).pathname;
363
+ }
364
+ catch {
365
+ return "";
366
+ }
367
+ };
368
+ /** What the adapter reported on this path, or a fresh record when it moved to another path. */
369
+ const samePath = () => {
370
+ const path = pathNow();
371
+ return routed?.path === path ? routed : { path };
372
+ };
373
+ const routedNow = () => routed !== undefined && routed.path === pathNow() ? routed : undefined;
374
+ const pending = createPendingSpans();
375
+ const processor = rumSpanProcessor({
376
+ platform,
377
+ pending,
378
+ session,
379
+ views,
380
+ queryAllowList: () => settings.queryAllowList,
381
+ userId: () => userId,
382
+ bus,
383
+ now: deps.perfNow,
384
+ timeOrigin: deps.timeOrigin,
385
+ });
386
+ const onStart = (span, request) => {
387
+ for (const h of hooks) {
388
+ try {
389
+ h(span, request);
390
+ }
391
+ catch (err) {
392
+ diag.warn("o11y: rum: onRequestStart hook threw", err);
393
+ }
394
+ }
395
+ };
396
+ // Buffer writes still in flight, so a flush after retention sees every batch exported before it.
397
+ // put never rejects.
398
+ const puts = new Set();
399
+ const settled = async () => {
400
+ await Promise.allSettled([...puts]);
401
+ };
402
+ const routing = {
403
+ decide: (id) => session.decide(id),
404
+ buffer: (b) => {
405
+ const p = retention.put(b).finally(() => puts.delete(p));
406
+ puts.add(p);
407
+ },
408
+ };
409
+ // A buffered batch goes out only when every session it holds records of is to be sent, because
410
+ // the buffer is shared by every tab and may hold another session's batches.
411
+ const keep = (b) => {
412
+ const ids = sessionsIn(b);
413
+ return ids !== undefined && [...ids].every((id) => session.decide(id) === "send");
414
+ };
415
+ const appExporter = options.spanExporter;
416
+ // An app that injects only a processor exports spans itself, so RUM adds no exporter.
417
+ const forward = options.spanProcessor === undefined || appExporter !== undefined;
418
+ /** The OTLP endpoints, once web resolved them. */
419
+ let ownUrls = [];
420
+ /** Endpoints collectors count as RUM's own traffic (ignoreUrl), as origin plus path, such as the replay endpoint. */
421
+ const collectorUrls = new Map();
422
+ /** Attributes collectors add to named events (addEventAttributes). */
423
+ const decorators = new Set();
424
+ const ignoreUrls = options.instrumentations?.ignoreUrls ?? [];
425
+ // The retention buffer sends through the platform's delivery, so the spans and log records an
426
+ // app's own exporter or a console exporter would get wait in memory instead, and go to that
427
+ // exporter once their session is kept. A release that comes after a revoke exports nothing.
428
+ const holdOpts = { allowed: () => controller?.recording() === true };
429
+ let held = appExporter === undefined ? undefined : holdingSpanExporter(appExporter, routing.decide, holdOpts);
430
+ let spanTarget = held;
431
+ const appLogExporter = options.logExporter;
432
+ let heldLogs = appLogExporter === undefined ? undefined : holdingLogExporter(appLogExporter, routing.decide, holdOpts);
433
+ /** The logs route core resolves, once the platform's env is known. */
434
+ let logsRoute = "otlp";
435
+ const holders = () => [held, heldLogs].filter((h) => h !== undefined);
436
+ const wrappers = {
437
+ consentController: (c) => {
438
+ controller = c;
439
+ return c;
440
+ },
441
+ transportOptions: (o) => gatewayTransportOptions(o, resolved.clientToken, deps.now),
442
+ platform: (po, env) => {
443
+ delivery = po.delivery;
444
+ endpoints = po.endpoints;
445
+ ownUrls = OTLP_SIGNALS.flatMap((s) => (po.endpoints[s] === undefined ? [] : [po.endpoints[s]]));
446
+ sdkDisabled = sdkDisabledIn(options.hermetic === true, env);
447
+ logsRoute = naturalLogsRoute(options.hermetic === true, env);
448
+ if (forward && appExporter === undefined) {
449
+ const route = naturalTracesRoute(options.hermetic === true, env);
450
+ // Core checks the protocol only of a route it builds, and traces reach it injected.
451
+ if (route === "otlp")
452
+ checkTracesProtocol(env);
453
+ if (route === "console") {
454
+ held = holdingSpanExporter(new ConsoleSpanExporter(), routing.decide, holdOpts);
455
+ spanTarget = held;
456
+ }
457
+ else if (route === "otlp" && po.endpoints.traces !== undefined) {
458
+ const inner = createSpanExporter(po.delivery, po.mode === undefined ? {} : { mode: po.mode });
459
+ spanTarget = retainingSpanExporter(inner, routing);
460
+ }
461
+ else
462
+ spanTarget = undefined;
463
+ }
464
+ },
465
+ // Traces reach core injected, so the set's span exporter goes unused. Only OTLP log records wait
466
+ // in the retention buffer; console ones wait in memory.
467
+ exporterSet: (set) => {
468
+ const logs = set.logExporter;
469
+ if (logs === undefined)
470
+ return set;
471
+ if (logsRoute === "console") {
472
+ heldLogs = holdingLogExporter(logs, routing.decide, holdOpts);
473
+ return { ...set, logExporter: heldLogs };
474
+ }
475
+ return { ...set, logExporter: retainingLogExporter(logs, routing) };
476
+ },
477
+ onRequestStart: onStart,
478
+ };
479
+ // Hide handling. On a navigation, every engine fires pagehide before visibilitychange, and web's
480
+ // flush on hide runs once per hide and exports whatever is pending at that moment; a flush
481
+ // started after it waits for its export, which never completes once the page is gone. So RUM
482
+ // subscribes to the lifecycle before the binding runs the platform's setup: on the first hide
483
+ // signal it runs the hide hooks (vitals commit their values) and emits the summaries, and the
484
+ // platform's flush then exports them with the detail already pending. web-vitals listens in the
485
+ // capture phase on window, so its own hide reports land before either listener runs, and a
486
+ // later hide signal of the same hide sends what they added.
487
+ //
488
+ // RUM never exports on hide itself. Firefox and WebKit fire pagehide while the document still
489
+ // reports visible, so the send mode is "unload" only once web's own pagehide listener has run,
490
+ // and the microtasks after each listener would carry an export RUM started to the transport
491
+ // before that: a normal send, which the browser drops with the page.
492
+ const hideHooks = new Set();
493
+ let hideHandled = false;
494
+ /** What a hide sends, once setup finished. */
495
+ let afterHide;
496
+ const runHide = () => {
497
+ if (hideHandled)
498
+ return;
499
+ hideHandled = true;
500
+ summary.visibility(false);
501
+ for (const hook of [...hideHooks]) {
502
+ try {
503
+ hook();
504
+ }
505
+ catch (err) {
506
+ diag.warn("o11y: rum: a hide hook threw", err);
507
+ }
508
+ }
509
+ };
510
+ const offLifecycle = lifecycle.subscribe({
511
+ hide: () => {
512
+ runHide();
513
+ afterHide?.();
514
+ },
515
+ show: () => {
516
+ hideHandled = false;
517
+ summary.visibility(true);
518
+ if (!killed)
519
+ session.touch();
520
+ },
521
+ restore: () => {
522
+ hideHandled = false;
523
+ },
524
+ });
525
+ let t;
526
+ try {
527
+ t = await deps.bind({
528
+ ...options,
529
+ spanProcessor: composeProcessors(processor, options.spanProcessor),
530
+ contextManager: () => rumContextManager((options.contextManager ?? createContextManager)(), () => active),
531
+ ...(forward ? { spanExporter: forwardingSpanExporter(() => spanTarget, pending) } : {}),
532
+ ...(heldLogs === undefined ? {} : { logExporter: heldLogs }),
533
+ }, wrappers);
534
+ }
535
+ catch (err) {
536
+ offLifecycle();
537
+ views.close();
538
+ session.close();
539
+ retention.close();
540
+ throw err;
541
+ }
542
+ telemetry = t;
543
+ const gate = controller;
544
+ if (gate === undefined) {
545
+ await t.shutdown();
546
+ throw new O11yError("INVALID_OPTION", "rum: web setup built no consent controller");
547
+ }
548
+ /** RUM records: the SDK is enabled, consent is granted and remote configuration has not switched it off. */
549
+ const on = () => !sdkDisabled && gate.recording() && !killed;
550
+ // Events with a body (semconv's browser.web_vital) are bridge records: core's redacting log
551
+ // processor classifies their attributes, and the retention exporters route them by session.id.
552
+ const bodyLogger = t.loggerProvider.getLogger("@libo11y/rum", VERSION);
553
+ const runtime = {
554
+ platform,
555
+ ...(deps.scope === undefined ? {} : { scope: deps.scope }),
556
+ telemetry: t,
557
+ tracer: t.tracerProvider.getTracer("@libo11y/rum", VERSION),
558
+ gate,
559
+ session,
560
+ views,
561
+ summary,
562
+ bus,
563
+ settings: () => settings,
564
+ now: deps.perfNow,
565
+ timeOrigin: deps.timeOrigin ?? performance.timeOrigin,
566
+ emit(name, attrs = {}, ctx, body) {
567
+ if (sdkDisabled || !gate.recording())
568
+ return;
569
+ const s = session.current();
570
+ const v = views.current();
571
+ let decorated = {};
572
+ for (const d of decorators) {
573
+ if (!d.names.has(name))
574
+ continue;
575
+ try {
576
+ decorated = { ...decorated, ...d.attrs() };
577
+ }
578
+ catch (err) {
579
+ diag.warn("o11y: rum: an event attributes hook threw", err);
580
+ }
581
+ }
582
+ const merged = {
583
+ ...(s === undefined ? {} : { [ATTR_SESSION_ID]: s.id }),
584
+ ...(v === undefined ? {} : { [ATTR_RUM_VIEW_ID]: v.id }),
585
+ ...(userId === undefined ? {} : { [ATTR_USER_ID]: userId }),
586
+ ...decorated,
587
+ ...attrs,
588
+ };
589
+ if (body === undefined) {
590
+ t.event(name, merged, ctx);
591
+ return;
592
+ }
593
+ bodyLogger.emit({
594
+ eventName: name,
595
+ severityNumber: SeverityNumber.INFO,
596
+ severityText: "INFO",
597
+ body: { ...body },
598
+ attributes: { ...merged, [EVENT_NAME_KEY]: name },
599
+ // Body events report page-level values at a hide, so the span active then is unrelated.
600
+ context: ctx ?? ROOT_CONTEXT,
601
+ });
602
+ },
603
+ onRequestStart(hook) {
604
+ hooks.add(hook);
605
+ return () => hooks.delete(hook);
606
+ },
607
+ activeAction: () => active,
608
+ setActiveAction(span) {
609
+ active = span;
610
+ },
611
+ breadcrumbs: () => crumbs.snapshot(deps.perfNow()),
612
+ onHide(hook) {
613
+ hideHooks.add(hook);
614
+ return () => hideHooks.delete(hook);
615
+ },
616
+ ignored(url) {
617
+ let u;
618
+ try {
619
+ u = new URL(url);
620
+ }
621
+ catch {
622
+ return false;
623
+ }
624
+ return (ownUrls.some((own) => u.href.startsWith(own)) ||
625
+ [...collectorUrls.values()].some((own) => `${u.origin}${u.pathname}` === own) ||
626
+ isIgnored(u, ignoreUrls));
627
+ },
628
+ remoteDocument: () => sessionDocument(session.current()),
629
+ addEventAttributes(names, attrs) {
630
+ const d = { names: new Set(names), attrs };
631
+ decorators.add(d);
632
+ return () => decorators.delete(d);
633
+ },
634
+ ignoreUrl(url) {
635
+ const key = Symbol(url);
636
+ let path = url;
637
+ try {
638
+ const u = new URL(url, deps.location());
639
+ path = `${u.origin}${u.pathname}`;
640
+ }
641
+ catch {
642
+ // kept as given
643
+ }
644
+ collectorUrls.set(key, path);
645
+ return () => collectorUrls.delete(key);
646
+ },
647
+ };
648
+ deps.onRuntime?.(runtime);
649
+ // Collectors run only while consent is granted, remote configuration has not switched RUM off,
650
+ // and the current session's settings enable them.
651
+ const running = new Map();
652
+ /** The session is up and the view begun, so the enabled collectors are to run. */
653
+ let collecting = false;
654
+ let starting;
655
+ let stopRemote;
656
+ /** Consent was granted at some point in this page, so RUM may have stored something. */
657
+ let everStarted = false;
658
+ /** Bumped by stopAll, so a start whose session load outlived a revoke does nothing. */
659
+ let generation = 0;
660
+ const reconcile = () => {
661
+ const want = collecting && on() ? settings.enabled : new Set();
662
+ for (const [name, stop] of [...running].reverse()) {
663
+ if (want.has(name))
664
+ continue;
665
+ running.delete(name);
666
+ try {
667
+ stop();
668
+ }
669
+ catch (err) {
670
+ diag.warn(`o11y: rum: collector ${name} failed to stop`, err);
671
+ }
672
+ }
673
+ for (const c of resolved.collectors) {
674
+ if (!want.has(c.name) || running.has(c.name))
675
+ continue;
676
+ try {
677
+ running.set(c.name, c.start(runtime));
678
+ }
679
+ catch (err) {
680
+ diag.warn(`o11y: rum: collector ${c.name} failed to start`, err);
681
+ }
682
+ }
683
+ };
684
+ /** Starts the session, the view and the collectors. */
685
+ const activate = async (gen) => {
686
+ if (killed) {
687
+ pending.discard();
688
+ return;
689
+ }
690
+ await session.start();
691
+ // Revoked while the session loaded, and maybe granted again: that later start runs instead.
692
+ if (gen !== generation || !gate.recording() || killed) {
693
+ if (gen === generation)
694
+ pending.discard();
695
+ return;
696
+ }
697
+ settings = forSession(session.current());
698
+ views.begin();
699
+ // Spans that started while the session loaded, such as app_load right after a late grant.
700
+ const s = session.current();
701
+ pending.resolve((load) => {
702
+ const v = load ? views.loadView() : views.current();
703
+ return {
704
+ ...(s === undefined ? {} : { [ATTR_SESSION_ID]: s.id }),
705
+ ...(v === undefined ? {} : { [ATTR_RUM_VIEW_ID]: v.id }),
706
+ };
707
+ });
708
+ const r = routedNow();
709
+ if (r?.name !== undefined)
710
+ views.rename(r.name);
711
+ // A kept session may find batches an earlier page of it left in the buffer.
712
+ if (session.kept()) {
713
+ flushRetention().catch((err) => diag.warn("o11y: rum: retention flush failed", err));
714
+ }
715
+ collecting = true;
716
+ reconcile();
717
+ if (r?.renderedAt !== undefined)
718
+ views.rendered(r.renderedAt);
719
+ // A fixed view (a content script) is on screen as soon as it starts.
720
+ else if (deps.scope?.fixedView === true)
721
+ views.rendered();
722
+ };
723
+ /** The kill switch acts at once; every other change waits for the next session. */
724
+ const onRemote = (doc) => {
725
+ if (!gate.recording())
726
+ return;
727
+ const off = doc?.enabled === false;
728
+ if (off && !killed) {
729
+ killed = true;
730
+ collecting = false;
731
+ reconcile();
732
+ active = undefined;
733
+ views.end();
734
+ }
735
+ else if (!off && killed) {
736
+ killed = false;
737
+ activate(generation).catch((err) => diag.warn("o11y: rum: start failed", err));
738
+ }
739
+ else if (!off && collecting) {
740
+ // The document the current session started under may only now be known, as when another
741
+ // tab started the session under a document this tab had not fetched yet.
742
+ settings = forSession(session.current());
743
+ reconcile();
744
+ bus.publish({ type: "config" });
745
+ }
746
+ };
747
+ const openRemote = () => {
748
+ if (rc === undefined)
749
+ return undefined;
750
+ const url = configUrl(rc.url, endpoints, deps.location(), t.resource.attributes["service.name"], resolved.clientToken);
751
+ const f = deps.fetch ?? pristineFetch;
752
+ if (url === undefined || f === undefined) {
753
+ diag.warn("o11y: rum: remote configuration has no URL or no fetch; it is off");
754
+ return undefined;
755
+ }
756
+ const connect = (storage) => {
757
+ configCache = storage;
758
+ return rc.open({
759
+ url,
760
+ fetch: f,
761
+ storage,
762
+ timers: {
763
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
764
+ clearTimeout: (h) => clearTimeout(h),
765
+ },
766
+ visible: shown,
767
+ });
768
+ };
769
+ let storage;
770
+ try {
771
+ storage = deps.storage?.();
772
+ }
773
+ catch {
774
+ // No storage: remote configuration caches nothing.
775
+ }
776
+ return storage instanceof Promise ? storage.then(connect, () => connect(undefined)) : connect(storage);
777
+ };
778
+ /** The connection being opened, while its cache storage loads. */
779
+ let opening;
780
+ /** The storage the connection caches in, for its flush. */
781
+ let configCache;
782
+ const startAll = () => {
783
+ if (sdkDisabled)
784
+ return Promise.resolve();
785
+ everStarted = true;
786
+ const gen = generation;
787
+ pending.open();
788
+ starting ??= (async () => {
789
+ try {
790
+ if (remote === undefined) {
791
+ const opened = opening ?? openRemote();
792
+ if (opened instanceof Promise) {
793
+ opening = opened;
794
+ const connection = await opened;
795
+ remote ??= connection;
796
+ if (opening === opened)
797
+ opening = undefined;
798
+ // Revoked while the cache loaded: the revoke found no connection to clear.
799
+ if (gen !== generation) {
800
+ if (!gate.recording())
801
+ remote?.clear();
802
+ return;
803
+ }
804
+ }
805
+ else
806
+ remote = opened;
807
+ }
808
+ killed = remote?.current()?.enabled === false;
809
+ await activate(gen);
810
+ if (gen !== generation || !gate.recording())
811
+ return;
812
+ // A refresh that changed nothing (a 304) may still find the session's own document, which
813
+ // another tab pinned since. A session without a version finds none.
814
+ stopRemote = remote?.start(onRemote, () => {
815
+ const s = session.current();
816
+ if (pinned?.id !== s?.id && sessionDocument(s))
817
+ onRemote(remote?.current());
818
+ });
819
+ }
820
+ catch (err) {
821
+ // A start that failed releases the spans waiting for its session, so no export stalls.
822
+ if (gen === generation)
823
+ pending.discard();
824
+ throw err;
825
+ }
826
+ })();
827
+ return starting;
828
+ };
829
+ const stopAll = () => {
830
+ generation++;
831
+ pending.discard();
832
+ collecting = false;
833
+ reconcile();
834
+ stopRemote?.();
835
+ stopRemote = undefined;
836
+ starting = undefined;
837
+ };
838
+ const flushRetention = async () => {
839
+ // A revoke or shutdown meanwhile (stopAll) ends this flush, even once a new grant records again.
840
+ const gen = generation;
841
+ const still = () => gen === generation && gate.recording();
842
+ reportFlush(t, "rum: retention flush", await t.forceFlush());
843
+ await settled();
844
+ if (still())
845
+ for (const h of holders())
846
+ h.release();
847
+ if (delivery !== undefined && still())
848
+ await retention.flush(delivery, keep, still);
849
+ };
850
+ // Session end: when tabs rotate an expired session at the same moment, each ends
851
+ // it and starts a session of its own, then all adopt the same newest one. The tab whose session
852
+ // won emits o11y.rum.session.end, so it is emitted once: each tab waits SESSION_END_ELECTION_MILLIS
853
+ // for the others' broadcasts and emits only if its successor is still the current session. An
854
+ // unkept session that ends removes only its own records from the shared retention buffer.
855
+ //
856
+ // Session start: the o11y.rum.session.start of a kept session waits for the same election,
857
+ // so only the session every context ends up sharing sends its start. That covers two tabs rotating at once and two
858
+ // contexts that both find nothing stored and create the first session, as an extension's side
859
+ // panel and content script do, each before it hears of the other's. A context whose session lost
860
+ // abandons its start. A page that hides first sends its pending start if that session is still
861
+ // current, because a hidden page may never run again.
862
+ const endTimers = new Set();
863
+ let endingSession;
864
+ const pendingStarts = new Map();
865
+ const sendStart = (s) => {
866
+ t.event(EVENT_RUM_SESSION_START, {
867
+ [ATTR_SESSION_ID]: s.id,
868
+ [ATTR_RUM_PLATFORM]: platform,
869
+ ...(s.configVersion === undefined ? {} : { [ATTR_RUM_CONFIG_VERSION]: s.configVersion }),
870
+ });
871
+ };
872
+ /** Decides every start still waiting for its election now. */
873
+ const settleStarts = () => {
874
+ for (const [timer, decide] of [...pendingStarts]) {
875
+ clearTimeout(timer);
876
+ decide();
877
+ }
878
+ };
879
+ const offSession = session.subscribe((e) => {
880
+ if (e.type === "start") {
881
+ // A new session takes the newest document; an adopted one, the document it started under.
882
+ settings = forSession(e.session);
883
+ queueMicrotask(reconcile);
884
+ }
885
+ // While remote configuration has switched RUM off, a rotation sends no session events.
886
+ if (e.type === "kept") {
887
+ if (on())
888
+ flushRetention().catch((err) => diag.warn("o11y: rum: retention flush failed", err));
889
+ }
890
+ else if (e.type === "start" && e.local && on()) {
891
+ if (endingSession !== undefined && e.previous?.id === endingSession.id)
892
+ endingSession.successor = e.session.id;
893
+ const started = e.session;
894
+ // An unkept session's start waits in the retention buffer and is sent only if the session is
895
+ // kept. A session that lost its election is abandoned and never kept, so its start is never
896
+ // sent, and buffering it at once means a reload before the election cannot lose it.
897
+ if (started.retained === undefined) {
898
+ sendStart(started);
899
+ return;
900
+ }
901
+ const decide = () => {
902
+ pendingStarts.delete(timer);
903
+ if (on() && session.current()?.id === started.id)
904
+ sendStart(started);
905
+ };
906
+ const timer = setTimeout(decide, SESSION_END_ELECTION_MILLIS);
907
+ pendingStarts.set(timer, decide);
908
+ }
909
+ else if (e.type === "end" && e.local) {
910
+ const ended = e.session;
911
+ if (ended.retained === undefined) {
912
+ for (const h of holders())
913
+ h.discard(ended.id);
914
+ void (async () => {
915
+ await settled();
916
+ await retention.discard((b) => sessionsIn(b)?.has(ended.id) === true);
917
+ })();
918
+ return;
919
+ }
920
+ const candidate = { id: ended.id, retained: ended.retained, successor: undefined };
921
+ endingSession = candidate;
922
+ const timer = setTimeout(() => {
923
+ endTimers.delete(timer);
924
+ if (endingSession === candidate)
925
+ endingSession = undefined;
926
+ if (!on() || candidate.successor === undefined)
927
+ return;
928
+ if (session.current()?.id !== candidate.successor)
929
+ return; // another tab's rotation won
930
+ t.event(EVENT_RUM_SESSION_END, {
931
+ [ATTR_SESSION_ID]: candidate.id,
932
+ [ATTR_RUM_SESSION_RETAINED]: candidate.retained,
933
+ });
934
+ }, SESSION_END_ELECTION_MILLIS);
935
+ endTimers.add(timer);
936
+ }
937
+ });
938
+ const stopRecording = () => {
939
+ stopAll();
940
+ // A revoked session sends no start.
941
+ for (const timer of pendingStarts.keys())
942
+ clearTimeout(timer);
943
+ pendingStarts.clear();
944
+ active = undefined;
945
+ crumbs.clear();
946
+ summary.reset();
947
+ views.end();
948
+ session.clear();
949
+ pinned = undefined;
950
+ for (const h of holders())
951
+ h.discard();
952
+ };
953
+ /** Removes the configuration cache, opening its storage when this page has not. */
954
+ const clearConfigCache = async () => {
955
+ const connection = remote ?? (await opening);
956
+ if (connection !== undefined) {
957
+ connection.clear();
958
+ await configCache?.flush?.();
959
+ return;
960
+ }
961
+ let storage;
962
+ try {
963
+ storage = await deps.storage?.();
964
+ storage?.removeItem(CONFIG_STORAGE_KEY);
965
+ storage?.removeItem(CONFIG_PINNED_STORAGE_KEY);
966
+ }
967
+ catch (err) {
968
+ diag.debug("o11y: rum: removing the remote configuration cache failed", err);
969
+ }
970
+ await storage?.flush?.();
971
+ };
972
+ /**
973
+ * Asks every collector to remove what it stored. One that fails keeps no other from it. Replay in a
974
+ * scoped context (a content script) stored nothing, and its storage there is the host page's.
975
+ */
976
+ const clearCollectors = async () => {
977
+ const cs = resolved.collectors.filter((c) => deps.scope === undefined || c.name !== "replay");
978
+ for (const r of await Promise.allSettled(cs.map(async (c) => c.clear?.()))) {
979
+ if (r.status === "rejected")
980
+ diag.debug("o11y: rum: a collector failed to remove what it stored", r.reason);
981
+ }
982
+ };
983
+ /**
984
+ * Removes what RUM stored, in this page or an earlier one: the session, the configuration cache,
985
+ * the retention buffer and what each collector stored. Resolves once stores that write
986
+ * asynchronously have removed them.
987
+ */
988
+ const forgetStored = async () => {
989
+ // A session started in this page was removed by session.clear when the gate closed.
990
+ if (!everStarted)
991
+ sessionStore.save(undefined);
992
+ await Promise.all([clearConfigCache(), retention.clear(), clearCollectors()]);
993
+ await sessionStore.flush?.();
994
+ };
995
+ const offRevoke = gate.onRevoke(async () => {
996
+ await settled();
997
+ // A grant may already have followed the revoke; its session's records are not to be removed.
998
+ if (!gate.recording())
999
+ await forgetStored();
1000
+ });
1001
+ const offGate = gate.subscribe((recording) => {
1002
+ if (recording)
1003
+ startAll().catch((err) => diag.warn("o11y: rum: start failed", err));
1004
+ else if (everStarted)
1005
+ stopRecording();
1006
+ });
1007
+ // A hidden page may never run again (frozen or discarded on mobile), so a start still waiting for
1008
+ // its election goes out now if its session is still current.
1009
+ afterHide = () => {
1010
+ settleStarts();
1011
+ summary.flush();
1012
+ };
1013
+ const onActivity = () => {
1014
+ if (!killed)
1015
+ session.touch();
1016
+ };
1017
+ const offActivity = lifecycle.activity?.(onActivity);
1018
+ const rum = {
1019
+ sessionId: () => (!sdkDisabled && gate.recording() ? session.current()?.id : undefined),
1020
+ identify(id) {
1021
+ if (id?.includes("@")) {
1022
+ throw new O11yError("INVALID_OPTION", "rum.identify: an email address is not a pseudonymous ID");
1023
+ }
1024
+ userId = id;
1025
+ },
1026
+ onRequestStart: (hook) => runtime.onRequestStart(hook),
1027
+ startView(o) {
1028
+ routed = { path: pathNow(), ...(o?.name === undefined ? {} : { name: o.name }) };
1029
+ if (!on())
1030
+ return;
1031
+ const cause = active?.isRecording() === true ? active.spanContext() : undefined;
1032
+ views.start({
1033
+ kind: deps.viewKind ?? "soft",
1034
+ ...(o?.name === undefined ? {} : { name: o.name }),
1035
+ ...(cause === undefined ? {} : { cause }),
1036
+ });
1037
+ },
1038
+ setViewName(name) {
1039
+ routed = { ...samePath(), name };
1040
+ if (on())
1041
+ views.rename(name);
1042
+ },
1043
+ viewRendered() {
1044
+ routed = { ...samePath(), renderedAt: deps.perfNow() };
1045
+ if (on())
1046
+ views.rendered();
1047
+ },
1048
+ addAction(name) {
1049
+ if (on())
1050
+ recordInstantAction(runtime, "custom", name);
1051
+ },
1052
+ addError(error, o) {
1053
+ if (!on())
1054
+ return;
1055
+ recordError(runtime, o?.source ?? "custom", error, o?.componentStack === undefined ? {} : { componentStack: o.componentStack });
1056
+ },
1057
+ };
1058
+ const handle = t;
1059
+ Object.defineProperty(handle, "rum", { value: rum, enumerable: true });
1060
+ runtimes.set(handle, runtime);
1061
+ const webShutdown = t.shutdown.bind(t);
1062
+ let shutdownPromise;
1063
+ handle.shutdown = (opts) => {
1064
+ shutdownPromise ??= (async () => {
1065
+ const deadline = shutdownMillis(opts?.timeoutMillis);
1066
+ const started = Date.now();
1067
+ stopAll();
1068
+ views.end();
1069
+ summary.flush();
1070
+ offLifecycle();
1071
+ offActivity?.();
1072
+ offGate();
1073
+ offRevoke();
1074
+ offSession();
1075
+ settleStarts();
1076
+ for (const timer of endTimers)
1077
+ clearTimeout(timer);
1078
+ endTimers.clear();
1079
+ const report = await webShutdown(opts);
1080
+ views.close();
1081
+ session.close();
1082
+ // A holding exporter whose shutdown outlived core's deadline still stops its exporter. Buffer
1083
+ // writes, and then the holding exporters' stops, get what is left of the same deadline.
1084
+ const closing = Promise.all(holders().map((h) => h.close()));
1085
+ const left = () => Math.max(0, deadline - (Date.now() - started));
1086
+ const done = await within(left(), settled());
1087
+ await within(left(), closing);
1088
+ retention.close();
1089
+ if (done)
1090
+ return report;
1091
+ return {
1092
+ ok: false,
1093
+ errors: [
1094
+ ...report.errors,
1095
+ { signal: "lifecycle", error: new Error("o11y: shutdown rum retention: deadline exceeded") },
1096
+ ],
1097
+ };
1098
+ })();
1099
+ return shutdownPromise;
1100
+ };
1101
+ // The bootstrap buffer is replayed only into the start setup makes with consent
1102
+ // granted. A page that starts pending discards it, even if consent is granted later. It is taken
1103
+ // before the collectors start, so an event is never both buffered and seen by a collector; one
1104
+ // that happens while the session loads, between the two, is not recorded.
1105
+ const replay = deps.bootstrap?.();
1106
+ // A denied start removes what an earlier page stored, as revoking would.
1107
+ if (gate.consent.state() === "denied")
1108
+ await forgetStored();
1109
+ if (!sdkDisabled && gate.recording()) {
1110
+ await startAll();
1111
+ // A scoped context (a content script) shares its world with no page bootstrap of its own: what
1112
+ // a bootstrap there buffered may be the host page's, so it is dropped.
1113
+ if (!killed && deps.scope === undefined)
1114
+ replay?.(runtime);
1115
+ }
1116
+ return handle;
1117
+ }