-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathindex.ts
600 lines (539 loc) · 21.1 KB
/
index.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
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
import SentryCli from "@sentry/cli";
import { transformAsync } from "@babel/core";
import componentNameAnnotatePlugin from "@sentry/babel-plugin-component-annotate";
import * as fs from "fs";
import * as path from "path";
import MagicString from "magic-string";
import { createUnplugin, TransformResult, UnpluginOptions } from "unplugin";
import { normalizeUserOptions, validateOptions } from "./options-mapping";
import { createDebugIdUploadFunction } from "./debug-id-upload";
import { releaseManagementPlugin } from "./plugins/release-management";
import { telemetryPlugin } from "./plugins/telemetry";
import { createLogger, Logger } from "./sentry/logger";
import { allowedToSendTelemetry, createSentryInstance } from "./sentry/telemetry";
import { Options, SentrySDKBuildFlags } from "./types";
import {
generateGlobalInjectorCode,
generateModuleMetadataInjectorCode,
getDependencies,
getPackageJson,
parseMajorVersion,
replaceBooleanFlagsInCode,
stringToUUID,
stripQueryAndHashFromPath,
} from "./utils";
import * as dotenv from "dotenv";
import { glob } from "glob";
import { logger } from "@sentry/utils";
interface SentryUnpluginFactoryOptions {
releaseInjectionPlugin: (injectionCode: string) => UnpluginOptions;
componentNameAnnotatePlugin?: () => UnpluginOptions;
moduleMetadataInjectionPlugin: (injectionCode: string) => UnpluginOptions;
debugIdInjectionPlugin: (logger: Logger) => UnpluginOptions;
debugIdUploadPlugin: (upload: (buildArtifacts: string[]) => Promise<void>) => UnpluginOptions;
bundleSizeOptimizationsPlugin: (buildFlags: SentrySDKBuildFlags) => UnpluginOptions;
}
/**
* The sentry bundler plugin concerns itself with two things:
* - Release injection
* - Sourcemaps upload
*
* Release injection:
* Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
* that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector;"`)
* to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
* by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
* If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
*
* Source maps upload:
*
* The sentry bundler plugin will also take care of uploading source maps to Sentry. This
* is all done in the `writeBundle` hook. In this hook the sentry plugin will execute the
* release creation pipeline:
*
* 1. Create a new release
* 2. Upload sourcemaps based on `include` and source-map-specific options
* 3. Associate a range of commits with the release (if `setCommits` is specified)
* 4. Finalize the release (unless `finalize` is disabled)
* 5. Add deploy information to the release (if `deploy` is specified)
*
* This release creation pipeline relies on Sentry CLI to execute the different steps.
*/
export function sentryUnpluginFactory({
releaseInjectionPlugin,
componentNameAnnotatePlugin,
moduleMetadataInjectionPlugin,
debugIdInjectionPlugin,
debugIdUploadPlugin,
bundleSizeOptimizationsPlugin,
}: SentryUnpluginFactoryOptions) {
return createUnplugin<Options | undefined, true>((userOptions = {}, unpluginMetaContext) => {
const logger = createLogger({
prefix:
userOptions._metaOptions?.loggerPrefixOverride ??
`[sentry-${unpluginMetaContext.framework}-plugin]`,
silent: userOptions.silent ?? false,
debug: userOptions.debug ?? false,
});
try {
const dotenvFile = fs.readFileSync(
path.join(process.cwd(), ".env.sentry-build-plugin"),
"utf-8"
);
// NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.
const dotenvResult = dotenv.parse(dotenvFile);
process.env = { ...process.env, ...dotenvResult };
logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
} catch (e: unknown) {
// Ignore "file not found" errors but throw all others
if (typeof e === "object" && e && "code" in e && e.code !== "ENOENT") {
throw e;
}
}
const options = normalizeUserOptions(userOptions);
// TODO(v3): Remove this warning
if (userOptions._experiments?.moduleMetadata) {
logger.warn(
"The `_experiments.moduleMetadata` option has been promoted to being stable. You can safely move the option out of the `_experiments` object scope."
);
}
if (unpluginMetaContext.watchMode || options.disable) {
return [
{
name: "sentry-noop-plugin",
},
];
}
const shouldSendTelemetry = allowedToSendTelemetry(options);
const { sentryHub, sentryClient } = createSentryInstance(
options,
shouldSendTelemetry,
unpluginMetaContext.framework
);
const sentrySession = sentryHub.startSession();
sentryHub.captureSession();
let sentEndSession = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
// We also need to manually end sesisons on errors because beforeExit is not called on crashes
process.on("beforeExit", () => {
if (!sentEndSession) {
sentryHub.endSession();
sentEndSession = true;
}
});
// Set the User-Agent that Sentry CLI will use when interacting with Sentry
process.env[
"SENTRY_PIPELINE"
] = `${unpluginMetaContext.framework}-plugin/${__PACKAGE_VERSION__}`;
function handleRecoverableError(unknownError: unknown) {
sentrySession.status = "abnormal";
try {
if (options.errorHandler) {
try {
if (unknownError instanceof Error) {
options.errorHandler(unknownError);
} else {
options.errorHandler(new Error("An unknown error occured"));
}
} catch (e) {
sentrySession.status = "crashed";
throw e;
}
} else {
sentrySession.status = "crashed";
throw unknownError;
}
} finally {
sentryHub.endSession();
}
}
if (!validateOptions(options, logger)) {
handleRecoverableError(
new Error("Options were not set correctly. See output above for more details.")
);
}
if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) {
logger.warn(
"Running Sentry plugin from within a `node_modules` folder. Some features may not work."
);
}
const plugins: UnpluginOptions[] = [];
plugins.push(
telemetryPlugin({
sentryClient,
sentryHub,
logger,
shouldSendTelemetry,
})
);
if (options.bundleSizeOptimizations) {
const { bundleSizeOptimizations } = options;
const replacementValues: SentrySDKBuildFlags = {};
if (bundleSizeOptimizations.excludeDebugStatements) {
replacementValues["__SENTRY_DEBUG__"] = false;
}
if (bundleSizeOptimizations.excludePerformanceMonitoring) {
replacementValues["__SENTRY_TRACE__"] = false;
}
if (bundleSizeOptimizations.excludeReplayCanvas) {
replacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
}
if (bundleSizeOptimizations.excludeReplayIframe) {
replacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
}
if (bundleSizeOptimizations.excludeReplayShadowDom) {
replacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
}
if (bundleSizeOptimizations.excludeReplayWorker) {
replacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
}
if (Object.keys(replacementValues).length > 0) {
plugins.push(bundleSizeOptimizationsPlugin(replacementValues));
}
}
if (!options.release.inject) {
logger.debug(
"Release injection disabled via `release.inject` option. Will not inject release."
);
} else if (!options.release.name) {
logger.warn(
"No release name provided. Will not inject release. Please set the `release.name` option to identify your release."
);
} else {
const injectionCode = generateGlobalInjectorCode({
release: options.release.name,
injectBuildInformation: options._experiments.injectBuildInformation || false,
});
plugins.push(releaseInjectionPlugin(injectionCode));
}
if (options.moduleMetadata) {
let metadata: Record<string, unknown>;
if (typeof options.moduleMetadata === "function") {
const args = {
org: options.org,
project: options.project,
release: options.release.name,
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
metadata = options.moduleMetadata(args);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
metadata = options.moduleMetadata;
}
const injectionCode = generateModuleMetadataInjectorCode(metadata);
plugins.push(moduleMetadataInjectionPlugin(injectionCode));
}
if (!options.release.name) {
logger.warn(
"No release name provided. Will not create release. Please set the `release.name` option to identify your release."
);
} else if (!options.authToken) {
logger.warn(
"No auth token provided. Will not create release. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/"
);
} else if (!options.org && !options.authToken.startsWith("sntrys_")) {
logger.warn(
"No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug."
);
} else if (!options.project) {
logger.warn(
"No project provided. Will not create release. Please set the `project` option to your Sentry project slug."
);
} else {
plugins.push(
releaseManagementPlugin({
logger,
releaseName: options.release.name,
shouldCreateRelease: options.release.create,
shouldFinalizeRelease: options.release.finalize,
include: options.release.uploadLegacySourcemaps,
setCommitsOption: options.release.setCommits,
deployOptions: options.release.deploy,
dist: options.release.dist,
handleRecoverableError: handleRecoverableError,
sentryHub,
sentryClient,
sentryCliOptions: {
authToken: options.authToken,
org: options.org,
project: options.project,
silent: options.silent,
url: options.url,
vcsRemote: options.release.vcsRemote,
headers: options.headers,
},
})
);
}
plugins.push(debugIdInjectionPlugin(logger));
if (!options.authToken) {
logger.warn(
"No auth token provided. Will not upload source maps. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/"
);
} else if (!options.org && !options.authToken.startsWith("sntrys_")) {
logger.warn(
"No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug."
);
} else if (!options.project) {
logger.warn(
"No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug."
);
} else {
plugins.push(
debugIdUploadPlugin(
createDebugIdUploadFunction({
assets: options.sourcemaps?.assets,
ignore: options.sourcemaps?.ignore,
filesToDeleteAfterUpload:
options.sourcemaps?.filesToDeleteAfterUpload ??
options.sourcemaps?.deleteFilesAfterUpload,
dist: options.release.dist,
releaseName: options.release.name,
logger: logger,
handleRecoverableError: handleRecoverableError,
rewriteSourcesHook: options.sourcemaps?.rewriteSources,
sentryHub,
sentryClient,
sentryCliOptions: {
authToken: options.authToken,
org: options.org,
project: options.project,
silent: options.silent,
url: options.url,
vcsRemote: options.release.vcsRemote,
headers: options.headers,
},
})
)
);
}
if (options.reactComponentAnnotation) {
if (!options.reactComponentAnnotation.enabled) {
logger.debug(
"The component name annotate plugin is currently disabled. Skipping component name annotations."
);
} else if (options.reactComponentAnnotation.enabled && !componentNameAnnotatePlugin) {
logger.warn(
"The component name annotate plugin is currently not supported by '@sentry/esbuild-plugin'"
);
} else {
componentNameAnnotatePlugin && plugins.push(componentNameAnnotatePlugin());
}
}
return plugins;
});
}
export function getBuildInformation() {
const packageJson = getPackageJson();
const { deps, depsVersions } = packageJson
? getDependencies(packageJson)
: { deps: [], depsVersions: {} };
return {
deps,
depsVersions,
nodeVersion: parseMajorVersion(process.version),
};
}
/**
* Determines whether the Sentry CLI binary is in its expected location.
* This function is useful since `@sentry/cli` installs the binary via a post-install
* script and post-install scripts may not always run. E.g. with `npm i --ignore-scripts`.
*/
export function sentryCliBinaryExists(): boolean {
return fs.existsSync(SentryCli.getPath());
}
export function createRollupReleaseInjectionHooks(injectionCode: string) {
const virtualReleaseInjectionFileId = "\0sentry-release-injection-file";
return {
resolveId(id: string) {
if (id === virtualReleaseInjectionFileId) {
return {
id: virtualReleaseInjectionFileId,
external: false,
moduleSideEffects: true,
};
} else {
return null;
}
},
load(id: string) {
if (id === virtualReleaseInjectionFileId) {
return injectionCode;
} else {
return null;
}
},
transform(code: string, id: string) {
if (id === virtualReleaseInjectionFileId) {
return null;
}
// id may contain query and hash which will trip up our file extension logic below
const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);
if (idWithoutQueryAndHash.match(/\\node_modules\\|\/node_modules\//)) {
return null;
}
if (
![".js", ".ts", ".jsx", ".tsx", ".mjs"].some((ending) =>
idWithoutQueryAndHash.endsWith(ending)
)
) {
return null;
}
const ms = new MagicString(code);
// Appending instead of prepending has less probability of mucking with user's source maps.
// Luckily import statements get hoisted to the top anyways.
ms.append(`\n\n;import "${virtualReleaseInjectionFileId}";`);
return {
code: ms.toString(),
map: ms.generateMap({ hires: "boundary" }),
};
},
};
}
export function createRollupBundleSizeOptimizationHooks(replacementValues: SentrySDKBuildFlags) {
return {
transform(code: string) {
return replaceBooleanFlagsInCode(code, replacementValues);
},
};
}
// We need to be careful not to inject the snippet before any `"use strict";`s.
// As an additional complication `"use strict";`s may come after any number of comments.
const COMMENT_USE_STRICT_REGEX =
// Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.
/^(?:\s*|\/\*(?:.|\r|\n)*?\*\/|\/\/.*[\n\r])*(?:"[^"]*";|'[^']*';)?/;
export function createRollupDebugIdInjectionHooks() {
return {
renderChunk(code: string, chunk: { fileName: string }) {
if (
[".js", ".mjs", ".cjs"].some((ending) => chunk.fileName.endsWith(ending)) // chunks could be any file (html, md, ...)
) {
const debugId = stringToUUID(code); // generate a deterministic debug ID
const codeToInject = getDebugIdSnippet(debugId);
const ms = new MagicString(code, { filename: chunk.fileName });
const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];
if (match) {
// Add injected code after any comments or "use strict" at the beginning of the bundle.
ms.appendLeft(match.length, codeToInject);
} else {
// ms.replace() doesn't work when there is an empty string match (which happens if
// there is neither, a comment, nor a "use strict" at the top of the chunk) so we
// need this special case here.
ms.prepend(codeToInject);
}
return {
code: ms.toString(),
map: ms.generateMap({ file: chunk.fileName, hires: "boundary" }),
};
} else {
return null; // returning null means not modifying the chunk at all
}
},
};
}
export function createRollupModuleMetadataInjectionHooks(injectionCode: string) {
return {
renderChunk(code: string, chunk: { fileName: string }) {
if (
[".js", ".mjs", ".cjs"].some((ending) => chunk.fileName.endsWith(ending)) // chunks could be any file (html, md, ...)
) {
const ms = new MagicString(code, { filename: chunk.fileName });
const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];
if (match) {
// Add injected code after any comments or "use strict" at the beginning of the bundle.
ms.appendLeft(match.length, injectionCode);
} else {
// ms.replace() doesn't work when there is an empty string match (which happens if
// there is neither, a comment, nor a "use strict" at the top of the chunk) so we
// need this special case here.
ms.prepend(injectionCode);
}
return {
code: ms.toString(),
map: ms.generateMap({ file: chunk.fileName, hires: "boundary" }),
};
} else {
return null; // returning null means not modifying the chunk at all
}
},
};
}
export function createRollupDebugIdUploadHooks(
upload: (buildArtifacts: string[]) => Promise<void>
) {
return {
async writeBundle(
outputOptions: { dir?: string; file?: string },
bundle: { [fileName: string]: unknown }
) {
if (outputOptions.dir) {
const outputDir = outputOptions.dir;
const buildArtifacts = await glob(
["/**/*.js", "/**/*.mjs", "/**/*.cjs", "/**/*.js.map", "/**/*.mjs.map", "/**/*.cjs.map"],
{
root: outputDir,
absolute: true,
nodir: true,
}
);
await upload(buildArtifacts);
} else if (outputOptions.file) {
await upload([outputOptions.file]);
} else {
const buildArtifacts = Object.keys(bundle).map((asset) => path.join(path.resolve(), asset));
await upload(buildArtifacts);
}
},
};
}
export function createComponentNameAnnotateHooks() {
type ParserPlugins = NonNullable<
NonNullable<Parameters<typeof transformAsync>[1]>["parserOpts"]
>["plugins"];
return {
async transform(this: void, code: string, id: string): Promise<TransformResult> {
// id may contain query and hash which will trip up our file extension logic below
const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);
if (idWithoutQueryAndHash.match(/\\node_modules\\|\/node_modules\//)) {
return null;
}
// We will only apply this plugin on jsx and tsx files
if (![".jsx", ".tsx"].some((ending) => idWithoutQueryAndHash.endsWith(ending))) {
return null;
}
const parserPlugins: ParserPlugins = [];
if (idWithoutQueryAndHash.endsWith(".jsx")) {
parserPlugins.push("jsx");
} else if (idWithoutQueryAndHash.endsWith(".tsx")) {
parserPlugins.push("jsx", "typescript");
}
try {
const result = await transformAsync(code, {
plugins: [[componentNameAnnotatePlugin]],
filename: id,
parserOpts: {
sourceType: "module",
allowAwaitOutsideFunction: true,
plugins: parserPlugins,
},
generatorOpts: {
decoratorsBeforeExport: true,
},
sourceMaps: true,
});
return {
code: result?.code ?? code,
map: result?.map,
};
} catch (e) {
logger.error(`Failed to apply react annotate plugin`, e);
}
return { code };
},
};
}
export function getDebugIdSnippet(debugId: string): string {
return `;!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${debugId}",e._sentryDebugIdIdentifier="sentry-dbid-${debugId}")}catch(e){}}();`;
}
export { stringToUUID, replaceBooleanFlagsInCode } from "./utils";
export type { Options, SentrySDKBuildFlags } from "./types";
export type { Logger } from "./sentry/logger";