-
-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathwrapper.ts
More file actions
910 lines (779 loc) · 25.9 KB
/
wrapper.ts
File metadata and controls
910 lines (779 loc) · 25.9 KB
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/* eslint-disable max-lines */
import type {
BaseEnvelopeItemHeaders,
Breadcrumb,
Envelope,
EnvelopeItem,
Event,
Package,
Primitive,
SeverityLevel,
User,
} from '@sentry/core';
import { debug, normalize, SentryError } from '@sentry/core';
import { NativeModules, Platform } from 'react-native';
import { isHardCrash } from './misc';
import type {
NativeAppStartResponse,
NativeDeviceContextsResponse,
NativeFramesResponse,
NativeReleaseResponse,
NativeScreenshot,
NativeStackFrames,
Spec,
} from './NativeRNSentry';
import type { ReactNativeClientOptions } from './options';
import type * as Hermes from './profiling/hermes';
import type { NativeAndroidProfileEvent, NativeProfileEvent } from './profiling/nativeTypes';
import type { MobileReplayOptions } from './replay/mobilereplay';
import type { RequiredKeysUser } from './user';
import { encodeUTF8 } from './utils/encode';
import { isTurboModuleEnabled } from './utils/environment';
import { convertToNormalizedObject } from './utils/normalize';
import { ReactNativeLibraries } from './utils/rnlibraries';
import { base64StringFromByteArray } from './vendor';
/**
* Returns the RNSentry module. Dynamically resolves if NativeModule or TurboModule is used.
*/
export function getRNSentryModule(): Spec | undefined {
return isTurboModuleEnabled()
? ReactNativeLibraries.TurboModuleRegistry?.get<Spec>('RNSentry')
: NativeModules.RNSentry;
}
const RNSentry: Spec | undefined = getRNSentryModule();
export interface Screenshot {
data: Uint8Array;
contentType: string;
filename: string;
}
export type NativeSdkOptions = Partial<ReactNativeClientOptions> & {
devServerUrl: string | undefined;
defaultSidecarUrl: string | undefined;
ignoreErrorsStr?: string[] | undefined;
ignoreErrorsRegex?: string[] | undefined;
} & {
mobileReplayOptions: MobileReplayOptions | undefined;
};
interface SentryNativeWrapper {
enableNative: boolean;
nativeIsReady: boolean;
platform: typeof Platform.OS;
_NativeClientError: Error;
_DisabledNativeError: Error;
_setPrimitiveProcessor: (processor: (value: Primitive) => void) => void;
_processItem(envelopeItem: EnvelopeItem): EnvelopeItem;
_processLevels(event: Event): Event;
_processLevel(level: SeverityLevel): SeverityLevel;
_serializeObject(data: { [key: string]: unknown }): { [key: string]: string };
_isModuleLoaded(module: Spec | undefined): module is Spec;
isNativeAvailable(): boolean;
initNativeSdk(options: NativeSdkOptions): PromiseLike<boolean>;
closeNativeSdk(): PromiseLike<void>;
sendEnvelope(envelope: Envelope): Promise<void>;
captureScreenshot(): Promise<Screenshot[] | null>;
fetchNativeRelease(): PromiseLike<NativeReleaseResponse>;
fetchNativeDeviceContexts(): PromiseLike<NativeDeviceContextsResponse | null>;
fetchNativeLogAttributes(): Promise<NativeDeviceContextsResponse | null>;
fetchNativeAppStart(): PromiseLike<NativeAppStartResponse | null>;
fetchNativeFrames(): PromiseLike<NativeFramesResponse | null>;
fetchNativeSdkInfo(): PromiseLike<Package | null>;
disableNativeFramesTracking(): void;
enableNativeFramesTracking(): void;
addBreadcrumb(breadcrumb: Breadcrumb): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setContext(key: string, context: { [key: string]: any } | null): void;
clearBreadcrumbs(): void;
setExtra(key: string, extra: unknown): void;
setUser(user: User | null): void;
setTag(key: string, value?: string): void;
nativeCrash(): void;
fetchModules(): Promise<Record<string, string> | null>;
fetchViewHierarchy(): PromiseLike<Uint8Array | null>;
startProfiling(platformProfilers: boolean): boolean;
stopProfiling(): {
hermesProfile: Hermes.Profile;
nativeProfile?: NativeProfileEvent;
androidProfile?: NativeAndroidProfileEvent;
} | null;
fetchNativePackageName(): string | null;
/**
* Fetches native stack frames and debug images for the instructions addresses.
*/
fetchNativeStackFramesBy(instructionsAddr: number[]): NativeStackFrames | null;
initNativeReactNavigationNewFrameTracking(): Promise<void>;
captureReplay(isHardCrash: boolean): Promise<string | null>;
getCurrentReplayId(): string | null;
crashedLastRun(): Promise<boolean | null>;
getNewScreenTimeToDisplay(): Promise<number | null | undefined>;
getDataFromUri(uri: string): Promise<Uint8Array | null>;
popTimeToDisplayFor(key: string): Promise<number | undefined | null>;
setActiveSpanId(spanId: string): void;
encodeToBase64(data: Uint8Array): Promise<string | null>;
primitiveProcessor(value: Primitive): string;
}
const EOL = encodeUTF8('\n');
/**
* Our internal interface for calling native functions
*/
export const NATIVE: SentryNativeWrapper = {
async fetchModules(): Promise<Record<string, string> | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const raw = await RNSentry.fetchModules();
if (raw) {
return JSON.parse(raw);
}
return null;
},
/**
* Sending the envelope over the bridge to native
* @param envelope Envelope
*/
async sendEnvelope(envelope: Envelope): Promise<void> {
if (!this.enableNative) {
debug.warn('Event was skipped as native SDK is not enabled.');
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const [envelopeHeader, envelopeItems] = envelope;
const headerString = JSON.stringify(envelopeHeader);
const headerBytes = encodeUTF8(headerString);
let envelopeBytes: Uint8Array = new Uint8Array(headerBytes.length + EOL.length);
envelopeBytes.set(headerBytes);
envelopeBytes.set(EOL, headerBytes.length);
let hardCrashed: boolean = false;
for (const rawItem of envelopeItems) {
const [itemHeader, itemPayload] = this._processItem(rawItem);
let bytesContentType: string;
let bytesPayload: number[] | Uint8Array | undefined;
if (typeof itemPayload === 'string') {
bytesContentType = 'text/plain';
bytesPayload = encodeUTF8(itemPayload);
} else if (itemPayload instanceof Uint8Array) {
bytesContentType =
typeof itemHeader.content_type === 'string' ? itemHeader.content_type : 'application/octet-stream';
bytesPayload = itemPayload;
} else {
bytesContentType = 'application/vnd.sentry.items.log+json';
bytesPayload = encodeUTF8(JSON.stringify(itemPayload));
if (!hardCrashed) {
hardCrashed = isHardCrash(itemPayload);
}
}
// Content type is not inside BaseEnvelopeItemHeaders.
(itemHeader as BaseEnvelopeItemHeaders).content_type = bytesContentType;
(itemHeader as BaseEnvelopeItemHeaders).length = bytesPayload.length;
const serializedItemHeader = JSON.stringify(itemHeader);
const bytesItemHeader = encodeUTF8(serializedItemHeader);
const newBytes = new Uint8Array(
envelopeBytes.length + bytesItemHeader.length + EOL.length + bytesPayload.length + EOL.length,
);
newBytes.set(envelopeBytes);
newBytes.set(bytesItemHeader, envelopeBytes.length);
newBytes.set(EOL, envelopeBytes.length + bytesItemHeader.length);
newBytes.set(bytesPayload, envelopeBytes.length + bytesItemHeader.length + EOL.length);
newBytes.set(EOL, envelopeBytes.length + bytesItemHeader.length + EOL.length + bytesPayload.length);
envelopeBytes = newBytes;
}
await RNSentry.captureEnvelope(base64StringFromByteArray(envelopeBytes), { hardCrashed });
},
/**
* Starts native with the provided options.
* @param options ReactNativeClientOptions
*/
async initNativeSdk(originalOptions: NativeSdkOptions): Promise<boolean> {
const options: NativeSdkOptions = {
enableNative: true,
autoInitializeNativeSdk: true,
...originalOptions,
// Keeps original behavior of enableLogs by not setting it when not defined.
...(originalOptions.enableLogs !== undefined
? { enableLogs: originalOptions.enableLogs && originalOptions.logsOrigin !== 'js' }
: {}),
};
if (!options.enableNative) {
if (options.enableNativeNagger) {
debug.warn('Note: Native Sentry SDK is disabled.');
}
this.enableNative = false;
return false;
}
if (!options.autoInitializeNativeSdk) {
if (options.enableNativeNagger) {
debug.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',
);
}
this.enableNative = true;
return false;
}
if (!options.dsn) {
debug.warn(
'Warning: No DSN was provided. The Sentry SDK will be disabled. Native SDK will also not be initalized.',
);
this.enableNative = false;
return false;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const ignoreErrorsStr = options.ignoreErrors?.filter(item => typeof item === 'string') as string[] | undefined;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const ignoreErrorsRegex = options.ignoreErrors
?.filter(item => item instanceof RegExp)
.map(item => (item as RegExp).source) as string[] | undefined;
if (ignoreErrorsStr && ignoreErrorsStr.length > 0) {
options.ignoreErrorsStr = ignoreErrorsStr;
}
if (ignoreErrorsRegex && ignoreErrorsRegex.length > 0) {
options.ignoreErrorsRegex = ignoreErrorsRegex;
}
// filter out all the options that would crash native.
/* eslint-disable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const {
beforeSend,
beforeBreadcrumb,
beforeSendTransaction,
integrations,
ignoreErrors,
logsOrigin,
...filteredOptions
} = options;
/* eslint-enable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const nativeIsReady = await RNSentry.initNativeSdk(filteredOptions);
this.nativeIsReady = nativeIsReady;
this.enableNative = true;
return nativeIsReady;
},
/**
* Fetches the attributes to be set into logs from Native
*/
async fetchNativeLogAttributes(): Promise<NativeDeviceContextsResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeLogAttributes();
},
/**
* 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.
*/
async fetchNativeSdkInfo(): Promise<Package | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeSdkInfo();
},
/**
* Fetches the device contexts. Not used on Android.
*/
async fetchNativeDeviceContexts(): Promise<NativeDeviceContextsResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeDeviceContexts();
},
async fetchNativeAppStart(): Promise<NativeAppStartResponse | null> {
if (!this.enableNative) {
debug.warn(this._DisabledNativeError);
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
debug.error(this._NativeClientError);
return null;
}
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 serialize all non-default user keys.
let userKeys = null;
let userDataKeys = null;
if (user) {
const { id, ip_address, email, username, geo, ...otherKeys } = user;
const requiredUser: RequiredKeysUser = {
id,
ip_address,
email,
username,
geo,
};
userKeys = this._serializeObject(requiredUser);
userDataKeys = this._serializeObject(otherKeys);
}
RNSentry.setUser(userKeys, userDataKeys);
},
/**
* 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;
}
if (typeof extra === 'string') {
return RNSentry.setExtra(key, extra);
}
if (typeof extra === 'undefined') {
return RNSentry.setExtra(key, 'undefined');
}
let stringifiedExtra: string | undefined;
try {
const normalizedExtra = normalize(extra);
stringifiedExtra = JSON.stringify(normalizedExtra);
} catch (e) {
debug.error('Extra for key ${key} not passed to native SDK, because it contains non-stringifiable values', e);
}
if (typeof stringifiedExtra === 'string') {
return RNSentry.setExtra(key, stringifiedExtra);
}
return RNSentry.setExtra(key, '**non-stringifiable**');
},
/**
* 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,
});
},
/**
* 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.
* @param key string
* @param context key-value map
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setContext(key: string, context: { [key: string]: any } | null): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (context === null) {
return RNSentry.setContext(key, null);
}
let normalizedContext: Record<string, unknown> | undefined;
try {
normalizedContext = convertToNormalizedObject(context);
} catch (e) {
debug.error('Context for key ${key} not passed to native SDK, because it contains non-serializable values', e);
}
if (normalizedContext) {
RNSentry.setContext(key, normalizedContext);
} else {
RNSentry.setContext(key, { error: '**non-serializable**' });
}
},
/**
* 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();
},
enableNativeFramesTracking(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
RNSentry.enableNativeFramesTracking();
},
isNativeAvailable(): boolean {
return this._isModuleLoaded(RNSentry);
},
async captureScreenshot(): Promise<Screenshot[] | null> {
if (!this.enableNative) {
debug.warn(this._DisabledNativeError);
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
debug.error(this._NativeClientError);
return null;
}
let raw: NativeScreenshot[] | null | undefined;
try {
raw = await RNSentry.captureScreenshot();
} catch (e) {
debug.warn('Failed to capture screenshot', e);
}
if (raw) {
return raw.map((item: NativeScreenshot) => ({
...item,
data: new Uint8Array(item.data),
}));
} else {
return null;
}
},
async fetchViewHierarchy(): Promise<Uint8Array | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const raw = await RNSentry.fetchViewHierarchy();
return raw ? new Uint8Array(raw) : null;
},
startProfiling(platformProfilers: boolean): boolean {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const { started, error } = RNSentry.startProfiling(platformProfilers);
if (started) {
debug.log('[NATIVE] Start Profiling');
} else {
debug.error('[NATIVE] Start Profiling Failed', error);
}
return !!started;
},
stopProfiling(): {
hermesProfile: Hermes.Profile;
nativeProfile?: NativeProfileEvent;
androidProfile?: NativeAndroidProfileEvent;
} | null {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const { profile, nativeProfile, androidProfile, error } = RNSentry.stopProfiling();
if (!profile || error) {
debug.error('[NATIVE] Stop Profiling Failed', error);
return null;
}
if (Platform.OS === 'ios' && !nativeProfile) {
debug.warn('[NATIVE] Stop Profiling Failed: No Native Profile');
}
if (Platform.OS === 'android' && !androidProfile) {
debug.warn('[NATIVE] Stop Profiling Failed: No Android Profile');
}
try {
return {
hermesProfile: JSON.parse(profile) as Hermes.Profile,
nativeProfile: nativeProfile as NativeProfileEvent | undefined,
androidProfile: androidProfile as NativeAndroidProfileEvent | undefined,
};
} catch (e) {
debug.error('[NATIVE] Failed to parse Hermes Profile JSON', e);
return null;
}
},
fetchNativePackageName(): string | null {
if (!this.enableNative) {
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
return null;
}
return RNSentry.fetchNativePackageName() || null;
},
fetchNativeStackFramesBy(instructionsAddr: number[]): NativeStackFrames | null {
if (!this.enableNative) {
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
return null;
}
return RNSentry.fetchNativeStackFramesBy(instructionsAddr) || null;
},
async initNativeReactNavigationNewFrameTracking(): Promise<void> {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
return RNSentry.initNativeReactNavigationNewFrameTracking();
},
async captureReplay(isHardCrash: boolean): Promise<string | null> {
if (!this.enableNative) {
debug.warn(`[NATIVE] \`${this.captureReplay.name}\` is not available when native is disabled.`);
return Promise.resolve(null);
}
if (!this._isModuleLoaded(RNSentry)) {
debug.warn(`[NATIVE] \`${this.captureReplay.name}\` is not available when native is not available.`);
return Promise.resolve(null);
}
return (await RNSentry.captureReplay(isHardCrash)) || null;
},
getCurrentReplayId(): string | null {
if (!this.enableNative) {
debug.warn(`[NATIVE] \`${this.getCurrentReplayId.name}\` is not available when native is disabled.`);
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
debug.warn(`[NATIVE] \`${this.getCurrentReplayId.name}\` is not available when native is not available.`);
return null;
}
return RNSentry.getCurrentReplayId() || null;
},
async crashedLastRun(): Promise<boolean | null> {
if (!this.enableNative) {
return null;
}
if (!this._isModuleLoaded(RNSentry)) {
return null;
}
const result = await RNSentry.crashedLastRun();
return typeof result === 'boolean' ? result : null;
},
getNewScreenTimeToDisplay(): Promise<number | null | undefined> {
if (!this.enableNative || !this._isModuleLoaded(RNSentry)) {
return Promise.resolve(null);
}
return RNSentry.getNewScreenTimeToDisplay();
},
async getDataFromUri(uri: string): Promise<Uint8Array | null> {
if (!this.enableNative || !this._isModuleLoaded(RNSentry)) {
return null;
}
try {
const data: number[] = await RNSentry.getDataFromUri(uri);
return new Uint8Array(data);
} catch (error) {
debug.error('Error:', error);
return null;
}
},
popTimeToDisplayFor(key: string): Promise<number | undefined | null> {
if (!this.enableNative || !this._isModuleLoaded(RNSentry)) {
return Promise.resolve(null);
}
try {
return RNSentry.popTimeToDisplayFor(key);
} catch (error) {
debug.error('Error:', error);
return Promise.resolve(null);
}
},
setActiveSpanId(spanId): void {
if (!this.enableNative || !this._isModuleLoaded(RNSentry)) {
return undefined;
}
try {
RNSentry.setActiveSpanId(spanId);
} catch (error) {
debug.error('Error:', error);
return undefined;
}
},
async encodeToBase64(data: Uint8Array): Promise<string | null> {
if (!this.enableNative || !this._isModuleLoaded(RNSentry)) {
return Promise.resolve(null);
}
try {
const byteArray = Array.from(data);
const base64 = await RNSentry.encodeToBase64(byteArray);
return base64 || null;
} catch (error) {
debug.error('Error:', error);
return Promise.resolve(null);
}
},
primitiveProcessor: function (value: Primitive): string {
return value as string;
},
/**
* Gets the event from envelopeItem and applies the level filter to the selected event.
* @param data An envelope item containing the event.
* @returns The event from envelopeItem or undefined.
*/
_processItem(item: EnvelopeItem): EnvelopeItem {
const [itemHeader, itemPayload] = item;
if (itemHeader.type == 'event' || itemHeader.type == 'transaction') {
const event = this._processLevels(itemPayload as Event);
if (NATIVE.platform === 'android') {
if ('message' in event) {
// @ts-expect-error Android still uses the old message object, without this the serialization of events will break.
event.message = { message: event.message };
}
}
return [itemHeader, event];
}
return item;
},
/**
* 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: SeverityLevel): SeverityLevel {
if (level == ('log' as SeverityLevel)) {
return 'debug' as SeverityLevel;
}
return level;
},
/**
* Checks whether the RNSentry module is loaded.
*/
_isModuleLoaded(module: Spec | undefined): module is Spec {
return !!module;
},
_setPrimitiveProcessor: function (processor: (value: Primitive) => any): void {
this.primitiveProcessor = processor;
},
_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,
};
/**
* Fethces the data from the given uri in Uint8Array format.
* @param uri string
* @returns Uint8Array | null
*/
export async function getDataFromUri(uri: string): Promise<Uint8Array | null> {
return NATIVE.getDataFromUri(uri);
}