Skip to content

Commit

Permalink
chore: Add prettier settings and run prettier on the repo (#2950)
Browse files Browse the repository at this point in the history
  • Loading branch information
AbhiPrasad authored Apr 3, 2023
1 parent e445a1b commit d7401ac
Show file tree
Hide file tree
Showing 81 changed files with 1,284 additions and 1,675 deletions.
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/test/react-native/versions

7 changes: 7 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"arrowParens": "avoid",
"printWidth": 120,
"proseWrap": "always",
"singleQuote": true,
"trailingComma": "all"
}
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
"build:tools": "tsc -p tsconfig.build.tools.json",
"clean": "rimraf dist coverage",
"test": "jest",
"lint": "eslint --config .eslintrc.js .",
"fix": "yarn fix:eslint && yarn fix:prettier",
"fix:eslint": "eslint --config .eslintrc.js --fix .",
"fix:prettier": "prettier --write \"{src,test,scripts}/**/**.ts\"",
"lint": "yarn lint:eslint && yarn lint:prettier",
"lint:eslint": "eslint --config .eslintrc.js .",
"lint:prettier": "prettier --check \"{src,test,scripts}/**/**.ts\"",
"test:watch": "jest --watch",
"run-ios": "cd sample && yarn react-native run-ios",
"run-android": "cd sample && yarn react-native run-android"
Expand Down
11 changes: 4 additions & 7 deletions src/js/NativeRNSentry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Package } from '@sentry/types';
import type { TurboModule} from 'react-native';
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
import type { UnsafeObject } from 'react-native/Libraries/Types/CodegenTypes';

Expand All @@ -10,7 +10,7 @@ export interface Spec extends TurboModule {
captureEnvelope(
bytes: number[],
options: {
store: boolean,
store: boolean;
},
): Promise<boolean>;
captureScreenshot(): Promise<NativeScreenshot[]>;
Expand All @@ -24,10 +24,7 @@ export interface Spec extends TurboModule {
fetchNativeAppStart(): Promise<NativeAppStartResponse | null>;
fetchNativeFrames(): Promise<NativeFramesResponse | null>;
initNativeSdk(options: UnsafeObject): Promise<boolean>;
setUser(
defaultUserKeys: UnsafeObject | null,
otherUserKeys: UnsafeObject | null
): void;
setUser(defaultUserKeys: UnsafeObject | null, otherUserKeys: UnsafeObject | null): void;
setContext(key: string, value: UnsafeObject | null): void;
setExtra(key: string, value: string): void;
setTag(key: string, value: string): void;
Expand Down Expand Up @@ -89,7 +86,7 @@ export type NativeScreenshot = {
data: number[];
contentType: string;
filename: string;
}
};

// The export must be here to pass codegen even if not used
export default TurboModuleRegistry.getEnforcing<Spec>('RNSentry');
4 changes: 2 additions & 2 deletions src/js/breadcrumb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const DEFAULT_BREADCRUMB_LEVEL: SeverityLevel = 'info';

type BreadcrumbCandidate = {
[K in keyof Partial<Breadcrumb>]: unknown;
}
};

/**
* Convert plain object to a valid Breadcrumb
Expand All @@ -32,7 +32,7 @@ export function breadcrumbFromObject(candidate: BreadcrumbCandidate): Breadcrumb
breadcrumb.data = candidate.data;
}
if (typeof candidate.timestamp === 'string') {
const timestamp = Date.parse(candidate.timestamp)
const timestamp = Date.parse(candidate.timestamp);
if (!isNaN(timestamp)) {
breadcrumb.timestamp = timestamp;
}
Expand Down
80 changes: 35 additions & 45 deletions src/js/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import { NATIVE } from './wrapper';
* @see SentryClient for usage documentation.
*/
export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {

private _outcomesBuffer: Outcome[];

/**
Expand All @@ -53,37 +52,31 @@ export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {
* @inheritDoc
*/
public eventFromException(exception: unknown, hint: EventHint = {}): PromiseLike<Event> {
return Screenshot.attachScreenshotToEventHint(hint, this._options)
.then(hintWithScreenshot => eventFromException(
this._options.stackParser,
exception,
hintWithScreenshot,
this._options.attachStacktrace,
));
return Screenshot.attachScreenshotToEventHint(hint, this._options).then(hintWithScreenshot =>
eventFromException(this._options.stackParser, exception, hintWithScreenshot, this._options.attachStacktrace),
);
}

/**
* @inheritDoc
*/
public eventFromMessage(message: string, level?: SeverityLevel, hint?: EventHint): PromiseLike<Event> {
return eventFromMessage(
this._options.stackParser,
message,
level,
hint,
this._options.attachStacktrace,
).then((event: Event) => {
// TMP! Remove this function once JS SDK uses threads for messages
if (!event.exception?.values || event.exception.values.length <= 0) {
return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace).then(
(event: Event) => {
// TMP! Remove this function once JS SDK uses threads for messages
if (!event.exception?.values || event.exception.values.length <= 0) {
return event;
}
const values = event.exception.values.map(
(exception: Exception): Thread => ({
stacktrace: exception.stacktrace,
}),
);
(event as { threads?: { values: Thread[] } }).threads = { values };
delete event.exception;
return event;
}
const values = event.exception.values.map((exception: Exception): Thread => ({
stacktrace: exception.stacktrace,
}));
(event as { threads?: { values: Thread[] } }).threads = { values };
delete event.exception;
return event;
});
},
);
}

/**
Expand All @@ -108,14 +101,11 @@ export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {
* Sends user feedback to Sentry.
*/
public captureUserFeedback(feedback: UserFeedback): void {
const envelope = createUserFeedbackEnvelope(
feedback,
{
metadata: this._options._metadata,
dsn: this.getDsn(),
tunnel: this._options.tunnel,
},
);
const envelope = createUserFeedbackEnvelope(feedback, {
metadata: this._options._metadata,
dsn: this.getDsn(),
tunnel: this._options.tunnel,
});
this._sendEnvelope(envelope);
}

Expand All @@ -125,7 +115,7 @@ export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {
public setupIntegrations(): void {
super.setupIntegrations();
const tracing = this.getIntegration(ReactNativeTracing);
const routingName = tracing?.options.routingInstrumentation?.name
const routingName = tracing?.options.routingInstrumentation?.name;
if (routingName) {
this.addIntegration(createIntegration(routingName));
}
Expand All @@ -144,16 +134,16 @@ export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {

let shouldClearOutcomesBuffer = true;
if (this._transport && this._dsn) {
this._transport.send(envelope)
.then(null, reason => {
if (reason instanceof SentryError) { // SentryError is thrown by SyncPromise
shouldClearOutcomesBuffer = false;
// If this is called asynchronously we want the _outcomesBuffer to be cleared
logger.error('SentryError while sending event, keeping outcomes buffer:', reason);
} else {
logger.error('Error while sending event:', reason);
}
});
this._transport.send(envelope).then(null, reason => {
if (reason instanceof SentryError) {
// SentryError is thrown by SyncPromise
shouldClearOutcomesBuffer = false;
// If this is called asynchronously we want the _outcomesBuffer to be cleared
logger.error('SentryError while sending event, keeping outcomes buffer:', reason);
} else {
logger.error('Error while sending event:', reason);
}
});
} else {
logger.error('Transport disabled');
}
Expand Down Expand Up @@ -189,7 +179,7 @@ export class ReactNativeClient extends BaseClient<ReactNativeClientOptions> {
if (__DEV__ && this._options.enableNativeNagger) {
Alert.alert(
'Sentry',
'Warning, could not connect to Sentry native SDK.\nIf you do not want to use the native component please pass `enableNative: false` in the options.\nVisit: https://docs.sentry.io/platforms/react-native/#linking for more details.'
'Warning, could not connect to Sentry native SDK.\nIf you do not want to use the native component please pass `enableNative: false` in the options.\nVisit: https://docs.sentry.io/platforms/react-native/#linking for more details.',
);
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ export {
withProfiler,
} from '@sentry/react';

export {
lastEventId,
} from '@sentry/browser';
export { lastEventId } from '@sentry/browser';

import * as Integrations from './integrations';
import { SDK_NAME, SDK_VERSION } from './version';
Expand Down
99 changes: 40 additions & 59 deletions src/js/integrations/debugsymbolicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import type { Event, EventHint, Integration, StackFrame } from '@sentry/types';
import { addContextToFrame, logger } from '@sentry/utils';

const INTERNAL_CALLSITES_REGEX = new RegExp(
['ReactNativeRenderer-dev\\.js$', 'MessageQueue\\.js$'].join('|')
);
const INTERNAL_CALLSITES_REGEX = new RegExp(['ReactNativeRenderer-dev\\.js$', 'MessageQueue\\.js$'].join('|'));

interface GetDevServer {
(): { url: string };
Expand Down Expand Up @@ -78,10 +76,7 @@ export class DebugSymbolicator implements Integration {
* Symbolicates the stack on the device talking to local dev server.
* Mutates the passed event.
*/
private async _symbolicate(
event: Event,
stack: string | undefined
): Promise<void> {
private async _symbolicate(event: Event, stack: string | undefined): Promise<void> {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const symbolicateStackTrace = require('react-native/Libraries/Core/Devtools/symbolicateStackTrace');
Expand All @@ -99,12 +94,10 @@ export class DebugSymbolicator implements Integration {
const stackWithoutInternalCallsites = newStack.filter(
(frame: { file?: string }) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
frame.file && frame.file.match(INTERNAL_CALLSITES_REGEX) === null
frame.file && frame.file.match(INTERNAL_CALLSITES_REGEX) === null,
);

const symbolicatedFrames = await this._convertReactNativeFramesToSentryFrames(
stackWithoutInternalCallsites
);
const symbolicatedFrames = await this._convertReactNativeFramesToSentryFrames(stackWithoutInternalCallsites);
this._replaceFramesInEvent(event, symbolicatedFrames);
} else {
logger.error('The stack is null');
Expand All @@ -120,9 +113,7 @@ export class DebugSymbolicator implements Integration {
* Converts ReactNativeFrames to frames in the Sentry format
* @param frames ReactNativeFrame[]
*/
private async _convertReactNativeFramesToSentryFrames(
frames: ReactNativeFrame[]
): Promise<StackFrame[]> {
private async _convertReactNativeFramesToSentryFrames(frames: ReactNativeFrame[]): Promise<StackFrame[]> {
let getDevServer: GetDevServer;
try {
getDevServer = require('react-native/Libraries/Core/Devtools/getDevServer');
Expand All @@ -132,44 +123,40 @@ export class DebugSymbolicator implements Integration {
// Below you will find lines marked with :HACK to prevent showing errors in the sentry ui
// But since this is a debug only feature: This is Fine (TM)
return Promise.all(
frames.map(
async (frame: ReactNativeFrame): Promise<StackFrame> => {
let inApp = !!frame.column && !!frame.lineNumber;
inApp =
inApp &&
frame.file !== undefined &&
!frame.file.includes('node_modules') &&
!frame.file.includes('native code');

const newFrame: StackFrame = {
colno: frame.column,
filename: frame.file,
function: frame.methodName,
in_app: inApp,
lineno: inApp ? frame.lineNumber : undefined, // :HACK
platform: inApp ? 'javascript' : 'node', // :HACK
};

// The upstream `react-native@0.61` delegates parsing of stacks to `stacktrace-parser`, which is buggy and
// leaves a trailing `(address at` in the function name.
// `react-native@0.62` seems to have custom logic to parse hermes frames specially.
// Anyway, all we do here is throw away the bogus suffix.
if (newFrame.function) {
const addressAtPos = newFrame.function.indexOf('(address at');
if (addressAtPos >= 0) {
newFrame.function = newFrame.function
.substr(0, addressAtPos)
.trim();
}
}

if (inApp) {
await this._addSourceContext(newFrame, getDevServer);
frames.map(async (frame: ReactNativeFrame): Promise<StackFrame> => {
let inApp = !!frame.column && !!frame.lineNumber;
inApp =
inApp &&
frame.file !== undefined &&
!frame.file.includes('node_modules') &&
!frame.file.includes('native code');

const newFrame: StackFrame = {
colno: frame.column,
filename: frame.file,
function: frame.methodName,
in_app: inApp,
lineno: inApp ? frame.lineNumber : undefined, // :HACK
platform: inApp ? 'javascript' : 'node', // :HACK
};

// The upstream `react-native@0.61` delegates parsing of stacks to `stacktrace-parser`, which is buggy and
// leaves a trailing `(address at` in the function name.
// `react-native@0.62` seems to have custom logic to parse hermes frames specially.
// Anyway, all we do here is throw away the bogus suffix.
if (newFrame.function) {
const addressAtPos = newFrame.function.indexOf('(address at');
if (addressAtPos >= 0) {
newFrame.function = newFrame.function.substr(0, addressAtPos).trim();
}
}

return newFrame;
if (inApp) {
await this._addSourceContext(newFrame, getDevServer);
}
)

return newFrame;
}),
);
}

Expand All @@ -195,23 +182,17 @@ export class DebugSymbolicator implements Integration {
* @param frame StackFrame
* @param getDevServer function from RN to get DevServer URL
*/
private async _addSourceContext(
frame: StackFrame,
getDevServer?: GetDevServer
): Promise<void> {
private async _addSourceContext(frame: StackFrame, getDevServer?: GetDevServer): Promise<void> {
let response;

const segments = frame.filename?.split('/') ?? [];

if (getDevServer) {
for (const idx in segments) {
if (Object.prototype.hasOwnProperty.call(segments, idx)) {
response = await fetch(
`${getDevServer().url}${segments.slice(-idx).join('/')}`,
{
method: 'GET',
}
);
response = await fetch(`${getDevServer().url}${segments.slice(-idx).join('/')}`, {
method: 'GET',
});

if (response.ok) {
break;
Expand Down
Loading

0 comments on commit d7401ac

Please sign in to comment.