@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,30 @@
1
+ /**
2
+ * The view summary accumulator (spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
3
+ * holds the shared vectors.
4
+ *
5
+ * Rules. A tracked view emits on close, and on flush when it has never emitted (seq 0) or has a
6
+ * nonzero count, unsent visible time or an unsent vital. Counts and time on view are deltas since
7
+ * the view's previous summary; a zero count is omitted. A vital is accepted once per view and name
8
+ * and is sent in the next summary of that view. A closed view stays tracked, for late vitals, until
9
+ * ten newer views closed after it, and while it is pinned (vitals() pins the load view until it has
10
+ * committed its held vitals).
11
+ */
12
+ import { type RUMPlatform } from "@libo11y/spec";
13
+ import type { SummaryAccumulator } from "../contracts/summary.ts";
14
+ export interface SummaryOptions {
15
+ readonly platform: RUMPlatform;
16
+ /** Emits one o11y.rum.view.summary record with these attributes. */
17
+ readonly emit: (attrs: Record<string, string | number>) => void;
18
+ /** performance.now(). */
19
+ readonly now: () => number;
20
+ /** Whether the page is visible now. */
21
+ readonly visible: () => boolean;
22
+ /** Optional attributes added to every summary, read as it is emitted: o11y.rum.connection.effective. */
23
+ readonly context?: () => Readonly<Record<string, string | number>>;
24
+ /**
25
+ * Optional attributes read once, when a view opens, and added to every summary of that view, late
26
+ * vitals included: o11y.rum.config.version of the session the view opened in.
27
+ */
28
+ readonly origin?: () => Readonly<Record<string, string | number>>;
29
+ }
30
+ export declare function createSummaryAccumulator(opts: SummaryOptions): SummaryAccumulator;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The view summary accumulator (spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
3
+ * holds the shared vectors.
4
+ *
5
+ * Rules. A tracked view emits on close, and on flush when it has never emitted (seq 0) or has a
6
+ * nonzero count, unsent visible time or an unsent vital. Counts and time on view are deltas since
7
+ * the view's previous summary; a zero count is omitted. A vital is accepted once per view and name
8
+ * and is sent in the next summary of that view. A closed view stays tracked, for late vitals, until
9
+ * ten newer views closed after it, and while it is pinned (vitals() pins the load view until it has
10
+ * committed its held vitals).
11
+ */
12
+ import { ATTR_RUM_PLATFORM, ATTR_RUM_SUMMARY_SEQ, ATTR_RUM_SUMMARY_TIME_ON_VIEW, ATTR_RUM_VIEW_ID, ATTR_RUM_VIEW_KIND, ATTR_RUM_VIEW_NAME, } from "@libo11y/spec";
13
+ import { ATTR_SESSION_ID, summaryCountKey, summaryVitalKey } from "../attrs.js";
14
+ const MAX_CLOSED = 10;
15
+ export function createSummaryAccumulator(opts) {
16
+ const tracked = new Map();
17
+ let current;
18
+ const accrue = (t) => {
19
+ if (t.resumedAt === undefined)
20
+ return;
21
+ const n = opts.now();
22
+ t.visibleMillis += Math.max(0, n - t.resumedAt);
23
+ t.resumedAt = n;
24
+ };
25
+ const pending = (t) => t.seq === 0 || t.counts.size > 0 || t.vitals.size > 0 || t.visibleMillis > 0;
26
+ const send = (t) => {
27
+ accrue(t);
28
+ if (!pending(t))
29
+ return;
30
+ const attrs = {
31
+ ...opts.context?.(),
32
+ ...t.origin,
33
+ [ATTR_RUM_PLATFORM]: opts.platform,
34
+ [ATTR_RUM_VIEW_ID]: t.view.id,
35
+ [ATTR_RUM_VIEW_NAME]: t.view.name,
36
+ [ATTR_RUM_VIEW_KIND]: t.view.kind,
37
+ [ATTR_SESSION_ID]: t.view.sessionId,
38
+ [ATTR_RUM_SUMMARY_SEQ]: t.seq,
39
+ [ATTR_RUM_SUMMARY_TIME_ON_VIEW]: t.visibleMillis / 1000,
40
+ };
41
+ for (const [k, n] of t.counts)
42
+ if (n !== 0)
43
+ attrs[summaryCountKey(k)] = n;
44
+ for (const [v, x] of t.vitals) {
45
+ attrs[summaryVitalKey(v)] = x;
46
+ t.sent.add(v);
47
+ }
48
+ t.seq += 1;
49
+ t.counts = new Map();
50
+ t.vitals = new Map();
51
+ t.visibleMillis = 0;
52
+ opts.emit(attrs);
53
+ };
54
+ const prune = () => {
55
+ const closed = [...tracked.values()].filter((t) => !t.open && !t.pinned);
56
+ for (const t of closed.slice(0, Math.max(0, closed.length - MAX_CLOSED)))
57
+ tracked.delete(t.view.id);
58
+ };
59
+ return {
60
+ open(view) {
61
+ const t = {
62
+ view,
63
+ seq: 0,
64
+ counts: new Map(),
65
+ vitals: new Map(),
66
+ sent: new Set(),
67
+ visibleMillis: 0,
68
+ resumedAt: opts.visible() ? opts.now() : undefined,
69
+ open: true,
70
+ pinned: false,
71
+ origin: opts.origin?.(),
72
+ };
73
+ tracked.set(view.id, t);
74
+ current = t;
75
+ },
76
+ close(viewId) {
77
+ const t = tracked.get(viewId);
78
+ if (t === undefined || !t.open)
79
+ return;
80
+ send(t);
81
+ t.open = false;
82
+ t.resumedAt = undefined;
83
+ if (current === t)
84
+ current = undefined;
85
+ prune();
86
+ },
87
+ rename(viewId, name) {
88
+ const t = tracked.get(viewId);
89
+ if (t !== undefined)
90
+ t.view = { ...t.view, name };
91
+ },
92
+ count(key, n = 1) {
93
+ if (current === undefined)
94
+ return;
95
+ current.counts.set(key, (current.counts.get(key) ?? 0) + n);
96
+ },
97
+ vital(viewId, name, value) {
98
+ const t = tracked.get(viewId);
99
+ if (t === undefined || t.sent.has(name) || t.vitals.has(name))
100
+ return;
101
+ t.vitals.set(name, value);
102
+ },
103
+ pin(viewId, pinned) {
104
+ const t = tracked.get(viewId);
105
+ if (t !== undefined)
106
+ t.pinned = pinned;
107
+ },
108
+ visibility(visible) {
109
+ if (current === undefined)
110
+ return;
111
+ if (visible)
112
+ current.resumedAt ??= opts.now();
113
+ else {
114
+ accrue(current);
115
+ current.resumedAt = undefined;
116
+ }
117
+ },
118
+ flush() {
119
+ for (const t of tracked.values())
120
+ send(t);
121
+ prune();
122
+ },
123
+ reset() {
124
+ tracked.clear();
125
+ current = undefined;
126
+ },
127
+ };
128
+ }
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/rum` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.6.0";
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/rum` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.6.0";
@@ -0,0 +1,40 @@
1
+ import type { RumCollector } from "../contracts/runtime.ts";
2
+ import { type HistoryHost } from "./history.ts";
3
+ import { type PaintHost } from "./paint.ts";
4
+ /** A view span ends this long after it started at the latest. */
5
+ export declare const VIEW_SPAN_CAP_MILLIS = 10000;
6
+ /** In history mode, a soft view rendered once the DOM was quiet this long. */
7
+ export declare const RENDER_IDLE_MILLIS = 100;
8
+ /** How long a load view span due to end waits for app_load before it starts as a root. */
9
+ export declare const APP_LOAD_WAIT_MILLIS = 1000;
10
+ export interface ViewsOptions {
11
+ /** Start a soft view whenever the URL path changes. Default true. Router adapters pass false and call rum.startView. */
12
+ readonly history?: boolean;
13
+ }
14
+ /** The part of MutationObserver the collectors use. */
15
+ export interface MutationObserverLike {
16
+ observe(target: object, options: MutationObserverInit): void;
17
+ disconnect(): void;
18
+ }
19
+ export type MutationObserverCtor = new (cb: () => void) => MutationObserverLike;
20
+ /** What views() needs from the page. Internal: tests inject a fake. */
21
+ export interface ViewsEnv {
22
+ /** performance.timeOrigin. */
23
+ readonly timeOrigin: number;
24
+ readonly paint: PaintHost;
25
+ readonly history?: HistoryHost;
26
+ readonly MutationObserver?: MutationObserverCtor;
27
+ /** What mutations are observed on: document.documentElement. */
28
+ readonly root?: object;
29
+ setTimeout(cb: () => void, ms: number): unknown;
30
+ clearTimeout(handle: unknown): void;
31
+ /** The navigation entry's loadEventEnd, 0 until the load event ended. */
32
+ navigationLoadEnd(): number;
33
+ /** Calls cb once the load event ended. Returns its cancellation. */
34
+ whenLoaded(cb: () => void): () => void;
35
+ }
36
+ /** The DOM mutations that count as rendering. */
37
+ export declare const MUTATIONS: MutationObserverInit;
38
+ export declare function viewsWith(opts: ViewsOptions, env: ViewsEnv): RumCollector;
39
+ /** The views collector: view spans for every view, and soft navigations in history mode. */
40
+ export declare function views(opts?: ViewsOptions): RumCollector;
@@ -0,0 +1,286 @@
1
+ /**
2
+ * views(): view spans and soft navigations.
3
+ *
4
+ * Every view the tracker starts gets a view span named "view <o11y.rum.view.name>" with
5
+ * o11y.rum.span.shape view, the platform, the view's name, ID and kind, and its session.id. It
6
+ * starts at the view's startTime. A soft or bfcache_restore view span is a root, linked to the
7
+ * action that caused it when there is one. The load view's span (initial or prerender on the web,
8
+ * the first screen on React Native) is a child of app_load (web's documentLoad span). Its creation waits for the span processor to report
9
+ * app_load, and once the view span is due to end it waits at most APP_LOAD_WAIT_MILLIS more, then
10
+ * starts as a root. The tracker learns the span's context (attachSpan), so actions link to it.
11
+ *
12
+ * A view span ends at the first paint after its view rendered: rum.viewRendered() (router
13
+ * adapters) or, in history mode, by itself. In history mode a soft view rendered once no DOM
14
+ * mutation happened for RENDER_IDLE_MILLIS, a bfcache_restore view at once, and the initial view
15
+ * at loadEventEnd when the page has loaded already, else at the first paint after the load event.
16
+ * Every view span ends VIEW_SPAN_CAP_MILLIS after it started at the latest, and at once when its
17
+ * view ends first. In history mode, every path change through pushState, replaceState or popstate
18
+ * starts a soft view named by settings().viewName, caused by the open action. With history off,
19
+ * nothing renders by itself and router adapters call rum.startView and rum.viewRendered. A runtime
20
+ * scope with fixedView (a content script) follows no URL change, and its viewAttributes go on every
21
+ * view span. Stop
22
+ * ends every open view span and removes every listener, observer and timer.
23
+ */
24
+ import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, ATTR_RUM_VIEW_KIND, ATTR_RUM_VIEW_NAME, RUM_SPAN_SHAPE_VALUE_VIEW, } from "@libo11y/spec";
25
+ import { ROOT_CONTEXT, trace } from "@opentelemetry/api";
26
+ import { ATTR_SESSION_ID } from "../attrs.js";
27
+ import { watchHistory } from "./history.js";
28
+ import { afterNextPaint } from "./paint.js";
29
+ /** A view span ends this long after it started at the latest. */
30
+ export const VIEW_SPAN_CAP_MILLIS = 10_000;
31
+ /** In history mode, a soft view rendered once the DOM was quiet this long. */
32
+ export const RENDER_IDLE_MILLIS = 100;
33
+ /** How long a load view span due to end waits for app_load before it starts as a root. */
34
+ export const APP_LOAD_WAIT_MILLIS = 1000;
35
+ const APP_LOAD_POLL_MILLIS = 100;
36
+ /** The DOM mutations that count as rendering. */
37
+ export const MUTATIONS = {
38
+ subtree: true,
39
+ childList: true,
40
+ attributes: true,
41
+ characterData: true,
42
+ };
43
+ export function viewsWith(opts, env) {
44
+ const followHistory = opts.history !== false;
45
+ return {
46
+ name: "views",
47
+ start(rt) {
48
+ // A fixed view scope (a content script) keeps its one view whatever the host page's URL does.
49
+ const history = followHistory && rt.scope?.fixedView !== true;
50
+ let stopped = false;
51
+ const open = new Map();
52
+ const timer = (o, cb, ms) => {
53
+ const h = env.setTimeout(() => {
54
+ o.timers.delete(h);
55
+ cb();
56
+ }, ms);
57
+ o.timers.add(h);
58
+ return h;
59
+ };
60
+ const quiet = (o) => {
61
+ for (const h of o.timers)
62
+ env.clearTimeout(h);
63
+ o.timers.clear();
64
+ o.observer?.disconnect();
65
+ o.observer = undefined;
66
+ o.offLoad?.();
67
+ o.offLoad = undefined;
68
+ };
69
+ // A fixed view (a content script) has no app_load: the host page's load is not its own.
70
+ const waitsForAppLoad = (o) => o.load && rt.views.appLoad() === undefined && rt.scope?.fixedView !== true;
71
+ const create = (o) => {
72
+ if (o.span !== undefined)
73
+ return o.span;
74
+ const v = o.view;
75
+ const appLoad = o.load ? rt.views.appLoad() : undefined;
76
+ const span = rt.tracer.startSpan(`view ${v.name}`, {
77
+ startTime: env.timeOrigin + v.startTime,
78
+ attributes: {
79
+ ...rt.scope?.viewAttributes,
80
+ [ATTR_RUM_SPAN_SHAPE]: RUM_SPAN_SHAPE_VALUE_VIEW,
81
+ [ATTR_RUM_PLATFORM]: rt.platform,
82
+ [ATTR_RUM_VIEW_NAME]: v.name,
83
+ [ATTR_RUM_VIEW_ID]: v.id,
84
+ [ATTR_RUM_VIEW_KIND]: v.kind,
85
+ [ATTR_SESSION_ID]: v.sessionId,
86
+ },
87
+ ...(o.cause === undefined ? {} : { links: [{ context: o.cause }] }),
88
+ }, appLoad === undefined ? ROOT_CONTEXT : trace.setSpanContext(ROOT_CONTEXT, appLoad));
89
+ o.span = span;
90
+ rt.views.attachSpan(v.id, span.spanContext());
91
+ return span;
92
+ };
93
+ const close = (o) => {
94
+ quiet(o);
95
+ open.delete(o.view.id);
96
+ const capAt = o.view.startTime + VIEW_SPAN_CAP_MILLIS;
97
+ create(o).end(env.timeOrigin + Math.min(o.endAt ?? rt.now(), capAt));
98
+ };
99
+ const finish = (o, at) => {
100
+ if (o.endAt !== undefined)
101
+ return;
102
+ o.endAt = Math.min(at, o.view.startTime + VIEW_SPAN_CAP_MILLIS);
103
+ if (o.span !== undefined || !waitsForAppLoad(o)) {
104
+ close(o);
105
+ return;
106
+ }
107
+ // The load view is due but app_load is not known yet: wait a little more for it.
108
+ o.observer?.disconnect();
109
+ o.observer = undefined;
110
+ o.waitUntil = rt.now() + APP_LOAD_WAIT_MILLIS;
111
+ };
112
+ const poll = (o) => {
113
+ timer(o, () => {
114
+ if (rt.views.appLoad() !== undefined) {
115
+ create(o);
116
+ if (o.endAt !== undefined)
117
+ close(o);
118
+ }
119
+ else if (o.waitUntil !== undefined && rt.now() >= o.waitUntil)
120
+ close(o);
121
+ else
122
+ poll(o);
123
+ }, APP_LOAD_POLL_MILLIS);
124
+ };
125
+ const paintThen = (o) => {
126
+ if (o.rendered || o.endAt !== undefined)
127
+ return;
128
+ o.rendered = true;
129
+ o.observer?.disconnect();
130
+ o.observer = undefined;
131
+ afterNextPaint(env.paint, rt.now, (at) => {
132
+ if (!stopped && open.get(o.view.id) === o)
133
+ finish(o, at);
134
+ });
135
+ };
136
+ const detectRender = (o) => {
137
+ let idle;
138
+ const arm = () => {
139
+ if (idle !== undefined) {
140
+ env.clearTimeout(idle);
141
+ o.timers.delete(idle);
142
+ }
143
+ idle = timer(o, () => paintThen(o), RENDER_IDLE_MILLIS);
144
+ };
145
+ if (env.MutationObserver !== undefined && env.root !== undefined) {
146
+ o.observer = new env.MutationObserver(arm);
147
+ o.observer.observe(env.root, MUTATIONS);
148
+ }
149
+ arm();
150
+ };
151
+ const start = (view, cause, atSetup, onScreen = false) => {
152
+ const o = {
153
+ view,
154
+ load: view.kind !== "bfcache_restore" && rt.views.loadView()?.id === view.id,
155
+ ...(cause === undefined ? {} : { cause }),
156
+ rendered: false,
157
+ timers: new Set(),
158
+ observer: undefined,
159
+ offLoad: undefined,
160
+ };
161
+ open.set(view.id, o);
162
+ if (waitsForAppLoad(o))
163
+ poll(o);
164
+ else
165
+ create(o);
166
+ const capAt = view.startTime + VIEW_SPAN_CAP_MILLIS;
167
+ timer(o, () => finish(o, Math.min(rt.now(), capAt)), Math.max(0, capAt - rt.now()));
168
+ // A restored page, or a view a session change started, is on screen already.
169
+ if (onScreen || view.kind === "bfcache_restore")
170
+ paintThen(o);
171
+ else if (!history)
172
+ return;
173
+ else if (view.kind === "soft")
174
+ detectRender(o);
175
+ else if (atSetup) {
176
+ const loadEnd = env.navigationLoadEnd();
177
+ if (loadEnd > 0)
178
+ finish(o, Math.max(view.startTime, loadEnd));
179
+ else
180
+ o.offLoad = env.whenLoaded(() => paintThen(o));
181
+ }
182
+ };
183
+ const offViews = rt.views.subscribe((e) => {
184
+ if (stopped)
185
+ return;
186
+ const o = open.get(e.view.id);
187
+ if (e.type === "start")
188
+ start(e.view, e.cause, false, e.rendered === true);
189
+ else if (o === undefined)
190
+ return;
191
+ else if (e.type === "rename") {
192
+ o.view = e.view;
193
+ o.span?.updateName(`view ${e.view.name}`);
194
+ o.span?.setAttribute(ATTR_RUM_VIEW_NAME, e.view.name);
195
+ }
196
+ else if (e.type === "rendered") {
197
+ // A render reported before the view started (before consent) means the view was on
198
+ // screen when it started; one reported during it ended getting into it.
199
+ if (e.at !== undefined && e.at >= o.view.startTime && !o.rendered && o.endAt === undefined) {
200
+ o.rendered = true;
201
+ finish(o, Math.min(e.at, rt.now()));
202
+ }
203
+ else
204
+ paintThen(o);
205
+ }
206
+ else if (e.type === "end")
207
+ finish(o, rt.now());
208
+ });
209
+ const current = rt.views.current();
210
+ if (current !== undefined)
211
+ start(current, undefined, true);
212
+ const unwatch = history && env.history !== undefined
213
+ ? watchHistory(env.history, (url) => {
214
+ if (stopped)
215
+ return;
216
+ const action = rt.activeAction();
217
+ rt.views.start({
218
+ kind: "soft",
219
+ name: rt.settings().viewName(url),
220
+ ...(action?.isRecording() === true ? { cause: action.spanContext() } : {}),
221
+ });
222
+ })
223
+ : undefined;
224
+ return () => {
225
+ stopped = true;
226
+ offViews();
227
+ unwatch?.();
228
+ for (const o of [...open.values()])
229
+ close(o);
230
+ };
231
+ },
232
+ };
233
+ }
234
+ function browserViewsEnv() {
235
+ const g = globalThis;
236
+ const doc = g.document;
237
+ const loadEnd = () => {
238
+ const nav = performance.getEntriesByType?.("navigation")[0];
239
+ return nav?.loadEventEnd ?? 0;
240
+ };
241
+ return {
242
+ timeOrigin: performance.timeOrigin,
243
+ paint: {
244
+ ...(typeof g.requestAnimationFrame === "function"
245
+ ? { requestAnimationFrame: (cb) => g.requestAnimationFrame(cb) }
246
+ : {}),
247
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
248
+ hidden: () => doc?.visibilityState === "hidden",
249
+ },
250
+ ...(g.history === undefined || g.location === undefined || typeof g.addEventListener !== "function"
251
+ ? {}
252
+ : {
253
+ history: {
254
+ history: g.history,
255
+ location: g.location,
256
+ addEventListener: (t, l) => g.addEventListener(t, l),
257
+ removeEventListener: (t, l) => g.removeEventListener(t, l),
258
+ },
259
+ }),
260
+ ...(typeof g.MutationObserver === "function" ? { MutationObserver: g.MutationObserver } : {}),
261
+ ...(doc?.documentElement == null ? {} : { root: doc.documentElement }),
262
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
263
+ clearTimeout: (h) => clearTimeout(h),
264
+ navigationLoadEnd: loadEnd,
265
+ whenLoaded(cb) {
266
+ let timer;
267
+ // loadEventEnd is set once the load handlers ran, so wait a task after the event.
268
+ const onLoad = () => {
269
+ timer = setTimeout(cb, 0);
270
+ };
271
+ if (doc?.readyState === "complete")
272
+ onLoad();
273
+ else
274
+ g.addEventListener?.("load", onLoad, { once: true });
275
+ return () => {
276
+ g.removeEventListener?.("load", onLoad);
277
+ if (timer !== undefined)
278
+ clearTimeout(timer);
279
+ };
280
+ },
281
+ };
282
+ }
283
+ /** The views collector: view spans for every view, and soft navigations in history mode. */
284
+ export function views(opts = {}) {
285
+ return { name: "views", start: (rt) => viewsWith(opts, browserViewsEnv()).start(rt) };
286
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Soft navigation detection without a router adapter: pushState, replaceState and popstate, by
3
+ * path. A change of only the query or the fragment is not a navigation.
4
+ */
5
+ export interface HistoryHost {
6
+ readonly history: Pick<History, "pushState" | "replaceState">;
7
+ readonly location: {
8
+ readonly href: string;
9
+ };
10
+ addEventListener(type: "popstate", l: () => void): void;
11
+ removeEventListener(type: "popstate", l: () => void): void;
12
+ }
13
+ /**
14
+ * Calls onChange with the new URL whenever the path changes. Returns the uninstall, which restores
15
+ * the original methods only when nothing patched over RUM's; otherwise RUM's wrapper stays in the
16
+ * chain and reports nothing.
17
+ */
18
+ export declare function watchHistory(host: HistoryHost, onChange: (url: URL) => void): () => void;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Soft navigation detection without a router adapter: pushState, replaceState and popstate, by
3
+ * path. A change of only the query or the fragment is not a navigation.
4
+ */
5
+ /**
6
+ * Calls onChange with the new URL whenever the path changes. Returns the uninstall, which restores
7
+ * the original methods only when nothing patched over RUM's; otherwise RUM's wrapper stays in the
8
+ * chain and reports nothing.
9
+ */
10
+ export function watchHistory(host, onChange) {
11
+ let installed = true;
12
+ let path = new URL(host.location.href).pathname;
13
+ const check = () => {
14
+ if (!installed)
15
+ return;
16
+ const url = new URL(host.location.href);
17
+ if (url.pathname === path)
18
+ return;
19
+ path = url.pathname;
20
+ onChange(url);
21
+ };
22
+ const h = host.history;
23
+ const wrap = (original) => function (...args) {
24
+ original.apply(this, args);
25
+ check();
26
+ };
27
+ const push = h.pushState;
28
+ const replace = h.replaceState;
29
+ const pushWrapper = wrap(push);
30
+ const replaceWrapper = wrap(replace);
31
+ h.pushState = pushWrapper;
32
+ h.replaceState = replaceWrapper;
33
+ host.addEventListener("popstate", check);
34
+ return () => {
35
+ installed = false;
36
+ if (h.pushState === pushWrapper)
37
+ h.pushState = push;
38
+ if (h.replaceState === replaceWrapper)
39
+ h.replaceState = replace;
40
+ host.removeEventListener("popstate", check);
41
+ };
42
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The view name when no router adapter names the view: the path, with every
3
+ * segment that holds a digit or is longer than 24 characters replaced by $id. Query and fragment
4
+ * are dropped, so a raw URL never becomes a view name.
5
+ */
6
+ export declare function defaultViewName(url: URL): string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The view name when no router adapter names the view: the path, with every
3
+ * segment that holds a digit or is longer than 24 characters replaced by $id. Query and fragment
4
+ * are dropped, so a raw URL never becomes a view name.
5
+ */
6
+ export function defaultViewName(url) {
7
+ const path = url.pathname
8
+ .split("/")
9
+ .map((s) => (s !== "" && (/\d/.test(s) || s.length > 24) ? "$id" : s))
10
+ .join("/");
11
+ return path === "" ? "/" : path;
12
+ }
@@ -0,0 +1,12 @@
1
+ /** The first paint after now, for view spans that end when the routed view is on screen. */
2
+ export interface PaintHost {
3
+ requestAnimationFrame?(cb: () => void): number;
4
+ setTimeout(cb: () => void, ms: number): unknown;
5
+ readonly hidden: () => boolean;
6
+ }
7
+ /**
8
+ * Calls cb with now() at the first paint after now: rendering follows the next animation frame,
9
+ * so a task queued in that frame runs after the paint. A hidden page renders no frames, so it
10
+ * waits for a task only.
11
+ */
12
+ export declare function afterNextPaint(host: PaintHost, now: () => number, cb: (at: number) => void): void;
@@ -0,0 +1,15 @@
1
+ /** The first paint after now, for view spans that end when the routed view is on screen. */
2
+ /**
3
+ * Calls cb with now() at the first paint after now: rendering follows the next animation frame,
4
+ * so a task queued in that frame runs after the paint. A hidden page renders no frames, so it
5
+ * waits for a task only.
6
+ */
7
+ export function afterNextPaint(host, now, cb) {
8
+ const task = () => {
9
+ host.setTimeout(() => cb(now()), 0);
10
+ };
11
+ if (host.hidden() || host.requestAnimationFrame === undefined)
12
+ task();
13
+ else
14
+ host.requestAnimationFrame(task);
15
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The view tracker: the initial (or prerender) view at begin, a bfcache_restore view on a
3
+ * persisted pageshow, a soft view of the same name when the session changes, and
4
+ * the soft views views() and the router adapters start. A platform whose views are all of one
5
+ * kind, as React Native's screens, passes viewKind: the first begin's view is then the load view and
6
+ * every view has that kind. Every view opens in the summary accumulator and closes when it ends.
7
+ * views() records the view spans and attaches their contexts.
8
+ */
9
+ import type { RUMViewKind } from "@libo11y/spec";
10
+ import type { SessionManager } from "../contracts/session.ts";
11
+ import type { SummaryAccumulator } from "../contracts/summary.ts";
12
+ import type { ViewTracker } from "../contracts/views.ts";
13
+ export interface ViewTrackerOptions {
14
+ readonly session: Pick<SessionManager, "current" | "subscribe">;
15
+ readonly summary: SummaryAccumulator;
16
+ readonly viewName: (url: URL) => string;
17
+ /** The page URL now. */
18
+ readonly location: () => string;
19
+ /** performance.now(). */
20
+ readonly now: () => number;
21
+ /** document.prerendering, or a navigation entry with `activationStart > 0`. */
22
+ readonly prerendered: () => boolean;
23
+ /** Where pageshow fires, for back/forward-cache restores. */
24
+ readonly window?: EventTarget | undefined;
25
+ /** When the initial view starts, performance.now(). Default 0, navigation start; a content script's view starts when RUM begins. */
26
+ readonly initialStart?: (() => number) | undefined;
27
+ /**
28
+ * The kind of every view the tracker starts itself (the load view, the view of a session change
29
+ * and of a later begin), for a platform with one kind of view, such as React Native's screen.
30
+ * Default the web's: initial or prerender, then soft.
31
+ */
32
+ readonly viewKind?: RUMViewKind | undefined;
33
+ readonly randomId?: () => string;
34
+ }
35
+ export declare function createViewTracker(opts: ViewTrackerOptions): ViewTracker & {
36
+ close(): void;
37
+ };