@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,72 @@
1
+ /**
2
+ * The bootstrap buffer, shared by the tiny `@libo11y/rum/bootstrap` entry and the
3
+ * collectors through a global registered symbol, so the two meet even when bundled apart. It has no
4
+ * imports.
5
+ *
6
+ * Only consent already "granted" buffers anything. Then the buffer holds, in memory and never in
7
+ * storage, up to maxEntries early errors (ErrorEvents whose target is not an element: an element's
8
+ * error is a resource error, the errors collector's job), unhandled rejections, CSP violations and
9
+ * clicks, for at most BOOTSTRAP_MAX_MILLIS, after which its listeners are removed. setupRum takes
10
+ * the buffer just before its collectors start, and replays it once they started, only when it
11
+ * starts with consent granted.
12
+ */
13
+ export declare const BOOTSTRAP_KEY: unique symbol;
14
+ /** The bootstrap stops buffering this long after it was installed. */
15
+ export declare const BOOTSTRAP_MAX_MILLIS = 30000;
16
+ /** One early event. at is performance.now() when it happened. */
17
+ export type BootstrapEntry = {
18
+ readonly kind: "error";
19
+ readonly at: number;
20
+ readonly error: unknown;
21
+ readonly message: string;
22
+ } | {
23
+ readonly kind: "rejection";
24
+ readonly at: number;
25
+ readonly reason: unknown;
26
+ } | {
27
+ readonly kind: "csp";
28
+ readonly at: number;
29
+ readonly directive: string;
30
+ readonly blocked: string;
31
+ } | {
32
+ readonly kind: "click";
33
+ readonly at: number;
34
+ readonly target: Element;
35
+ };
36
+ export interface BootstrapBuffer {
37
+ readonly entries: BootstrapEntry[];
38
+ /** performance.now() when the bootstrap was installed. */
39
+ readonly startedAt: number;
40
+ /** Removes the listeners. Idempotent. */
41
+ stop(): void;
42
+ }
43
+ /** Options for installRumBootstrap. */
44
+ export interface RumBootstrapOptions {
45
+ /** The consent state setupRum will start with. Only "granted" buffers anything. Default "pending". */
46
+ readonly consent?: "pending" | "granted";
47
+ /** The most entries held. Default 100. */
48
+ readonly maxEntries?: number;
49
+ }
50
+ /** The clock the bootstrap runs on. */
51
+ export interface BootstrapClock {
52
+ /** performance.now(). */
53
+ now(): number;
54
+ setTimeout(cb: () => void, ms: number): unknown;
55
+ }
56
+ /** The page's bootstrap buffer, if a bootstrap installed one and nothing took it yet. */
57
+ export declare function bootstrapBuffer(): BootstrapBuffer | undefined;
58
+ /** Takes the buffer out of the page, its listeners removed: later calls return undefined. */
59
+ export declare function takeBootstrap(): BootstrapBuffer | undefined;
60
+ /** installRumBootstrap with the event target and clock given. Internal: tests inject both. */
61
+ export declare function installRumBootstrapOn(target: EventTarget, opts: RumBootstrapOptions, clock: BootstrapClock): void;
62
+ /** What afterLoad needs from the page. */
63
+ export interface LoadHost {
64
+ readonly document?: {
65
+ readonly readyState?: string;
66
+ };
67
+ readonly window?: EventTarget;
68
+ /** requestIdleCallback where there is one, else a zero timeout. */
69
+ idle(cb: () => void): void;
70
+ }
71
+ /** afterLoad with the page given. Internal: tests inject it. */
72
+ export declare function afterLoadOn(host: LoadHost, load: () => void): void;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The bootstrap buffer, shared by the tiny `@libo11y/rum/bootstrap` entry and the
3
+ * collectors through a global registered symbol, so the two meet even when bundled apart. It has no
4
+ * imports.
5
+ *
6
+ * Only consent already "granted" buffers anything. Then the buffer holds, in memory and never in
7
+ * storage, up to maxEntries early errors (ErrorEvents whose target is not an element: an element's
8
+ * error is a resource error, the errors collector's job), unhandled rejections, CSP violations and
9
+ * clicks, for at most BOOTSTRAP_MAX_MILLIS, after which its listeners are removed. setupRum takes
10
+ * the buffer just before its collectors start, and replays it once they started, only when it
11
+ * starts with consent granted.
12
+ */
13
+ export const BOOTSTRAP_KEY = Symbol.for("libo11y.rum.bootstrap");
14
+ /** The bootstrap stops buffering this long after it was installed. */
15
+ export const BOOTSTRAP_MAX_MILLIS = 30_000;
16
+ const DEFAULT_MAX_ENTRIES = 100;
17
+ const holder = globalThis;
18
+ /** The page's bootstrap buffer, if a bootstrap installed one and nothing took it yet. */
19
+ export function bootstrapBuffer() {
20
+ return holder[BOOTSTRAP_KEY];
21
+ }
22
+ /** Takes the buffer out of the page, its listeners removed: later calls return undefined. */
23
+ export function takeBootstrap() {
24
+ const b = holder[BOOTSTRAP_KEY];
25
+ holder[BOOTSTRAP_KEY] = undefined;
26
+ b?.stop();
27
+ return b;
28
+ }
29
+ const isElement = (v) => typeof v === "object" && v !== null && typeof v.tagName === "string";
30
+ /** installRumBootstrap with the event target and clock given. Internal: tests inject both. */
31
+ export function installRumBootstrapOn(target, opts, clock) {
32
+ if (opts.consent !== "granted" || holder[BOOTSTRAP_KEY] !== undefined)
33
+ return;
34
+ const max = opts.maxEntries ?? DEFAULT_MAX_ENTRIES;
35
+ const startedAt = clock.now();
36
+ const entries = [];
37
+ const at = (e) => {
38
+ const now = clock.now();
39
+ return Number.isFinite(e.timeStamp) && e.timeStamp > 0 && e.timeStamp <= now ? e.timeStamp : now;
40
+ };
41
+ let stopped = false;
42
+ const push = (entry) => {
43
+ if (clock.now() - startedAt >= BOOTSTRAP_MAX_MILLIS)
44
+ stop();
45
+ else if (entries.length < max)
46
+ entries.push(entry);
47
+ };
48
+ const onError = (e) => {
49
+ const ev = e;
50
+ if (isElement(ev.target))
51
+ return;
52
+ push({ kind: "error", at: at(e), error: ev.error, message: String(ev.message ?? "") });
53
+ };
54
+ const onRejection = (e) => {
55
+ push({ kind: "rejection", at: at(e), reason: e.reason });
56
+ };
57
+ const onCsp = (e) => {
58
+ const v = e;
59
+ push({
60
+ kind: "csp",
61
+ at: at(e),
62
+ directive: String(v.effectiveDirective ?? ""),
63
+ blocked: String(v.blockedURI ?? ""),
64
+ });
65
+ };
66
+ const onClick = (e) => {
67
+ if (isElement(e.target))
68
+ push({ kind: "click", at: at(e), target: e.target });
69
+ };
70
+ const listeners = [
71
+ ["error", onError, true],
72
+ ["unhandledrejection", onRejection, false],
73
+ ["securitypolicyviolation", onCsp, false],
74
+ ["click", onClick, true],
75
+ ];
76
+ function stop() {
77
+ if (stopped)
78
+ return;
79
+ stopped = true;
80
+ for (const [type, l, capture] of listeners)
81
+ target.removeEventListener(type, l, { capture });
82
+ }
83
+ for (const [type, l, capture] of listeners)
84
+ target.addEventListener(type, l, { capture });
85
+ clock.setTimeout(stop, BOOTSTRAP_MAX_MILLIS);
86
+ holder[BOOTSTRAP_KEY] = { entries, startedAt, stop };
87
+ }
88
+ /** afterLoad with the page given. Internal: tests inject it. */
89
+ export function afterLoadOn(host, load) {
90
+ if (host.document?.readyState === "complete" || host.window === undefined) {
91
+ host.idle(load);
92
+ return;
93
+ }
94
+ host.window.addEventListener("load", () => host.idle(load), { once: true });
95
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Replays the bootstrap buffer once the collectors started: each entry goes out on the bus as a
3
+ * bootstrap signal with its original time, and the collector of its kind records it (errors()
4
+ * the errors, actions() the clicks), so a kind whose collector the app did not install is dropped.
5
+ * Nothing is replayed unless consent is granted.
6
+ */
7
+ import type { RumRuntime } from "../contracts/runtime.ts";
8
+ import type { BootstrapBuffer } from "./buffer.ts";
9
+ /** Feeds the buffered entries to the collectors and returns how many. The buffer is stopped either way. */
10
+ export declare function replayBootstrap(rt: RumRuntime, buffer: BootstrapBuffer | undefined): number;
@@ -0,0 +1,11 @@
1
+ /** Feeds the buffered entries to the collectors and returns how many. The buffer is stopped either way. */
2
+ export function replayBootstrap(rt, buffer) {
3
+ if (buffer === undefined)
4
+ return 0;
5
+ buffer.stop();
6
+ if (!rt.gate.recording())
7
+ return 0;
8
+ for (const entry of buffer.entries)
9
+ rt.bus.publish({ type: "bootstrap", entry });
10
+ return buffer.entries.length;
11
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@libo11y/rum/bootstrap`: the first part of the two-part loader. It is tiny and imports nothing
3
+ * from OpenTelemetry or the rest of libo11y, so it can go in the app's entry chunk:
4
+ *
5
+ * import { afterLoad, installRumBootstrap } from "@libo11y/rum/bootstrap";
6
+ * installRumBootstrap({ consent: knownConsent });
7
+ * afterLoad(() => import("./rum.ts"));
8
+ *
9
+ * With consent "granted" it holds early errors, rejections, CSP violations and clicks in memory
10
+ * until setupRum replays them; with "pending", the default, it records nothing at all.
11
+ */
12
+ import { type RumBootstrapOptions } from "./bootstrap/buffer.ts";
13
+ export type { RumBootstrapOptions } from "./bootstrap/buffer.ts";
14
+ /** Starts buffering early errors, rejections, CSP violations and clicks in memory, for at most 30 s. */
15
+ export declare function installRumBootstrap(opts?: RumBootstrapOptions): void;
16
+ /** Runs load once the page's load event has fired (now, if it has), in an idle callback where available. */
17
+ export declare function afterLoad(load: () => void): void;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `@libo11y/rum/bootstrap`: the first part of the two-part loader. It is tiny and imports nothing
3
+ * from OpenTelemetry or the rest of libo11y, so it can go in the app's entry chunk:
4
+ *
5
+ * import { afterLoad, installRumBootstrap } from "@libo11y/rum/bootstrap";
6
+ * installRumBootstrap({ consent: knownConsent });
7
+ * afterLoad(() => import("./rum.ts"));
8
+ *
9
+ * With consent "granted" it holds early errors, rejections, CSP violations and clicks in memory
10
+ * until setupRum replays them; with "pending", the default, it records nothing at all.
11
+ */
12
+ import { afterLoadOn, installRumBootstrapOn } from "./bootstrap/buffer.js";
13
+ /** Starts buffering early errors, rejections, CSP violations and clicks in memory, for at most 30 s. */
14
+ export function installRumBootstrap(opts = {}) {
15
+ installRumBootstrapOn(globalThis, opts, {
16
+ now: () => performance.now(),
17
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
18
+ });
19
+ }
20
+ /** Runs load once the page's load event has fired (now, if it has), in an idle callback where available. */
21
+ export function afterLoad(load) {
22
+ const g = globalThis;
23
+ afterLoadOn({
24
+ ...(g.document === undefined ? {} : { document: g.document }),
25
+ ...(typeof g.addEventListener === "function" ? { window: g } : {}),
26
+ idle: (cb) => {
27
+ if (typeof g.requestIdleCallback === "function")
28
+ g.requestIdleCallback(cb, { timeout: 2000 });
29
+ else
30
+ setTimeout(cb, 0);
31
+ },
32
+ }, load);
33
+ }
package/dist/bus.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { RumBus } from "./contracts/runtime.ts";
2
+ /** A synchronous in-page bus. A throwing listener is reported through diag and the rest still run. */
3
+ export declare function createBus(): RumBus;
package/dist/bus.js ADDED
@@ -0,0 +1,21 @@
1
+ import { diag } from "@opentelemetry/api";
2
+ /** A synchronous in-page bus. A throwing listener is reported through diag and the rest still run. */
3
+ export function createBus() {
4
+ const listeners = new Set();
5
+ return {
6
+ publish(signal) {
7
+ for (const l of listeners) {
8
+ try {
9
+ l(signal);
10
+ }
11
+ catch (err) {
12
+ diag.warn(`o11y: rum: ${signal.type} listener threw`, err);
13
+ }
14
+ }
15
+ },
16
+ subscribe(listener) {
17
+ listeners.add(listener);
18
+ return () => listeners.delete(listener);
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,34 @@
1
+ import type { CollectorName, RumSettings } from "../contracts/runtime.ts";
2
+ /** One remote configuration document, flattened from the gateway's body. */
3
+ export interface RemoteConfigDocument {
4
+ /** The gateway's version of the document, also its ETag. */
5
+ readonly version: string;
6
+ /** false switches RUM off at once (the kill switch). */
7
+ readonly enabled?: boolean;
8
+ /** The share of new sessions kept, 0 to 1, clamped to the limits. */
9
+ readonly sessionSampleRate?: number;
10
+ /** false switches an installed collector off. true never switches on one the app did not install. */
11
+ readonly collectors?: Readonly<Partial<Record<CollectorName, boolean>>>;
12
+ /** Replay's remote settings, kept as an object for `@libo11y/rum-replay` to clamp. */
13
+ readonly replay?: Readonly<Record<string, unknown>>;
14
+ }
15
+ /** The range remote configuration may move a value within. */
16
+ export interface RemoteConfigLimits {
17
+ /** The range of sessionSampleRate: min and max between 0 and 1, min not above max. Default [rate, rate]: no change. */
18
+ readonly sessionSampleRate?: readonly [min: number, max: number];
19
+ }
20
+ /** Limits with every default applied. */
21
+ export interface ResolvedLimits {
22
+ readonly sessionSampleRate: readonly [min: number, max: number];
23
+ }
24
+ /**
25
+ * The limits for a code sample rate. The default range is [rate, rate]: no change. Throws O11yError
26
+ * INVALID_OPTION unless `0 <= min <= max <= 1`.
27
+ */
28
+ export declare function resolveLimits(rate: number, limits: RemoteConfigLimits | undefined): ResolvedLimits;
29
+ /** The document in a config endpoint body, or undefined when the body is not one. */
30
+ export declare function parseRemoteConfig(body: unknown): RemoteConfigDocument | undefined;
31
+ /** The settings code sets, with doc applied within limits. */
32
+ export declare function clampConfig<S extends RumSettings>(code: S, doc: RemoteConfigDocument | undefined, limits: ResolvedLimits): S & {
33
+ readonly enabledByRemote: boolean;
34
+ };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Remote configuration against the limits code sets. The gateway serves
3
+ * GET /_o11y/v1/config?service=<service.name> as {"version": "...", "config": {...}}; RUM owns
4
+ * the keys inside config: enabled, sessionSampleRate, collectors and replay, whose object
5
+ * `@libo11y/rum-replay` clamps itself. Unknown keys are ignored, so
6
+ * the gateway may add fields. Remote values can move sessionSampleRate only within the limits the
7
+ * code allows, can switch an installed collector off but never on one the app did not install, and
8
+ * enabled false is the kill switch.
9
+ */
10
+ import { O11yError } from "@libo11y/core";
11
+ const COLLECTORS = new Set([
12
+ "views",
13
+ "actions",
14
+ "errors",
15
+ "vitals",
16
+ "resources",
17
+ "long_animation_frames",
18
+ "replay",
19
+ ]);
20
+ function isObject(v) {
21
+ return typeof v === "object" && v !== null && !Array.isArray(v);
22
+ }
23
+ /**
24
+ * The limits for a code sample rate. The default range is [rate, rate]: no change. Throws O11yError
25
+ * INVALID_OPTION unless `0 <= min <= max <= 1`.
26
+ */
27
+ export function resolveLimits(rate, limits) {
28
+ const range = limits?.sessionSampleRate;
29
+ if (range === undefined)
30
+ return { sessionSampleRate: [rate, rate] };
31
+ const [min, max] = range;
32
+ if (!(min >= 0 && min <= max && max <= 1)) {
33
+ throw new O11yError("INVALID_OPTION", "rum.remoteConfig.limits.sessionSampleRate must satisfy 0 <= min <= max <= 1");
34
+ }
35
+ return { sessionSampleRate: [min, max] };
36
+ }
37
+ /** The document in a config endpoint body, or undefined when the body is not one. */
38
+ export function parseRemoteConfig(body) {
39
+ if (!isObject(body))
40
+ return undefined;
41
+ const { version, config } = body;
42
+ if (typeof version !== "string" || version === "" || !isObject(config))
43
+ return undefined;
44
+ const rate = config.sessionSampleRate;
45
+ const collectors = {};
46
+ let anyCollector = false;
47
+ if (isObject(config.collectors)) {
48
+ for (const [name, on] of Object.entries(config.collectors)) {
49
+ if (COLLECTORS.has(name) && typeof on === "boolean") {
50
+ collectors[name] = on;
51
+ anyCollector = true;
52
+ }
53
+ }
54
+ }
55
+ return {
56
+ version,
57
+ ...(typeof config.enabled === "boolean" ? { enabled: config.enabled } : {}),
58
+ ...(typeof rate === "number" && rate >= 0 && rate <= 1 ? { sessionSampleRate: rate } : {}),
59
+ ...(anyCollector ? { collectors } : {}),
60
+ ...(isObject(config.replay) ? { replay: config.replay } : {}),
61
+ };
62
+ }
63
+ /** The settings code sets, with doc applied within limits. */
64
+ export function clampConfig(code, doc, limits) {
65
+ if (doc === undefined)
66
+ return { ...code, enabledByRemote: true };
67
+ const [lo, hi] = limits.sessionSampleRate;
68
+ const rate = doc.sessionSampleRate === undefined
69
+ ? code.sessionSampleRate
70
+ : Math.min(Math.max(doc.sessionSampleRate, lo), hi);
71
+ const off = doc.collectors ?? {};
72
+ return {
73
+ ...code,
74
+ sessionSampleRate: rate,
75
+ enabled: new Set([...code.enabled].filter((n) => off[n] !== false)),
76
+ configVersion: doc.version,
77
+ enabledByRemote: doc.enabled !== false,
78
+ };
79
+ }
@@ -0,0 +1,103 @@
1
+ import type { RumSettings } from "../contracts/runtime.ts";
2
+ import { type RemoteConfigDocument, type RemoteConfigLimits } from "./clamp.ts";
3
+ export declare const CONFIG_STORAGE_KEY = "libo11y.rum.config";
4
+ /** The pinned documents, pinned longest ago first. */
5
+ export declare const CONFIG_PINNED_STORAGE_KEY = "libo11y.rum.config.pinned";
6
+ /** A config request that has not answered by then counts as failed. */
7
+ export declare const REQUEST_TIMEOUT_MILLIS = 10000;
8
+ /** The default refresh interval while the page is visible. */
9
+ export declare const DEFAULT_REFRESH_MILLIS = 300000;
10
+ /** The most documents pin keeps. Past it the one pinned longest ago is dropped first. */
11
+ export declare const PINNED_MAX = 8;
12
+ /** The storage remote configuration caches in. */
13
+ export type RemoteConfigStorage = Pick<Storage, "getItem" | "setItem" | "removeItem"> & {
14
+ /**
15
+ * Sets key to fn of the value storage holds now, serialized with every other context's updates,
16
+ * where storage is shared by contexts that each hold a copy in memory. Optional: without it, pin
17
+ * reads and sets the value.
18
+ */
19
+ updateItem?(key: string, fn: (current: string | null) => string): void;
20
+ };
21
+ /** The timers the client runs on. */
22
+ export interface RemoteConfigTimers {
23
+ setTimeout(cb: () => void, ms: number): unknown;
24
+ clearTimeout(handle: unknown): void;
25
+ }
26
+ export interface RemoteConfigClient {
27
+ /** The newest document known: from the cache of an earlier page, then from each fetch. */
28
+ current(): RemoteConfigDocument | undefined;
29
+ /**
30
+ * The newest document, the one before it or a pinned document whose version is version: the
31
+ * document a session started under. Undefined for undefined (a session that started without one)
32
+ * and for a version the client no longer has, never a document of another version.
33
+ */
34
+ find(version: string | undefined): RemoteConfigDocument | undefined;
35
+ /**
36
+ * Keeps doc in the cache while newer documents arrive, so a reload or another tab resuming the
37
+ * session that runs under it still finds it. At most PINNED_MAX documents are kept. clear removes
38
+ * them. Optional, for a client written before it.
39
+ */
40
+ pin?(doc: RemoteConfigDocument): void;
41
+ /** Fetches now. Resolves true when the newest document changed. Never rejects. */
42
+ refresh(): Promise<boolean>;
43
+ /**
44
+ * Refreshes now and every refreshMillis while visible, calling onChange when the newest document
45
+ * changed and onRefresh after any other refresh, as a 304, when another tab may have cached a
46
+ * document since.
47
+ */
48
+ start(onChange: (doc: RemoteConfigDocument | undefined) => void, onRefresh?: () => void): () => void;
49
+ /** Removes the cache, and keeps a response in flight from being cached. */
50
+ clear(): void;
51
+ }
52
+ export interface RemoteConfigClientOptions {
53
+ /** The full config URL, service and client_token included. */
54
+ readonly url: string;
55
+ readonly refreshMillis: number;
56
+ readonly fetch: typeof fetch;
57
+ readonly storage?: RemoteConfigStorage | undefined;
58
+ readonly timers: RemoteConfigTimers;
59
+ readonly visible: () => boolean;
60
+ }
61
+ export declare function createRemoteConfig(o: RemoteConfigClientOptions): RemoteConfigClient;
62
+ /** Options for remoteConfig. */
63
+ export interface RemoteConfigOptions {
64
+ /**
65
+ * The config URL. Default: the export endpoint's /v1/config, such as /_o11y/v1/config next to
66
+ * /_o11y/v1/traces. setupRum adds the service and client_token query parameters.
67
+ */
68
+ readonly url?: string;
69
+ /** How often to look for a new version while the page is visible. Default 300000. */
70
+ readonly refreshMillis?: number;
71
+ /** The range remote configuration may move a value within. Default: no change. */
72
+ readonly limits?: RemoteConfigLimits;
73
+ }
74
+ /** What setupRum hands remoteConfig once consent is granted. */
75
+ export interface RemoteConfigOpenOptions {
76
+ /** The full config URL, service and client_token included. */
77
+ readonly url: string;
78
+ readonly fetch: typeof fetch;
79
+ readonly storage?: RemoteConfigStorage | undefined;
80
+ readonly timers: RemoteConfigTimers;
81
+ readonly visible: () => boolean;
82
+ }
83
+ /** An open remote configuration: the client, and the clamp to the limits code set. */
84
+ export interface RemoteConfigConnection extends RemoteConfigClient {
85
+ /** code with doc applied within the limits. */
86
+ apply<S extends RumSettings>(code: S, doc: RemoteConfigDocument | undefined): S & {
87
+ readonly enabledByRemote: boolean;
88
+ };
89
+ }
90
+ /** Remote configuration from the RUM gateway, for RumOptions.remoteConfig. */
91
+ export interface RemoteConfig {
92
+ /** RemoteConfigOptions.url. */
93
+ readonly url?: string;
94
+ /** Called by setupRum once consent is granted. */
95
+ open(o: RemoteConfigOpenOptions): RemoteConfigConnection;
96
+ }
97
+ /**
98
+ * Remote configuration from the RUM gateway (GET /_o11y/v1/config). A fetched document applies to
99
+ * the next session, except that enabled false switches RUM off at once and enabled true switches it
100
+ * back on. Remote values never go beyond the limits given here, and never switch on a collector the
101
+ * app did not install. Throws O11yError INVALID_OPTION for invalid limits or refreshMillis.
102
+ */
103
+ export declare function remoteConfig(opts?: RemoteConfigOptions): RemoteConfig;