-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathgeneratePlugin.ts
318 lines (277 loc) · 11.8 KB
/
generatePlugin.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
import fs from 'fs';
import path from 'path';
import { type Package } from '@sentry/core';
import HtmlWebpackPlugin, { createHtmlTagObject } from 'html-webpack-plugin';
import type { Compiler } from 'webpack';
import { addStaticAsset, symlinkAsset } from './staticAssets';
const LOADER_TEMPLATE = fs.readFileSync(path.join(__dirname, '../fixtures/loader.js'), 'utf-8');
const PACKAGES_DIR = path.join(__dirname, '..', '..', '..', 'packages');
const ROOT_PACKAGE_JSON_PATH = path.join(__dirname, '..', '..', '..', 'package.json');
/**
* Possible values: See BUNDLE_PATHS.browser
*/
const bundleKey = process.env.PW_BUNDLE || '';
// `esm` and `cjs` builds are modules that can be imported / aliased by webpack
const useCompiledModule = bundleKey === 'esm' || bundleKey === 'cjs';
// Bundles need to be injected into HTML before Sentry initialization.
const useBundleOrLoader = bundleKey && !useCompiledModule;
const useLoader = bundleKey.startsWith('loader');
// These are imports that, when using CDN bundles, are not included in the main CDN bundle.
// In this case, if we encounter this import, we want to add this CDN bundle file instead
// IMPORTANT NOTE: In order for this to work, you need to import this from browser like this:
// import { httpClientIntegration } from '@sentry/browser';
// You cannot use e.g. Sentry.httpClientIntegration, as this will not be detected
const IMPORTED_INTEGRATION_CDN_BUNDLE_PATHS: Record<string, string> = {
httpClientIntegration: 'httpclient',
captureConsoleIntegration: 'captureconsole',
rewriteFramesIntegration: 'rewriteframes',
contextLinesIntegration: 'contextlines',
extraErrorDataIntegration: 'extraerrordata',
reportingObserverIntegration: 'reportingobserver',
feedbackIntegration: 'feedback',
moduleMetadataIntegration: 'modulemetadata',
graphqlClientIntegration: 'graphqlclient',
// technically, this is not an integration, but let's add it anyway for simplicity
makeMultiplexedTransport: 'multiplexedtransport',
};
const BUNDLE_PATHS: Record<string, Record<string, string>> = {
browser: {
cjs: 'build/npm/cjs/index.js',
esm: 'build/npm/esm/index.js',
bundle: 'build/bundles/bundle.js',
bundle_min: 'build/bundles/bundle.min.js',
bundle_replay: 'build/bundles/bundle.replay.js',
bundle_replay_min: 'build/bundles/bundle.replay.min.js',
bundle_tracing: 'build/bundles/bundle.tracing.js',
bundle_tracing_min: 'build/bundles/bundle.tracing.min.js',
bundle_tracing_replay: 'build/bundles/bundle.tracing.replay.js',
bundle_tracing_replay_min: 'build/bundles/bundle.tracing.replay.min.js',
bundle_tracing_replay_feedback: 'build/bundles/bundle.tracing.replay.feedback.js',
bundle_tracing_replay_feedback_min: 'build/bundles/bundle.tracing.replay.feedback.min.js',
loader_base: 'build/bundles/bundle.min.js',
loader_eager: 'build/bundles/bundle.min.js',
loader_debug: 'build/bundles/bundle.debug.min.js',
loader_tracing: 'build/bundles/bundle.tracing.min.js',
loader_replay: 'build/bundles/bundle.replay.min.js',
loader_replay_buffer: 'build/bundles/bundle.replay.min.js',
loader_tracing_replay: 'build/bundles/bundle.tracing.replay.debug.min.js',
},
integrations: {
cjs: 'build/npm/cjs/index.js',
esm: 'build/npm/esm/index.js',
bundle: 'build/bundles/[INTEGRATION_NAME].js',
bundle_min: 'build/bundles/[INTEGRATION_NAME].min.js',
},
feedback: {
bundle: 'build/bundles/[INTEGRATION_NAME].js',
bundle_min: 'build/bundles/[INTEGRATION_NAME].min.js',
},
wasm: {
cjs: 'build/npm/cjs/index.js',
esm: 'build/npm/esm/index.js',
bundle: 'build/bundles/wasm.js',
bundle_min: 'build/bundles/wasm.min.js',
},
};
export const LOADER_CONFIGS: Record<string, { options: Record<string, unknown>; lazy: boolean }> = {
loader_base: {
options: {},
lazy: true,
},
loader_eager: {
options: {},
lazy: false,
},
loader_debug: {
options: { debug: true },
lazy: true,
},
loader_tracing: {
options: { tracesSampleRate: 1 },
lazy: false,
},
loader_replay: {
options: { replaysSessionSampleRate: 1, replaysOnErrorSampleRate: 1 },
lazy: false,
},
loader_replay_buffer: {
options: { replaysSessionSampleRate: 0, replaysOnErrorSampleRate: 1 },
lazy: false,
},
loader_tracing_replay: {
options: { tracesSampleRate: 1, replaysSessionSampleRate: 1, replaysOnErrorSampleRate: 1, debug: true },
lazy: false,
},
};
/*
* Generate webpack aliases based on packages in monorepo
*
* When using compiled versions of the tracing and browser packages, their aliases look for example like
* '@sentry/browser': 'path/to/sentry-javascript/packages/browser/esm/index.js'
* and all other monorepo packages' aliases look for example like
* '@sentry/react': 'path/to/sentry-javascript/packages/react'
*
* When using bundled versions of the tracing and browser packages, all aliases look for example like
* '@sentry/browser': false
* so that the compiled versions aren't included
*/
function generateSentryAlias(): Record<string, string> {
const rootPackageJson = JSON.parse(fs.readFileSync(ROOT_PACKAGE_JSON_PATH, 'utf8')) as { workspaces: string[] };
const packageNames = rootPackageJson.workspaces
.filter(workspace => !workspace.startsWith('dev-packages/'))
.map(workspace => workspace.replace('packages/', ''));
return Object.fromEntries(
packageNames.map(packageName => {
const packageJSON: Package = JSON.parse(
fs.readFileSync(path.resolve(PACKAGES_DIR, packageName, 'package.json'), { encoding: 'utf-8' }).toString(),
);
const modulePath = path.resolve(PACKAGES_DIR, packageName);
const bundleKeyPath = bundleKey && BUNDLE_PATHS[packageName]?.[bundleKey];
if (useCompiledModule && bundleKeyPath) {
const bundlePath = path.resolve(modulePath, bundleKeyPath);
return [packageJSON['name'], bundlePath];
}
if (useBundleOrLoader) {
// If we're injecting a bundle, ignore the webpack imports.
return [packageJSON['name'], false];
}
return [packageJSON['name'], modulePath];
}),
);
}
class SentryScenarioGenerationPlugin {
public requiredIntegrations: string[] = [];
public requiresWASMIntegration: boolean = false;
public localOutPath: string;
private _name: string = 'SentryScenarioGenerationPlugin';
public constructor(localOutPath: string) {
this.localOutPath = localOutPath;
}
public apply(compiler: Compiler): void {
compiler.options.resolve.alias = generateSentryAlias();
compiler.options.externals = useBundleOrLoader
? {
// To help Webpack resolve Sentry modules in `import` statements in cases where they're provided in bundles rather than in `node_modules`
'@sentry/browser': 'Sentry',
'@sentry-internal/replay': 'Sentry',
'@sentry/wasm': 'Sentry',
}
: {};
compiler.hooks.normalModuleFactory.tap(this._name, factory => {
factory.hooks.parser.for('javascript/auto').tap(this._name, parser => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
parser.hooks.import.tap(
this._name,
(statement: { specifiers: [{ imported: { name: string } }] }, source: string) => {
const imported = statement.specifiers?.[0]?.imported?.name;
const bundleName = imported && IMPORTED_INTEGRATION_CDN_BUNDLE_PATHS[imported];
if (bundleName) {
this.requiredIntegrations.push(bundleName);
} else if (source === '@sentry/wasm') {
this.requiresWASMIntegration = true;
}
},
);
});
});
compiler.hooks.compilation.tap(this._name, compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(this._name, (data, cb) => {
if (useBundleOrLoader) {
const bundleName = 'browser';
const bundlePath = BUNDLE_PATHS[bundleName]?.[bundleKey];
if (!bundlePath) {
throw new Error(`Could not find bundle or loader for key ${bundleKey}`);
}
const bundleObject = useLoader
? createHtmlTagObject('script', {
src: 'loader.js',
})
: createHtmlTagObject('script', {
src: 'cdn.bundle.js',
});
symlinkAsset(
path.resolve(PACKAGES_DIR, bundleName, bundlePath),
path.join(this.localOutPath, 'cdn.bundle.js'),
);
if (useLoader) {
const loaderConfig = LOADER_CONFIGS[bundleKey];
addStaticAsset(this.localOutPath, 'loader.js', () => {
return LOADER_TEMPLATE.replace('__LOADER_BUNDLE__', "'/cdn.bundle.js'")
.replace(
'__LOADER_OPTIONS__',
JSON.stringify({
dsn: 'https://[email protected]/1337',
...loaderConfig?.options,
}),
)
.replace('__LOADER_LAZY__', loaderConfig?.lazy ? 'true' : 'false');
});
}
// Convert e.g. bundle_tracing_min to bundle_min
const integrationBundleKey = bundleKey
.replace('loader_', 'bundle_')
.replace('_replay', '')
.replace('_tracing', '')
.replace('_feedback', '');
// For feedback bundle, make sure to add modal & screenshot integrations
if (bundleKey.includes('_feedback')) {
['feedback-modal', 'feedback-screenshot'].forEach(integration => {
const fileName = `${integration}.bundle.js`;
// We add the files, but not a script tag - they are lazy-loaded
symlinkAsset(
path.resolve(
PACKAGES_DIR,
'feedback',
BUNDLE_PATHS['feedback']?.[integrationBundleKey]?.replace('[INTEGRATION_NAME]', integration) || '',
),
path.join(this.localOutPath, fileName),
);
});
}
const baseIntegrationFileName = BUNDLE_PATHS['integrations']?.[integrationBundleKey];
if (baseIntegrationFileName) {
this.requiredIntegrations.forEach(integration => {
const fileName = `${integration}.bundle.js`;
symlinkAsset(
path.resolve(
PACKAGES_DIR,
'browser',
baseIntegrationFileName.replace('[INTEGRATION_NAME]', integration),
),
path.join(this.localOutPath, fileName),
);
if (integration === 'feedback') {
symlinkAsset(
path.resolve(PACKAGES_DIR, 'feedback', 'build/bundles/feedback-modal.js'),
path.join(this.localOutPath, 'feedback-modal.bundle.js'),
);
symlinkAsset(
path.resolve(PACKAGES_DIR, 'feedback', 'build/bundles/feedback-screenshot.js'),
path.join(this.localOutPath, 'feedback-screenshot.bundle.js'),
);
}
const integrationObject = createHtmlTagObject('script', {
src: fileName,
});
data.assetTags.scripts.unshift(integrationObject);
});
}
const baseWasmFileName = BUNDLE_PATHS['wasm']?.[integrationBundleKey];
if (this.requiresWASMIntegration && baseWasmFileName) {
symlinkAsset(
path.resolve(PACKAGES_DIR, 'wasm', baseWasmFileName),
path.join(this.localOutPath, 'wasm.bundle.js'),
);
const wasmObject = createHtmlTagObject('script', {
src: 'wasm.bundle.js',
});
data.assetTags.scripts.unshift(wasmObject);
}
data.assetTags.scripts.unshift(bundleObject);
}
cb(null, data);
});
});
}
}
export default SentryScenarioGenerationPlugin;