Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nuxt): Respect user-provided source map generation settings #14020

Merged
merged 4 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
235 changes: 208 additions & 27 deletions packages/nuxt/src/vite/sourceMaps.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
import type { Nuxt } from '@nuxt/schema';
import { type SentryRollupPluginOptions, sentryRollupPlugin } from '@sentry/rollup-plugin';
import { consoleSandbox } from '@sentry/utils';
import { type SentryVitePluginOptions, sentryVitePlugin } from '@sentry/vite-plugin';
import type { NitroConfig } from 'nitropack';
import type { OutputOptions } from 'rollup';
import type { SentryNuxtModuleOptions } from '../common/types';

/**
* Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps
*/
export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined;

/**
* Setup source maps for Sentry inside the Nuxt module during build time (in Vite for Nuxt and Rollup for Nitro).
*/
export function setupSourceMaps(moduleOptions: SentryNuxtModuleOptions, nuxt: Nuxt): void {
const sourceMapsUploadOptions = moduleOptions.sourceMapsUploadOptions || {};
const sourceMapsEnabled = sourceMapsUploadOptions.enabled ?? true;

nuxt.hook('vite:extendConfig', async (viteInlineConfig, _env) => {
if (sourceMapsEnabled && viteInlineConfig.mode !== 'development') {
// Add Sentry plugin
viteInlineConfig.plugins = viteInlineConfig.plugins || [];
viteInlineConfig.plugins.push(sentryVitePlugin(getPluginOptions(moduleOptions)));
nuxt.hook('modules:done', () => {
if (sourceMapsEnabled && !nuxt.options.dev) {
changeNuxtSourceMapSettings(nuxt, moduleOptions);
}
});

// Enable source maps
viteInlineConfig.build = viteInlineConfig.build || {};
viteInlineConfig.build.sourcemap = true;
nuxt.hook('vite:extendConfig', async (viteConfig, _env) => {
if (sourceMapsEnabled && viteConfig.mode !== 'development') {
const previousUserSourceMapSetting = changeViteSourceMapSettings(viteConfig, moduleOptions);

logDebugInfo(moduleOptions, viteInlineConfig.build?.sourcemap);
// Add Sentry plugin
viteConfig.plugins = viteConfig.plugins || [];
viteConfig.plugins.push(
sentryVitePlugin(getPluginOptions(moduleOptions, previousUserSourceMapSetting === 'unset')),
);
}
});

Expand All @@ -38,15 +49,12 @@ export function setupSourceMaps(moduleOptions: SentryNuxtModuleOptions, nuxt: Nu
nitroConfig.rollupConfig.plugins = [nitroConfig.rollupConfig.plugins];
}

// Add Sentry plugin
nitroConfig.rollupConfig.plugins.push(sentryRollupPlugin(getPluginOptions(moduleOptions)));

// Enable source maps
nitroConfig.rollupConfig.output = nitroConfig?.rollupConfig?.output || {};
nitroConfig.rollupConfig.output.sourcemap = true;
nitroConfig.rollupConfig.output.sourcemapExcludeSources = false; // Adding "sourcesContent" to the source map (Nitro sets this eto `true`)
const previousUserSourceMapSetting = changeRollupSourceMapSettings(nitroConfig, moduleOptions);

logDebugInfo(moduleOptions, nitroConfig.rollupConfig.output?.sourcemap);
// Add Sentry plugin
nitroConfig.rollupConfig.plugins.push(
sentryRollupPlugin(getPluginOptions(moduleOptions, previousUserSourceMapSetting === 'unset')),
);
}
});
}
Expand All @@ -65,9 +73,19 @@ function normalizePath(path: string): string {
*/
export function getPluginOptions(
moduleOptions: SentryNuxtModuleOptions,
deleteFilesAfterUpload: boolean,
): SentryVitePluginOptions | SentryRollupPluginOptions {
const sourceMapsUploadOptions = moduleOptions.sourceMapsUploadOptions || {};

if (typeof sourceMapsUploadOptions.sourcemaps?.filesToDeleteAfterUpload === 'undefined' && deleteFilesAfterUpload) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.log(
'[Sentry] Setting `sentry.sourceMapsUploadOptions.sourcemaps.filesToDeleteAfterUpload: [".*/**/*.map"]` to delete generated source maps after they were uploaded to Sentry.',
);
});
}

return {
org: sourceMapsUploadOptions.org ?? process.env.SENTRY_ORG,
project: sourceMapsUploadOptions.project ?? process.env.SENTRY_PROJECT,
Expand All @@ -83,29 +101,192 @@ export function getPluginOptions(

sourcemaps: {
// 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 we have to accept that sourcemaps are uploaded multiple times (with the vitePlugin for Nuxt and the rollupPlugin for Nitro).
// We cannot determine automatically how the build folder looks like (depends on the preset), so we have to accept that source maps are uploaded multiple times (with the vitePlugin for Nuxt 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: sourceMapsUploadOptions.sourcemaps?.assets ?? undefined,
ignore: sourceMapsUploadOptions.sourcemaps?.ignore ?? undefined,
filesToDeleteAfterUpload: sourceMapsUploadOptions.sourcemaps?.filesToDeleteAfterUpload ?? undefined,
filesToDeleteAfterUpload: sourceMapsUploadOptions.sourcemaps?.filesToDeleteAfterUpload
? sourceMapsUploadOptions.sourcemaps?.filesToDeleteAfterUpload
: deleteFilesAfterUpload
? ['.*/**/*.map']
: undefined,
rewriteSources: (source: string) => normalizePath(source),
...moduleOptions?.unstable_sentryBundlerPluginOptions?.sourcemaps,
},
};
}

function logDebugInfo(moduleOptions: SentryNuxtModuleOptions, sourceMapsPreviouslyEnabled: boolean): void {
if (moduleOptions.debug && !sourceMapsPreviouslyEnabled) {
/* There are 3 ways to set up source maps (https://github.com/getsentry/sentry-javascript/issues/13993)
1. User explicitly disabled source maps
- keep this setting (emit a warning that errors won't be unminified in Sentry)
- We will not upload anything
2. users enabled source map generation (true, hidden, inline).
- keep this setting (don't do anything - like deletion - besides uploading)
3. users did not set source maps generation
- we enable 'hidden' source maps generation
- configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this)

Nuxt has 3 places to set source maps: vite options, rollup options, nuxt itself
Ideally, all 3 are enabled to get all source maps.
*/

/** only exported for testing */
export function changeNuxtSourceMapSettings(
nuxt: Nuxt,
sentryModuleOptions: SentryNuxtModuleOptions,
): { client: UserSourceMapSetting; server: UserSourceMapSetting } {
nuxt.options = nuxt.options || {};
nuxt.options.sourcemap = nuxt.options.sourcemap ?? { server: undefined, client: undefined };

let previousUserSourceMapSetting: { client: UserSourceMapSetting; server: UserSourceMapSetting } = {
client: undefined,
server: undefined,
};

const nuxtSourceMap = nuxt.options.sourcemap;

if (typeof nuxtSourceMap === 'string' || typeof nuxtSourceMap === 'boolean' || typeof nuxtSourceMap === 'undefined') {
switch (nuxtSourceMap) {
case false:
warnExplicitlyDisabledSourceMap('sourcemap');
previousUserSourceMapSetting = { client: 'disabled', server: 'disabled' };
break;

case 'hidden':
case true:
logKeepSourceMapSetting(sentryModuleOptions, 'sourcemap', (nuxtSourceMap as true).toString());
previousUserSourceMapSetting = { client: 'enabled', server: 'enabled' };
break;
case undefined:
nuxt.options.sourcemap = { server: 'hidden', client: 'hidden' };
logSentryEnablesSourceMap('sourcemap.client', 'hidden');
logSentryEnablesSourceMap('sourcemap.server', 'hidden');
previousUserSourceMapSetting = { client: 'unset', server: 'unset' };
break;
}
} else {
if (nuxtSourceMap.client === false) {
warnExplicitlyDisabledSourceMap('sourcemap.client');
previousUserSourceMapSetting.client = 'disabled';
} else if (['hidden', true].includes(nuxtSourceMap.client)) {
logKeepSourceMapSetting(sentryModuleOptions, 'sourcemap.client', nuxtSourceMap.client.toString());
previousUserSourceMapSetting.client = 'enabled';
} else {
nuxt.options.sourcemap.client = 'hidden';
logSentryEnablesSourceMap('sourcemap.client', 'hidden');
previousUserSourceMapSetting.client = 'unset';
}

if (nuxtSourceMap.server === false) {
warnExplicitlyDisabledSourceMap('sourcemap.server');
previousUserSourceMapSetting.server = 'disabled';
} else if (['hidden', true].includes(nuxtSourceMap.server)) {
logKeepSourceMapSetting(sentryModuleOptions, 'sourcemap.server', nuxtSourceMap.server.toString());
previousUserSourceMapSetting.server = 'enabled';
} else {
nuxt.options.sourcemap.server = 'hidden';
logSentryEnablesSourceMap('sourcemap.server', 'hidden');
previousUserSourceMapSetting.server = 'unset';
}
}

return previousUserSourceMapSetting;
}

/** only exported for testing */
export function changeViteSourceMapSettings(
viteConfig: { build?: { sourcemap?: boolean | 'inline' | 'hidden' } },
sentryModuleOptions: SentryNuxtModuleOptions,
): UserSourceMapSetting {
viteConfig.build = viteConfig.build || {};
const viteSourceMap = viteConfig.build.sourcemap;

let previousUserSourceMapSetting: UserSourceMapSetting;

if (viteSourceMap === false) {
warnExplicitlyDisabledSourceMap('vite.build.sourcemap');
previousUserSourceMapSetting = 'disabled';
} else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) {
logKeepSourceMapSetting(sentryModuleOptions, 'vite.build.sourcemap', viteSourceMap.toString());
previousUserSourceMapSetting = 'enabled';
} else {
viteConfig.build.sourcemap = 'hidden';
logSentryEnablesSourceMap('vite.build.sourcemap', 'hidden');
previousUserSourceMapSetting = 'unset';
}

return previousUserSourceMapSetting;
}

/** only exported for testing */
export function changeRollupSourceMapSettings(
nitroConfig: {
rollupConfig?: {
output?: {
sourcemap?: OutputOptions['sourcemap'];
sourcemapExcludeSources?: OutputOptions['sourcemapExcludeSources'];
};
};
},
sentryModuleOptions: SentryNuxtModuleOptions,
): UserSourceMapSetting {
nitroConfig.rollupConfig = nitroConfig.rollupConfig || {};
nitroConfig.rollupConfig.output = nitroConfig.rollupConfig.output || { sourcemap: undefined };

let previousUserSourceMapSetting: UserSourceMapSetting;

const nitroSourceMap = nitroConfig.rollupConfig.output.sourcemap;

if (nitroSourceMap === false) {
warnExplicitlyDisabledSourceMap('nitro.rollupConfig.output.sourcemap');
previousUserSourceMapSetting = 'disabled';
} else if (nitroSourceMap && ['hidden', 'inline', true].includes(nitroSourceMap)) {
logKeepSourceMapSetting(sentryModuleOptions, 'nitro.rollupConfig.output.sourcemap', nitroSourceMap.toString());
previousUserSourceMapSetting = 'enabled';
} else {
nitroConfig.rollupConfig.output.sourcemap = 'hidden';
logSentryEnablesSourceMap('nitro.rollupConfig.output.sourcemap', 'hidden');
previousUserSourceMapSetting = 'unset';
}

nitroConfig.rollupConfig.output.sourcemapExcludeSources = false;
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.log('[Sentry]: Enabled source maps generation in the Vite build options.');
console.log(
'[Sentry] Disabled source map setting in the Nuxt config: `nitro.rollupConfig.output.sourcemapExcludeSources`. Source maps will include the actual code to be able to un-minify code snippets in Sentry.',
);
});

const sourceMapsUploadOptions = moduleOptions.sourceMapsUploadOptions || {};
return previousUserSourceMapSetting;
}

if (!sourceMapsUploadOptions.sourcemaps?.filesToDeleteAfterUpload) {
function logKeepSourceMapSetting(
sentryNuxtModuleOptions: SentryNuxtModuleOptions,
settingKey: string,
settingValue: string,
): void {
if (sentryNuxtModuleOptions.debug) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[Sentry] We recommend setting the `sourceMapsUploadOptions.sourcemaps.filesToDeleteAfterUpload` option to clean up source maps after uploading. Otherwise, source maps might be deployed to production, depending on your configuration',
console.log(
`[Sentry] We discovered \`${settingKey}\` is set to \`${settingValue}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`,
);
}
});
}
}

function warnExplicitlyDisabledSourceMap(settingKey: string): void {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
`[Sentry] Parts of source map generation are currently disabled in your Nuxt configuration (\`${settingKey}: false\`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\`.`,
);
});
}

function logSentryEnablesSourceMap(settingKey: string, settingValue: string): void {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.log(`[Sentry] Enabled source map generation in the build options with \`${settingKey}: ${settingValue}\`.`);
});
}
Loading
Loading