diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 804f5398fa14..f8c085f5e10c 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -170,7 +170,8 @@ export type SentryBuildPluginManager = { }; /** - * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option. + * Deletes the files that match the user's `sourcemaps.filesToDeleteAfterUpload` and the SDK's + * `sourcemaps.sdkFilesToDeleteAfterUpload`. */ deleteArtifacts(): Promise; @@ -1001,13 +1002,20 @@ export function createSentryBuildPluginManager( }, /** - * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option. + * Deletes the files that match the user's `sourcemaps.filesToDeleteAfterUpload` and the SDK's + * `sourcemaps.sdkFilesToDeleteAfterUpload`. */ async deleteArtifacts() { try { - const filesToDelete = await options.sourcemaps?.filesToDeleteAfterUpload; - if (filesToDelete !== undefined) { - const filePathsToDelete = await globFiles(filesToDelete); + const patterns = ( + await Promise.all([ + options.sourcemaps?.filesToDeleteAfterUpload, + options.sourcemaps?.sdkFilesToDeleteAfterUpload, + ]) + ).filter(pattern => pattern !== undefined); + if (patterns.length > 0) { + const globbedPaths = await Promise.all(patterns.map(pattern => globFiles(pattern))); + const filePathsToDelete = [...new Set(globbedPaths.flat())]; logger.debug('Waiting for dependencies on generated files to be freed before deleting...'); diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index 1c1cad657957..5b39241971ea 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -36,6 +36,7 @@ export type NormalizedOptions = { filesToDeleteAfterUpload?: string | string[] | Promise; deleteSourcemapsAfterUpload?: boolean; sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + sdkFilesToDeleteAfterUpload?: string | string[] | Promise; } | undefined; release: { diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index c6854ea7e29e..227d4955b108 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -737,10 +737,11 @@ export type HandleRecoverableErrorFn = (error: unknown, throwByDefault: boolean) * @internal For Sentry SDK packages only. It can change in any release. * * Like `Options`, but with the SDK's own source map deletion decision in - * `sourcemaps.sdkDeleteSourceMaps`. The plugin calls its function form when it decides how to treat - * the bundler's source map setting, so an SDK can give a value that it only knows after it created - * the plugin. Vite passes the name of an environment with its own `build.sourcemap`, and `undefined` - * for the top-level `build.sourcemap`. + * `sourcemaps.sdkDeleteSourceMaps` and the SDK's own files to delete in + * `sourcemaps.sdkFilesToDeleteAfterUpload`. The plugin calls the function form of `sdkDeleteSourceMaps` + * when it decides how to treat the bundler's source map setting, so an SDK can give a value that it + * only knows after it created the plugin. Vite passes the name of an environment with its own + * `build.sourcemap`, and `undefined` for the top-level `build.sourcemap`. */ export type InternalOptions = Omit & { sourcemaps?: NonNullable & { @@ -754,5 +755,10 @@ export type InternalOptions = Omit & { * decides whether source maps are removed, and `true` here still makes that all of them. */ sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + /** + * The SDK's own files to delete after the upload. The plugin deletes them next to the files of + * the user's `sourcemaps.filesToDeleteAfterUpload`. + */ + sdkFilesToDeleteAfterUpload?: string | string[] | Promise; }; }; diff --git a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts index 5349777dfc2b..3c86be006189 100644 --- a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts +++ b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts @@ -569,6 +569,71 @@ describe('createSentryBuildPluginManager', () => { }); }); + describe('deleteArtifacts', () => { + const managerOptions = { + authToken: 't', + org: 'o', + project: 'p', + release: { name: 'some-release-name' }, + telemetry: false, + silent: true, + }; + const meta = { buildTool: 'esbuild', loggerPrefix: '[sentry-esbuild-plugin]' }; + + it("deletes the files of the user's and the SDK's globs once", async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + mockGlobFiles.mockImplementation(async patterns => + patterns === 'user/**/*.map' ? ['/app/user/a.js.map', '/app/shared.js.map'] : ['/app/shared.js.map'], + ); + const manager = createSentryBuildPluginManager( + { + ...managerOptions, + sourcemaps: { + filesToDeleteAfterUpload: 'user/**/*.map', + sdkFilesToDeleteAfterUpload: Promise.resolve(['sdk/**/*.map']), + }, + }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).toHaveBeenCalledWith('user/**/*.map'); + expect(mockGlobFiles).toHaveBeenCalledWith(['sdk/**/*.map']); + expect(rmSpy).toHaveBeenCalledTimes(2); + expect(rmSpy).toHaveBeenCalledWith('/app/user/a.js.map', { force: true }); + expect(rmSpy).toHaveBeenCalledWith('/app/shared.js.map', { force: true }); + }); + + it('deletes the files of the SDK glob without a user glob', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + mockGlobFiles.mockResolvedValue(['/app/sdk/a.js.map']); + const manager = createSentryBuildPluginManager( + { ...managerOptions, sourcemaps: { sdkFilesToDeleteAfterUpload: 'sdk/**/*.map' } }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).toHaveBeenCalledTimes(1); + expect(mockGlobFiles).toHaveBeenCalledWith('sdk/**/*.map'); + expect(rmSpy).toHaveBeenCalledWith('/app/sdk/a.js.map', { force: true }); + }); + + it('deletes nothing without a glob', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + const manager = createSentryBuildPluginManager( + { ...managerOptions, sourcemaps: { sdkFilesToDeleteAfterUpload: Promise.resolve(undefined) } }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).not.toHaveBeenCalled(); + expect(rmSpy).not.toHaveBeenCalled(); + }); + }); + describe('injectDebugIds', () => { it('should call the CLI inject command for each build artifact path', async () => { mockSourcemapInject.mockResolvedValue(undefined); diff --git a/packages/nextjs/src/config/getBuildPluginOptions.ts b/packages/nextjs/src/config/getBuildPluginOptions.ts index 21d4e1ac86dc..bf431d02647d 100644 --- a/packages/nextjs/src/config/getBuildPluginOptions.ts +++ b/packages/nextjs/src/config/getBuildPluginOptions.ts @@ -302,7 +302,7 @@ export function getBuildPluginOptions({ const loggerPrefix = LOGGER_PREFIXES[buildTool]; const widenClientFileUpload = sentryBuildOptions.widenClientFileUpload ?? false; const userSourcemaps = sentryBuildOptions.sourcemaps; - const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(userSourcemaps) ?? false; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions) ?? false; // `sourcemaps.delete: true` removes the source maps next to the user's `filesToDeleteAfterUpload`. const userFilesReplaceDeletion = userSourcemaps?.delete !== true; @@ -368,7 +368,7 @@ export function getBuildPluginOptions({ rewriteSources: sentryBuildOptions.sourcemaps?.rewriteSources ?? rewriteWebpackSources, assets: sentryBuildOptions.sourcemaps?.assets ?? sourcemapUploadAssets, ignore: finalIgnorePatterns, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, // Every client map goes, also those the user turned on with `productionBrowserSourceMaps` or // `devtool`, and those of chunks the upload leaves out. sdkDeleteSourceMaps: webpackPluginDeletesSourcemaps, diff --git a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts index 7d44bc311ef4..5934362b4c45 100644 --- a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts +++ b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts @@ -72,7 +72,7 @@ export async function handleRunAfterProductionCompile( prepareArtifacts: false, }); - const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions.sourcemaps) ?? false; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions) ?? false; // Deletion covers all of `static/`, so if Next.js emits chunks outside the upload // patterns, their maps would be deleted without ever having been uploaded — warn instead diff --git a/packages/nextjs/src/config/sourceMapOptions.ts b/packages/nextjs/src/config/sourceMapOptions.ts index 341f9e8ea203..27b096e5cfb9 100644 --- a/packages/nextjs/src/config/sourceMapOptions.ts +++ b/packages/nextjs/src/config/sourceMapOptions.ts @@ -15,9 +15,29 @@ export function sentryEnablesSourceMaps(options: SentryBuildOptions): boolean { return (upload && hasSourceMapUploadCredentials(options)) || (sourcemaps?.delete === false && injectDebugIds); } -/** Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides. */ -export function getDeleteSourceMapsOption(sourcemaps: SourceMapsOptions): boolean | undefined { - return sourcemaps?.delete ?? sourcemaps?.deleteSourcemapsAfterUpload; +export const SDK_DELETES_SOURCE_MAPS_MESSAGE = + '[@sentry/nextjs] Source maps will be deleted after the upload to Sentry. To keep them, set `sourcemaps.delete: false` in `withSentryConfig()`. To neither generate nor upload source maps, set `sourcemaps.upload: false`.'; + +// Every build phase that runs in this process gets the same options object. +const sdkDeletesSourceMaps = new WeakSet(); + +/** + * Makes the SDK delete the source maps after the upload when the user set neither `sourcemaps.delete` + * nor `sourcemaps.deleteSourcemapsAfterUpload`. + */ +export function setSdkDeletesSourceMaps(options: SentryBuildOptions): void { + sdkDeletesSourceMaps.add(options); +} + +/** + * Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides, and + * then `setSdkDeletesSourceMaps`. + */ +export function getDeleteSourceMapsOption(options: SentryBuildOptions): boolean | undefined { + const { sourcemaps } = options; + return ( + sourcemaps?.delete ?? sourcemaps?.deleteSourcemapsAfterUpload ?? (sdkDeletesSourceMaps.has(options) || undefined) + ); } /** @@ -37,8 +57,7 @@ export function mergeFilesToDeleteAfterUpload( } /** - * `disable`, `upload` and `injectDebugIds` for the bundler plugin. It warns when `disable` is set next to the - * options that replace it, so `disable` gets no default then. + * `disable`, `upload` and `injectDebugIds` for the bundler plugin. `disable` is only ever the user's own value. */ // TODO(v12): Remove `disable`. export function getSourceMapFeatureOptions( @@ -46,10 +65,9 @@ export function getSourceMapFeatureOptions( skipSourcemapsUpload: boolean, ): Pick, 'disable' | 'upload' | 'injectDebugIds'> { if (skipSourcemapsUpload) { - return { disable: true }; + return { upload: false, injectDebugIds: false }; } const { disable, upload, injectDebugIds } = userSourcemaps ?? {}; - const usesFeatureOptions = upload !== undefined || injectDebugIds !== undefined; - return { disable: disable ?? (usesFeatureOptions ? undefined : false), upload, injectDebugIds }; + return { disable, upload, injectDebugIds }; } diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 09bffbda9765..391423b1be52 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -10,7 +10,12 @@ import type { VercelCronsConfig } from '../common/types'; import { getBuildLogger } from './buildLogger'; import { externalizeOrchestrionRuntimePackages } from './diagnosticsChannelInjection'; import { getBuildPluginOptions, normalizePathForGlob } from './getBuildPluginOptions'; -import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from './sourceMapOptions'; +import { + getDeleteSourceMapsOption, + SDK_DELETES_SOURCE_MAPS_MESSAGE, + sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, +} from './sourceMapOptions'; import type { RouteManifest } from './manifest/types'; import type { BuildContext, @@ -385,14 +390,9 @@ export function constructWebpackConfigFunction({ } // enable source map deletion if not explicitly disabled - if (!isServer && getDeleteSourceMapsOption(userSentryOptions.sourcemaps) === undefined) { - debug.warn( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', - ); - userSentryOptions.sourcemaps = { - ...userSentryOptions.sourcemaps, - deleteSourcemapsAfterUpload: true, - }; + if (!isServer && getDeleteSourceMapsOption(userSentryOptions) === undefined) { + debug.warn(SDK_DELETES_SOURCE_MAPS_MESSAGE); + setSdkDeletesSourceMaps(userSentryOptions); } } diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index cc238b65824e..40261d2854f2 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -36,7 +36,7 @@ import { maybeAddReleaseServerTimingHeader } from './release'; /** * Materializes the final Next.js config object with Sentry's build-time integrations applied. * - * Note: this mutates both `incomingUserNextConfigObject` and `userSentryOptions` (to apply defaults). + * Note: this mutates `incomingUserNextConfigObject` (to apply defaults). */ export function getFinalConfigObject( incomingUserNextConfigObject: NextConfigObject, diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index b6172939b069..f1d8b20dc123 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -6,7 +6,12 @@ import { import { getBuildLogger } from '../buildLogger'; import { handleRunAfterProductionCompile } from '../handleRunAfterProductionCompile'; import type { RouteManifest } from '../manifest/types'; -import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from '../sourceMapOptions'; +import { + getDeleteSourceMapsOption, + SDK_DELETES_SOURCE_MAPS_MESSAGE, + sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, +} from '../sourceMapOptions'; import { constructTurbopackConfig } from '../turbopack'; import type { NextConfigObject, SentryBuildOptions, TurbopackOptions } from '../types'; import { detectActiveBundler, supportsProductionCompileHook, supportsTurbopackRuleCondition } from '../util'; @@ -240,7 +245,7 @@ export function maybeSetUpRunAfterProductionCompileHook({ /** * For supported turbopack builds, auto-enables browser sourcemaps and defaults to deleting them after upload. * - * Note: this mutates both `incomingUserNextConfigObject` and `userSentryOptions`. + * Note: this mutates `incomingUserNextConfigObject`. */ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject: NextConfigObject, @@ -266,20 +271,15 @@ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject.productionBrowserSourceMaps = true; // Enable source map deletion if not explicitly disabled - if (getDeleteSourceMapsOption(userSentryOptions.sourcemaps) !== undefined) { + if (getDeleteSourceMapsOption(userSentryOptions) !== undefined) { return; } if (userSentryOptions.debug) { - logger.warn( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', - ); + logger.warn(SDK_DELETES_SOURCE_MAPS_MESSAGE); } - userSentryOptions.sourcemaps = { - ...userSentryOptions.sourcemaps, - deleteSourcemapsAfterUpload: true, - }; + setSdkDeletesSourceMaps(userSentryOptions); } /** diff --git a/packages/nextjs/test/config/getBuildPluginOptions.test.ts b/packages/nextjs/test/config/getBuildPluginOptions.test.ts index 6b6f5b2d79cf..48190303c755 100644 --- a/packages/nextjs/test/config/getBuildPluginOptions.test.ts +++ b/packages/nextjs/test/config/getBuildPluginOptions.test.ts @@ -55,7 +55,7 @@ describe('getBuildPluginOptions', () => { '**/route_client-reference-manifest.js', '**/middleware-react-loadable-manifest.js', ], - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, rewriteSources: expect.any(Function), }, release: { @@ -386,7 +386,7 @@ describe('getBuildPluginOptions', () => { project: 'test-project', }; - it('disables sourcemaps when useRunAfterProductionCompileHook is true for webpack builds', () => { + it('turns the upload and debug ID injection off when useRunAfterProductionCompileHook is true for webpack builds', () => { const webpackBuildTools = ['webpack-client', 'webpack-nodejs', 'webpack-edge'] as const; webpackBuildTools.forEach(buildTool => { @@ -398,11 +398,12 @@ describe('getBuildPluginOptions', () => { useRunAfterProductionCompileHook: true, }); - expect(result.sourcemaps?.disable).toBe(true); + expect(result.sourcemaps).toMatchObject({ upload: false, injectDebugIds: false }); + expect(result.sourcemaps?.disable).toBeUndefined(); }); }); - it('does not disable sourcemaps when useRunAfterProductionCompileHook is true for after-production-compile builds', () => { + it('passes the source map features on unchanged when useRunAfterProductionCompileHook is true for after-production-compile builds', () => { const afterProductionCompileBuildTools = [ 'after-production-compile-webpack', 'after-production-compile-turbopack', @@ -417,11 +418,11 @@ describe('getBuildPluginOptions', () => { useRunAfterProductionCompileHook: true, }); - expect(result.sourcemaps?.disable).toBe(false); + expect(result.sourcemaps).toMatchObject({ disable: undefined, upload: undefined, injectDebugIds: undefined }); }); }); - it('does not disable sourcemaps when useRunAfterProductionCompileHook is false', () => { + it('passes the source map features on unchanged when useRunAfterProductionCompileHook is false', () => { const result = getBuildPluginOptions({ sentryBuildOptions: baseSentryOptions, releaseName: mockReleaseName, @@ -430,7 +431,7 @@ describe('getBuildPluginOptions', () => { useRunAfterProductionCompileHook: false, }); - expect(result.sourcemaps?.disable).toBe(false); + expect(result.sourcemaps).toMatchObject({ disable: undefined, upload: undefined, injectDebugIds: undefined }); }); }); @@ -451,7 +452,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-webpack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -475,7 +476,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-turbopack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -497,7 +498,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: true, }); }); @@ -515,7 +516,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }); @@ -535,7 +536,7 @@ describe('getBuildPluginOptions', () => { // The upload runs after the compile, and the after-production-compile options delete the maps. expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }); @@ -555,7 +556,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }, @@ -615,7 +616,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); @@ -635,7 +636,10 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map', '.next/server/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ + '.next/static/**/*.map', + '.next/server/**/*.map', + ]); }); it('filesToDeleteAfterUpload overrides deleteSourcemapsAfterUpload default pattern', () => { @@ -655,7 +659,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['custom/**/*.map']); expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); @@ -675,7 +679,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-nodejs', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/server/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['.next/server/**/*.map']); }); it('uses custom sourcemap assets when provided', () => { @@ -782,7 +786,7 @@ describe('getBuildPluginOptions', () => { buildTool, }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -802,7 +806,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-turbopack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['custom/**/*.map']); }); // The plugin would also remove the server source maps, which broke deployments on Vercel. @@ -1183,7 +1187,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - disable: false, + disable: undefined, assets: ['/path/to/.next/server', '/path/to/.next/static/chunks/pages', '/path/to/.next/static/chunks/app'], ignore: [ '/path/to/.next/static/chunks/main-*', @@ -1199,7 +1203,7 @@ describe('getBuildPluginOptions', () => { '**/route_client-reference-manifest.js', '**/middleware-react-loadable-manifest.js', ], - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, rewriteSources: expect.any(Function), }); }); @@ -1223,7 +1227,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.assets).toEqual([`${complexPath}/server`, `${complexPath}/static/chunks`]); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ `${complexPath}/static/**/*.js.map`, `${complexPath}/static/**/*.mjs.map`, `${complexPath}/static/**/*.cjs.map`, diff --git a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts index 2cfe68e173ce..5015cfd2738b 100644 --- a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts +++ b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts @@ -9,6 +9,7 @@ import { handleRunAfterProductionCompile, stripSourceMappingURLComments, } from '../../src/config/handleRunAfterProductionCompile'; +import { setSdkDeletesSourceMaps } from '../../src/config/sourceMapOptions'; import type { SentryBuildOptions } from '../../src/config/types'; vi.mock('@sentry/core/server', async importOriginal => ({ @@ -347,6 +348,25 @@ describe('handleRunAfterProductionCompile', () => { ); }); + it('strips sourceMappingURL comments for turbopack builds when the SDK turned deletion on', async () => { + const sentryBuildOptions: SentryBuildOptions = { ...mockSentryBuildOptions, sourcemaps: {} }; + setSdkDeletesSourceMaps(sentryBuildOptions); + + await handleRunAfterProductionCompile( + { + releaseName: 'test-release', + distDir: '/path/to/.next', + buildTool: 'turbopack', + }, + sentryBuildOptions, + ); + + expect(readdirSpy).toHaveBeenCalledWith( + path.join('/path/to/.next', 'static'), + expect.objectContaining({ recursive: true }), + ); + }); + it('does NOT strip sourceMappingURL comments for webpack builds even with deleteSourcemapsAfterUpload', async () => { await handleRunAfterProductionCompile( { diff --git a/packages/nextjs/test/config/sourceMapOptions.test.ts b/packages/nextjs/test/config/sourceMapOptions.test.ts index ecf15450b13a..fd989cd3e087 100644 --- a/packages/nextjs/test/config/sourceMapOptions.test.ts +++ b/packages/nextjs/test/config/sourceMapOptions.test.ts @@ -4,6 +4,7 @@ import { getSourceMapFeatureOptions, mergeFilesToDeleteAfterUpload, sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, } from '../../src/config/sourceMapOptions'; import type { NextConfigObject, SentryBuildOptions } from '../../src/config/types'; import type { BundlerInfo } from '../../src/config/withSentryConfig/getFinalConfigObjectBundlerUtils'; @@ -53,13 +54,31 @@ describe('getDeleteSourceMapsOption', () => { [{ delete: false, deleteSourcemapsAfterUpload: true }, false], [{ delete: true, deleteSourcemapsAfterUpload: false }, true], ] as const)('with %j it returns %s', (sourcemaps, expected) => { - expect(getDeleteSourceMapsOption(sourcemaps)).toBe(expected); + expect(getDeleteSourceMapsOption({ sourcemaps })).toBe(expected); + }); + + it.each([ + [undefined, true], + [{ deleteSourcemapsAfterUpload: false }, false], + [{ delete: false }, false], + ] as const)('after `setSdkDeletesSourceMaps`, with %j it returns %s', (sourcemaps, expected) => { + const options: SentryBuildOptions = { sourcemaps }; + setSdkDeletesSourceMaps(options); + + expect(getDeleteSourceMapsOption(options)).toBe(expected); + expect(options.sourcemaps).toEqual(sourcemaps); + }); + + it('reads the SDK default only for the options object it was set on', () => { + setSdkDeletesSourceMaps({}); + + expect(getDeleteSourceMapsOption({})).toBeUndefined(); }); }); describe('getSourceMapFeatureOptions', () => { it.each([ - [undefined, { disable: false }], + [undefined, {}], [{ disable: 'disable-upload' }, { disable: 'disable-upload' }], [{ upload: false }, { disable: undefined, upload: false }], [{ injectDebugIds: false }, { disable: undefined, injectDebugIds: false }], @@ -72,8 +91,11 @@ describe('getSourceMapFeatureOptions', () => { expect(getSourceMapFeatureOptions(sourcemaps, false)).toEqual(expected); }); - it('switches the webpack plugin off when the upload runs after the compile', () => { - expect(getSourceMapFeatureOptions({ upload: true, injectDebugIds: true }, true)).toEqual({ disable: true }); + it('turns the upload and debug ID injection off when the upload runs after the compile', () => { + expect(getSourceMapFeatureOptions({ disable: false, upload: true, injectDebugIds: true }, true)).toEqual({ + upload: false, + injectDebugIds: false, + }); }); }); @@ -95,7 +117,11 @@ describe('maybeEnableTurbopackSourcemaps with the new source map options', () => function run(sourcemaps: NonNullable, nextConfig: NextConfigObject = {}) { const userSentryOptions: SentryBuildOptions = { ...CREDENTIALS, sourcemaps }; maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED); - return { nextConfig, sourcemaps: userSentryOptions.sourcemaps }; + return { + nextConfig, + sourcemaps: userSentryOptions.sourcemaps, + deleteSourceMaps: getDeleteSourceMapsOption(userSentryOptions), + }; } it.each([{ upload: false }, { injectDebugIds: false }, { upload: false, delete: true }])( @@ -122,7 +148,8 @@ describe('maybeEnableTurbopackSourcemaps with the new source map options', () => const result = run({ upload: true }); expect(result.nextConfig.productionBrowserSourceMaps).toBe(true); - expect(result.sourcemaps).toEqual({ upload: true, deleteSourcemapsAfterUpload: true }); + expect(result.sourcemaps).toEqual({ upload: true }); + expect(result.deleteSourceMaps).toBe(true); }); it('turns no source maps on without upload credentials', () => { diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index fc230474312b..a776be34a51a 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -6,6 +6,8 @@ import type * as os from 'os'; import * as path from 'path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as getBuildPluginOptionsModule from '../../../src/config/getBuildPluginOptions'; +import { getDeleteSourceMapsOption } from '../../../src/config/sourceMapOptions'; +import type { SentryBuildOptions } from '../../../src/config/types'; import { CLIENT_SDK_CONFIG_FILE, clientBuildContext, @@ -76,35 +78,32 @@ describe('constructWebpackConfigFunction()', () => { expect(finalWebpackConfig.devtool).toEqual(customDevtool); }); - it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => { + it('turns source map deletion on for client builds when not explicitly set', async () => { const getBuildPluginOptionsSpy = vi.spyOn(getBuildPluginOptionsModule, 'getBuildPluginOptions'); vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ sentryWebpackPlugin: () => ({ _name: 'sentry-webpack-plugin', }), })); + const sentryBuildTimeOptions: SentryBuildOptions = { sourcemaps: {} }; await materializeFinalWebpackConfig({ exportedNextConfig, incomingWebpackConfig: clientWebpackConfig, incomingWebpackBuildContext: clientBuildContext, - sentryBuildTimeOptions: { - sourcemaps: {}, - }, + sentryBuildTimeOptions, }); expect(getBuildPluginOptionsSpy).toHaveBeenCalledWith( expect.objectContaining({ - sentryBuildOptions: expect.objectContaining({ - sourcemaps: { - deleteSourcemapsAfterUpload: true, - }, - }), + sentryBuildOptions: sentryBuildTimeOptions, buildTool: 'webpack-client', distDirAbsPath: expect.any(String), releaseName: undefined, }), ); + expect(sentryBuildTimeOptions.sourcemaps).toEqual({}); + expect(getDeleteSourceMapsOption(sentryBuildTimeOptions)).toBe(true); getBuildPluginOptionsSpy.mockRestore(); }); diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index af2cc03a303b..bf167defd132 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -4,6 +4,7 @@ import { filterInstrumentedExternals, ORCHESTRION_RUNTIME_EXTERNAL_PACKAGES, } from '../../src/config/diagnosticsChannelInjection'; +import { getDeleteSourceMapsOption } from '../../src/config/sourceMapOptions'; import type { SentryBuildOptions } from '../../src/config/types'; import * as util from '../../src/config/util'; import { DEFAULT_SERVER_EXTERNAL_PACKAGES } from '../../src/config/withSentryConfig'; @@ -653,7 +654,7 @@ describe('withSentryConfig', () => { expect(finalConfig.productionBrowserSourceMaps).toBe(true); }); - it('automatically enables deleteSourcemapsAfterUpload for turbopack builds when not explicitly set', () => { + it('turns source map deletion on for turbopack builds when not explicitly set', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -667,9 +668,9 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); - // Both productionBrowserSourceMaps and deleteSourcemapsAfterUpload should be enabled + // Both source map generation and deletion should be enabled expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); }); it('does not auto-enable source map generation when `disable` is "disable-upload"', () => { @@ -690,7 +691,7 @@ describe('withSentryConfig', () => { // The SDK must not generate source maps it will neither upload nor delete - they would be served // publicly from `.next/static`. Generating them is the user's call via `productionBrowserSourceMaps`. expect(finalConfig.productionBrowserSourceMaps).toBeUndefined(); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('preserves explicitly configured deleteSourcemapsAfterUpload setting', () => { @@ -708,7 +709,7 @@ describe('withSentryConfig', () => { expect(sentryOptions.sourcemaps.deleteSourcemapsAfterUpload).toBe(false); }); - it('does not modify deleteSourcemapsAfterUpload when sourcemaps are disabled', () => { + it('does not turn source map deletion on when sourcemaps are disabled', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -720,10 +721,10 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(exportedNextConfig, undefined, sentryOptions); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); - it('does not enable deleteSourcemapsAfterUpload when user pre-configured productionBrowserSourceMaps: true', () => { + it('does not turn source map deletion on when user pre-configured productionBrowserSourceMaps: true', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -739,7 +740,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(configWithSourceMapsPreEnabled, undefined, sentryOptions); // Should NOT automatically enable deletion because productionBrowserSourceMaps was already set by user - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('does not enable sourcemaps or deletion when user explicitly sets productionBrowserSourceMaps: false', () => { @@ -759,7 +760,7 @@ describe('withSentryConfig', () => { // Should NOT modify productionBrowserSourceMaps or enable deletion when user explicitly set to false expect(finalConfig.productionBrowserSourceMaps).toBe(false); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('logs correct message when enabling sourcemaps for turbopack', () => { @@ -800,7 +801,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(consoleWarnSpy).toHaveBeenCalledWith( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', + '[@sentry/nextjs] Source maps will be deleted after the upload to Sentry. To keep them, set `sourcemaps.delete: false` in `withSentryConfig()`. To neither generate nor upload source maps, set `sourcemaps.upload: false`.', ); consoleWarnSpy.mockRestore(); @@ -897,7 +898,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); }); it('works when TURBOPACK env var is truthy string', () => { @@ -937,7 +938,7 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); expect(finalConfig.env).toHaveProperty('_sentryTunnelRoute', '/custom-tunnel'); }); @@ -963,7 +964,7 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); expect(finalConfig.env).toHaveProperty('_sentryRelease', 'custom-release-1.0.0'); // Restore original env var diff --git a/packages/nitro/src/sourceMaps.ts b/packages/nitro/src/sourceMaps.ts index a32df5f81100..9d57495b78b2 100644 --- a/packages/nitro/src/sourceMaps.ts +++ b/packages/nitro/src/sourceMaps.ts @@ -1,4 +1,4 @@ -import type { Options as BundlerPluginOptions } from '@sentry/bundler-plugins/core'; +import type { InternalOptions as BundlerPluginOptions } from '@sentry/bundler-plugins/core'; import { createSentryBuildPluginManager } from '@sentry/bundler-plugins/core'; import { resolveSourceMapsFeatures, warnOnConflictingSourceMapOptions } from '@sentry/core'; import type { Nitro, NitroConfig } from 'nitro/types'; @@ -120,7 +120,7 @@ export function getPluginOptions( if (options?.debug && defaultFilesToDelete && userFilesToDelete === undefined) { // eslint-disable-next-line no-console console.log( - `[@sentry/nitro] Setting \`sourcemaps.filesToDeleteAfterUpload: ["${defaultFilesToDelete[0]}"]\` to delete generated source maps after they were uploaded to Sentry.`, + `[@sentry/nitro] Deleting the generated source maps after the upload: ${defaultFilesToDelete.join(', ')}`, ); } @@ -140,7 +140,7 @@ export function getPluginOptions( injectDebugIds: options?.sourcemaps?.injectDebugIds, assets: options?.sourcemaps?.assets, ignore: options?.sourcemaps?.ignore, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, rewriteSources: options?.sourcemaps?.rewriteSources ?? ((source: string) => normalizePath(source)), }, release: options?.release, @@ -162,7 +162,7 @@ export function getPluginOptions( 3. User did not set source maps (undefined) - We enable source maps when Sentry uploads them, or when `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave the setting unset - - Configure `filesToDeleteAfterUpload` to clean up .map files after upload + - Delete the .map files after the upload */ export function configureSourcemapSettings( config: NitroConfig, @@ -185,7 +185,7 @@ export function configureSourcemapSettings( usesSourceMaps && // eslint-disable-next-line no-console console.warn( - '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or use `sourcemaps: { disable: true }` in your Sentry options to silence this warning.', + '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or set `sourcemaps: { upload: false }` in your Sentry options to silence this warning.', ); return { sentryEnabledSourcemaps: false }; } diff --git a/packages/nitro/test/sourceMaps.test.ts b/packages/nitro/test/sourceMaps.test.ts index 47d4f78f569f..8afaf0f021ae 100644 --- a/packages/nitro/test/sourceMaps.test.ts +++ b/packages/nitro/test/sourceMaps.test.ts @@ -28,7 +28,7 @@ describe('getPluginOptions', () => { debug: false, silent: false, sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: ['/project/.output/server/**/*.map'], + sdkFilesToDeleteAfterUpload: ['/project/.output/server/**/*.map'], rewriteSources: expect.any(Function), }), _metaOptions: expect.objectContaining({ @@ -38,6 +38,7 @@ describe('getPluginOptions', () => { }), }), ); + expect(options.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); expect(options.org).toBeUndefined(); expect(options.project).toBeUndefined(); expect(options.authToken).toBeUndefined(); @@ -47,7 +48,7 @@ describe('getPluginOptions', () => { it('does not default filesToDeleteAfterUpload when user enabled sourcemaps themselves', () => { const options = getPluginOptions(undefined, false); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); }); it('respects user-provided filesToDeleteAfterUpload even when Sentry enabled sourcemaps', () => { @@ -57,14 +58,16 @@ describe('getPluginOptions', () => { '/project/.output/server', ); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toEqual(['dist/**/*.map']); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['dist/**/*.map']); }); - it('logs the default filesToDeleteAfterUpload glob in debug mode', () => { + it('logs the default deletion glob in debug mode', () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); getPluginOptions({ debug: true }, true, '/project/.output/server'); - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('/project/.output/server/**/*.map')); + expect(logSpy).toHaveBeenCalledWith( + '[@sentry/nitro] Deleting the generated source maps after the upload: /project/.output/server/**/*.map', + ); logSpy.mockRestore(); }); @@ -76,7 +79,7 @@ describe('getPluginOptions', () => { '/project/.output/server', ); - expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining('filesToDeleteAfterUpload')); + expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining('Deleting the generated source maps')); logSpy.mockRestore(); }); @@ -143,7 +146,7 @@ describe('getPluginOptions', () => { expect(options.release).toEqual({ name: 'v1.0.0' }); expect(options.sourcemaps?.assets).toEqual(['dist/**']); expect(options.sourcemaps?.ignore).toEqual(['dist/test/**']); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toEqual(['dist/**/*.map']); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['dist/**/*.map']); }); it('normalizes source paths via rewriteSources', () => { @@ -198,6 +201,14 @@ describe('configureSourcemapSettings', () => { warnSpy.mockRestore(); }); + it('does not warn about `sourcemap: false` with `sourcemaps.upload: false`', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + configureSourcemapSettings({ sourcemap: false }, { sourcemaps: { upload: false } }); + + expect(warnSpy).not.toHaveBeenCalled(); + warnSpy.mockRestore(); + }); + it('does not modify experimental config when user disabled sourcemaps', () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); const config: NitroConfig = { sourcemap: false }; @@ -322,7 +333,7 @@ describe('getPluginOptions with the new source map options', () => { '/output/server', ); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(expected); }); }); diff --git a/packages/nuxt/src/vite/sourceMapDeletion.ts b/packages/nuxt/src/vite/sourceMapDeletion.ts index 7d1089d6986b..92cf4b67a6ca 100644 --- a/packages/nuxt/src/vite/sourceMapDeletion.ts +++ b/packages/nuxt/src/vite/sourceMapDeletion.ts @@ -83,13 +83,13 @@ export function logSentryEnabledSourceMaps(fallback: DeletionFallback, deleteOpt } else if (fallback[side]) { // eslint-disable-next-line no-console console.log( - `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload. Set \`sourcemaps.delete: false\` to keep them.`, ); } } } -/** `filesToDeleteAfterUpload` is matched from the working directory and needs forward slashes, also on Windows. */ +/** The deletion globs are matched from the working directory and need forward slashes, also on Windows. */ function toGlobPath(directory: string): string { return path.relative(process.cwd(), directory).split(path.sep).join('/') || '.'; } @@ -107,7 +107,7 @@ function toGlobPath(directory: string): string { * the same rules to the server maps there. */ export function withClientSourceMapDeletion( - options: Options, + options: InternalOptions, userSourcemaps: Pick, 'delete' | 'filesToDeleteAfterUpload'> | undefined, fallback: DeletionFallback, viteServer = false, @@ -127,6 +127,7 @@ export function withClientSourceMapDeletion( sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, delete: undefined, deleteSourcemapsAfterUpload: undefined, // The Vite plugin reads this in its `config` hook, after `modules:done` set the fallback. @@ -152,12 +153,13 @@ function isClientEnvironment(environment: string | undefined): boolean { return environment === undefined || environment === 'client'; } -export function withoutSourceMapDeletion(options: Options): InternalOptions { +export function withoutSourceMapDeletion(options: InternalOptions): InternalOptions { return { ...options, sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, delete: undefined, deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: false, @@ -165,18 +167,18 @@ export function withoutSourceMapDeletion(options: Options): InternalOptions { }; } -export async function deleteSourceMapsAfterBuild(options: Options): Promise { - const filesToDeleteAfterUpload = await options.sourcemaps?.filesToDeleteAfterUpload; +export async function deleteSourceMapsAfterBuild(options: InternalOptions): Promise { + const sdkFilesToDeleteAfterUpload = await options.sourcemaps?.sdkFilesToDeleteAfterUpload; - if (filesToDeleteAfterUpload === undefined) { + if (sdkFilesToDeleteAfterUpload === undefined) { return; } - const deletionOptions: Options = { + const deletionOptions: InternalOptions = { ...options, sourcemaps: { ...options.sourcemaps, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload, }, }; @@ -189,17 +191,17 @@ export async function deleteSourceMapsAfterBuild(options: Options): Promise { - const filesToDeleteAfterUpload = await options.sourcemaps?.filesToDeleteAfterUpload; +export async function deletePublicSourceMaps(options: InternalOptions, publicDir: string): Promise { + const sdkFilesToDeleteAfterUpload = await options.sourcemaps?.sdkFilesToDeleteAfterUpload; - if (filesToDeleteAfterUpload === undefined) { + if (sdkFilesToDeleteAfterUpload === undefined) { return; } - const files = await globFiles(filesToDeleteAfterUpload); + const files = await globFiles(sdkFilesToDeleteAfterUpload); const publicFiles = files.filter(file => isInDirectory(file, publicDir)); await Promise.all( diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index 655f5768f148..619b25910c09 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -1,7 +1,7 @@ import type { Nuxt } from '@nuxt/schema'; -import { 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 { type InternalOptions, resolveReleaseName } from '@sentry/bundler-plugins/core'; +import { sentryRollupPlugin } from '@sentry/bundler-plugins/rollup'; +import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; import type { NitroConfig } from 'nitropack'; import type { Plugin } from 'vite'; @@ -180,8 +180,8 @@ export function setupSourceMaps( function moveClientReleaseToRuntimeConfig( nuxt: Nuxt, moduleOptions: SentryNuxtModuleOptions, - pluginOptions: SentryVitePluginOptions, -): SentryVitePluginOptions { + pluginOptions: InternalOptions, +): InternalOptions { if (moduleOptions.release?.inject === false) { return pluginOptions; } @@ -210,7 +210,7 @@ function normalizePath(path: string): string { export function getPluginOptions( moduleOptions: SentryNuxtModuleOptions, shouldDeleteFilesFallback?: DeletionFallback, -): SentryVitePluginOptions | SentryRollupPluginOptions { +): InternalOptions { const sourcemapsOptions = moduleOptions.sourcemaps || {}; const filesToDeleteAfterUpload = resolveFilesToDeleteAfterUpload(moduleOptions, shouldDeleteFilesFallback); @@ -243,13 +243,13 @@ export function getPluginOptions( upload: sourcemapsOptions.upload, injectDebugIds: sourcemapsOptions.injectDebugIds, // `sourcemaps.delete` does not reach the plugins: `withClientSourceMapDeletion` and - // `filesToDeleteAfterUpload` apply it, because Nitro still needs the maps of the SSR build. + // `sdkFilesToDeleteAfterUpload` apply it, because Nitro still needs the maps of the SSR build. // The server/client files are in different places depending on the nitro preset (e.g. '.output/server' or '.netlify/functions-internal/server') // We cannot determine automatically how the build folder looks like (depends on the preset), so each plugin uploads its own build output (the vitePlugin for the Nuxt client and the rollupPlugin for Nitro). // If we could know where the server/client assets are located, we could do something like this (based on the Nitro preset): isNitro ? ['./.output/server/**/*'] : ['./.output/public/**/*'], assets: sourcemapsOptions.assets ?? undefined, ignore: sourcemapsOptions.ignore ?? undefined, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, rewriteSources: sourcemapsOptions.rewriteSources ?? normalizePath, resolveSourceMap: sourcemapsOptions.resolveSourceMap, }, @@ -284,12 +284,7 @@ function resolveFilesToDeleteAfterUpload( if (typeof filesToDeleteAfterUpload === 'undefined' && shouldDeleteFilesAfterUpload && moduleOptions.debug) { // eslint-disable-next-line no-console - console.log( - `[Sentry] Setting \`sentry.sourcemaps.filesToDeleteAfterUpload: [${fallbackFilesToDelete - // Logging it as strings in the array - .map(path => `"${path}"`) - .join(', ')}]\` to delete generated source maps after they were uploaded to Sentry.`, - ); + console.log(`[Sentry] Deleting the generated source maps after the upload: ${fallbackFilesToDelete.join(', ')}`); } return filesToDeleteAfterUpload !== undefined @@ -309,8 +304,8 @@ function resolveFilesToDeleteAfterUpload( - we enable 'hidden' source maps generation when Sentry uploads the maps, or when `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - client with the Vite builder: pass `sdkDeleteSourceMaps: true`, so the maps never reach the build output - - client with another builder: configure `filesToDeleteAfterUpload` for the .map files in Nitro's public dir - - server: configure `filesToDeleteAfterUpload` to delete the .map files after the build (we emit a log about this) + - client with another builder: delete the .map files in Nitro's public dir + - server: delete the .map files after the build (we emit a log about this) Users only have to explicitly enable client source maps. Sentry only overwrites the base Nuxt source map settings as they propagate. */ diff --git a/packages/nuxt/test/vite/sourceMapDeletion.test.ts b/packages/nuxt/test/vite/sourceMapDeletion.test.ts index 73f180cd5c83..9e66e8576e4f 100644 --- a/packages/nuxt/test/vite/sourceMapDeletion.test.ts +++ b/packages/nuxt/test/vite/sourceMapDeletion.test.ts @@ -45,7 +45,7 @@ describe('deletePublicSourceMaps', () => { await deletePublicSourceMaps( { sourcemaps: { - filesToDeleteAfterUpload: [toGlob('.*/**/public*/**/*.map'), toGlob('.*/**/server/**/*.map')], + sdkFilesToDeleteAfterUpload: [toGlob('.*/**/public*/**/*.map'), toGlob('.*/**/server/**/*.map')], }, }, publicDir, @@ -61,7 +61,7 @@ describe('deletePublicSourceMaps', () => { it('keeps the files in the public dir that no pattern matches', async () => { await deletePublicSourceMaps( - { sourcemaps: { filesToDeleteAfterUpload: toGlob('.output/public/_nuxt/pages/*.map') } }, + { sourcemaps: { sdkFilesToDeleteAfterUpload: toGlob('.output/public/_nuxt/pages/*.map') } }, publicDir, ); @@ -76,7 +76,7 @@ describe('deletePublicSourceMaps', () => { it('resolves a promised list of patterns', async () => { await deletePublicSourceMaps( - { sourcemaps: { filesToDeleteAfterUpload: Promise.resolve([toGlob('.output/public/**/*.map')]) } }, + { sourcemaps: { sdkFilesToDeleteAfterUpload: Promise.resolve([toGlob('.output/public/**/*.map')]) } }, publicDir, ); diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index c36ea805aea3..ed2f9edb7593 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -370,6 +370,7 @@ describe('setupSourceMaps hooks', () => { assets: undefined, ignore: undefined, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: expect.any(Function), rewriteSources: expect.any(Function), @@ -377,7 +378,7 @@ describe('setupSourceMaps hooks', () => { }); }); - it('sentryRollupPlugin is called without filesToDeleteAfterUpload when source maps are explicitly enabled', async () => { + it('sentryRollupPlugin is called without deletion globs when source maps are explicitly enabled', async () => { const mockNuxt = createMockNuxt({ _prepare: false, dev: false, @@ -393,7 +394,10 @@ describe('setupSourceMaps hooks', () => { expect(mockSentryRollupPlugin).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: undefined }), + sourcemaps: expect.objectContaining({ + filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, + }), }), ); }); @@ -415,6 +419,7 @@ describe('setupSourceMaps hooks', () => { expect(mockNuxt.options.sourcemap).toEqual({ client: 'hidden', server: true }); expect(getDeleteOption()).toBe(true); expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(capturedViteOptions.options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); }); // The plugin then also removes the maps of chunks that the user's `assets` or `ignore` leave out. @@ -529,9 +534,9 @@ describe('setupSourceMaps hooks', () => { return mockNuxt; } - function expectFilesDeletedAfterBuild(filesToDeleteAfterUpload: string[]): void { + function expectFilesDeletedAfterBuild(sdkFilesToDeleteAfterUpload: string[]): void { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( - expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + expect.objectContaining({ sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload }) }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); } @@ -610,9 +615,12 @@ describe('setupSourceMaps hooks', () => { await mockNuxt.triggerHook('close'); expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(capturedViteOptions.options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); expect(getDeleteOption()).toBeUndefined(); expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( - expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + expect.objectContaining({ + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload }), + }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); }); @@ -634,7 +642,7 @@ describe('setupSourceMaps hooks', () => { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: defaultFilesToDeleteAfterUpload }), + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: defaultFilesToDeleteAfterUpload }), }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); @@ -669,7 +677,7 @@ describe('setupSourceMaps hooks', () => { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }), + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload }), }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); @@ -895,7 +903,7 @@ describe('setupSourceMaps hooks', () => { for (const side of ['client', 'server']) { expect(consoleLogSpy).toHaveBeenCalledWith( - `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload. Set \`sourcemaps.delete: false\` to keep them.`, ); } }, diff --git a/packages/nuxt/test/vite/sourceMaps.test.ts b/packages/nuxt/test/vite/sourceMaps.test.ts index e6df2bfc5305..90c3334987b9 100644 --- a/packages/nuxt/test/vite/sourceMaps.test.ts +++ b/packages/nuxt/test/vite/sourceMaps.test.ts @@ -105,7 +105,7 @@ describe('getPluginOptions', () => { sourcemaps: expect.objectContaining({ assets: ['custom-assets/**/*'], ignore: ['ignore-this.js'], - filesToDeleteAfterUpload: ['delete-this.js'], + sdkFilesToDeleteAfterUpload: ['delete-this.js'], rewriteSources: expect.any(Function), }), _metaOptions: expect.objectContaining({ @@ -256,7 +256,7 @@ describe('getPluginOptions', () => { expected: undefined, }, ])( - 'sets filesToDeleteAfterUpload correctly when $name', + 'sets sdkFilesToDeleteAfterUpload correctly when $name', ({ clientFallback, serverFallback, customOptions = {}, serverDir = NODE_SERVER_DIR, expected }) => { const options = getPluginOptions(customOptions as SentryNuxtModuleOptions, { client: clientFallback, @@ -264,7 +264,8 @@ describe('getPluginOptions', () => { serverDir: serverDir ?? undefined, }); - expect(options?.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); + expect(options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(expected); + expect(options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); }, ); }); diff --git a/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts b/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts index a83b7ab5d279..265da9c130c3 100644 --- a/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts +++ b/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts @@ -137,11 +137,7 @@ export const sentryOnBuildEnd: BuildEndHook = async ({ reactRouterConfig, viteCo updatedFilesToDeleteAfterUpload = defaultFilesToDelete; debug && // eslint-disable-next-line no-console - console.info( - `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify( - updatedFilesToDeleteAfterUpload, - )}\` to delete generated source maps after they were uploaded to Sentry.`, - ); + console.info(`[Sentry] Deleting the generated source maps after the upload: ${defaultFilesToDelete.join(', ')}`); } if (updatedFilesToDeleteAfterUpload) { try { diff --git a/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts b/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts index 61f223724d4e..056a0c2bbfc3 100644 --- a/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts +++ b/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts @@ -459,7 +459,9 @@ describe('sentryOnBuildEnd', () => { // @ts-expect-error - mocking the React config await sentryOnBuildEnd(config); - expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[Sentry] Automatically setting')); + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining('[Sentry] Deleting the generated source maps after the upload: '), + ); expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Deleting asset after upload:')); expect(mockSentrySdkInstance.sourcemap.inject).toHaveBeenCalledWith({ directory: '/build' }); diff --git a/packages/sveltekit/src/vite/sourceMaps.ts b/packages/sveltekit/src/vite/sourceMaps.ts index b1f22b11a4b9..dcbef0f208ab 100644 --- a/packages/sveltekit/src/vite/sourceMaps.ts +++ b/packages/sveltekit/src/vite/sourceMaps.ts @@ -85,7 +85,8 @@ export async function makeCustomSentryVitePlugins( }, sourcemaps: { ...options?.sourcemaps, - filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, + filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, // The adapter runs after the bundler and still needs the source maps, so // the SDK deletes them from disk afterwards instead of the plugin. deleteSourcemapsAfterUpload: undefined, @@ -180,9 +181,7 @@ export async function makeCustomSentryVitePlugins( debug && // eslint-disable-next-line no-console console.info( - `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: [${defaultFileDeletionGlob - .map(file => `"${file}"`) - .join(', ')}]\` to delete generated source maps after they were uploaded to Sentry.`, + `[Sentry] Deleting the generated source maps after the upload: ${defaultFileDeletionGlob.join(', ')}`, ); _resolveFilesToDeleteAfterUpload?.( @@ -353,7 +352,7 @@ export async function makeCustomSentryVitePlugins( * 3. Users didn't set source maps generation * - we enable 'hidden' source maps generation when Sentry uploads the maps, or when * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - * - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this) + * - delete all .map files after the upload (we emit a log about this) * * --> only exported for testing */ diff --git a/packages/sveltekit/test/vite/sourceMaps.test.ts b/packages/sveltekit/test/vite/sourceMaps.test.ts index f162821fc5ae..85b0e8b8ddf3 100644 --- a/packages/sveltekit/test/vite/sourceMaps.test.ts +++ b/packages/sveltekit/test/vite/sourceMaps.test.ts @@ -487,8 +487,9 @@ describe('source map deletion with `sourcemaps.delete`', () => { deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: false, delete: undefined, + filesToDeleteAfterUpload: undefined, }); - return mergedOptions.sourcemaps?.filesToDeleteAfterUpload; + return mergedOptions.sourcemaps?.sdkFilesToDeleteAfterUpload; } beforeEach(() => { @@ -623,7 +624,7 @@ describe('deleteFilesAfterUpload', () => { inject: false, }, sourcemaps: { - filesToDeleteAfterUpload: expect.any(Promise), + sdkFilesToDeleteAfterUpload: expect.any(Promise), sdkDeleteSourceMaps: false, }, }); @@ -643,7 +644,7 @@ describe('deleteFilesAfterUpload', () => { // @ts-expect-error this function exists! await filesToDeleteAfterUploadSettingPlugin.configResolved(); - await expect(mergedOptions.sourcemaps.filesToDeleteAfterUpload).resolves.toEqual([ + await expect(mergedOptions.sourcemaps.sdkFilesToDeleteAfterUpload).resolves.toEqual([ './.*/**/*.map', './.svelte-kit/output/**/*.map', ]); @@ -703,7 +704,7 @@ describe('deleteFilesAfterUpload', () => { inject: false, }, sourcemaps: { - filesToDeleteAfterUpload: expect.any(Promise), + sdkFilesToDeleteAfterUpload: expect.any(Promise), sdkDeleteSourceMaps: false, }, }); @@ -723,7 +724,7 @@ describe('deleteFilesAfterUpload', () => { // @ts-expect-error this function exists! await filesToDeleteAfterUploadSettingPlugin.configResolved(); - await expect(mergedOptions.sourcemaps.filesToDeleteAfterUpload).resolves.toEqual( + await expect(mergedOptions.sourcemaps.sdkFilesToDeleteAfterUpload).resolves.toEqual( filesToDeleteAfterUploadExpected, ); },