-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathreact-native-wizard.ts
More file actions
506 lines (443 loc) · 15.1 KB
/
Copy pathreact-native-wizard.ts
File metadata and controls
506 lines (443 loc) · 15.1 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
/* eslint-disable max-lines */
// @ts-expect-error - clack is ESM and TS complains about that. It works though
import clack from '@clack/prompts';
import chalk from 'chalk';
import * as fs from 'fs';
import * as Sentry from '@sentry/node';
import { platform } from 'os';
import { podInstall } from './cocoapod';
import { traceStep, withTelemetry } from '../telemetry';
import { offerProjectScopedMcpConfig } from '../utils/clack/mcp-config';
import {
CliSetupConfigContent,
abort,
abortIfCancelled,
addSentryCliConfig,
confirmContinueIfNoOrDirtyGitRepo,
confirmContinueIfPackageVersionNotSupported,
ensurePackageIsInstalled,
getOrAskForProjectData,
getPackageDotJson,
installPackage,
printWelcome,
propertiesCliSetupConfig,
runPrettierIfInstalled,
} from '../utils/clack';
import { getPackageVersion, hasPackageInstalled } from '../utils/package-json';
import { getIssueStreamUrl } from '../utils/url';
import {
isExpoCNG,
patchExpoAppConfig,
printSentryExpoMigrationOutro,
} from './expo';
import { addExpoEnvLocal } from './expo-env-file';
import { addSentryToExpoMetroConfig } from './expo-metro';
import { APP_BUILD_GRADLE, XCODE_PROJECT, getFirstMatchedPath } from './glob';
import {
addRNSentryGradlePlugin,
doesAppBuildGradleIncludeRNSentryGradlePlugin,
writeAppBuildGradle,
} from './gradle';
import {
addSentryInit,
sessionReplayOnErrorSampleRate,
sessionReplaySampleRate,
wrapRootComponent,
} from './javascript';
import { patchMetroWithSentryConfig } from './metro';
import { ReactNativeWizardOptions } from './options';
import {
addDebugFilesUploadPhaseWithBundledScripts,
addSentryWithBundledScriptsToBundleShellScript,
findBundlePhase,
findDebugFilesUploadPhase,
getValidExistingBuildPhases,
patchBundlePhase,
writeXcodeProject,
} from './xcode';
import xcode from 'xcode';
import { abortIfSpotlightNotSupported } from '../utils/abort-if-sportlight-not-supported';
export const RN_SDK_PACKAGE = '@sentry/react-native';
export const RN_SDK_SUPPORTED_RANGE = '>=6.12.0';
export const RN_PACKAGE = 'react-native';
export const RN_HUMAN_NAME = 'React Native';
export const SUPPORTED_RN_RANGE = '>=0.69.0';
export const SUPPORTED_EXPO_RANGE = '>=50.0.0';
export type RNCliSetupConfigContent = Pick<
Required<CliSetupConfigContent>,
'authToken' | 'org' | 'project' | 'url'
>;
export async function runReactNativeWizard(
params: ReactNativeWizardOptions,
): Promise<void> {
return withTelemetry(
{
enabled: params.telemetryEnabled,
integration: 'react-native',
wizardOptions: params,
},
() => runReactNativeWizardWithTelemetry(params),
);
}
export async function runReactNativeWizardWithTelemetry(
options: ReactNativeWizardOptions,
): Promise<void> {
const { promoCode, telemetryEnabled, forceInstall } = options;
printWelcome({
wizardName: 'Sentry React Native Wizard',
promoCode,
telemetryEnabled,
});
await confirmContinueIfNoOrDirtyGitRepo({
ignoreGitChanges: options.ignoreGitChanges,
cwd: undefined,
});
const packageJson = await getPackageDotJson();
const hasInstalled = (dep: string) => hasPackageInstalled(dep, packageJson);
if (hasInstalled('sentry-expo')) {
Sentry.setTag('has-sentry-expo-installed', true);
printSentryExpoMigrationOutro();
return;
}
await ensurePackageIsInstalled(packageJson, RN_PACKAGE, RN_HUMAN_NAME);
const rnVersion = getPackageVersion(RN_PACKAGE, packageJson);
if (rnVersion) {
await confirmContinueIfPackageVersionNotSupported({
packageName: RN_HUMAN_NAME,
packageVersion: rnVersion,
packageId: RN_PACKAGE,
acceptableVersions: SUPPORTED_RN_RANGE,
note: `Please upgrade to ${SUPPORTED_RN_RANGE} if you wish to use the Sentry Wizard.
Or setup using ${chalk.cyan(
'https://docs.sentry.io/platforms/react-native/manual-setup/manual-setup/',
)}`,
});
}
await installPackage({
packageName: RN_SDK_PACKAGE,
alreadyInstalled: hasPackageInstalled(RN_SDK_PACKAGE, packageJson),
forceInstall,
});
const sdkVersion = getPackageVersion(
RN_SDK_PACKAGE,
await getPackageDotJson(),
);
if (sdkVersion) {
await confirmContinueIfPackageVersionNotSupported({
packageName: 'Sentry React Native SDK',
packageVersion: sdkVersion,
packageId: RN_SDK_PACKAGE,
acceptableVersions: RN_SDK_SUPPORTED_RANGE,
note: `Please upgrade to ${RN_SDK_SUPPORTED_RANGE} to continue with the wizard in this project.`,
});
} else {
const continueWithoutSdk = await abortIfCancelled(
clack.confirm({
message:
'Could not detect Sentry React Native SDK version. Do you want to continue anyway?',
}),
);
if (!continueWithoutSdk) {
await abort(undefined, 0);
}
}
Sentry.setTag(`detected-sentry-react-native-sdk-version`, sdkVersion);
const expoVersion = getPackageVersion('expo', packageJson);
const isExpo = !!expoVersion;
if (expoVersion) {
await confirmContinueIfPackageVersionNotSupported({
packageName: 'Expo SDK',
packageVersion: expoVersion,
packageId: 'expo',
acceptableVersions: SUPPORTED_EXPO_RANGE,
note: `Please upgrade to ${SUPPORTED_EXPO_RANGE} to continue with the wizard in this Expo project.`,
});
}
const projectData = await getOrAskForProjectData(options, 'react-native');
if (projectData.spotlight) {
return abortIfSpotlightNotSupported('React Native');
}
const { selectedProject, authToken, sentryUrl } = projectData;
const orgSlug = selectedProject.organization.slug;
const projectSlug = selectedProject.slug;
const projectId = selectedProject.id;
const cliConfig: RNCliSetupConfigContent = {
authToken,
org: orgSlug,
project: projectSlug,
url: sentryUrl,
};
// Ask if user wants to enable Session Replay
const enableSessionReplay = await abortIfCancelled(
clack.confirm({
message:
'Do you want to enable Session Replay to help debug issues? (See https://docs.sentry.io/platforms/react-native/session-replay/)',
}),
);
Sentry.setTag('enable-session-replay', enableSessionReplay);
if (enableSessionReplay) {
clack.log.info(
`Session Replay will be enabled with default settings (replaysSessionSampleRate: ${sessionReplaySampleRate}, replaysOnErrorSampleRate: ${sessionReplayOnErrorSampleRate}).`,
);
clack.log.message(
'By default, all text content, images, and webviews will be masked for privacy. You can customize this in your code later.',
);
}
// Ask if user wants to enable the Feedback Widget
const enableFeedbackWidget = await abortIfCancelled(
clack.confirm({
message:
'Do you want to enable the Feedback Widget to collect feedback from your users? (See https://docs.sentry.io/platforms/react-native/user-feedback/)',
}),
);
Sentry.setTag('enable-feedback-widget', enableFeedbackWidget);
if (enableFeedbackWidget) {
clack.log.info(
`The Feedback Widget will be enabled with default settings. You can show the widget by calling Sentry.showFeedbackWidget() in your code.`,
);
}
// Ask if user wants to enable Logs
const enableLogs = await abortIfCancelled(
clack.confirm({
message:
'Do you want to enable Logs? (See https://docs.sentry.io/platforms/react-native/logs/)',
}),
);
Sentry.setTag('enable-logs', enableLogs);
if (enableLogs) {
clack.log.info(
`Logs will be enabled with default settings. You can send logs using the Sentry.logger APIs.`,
);
}
await traceStep('patch-app-js', () =>
addSentryInit({
dsn: selectedProject.keys[0].dsn.public,
enableSessionReplay,
enableFeedbackWidget,
enableLogs,
}),
);
await traceStep('patch-app-js-wrap', () => wrapRootComponent());
if (isExpo) {
await traceStep('patch-expo-app-config', () =>
patchExpoAppConfig(cliConfig),
);
await traceStep('add-expo-env-local', () => addExpoEnvLocal(cliConfig));
}
if (isExpo) {
await traceStep('patch-metro-config', addSentryToExpoMetroConfig);
} else {
await traceStep('patch-metro-config', patchMetroWithSentryConfig);
}
if (isExpo && (await isExpoCNG())) {
Sentry.setTag('expo-cng', true);
clack.log.info(
`Detected Expo Continuous Native Generation (CNG) setup. Skipping native files patching.`,
);
} else {
if (fs.existsSync('ios')) {
Sentry.setTag('patch-ios', true);
await traceStep('patch-xcode-files', () => patchXcodeFiles(cliConfig));
}
if (fs.existsSync('android')) {
Sentry.setTag('patch-android', true);
await traceStep('patch-android-files', () =>
patchAndroidFiles(cliConfig),
);
}
}
await runPrettierIfInstalled({ cwd: undefined });
// Offer optional project-scoped MCP config for Sentry with org and project scope
await offerProjectScopedMcpConfig(
selectedProject.organization.slug,
selectedProject.slug,
);
const confirmedFirstException = await confirmFirstSentryException(
sentryUrl,
orgSlug,
projectId,
);
Sentry.setTag('user-confirmed-first-error', confirmedFirstException);
if (confirmedFirstException) {
clack.outro(
`${chalk.green('Everything is set up!')}
${chalk.dim(
'If you encounter any issues, let us know here: https://github.com/getsentry/sentry-react-native/issues',
)}`,
);
} else {
clack.outro(
`${chalk.dim(
'Let us know here: https://github.com/getsentry/sentry-react-native/issues',
)}`,
);
}
}
async function confirmFirstSentryException(
url: string,
orgSlug: string,
projectId: string,
) {
const issuesStreamUrl = getIssueStreamUrl({ url, orgSlug, projectId });
clack.log
.step(`To make sure everything is set up correctly, put the following code snippet into your application.
The snippet will create a button that, when tapped, sends a test event to Sentry.
After that check your project issues:
${chalk.cyan(issuesStreamUrl)}`);
// We want the code snippet to be easily copy-pasteable, without any clack artifacts
// eslint-disable-next-line no-console
console.log(
chalk.greenBright(`
<Button title='Try!' onPress={ () => { Sentry.captureException(new Error('First error')) }}/>
`),
);
const firstErrorConfirmed = clack.confirm({
message: `Have you successfully sent a test event?`,
});
return firstErrorConfirmed;
}
async function patchXcodeFiles(config: RNCliSetupConfigContent) {
await addSentryCliConfig(config, {
...propertiesCliSetupConfig,
name: 'source maps and iOS debug files',
filename: 'ios/sentry.properties',
gitignore: false,
});
if (platform() === 'darwin' && (await confirmPodInstall())) {
await traceStep('pod-install', () => podInstall('ios'));
}
const xcodeProjectPath = traceStep('find-xcode-project', () =>
getFirstMatchedPath(XCODE_PROJECT),
);
Sentry.setTag(
'xcode-project-status',
xcodeProjectPath ? 'found' : 'not-found',
);
if (!xcodeProjectPath) {
clack.log.warn(
`Could not find Xcode project file using ${chalk.cyan(XCODE_PROJECT)}.`,
);
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const [xcodeProject, buildPhasesMap] = traceStep(
'parse-xcode-project',
() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
const project = xcode.project(xcodeProjectPath);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
project.parseSync();
const map = getValidExistingBuildPhases(project);
return [project, map];
},
);
Sentry.setTag('xcode-project-status', 'parsed');
await traceStep('patch-bundle-phase', async () => {
const bundlePhase = findBundlePhase(buildPhasesMap);
Sentry.setTag(
'xcode-bundle-phase-status',
bundlePhase ? 'found' : 'not-found',
);
await patchBundlePhase(
bundlePhase,
addSentryWithBundledScriptsToBundleShellScript,
);
Sentry.setTag('xcode-bundle-phase-status', 'patched');
});
traceStep('add-debug-files-upload-phase', () => {
const debugFilesUploadPhaseExists =
!!findDebugFilesUploadPhase(buildPhasesMap);
Sentry.setTag(
'xcode-debug-files-upload-phase-status',
debugFilesUploadPhaseExists ? 'already-exists' : undefined,
);
addDebugFilesUploadPhaseWithBundledScripts(xcodeProject, {
debugFilesUploadPhaseExists,
});
Sentry.setTag('xcode-debug-files-upload-phase-status', 'added');
});
traceStep('write-xcode-project', () => {
writeXcodeProject(xcodeProjectPath, xcodeProject);
});
Sentry.setTag('xcode-project-status', 'patched');
}
async function patchAndroidFiles(config: RNCliSetupConfigContent) {
await addSentryCliConfig(config, {
...propertiesCliSetupConfig,
name: 'source maps and iOS debug files',
filename: 'android/sentry.properties',
gitignore: false,
});
const appBuildGradlePath = traceStep('find-app-build-gradle', () =>
getFirstMatchedPath(APP_BUILD_GRADLE),
);
Sentry.setTag(
'app-build-gradle-status',
appBuildGradlePath ? 'found' : 'not-found',
);
if (!appBuildGradlePath) {
clack.log.warn(
`Could not find Android ${chalk.cyan(
'app/build.gradle',
)} file using ${chalk.cyan(APP_BUILD_GRADLE)}.`,
);
return;
}
const appBuildGradle = traceStep('read-app-build-gradle', () =>
fs.readFileSync(appBuildGradlePath, 'utf-8'),
);
const includesSentry =
doesAppBuildGradleIncludeRNSentryGradlePlugin(appBuildGradle);
if (includesSentry) {
Sentry.setTag('app-build-gradle-status', 'already-includes-sentry');
clack.log.warn(
`Android ${chalk.cyan('app/build.gradle')} file already includes Sentry.`,
);
return;
}
const patchedAppBuildGradle = traceStep('add-rn-sentry-gradle-plugin', () =>
addRNSentryGradlePlugin(appBuildGradle),
);
if (!doesAppBuildGradleIncludeRNSentryGradlePlugin(patchedAppBuildGradle)) {
Sentry.setTag(
'app-build-gradle-status',
'failed-to-add-rn-sentry-gradle-plugin',
);
clack.log.warn(
`Could not add Sentry RN Gradle Plugin to ${chalk.cyan(
'app/build.gradle',
)}.`,
);
return;
}
Sentry.setTag('app-build-gradle-status', 'added-rn-sentry-gradle-plugin');
clack.log.success(
`Added Sentry RN Gradle Plugin to ${chalk.bold('app/build.gradle')}.`,
);
traceStep('write-app-build-gradle', () =>
writeAppBuildGradle(appBuildGradlePath, patchedAppBuildGradle),
);
clack.log.success(
chalk.green(`Android ${chalk.cyan('app/build.gradle')} saved.`),
);
}
async function confirmPodInstall(): Promise<boolean> {
return traceStep('confirm-pod-install', async () => {
const continueWithPodInstall = await abortIfCancelled(
clack.select({
message: 'Do you want to run `pod install` now?',
options: [
{
value: true,
label: 'Yes',
hint: 'Recommended for smaller projects, this might take several minutes',
},
{ value: false, label: `No, I'll do it later` },
],
initialValue: true,
}),
);
Sentry.setTag('continue-with-pod-install', continueWithPodInstall);
return continueWithPodInstall;
});
}