-
-
Notifications
You must be signed in to change notification settings - Fork 342
/
Copy pathwrapper.ts
551 lines (467 loc) · 14 KB
/
wrapper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/* eslint-disable max-lines */
import {
Breadcrumb,
Event,
Package,
Response,
Severity,
User,
} from "@sentry/types";
import { logger, SentryError } from "@sentry/utils";
import { NativeModules, Platform } from "react-native";
import {
NativeAppStartResponse,
NativeDeviceContextsResponse,
NativeFramesResponse,
NativeReleaseResponse,
SentryNativeBridgeModule,
} from "./definitions";
import { ReactNativeOptions } from "./options";
const RNSentry = NativeModules.RNSentry as SentryNativeBridgeModule | undefined;
interface SentryNativeWrapper {
enableNative: boolean;
nativeIsReady: boolean;
platform: typeof Platform.OS;
_NativeClientError: Error;
_DisabledNativeError: Error;
_processLevels(event: Event): Event;
_processLevel(level: Severity): Severity;
_serializeObject(data: { [key: string]: unknown }): { [key: string]: string };
_isModuleLoaded(
module: SentryNativeBridgeModule | undefined
): module is SentryNativeBridgeModule;
isNativeTransportAvailable(): boolean;
initNativeSdk(options: ReactNativeOptions): PromiseLike<boolean>;
closeNativeSdk(): PromiseLike<void>;
sendEvent(event: Event): PromiseLike<Response>;
fetchNativeRelease(): PromiseLike<NativeReleaseResponse>;
fetchNativeDeviceContexts(): PromiseLike<NativeDeviceContextsResponse>;
fetchNativeAppStart(): PromiseLike<NativeAppStartResponse | null>;
fetchNativeFrames(): PromiseLike<NativeFramesResponse | null>;
fetchNativeSdkInfo(): PromiseLike<Package | null>;
disableNativeFramesTracking(): void;
addBreadcrumb(breadcrumb: Breadcrumb): void;
setContext(key: string, context: { [key: string]: unknown } | null): void;
clearBreadcrumbs(): void;
setExtra(key: string, extra: unknown): void;
setUser(user: User | null): void;
setTag(key: string, value: string): void;
nativeCrash(): void;
}
/**
* Our internal interface for calling native functions
*/
export const NATIVE: SentryNativeWrapper = {
/**
* Sending the event over the bridge to native
* @param event Event
*/
async sendEvent(_event: Event): Promise<Response> {
if (!this.enableNative) {
return {
reason: `Event was skipped as native SDK is not enabled.`,
status: "skipped",
};
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const event = this._processLevels(_event);
// Delete this metadata as this should not be sent to Sentry.
delete event.sdkProcessingMetadata;
const header = {
event_id: event.event_id,
sdk: event.sdk,
};
let envelopeWasSent = false;
if (NATIVE.platform === "android") {
// Android
const headerString = JSON.stringify(header);
/*
We do this to avoid duplicate breadcrumbs on Android as sentry-android applies the breadcrumbs
from the native scope onto every envelope sent through it. This scope will contain the breadcrumbs
sent through the scope sync feature. This causes duplicate breadcrumbs.
We then remove the breadcrumbs here but only when mechanism.handled is true. If it is handled == false,
this is a signal that the app would crash and android would lose the breadcrumbs by the time the app is restarted to read
the envelope.
*/
if (event.exception?.values?.[0]?.mechanism?.handled) {
event.breadcrumbs = [];
}
const payload = {
...event,
message: {
message: event.message,
},
};
const payloadString = JSON.stringify(payload);
let length = payloadString.length;
try {
length = await RNSentry.getStringBytesLength(payloadString);
} catch {
// The native call failed, we do nothing, we have payload.length as a fallback
}
const item = {
content_type: "application/json",
length,
type: payload.type ?? "event",
};
const itemString = JSON.stringify(item);
const envelopeString = `${headerString}\n${itemString}\n${payloadString}`;
envelopeWasSent = await RNSentry.captureEnvelope(envelopeString);
} else {
// iOS/Mac
const payload = {
...event,
message: {
message: event.message,
},
};
// Serialize and remove any instances that will crash the native bridge such as Spans
const serializedPayload = JSON.parse(JSON.stringify(payload));
// The envelope item is created (and its length determined) on the iOS side of the native bridge.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
envelopeWasSent = await RNSentry.captureEnvelope({
header,
payload: serializedPayload,
});
}
if (envelopeWasSent) {
return {
status: "success",
};
}
return {
status: "failed",
};
},
/**
* Starts native with the provided options.
* @param options ReactNativeOptions
*/
async initNativeSdk(originalOptions: ReactNativeOptions): Promise<boolean> {
const options = {
enableNative: true,
autoInitializeNativeSdk: true,
...originalOptions,
};
if (!options.enableNative) {
if (options.enableNativeNagger) {
logger.warn("Note: Native Sentry SDK is disabled.");
}
this.enableNative = false;
return false;
}
if (!options.autoInitializeNativeSdk) {
if (options.enableNativeNagger) {
logger.warn(
"Note: Native Sentry SDK was not initialized automatically, you will need to initialize it manually. If you wish to disable the native SDK and get rid of this warning, pass enableNative: false"
);
}
return false;
}
if (!options.dsn) {
logger.warn(
"Warning: No DSN was provided. The Sentry SDK will be disabled. Native SDK will also not be initalized."
);
return false;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// filter out all the options that would crash native.
/* eslint-disable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const {
beforeSend,
beforeBreadcrumb,
integrations,
defaultIntegrations,
transport,
...filteredOptions
} = options;
/* eslint-enable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const nativeIsReady = await RNSentry.initNativeSdk(filteredOptions);
this.nativeIsReady = nativeIsReady;
return nativeIsReady;
},
/**
* Fetches the release from native
*/
async fetchNativeRelease(): Promise<NativeReleaseResponse> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeRelease();
},
/**
* Fetches the Sdk info for the native sdk.
* NOTE: Only available on iOS.
*/
async fetchNativeSdkInfo(): Promise<Package | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (this.platform !== "ios") {
return null;
}
return RNSentry.fetchNativeSdkInfo();
},
/**
* Fetches the device contexts. Not used on Android.
*/
async fetchNativeDeviceContexts(): Promise<NativeDeviceContextsResponse> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (this.platform !== "ios") {
// Only ios uses deviceContexts, return an empty object.
return {};
}
return RNSentry.fetchNativeDeviceContexts();
},
async fetchNativeAppStart(): Promise<NativeAppStartResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeAppStart();
},
async fetchNativeFrames(): Promise<NativeFramesResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeFrames();
},
/**
* Triggers a native crash.
* Use this only for testing purposes.
*/
nativeCrash(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.crash();
},
/**
* Sets the user in the native scope.
* Passing null clears the user.
*/
setUser(user: User | null): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// separate and serialze all non-default user keys.
let defaultUserKeys = null;
let otherUserKeys = null;
if (user) {
const { id, ip_address, email, username, ...otherKeys } = user;
defaultUserKeys = this._serializeObject({
email,
id,
ip_address,
username,
});
otherUserKeys = this._serializeObject(otherKeys);
}
RNSentry.setUser(defaultUserKeys, otherUserKeys);
},
/**
* Sets a tag in the native module.
* @param key string
* @param value string
*/
setTag(key: string, value: string): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const stringifiedValue =
typeof value === "string" ? value : JSON.stringify(value);
RNSentry.setTag(key, stringifiedValue);
},
/**
* Sets an extra in the native scope, will stringify
* extra value if it isn't already a string.
* @param key string
* @param extra any
*/
setExtra(key: string, extra: unknown): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// we stringify the extra as native only takes in strings.
const stringifiedExtra =
typeof extra === "string" ? extra : JSON.stringify(extra);
RNSentry.setExtra(key, stringifiedExtra);
},
/**
* Adds breadcrumb to the native scope.
* @param breadcrumb Breadcrumb
*/
addBreadcrumb(breadcrumb: Breadcrumb): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.addBreadcrumb({
...breadcrumb,
// Process and convert deprecated levels
level: breadcrumb.level
? this._processLevel(breadcrumb.level)
: undefined,
data: breadcrumb.data
? this._serializeObject(breadcrumb.data)
: undefined,
});
},
/**
* Clears breadcrumbs on the native scope.
*/
clearBreadcrumbs(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.clearBreadcrumbs();
},
/**
* Sets context on the native scope. Not implemented in Android yet.
* @param key string
* @param context key-value map
*/
setContext(key: string, context: { [key: string]: unknown } | null): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (this.platform === "android") {
// setContext not available on the Android SDK yet.
this.setExtra(key, context);
} else {
RNSentry.setContext(
key,
context !== null ? this._serializeObject(context) : null
);
}
},
/**
* Closes the Native Layer SDK
*/
async closeNativeSdk(): Promise<void> {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
return RNSentry.closeNativeSdk().then(() => {
this.enableNative = false;
});
},
disableNativeFramesTracking(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
RNSentry.disableNativeFramesTracking();
},
isNativeTransportAvailable(): boolean {
return this.enableNative && this._isModuleLoaded(RNSentry);
},
/**
* Serializes all values of root-level keys into strings.
* @param data key-value map.
* @returns An object where all root-level values are strings.
*/
_serializeObject(data: {
[key: string]: unknown;
}): { [key: string]: string } {
const serialized: { [key: string]: string } = {};
Object.keys(data).forEach((dataKey) => {
const value = data[dataKey];
serialized[dataKey] =
typeof value === "string" ? value : JSON.stringify(value);
});
return serialized;
},
/**
* Convert js severity level in event.level and event.breadcrumbs to more widely supported levels.
* @param event
* @returns Event with more widely supported Severity level strings
*/
_processLevels(event: Event): Event {
const processed: Event = {
...event,
level: event.level ? this._processLevel(event.level) : undefined,
breadcrumbs: event.breadcrumbs?.map((breadcrumb) => ({
...breadcrumb,
level: breadcrumb.level
? this._processLevel(breadcrumb.level)
: undefined,
})),
};
return processed;
},
/**
* Convert js severity level which has critical and log to more widely supported levels.
* @param level
* @returns More widely supported Severity level strings
*/
_processLevel(level: Severity): Severity {
if (level === Severity.Critical) {
return Severity.Fatal;
}
if (level === Severity.Log) {
return Severity.Debug;
}
return level;
},
/**
* Checks whether the RNSentry module is loaded.
*/
_isModuleLoaded(
module: SentryNativeBridgeModule | undefined
): module is SentryNativeBridgeModule {
return !!module;
},
_DisabledNativeError: new SentryError("Native is disabled"),
_NativeClientError: new SentryError(
"Native Client is not available, can't start on native."
),
enableNative: true,
nativeIsReady: false,
platform: Platform.OS,
};