From c29295cb111038a897ba5acd145342a13ecbb7ed Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Mon, 30 Nov 2026 11:34:17 +0100 Subject: [PATCH] fix(cli): Do not expose source maps in the wizard's Vite and webpack setup The source maps wizard set `build.sourcemap: true` or `devtool: "source-map"`. The Sentry plugin treats an explicit setting as the user's choice and keeps the source maps in the build output after uploading them. Leave the setting unset instead, so the plugin generates hidden source maps and removes them after the upload. Ask before removing a setting that disables source maps, and keep all other explicit values. Add the Vite plugin even if `build` is not an object literal. Ported from getsentry/sentry-wizard#1402. Co-Authored-By: Claude Opus 5.5 --- .../src/lib/wizard/sourcemaps/tools/vite.ts | 84 +++++++------- .../lib/wizard/sourcemaps/tools/webpack.ts | 82 +++++++------- .../sourcemaps/utils/disabled-source-maps.ts | 49 ++++++++ .../lib/wizard/sourcemaps/tools/vite.test.ts | 105 ++++++++++++++++-- .../wizard/sourcemaps/tools/webpack.test.ts | 78 ++++++++++--- 5 files changed, 290 insertions(+), 108 deletions(-) create mode 100644 packages/cli/src/lib/wizard/sourcemaps/utils/disabled-source-maps.ts diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts index 3b2f4350b..977c05760 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts @@ -1,6 +1,7 @@ /** - * Source maps setup for Vite: add the Sentry Vite plugin to the Vite config - * and turn on `build.sourcemap`. + * Source maps setup for Vite: add the Sentry Vite plugin to the Vite config. + * `build.sourcemap` stays unset, so the plugin generates hidden source maps + * and removes them from the build output after uploading them. */ import type { namedTypes as t } from "ast-types"; @@ -9,7 +10,6 @@ import { generateCode, parseModule } from "magicast"; import { addVitePlugin } from "magicast/helpers"; import { promises } from "node:fs"; import path from "node:path"; -import recast from "recast"; import { Sentry } from "../../telemetry.js"; import { @@ -29,6 +29,7 @@ import { import { clack } from "../../utils/clack/prompts.js"; import { debug } from "../../utils/debug.js"; import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; +import { askShouldRemoveDisabledSourceMaps } from "../utils/disabled-source-maps.js"; import type { SourceMapUploadToolConfigurationFunction, SourceMapUploadToolConfigurationOptions, @@ -44,9 +45,8 @@ const getViteConfigSnippet = ( ${plus(`import { sentryVitePlugin } from "${importPath}";`)} export default defineConfig({ - build: { - ${plus("sourcemap: true, // Source map generation must be turned on")} - }, + // Leave \`build.sourcemap\` unset. The Sentry plugin then generates hidden source + // maps and removes them from the build output after uploading them. plugins: [ // Put the Sentry vite plugin after all other plugins ${plus(`sentryVitePlugin({ @@ -144,8 +144,11 @@ export async function addVitePluginToConfig( } } - const enabledSourcemaps = enableSourcemapGeneration(mod.$ast as t.Program); - if (!enabledSourcemaps) { + const handledSourcemaps = await handleDisabledSourcemaps( + mod.$ast as t.Program, + prettyViteConfigFilename, + ); + if (!handledSourcemaps) { Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); return false; } @@ -171,7 +174,7 @@ export async function addVitePluginToConfig( await promises.writeFile(viteConfigPath, code); clack.log.success( - `Added the Sentry Vite plugin to ${prettyViteConfigFilename} and enabled source maps`, + `Added the Sentry Vite plugin to ${prettyViteConfigFilename}.`, ); return true; @@ -182,57 +185,52 @@ export async function addVitePluginToConfig( } } -function enableSourcemapGeneration(program: t.Program): boolean { +/** + * Offers to remove `build.sourcemap: false`. All other values are left alone: + * if the option is unset, the Sentry plugin generates hidden source maps and + * removes them after the upload. + * + * @returns false if the config object could not be found + */ +async function handleDisabledSourcemaps( + program: t.Program, + prettyConfigFilename: string, +): Promise { const configObj = getViteConfigObject(program); if (!configObj) { return false; } - const b = recast.types.builders; - const buildProp = getObjectProperty(configObj, "build"); - // case 1: build property doesn't exist yet, so we can just add it - if (!buildProp) { - configObj.properties.push( - b.objectProperty( - b.identifier("build"), - b.objectExpression([ - b.objectProperty(b.identifier("sourcemap"), b.booleanLiteral(true)), - ]), - ), - ); + // A `build` value we can't analyze doesn't block adding the plugin. If it + // turns off source maps, the plugin warns about it during the build. + if (buildProp?.value.type !== "ObjectExpression") { return true; } - if (buildProp.value.type !== "ObjectExpression") { - return false; - } - const buildObj = buildProp.value; - const sourceMapsProp = getObjectProperty(buildObj, "sourcemap"); - - // case 2: build.sourcemap property doesn't exist yet, so we just add it - if (!sourceMapsProp) { - buildObj.properties.push( - b.objectProperty(b.identifier("sourcemap"), b.booleanLiteral(true)), - ); - return true; - } + const sourcemapProp = getObjectProperty(buildObj, "sourcemap"); - // case 3: build.sourcemap property exists, and it's set to 'hidden' if ( - sourceMapsProp.value.type === "StringLiteral" && - sourceMapsProp.value.value === "hidden" + sourcemapProp?.value.type === "BooleanLiteral" && + !sourcemapProp.value.value && + (await askShouldRemoveDisabledSourceMaps( + "build.sourcemap: false", + prettyConfigFilename, + )) ) { - // nothing to do for us - return true; + buildObj.properties = buildObj.properties.filter( + (p) => p !== sourcemapProp, + ); + clack.log.success( + `Removed ${chalk.cyan( + "build.sourcemap: false", + )} from ${prettyConfigFilename}.`, + ); } - // case 4: build.sourcemap property exists, but it's not enabled, so we set it to true - // or it is already true in which case this is a noop - sourceMapsProp.value = b.booleanLiteral(true); return true; } diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts index 5a652df36..4a4d52ba5 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts @@ -1,6 +1,7 @@ /** * Source maps setup for webpack: add the Sentry webpack plugin to a CommonJS - * webpack config and turn on `devtool: "source-map"`. + * webpack config. `devtool` stays unset, so the plugin generates hidden source + * maps and removes them from the build output after uploading them. */ import type { namedTypes as t } from "ast-types"; @@ -24,6 +25,7 @@ import { import { clack } from "../../utils/clack/prompts.js"; import { debug } from "../../utils/debug.js"; import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; +import { askShouldRemoveDisabledSourceMaps } from "../utils/disabled-source-maps.js"; import type { SourceMapUploadToolConfigurationFunction, SourceMapUploadToolConfigurationOptions, @@ -41,7 +43,8 @@ const getCodeSnippet = ( module.exports = { // ... other options - ${plus('devtool: "source-map", // Source map generation must be turned on')} + // Leave \`devtool\` unset for production. The Sentry plugin then generates hidden + // source maps and removes them from the build output after uploading them. plugins: [ // Put the Sentry Webpack plugin after all other plugins ${plus(`sentryWebpackPlugin({ @@ -102,7 +105,7 @@ export const configureWebPackPlugin: SourceMapUploadToolConfigurationFunction = }; /** - * Modifies a webpack config file to enable source map generation and add the Sentry webpack plugin + * Modifies a webpack config file to add the Sentry webpack plugin * exported only for testing */ export async function modifyWebpackConfig( @@ -141,19 +144,7 @@ export async function modifyWebpackConfig( return false; } - const enabledSourcemaps = enableSourcemapsGeneration(configObject); - - if (enabledSourcemaps) { - clack.log.success( - `Enabled source map generation in ${prettyConfigFilename}.`, - ); - } else { - clack.log.warn( - `Couldn't enable source maps generation in ${prettyConfigFilename} Please follow the instructions below.`, - ); - Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); - return false; - } + await handleDisabledSourcemaps(configObject, prettyConfigFilename); const addedPlugin = addSentryWebpackPlugin( program, @@ -311,9 +302,15 @@ function addSentryWebpackPluginImport(program: t.Program, importPath: string) { return b; } -function enableSourcemapsGeneration(configObj: t.ObjectExpression): boolean { - const b = recast.types.builders; - +/** + * Offers to remove a `devtool` value that disables source maps. All other + * values are left alone: if the option is unset, the Sentry plugin generates + * hidden source maps and removes them after the upload. + */ +async function handleDisabledSourcemaps( + configObj: t.ObjectExpression, + prettyConfigFilename: string, +): Promise { const devtoolProp = configObj.properties.find( (p): p is t.Property => p.type === "Property" && @@ -321,30 +318,35 @@ function enableSourcemapsGeneration(configObj: t.ObjectExpression): boolean { p.key.name === "devtool", ); - if (devtoolProp) { - // devtool can have quite a lot of source maps values. - // see: https://webpack.js.org/configuration/devtool/#devtool - // For Sentry to work best, we should set it to "source-map" or "hidden-source-map" - // Heuristic: - // - all values that contain "hidden" will be set to "hidden-source-map" - // - all other values will be set to "source-map" - if ( - (devtoolProp.value.type === "Literal" || - devtoolProp.value.type === "StringLiteral") && - devtoolProp.value.value?.toString().startsWith("hidden-") - ) { - devtoolProp.value = b.stringLiteral("hidden-source-map"); - } else { - devtoolProp.value = b.stringLiteral("source-map"); - } - return true; + if (devtoolProp?.value.type !== "Literal") { + return; } - configObj.properties.push( - b.objectProperty(b.identifier("devtool"), b.stringLiteral("source-map")), - ); + const devtool = devtoolProp.value.value; + // Values like "eval" don't produce source maps either + const isDisabled = + devtool === false || + (typeof devtool === "string" && !devtool.includes("source-map")); + + // With SourceMapDevToolPlugin, users set `devtool: false` to configure source + // maps themselves + if ( + !isDisabled || + recast.print(configObj).code.includes("SourceMapDevToolPlugin") + ) { + return; + } - return true; + const setting = `devtool: ${JSON.stringify(devtool)}`; + + if (await askShouldRemoveDisabledSourceMaps(setting, prettyConfigFilename)) { + configObj.properties = configObj.properties.filter( + (p) => p !== devtoolProp, + ); + clack.log.success( + `Removed ${chalk.cyan(setting)} from ${prettyConfigFilename}.`, + ); + } } function getWebpackConfigObject( diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/disabled-source-maps.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/disabled-source-maps.ts new file mode 100644 index 000000000..b428860e9 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/disabled-source-maps.ts @@ -0,0 +1,49 @@ +/** + * Asks whether a bundler setting that disables source maps should be removed. + * + * If the setting is unset, the Sentry bundler plugins generate hidden source + * maps and remove them from the build output after uploading them. + */ + +import chalk from "chalk"; + +import { Sentry } from "../../telemetry.js"; +import { abortIfCancelled } from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; + +export async function askShouldRemoveDisabledSourceMaps( + setting: string, + prettyConfigFilename: string, +): Promise { + const shouldRemove = await abortIfCancelled( + clack.select({ + message: `Source maps are disabled by ${chalk.cyan( + setting, + )} in ${prettyConfigFilename}. Should the wizard remove this setting so that Sentry can un-minify your stack traces?`, + options: [ + { + label: "Yes, remove it", + hint: "source maps are not exposed, Sentry removes them from the build output after the upload", + value: true, + }, + { + label: "No, keep source maps disabled", + value: false, + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("removed-disabled-source-maps", shouldRemove); + + if (!shouldRemove) { + clack.log.warn( + `Source maps stay disabled. Stack traces in Sentry will be minified until you remove ${chalk.cyan( + setting, + )} from ${prettyConfigFilename}.`, + ); + } + + return shouldRemove; +} diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts index d823ea38c..5c5fbe660 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts @@ -1,3 +1,4 @@ +import { select } from "@clack/prompts"; import fs from "node:fs"; import { addVitePluginToConfig } from "../../../../../src/lib/wizard/sourcemaps/tools/vite.js"; @@ -14,7 +15,10 @@ vi.mock("@clack/prompts", () => { log: { info: vi.fn(), success: vi.fn(), + warn: vi.fn(), }, + select: vi.fn(() => Promise.resolve(true)), + isCancel: vi.fn().mockReturnValue(false), }; }); @@ -48,10 +52,6 @@ export default defineConfig({ org: "my-org", project: "my-project" })], - - build: { - sourcemap: true - } }) `, ], @@ -75,7 +75,6 @@ export default defineConfig({ })], build: { test: 1, - sourcemap: true } }) `, @@ -105,7 +104,7 @@ export default { `, ], [ - "rewrite sourcemap: false to true", + "remove sourcemap: false after confirmation", ` const cfg = { plugins: [ @@ -125,16 +124,38 @@ const cfg = { project: "my-project" })], - build: { - sourcemap: true, - } + build: {} } export default cfg; `, ], + ...["true", "'inline'", "mode === 'development'"].map((value) => [ + `keep sourcemap: ${value}`, + ` +export default { + plugins: [ + vue(), + ], + build: { + sourcemap: ${value}, + } +} +`, + `import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; +export default { + plugins: [vue(), sentryVitePlugin({ + org: "my-org", + project: "my-project" + })], + build: { + sourcemap: ${value}, + } +} +`, + ]), ])( - "adds the plugin and enables source maps generation (%s)", + "adds the plugin without exposing source maps (%s)", async (_, originalCode, expectedCode) => { updateFileContent(originalCode); @@ -190,4 +211,68 @@ export default defineConfig({ expect(written).toContain('"sourcemap": "hidden"'); expect(written).not.toContain("sourcemap: true"); }); + + it.each([ + [ + "object spread in the config", + "export default defineConfig({ ...base, plugins: [] })", + false, + ], + [ + "build is not an object", + "export default defineConfig({ plugins: [], build: getBuild() })", + false, + ], + [ + "object spread next to sourcemap: false", + "export default defineConfig({ plugins: [], build: { ...b, sourcemap: false } })", + true, + ], + ])( + "adds the plugin if the config contains code it cannot analyze (%s)", + async (_, originalCode, asksToRemove) => { + updateFileContent(originalCode); + + const addedCode = await addVitePluginToConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/vite", + ); + + expect(addedCode).toBe(true); + expect(select).toHaveBeenCalledTimes(asksToRemove ? 1 : 0); + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).toContain("sentryVitePlugin("); + expect(written).not.toContain("sourcemap: false"); + }, + ); + + it("keeps sourcemap: false if the user declines", async () => { + vi.mocked(select).mockResolvedValueOnce(false); + updateFileContent("export default { build: { sourcemap: false } }"); + + const addedCode = await addVitePluginToConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/vite", + ); + + expect(select).toHaveBeenCalledTimes(1); + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).toContain("sourcemap: false"); + expect(written).toContain("sentryVitePlugin("); + expect(addedCode).toBe(true); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts index 38e3cc85e..d85b9eab1 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts @@ -1,3 +1,4 @@ +import { select } from "@clack/prompts"; import fs from "node:fs"; import { modifyWebpackConfig } from "../../../../../src/lib/wizard/sourcemaps/tools/webpack.js"; @@ -15,6 +16,7 @@ vi.mock("@clack/prompts", () => { log: { info: vi.fn(), success: vi.fn(), + warn: vi.fn(), }, select: vi.fn().mockImplementation(() => Promise.resolve(true)), isCancel: vi.fn().mockReturnValue(false), @@ -49,8 +51,6 @@ module.exports = { path: path.resolve(__dirname, "build"), }, - devtool: "source-map", - plugins: [sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, org: "my-org", @@ -81,8 +81,6 @@ const config = { path: path.resolve(__dirname, "build"), }, - devtool: "source-map", - plugins: [sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, org: "my-org", @@ -117,7 +115,7 @@ const config = { path: path.resolve(__dirname, "build"), }, - devtool: "hidden-source-map", + devtool: "hidden-cheap-source-map", plugins: [sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, @@ -154,7 +152,7 @@ const config = { path: path.resolve(__dirname, "build"), }, - devtool: "source-map", + devtool: getSourcemapSetting(), plugins: [sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, @@ -180,19 +178,15 @@ const noSourcemapUndefinedPluginsPojoResult = `const { module.exports = { entry: "./src/index.js", - plugins: [sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, org: "my-org", project: "my-project" })], - output: { filename: "main.js", path: path.resolve(__dirname, "build"), }, - - devtool: "source-map" };`; const noSourcemapPluginsPojo = `module.exports = { @@ -213,19 +207,15 @@ const noSourcemapPluginsPojoResult = `const { module.exports = { entry: "./src/index.js", - plugins: [new HtmlWebpackPlugin(), new MiniCssExtractPlugin(), sentryWebpackPlugin({ authToken: process.env.SENTRY_AUTH_TOKEN, org: "my-org", project: "my-project" })], - output: { filename: "main.js", path: path.resolve(__dirname, "build"), }, - - devtool: "source-map" };`; describe("modifyWebpackConfig", () => { @@ -266,7 +256,7 @@ describe("modifyWebpackConfig", () => { noSourcemapPluginsPojoResult, ], ])( - "adds plugin and source maps emission to the webpack config (%s)", + "adds plugin to the webpack config without exposing source maps (%s)", async (_, originalCode, expectedCode) => { updateFileContent(originalCode); @@ -338,4 +328,62 @@ describe("modifyWebpackConfig", () => { `plugins: [...${plugins}, sentryWebpackPlugin(`, ); }); + + const options = { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }; + + it.each(["false", '"eval"'])( + "removes devtool: %s after confirmation", + async (value) => { + updateFileContent(`module.exports = { devtool: ${value} };`); + + await modifyWebpackConfig("", options, "@sentry/bundler-plugins/webpack"); + + expect(select).toHaveBeenCalledTimes(1); + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).not.toContain("devtool"); + expect(written).toContain("sentryWebpackPlugin("); + }, + ); + + it("keeps devtool: false if the user declines", async () => { + vi.mocked(select).mockResolvedValueOnce(false); + updateFileContent("module.exports = { devtool: false };"); + + await modifyWebpackConfig("", options, "@sentry/bundler-plugins/webpack"); + + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).toContain("devtool: false"); + expect(written).toContain("sentryWebpackPlugin("); + }); + + it("keeps devtool: false without asking if SourceMapDevToolPlugin is used", async () => { + updateFileContent( + "module.exports = { devtool: false, plugins: [new webpack.SourceMapDevToolPlugin({})] };", + ); + + await modifyWebpackConfig("", options, "@sentry/bundler-plugins/webpack"); + + expect(select).not.toHaveBeenCalled(); + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).toContain("devtool: false"); + }); + + it.each(["source-map", "nosources-source-map", "eval-source-map"])( + 'keeps devtool: "%s" without asking', + async (value) => { + updateFileContent(`module.exports = { devtool: "${value}" };`); + + await modifyWebpackConfig("", options, "@sentry/bundler-plugins/webpack"); + + expect(select).not.toHaveBeenCalled(); + const written = writeFileSpy.mock.calls[0]?.[1]; + expect(written).toContain(`devtool: "${value}"`); + }, + ); });