@libo11y/rum-react-native 0.0.0-stage → 0.7.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.
@@ -0,0 +1,368 @@
1
+ import { ATTR_RUM_APP_UPDATE_ID, ATTR_RUM_ERROR_BINARY_IMAGES, ATTR_RUM_ERROR_HANG_DURATION, ATTR_RUM_ERROR_SIGNAL, ATTR_RUM_ERROR_SOURCE, ATTR_RUM_VIEW_ID, EVENT_RUM_ERROR, } from "@libo11y/spec";
2
+ import { diag, ROOT_CONTEXT } from "@opentelemetry/api";
3
+ import { nativeStack } from "./native-stack.js";
4
+ export { nativeStack } from "./native-stack.js";
5
+ /**
6
+ * When the collector reads the module's reports after it starts, in milliseconds. It then reads
7
+ * them again every last of these.
8
+ */
9
+ export const POLL_MILLIS = [0, 15_000, 60_000];
10
+ /** How far after a report's payload end its process may have started (clocks differ a little). */
11
+ const SLACK_MILLIS = 60_000;
12
+ /** Mach exception names by type (mach/exception_types.h). */
13
+ const MACH_EXCEPTIONS = new Map([
14
+ [1, "EXC_BAD_ACCESS"],
15
+ [2, "EXC_BAD_INSTRUCTION"],
16
+ [3, "EXC_ARITHMETIC"],
17
+ [4, "EXC_EMULATION"],
18
+ [5, "EXC_SOFTWARE"],
19
+ [6, "EXC_BREAKPOINT"],
20
+ [7, "EXC_SYSCALL"],
21
+ [8, "EXC_MACH_SYSCALL"],
22
+ [9, "EXC_RPC_ALERT"],
23
+ [10, "EXC_CRASH"],
24
+ [11, "EXC_RESOURCE"],
25
+ [12, "EXC_GUARD"],
26
+ [13, "EXC_CORPSE_NOTIFY"],
27
+ ]);
28
+ /** POSIX signal names by number on Darwin (sys/signal.h). */
29
+ const SIGNALS = new Map([
30
+ [1, "SIGHUP"],
31
+ [2, "SIGINT"],
32
+ [3, "SIGQUIT"],
33
+ [4, "SIGILL"],
34
+ [5, "SIGTRAP"],
35
+ [6, "SIGABRT"],
36
+ [7, "SIGEMT"],
37
+ [8, "SIGFPE"],
38
+ [9, "SIGKILL"],
39
+ [10, "SIGBUS"],
40
+ [11, "SIGSEGV"],
41
+ [12, "SIGSYS"],
42
+ [13, "SIGPIPE"],
43
+ [14, "SIGALRM"],
44
+ [15, "SIGTERM"],
45
+ ]);
46
+ /**
47
+ * exception.type is the Objective-C or Swift exception name, else the Mach exception name, else the
48
+ * signal name, else NativeCrash; a hang is AppHang. The message is the exception's message, else the
49
+ * termination reason, else the exception and signal.
50
+ */
51
+ export function describeDiagnostic(d) {
52
+ const { lines, images } = nativeStack(d.callStackTree, d.kind);
53
+ if (d.kind === "hang") {
54
+ const s = d.hangSeconds;
55
+ return {
56
+ source: "hang",
57
+ type: "AppHang",
58
+ message: s === undefined ? "The main thread was unresponsive" : `The main thread was unresponsive for ${s} s`,
59
+ ...(s === undefined ? {} : { hangSeconds: s }),
60
+ lines,
61
+ images,
62
+ };
63
+ }
64
+ const signal = d.signal === undefined ? undefined : (SIGNALS.get(d.signal) ?? `SIG${d.signal}`);
65
+ const mach = d.exceptionType === undefined
66
+ ? undefined
67
+ : (MACH_EXCEPTIONS.get(d.exceptionType) ?? `EXC_${d.exceptionType}`);
68
+ const type = d.objcName ?? mach ?? signal ?? "NativeCrash";
69
+ const machText = mach === undefined
70
+ ? undefined
71
+ : `${mach}${signal === undefined ? "" : ` (${signal})`}${d.exceptionCode === undefined ? "" : `, code ${d.exceptionCode}`}`;
72
+ const message = d.objcMessage ?? d.terminationReason ?? machText ?? signal ?? "";
73
+ return { source: "crash", type, message, ...(signal === undefined ? {} : { signal }), lines, images };
74
+ }
75
+ /**
76
+ * The context a report happened in: the last entry its own process wrote at or before the
77
+ * report's payload ended, by process ID. A process ID is reused, so the process is the latest one
78
+ * with that ID that started before the end; only that choice allows for clock slack. The report
79
+ * may have happened anywhere from the payload's begin to its end, so the process must have written
80
+ * an entry at or before the begin, or stamped every entry with a first consent that early: consent
81
+ * covered the whole window. A report without a process
82
+ * ID, or whose window starts before its process's first entry, maps to nothing. A crash is never about the current
83
+ * process (currentStart); a hang may be. Late entries name no context.
84
+ */
85
+ export function attributeReport(d, history, currentStart) {
86
+ if (d.pid === undefined)
87
+ return undefined;
88
+ const latest = (es) => es.reduce((a, e) => (a === undefined || e.at >= a.at ? e : a), undefined);
89
+ const own = history.filter((e) => e.pid === d.pid &&
90
+ e.late !== true &&
91
+ (d.kind === "hang" || currentStart === undefined || e.processStart !== currentStart));
92
+ const starts = own.flatMap((e) => e.processStart !== undefined && e.processStart <= d.end + SLACK_MILLIS ? [e.processStart] : []);
93
+ const start = starts.length === 0 ? undefined : Math.max(...starts);
94
+ const proc = start === undefined ? own : own.filter((e) => e.processStart === start);
95
+ // The report may have happened anywhere in its payload's window, so the process must have
96
+ // recorded under consent from before the window began.
97
+ if (!proc.some((e) => Math.min(e.at, e.since ?? e.at) <= d.begin))
98
+ return undefined;
99
+ return latest(proc.filter((e) => e.at <= d.end));
100
+ }
101
+ /**
102
+ * Whether a crash is the abort React Native raises for a fatal JavaScript error (RCTFatal), which
103
+ * errors() already recorded as uncaught: an RCTFatalException, or a SIGABRT with no exception name
104
+ * where iOS does not report one.
105
+ */
106
+ function jsFatalAbort(d) {
107
+ if (d.objcName !== undefined)
108
+ return d.objcName.startsWith("RCTFatalException");
109
+ return d.signal === 6;
110
+ }
111
+ function resourceString(rt, key) {
112
+ try {
113
+ const v = rt.telemetry.resource?.attributes?.[key];
114
+ return typeof v === "string" && v !== "" ? v : undefined;
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ /** Starts writing the context and turning reports into records. */
121
+ export function startNativeReports(rt, deps) {
122
+ const { native } = deps;
123
+ const currentStart = native.processStart();
124
+ // The module keeps nothing written before it is enabled, so nothing is written until it is.
125
+ let enabled = false;
126
+ let last = "";
127
+ /** Writes the context when it changed; resolves once the module has it. */
128
+ const write = (fatal = false) => {
129
+ if (!enabled)
130
+ return Promise.resolve();
131
+ const s = rt.session.current();
132
+ const v = rt.views.current();
133
+ if (s === undefined || v === undefined)
134
+ return Promise.resolve();
135
+ const version = resourceString(rt, "service.version");
136
+ const updateId = resourceString(rt, ATTR_RUM_APP_UPDATE_ID);
137
+ const fields = {
138
+ sessionId: s.id,
139
+ viewId: v.id,
140
+ viewName: v.name,
141
+ viewKind: v.kind,
142
+ seq: rt.summary.nextSeq(v.id) ?? 0,
143
+ kept: rt.session.kept(),
144
+ ...(version === undefined ? {} : { version }),
145
+ ...(updateId === undefined ? {} : { updateId }),
146
+ };
147
+ const key = JSON.stringify(fields);
148
+ if (key === last && !fatal)
149
+ return Promise.resolve();
150
+ last = key;
151
+ return native
152
+ .recordContext({ at: rt.timeOrigin + rt.now(), ...fields, ...(fatal ? { fatal: true } : {}) })
153
+ .then((kept) => {
154
+ // A write the module refused is not the context it holds: write it again next time.
155
+ if (!kept && last === key)
156
+ last = "";
157
+ });
158
+ };
159
+ /** The next seq of each earlier view this launch sent a late summary for. */
160
+ const lateSeq = new Map();
161
+ /** The seq each report's late summary had, so a report tried again reuses it. */
162
+ const seqOf = new Map();
163
+ /**
164
+ * Records one report. False when it is dropped on purpose; a throw, as when the pipeline did not
165
+ * take the record, leaves it for the next poll. Otherwise it returns what marks the report
166
+ * counted: a late entry naming it, written only once a flush exported its summary, and resolving
167
+ * whether the module kept it. A report tried again after the mark is not counted again; one
168
+ * tried again after a failed flush, a dropped summary or a failed mark is.
169
+ */
170
+ const record = (d, history) => {
171
+ const entry = attributeReport(d, history, currentStart);
172
+ // No process ID, or one with no context: nothing shows that process recorded under consent.
173
+ if (entry === undefined)
174
+ return false;
175
+ if (entry.fatal === true && d.kind === "crash" && jsFatalAbort(d))
176
+ return false;
177
+ const described = describeDiagnostic(d);
178
+ const now = rt.timeOrigin + rt.now();
179
+ const time = Math.min(now, Math.max(d.end, entry.at));
180
+ if (entry.sessionId === rt.session.current()?.id)
181
+ rt.session.retain("error");
182
+ else if (entry.kept !== undefined)
183
+ rt.session.recall(entry.sessionId, entry.kept);
184
+ const taken = rt.emit(EVENT_RUM_ERROR, {
185
+ [ATTR_RUM_ERROR_SOURCE]: described.source,
186
+ "exception.type": described.type,
187
+ "exception.message": described.message,
188
+ ...(described.lines.length === 0
189
+ ? {}
190
+ : {
191
+ "exception.stacktrace": described.lines.join("\n"),
192
+ [ATTR_RUM_ERROR_BINARY_IMAGES]: described.images.join("\n"),
193
+ }),
194
+ ...(described.signal === undefined ? {} : { [ATTR_RUM_ERROR_SIGNAL]: described.signal }),
195
+ ...(described.hangSeconds === undefined
196
+ ? {}
197
+ : { [ATTR_RUM_ERROR_HANG_DURATION]: described.hangSeconds }),
198
+ // The app version of the launch that crashed: its context's, else what MetricKit says.
199
+ ...(() => {
200
+ const version = entry.version ?? d.appVersion ?? d.appBuild;
201
+ return version === undefined ? {} : { "service.version": version };
202
+ })(),
203
+ "session.id": entry.sessionId,
204
+ [ATTR_RUM_VIEW_ID]: entry.viewId,
205
+ ...(entry.updateId === undefined ? {} : { [ATTR_RUM_APP_UPDATE_ID]: entry.updateId }),
206
+ }, ROOT_CONTEXT, undefined, time);
207
+ if (!taken)
208
+ throw new Error("the record did not reach the log export");
209
+ if (history.some((e) => e.late === true && e.report === d.id))
210
+ return async () => true;
211
+ const key = `errors.${described.source}`;
212
+ const view = { viewId: entry.viewId, viewName: entry.viewName, viewKind: entry.viewKind };
213
+ const mark = (seq) => () => native.recordContext({
214
+ at: now,
215
+ sessionId: entry.sessionId,
216
+ ...view,
217
+ seq,
218
+ late: true,
219
+ report: d.id,
220
+ });
221
+ // A hang of this process in the screen still current counts in that screen's own summary,
222
+ // sent now so the flush that follows exports it.
223
+ if (entry.processStart === currentStart && entry.viewId === rt.views.current()?.id) {
224
+ rt.summary.count(key);
225
+ if (!rt.summary.flush())
226
+ throw new Error("the summary did not reach the log export");
227
+ return mark(rt.summary.nextSeq(entry.viewId) ?? 0);
228
+ }
229
+ // The view's latest seq: its process's entries, a late summary a launch sent, and this
230
+ // process's own count when the view is one of its own.
231
+ const written = history
232
+ .filter((e) => e.viewId === entry.viewId && (e.processStart === entry.processStart || e.late === true))
233
+ .reduce((m, e) => Math.max(m, e.seq), entry.seq);
234
+ const seq = seqOf.get(d.id) ??
235
+ Math.max(written, lateSeq.get(entry.viewId) ?? 0, rt.summary.nextSeq(entry.viewId) ?? 0);
236
+ seqOf.set(d.id, seq);
237
+ lateSeq.set(entry.viewId, Math.max(lateSeq.get(entry.viewId) ?? 0, seq + 1));
238
+ const counted = rt.summary.late({
239
+ id: entry.viewId,
240
+ name: entry.viewName,
241
+ kind: entry.viewKind,
242
+ sessionId: entry.sessionId,
243
+ }, seq, key);
244
+ if (!counted)
245
+ throw new Error("the summary did not reach the log export");
246
+ return mark(seq + 1);
247
+ };
248
+ let stopped = false;
249
+ let polling = false;
250
+ const poll = async () => {
251
+ if (stopped || polling || !enabled)
252
+ return;
253
+ polling = true;
254
+ try {
255
+ write();
256
+ const pending = await native.pendingDiagnostics();
257
+ if (stopped || pending.length === 0)
258
+ return;
259
+ const history = await native.contextHistory();
260
+ if (stopped)
261
+ return;
262
+ const dropped = [];
263
+ const recorded = [];
264
+ const marks = [];
265
+ for (const d of pending) {
266
+ try {
267
+ const mark = record(d, history);
268
+ if (mark === false)
269
+ dropped.push(d.id);
270
+ else {
271
+ recorded.push(d.id);
272
+ marks.push(mark);
273
+ }
274
+ }
275
+ catch (err) {
276
+ // Kept for the next poll.
277
+ diag.warn("o11y: rum: recording a native report failed", err);
278
+ }
279
+ }
280
+ // A recorded report is marked counted and acknowledged once a flush exported its record and
281
+ // summary to delivery or its retry queue, so a crash before the export does not lose it.
282
+ let delivered = recorded.length > 0;
283
+ if (delivered) {
284
+ const report = await rt.telemetry.forceFlush();
285
+ delivered = !report.errors.some((e) => e.signal === "logs" || e.signal === "lifecycle");
286
+ }
287
+ // A revoke while this poll waited ends it: what a later grant's module holds is not this
288
+ // grant's to mark or acknowledge.
289
+ if (stopped)
290
+ return;
291
+ // A report is acknowledged once its mark is on disk, so a later launch never counts it again.
292
+ const marked = delivered ? await Promise.all(marks.map((mark) => mark())) : [];
293
+ if (stopped)
294
+ return;
295
+ native.acknowledgeDiagnostics([...dropped, ...recorded.filter((_, i) => marked[i] === true)]);
296
+ }
297
+ catch (err) {
298
+ diag.warn("o11y: rum: reading native reports failed", err);
299
+ }
300
+ finally {
301
+ polling = false;
302
+ }
303
+ };
304
+ const delays = deps.pollMillis ?? POLL_MILLIS;
305
+ const every = delays.at(-1) ?? 0;
306
+ const timers = new Set();
307
+ const later = (ms, then) => {
308
+ const t = deps.setTimeout(() => {
309
+ timers.delete(t);
310
+ if (!stopped)
311
+ then();
312
+ }, ms);
313
+ timers.add(t);
314
+ };
315
+ const repeat = () => {
316
+ void poll();
317
+ if (every > 0)
318
+ later(every, repeat);
319
+ };
320
+ for (const [i, ms] of delays.entries()) {
321
+ later(ms, i === delays.length - 1 ? repeat : () => void poll());
322
+ }
323
+ native.setRecording(true).then(() => {
324
+ if (stopped)
325
+ return;
326
+ enabled = true;
327
+ write();
328
+ // The startup poll, when the timer for it fired before the module was enabled.
329
+ void poll();
330
+ }, (err) => diag.warn("o11y: rum: the native module could not start recording", err));
331
+ const offViews = rt.views.subscribe((e) => {
332
+ if (e.type === "start" || e.type === "rename")
333
+ write();
334
+ });
335
+ const offSession = rt.session.subscribe((e) => {
336
+ if (e.type === "start" || e.type === "kept")
337
+ write();
338
+ });
339
+ // A hide sends the summaries after its hooks run, so the context is written after them.
340
+ let hideTimer;
341
+ const offHide = rt.onHide(() => {
342
+ deps.clearTimeout(hideTimer);
343
+ hideTimer = deps.setTimeout(write, 0);
344
+ });
345
+ return {
346
+ stop() {
347
+ stopped = true;
348
+ for (const t of timers)
349
+ deps.clearTimeout(t);
350
+ timers.clear();
351
+ deps.clearTimeout(hideTimer);
352
+ offViews();
353
+ offSession();
354
+ offHide();
355
+ // A revoke closes the gate before the collectors stop: the module stops keeping reports and
356
+ // deletes what it holds. A shutdown or remote configuration leaves it recording; errors()'s
357
+ // clear switches it off on a revoke or a denied start when the collector is not running.
358
+ if (!rt.gate.recording()) {
359
+ native
360
+ .setRecording(false)
361
+ .catch((err) => diag.warn("o11y: rum: the native module could not delete what it holds", err));
362
+ }
363
+ },
364
+ fatal() {
365
+ return stopped ? Promise.resolve() : write(true);
366
+ },
367
+ };
368
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The native stack format of spec 1.4.0, built from MetricKit's call stack tree. It imports nothing,
3
+ * so the gateway journey and other tools can build a stack exactly as errors() does.
4
+ */
5
+ /**
6
+ * The stack of the thread MetricKit attributes the report to (else the first), innermost first, in
7
+ * the spec's native format, and one `<UUID> <load address> <name>` line per binary in it. Both stay
8
+ * under the gateway's value limit: the stack is cut at a frame boundary, and only the images of the
9
+ * kept frames are listed. kind says how MetricKit laid the tree out (framesOf).
10
+ */
11
+ export declare function nativeStack(tree: unknown, kind?: "crash" | "hang"): {
12
+ lines: string[];
13
+ images: string[];
14
+ };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The native stack format of spec 1.4.0, built from MetricKit's call stack tree. It imports nothing,
3
+ * so the gateway journey and other tools can build a stack exactly as errors() does.
4
+ */
5
+ /** The gateway's default limit on one attribute value, which the stack and images stay under. */
6
+ const MAX_VALUE_BYTES = 4096;
7
+ /** The most frames a native stack keeps. */
8
+ const MAX_FRAMES = 64;
9
+ /** The most nested frames read from one MetricKit tree, against a malformed or cyclic payload. */
10
+ const MAX_DEPTH = 512;
11
+ const isObject = (v) => typeof v === "object" && v !== null;
12
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
13
+ function frameOf(v) {
14
+ if (!isObject(v))
15
+ return undefined;
16
+ const { binaryUUID, binaryName, address, offsetIntoBinaryTextSegment: offset } = v;
17
+ if (typeof binaryUUID !== "string" || binaryUUID === "" || !isCount(offset))
18
+ return undefined;
19
+ const name = typeof binaryName === "string" && binaryName !== "" ? binaryName.replace(/\s+/g, " ") : "???";
20
+ return { uuid: binaryUUID.toUpperCase(), name, address: isCount(address) ? address : offset, offset };
21
+ }
22
+ const subFramesOf = (node) => isObject(node) && Array.isArray(node.subFrames) ? node.subFrames : [];
23
+ const samplesOf = (node) => isObject(node) && isCount(node.sampleCount) ? node.sampleCount : 0;
24
+ /** The most sampled of nodes, the first on a tie. */
25
+ const mostSampled = (nodes) => nodes.reduce((best, n) => (best === undefined || samplesOf(n) > samplesOf(best) ? n : best), undefined);
26
+ /**
27
+ * The frames of one MetricKit call stack, innermost first. A crash's stack starts at the crashed
28
+ * frame and nests each caller as its first subframe. A hang's is the main thread's samples
29
+ * aggregated from the outermost frame (dyld's start), nesting the callees of each frame, which
30
+ * branch where samples differ: its stack is the most sampled path, reversed.
31
+ */
32
+ function framesOf(stack, kind) {
33
+ const out = [];
34
+ const roots = isObject(stack) && Array.isArray(stack.callStackRootFrames) ? stack.callStackRootFrames : [];
35
+ const next = kind === "hang" ? mostSampled : (nodes) => nodes[0];
36
+ let node = next(roots);
37
+ for (let depth = 0; node !== undefined && depth < MAX_DEPTH; depth++) {
38
+ const f = frameOf(node);
39
+ if (f === undefined)
40
+ break;
41
+ out.push(f);
42
+ node = next(subFramesOf(node));
43
+ }
44
+ return kind === "hang" ? out.reverse() : out;
45
+ }
46
+ const hex = (n) => n.toString(16);
47
+ const loadOf = (f) => Math.max(0, f.address - f.offset);
48
+ function frameLine(i, f) {
49
+ return `${String(i).padEnd(3)} ${f.name.padEnd(30)} 0x${hex(f.address).padStart(16, "0")} 0x${hex(loadOf(f))} + ${f.offset}`;
50
+ }
51
+ /**
52
+ * The stack of the thread MetricKit attributes the report to (else the first), innermost first, in
53
+ * the spec's native format, and one `<UUID> <load address> <name>` line per binary in it. Both stay
54
+ * under the gateway's value limit: the stack is cut at a frame boundary, and only the images of the
55
+ * kept frames are listed. kind says how MetricKit laid the tree out (framesOf).
56
+ */
57
+ export function nativeStack(tree, kind = "crash") {
58
+ const stacks = isObject(tree) && Array.isArray(tree.callStacks) ? tree.callStacks : [];
59
+ const stack = stacks.find((s) => isObject(s) && s.threadAttributed === true) ?? stacks[0];
60
+ const lines = [];
61
+ const images = [];
62
+ const seen = new Set();
63
+ let lineBytes = 0;
64
+ let imageBytes = 0;
65
+ for (const [i, f] of framesOf(stack, kind).slice(0, MAX_FRAMES).entries()) {
66
+ const line = frameLine(i, f);
67
+ const image = seen.has(f.uuid) ? undefined : `${f.uuid} 0x${hex(loadOf(f))} ${f.name}`;
68
+ const addImage = image === undefined ? 0 : image.length + (images.length > 0 ? 1 : 0);
69
+ const addLine = line.length + (lines.length > 0 ? 1 : 0);
70
+ if (lineBytes + addLine > MAX_VALUE_BYTES || imageBytes + addImage > MAX_VALUE_BYTES)
71
+ break;
72
+ lines.push(line);
73
+ lineBytes += addLine;
74
+ if (image !== undefined) {
75
+ seen.add(f.uuid);
76
+ images.push(image);
77
+ imageBytes += addImage;
78
+ }
79
+ }
80
+ return { lines, images };
81
+ }
@@ -0,0 +1,27 @@
1
+ /** The public options of setupRumReactNative and its telemetry handle. */
2
+ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "@libo11y/react-native";
3
+ import type { Rum, RumOptions } from "@libo11y/rum";
4
+ /**
5
+ * RUM's own options on React Native: the browser's RumOptions without URL naming, because an app
6
+ * has no URL, plus the first screen's name. Every view is a screen.
7
+ */
8
+ export interface RumReactNativeOptions extends Omit<RumOptions, "viewName"> {
9
+ /**
10
+ * The name of a screen nothing named: the first screen until a router adapter or
11
+ * rum.setViewName names it, and a rum.startView without a name. Default "app".
12
+ */
13
+ readonly initialViewName?: string;
14
+ }
15
+ /** The options of setupRumReactNative: the setup options of `@libo11y/react-native` and RUM's own. */
16
+ export interface RumReactNativeSetupOptions extends ReactNativeSetupOptions {
17
+ /** RUM's own options. */
18
+ readonly rum?: RumReactNativeOptions;
19
+ }
20
+ /**
21
+ * React Native telemetry with RUM. rum is the same Rum handle the browser's setupRum returns, so
22
+ * `@libo11y/rum-react` and `@libo11y/rum-connect` accept it as it is.
23
+ */
24
+ export interface ReactNativeRumTelemetry extends ReactNativeTelemetry {
25
+ /** The application's handle on RUM. */
26
+ readonly rum: Rum;
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * screens(): the views collector of React Native. Every view is a screen. The first
3
+ * screen is the load view, and its span is a child of app_load; every later screen span is a root
4
+ * linked to the action that caused it. An app has no URL to follow, so a screen starts only when
5
+ * rum.startView starts it (a router adapter or the app), and a screen span ends at the first frame
6
+ * after rum.viewRendered() (requestAnimationFrame, then a zero-delay task), or 10 seconds after it
7
+ * started without one. Screens carry no web vitals.
8
+ */
9
+ import { type RumCollector } from "@libo11y/rum/core";
10
+ import type { RumReactNativeEnv } from "./contracts/env.ts";
11
+ /** The screens collector over env. Its name is views, as the browser's views collector's. */
12
+ export declare function screensWith(env: RumReactNativeEnv): RumCollector;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * screens(): the views collector of React Native. Every view is a screen. The first
3
+ * screen is the load view, and its span is a child of app_load; every later screen span is a root
4
+ * linked to the action that caused it. An app has no URL to follow, so a screen starts only when
5
+ * rum.startView starts it (a router adapter or the app), and a screen span ends at the first frame
6
+ * after rum.viewRendered() (requestAnimationFrame, then a zero-delay task), or 10 seconds after it
7
+ * started without one. Screens carry no web vitals.
8
+ */
9
+ import { viewsWith } from "@libo11y/rum/core";
10
+ /** The views env of a screen on React Native: frames and timers, no history, no DOM, no load event. */
11
+ function screensEnv(env, timeOrigin) {
12
+ return {
13
+ timeOrigin,
14
+ paint: {
15
+ requestAnimationFrame: (cb) => env.requestAnimationFrame(cb),
16
+ setTimeout: (cb, ms) => env.setTimeout(cb, ms),
17
+ // An app in the background draws no frames, so a render then waits for a task only.
18
+ hidden: () => !env.visible(),
19
+ },
20
+ setTimeout: (cb, ms) => env.setTimeout(cb, ms),
21
+ clearTimeout: (h) => env.clearTimeout(h),
22
+ navigationLoadEnd: () => 0,
23
+ whenLoaded: () => () => { },
24
+ };
25
+ }
26
+ /** The screens collector over env. Its name is views, as the browser's views collector's. */
27
+ export function screensWith(env) {
28
+ return {
29
+ name: "views",
30
+ start: (rt) => viewsWith({ history: false }, screensEnv(env, rt.timeOrigin)).start(rt),
31
+ };
32
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The RUM session on device storage. An app is one JavaScript context, so no other context changes
3
+ * the session and onChange never fires. The record is the web's ({ v: 1, ...state } under
4
+ * SESSION_STORAGE_KEY), so a relaunch within the idle window continues the session, as a reload
5
+ * does on the web. Writes run one after another in call order, and a load waits for those already
6
+ * made, so a revoke's removal is never read back. The session manager first uses the store when
7
+ * consent is granted, so nothing is read or written before.
8
+ */
9
+ import type { KeyValueStorage } from "@libo11y/react-native";
10
+ import { type SessionStore } from "@libo11y/rum/core";
11
+ /** A SessionStore on device storage, whose writes can be awaited. */
12
+ export interface DeviceSessionStore extends SessionStore {
13
+ /**
14
+ * Resolves once every write already made has reached storage or failed. A failed write was
15
+ * reported through diag when it failed. Never rejects.
16
+ */
17
+ flush(): Promise<void>;
18
+ }
19
+ /** A SessionStore over storage. */
20
+ export declare function storageSessionStore(storage: KeyValueStorage): DeviceSessionStore;
@@ -0,0 +1,28 @@
1
+ import { parseSessionState, SESSION_STORAGE_KEY } from "@libo11y/rum/core";
2
+ import { diag } from "@opentelemetry/api";
3
+ /** A SessionStore over storage. */
4
+ export function storageSessionStore(storage) {
5
+ /** The last write, settled: every write and load runs after it. */
6
+ let last = Promise.resolve();
7
+ return {
8
+ async load() {
9
+ await last;
10
+ try {
11
+ const raw = await storage.getItem(SESSION_STORAGE_KEY);
12
+ return raw === null ? undefined : parseSessionState(JSON.parse(raw));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ },
18
+ save(state) {
19
+ const write = () => state === undefined
20
+ ? storage.removeItem(SESSION_STORAGE_KEY)
21
+ : storage.setItem(SESSION_STORAGE_KEY, JSON.stringify({ v: 1, ...state }));
22
+ last = last.then(write).catch((err) => diag.warn("o11y: rum: saving the session failed", err));
23
+ },
24
+ flush: () => last,
25
+ onChange: () => () => { },
26
+ close: () => { },
27
+ };
28
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * setupRumReactNativeWith: the RUM core (`@libo11y/rum/core`) bound to React Native. The platform is
3
+ * `@libo11y/react-native`'s setup through reactNativeBinding, the lifecycle its AppState, and every
4
+ * view a screen; a new screen is activity. Device storage (options.storage, default memoryStorage()) holds the retry queue,
5
+ * the retention buffer of sessions not yet kept, the session, so a relaunch within the idle window
6
+ * continues it, and the remote configuration cache. RUM writes none of it before consent is
7
+ * granted. RUM's core removes it: a start with consent denied removes what an earlier launch left
8
+ * before setup resolves, and a revoke removes it all, also what an earlier launch left, before the
9
+ * revoke resolves. A pending start leaves it untouched. The app_load span is recorded once per process (app-start.ts). setupRumReactNative,
10
+ * in index.ts, passes the real dependencies from env.ts.
11
+ */
12
+ import { type ReactNativeDeps } from "@libo11y/react-native/internal";
13
+ import type { RumReactNativeEnv } from "./contracts/env.ts";
14
+ import type { ReactNativeRumTelemetry, RumReactNativeSetupOptions } from "./options.ts";
15
+ /** The fixed URL RUM's core reads where a page has its location: an app has none. */
16
+ export declare const APP_LOCATION = "app:///";
17
+ /** What setupRumReactNativeWith builds on. Internal: tests replace parts of it. */
18
+ export interface RumReactNativeDeps {
19
+ /** `@libo11y/react-native`'s dependencies, which the binding wraps. */
20
+ readonly platform: ReactNativeDeps;
21
+ readonly env: RumReactNativeEnv;
22
+ /** Epoch milliseconds. */
23
+ readonly now: () => number;
24
+ /** performance.now(). */
25
+ readonly perfNow: () => number;
26
+ /** The epoch milliseconds perfNow counts from. */
27
+ readonly timeOrigin: number;
28
+ /**
29
+ * The fetch the OTLP transport and remote configuration use. Default the global fetch captured
30
+ * before the instrumentation patched it.
31
+ */
32
+ readonly fetch?: typeof fetch;
33
+ }
34
+ /**
35
+ * React Native telemetry with RUM over deps, installing it globally when install is true. Resolves
36
+ * with the platform's telemetry, with rum added.
37
+ */
38
+ export declare function setupRumReactNativeWith(options: RumReactNativeSetupOptions, deps: RumReactNativeDeps, install: boolean): Promise<ReactNativeRumTelemetry>;