forked from getsentry/sentry-javascript-bundler-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
457 lines (410 loc) · 15.7 KB
/
index.ts
File metadata and controls
457 lines (410 loc) · 15.7 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
import { transformAsync } from "@babel/core";
import componentNameAnnotatePlugin from "@sentry/babel-plugin-component-annotate";
import SentryCli from "@sentry/cli";
import { logger } from "@sentry/utils";
import * as fs from "fs";
import { glob } from "glob";
import MagicString, { SourceMap } from "magic-string";
import * as path from "path";
import { createUnplugin, TransformResult, UnpluginInstance, UnpluginOptions } from "unplugin";
import { createSentryBuildPluginManager } from "./build-plugin-manager";
import { createDebugIdUploadFunction } from "./debug-id-upload";
import { Logger } from "./logger";
import { Options, SentrySDKBuildFlags } from "./types";
import {
containsOnlyImports,
generateGlobalInjectorCode,
generateModuleMetadataInjectorCode,
replaceBooleanFlagsInCode,
stringToUUID,
stripQueryAndHashFromPath,
} from "./utils";
type InjectionPlugin = (
injectionCode: string,
debugIds: boolean,
logger: Logger
) => UnpluginOptions;
type LegacyPlugins = {
releaseInjectionPlugin: (injectionCode: string) => UnpluginOptions;
moduleMetadataInjectionPlugin: (injectionCode: string) => UnpluginOptions;
debugIdInjectionPlugin: (logger: Logger) => UnpluginOptions;
};
interface SentryUnpluginFactoryOptions {
injectionPlugin: InjectionPlugin | LegacyPlugins;
componentNameAnnotatePlugin?: (ignoredComponents?: string[]) => UnpluginOptions;
debugIdUploadPlugin: (
upload: (buildArtifacts: string[]) => Promise<void>,
logger: Logger,
createDependencyOnBuildArtifacts: () => () => void,
webpack_forceExitOnBuildComplete?: boolean
) => UnpluginOptions;
bundleSizeOptimizationsPlugin: (buildFlags: SentrySDKBuildFlags) => UnpluginOptions;
}
/**
* Creates an unplugin instance used to create Sentry plugins for Vite, Rollup, esbuild, and Webpack.
*/
export function sentryUnpluginFactory({
injectionPlugin,
componentNameAnnotatePlugin,
debugIdUploadPlugin,
bundleSizeOptimizationsPlugin,
}: SentryUnpluginFactoryOptions): UnpluginInstance<Options | undefined, true> {
return createUnplugin<Options | undefined, true>((userOptions = {}, unpluginMetaContext) => {
const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {
loggerPrefix:
userOptions._metaOptions?.loggerPrefixOverride ??
`[sentry-${unpluginMetaContext.framework}-plugin]`,
buildTool: unpluginMetaContext.framework,
});
const {
logger,
normalizedOptions: options,
bundleSizeOptimizationReplacementValues,
} = sentryBuildPluginManager;
if (options.disable) {
return [
{
name: "sentry-noop-plugin",
},
];
}
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[] = [];
// Add plugin to emit a telemetry signal when the build starts
plugins.push({
name: "sentry-telemetry-plugin",
buildStart() {
// Technically, for very fast builds we might miss the telemetry signal
// but it's okay because telemetry is not critical for us.
// We cannot await the flush here because it would block the build start
// which in turn would break module federation builds, see
// https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/816
void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {
// Nothing for the users to do here. If telemetry fails it's acceptable.
});
},
});
if (Object.keys(bundleSizeOptimizationReplacementValues).length > 0) {
plugins.push(bundleSizeOptimizationsPlugin(bundleSizeOptimizationReplacementValues));
}
let injectionCode = "";
if (!options.release.inject) {
logger.debug(
"Release injection disabled via `release.inject` option. Will not inject release."
);
} else if (!options.release.name) {
logger.debug(
"No release name provided. Will not inject release. Please set the `release.name` option to identify your release."
);
} else {
const code = generateGlobalInjectorCode({
release: options.release.name,
injectBuildInformation: options._experiments.injectBuildInformation || false,
});
if (typeof injectionPlugin !== "function") {
plugins.push(injectionPlugin.releaseInjectionPlugin(code));
} else {
injectionCode += code;
}
}
if (Object.keys(sentryBuildPluginManager.bundleMetadata).length > 0) {
const code = generateModuleMetadataInjectorCode(sentryBuildPluginManager.bundleMetadata);
if (typeof injectionPlugin !== "function") {
plugins.push(injectionPlugin.moduleMetadataInjectionPlugin(code));
} else {
injectionCode += code;
}
}
if (
typeof injectionPlugin === "function" &&
(injectionCode !== "" || options.sourcemaps?.disable !== true)
) {
plugins.push(injectionPlugin(injectionCode, options.sourcemaps?.disable !== true, logger));
}
// Add plugin to create and finalize releases, and also take care of adding commits and legacy sourcemaps
const freeGlobalDependencyOnBuildArtifacts =
sentryBuildPluginManager.createDependencyOnBuildArtifacts();
plugins.push({
name: "sentry-release-management-plugin",
async writeBundle() {
try {
await sentryBuildPluginManager.createRelease();
} finally {
freeGlobalDependencyOnBuildArtifacts();
}
},
});
if (options.sourcemaps?.disable !== true) {
if (typeof injectionPlugin !== "function") {
plugins.push(injectionPlugin.debugIdInjectionPlugin(logger));
}
if (options.sourcemaps?.disable !== "disable-upload") {
// This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
const webpack_forceExitOnBuildComplete =
typeof options._experiments["forceExitOnBuildCompletion"] === "boolean"
? options._experiments["forceExitOnBuildCompletion"]
: undefined;
plugins.push(
debugIdUploadPlugin(
createDebugIdUploadFunction({
sentryBuildPluginManager,
}),
logger,
sentryBuildPluginManager.createDependencyOnBuildArtifacts,
webpack_forceExitOnBuildComplete
)
);
}
}
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(options.reactComponentAnnotation.ignoredComponents)
);
}
}
// Add plugin to delete unwanted artifacts like source maps after the uploads have completed
plugins.push({
name: "sentry-file-deletion-plugin",
async writeBundle() {
await sentryBuildPluginManager.deleteArtifacts();
},
});
return plugins;
});
}
/**
* 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());
}
// 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])*(?:"[^"]*";|'[^']*';)?/;
/**
* Simplified `renderChunk` hook type from Rollup.
* We can't reference the type directly because the Vite plugin complains
* about type mismatches
*/
type RenderChunkHook = (
code: string,
chunk: {
fileName: string;
facadeModuleId?: string | null;
}
) => {
code: string;
map: SourceMap;
} | null;
/**
* Checks if a file is a JavaScript file based on its extension.
* Handles query strings and hashes in the filename.
*/
function isJsFile(fileName: string): boolean {
const cleanFileName = stripQueryAndHashFromPath(fileName);
return [".js", ".mjs", ".cjs"].some((ext) => cleanFileName.endsWith(ext));
}
/**
* Checks if a chunk should be skipped for code injection
*
* This is necessary to handle Vite's MPA (multi-page application) mode where
* HTML entry points create "facade" chunks that should not contain injected code.
* See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829
*
* However, in SPA mode, the main bundle also has an HTML facade but contains
* substantial application code. We should NOT skip injection for these bundles.
*
* @param code - The chunk's code content
* @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks
* @returns true if the chunk should be skipped
*/
function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {
// Skip empty chunks - these are placeholder chunks that should be optimized away
if (code.trim().length === 0) {
return true;
}
// For HTML facade chunks, only skip if they contain only import statements
if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith(".html")) {
return containsOnlyImports(code);
}
return false;
}
export function createRollupBundleSizeOptimizationHooks(replacementValues: SentrySDKBuildFlags): {
transform: UnpluginOptions["transform"];
} {
return {
transform(code: string) {
return replaceBooleanFlagsInCode(code, replacementValues);
},
};
}
export function createRollupInjectionHooks(
injectionCode: string,
debugIds: boolean
): {
renderChunk: RenderChunkHook;
} {
return {
renderChunk(code: string, chunk: { fileName: string; facadeModuleId?: string | null }) {
if (!isJsFile(chunk.fileName)) {
return null; // returning null means not modifying the chunk at all
}
// Skip empty chunks and HTML facade chunks (Vite MPA)
if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) {
return null;
}
let codeToInject = injectionCode;
if (debugIds) {
// Check if a debug ID has already been injected to avoid duplicate injection (e.g. by another plugin or Sentry CLI)
const chunkStartSnippet = code.slice(0, 6000);
const chunkEndSnippet = code.slice(-500);
if (
!(
chunkStartSnippet.includes("_sentryDebugIdIdentifier") ||
chunkEndSnippet.includes("//# debugId=")
)
) {
const debugId = stringToUUID(code); // generate a deterministic debug ID
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" }),
};
},
};
}
export function createRollupDebugIdUploadHooks(
upload: (buildArtifacts: string[]) => Promise<void>,
_logger: Logger,
createDependencyOnBuildArtifacts: () => () => void
): {
writeBundle: (
outputOptions: { dir?: string; file?: string },
bundle: { [fileName: string]: unknown }
) => Promise<void>;
} {
const freeGlobalDependencyOnDebugIdSourcemapArtifacts = createDependencyOnBuildArtifacts();
return {
async writeBundle(
outputOptions: { dir?: string; file?: string },
bundle: { [fileName: string]: unknown }
) {
try {
if (outputOptions.dir) {
const outputDir = outputOptions.dir;
const buildArtifacts = await glob(
[
"/**/*.js",
"/**/*.mjs",
"/**/*.cjs",
"/**/*.js.map",
"/**/*.mjs.map",
"/**/*.cjs.map",
].map((q) => `${q}?(\\?*)?(#*)`), // We want to allow query and hashes strings at the end of files
{
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);
}
} finally {
freeGlobalDependencyOnDebugIdSourcemapArtifacts();
}
},
};
}
export function createComponentNameAnnotateHooks(ignoredComponents?: string[]): {
transform: UnpluginOptions["transform"];
} {
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, { ignoredComponents }]],
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 `;{try{(function(){var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${debugId}",e._sentryDebugIdIdentifier="sentry-dbid-${debugId}");})();}catch(e){}};`;
}
export type { Logger } from "./logger";
export type { Options, SentrySDKBuildFlags } from "./types";
export { replaceBooleanFlagsInCode, stringToUUID } from "./utils";
export { createSentryBuildPluginManager } from "./build-plugin-manager";