diff --git a/packages/astro/src/integration/index.ts b/packages/astro/src/integration/index.ts index 9185358dc2a4..9164eac6f2c4 100644 --- a/packages/astro/src/integration/index.ts +++ b/packages/astro/src/integration/index.ts @@ -1,3 +1,5 @@ +/* oxlint-disable max-lines */ +import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core'; import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; @@ -139,6 +141,10 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { ], }, }); + } else if (sdkEnabled.server && command !== 'dev') { + // TODO: Revisit which features the plugin should run when source maps are off. For now it only injects + // module versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime. + updateConfig({ vite: { plugins: [sentryVitePlugin(getDisabledSourcemapsOptions({ debug }))] } }); } runtimeRelease && injectScript('head-inline', buildReleaseSnippet(runtimeRelease)); diff --git a/packages/astro/test/integration/index.files.test.ts b/packages/astro/test/integration/index.files.test.ts index 39ca0ef66ed9..e83f02980d9c 100644 --- a/packages/astro/test/integration/index.files.test.ts +++ b/packages/astro/test/integration/index.files.test.ts @@ -1,3 +1,4 @@ +import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { sentryAstro } from '../../src/integration'; @@ -9,7 +10,8 @@ vi.mock('fs', async requireActual => { }); // Without a configured name, the real resolver falls back to the git revision of this checkout. -vi.mock('@sentry/bundler-plugins/core', () => ({ +vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({ + ...(await importOriginal()), resolveReleaseName: (name?: string) => name, })); diff --git a/packages/astro/test/integration/index.test.ts b/packages/astro/test/integration/index.test.ts index f979330c2a23..bb6d9761b8dd 100644 --- a/packages/astro/test/integration/index.test.ts +++ b/packages/astro/test/integration/index.test.ts @@ -1,3 +1,4 @@ +import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core'; import type * as FsModule from 'fs'; import type { AstroConfig, AstroIntegrationLogger } from 'astro'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -22,7 +23,8 @@ vi.mock('@sentry/bundler-plugins/vite', () => ({ // Without a configured name, the real resolver falls back to the git revision of this checkout. const resolveReleaseName = vi.fn((name?: string) => name); -vi.mock('@sentry/bundler-plugins/core', () => ({ +vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({ + ...(await importOriginal()), resolveReleaseName: (name?: string) => resolveReleaseName(name), })); @@ -531,19 +533,55 @@ describe('sentryAstro integration', () => { it("doesn't enable source maps if `sourcemaps.disable` is `true`", async () => { const integration = sentryAstro({ sourcemaps: { disable: true }, + debug: true, }); expect(integration.hooks['astro:config:setup']).toBeDefined(); // @ts-expect-error - the hook exists and we only need to pass what we actually use await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config }); - // only the orchestrion plugin and the server init are wired, no sourcemaps plugin - expect(updateConfig).toHaveBeenCalledTimes(2); + // one call each for the module versions plugin, the orchestrion plugin and the server init + expect(updateConfig).toHaveBeenCalledTimes(3); expect(updateConfig).toHaveBeenCalledWith({ vite: { plugins: [{ name: 'sentry-orchestrion-vite' }], }, }); + expect(updateConfig).not.toHaveBeenCalledWith({ vite: expect.objectContaining({ build: expect.anything() }) }); + // the bundler plugin only injects module versions + expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); + expect(sentryVitePluginSpy).toHaveBeenCalledWith({ + debug: true, + telemetry: false, + sourcemaps: { upload: false, injectDebugIds: false }, + release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false }, + }); + }); + + it("doesn't add the module versions plugin if `sourcemaps.disable` is `true` and the server SDK is disabled", async () => { + const integration = sentryAstro({ + sourcemaps: { disable: true }, + enabled: { client: true, server: false }, + }); + + // @ts-expect-error - the hook exists and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config }); + + expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0); + }); + + it("doesn't add the module versions plugin in dev mode", async () => { + const integration = sentryAstro({ sourcemaps: { disable: true } }); + + // @ts-expect-error - the hook exists and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ + ...baseConfigHookObject, + updateConfig, + injectScript, + config, + command: 'dev', + }); + expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0); }); diff --git a/packages/bundler-plugins/src/bun/index.ts b/packages/bundler-plugins/src/bun/index.ts index 132c7977b753..2c43dfd182e1 100644 --- a/packages/bundler-plugins/src/bun/index.ts +++ b/packages/bundler-plugins/src/bun/index.ts @@ -7,6 +7,7 @@ import { createDebugIdUploadFunction, CodeInjection, getSourceMapFeatures, + getServerModulesDefinition, } from '../core'; import * as fs from 'node:fs'; @@ -20,6 +21,7 @@ interface BunBuildConfig { sourcemap?: 'none' | 'linked' | 'inline' | 'external' | boolean; outdir?: string; define?: Record; + target?: 'browser' | 'bun' | 'node'; } interface BunPluginBuilder { @@ -150,6 +152,13 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin { config.define = { ...config.define, ...replacementStringValues }; } + const serverModules = sentryBuildPluginManager.getModuleVersions({ + isServerBuild: config.target === 'bun' || config.target === 'node', + }); + if (serverModules) { + config.define = { ...config.define, ...getServerModulesDefinition(serverModules) }; + } + const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts(); const upload = createDebugIdUploadFunction({ sentryBuildPluginManager }); diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 838a9cc8e3d4..1c84b26f11c6 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -13,6 +13,7 @@ import { createLogger } from './logger'; import { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry'; import type { InternalOptions, SentrySDKBuildFlags } from './types'; import { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils'; +import { getInstalledModules } from './installed-modules'; import { defaultRewriteSourcesHook, prepareArtifactForUpload, @@ -97,6 +98,12 @@ export type SentryBuildPluginManager = { // See `generateModuleMetadataInjectorCode` for how this should be used exactly bundleMetadata: Record; + /** + * Returns the app's module versions to replace `__SENTRY_SERVER_MODULES__` with in a build, or `undefined` when the + * build gets none (see the `injectModuleVersions` option). The versions are read once per root. + */ + getModuleVersions(build: { root?: string; isServerBuild: boolean }): Record | undefined; + /** * Contains utility functions for emitting telemetry via the build plugin manager. */ @@ -239,6 +246,7 @@ export function createSentryBuildPluginManager( }, }, bundleMetadata: {}, + getModuleVersions: () => undefined, createRelease: async () => { /* noop */ }, @@ -474,6 +482,25 @@ export function createSentryBuildPluginManager( } } + const moduleVersionsByRoot = new Map | undefined>(); + function getModuleVersions({ + root = process.cwd(), + isServerBuild, + }: { + root?: string; + isServerBuild: boolean; + }): Record | undefined { + if (!(options.injectModuleVersions ?? isServerBuild)) { + return undefined; + } + + if (!moduleVersionsByRoot.has(root)) { + const modules = getInstalledModules(root); + moduleVersionsByRoot.set(root, Object.keys(modules).length > 0 ? modules : undefined); + } + return moduleVersionsByRoot.get(root); + } + return { /** * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.) @@ -497,6 +524,8 @@ export function createSentryBuildPluginManager( // See `generateModuleMetadataInjectorCode` for how this should be used exactly bundleMetadata, + getModuleVersions, + /** * Contains utility functions for emitting telemetry via the build plugin manager. */ @@ -527,6 +556,11 @@ export function createSentryBuildPluginManager( * - adds deploy information */ async createRelease() { + const { create, finalize, setCommits, deploy, uploadLegacySourcemaps } = options.release; + if (!create && !finalize && setCommits === false && !deploy && !uploadLegacySourcemaps) { + return; + } + if (!options.release.name) { logger.debug( 'No release name provided. Will not create release. Please set the `release.name` option to identify your release.', diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts index abad714a3706..471e0ef250d9 100644 --- a/packages/bundler-plugins/src/core/index.ts +++ b/packages/bundler-plugins/src/core/index.ts @@ -105,12 +105,17 @@ export type { InternalOptions, Options, SentrySDKBuildFlags } from './types'; export { CodeInjection, replaceBooleanFlagsInCode, + replaceInCode, stringToUUID, generateReleaseInjectorCode, generateModuleMetadataInjectorCode, resolveReleaseName, + getServerModulesDefinition, + getServerModulesReplacement, + SERVER_MODULES_PLACEHOLDER, } from './utils'; export { createSentryBuildPluginManager } from './build-plugin-manager'; +export { getDisabledSourcemapsOptions } from './installed-modules'; export type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager'; export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload'; export { diff --git a/packages/bundler-plugins/src/core/installed-modules.ts b/packages/bundler-plugins/src/core/installed-modules.ts new file mode 100644 index 000000000000..52940b463d14 --- /dev/null +++ b/packages/bundler-plugins/src/core/installed-modules.ts @@ -0,0 +1,28 @@ +import * as fs from 'fs'; +import { collectInstalledModules } from '@sentry/core/server'; +import type { Options } from './types'; + +/** + * The dependencies of the app at `root`, with the exact version installed in `node_modules` where it resolves and + * the declared range otherwise. + */ +export function getInstalledModules(root: string): Record { + return collectInstalledModules({ + readFile: filePath => (fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : undefined), + cwd: root, + }); +} + +/** + * Plugin options for frameworks that add the plugin although the user turned source maps off. For now they turn off + * everything except injecting module versions: no source map upload, deletion or debug IDs, no release creation or + * injection, and no telemetry. + */ +export function getDisabledSourcemapsOptions(options: Pick = {}): Options { + return { + ...options, + telemetry: false, + sourcemaps: { upload: false, injectDebugIds: false }, + release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false }, + }; +} diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index 32096cc7ead9..d693f8d3d10d 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -88,6 +88,7 @@ export type NormalizedOptions = { }; applicationKey: string | undefined; moduleMetadata: ModuleMetadata | ModuleMetadataCallback | undefined; + injectModuleVersions: boolean | undefined; _experiments: { injectBuildInformation?: boolean; } & Record; @@ -138,6 +139,7 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption }, applicationKey: userOptions.applicationKey, moduleMetadata: userOptions.moduleMetadata, + injectModuleVersions: userOptions.injectModuleVersions, _experiments: userOptions._experiments ?? {}, }; diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index 1faf8a842488..c9337de84a2d 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -495,6 +495,15 @@ export interface Options { */ applicationKey?: string; + /** + * Injects the installed versions of the app's dependencies for the Node SDK's `modulesIntegration`, which + * otherwise reads them from `node_modules` at runtime. Only takes effect when the SDK is bundled. + * + * Defaults to server builds only (Vite SSR, webpack `node` targets, esbuild `platform: 'node'`, Bun); plain Rollup + * needs `true`, and `false` disables it. Avoid `true` for browser builds, as it ships the list to users. + */ + injectModuleVersions?: boolean; + /** * Options that are considered experimental and subject to change. * diff --git a/packages/bundler-plugins/src/core/utils.ts b/packages/bundler-plugins/src/core/utils.ts index d0f15bb8bea2..d8c099cb27cd 100644 --- a/packages/bundler-plugins/src/core/utils.ts +++ b/packages/bundler-plugins/src/core/utils.ts @@ -369,19 +369,41 @@ export function stripQueryAndHashFromPath(path: string): string { return path.split('?')[0]!.split('#')[0]!; } -export function replaceBooleanFlagsInCode( - code: string, - replacementValues: Record, -): { code: string; map: SourceMap } | null { - const ms = new MagicString(code); +/** The placeholder that the Node SDK's `modulesIntegration` reads the module versions from. */ +export const SERVER_MODULES_PLACEHOLDER = '__SENTRY_SERVER_MODULES__'; + +/** The `define` entry that replaces the module versions placeholder, for bundlers with `define` support. */ +export function getServerModulesDefinition(serverModules: Record): Record { + return { [SERVER_MODULES_PLACEHOLDER]: stringifyForCodeInjection(serverModules) }; +} + +/** The replacement for the module versions placeholder in plain code, where the object needs parentheses. */ +export function getServerModulesReplacement(serverModules: Record): Record { + return { [SERVER_MODULES_PLACEHOLDER]: `(${stringifyForCodeInjection(serverModules)})` }; +} +/** The boolean flags as code, such as `'false'`. Flags without a value are left out. */ +function getBooleanFlagReplacements(replacementValues: Record): Record { + const replacements: Record = {}; Object.keys(replacementValues).forEach(key => { const value = replacementValues[key]; - if (typeof value === 'boolean') { - ms.replaceAll(key, JSON.stringify(value)); + replacements[key] = JSON.stringify(value); } }); + return replacements; +} + +/** Replaces every occurrence of each key of `replacements` in `code` with its value. */ +export function replaceInCode( + code: string, + replacements: Record, +): { code: string; map: SourceMap } | null { + const ms = new MagicString(code); + + Object.keys(replacements).forEach(key => { + ms.replaceAll(key, replacements[key] as string); + }); if (ms.hasChanged()) { return { @@ -393,6 +415,13 @@ export function replaceBooleanFlagsInCode( return null; } +export function replaceBooleanFlagsInCode( + code: string, + replacementValues: Record, +): { code: string; map: SourceMap } | null { + return replaceInCode(code, getBooleanFlagReplacements(replacementValues)); +} + // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks export function getTurborepoEnvPassthroughWarning(envVarName: string): string { return process.env['TURBO_HASH'] diff --git a/packages/bundler-plugins/src/esbuild/index.ts b/packages/bundler-plugins/src/esbuild/index.ts index 19a5db9dcc0e..96b94c1e6121 100644 --- a/packages/bundler-plugins/src/esbuild/index.ts +++ b/packages/bundler-plugins/src/esbuild/index.ts @@ -10,6 +10,7 @@ import { addDebugIdToEmittedArtifacts, isJsFile, getSourceMapFeatures, + getServerModulesDefinition, } from '../core'; import * as path from 'node:path'; import { createRequire } from 'node:module'; @@ -62,6 +63,7 @@ interface EsbuildInitialOptions { absWorkingDir?: string; logOverride?: Record; sourcemap?: EsbuildSourceMapSetting; + platform?: string; } /** Maps esbuild's `sourcemap` setting onto the plugin's source map kinds. */ @@ -223,6 +225,14 @@ export function sentryEsbuildPlugin(userOptions: InternalOptions = {}): any { initialOptions.define = { ...initialOptions.define, ...replacementStringValues }; } + const serverModules = sentryBuildPluginManager.getModuleVersions({ + root: initialOptions.absWorkingDir, + isServerBuild: initialOptions.platform === 'node', + }); + if (serverModules) { + initialOptions.define = { ...initialOptions.define, ...getServerModulesDefinition(serverModules) }; + } + // Debug ID injection - requires per-entry-point unique IDs if (injectDebugIds) { // `setup` runs once per context, `onStart` once per build, so a diff --git a/packages/bundler-plugins/src/loader-utils/index.ts b/packages/bundler-plugins/src/loader-utils/index.ts index 96fe7cd50bf0..ac11f4714dd4 100644 --- a/packages/bundler-plugins/src/loader-utils/index.ts +++ b/packages/bundler-plugins/src/loader-utils/index.ts @@ -2,3 +2,4 @@ // don't pull in the build plugin manager and the `sentry` CLI. export { getCodeInjectionPosition } from '../core/get-code-injection-position'; export { createComponentNameAnnotateHooks } from '../core/component-annotate-hooks'; +export { getInstalledModules } from '../core/installed-modules'; diff --git a/packages/bundler-plugins/src/rollup/index.ts b/packages/bundler-plugins/src/rollup/index.ts index 846bfbb3c68c..d8cad06408f2 100644 --- a/packages/bundler-plugins/src/rollup/index.ts +++ b/packages/bundler-plugins/src/rollup/index.ts @@ -1,16 +1,20 @@ -import type { ChunkGraphNode, InternalOptions, Options } from '../core'; +/* oxlint-disable max-lines */ +import type { ChunkGraphNode, InternalOptions, Options, SentryBuildPluginManager } from '../core'; import { createSentryBuildPluginManager, generateReleaseInjectorCode, generateModuleMetadataInjectorCode, isJsFile, isInitialChunk, + SERVER_MODULES_PLACEHOLDER, shouldSkipCodeInjection, getDebugIdSnippet, createDebugIdUploadFunction, globFiles, createComponentNameAnnotateHooks, + getServerModulesReplacement, replaceBooleanFlagsInCode, + replaceInCode, CodeInjection, getCodeInjectionPosition, getSourceMapFeatures, @@ -23,7 +27,7 @@ import { createRequire } from 'node:module'; import { finalizeRolldownDebugIds, getDebugIdForChunk, hasExistingDebugID } from './debug-id-injection'; import { stampDebugIds, type OutputBundle } from './debug-id-stamping'; import { createSourceMapHandling, type OutputDestinationOptions } from './source-map-handling'; -import { createViteSourceMapHooks } from '../vite/source-map-hooks'; +import { createViteSourceMapHooks, type ViteResolvedConfig } from '../vite/source-map-hooks'; import { createViteReleaseHtmlInjection, type BuildInputOptions, @@ -88,6 +92,11 @@ function getViteParseAstAsync(): Promise { return viteParseAstAsyncPromise; } +// Plain Rollup builds get no module versions unless the user opts in, see `injectModuleVersions`. +function mayInjectModuleVersions(injectModuleVersions: boolean | undefined, buildTool: 'rollup' | 'vite'): boolean { + return injectModuleVersions === true || (buildTool === 'vite' && injectModuleVersions !== false); +} + /** * @ignore - internal plugin factory shared by the Rollup and Vite plugins. * @@ -372,7 +381,61 @@ export function _createRollupPluginInternals( }, }; - return { main, post }; + const moduleVersions = mayInjectModuleVersions(options.injectModuleVersions, buildTool) + ? createModuleVersionsPlugin(sentryBuildPluginManager, buildTool, options.injectModuleVersions === true) + : undefined; + + return { main, post, moduleVersions }; +} + +/** + * Replaces the module versions placeholder in its own plugin, so builds that cannot contain it register no + * `transform` hook, and the hook filter keeps every other module from reaching the handler. + */ +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type +function createModuleVersionsPlugin( + sentryBuildPluginManager: SentryBuildPluginManager, + buildTool: 'rollup' | 'vite', + forced: boolean, +) { + let root: string | undefined; + // Vite before 6 has no environments and runs an SSR build with its own config. + let viteSsrBuild = false; + + return { + name: `sentry-${buildTool}-module-versions`, + ...(buildTool === 'vite' + ? { + configResolved(config: ViteResolvedConfig): void { + root = config.root; + viteSsrBuild = !!config.build.ssr; + }, + ...(forced ? {} : { applyToEnvironment: isServerEnvironment }), + } + : {}), + transform: { + filter: { id: JS_MODULE_ID_FILTER, code: SERVER_MODULES_PLACEHOLDER }, + handler(this: ViteHookContext | undefined, code: string): TransformResult { + // Rollup before 4.38 and Vite before 6.3 ignore the filter. + if (!code.includes(SERVER_MODULES_PLACEHOLDER)) { + return null; + } + + const environment = this?.environment; + const serverModules = sentryBuildPluginManager.getModuleVersions({ + root, + isServerBuild: environment ? isServerEnvironment(environment) : viteSsrBuild, + }); + return serverModules ? replaceInCode(code, getServerModulesReplacement(serverModules)) : null; + }, + }, + }; +} + +type ViteEnvironment = NonNullable; + +function isServerEnvironment(environment: ViteEnvironment): boolean { + return environment.config?.consumer === 'server'; } /** @@ -389,10 +452,10 @@ export function _rollupPluginInternal( // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any export function sentryRollupPlugin(userOptions: Options = {}): any { - const { main, post } = _createRollupPluginInternals(userOptions, 'rollup'); + const { main, post, moduleVersions } = _createRollupPluginInternals(userOptions, 'rollup'); // We return an array here so we don't break backwards compatibility with what // unplugin used to return - return post ? [main, post] : [main]; + return [main, ...(moduleVersions ? [moduleVersions] : []), ...(post ? [post] : [])]; } export type { Options as SentryRollupPluginOptions } from '../core'; diff --git a/packages/bundler-plugins/src/vite/index.ts b/packages/bundler-plugins/src/vite/index.ts index 414b0b0d538e..1394c82fabc6 100644 --- a/packages/bundler-plugins/src/vite/index.ts +++ b/packages/bundler-plugins/src/vite/index.ts @@ -23,10 +23,14 @@ function getViteMajorVersion(): string | undefined { } export const sentryVitePlugin = (options?: InternalOptions): SentryVitePlugin[] => { - const { main, post } = _createRollupPluginInternals(options, 'vite', getViteMajorVersion()); + const { main, post, moduleVersions } = _createRollupPluginInternals(options, 'vite', getViteMajorVersion()); const plugins: SentryVitePlugin[] = [{ enforce: 'pre', ...main }]; + if (moduleVersions) { + plugins.push({ enforce: 'pre', ...moduleVersions }); + } + if (post) { plugins.push({ enforce: 'post', ...post }); } diff --git a/packages/bundler-plugins/src/vite/source-map-hooks.ts b/packages/bundler-plugins/src/vite/source-map-hooks.ts index 7764439a465e..6fa95520e7e5 100644 --- a/packages/bundler-plugins/src/vite/source-map-hooks.ts +++ b/packages/bundler-plugins/src/vite/source-map-hooks.ts @@ -9,6 +9,7 @@ type BundlerOutputOptions = BundlerOutput | BundlerOutput[] | undefined; type ViteBuildOptions = { sourcemap?: RollupSourceMapSetting; + ssr?: boolean | string; outDir?: string; rollupOptions?: { output?: BundlerOutputOptions }; rolldownOptions?: { output?: BundlerOutputOptions }; diff --git a/packages/bundler-plugins/src/webpack/index.ts b/packages/bundler-plugins/src/webpack/index.ts index 2472ab0c9a9d..12b850cc0ebf 100644 --- a/packages/bundler-plugins/src/webpack/index.ts +++ b/packages/bundler-plugins/src/webpack/index.ts @@ -21,6 +21,7 @@ import { isJsFile, stampDebugId, getSourceMapFeatures, + getServerModulesDefinition, } from '../core/index'; import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -80,6 +81,8 @@ type WebpackCompiler = { plugins?: unknown[]; mode?: string; devtool?: string | false; + target?: string | string[] | false; + context?: string; module?: { rules?: unknown[]; }; @@ -207,6 +210,13 @@ type WebpackModule = { default?: { version?: string }; }; +// Electron's preload and renderer contexts run browser SDKs, so only its main process counts. +const NODE_TARGET = /^(?:(?:async-)?node(?:\d+(?:\.\d+)?)?|electron(?:\d+(?:\.\d+)?)?-main)$/; + +function isNodeTarget(target: string | string[] | false | undefined): boolean { + return (Array.isArray(target) ? target : [target]).some(t => typeof t === 'string' && NODE_TARGET.test(t)); +} + // Only used for telemetry; `webpack` is an optional peer dependency and may be absent (e.g. rspack). function getWebpackMajorVersion(): string | undefined { try { @@ -582,6 +592,15 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptio compiler.options.plugins.push(new DefinePlugin(replacementValues)); } + const serverModules = sentryBuildPluginManager.getModuleVersions({ + root: compiler.options.context, + isServerBuild: isNodeTarget(compiler.options.target), + }); + if (serverModules && DefinePlugin) { + compiler.options.plugins = compiler.options.plugins || []; + compiler.options.plugins.push(new DefinePlugin(getServerModulesDefinition(serverModules))); + } + // Add component name annotation transform if (transformAnnotations?.transform) { compiler.options.module = compiler.options.module || {}; diff --git a/packages/bundler-plugins/test/bun/bun.test.ts b/packages/bundler-plugins/test/bun/bun.test.ts index 8d693d89957a..bc9e7b2d4fdc 100644 --- a/packages/bundler-plugins/test/bun/bun.test.ts +++ b/packages/bundler-plugins/test/bun/bun.test.ts @@ -20,7 +20,13 @@ const UUID = '0217b985-5bfb-77df-6475-6e2164756e21'; type Output = { path: string; kind: string }; type OnEnd = (result: { success: boolean; outputs: Output[]; logs: unknown[] }) => Promise; -type Config = { banner?: string; sourcemap?: string | boolean; define?: Record; outdir?: string }; +type Config = { + banner?: string; + sourcemap?: string | boolean; + define?: Record; + outdir?: string; + target?: 'browser' | 'bun' | 'node'; +}; interface BunPlugin { name: string; @@ -71,6 +77,20 @@ describe('sentryBunPlugin', () => { expect(onEnd).toBeUndefined(); }); + it.each(['bun', 'node'] as const)('injects module versions into builds with the %s target', target => { + const config: Config = { target }; + setupPlugin(sentryBunPlugin({ telemetry: false }) as BunPlugin, config); + + expect(config.define?.__SENTRY_SERVER_MODULES__).toContain('"@sentry/core"'); + }); + + it.each([undefined, 'browser'] as const)('does not inject module versions with the %j target', target => { + const config: Config = { target }; + setupPlugin(sentryBunPlugin({ telemetry: false }) as BunPlugin, config); + + expect(config.define?.__SENTRY_SERVER_MODULES__).toBeUndefined(); + }); + it('adds the debug ID snippet to the banner when Bun emits source maps', () => { const config: Config = { banner: '// existing', sourcemap: 'external', outdir: outDir }; setupPlugin(sentryBunPlugin({ telemetry: false }) as BunPlugin, config); diff --git a/packages/bundler-plugins/test/core/module-versions.test.ts b/packages/bundler-plugins/test/core/module-versions.test.ts new file mode 100644 index 000000000000..2f24ad71b184 --- /dev/null +++ b/packages/bundler-plugins/test/core/module-versions.test.ts @@ -0,0 +1,66 @@ +import * as fs from 'fs'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createSentryBuildPluginManager } from '../../src/core/build-plugin-manager'; +import { getInstalledModules } from '../../src/core/installed-modules'; +import { getServerModulesReplacement, replaceInCode } from '../../src/core/utils'; +import type { Options } from '../../src/core'; +import { createModuleVersionsProject, INJECTED_MODULES } from '../utils/module-versions-project'; + +describe('getServerModulesReplacement', () => { + it('replaces the `__SENTRY_SERVER_MODULES__` placeholder with the versions in parentheses', () => { + const code = 'const modules = __SENTRY_SERVER_MODULES__;'; + + expect(replaceInCode(code, getServerModulesReplacement({ installed: '1.2.3' }))?.code).toBe( + 'const modules = ({"installed":"1.2.3"});', + ); + }); +}); + +describe('module versions', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + function getModuleVersions(options: Options, isServerBuild: boolean): Record | undefined { + return createSentryBuildPluginManager( + { telemetry: false, silent: true, ...options }, + { buildTool: 'test', loggerPrefix: '[test]' }, + ).getModuleVersions({ root, isServerBuild }); + } + + it('reads installed versions and falls back to declared ranges', () => { + expect(getInstalledModules(root)).toEqual(INJECTED_MODULES); + }); + + it('returns the versions for server builds by default', () => { + expect(getModuleVersions({}, true)).toEqual(INJECTED_MODULES); + }); + + it('returns nothing for other builds by default', () => { + expect(getModuleVersions({}, false)).toBeUndefined(); + }); + + it('returns the versions for every build with `injectModuleVersions: true`', () => { + expect(getModuleVersions({ injectModuleVersions: true }, false)).toEqual(INJECTED_MODULES); + }); + + it('returns nothing with `injectModuleVersions: false`', () => { + expect(getModuleVersions({ injectModuleVersions: false }, true)).toBeUndefined(); + }); + + it('returns nothing when the plugin is disabled', () => { + expect(getModuleVersions({ disable: true }, true)).toBeUndefined(); + }); + + it('returns nothing when the project has no dependencies', () => { + fs.writeFileSync(`${root}/package.json`, JSON.stringify({ name: 'app' })); + + expect(getModuleVersions({}, true)).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/esbuild/module-versions-injection.test.ts b/packages/bundler-plugins/test/esbuild/module-versions-injection.test.ts new file mode 100644 index 000000000000..853f01b27f2c --- /dev/null +++ b/packages/bundler-plugins/test/esbuild/module-versions-injection.test.ts @@ -0,0 +1,41 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import * as esbuild from 'esbuild'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { sentryEsbuildPlugin } from '../../src/esbuild'; +import { createModuleVersionsProject, INJECTED_MODULES, runAndReadModules } from '../utils/module-versions-project'; + +describe('module versions injection (esbuild)', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + async function buildApp(platform: esbuild.Platform | undefined): Promise { + const outfile = path.join(root, 'dist', 'main.js'); + await esbuild.build({ + absWorkingDir: root, + entryPoints: ['./entry.js'], + bundle: true, + platform, + format: 'cjs', + outfile, + logLevel: 'silent', + plugins: [sentryEsbuildPlugin({ telemetry: false, silent: true, release: { create: false } })], + }); + return fs.readFileSync(outfile, 'utf8'); + } + + it("injects into builds with `platform: 'node'`", async () => { + expect(runAndReadModules(await buildApp('node'))).toEqual(INJECTED_MODULES); + }); + + it.each([undefined, 'browser', 'neutral'] as const)('does not inject with platform %j', async platform => { + expect(runAndReadModules(await buildApp(platform))).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/rollup/module-versions-injection.test.ts b/packages/bundler-plugins/test/rollup/module-versions-injection.test.ts new file mode 100644 index 000000000000..5902aefb59fc --- /dev/null +++ b/packages/bundler-plugins/test/rollup/module-versions-injection.test.ts @@ -0,0 +1,40 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { rollup } from 'rollup'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { sentryRollupPlugin } from '../../src/rollup'; +import type { Options } from '../../src/core'; +import { createModuleVersionsProject, INJECTED_MODULES, runAndReadModules } from '../utils/module-versions-project'; + +describe('module versions injection (rollup)', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + async function buildApp(options: Options): Promise { + const bundle = await rollup({ + input: path.join(root, 'entry.js'), + plugins: [sentryRollupPlugin({ telemetry: false, silent: true, release: { create: false }, ...options })], + }); + const { output } = await bundle.generate({ format: 'esm' }); + return output.map(chunk => (chunk.type === 'chunk' ? chunk.code : '')).join('\n'); + } + + it('does not inject by default, because Rollup cannot tell where the output runs', async () => { + expect(runAndReadModules(await buildApp({}))).toBeUndefined(); + }); + + it('injects with `injectModuleVersions: true`', async () => { + // Rollup has no root option, so the versions come from the working directory, not from `root`. + const modules = runAndReadModules(await buildApp({ injectModuleVersions: true })); + + expect(modules).toEqual(expect.objectContaining({ '@sentry/core': expect.any(String) })); + expect(modules).not.toEqual(INJECTED_MODULES); + }); +}); diff --git a/packages/bundler-plugins/test/rollup/public-api.test.ts b/packages/bundler-plugins/test/rollup/public-api.test.ts index 85fa16562da1..b5f10ef041b0 100644 --- a/packages/bundler-plugins/test/rollup/public-api.test.ts +++ b/packages/bundler-plugins/test/rollup/public-api.test.ts @@ -122,6 +122,16 @@ describe('sentryRollupPlugin', () => { expect(plugins.map(plugin => plugin.name)).toEqual(['sentry-rollup-plugin', 'sentry-rollup-upload-staging']); }); + it('adds the module versions plugin with `injectModuleVersions: true`', () => { + const plugins = sentryRollupPlugin({ telemetry: false, injectModuleVersions: true }) as Plugin[]; + + expect(plugins.map(plugin => plugin.name)).toEqual([ + 'sentry-rollup-plugin', + 'sentry-rollup-module-versions', + 'sentry-rollup-upload-staging', + ]); + }); + it('returns only the noop plugin when disabled', () => { const plugins = sentryRollupPlugin({ disable: true }) as Plugin[]; diff --git a/packages/bundler-plugins/test/utils/module-versions-project.ts b/packages/bundler-plugins/test/utils/module-versions-project.ts new file mode 100644 index 000000000000..c17f11827cb0 --- /dev/null +++ b/packages/bundler-plugins/test/utils/module-versions-project.ts @@ -0,0 +1,40 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { runInNewContext } from 'node:vm'; + +/** What `__SENTRY_SERVER_MODULES__` holds for the project from `createModuleVersionsProject`. */ +export const INJECTED_MODULES = { 'declared-only': '^2.0.0', installed: '1.2.3' }; + +/** + * Creates an app with one installed and one declared-only dependency, and an `entry.js` that the bundler tests + * build. The entry reads the modules like the Node SDK's `modulesIntegration`. + */ +export function createModuleVersionsProject(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-module-versions-')); + fs.writeFileSync( + path.join(root, 'package.json'), + JSON.stringify({ name: 'app', dependencies: { 'declared-only': '^2.0.0', installed: '^1.0.0' } }), + ); + fs.mkdirSync(path.join(root, 'node_modules', 'installed'), { recursive: true }); + fs.writeFileSync( + path.join(root, 'node_modules', 'installed', 'package.json'), + JSON.stringify({ name: 'installed', version: '1.2.3' }), + ); + fs.writeFileSync( + path.join(root, 'entry.js'), + [ + "globalThis.modules = typeof __SENTRY_SERVER_MODULES__ !== 'undefined' ? __SENTRY_SERVER_MODULES__ : undefined;", + '', + ].join('\n'), + ); + return root; +} + +/** Runs a bundle of `entry.js` and returns the modules that it read. */ +export function runAndReadModules(code: string): unknown { + const module = { exports: {} }; + const context: Record = { module, exports: module.exports }; + runInNewContext(code, context); + return context.modules; +} diff --git a/packages/bundler-plugins/test/vite/disabled-sourcemaps-options.test.ts b/packages/bundler-plugins/test/vite/disabled-sourcemaps-options.test.ts new file mode 100644 index 000000000000..4d7e4582d575 --- /dev/null +++ b/packages/bundler-plugins/test/vite/disabled-sourcemaps-options.test.ts @@ -0,0 +1,94 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { createBuilder } from 'vite'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getDisabledSourcemapsOptions } from '../../src/core'; +import { sentryVitePlugin } from '../../src/vite'; +import { createModuleVersionsProject, INJECTED_MODULES, runAndReadModules } from '../utils/module-versions-project'; + +const { sdk } = vi.hoisted(() => ({ + sdk: { + release: { create: vi.fn(), finalize: vi.fn(), 'set-commits': vi.fn(), deploy: vi.fn() }, + sourcemap: { upload: vi.fn(), inject: vi.fn() }, + run: vi.fn(), + }, +})); + +vi.mock('sentry', () => ({ createSentrySDK: () => sdk })); + +function readFiles(dir: string): Record { + return Object.fromEntries( + fs + .readdirSync(dir, { recursive: true, encoding: 'utf8' }) + .filter(file => fs.statSync(path.join(dir, file)).isFile()) + .map(file => [file, fs.readFileSync(path.join(dir, file), 'utf8')]), + ); +} + +describe('getDisabledSourcemapsOptions (vite)', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + vi.stubEnv('SENTRY_RELEASE', '1.2.3'); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ['without credentials', { SENTRY_AUTH_TOKEN: undefined }], + // Credentials in the environment must not make the plugin create a release or upload anything. + [ + 'with credentials in the environment', + { SENTRY_AUTH_TOKEN: 'token', SENTRY_ORG: 'org', SENTRY_PROJECT: 'project' }, + ], + ])('only injects module versions into the server build %s', async (_, env: Record) => { + for (const [name, value] of Object.entries(env)) { + vi.stubEnv(name, value); + } + const warn = vi.spyOn(console, 'warn'); + const info = vi.spyOn(console, 'info'); + const clientOutDir = path.join(root, 'dist', 'client'); + const serverOutDir = path.join(root, 'dist', 'server'); + + const builder = await createBuilder({ + configFile: false, + logLevel: 'silent', + root, + plugins: sentryVitePlugin(getDisabledSourcemapsOptions()), + environments: { + client: { build: { outDir: clientOutDir, rollupOptions: { input: path.join(root, 'entry.js') } } }, + ssr: { + build: { + outDir: serverOutDir, + ssr: path.join(root, 'entry.js'), + rollupOptions: { output: { format: 'cjs' } }, + }, + }, + }, + }); + await builder.buildApp(); + + const clientFiles = readFiles(clientOutDir); + const serverFiles = readFiles(serverOutDir); + const allCode = Object.values({ ...clientFiles, ...serverFiles }).join('\n'); + + expect(runAndReadModules(Object.values(serverFiles).join('\n'))).toEqual(INJECTED_MODULES); + expect(runAndReadModules(Object.values(clientFiles).join('\n'))).toBeUndefined(); + expect(Object.keys({ ...clientFiles, ...serverFiles }).filter(file => file.endsWith('.map'))).toEqual([]); + expect(allCode).not.toContain('SENTRY_RELEASE'); + expect(allCode).not.toContain('sentry-dbid'); + expect(sdk.release.create).not.toHaveBeenCalled(); + expect(sdk.release.finalize).not.toHaveBeenCalled(); + expect(sdk.release['set-commits']).not.toHaveBeenCalled(); + expect(sdk.release.deploy).not.toHaveBeenCalled(); + expect(sdk.sourcemap.upload).not.toHaveBeenCalled(); + expect(sdk.sourcemap.inject).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + expect(info).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bundler-plugins/test/vite/module-versions-injection.test.ts b/packages/bundler-plugins/test/vite/module-versions-injection.test.ts new file mode 100644 index 000000000000..92f92b9a947f --- /dev/null +++ b/packages/bundler-plugins/test/vite/module-versions-injection.test.ts @@ -0,0 +1,118 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { build, createBuilder } from 'vite'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { sentryVitePlugin } from '../../src/vite'; +import { createModuleVersionsProject, INJECTED_MODULES, runAndReadModules } from '../utils/module-versions-project'; + +describe('module versions injection (vite)', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + function plugins(): ReturnType { + return sentryVitePlugin({ telemetry: false, silent: true, release: { create: false } }); + } + + function readJs(dir: string): string { + return fs + .readdirSync(dir) + .filter(file => file.endsWith('.js') || file.endsWith('.mjs')) + .map(file => fs.readFileSync(path.join(dir, file), 'utf8')) + .join('\n'); + } + + it('injects into SSR builds', async () => { + const outDir = path.join(root, 'dist'); + await build({ + configFile: false, + logLevel: 'silent', + root, + plugins: plugins(), + build: { outDir, ssr: path.join(root, 'entry.js'), minify: false, rollupOptions: { output: { format: 'cjs' } } }, + }); + + expect(runAndReadModules(readJs(outDir))).toEqual(INJECTED_MODULES); + }); + + it('injects into a bundled SDK, and leaves an external one to read `node_modules` at runtime', async () => { + const sdkDir = path.join(root, 'node_modules', 'sdk'); + fs.mkdirSync(sdkDir); + fs.writeFileSync( + path.join(sdkDir, 'package.json'), + JSON.stringify({ name: 'sdk', version: '1.0.0', main: 'index.js' }), + ); + fs.renameSync(path.join(root, 'entry.js'), path.join(sdkDir, 'index.js')); + fs.writeFileSync(path.join(root, 'entry.js'), "import 'sdk';\n"); + + async function buildSsr(noExternal: boolean): Promise { + const outDir = path.join(root, noExternal ? 'dist-bundled' : 'dist-external'); + await build({ + configFile: false, + logLevel: 'silent', + root, + plugins: plugins(), + ssr: noExternal ? { noExternal: true } : undefined, + build: { + outDir, + ssr: path.join(root, 'entry.js'), + minify: false, + rollupOptions: { output: { format: 'cjs' } }, + }, + }); + return readJs(outDir); + } + + expect(runAndReadModules(await buildSsr(true))).toEqual(INJECTED_MODULES); + const external = await buildSsr(false); + expect(external).toContain('require("sdk")'); + expect(external).not.toContain('"installed"'); + }); + + it('does not inject into client builds', async () => { + const outDir = path.join(root, 'dist'); + await build({ + configFile: false, + logLevel: 'silent', + root, + plugins: plugins(), + build: { outDir, lib: { entry: path.join(root, 'entry.js'), formats: ['es'] }, minify: false }, + }); + + expect(runAndReadModules(readJs(outDir))).toBeUndefined(); + }); + + it('injects only into environments with the server consumer', async () => { + const clientOutDir = path.join(root, 'dist', 'client'); + const serverOutDir = path.join(root, 'dist', 'server'); + const builder = await createBuilder({ + configFile: false, + logLevel: 'silent', + root, + plugins: plugins(), + environments: { + client: { + build: { outDir: clientOutDir, rollupOptions: { input: path.join(root, 'entry.js') }, minify: false }, + }, + ssr: { + build: { + outDir: serverOutDir, + ssr: path.join(root, 'entry.js'), + minify: false, + rollupOptions: { output: { format: 'cjs' } }, + }, + }, + }, + }); + await builder.buildApp(); + + expect(runAndReadModules(readJs(path.join(clientOutDir, 'assets')))).toBeUndefined(); + expect(runAndReadModules(readJs(serverOutDir))).toEqual(INJECTED_MODULES); + }); +}); diff --git a/packages/bundler-plugins/test/vite/public-api.test.ts b/packages/bundler-plugins/test/vite/public-api.test.ts index 08fcae0c6212..8f476a18aa68 100644 --- a/packages/bundler-plugins/test/vite/public-api.test.ts +++ b/packages/bundler-plugins/test/vite/public-api.test.ts @@ -24,7 +24,35 @@ describe('sentryVitePlugin', () => { const pluginNames = plugins.map(plugin => plugin.name); - expect(pluginNames).toEqual(['sentry-vite-plugin', 'sentry-vite-upload-staging']); + expect(pluginNames).toEqual(['sentry-vite-plugin', 'sentry-vite-module-versions', 'sentry-vite-upload-staging']); + }); + + it('replaces the module versions placeholder only in its own plugin, for server environments', () => { + const plugins = sentryVitePlugin({ telemetry: false }); + const main = plugins.find(plugin => plugin.name === 'sentry-vite-plugin'); + const moduleVersions = plugins.find(plugin => plugin.name === 'sentry-vite-module-versions') as { + applyToEnvironment: (environment: { config: { consumer: string } }) => boolean; + transform: { filter: { code: string } }; + }; + + expect(main).not.toHaveProperty('transform'); + expect(moduleVersions.transform.filter.code).toBe('__SENTRY_SERVER_MODULES__'); + expect(moduleVersions.applyToEnvironment({ config: { consumer: 'server' } })).toBe(true); + expect(moduleVersions.applyToEnvironment({ config: { consumer: 'client' } })).toBe(false); + }); + + it('applies the module versions plugin to every environment with `injectModuleVersions: true`', () => { + const plugins = sentryVitePlugin({ telemetry: false, injectModuleVersions: true }); + + expect(plugins.find(plugin => plugin.name === 'sentry-vite-module-versions')).not.toHaveProperty( + 'applyToEnvironment', + ); + }); + + it('adds no module versions plugin with `injectModuleVersions: false`', () => { + const plugins = sentryVitePlugin({ telemetry: false, injectModuleVersions: false }); + + expect(plugins.map(plugin => plugin.name)).not.toContain('sentry-vite-module-versions'); }); it('returns an array of Vite pluginswhen unplugin returns a single plugin', () => { diff --git a/packages/bundler-plugins/test/webpack/module-versions-injection.test.ts b/packages/bundler-plugins/test/webpack/module-versions-injection.test.ts new file mode 100644 index 000000000000..92e1cb74082f --- /dev/null +++ b/packages/bundler-plugins/test/webpack/module-versions-injection.test.ts @@ -0,0 +1,67 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { webpack } from 'webpack'; +import type { Configuration } from 'webpack'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { sentryWebpackPlugin } from '../../src/webpack/index'; +import type { Options } from '../../src/core'; +import { createModuleVersionsProject, INJECTED_MODULES, runAndReadModules } from '../utils/module-versions-project'; + +describe('module versions injection (webpack)', () => { + let root: string; + + beforeEach(() => { + root = createModuleVersionsProject(); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + function buildApp(target: Configuration['target'], options: Options = {}): Promise { + const outDir = path.join(root, 'dist'); + return new Promise((resolve, reject) => { + webpack( + { + mode: 'none', + context: root, + target, + entry: './entry.js', + output: { path: outDir, filename: 'main.js' }, + plugins: [sentryWebpackPlugin({ telemetry: false, silent: true, release: { create: false }, ...options })], + }, + (err, stats) => { + if (err || !stats || stats.hasErrors()) { + return reject(err ?? new Error(stats?.toString() ?? 'no stats')); + } + resolve(fs.readFileSync(path.join(outDir, 'main.js'), 'utf8')); + }, + ); + }); + } + + it.each(['node', 'async-node', 'node18', ['node20', 'es2020'], 'electron-main', 'electron28-main'])( + 'injects into builds with the %j target', + { timeout: 15_000 }, + async target => { + expect(runAndReadModules(await buildApp(target))).toEqual(INJECTED_MODULES); + }, + ); + + it.each([ + undefined, + 'web', + 'webworker', + ['web', 'es6'], + 'node-webkit', + 'nwjs', + 'electron-preload', + 'electron-renderer', + ])('does not inject into builds with the %j target', { timeout: 15_000 }, async target => { + expect(runAndReadModules(await buildApp(target))).toBeUndefined(); + }); + + it('does not inject with `injectModuleVersions: false`', { timeout: 15_000 }, async () => { + expect(runAndReadModules(await buildApp('node', { injectModuleVersions: false }))).toBeUndefined(); + }); +}); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 046106d68909..cce5612b5404 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -72,3 +72,4 @@ export { createFetchIntegration } from './integrations/fetch'; export type { FetchIntegrationOptions } from './integrations/fetch'; export { classifyResponseStreaming } from './utils/responseStreaming'; export type { StreamingGuess } from './utils/responseStreaming'; +export { collectInstalledModules } from './utils/installedModules'; diff --git a/packages/server-utils/src/utils/installedModules.ts b/packages/core/src/utils/installedModules.ts similarity index 100% rename from packages/server-utils/src/utils/installedModules.ts rename to packages/core/src/utils/installedModules.ts diff --git a/packages/server-utils/test/utils/installedModules.test.ts b/packages/core/test/lib/utils/installedModules.test.ts similarity index 98% rename from packages/server-utils/test/utils/installedModules.test.ts rename to packages/core/test/lib/utils/installedModules.test.ts index d487abc0bfea..617cb032f712 100644 --- a/packages/server-utils/test/utils/installedModules.test.ts +++ b/packages/core/test/lib/utils/installedModules.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { collectInstalledModules } from '../../src/utils/installedModules'; +import { collectInstalledModules } from '../../../src/utils/installedModules'; function makeFs(files: Record): (path: string) => string | undefined { return path => { diff --git a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts index 1153c654a8b0..7e92aac9778e 100644 --- a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts +++ b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts @@ -3,7 +3,7 @@ import type { VercelCronsConfig } from '../../common/types'; import type { RouteManifest } from '../manifest/types'; import type { JSONValue, TurbopackMatcherWithRule } from '../types'; import type { TunnelRouteInjectedValues } from '../withSentryConfig/tunnel'; -import { getPackageModules, supportsTurbopackRuleCondition } from '../util'; +import { supportsTurbopackRuleCondition } from '../util'; /** * Generate the value injection rules for client and server in turbopack config. @@ -58,10 +58,6 @@ export function generateValueInjectionRules({ serverValues._sentryRewriteFramesDistDir = distDirName; } - // Inject server modules (matching webpack's __SENTRY_SERVER_MODULES__ behavior) - // Use process.cwd() to get the project directory at build time - serverValues.__SENTRY_SERVER_MODULES__ = getPackageModules(process.cwd()); - if (Object.keys(isomorphicValues).length > 0) { clientValues = { ...clientValues, ...isomorphicValues }; serverValues = { ...serverValues, ...isomorphicValues }; diff --git a/packages/nextjs/src/config/types.ts b/packages/nextjs/src/config/types.ts index e8d1489172ec..e94dcbd27a93 100644 --- a/packages/nextjs/src/config/types.ts +++ b/packages/nextjs/src/config/types.ts @@ -74,6 +74,7 @@ export type NextConfigObject = { turbopack?: TurbopackOptions; compiler?: { define?: Record; + defineServer?: Record; runAfterProductionCompile?: (context: { distDir: string; projectDir: string }) => Promise | void; }; }; diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 49e3e3080944..eea577b1dbd3 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -1,5 +1,4 @@ import { parseSemver } from '@sentry/core'; -import { collectInstalledModules } from '@sentry/server-utils/no-diagnostic-channels'; import * as fs from 'fs'; import { createRequire } from 'module'; @@ -219,17 +218,3 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { return 'webpack'; } } - -/** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ -export function getPackageModules(projectDir: string): Record { - return collectInstalledModules({ - readFile: filePath => { - try { - return fs.readFileSync(filePath, 'utf8'); - } catch { - return undefined; - } - }, - cwd: projectDir, - }); -} diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 72bad5ce5eb9..ab30575b3996 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -25,7 +25,7 @@ import type { WebpackPluginInstance, } from './types'; import { sentryOrchestrionWebpackPlugin } from '@sentry/server-utils/orchestrion/webpack'; -import { DEFAULT_PAGE_EXTENSIONS, getNextjsVersion, getPackageModules } from './util'; +import { DEFAULT_PAGE_EXTENSIONS, getNextjsVersion } from './util'; import type { VercelCronsConfigResult } from './withSentryConfig/getFinalConfigObjectUtils'; import { shouldInjectReleaseIntoClient } from './withSentryConfig/release'; import { getTunnelRouteInjectedValues } from './withSentryConfig/tunnel'; @@ -421,16 +421,9 @@ export function constructWebpackConfigFunction({ setupTreeshakingFromConfig(userSentryOptions, newConfig, buildContext); - // We inject a map of dependencies that the nextjs app has, as we cannot reliably extract them at runtime, sadly - newConfig.plugins = newConfig.plugins || []; - newConfig.plugins.push( - new buildContext.webpack.DefinePlugin({ - __SENTRY_SERVER_MODULES__: JSON.stringify(getPackageModules(projectDir)), - }), - ); - // Orchestrion code-transform loader — Node server runtime only, never the edge compilation if (runtime === 'server' && userSentryOptions.buildTimeInstrumentation !== false) { + newConfig.plugins = newConfig.plugins || []; newConfig.plugins.push(sentryOrchestrionWebpackPlugin() as unknown as WebpackPluginInstance); prependOrchestrionRuntimeExternals(newConfig); } diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index cc238b65824e..58a4089a2836 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -7,6 +7,7 @@ import { getBundlerInfo, getServerExternalPackagesPatch, getTurbopackPatch, + getTurbopackServerModulesPatch, getWebpackPatch, maybeConstructTurbopackConfig, maybeEnableTurbopackSourcemaps, @@ -119,6 +120,7 @@ export function getFinalConfigObject( vercelCronsConfigResult, }), ...getTurbopackPatch(bundlerInfo, turboPackConfig), + ...getTurbopackServerModulesPatch(incomingUserNextConfigObject, bundlerInfo), }; } diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index 9feb66f0d304..9882c2121112 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -1,3 +1,6 @@ +/* oxlint-disable max-lines */ +import { getInstalledModules } from '@sentry/bundler-plugins/loader-utils'; +import { stringifyForCodeInjection } from '@sentry/core'; import { BUNDLE_SAFE_INSTRUMENTED_PACKAGES, filterInstrumentedExternals, @@ -392,6 +395,35 @@ export function maybeSetTurbopackTreeshakeDefines( }; } +/** + * Returns the patch that replaces the `__SENTRY_SERVER_MODULES__` placeholder in Turbopack server builds through + * `compiler.defineServer`, like the Sentry webpack plugin does for webpack builds. + */ +export function getTurbopackServerModulesPatch( + incomingUserNextConfigObject: NextConfigObject, + bundlerInfo: BundlerInfo, +): Partial { + if (!bundlerInfo.isTurbopackSupported || !bundlerInfo.isTurbopack) { + return {}; + } + + const serverModules = getInstalledModules(process.cwd()); + if (Object.keys(serverModules).length === 0) { + return {}; + } + + return { + compiler: { + ...incomingUserNextConfigObject.compiler, + defineServer: { + // Next.js only accepts strings here, so the SDK gets the versions as JSON. + __SENTRY_SERVER_MODULES__: stringifyForCodeInjection(serverModules), + ...incomingUserNextConfigObject.compiler?.defineServer, + }, + }, + }; +} + /** * Returns the patch for adding turbopack config (if enabled and supported). */ diff --git a/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts b/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts index fdf4aa6fbe4b..f5189b01ef44 100644 --- a/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts +++ b/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts @@ -53,7 +53,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -82,7 +81,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRelease: 'my-app@1.2.3', _sentryRewriteFramesDistDir: 'build', @@ -123,7 +121,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -211,7 +208,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -264,7 +260,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -349,7 +344,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -396,7 +390,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -440,7 +433,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -482,7 +474,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: '15.0.0', @@ -540,7 +531,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: '14.0.0', @@ -585,7 +575,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -653,7 +642,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, @@ -697,7 +685,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, @@ -752,7 +739,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, @@ -801,7 +787,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -829,7 +814,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', }, @@ -928,7 +912,6 @@ describe('constructTurbopackConfig', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, diff --git a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts index 34756d937204..e6d7609f91ca 100644 --- a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts +++ b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts @@ -34,7 +34,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, @@ -60,7 +59,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, @@ -88,7 +86,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryRelease: 'my-app@1.2.3', _sentryRewriteFramesDistDir: 'build', @@ -135,7 +132,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryNextJsVersion: '14.0.0', }, @@ -170,7 +166,6 @@ describe('generateValueInjectionRules', () => { ], }); - // Server rule should exist with __SENTRY_SERVER_MODULES__ const serverRule = result.find(rule => rule.matcher === '**/instrumentation.*'); expect(serverRule).toBeDefined(); expect(serverRule?.rule).toEqual({ @@ -179,7 +174,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, @@ -219,7 +213,6 @@ describe('generateValueInjectionRules', () => { { options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, @@ -268,7 +261,6 @@ describe('generateValueInjectionRules', () => { { options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, @@ -304,7 +296,7 @@ describe('generateValueInjectionRules', () => { ], }); - // Server rule should have __SENTRY_SERVER_MODULES__ and nextJsVersion + // Server rule should have nextJsVersion const serverRule = result.find(rule => rule.matcher === '**/instrumentation.*'); expect(serverRule).toBeDefined(); expect(serverRule?.rule).toEqual({ @@ -313,7 +305,6 @@ describe('generateValueInjectionRules', () => { loader: '/mocked/path/to/valueInjectionLoader.js', options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, _sentryNextJsVersion: '14.0.0', }, @@ -359,7 +350,6 @@ describe('generateValueInjectionRules', () => { { _sentryTunnelRoute: '/monitoring', _sentryTurbopack: true, - __SENTRY_SERVER_MODULES__: expect.any(Object), }, ], ]); @@ -376,10 +366,7 @@ describe('generateValueInjectionRules', () => { ]); expect(injectedValues).toEqual([ ['**/instrumentation-client.*', { _sentryBasePath: '/docs' }], - [ - '**/instrumentation.*', - { _sentryBasePath: '/docs', _sentryTurbopack: true, __SENTRY_SERVER_MODULES__: expect.any(Object) }, - ], + ['**/instrumentation.*', { _sentryBasePath: '/docs', _sentryTurbopack: true }], ]); }); }); @@ -479,7 +466,6 @@ describe('generateValueInjectionRules', () => { loader: expect.any(String), options: { values: { - __SENTRY_SERVER_MODULES__: expect.any(Object), _sentryTurbopack: true, }, }, diff --git a/packages/nextjs/test/config/turbopackServerModules.test.ts b/packages/nextjs/test/config/turbopackServerModules.test.ts new file mode 100644 index 000000000000..9af0f2faa9f4 --- /dev/null +++ b/packages/nextjs/test/config/turbopackServerModules.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi } from 'vitest'; +import { getTurbopackServerModulesPatch } from '../../src/config/withSentryConfig/getFinalConfigObjectBundlerUtils'; + +const modules = { 'a': '1.0.0\u2028' }; + +vi.mock('@sentry/bundler-plugins/loader-utils', () => ({ getInstalledModules: () => modules })); + +describe('getTurbopackServerModulesPatch', () => { + it('escapes the module versions for code injection and keeps them parseable', () => { + const patch = getTurbopackServerModulesPatch( + {}, + { isTurbopack: true, isWebpack: false, isTurbopackSupported: true }, + ); + const value = patch.compiler?.defineServer?.__SENTRY_SERVER_MODULES__ as string; + + expect(value).not.toMatch(/[<>\u2028]/); + expect(JSON.parse(value)).toEqual(modules); + }); +}); diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index 0908faab2a44..8dacd35609cf 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -398,18 +398,10 @@ describe('constructWebpackConfigFunction()', () => { sentryBuildTimeOptions: {}, }); - const definePlugin = finalWebpackConfig.plugins?.find( - plugin => plugin.constructor.name === 'DefinePlugin', - ) as any; + const definePlugin = finalWebpackConfig.plugins?.find(plugin => plugin.constructor.name === 'DefinePlugin'); - // Should not have a DefinePlugin for treeshaking (may have one for __SENTRY_SERVER_MODULES__) - if (definePlugin) { - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_DEBUG__'); - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_TRACING__'); - expect(definePlugin.definitions).not.toHaveProperty('__RRWEB_EXCLUDE_IFRAME__'); - expect(definePlugin.definitions).not.toHaveProperty('__RRWEB_EXCLUDE_SHADOW_DOM__'); - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_EXCLUDE_REPLAY_WORKER__'); - } + // The Sentry webpack plugin injects `__SENTRY_SERVER_MODULES__`, so nothing else needs a DefinePlugin. + expect(definePlugin).toBeUndefined(); }); it('does not add DefinePlugin when treeshake option is empty object', async () => { @@ -430,18 +422,9 @@ describe('constructWebpackConfigFunction()', () => { }, }); - const definePlugin = finalWebpackConfig.plugins?.find( - plugin => plugin.constructor.name === 'DefinePlugin', - ) as any; + const definePlugin = finalWebpackConfig.plugins?.find(plugin => plugin.constructor.name === 'DefinePlugin'); - // Should not have treeshaking flags in DefinePlugin - if (definePlugin) { - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_DEBUG__'); - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_TRACING__'); - expect(definePlugin.definitions).not.toHaveProperty('__RRWEB_EXCLUDE_IFRAME__'); - expect(definePlugin.definitions).not.toHaveProperty('__RRWEB_EXCLUDE_SHADOW_DOM__'); - expect(definePlugin.definitions).not.toHaveProperty('__SENTRY_EXCLUDE_REPLAY_WORKER__'); - } + expect(definePlugin).toBeUndefined(); }); it('adds __SENTRY_DEBUG__ flag when debugLogging is true', async () => { @@ -693,9 +676,7 @@ describe('constructWebpackConfigFunction()', () => { }, }); - const definePlugin = finalWebpackConfig.plugins?.find( - plugin => plugin.constructor.name === 'DefinePlugin', - ) as any; + const definePlugin = finalWebpackConfig.plugins?.find(plugin => plugin.constructor.name === 'DefinePlugin'); // Should not have treeshaking flags if (definePlugin) { diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index 948e9a36dc0e..55f32e347159 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -554,6 +554,42 @@ describe('withSentryConfig', () => { }); }); + describe('turbopack server modules', () => { + const originalTurbopack = process.env.TURBOPACK; + + afterEach(() => { + vi.restoreAllMocks(); + process.env.TURBOPACK = originalTurbopack; + }); + + it('replaces `__SENTRY_SERVER_MODULES__` in server builds and keeps user server defines', () => { + process.env.TURBOPACK = '1'; + vi.spyOn(util, 'getNextjsVersion').mockReturnValue('16.0.0'); + + const finalConfig = materializeFinalNextConfig({ + ...exportedNextConfig, + compiler: { defineServer: { USER_FLAG: 'x' } }, + }); + + expect(finalConfig.compiler?.defineServer).toEqual({ + __SENTRY_SERVER_MODULES__: expect.any(String), + USER_FLAG: 'x', + }); + expect(JSON.parse(finalConfig.compiler?.defineServer?.__SENTRY_SERVER_MODULES__ as string)).toEqual( + expect.objectContaining({ next: expect.any(String) }), + ); + expect(finalConfig.compiler?.define).toBeUndefined(); + }); + + it('does not set the define on webpack builds', () => { + delete process.env.TURBOPACK; + + const finalConfig = materializeFinalNextConfig({ ...exportedNextConfig }); + + expect(finalConfig.compiler?.defineServer).toBeUndefined(); + }); + }); + describe('turbopack sourcemap configuration', () => { const originalTurbopack = process.env.TURBOPACK; diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 5891d0c73710..9ee1a2be49d3 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { Module } from 'node:module'; -import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; -import { collectInstalledModules } from '@sentry/server-utils'; +import type { IntegrationFn } from '@sentry/core'; +import { collectInstalledModules } from '@sentry/core/server'; type ModuleInfo = Record; @@ -9,26 +9,27 @@ let moduleCache: ModuleInfo | undefined; const INTEGRATION_NAME = 'Modules' as const; -declare const __SENTRY_SERVER_MODULES__: Record; +declare const __SENTRY_SERVER_MODULES__: Record | string; -/** - * Reads the modules injected at build time into `__SENTRY_SERVER_MODULES__` (e.g. by the Next.js SDK). - * - * Must be read lazily (per call), not captured at module-eval time: webpack replaces the token via - * `DefinePlugin` (available immediately), but Turbopack assigns `globalThis.__SENTRY_SERVER_MODULES__` - * at runtime, *after* this module's imports are hoisted and evaluated. A `const` capture would be - * empty under Turbopack. See getsentry/sentry-javascript#19147. - */ +/** Reads the module versions that a bundler injected at build time. */ function getServerModules(): Record { - // webpack: the token is replaced with a literal at build time. - if (typeof __SENTRY_SERVER_MODULES__ !== 'undefined') { - return __SENTRY_SERVER_MODULES__; + let serverModules: Record | string | undefined; + try { + // The only reference to the placeholder, so a bundler that replaces it inlines the versions once. + serverModules = __SENTRY_SERVER_MODULES__; + } catch { + // Not replaced at build time + return {}; + } + if (typeof serverModules !== 'string') { + return serverModules || {}; + } + // Next.js Turbopack builds pass JSON, because `compiler.defineServer` only accepts strings. + try { + return JSON.parse(serverModules) as Record; + } catch { + return {}; } - // Turbopack: the value is assigned onto the global object at runtime. - return ( - (GLOBAL_OBJ as typeof GLOBAL_OBJ & { __SENTRY_SERVER_MODULES__?: Record }) - .__SENTRY_SERVER_MODULES__ ?? {} - ); } const _modulesIntegration = (() => { diff --git a/packages/node/test/integrations/modules.test.ts b/packages/node/test/integrations/modules.test.ts index 8fc3ed484c41..ae5f2957c5f0 100644 --- a/packages/node/test/integrations/modules.test.ts +++ b/packages/node/test/integrations/modules.test.ts @@ -1,34 +1,25 @@ -import { GLOBAL_OBJ } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; -type GlobalWithModules = typeof GLOBAL_OBJ & { __SENTRY_SERVER_MODULES__?: Record }; +type GlobalWithModules = typeof globalThis & { __SENTRY_SERVER_MODULES__?: Record | string }; describe('modulesIntegration', () => { afterEach(() => { - delete (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__; + delete (globalThis as GlobalWithModules).__SENTRY_SERVER_MODULES__; vi.resetModules(); }); - it('includes modules injected onto the global AFTER this module was evaluated (Turbopack ordering)', async () => { - // Re-evaluate the integration module with no injected global present. This mirrors Turbopack: - // the instrumentation file's hoisted ESM imports evaluate this module *before* its - // `globalThis.__SENTRY_SERVER_MODULES__ = {...}` assignment runs. A module-level capture would - // freeze an empty value here and never see the injection (getsentry/sentry-javascript#19147). - vi.resetModules(); + // Without a bundler, the placeholder resolves to the global. + it('uses the modules that replace `__SENTRY_SERVER_MODULES__` as is', async () => { + (globalThis as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/build-injected': '1.2.3' }; const { modulesIntegration } = await import('../../src/integrations/modules'); - // The runtime injection happens only now — after the module is already evaluated. - (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/turbopack-injected': '1.2.3' }; - - expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/turbopack-injected': '1.2.3' }); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/build-injected': '1.2.3' }); }); - it('uses only modules already present before evaluation (webpack DefinePlugin / pre-set global)', async () => { - (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/prebuilt-injected': '4.5.6' }; - - vi.resetModules(); + it('parses modules that replace `__SENTRY_SERVER_MODULES__` as JSON', async () => { + (globalThis as GlobalWithModules).__SENTRY_SERVER_MODULES__ = JSON.stringify({ '@sentry/build-injected': '1.2.3' }); const { modulesIntegration } = await import('../../src/integrations/modules'); - expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/prebuilt-injected': '4.5.6' }); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/build-injected': '1.2.3' }); }); }); diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index ded5a827068a..ac9ccea63acc 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -1,5 +1,6 @@ +/* oxlint-disable max-lines */ import type { Nuxt } from '@nuxt/schema'; -import { resolveReleaseName } from '@sentry/bundler-plugins/core'; +import { getDisabledSourcemapsOptions, resolveReleaseName } from '@sentry/bundler-plugins/core'; import { sentryRollupPlugin, type SentryRollupPluginOptions } from '@sentry/bundler-plugins/rollup'; import { sentryVitePlugin, type SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; @@ -117,30 +118,41 @@ export function setupSourceMaps( } nuxt.hook('nitro:config', (nitroConfig: NitroConfig) => { - if (sourceMapsEnabled && !nitroConfig.dev && !nuxt.options?._prepare) { - nitroConfig.rollupConfig ??= {}; - - if (nitroConfig.rollupConfig.plugins === null || nitroConfig.rollupConfig.plugins === undefined) { - nitroConfig.rollupConfig.plugins = []; - } else if (!Array.isArray(nitroConfig.rollupConfig.plugins)) { - // `rollupConfig.plugins` can be a single plugin, so we want to put it into an array so that we can push our own plugin - nitroConfig.rollupConfig.plugins = [nitroConfig.rollupConfig.plugins]; - } + if (nitroConfig.dev || nuxt.options?._prepare) { + return; + } - validateNitroSourceMapSettings(nuxt, nitroConfig, moduleOptions); - applyNitroSourceMapSettings(nitroConfig, shouldDeleteFilesFallback, moduleOptions.sourcemaps?.delete); + nitroConfig.rollupConfig ??= {}; - if (isDebug) { - // eslint-disable-next-line no-console - console.log('[Sentry] Adding Sentry Rollup plugin to the server runtime.'); - } + if (nitroConfig.rollupConfig.plugins === null || nitroConfig.rollupConfig.plugins === undefined) { + nitroConfig.rollupConfig.plugins = []; + } else if (!Array.isArray(nitroConfig.rollupConfig.plugins)) { + // `rollupConfig.plugins` can be a single plugin, so we want to put it into an array so that we can push our own plugin + nitroConfig.rollupConfig.plugins = [nitroConfig.rollupConfig.plugins]; + } - // Add Sentry plugin - // Runs only on server-side (Nitro) + if (!sourceMapsEnabled) { + // TODO: Revisit which features the plugin should run when source maps are off. For now it only injects module + // versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime. nitroConfig.rollupConfig.plugins.push( - sentryRollupPlugin(withoutSourceMapDeletion(getPluginOptions(moduleOptions, shouldDeleteFilesFallback))), + sentryRollupPlugin(getDisabledSourcemapsOptions({ debug: moduleOptions.debug, injectModuleVersions: true })), ); + return; } + + validateNitroSourceMapSettings(nuxt, nitroConfig, moduleOptions); + applyNitroSourceMapSettings(nitroConfig, shouldDeleteFilesFallback, moduleOptions.sourcemaps?.delete); + + if (isDebug) { + // eslint-disable-next-line no-console + console.log('[Sentry] Adding Sentry Rollup plugin to the server runtime.'); + } + + // Add Sentry plugin + // Runs only on server-side (Nitro) + const serverPluginOptions = withoutSourceMapDeletion(getPluginOptions(moduleOptions, shouldDeleteFilesFallback)); + // Rollup cannot tell that Nitro's output runs on the server. + nitroConfig.rollupConfig.plugins.push(sentryRollupPlugin({ ...serverPluginOptions, injectModuleVersions: true })); }); nuxt.hook('nitro:init', nitro => { diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index b0722f380fc3..19bd58bfa783 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -729,7 +729,7 @@ describe('setupSourceMaps hooks', () => { const nitroConfig = { rollupConfig: { plugins: [] as unknown[], output: {} }, dev: false }; await mockNuxt.triggerHook('nitro:config', nitroConfig); - expect(mockSentryRollupPlugin).toHaveBeenCalled(); + expect(mockSentryRollupPlugin).toHaveBeenCalledWith(expect.objectContaining({ injectModuleVersions: true })); expect(nitroConfig.rollupConfig.plugins.length).toBeGreaterThan(0); }); @@ -787,6 +787,38 @@ describe('setupSourceMaps hooks', () => { expect(mockSentryRollupPlugin).not.toHaveBeenCalled(); }); + + it('only adds sentryRollupPlugin for module versions when source maps are disabled', async () => { + const mockNuxt = createMockNuxt({ _prepare: false, dev: false }); + const { mockAddVitePlugin } = createMockAddVitePlugin(); + + setupSourceMaps({ sourcemaps: { disable: true }, debug: true }, mockNuxt as unknown as Nuxt, mockAddVitePlugin); + await mockNuxt.triggerHook('modules:done'); + + const nitroConfig = { rollupConfig: { plugins: [{ name: 'user-plugin' }] as unknown[] }, dev: false }; + await mockNuxt.triggerHook('nitro:config', nitroConfig); + + expect(mockSentryVitePlugin).not.toHaveBeenCalled(); + expect(mockSentryRollupPlugin).toHaveBeenCalledTimes(1); + expect(mockSentryRollupPlugin).toHaveBeenCalledWith({ + debug: true, + injectModuleVersions: true, + telemetry: false, + sourcemaps: { upload: false, injectDebugIds: false }, + release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false }, + }); + expect(nitroConfig.rollupConfig.plugins).toEqual([{ name: 'user-plugin' }, { name: 'sentry-rollup-plugin' }]); + }); + + it('does not add sentryRollupPlugin for module versions in dev mode when source maps are disabled', async () => { + const mockNuxt = createMockNuxt({ dev: true }); + const { mockAddVitePlugin } = createMockAddVitePlugin(); + + setupSourceMaps({ sourcemaps: { disable: true } }, mockNuxt as unknown as Nuxt, mockAddVitePlugin); + await mockNuxt.triggerHook('nitro:config', { rollupConfig: { plugins: [] }, dev: true }); + + expect(mockSentryRollupPlugin).not.toHaveBeenCalled(); + }); }); describe('nitro:init hook', () => { diff --git a/packages/server-utils/src/exports.ts b/packages/server-utils/src/exports.ts index 94e49d229749..d9fae4eb0f29 100644 --- a/packages/server-utils/src/exports.ts +++ b/packages/server-utils/src/exports.ts @@ -6,7 +6,6 @@ export * from './ai'; export { getSqlQuerySummary, sanitizeSqlQuery, getSqlQueryAttributes, getSqlSpanName } from './utils/sql'; export type { SqlDialect } from './utils/sql'; export { isBun, isCloudflareWorkers, isDeno } from './utils/runtime'; -export { collectInstalledModules } from './utils/installedModules'; export { instrumentPostgresJsSql } from './integrations/postgresjs-wrapper'; export type { PostgresConnectionContext } from './integrations/postgresjs-wrapper'; diff --git a/packages/solidstart/src/vite/sentrySolidStart.ts b/packages/solidstart/src/vite/sentrySolidStart.ts index e3b998c007a0..2d1caba975fa 100644 --- a/packages/solidstart/src/vite/sentrySolidStart.ts +++ b/packages/solidstart/src/vite/sentrySolidStart.ts @@ -5,6 +5,8 @@ import { stringifyForCodeInjection, warnOnRemovedBuildOptions, } from '@sentry/core'; +import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core'; +import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { setupSentryNitroModule } from '@sentry/nitro'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import type { Plugin, UserConfig } from 'vite'; @@ -74,6 +76,10 @@ export function sentrySolidStart(options: SentrySolidStartOptions = {}): Plugin[ ...makeEnableSourceMapsVitePlugin(options, sourceMapState), ...makeAddSentryVitePluginSolidStart2(options, sourceMapState, runtimeRelease), ); + } else { + // TODO: Revisit which features the plugin should run when source maps are off. For now it only injects module + // versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime. + plugins.push(...sentryVitePlugin(getDisabledSourcemapsOptions({ debug: options.debug }))); } return plugins; diff --git a/packages/solidstart/src/vite/sentrySolidStartVite.ts b/packages/solidstart/src/vite/sentrySolidStartVite.ts index 5f0d26b6ddb8..742ffe66162b 100644 --- a/packages/solidstart/src/vite/sentrySolidStartVite.ts +++ b/packages/solidstart/src/vite/sentrySolidStartVite.ts @@ -1,3 +1,5 @@ +import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core'; +import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures, stringifyForCodeInjection, warnOnRemovedBuildOptions } from '@sentry/core'; import type { Plugin, UserConfig } from 'vite'; import { makeBuildInstrumentationFilePlugin } from './buildInstrumentationFile'; @@ -40,6 +42,10 @@ export const sentrySolidStartVite = ( ...makeEnableSourceMapsVitePlugin(options, sourceMapState), ...makeAddSentryVitePlugin(options, sourceMapState, runtimeRelease), ); + } else { + // TODO: Revisit which features the plugin should run when source maps are off. For now it only injects module + // versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime. + sentryPlugins.push(...sentryVitePlugin(getDisabledSourcemapsOptions({ debug: options.debug }))); } } diff --git a/packages/solidstart/test/config/withSentry.test.ts b/packages/solidstart/test/config/withSentry.test.ts index 583081ac4bcd..fc24ed5cc308 100644 --- a/packages/solidstart/test/config/withSentry.test.ts +++ b/packages/solidstart/test/config/withSentry.test.ts @@ -163,6 +163,7 @@ describe('withSentry()', () => { 'sentry-solidstart-build-instrumentation-file', 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', ]); }); @@ -188,6 +189,7 @@ describe('withSentry()', () => { 'sentry-solidstart-build-instrumentation-file', 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', 'my-test-plugin', ]); @@ -217,6 +219,7 @@ describe('withSentry()', () => { 'sentry-solidstart-build-instrumentation-file', 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', 'my-test-plugin', ]); diff --git a/packages/solidstart/test/vite/sentrySolidStart.test.ts b/packages/solidstart/test/vite/sentrySolidStart.test.ts index c72ed1e5f427..8f5c491e900e 100644 --- a/packages/solidstart/test/vite/sentrySolidStart.test.ts +++ b/packages/solidstart/test/vite/sentrySolidStart.test.ts @@ -61,6 +61,7 @@ describe('sentrySolidStart()', () => { 'code-transformer', 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', ]); }); @@ -78,10 +79,17 @@ describe('sentrySolidStart()', () => { expect(names).toContain('sentry-solidstart-update-source-map-setting'); }); - it('omits the source maps plugins when source maps are disabled', () => { + it('only adds the bundler plugin for module versions when source maps are disabled', () => { const names = sentrySolidStart({ sourcemaps: { disable: true } }).map(plugin => plugin.name); - expect(names).toEqual(['sentry-solidstart-nitro', 'sentry-solidstart-server-entry', 'code-transformer']); + expect(names).toEqual([ + 'sentry-solidstart-nitro', + 'sentry-solidstart-server-entry', + 'code-transformer', + 'sentry-vite-plugin', + 'sentry-vite-module-versions', + 'sentry-vite-upload-staging', + ]); }); // `'disable-upload'` still injects debug IDs, so the plugins have to run; the bundler plugin diff --git a/packages/solidstart/test/vite/sentrySolidStartVite.test.ts b/packages/solidstart/test/vite/sentrySolidStartVite.test.ts index 6d1c76c851f0..3b52904f886b 100644 --- a/packages/solidstart/test/vite/sentrySolidStartVite.test.ts +++ b/packages/solidstart/test/vite/sentrySolidStartVite.test.ts @@ -1,4 +1,5 @@ import type { Plugin } from 'vite'; +import * as bundlerPluginsVite from '@sentry/bundler-plugins/vite'; import { describe, expect, it, vi } from 'vitest'; import { sentrySolidStartVite } from '../../src/vite/sentrySolidStartVite'; @@ -27,14 +28,30 @@ describe('sentrySolidStartVite()', () => { 'sentry-solidstart-build-instrumentation-file', 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', ]); }); - it("returns only build-instrumentation-file plugin if source maps upload isn't enabled", () => { - const plugins = getSentrySolidStartVitePlugins({ sourcemaps: { disable: true } }); + it("only adds the bundler plugin for module versions if source maps upload isn't enabled", () => { + const sentryVitePluginSpy = vi.spyOn(bundlerPluginsVite, 'sentryVitePlugin'); + sentryVitePluginSpy.mockClear(); + + const plugins = getSentrySolidStartVitePlugins({ sourcemaps: { disable: true }, debug: true }); const names = plugins.map(plugin => plugin.name); - expect(names).toEqual(['sentry-solidstart-tunnel-base-path', 'sentry-solidstart-build-instrumentation-file']); + expect(names).toEqual([ + 'sentry-solidstart-tunnel-base-path', + 'sentry-solidstart-build-instrumentation-file', + 'sentry-vite-plugin', + 'sentry-vite-module-versions', + 'sentry-vite-upload-staging', + ]); + expect(sentryVitePluginSpy).toHaveBeenCalledWith({ + debug: true, + telemetry: false, + sourcemaps: { upload: false, injectDebugIds: false }, + release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false }, + }); }); it('returns only build-instrumentation-file plugin if `NODE_ENV` is development', async () => { diff --git a/packages/sveltekit/src/vite/sentryVitePlugins.ts b/packages/sveltekit/src/vite/sentryVitePlugins.ts index 81851d5ff124..6f26886650f3 100644 --- a/packages/sveltekit/src/vite/sentryVitePlugins.ts +++ b/packages/sveltekit/src/vite/sentryVitePlugins.ts @@ -1,3 +1,5 @@ +import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core'; +import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { consoleSandbox, warnOnRemovedBuildOptions } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import * as fs from 'fs'; @@ -107,6 +109,10 @@ export async function sentrySvelteKit(options: SentrySvelteKitPluginOptions = {} getKitConfig, }); sentryPlugins.push(...sentryVitePlugins); + } else if (process.env.NODE_ENV !== 'development') { + // TODO: Revisit which features the plugin should run when source maps are off. For now it only injects module + // versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime. + sentryPlugins.push(...sentryVitePlugin(getDisabledSourcemapsOptions({ debug: mergedOptions.debug }))); } return sentryPlugins; diff --git a/packages/sveltekit/test/vite/sentrySvelteKitPlugins.test.ts b/packages/sveltekit/test/vite/sentrySvelteKitPlugins.test.ts index 08f5ac77d769..0c7281686967 100644 --- a/packages/sveltekit/test/vite/sentrySvelteKitPlugins.test.ts +++ b/packages/sveltekit/test/vite/sentrySvelteKitPlugins.test.ts @@ -3,6 +3,7 @@ import * as os from 'os'; import * as path from 'path'; import type { Plugin } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as bundlerPluginsVite from '@sentry/bundler-plugins/vite'; import * as autoInstrument from '../../src/vite/autoInstrument'; import { generateVitePluginOptions, sentrySvelteKit } from '../../src/vite/sentryVitePlugins'; import * as sourceMaps from '../../src/vite/sourceMaps'; @@ -70,8 +71,8 @@ describe('sentrySvelteKit()', () => { // 1 kit config resolver + 1 browser-tracing variant resolver + 1 OpenTelemetry API resolver // + 1 tunnel base path plugin + 1 auto instrument plugin // + 1 orchestrion plugin + 1 build flag plugin + 1 global values injection plugin + 1 modified main plugin - // + 1 debug ID plugin + 1 release injection plugin + 3 custom plugins - expect(plugins).toHaveLength(14); + // + 1 module versions plugin + 1 debug ID plugin + 1 release injection plugin + 3 custom plugins + expect(plugins).toHaveLength(15); }); it('returns the custom sentry source maps upload plugin, unmodified sourcemaps plugins and the auto-instrument plugin by default', async () => { @@ -96,6 +97,7 @@ describe('sentrySvelteKit()', () => { 'sentry-sveltekit-global-values-injection-plugin', // modified main plugin (writeBundle deferred to closeBundle): 'sentry-vite-plugin', + 'sentry-vite-module-versions', 'sentry-vite-upload-staging', // release injection plugin (replaces the bundler plugin's build-time injection): 'sentry-sveltekit-release-injection-plugin', @@ -106,9 +108,39 @@ describe('sentrySvelteKit()', () => { ]); }); - it("doesn't return the sentry source maps plugins if autoUploadSourcemaps is `false`", async () => { + it('only adds the bundler plugin for module versions if autoUploadSourceMaps is `false`', async () => { + const makePluginSpy = vi.spyOn(sourceMaps, 'makeCustomSentryVitePlugins'); + makePluginSpy.mockClear(); + const plugins = await getSentrySvelteKitPlugins({ autoUploadSourceMaps: false }); - expect(plugins).toHaveLength(7); // kit config resolver + browser-tracing variant resolver + OpenTelemetry API resolver + tunnel base path + auto instrument + orchestrion + build flag + + expect(makePluginSpy).not.toHaveBeenCalled(); + expect(plugins.map(plugin => plugin.name)).toEqual([ + 'sentry-sveltekit-kit-config-resolver', + 'sentry-sveltekit-browser-tracing-variant', + 'sentry-sveltekit-opentelemetry-api', + 'sentry-sveltekit-tunnel-base-path', + 'sentry-auto-instrumentation', + 'sentry-orchestrion-vite', + 'sentry-sveltekit-build-flag', + 'sentry-vite-plugin', + 'sentry-vite-module-versions', + 'sentry-vite-upload-staging', + ]); + }); + + it('turns off everything but module versions in the bundler plugin if autoUploadSourceMaps is `false`', async () => { + const sentryVitePluginSpy = vi.spyOn(bundlerPluginsVite, 'sentryVitePlugin'); + sentryVitePluginSpy.mockClear(); + + await getSentrySvelteKitPlugins({ autoUploadSourceMaps: false, debug: true }); + + expect(sentryVitePluginSpy).toHaveBeenCalledWith({ + debug: true, + telemetry: false, + sourcemaps: { upload: false, injectDebugIds: false }, + release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false }, + }); }); it("doesn't return the sentry source maps plugins if `NODE_ENV` is development", async () => { @@ -127,7 +159,7 @@ describe('sentrySvelteKit()', () => { it("doesn't return the auto instrument plugin if autoInstrument is `false`", async () => { const plugins = await getSentrySvelteKitPlugins({ autoInstrument: false }); const pluginNames = plugins.map(plugin => plugin.name); - expect(plugins).toHaveLength(13); // kit config resolver + browser-tracing variant resolver + OpenTelemetry API resolver + tunnel base path + orchestrion + build flag + global values injection + 1 modified main plugin + 1 debug ID plugin + 1 release injection plugin + 3 custom plugins + expect(plugins).toHaveLength(14); // kit config resolver + browser-tracing variant resolver + OpenTelemetry API resolver + tunnel base path + orchestrion + build flag + global values injection + 1 modified main plugin + 1 module versions plugin + 1 debug ID plugin + 1 release injection plugin + 3 custom plugins expect(pluginNames).not.toContain('sentry-auto-instrumentation'); });