Skip to content

Commit d239e57

Browse files
ref(bundler-plugins): Address review feedback on module versions injection
- The Node SDK references `__SENTRY_SERVER_MODULES__` once, so bundlers inline the versions in one place instead of two or three. - `replaceBooleanFlagsInCode` only replaces boolean flags again. The Rollup plugin replaces the flags and the placeholder with a generic `replaceInCode`. - The bundler plugin integration test setup builds the three packed packages with one `build:dev:filter` call. Co-Authored-By: Francesco Gringl-Novy <[email protected]>
1 parent 785802e commit d239e57

6 files changed

Lines changed: 65 additions & 54 deletions

File tree

‎dev-packages/bundler-plugin-integration-tests/setup.mjs‎

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,24 +18,17 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url));
1818
// monorepo build). Then `build:tarball` (npm pack) produces `sentry-bundler-plugins-<version>.tgz`
1919
// so the fixture installs below resolve the local build rather than a published version.
2020
const repoRoot = join(__dirname, '..', '..');
21-
const bundlerPluginsDir = join(repoRoot, 'packages', 'bundler-plugins');
2221

23-
const coreDir = join(repoRoot, 'packages', 'core');
24-
console.log('Building @sentry/core and its workspace dependencies...');
25-
execSync('pnpm run build:dev:filter @sentry/core', { cwd: repoRoot, stdio: 'inherit' });
26-
console.log('Packing @sentry/core...');
27-
execSync('pnpm run build:tarball', { cwd: coreDir, stdio: 'inherit' });
22+
console.log('Building @sentry/core, @sentry/server-utils, @sentry/bundler-plugins and their workspace dependencies...');
23+
execSync('pnpm run build:dev:filter @sentry/core @sentry/server-utils @sentry/bundler-plugins', {
24+
cwd: repoRoot,
25+
stdio: 'inherit',
26+
});
2827

29-
const serverUtilsDir = join(repoRoot, 'packages', 'server-utils');
30-
console.log('Building @sentry/server-utils and its workspace dependencies...');
31-
execSync('pnpm run build:dev:filter @sentry/server-utils', { cwd: repoRoot, stdio: 'inherit' });
32-
console.log('Packing @sentry/server-utils...');
33-
execSync('pnpm run build:tarball', { cwd: serverUtilsDir, stdio: 'inherit' });
34-
35-
console.log('Building @sentry/bundler-plugins and its workspace dependencies...');
36-
execSync('pnpm run build:dev:filter @sentry/bundler-plugins', { cwd: repoRoot, stdio: 'inherit' });
37-
console.log('Packing @sentry/bundler-plugins...');
38-
execSync('pnpm run build:tarball', { cwd: bundlerPluginsDir, stdio: 'inherit' });
28+
for (const name of ['core', 'server-utils', 'bundler-plugins']) {
29+
console.log(`Packing @sentry/${name}...`);
30+
execSync('pnpm run build:tarball', { cwd: join(repoRoot, 'packages', name), stdio: 'inherit' });
31+
}
3932

4033
const fixturesDir = join(__dirname, 'fixtures');
4134
const entries = await fs.readdir(fixturesDir, { withFileTypes: true });

‎packages/bundler-plugins/src/core/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,14 @@ export type { InternalOptions, Options, SentrySDKBuildFlags } from './types';
105105
export {
106106
CodeInjection,
107107
replaceBooleanFlagsInCode,
108+
replaceInCode,
109+
getBooleanFlagReplacements,
108110
stringToUUID,
109111
generateReleaseInjectorCode,
110112
generateModuleMetadataInjectorCode,
111113
resolveReleaseName,
112114
getServerModulesDefinition,
115+
getServerModulesReplacement,
113116
SERVER_MODULES_PLACEHOLDER,
114117
} from './utils';
115118
export { createSentryBuildPluginManager } from './build-plugin-manager';

‎packages/bundler-plugins/src/core/utils.ts‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -377,28 +377,35 @@ export function getServerModulesDefinition(serverModules: Record<string, string>
377377
return { [SERVER_MODULES_PLACEHOLDER]: stringifyForCodeInjection(serverModules) };
378378
}
379379

380-
/**
381-
* Replaces the boolean flags, and the `__SENTRY_SERVER_MODULES__` placeholder that the Node SDK's `modulesIntegration`
382-
* reads when `serverModules` is set.
383-
*/
384-
export function replaceBooleanFlagsInCode(
385-
code: string,
386-
replacementValues: Record<string, boolean | undefined>,
387-
serverModules?: Record<string, string>,
388-
): { code: string; map: SourceMap } | null {
389-
const ms = new MagicString(code);
380+
/** The replacement for the module versions placeholder in plain code, where the object needs parentheses. */
381+
export function getServerModulesReplacement(serverModules: Record<string, string>): Record<string, string> {
382+
return { [SERVER_MODULES_PLACEHOLDER]: `(${stringifyForCodeInjection(serverModules)})` };
383+
}
390384

385+
/** The boolean flags as code, such as `'false'`. Flags without a value are left out. */
386+
export function getBooleanFlagReplacements(
387+
replacementValues: Record<string, boolean | undefined>,
388+
): Record<string, string> {
389+
const replacements: Record<string, string> = {};
391390
Object.keys(replacementValues).forEach(key => {
392391
const value = replacementValues[key];
393-
394392
if (typeof value === 'boolean') {
395-
ms.replaceAll(key, JSON.stringify(value));
393+
replacements[key] = JSON.stringify(value);
396394
}
397395
});
396+
return replacements;
397+
}
398398

399-
if (serverModules) {
400-
ms.replaceAll(SERVER_MODULES_PLACEHOLDER, `(${stringifyForCodeInjection(serverModules)})`);
401-
}
399+
/** Replaces every occurrence of each key of `replacements` in `code` with its value. */
400+
export function replaceInCode(
401+
code: string,
402+
replacements: Record<string, string>,
403+
): { code: string; map: SourceMap } | null {
404+
const ms = new MagicString(code);
405+
406+
Object.keys(replacements).forEach(key => {
407+
ms.replaceAll(key, replacements[key] as string);
408+
});
402409

403410
if (ms.hasChanged()) {
404411
return {
@@ -410,6 +417,13 @@ export function replaceBooleanFlagsInCode(
410417
return null;
411418
}
412419

420+
export function replaceBooleanFlagsInCode(
421+
code: string,
422+
replacementValues: Record<string, boolean | undefined>,
423+
): { code: string; map: SourceMap } | null {
424+
return replaceInCode(code, getBooleanFlagReplacements(replacementValues));
425+
}
426+
413427
// https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
414428
export function getTurborepoEnvPassthroughWarning(envVarName: string): string {
415429
return process.env['TURBO_HASH']

‎packages/bundler-plugins/src/rollup/index.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import {
1212
createDebugIdUploadFunction,
1313
globFiles,
1414
createComponentNameAnnotateHooks,
15-
replaceBooleanFlagsInCode,
15+
getBooleanFlagReplacements,
16+
getServerModulesReplacement,
17+
replaceInCode,
1618
CodeInjection,
1719
getCodeInjectionPosition,
1820
getSourceMapFeatures,
@@ -184,7 +186,8 @@ export function _createRollupPluginInternals(
184186
)
185187
: undefined;
186188

187-
const transformReplace = Object.keys(replacementValues).length > 0;
189+
const flagReplacements = getBooleanFlagReplacements(replacementValues);
190+
const transformReplace = Object.keys(flagReplacements).length > 0;
188191
const transformServerModules = mayInjectModuleVersions(options.injectModuleVersions, buildTool);
189192
const shouldTransform = transformAnnotations || transformReplace || transformServerModules;
190193

@@ -229,7 +232,10 @@ export function _createRollupPluginInternals(
229232

230233
const serverModules = getServerModules(this, code);
231234
if (transformReplace || serverModules) {
232-
return replaceBooleanFlagsInCode(code, replacementValues, serverModules);
235+
return replaceInCode(
236+
code,
237+
serverModules ? { ...flagReplacements, ...getServerModulesReplacement(serverModules) } : flagReplacements,
238+
);
233239
}
234240

235241
return null;

‎packages/bundler-plugins/test/core/module-versions.test.ts‎

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,16 @@ import * as fs from 'fs';
22
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
33
import { createSentryBuildPluginManager } from '../../src/core/build-plugin-manager';
44
import { getInstalledModules } from '../../src/core/installed-modules';
5-
import { replaceBooleanFlagsInCode } from '../../src/core/utils';
5+
import { getServerModulesReplacement, replaceInCode } from '../../src/core/utils';
66
import type { Options } from '../../src/core';
77
import { createModuleVersionsProject, INJECTED_MODULES } from '../utils/module-versions-project';
88

9-
describe('replaceBooleanFlagsInCode with server modules', () => {
10-
const modules = { installed: '1.2.3' };
9+
describe('getServerModulesReplacement', () => {
10+
it('replaces the `__SENTRY_SERVER_MODULES__` placeholder with the versions in parentheses', () => {
11+
const code = 'const modules = __SENTRY_SERVER_MODULES__;';
1112

12-
it('replaces the `__SENTRY_SERVER_MODULES__` placeholder', () => {
13-
const code = "if (typeof __SENTRY_SERVER_MODULES__ !== 'undefined') return __SENTRY_SERVER_MODULES__;";
14-
15-
expect(replaceBooleanFlagsInCode(code, {}, modules)?.code).toBe(
16-
'if (typeof ({"installed":"1.2.3"}) !== \'undefined\') return ({"installed":"1.2.3"});',
17-
);
18-
});
19-
20-
it('replaces flags and the placeholder in one pass', () => {
21-
const code = 'if (__SENTRY_DEBUG__) console.log(__SENTRY_SERVER_MODULES__);';
22-
23-
expect(replaceBooleanFlagsInCode(code, { __SENTRY_DEBUG__: false }, modules)?.code).toBe(
24-
'if (false) console.log(({"installed":"1.2.3"}));',
13+
expect(replaceInCode(code, getServerModulesReplacement({ installed: '1.2.3' }))?.code).toBe(
14+
'const modules = ({"installed":"1.2.3"});',
2515
);
2616
});
2717
});

‎packages/node/src/integrations/modules.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,20 @@ declare const __SENTRY_SERVER_MODULES__: Record<string, string> | string;
1313

1414
/** Reads the module versions that a bundler injected at build time. */
1515
function getServerModules(): Record<string, string> {
16-
if (typeof __SENTRY_SERVER_MODULES__ === 'undefined') {
16+
let serverModules: Record<string, string> | string | undefined;
17+
try {
18+
// The only reference to the placeholder, so a bundler that replaces it inlines the versions once.
19+
serverModules = __SENTRY_SERVER_MODULES__;
20+
} catch {
21+
// Not replaced at build time
1722
return {};
1823
}
19-
if (typeof __SENTRY_SERVER_MODULES__ !== 'string') {
20-
return __SENTRY_SERVER_MODULES__;
24+
if (typeof serverModules !== 'string') {
25+
return serverModules || {};
2126
}
2227
// Next.js Turbopack builds pass JSON, because `compiler.defineServer` only accepts strings.
2328
try {
24-
return JSON.parse(__SENTRY_SERVER_MODULES__) as Record<string, string>;
29+
return JSON.parse(serverModules) as Record<string, string>;
2530
} catch {
2631
return {};
2732
}

0 commit comments

Comments
 (0)