Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott

Work in this release was contributed by @kyrylolvov. Thank you for your contribution!

### Important Changes

- **feat(bundler-plugins): Release `@sentry/webpack-plugin`, `@sentry/vite-plugin`, `@sentry/rollup-plugin` and `@sentry/esbuild-plugin` from the SDK repository ([#25095](https://github.com/getsentry/sentry-javascript/pull/25095))**
Expand Down
160 changes: 160 additions & 0 deletions packages/tanstackstart-react/src/vite/nitroSourceMaps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { readFile } from 'node:fs/promises';
import * as path from 'node:path';
import type { BuildEnvironmentOptions, Plugin, ResolvedConfig } from 'vite';

/** `nitro/vite` builds the final server in an environment with this name. */
const NITRO_ENVIRONMENT = 'nitro';

/** The environment Vite passes to `applyToEnvironment`. */
export type PluginEnvironment = Parameters<NonNullable<Plugin['applyToEnvironment']>>[0];

type BundlerSourceMapConfig = { output?: { sourcemap?: unknown } };

type NitroSourceMapConfig = {
sourcemap?: unknown;
rollupConfig?: BundlerSourceMapConfig;
rolldownConfig?: BundlerSourceMapConfig;
};

/** The parts of the Nitro instance that this plugin uses. */
type Nitro = {
options: {
sourcemap: unknown;
experimental: { sourcemapMinify?: false };
// c12 keeps each config source that Nitro merged: the `nitro()` options, `nitro.config.ts`, presets and more.
// It is internal until Nitro exposes the layers: https://github.com/nitrojs/nitro/issues/4771
_c12?: { layers?: { config?: NitroSourceMapConfig | null }[] };
};
};

/**
* Tells the plugin that deletes source maps after the upload whether the source maps of an environment are only
* there because Sentry enabled them.
*/
export type SourceMapsEnablerApi = { hasSentryEnabledSourceMaps(environmentName: string): boolean };

/**
* Whether Nitro bundles the output of this environment again. With `nitro/vite`, every server environment besides
* `nitro` is a Nitro service, such as TanStack Start's `ssr` environment.
*/
export function isNitroService(environment: PluginEnvironment): boolean {
return (
environment.name !== NITRO_ENVIRONMENT &&
environment.config.consumer === 'server' &&
NITRO_ENVIRONMENT in environment.config.environments
);
}

/**
* Keeps the sources in the source maps of Nitro's server build. Enables these source maps, unless a Nitro config
* source or `build.rolldownOptions.output.sourcemap` of the Vite config sets them, or the Vite config disables them.
*/
export function makeEnableNitroSourceMapsPlugin({ debug }: { debug?: boolean }): Plugin & {
api: SourceMapsEnablerApi;
nitro: { name: string; setup: (nitro: Nitro) => void };
} {
let enabledSourceMaps = false;
let viteConfigPreventsSourceMaps = false;

return {
name: 'sentry-tanstackstart-nitro-source-maps',
apply: 'build',
// The `config` hook must run before the one of `nitro/vite`, which runs the Nitro modules.
enforce: 'pre',
api: {
hasSentryEnabledSourceMaps: environmentName => enabledSourceMaps && environmentName === NITRO_ENVIRONMENT,
},
config(viteConfig) {
// Nitro overrides `build.sourcemap` for its environments, but `false` shows that the user wants no source maps.
viteConfigPreventsSourceMaps =
viteConfig.build?.sourcemap === false || hasOutputSourceMapSetting(viteConfig.build);
},
// `nitro/vite` installs the Nitro module of each Vite plugin after it merged all config sources.
nitro: {
name: 'sentry-tanstackstart-nitro-source-maps',
setup(nitro) {
// Otherwise Nitro removes `sourcesContent` from its source maps, and `mappings` from maps with only
// `node_modules` sources. Nitro only allows `false`.
nitro.options.experimental.sourcemapMinify = false;

const layers = nitro.options._c12?.layers;
// Without the config sources, Sentry cannot tell if the user disabled source maps.
if (!layers || viteConfigPreventsSourceMaps || layers.some(layer => hasNitroSourceMapSetting(layer.config))) {
return;
}

nitro.options.sourcemap = 'hidden';
enabledSourceMaps = true;
logDebug(debug, "Enabled source map generation for the Nitro server build with `nitro.sourcemap: 'hidden'`.");
},
},
};
}

/**
* Nitro reads the output of its services as plain code, so its source maps would end at that output. Loading the
* service's source map with the code lets the bundler compose both maps to the original source files.
*/
export function makeComposeNitroServiceSourceMapsPlugin(): Plugin {
return {
name: 'sentry-tanstackstart-nitro-service-source-maps',
apply: 'build',
applyToEnvironment: environment => environment.name === NITRO_ENVIRONMENT,
async load(id) {
const serviceOutDirs = getNitroServiceOutDirs(this.environment.config);
if (!serviceOutDirs.some(outDir => isInDirectory(id, outDir))) {
return null;
}

try {
const [code, map] = await Promise.all([readFile(id, 'utf8'), readFile(`${id}.map`, 'utf8')]);
return { code, map };
} catch {
// A chunk without a source map: let Nitro load the code as usual.
return null;
}
},
};
}

/** The output directories of the environments that Nitro bundles again. Empty in a build without Nitro. */
export function getNitroServiceOutDirs(config: ResolvedConfig): string[] {
if (!(NITRO_ENVIRONMENT in config.environments)) {
return [];
}

return Object.entries(config.environments)
.filter(([name, environment]) => name !== NITRO_ENVIRONMENT && environment.consumer === 'server')
.map(([, environment]) => path.resolve(config.root, environment.build.outDir));
}

function isInDirectory(file: string, directory: string): boolean {
const relativePath = path.relative(directory, file);
return (
relativePath !== '' &&
relativePath !== '..' &&
!relativePath.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativePath)
);
}

/** `output.sourcemap` of the bundler config overrides `build.sourcemap` in the build output. */
export function hasOutputSourceMapSetting(
build: Pick<BuildEnvironmentOptions, 'rolldownOptions'> | undefined,
): boolean {
return [build?.rolldownOptions?.output ?? []].flat().some(output => output.sourcemap !== undefined);
}

/** In a Nitro config, `output.sourcemap` of the bundler config overrides `sourcemap` in the build output. */
function hasNitroSourceMapSetting(config: NitroSourceMapConfig | null | undefined): boolean {
return [config?.sourcemap, config?.rollupConfig?.output?.sourcemap, config?.rolldownConfig?.output?.sourcemap].some(
setting => setting !== undefined,
);
}

function logDebug(debug: boolean | undefined, message: string): void {
if (debug) {
// eslint-disable-next-line no-console
console.log(`[Sentry] ${message}`);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { BuildTimeOptionsBase, ReactComponentAnnotationOptions } from '@sen
import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
import type { Plugin } from 'vite';
import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware';
import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugin } from './nitroSourceMaps';
import { makeRoutePatternPlugin } from './routePatterns';
import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps';
import type { TunnelRouteOptions } from './tunnelRoute';
Expand Down Expand Up @@ -92,7 +93,7 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P
// (CommonJS) deps via `ssr.noExternal`, which the `vite dev` SSR module runner can't evaluate.
plugins.push(sentryOrchestrionPlugin({ buildTimeInstrumentation: options.buildTimeInstrumentation }));

plugins.push(...makeAddSentryVitePlugin(options));
plugins.push(...makeAddSentryVitePlugin(options), makeComposeNitroServiceSourceMapsPlugin());

// middleware auto-instrumentation
if (options.autoInstrumentMiddleware !== false) {
Expand All @@ -102,7 +103,7 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P
// source maps
const sourceMapsDisabled = options.sourcemaps?.disable === true || options.sourcemaps?.disable === 'disable-upload';
if (!sourceMapsDisabled) {
plugins.push(...makeEnableSourceMapsVitePlugin(options));
plugins.push(...makeEnableSourceMapsVitePlugin(options), makeEnableNitroSourceMapsPlugin(options));
}

return plugins;
Expand Down
33 changes: 19 additions & 14 deletions packages/tanstackstart-react/src/vite/sourceMaps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { sentryVitePlugin } from '@sentry/bundler-plugins/vite';
import * as path from 'node:path';
import type { BuildEnvironmentOptions, Plugin, ResolvedConfig, UserConfig } from 'vite';
import type { Plugin, ResolvedConfig, UserConfig } from 'vite';
import {
getNitroServiceOutDirs,
hasOutputSourceMapSetting,
isNitroService,
type PluginEnvironment,
type SourceMapsEnablerApi,
} from './nitroSourceMaps';
import type { SentryTanstackStartOptions } from './sentryTanstackStart';

type FilesToDeleteAfterUpload = string | string[] | undefined;
Expand Down Expand Up @@ -30,12 +37,6 @@ export function rewriteTanstackStartSource(source: string, _map: unknown, contex
return path.relative(process.cwd(), absolutePath).split(path.sep).join('/');
}

/**
* Tells the plugin that deletes source maps after the upload whether the source maps of an environment are only
* there because Sentry enabled them.
*/
type SourceMapsEnablerApi = { hasSentryEnabledSourceMaps(environmentName: string): boolean };

/**
* A Sentry plugin for adding the @sentry/bundler-plugins/vite to automatically upload source maps to Sentry.
*/
Expand Down Expand Up @@ -125,18 +126,27 @@ export function makeAddSentryVitePlugin(options: SentryTanstackStartOptions): Pl
},
});

return [configPlugin, ...sentryPlugins];
// Nitro bundles the output of its services again. Debug IDs from a service would end up in Nitro's output and point
// to the service's source maps instead of Nitro's.
const scopedSentryPlugins = sentryPlugins.map(plugin => ({
...plugin,
applyToEnvironment: (environment: PluginEnvironment) => !isNitroService(environment),
}));

return [configPlugin, ...scopedSentryPlugins];
}

/**
* Globs for the source maps in the output directories that only have source maps because Sentry enabled them. A glob
* such as `./**\/*.map` does not enter dot directories like `.output`, where Nitro puts the client build.
*/
function getSentryEnabledSourceMapGlobs(config: ResolvedConfig): string[] {
const serviceOutDirs = getNitroServiceOutDirs(config);
const outDirs = Object.entries(config.environments)
.filter(([name]) => hasSentryEnabledSourceMaps(config, name))
.filter(([, environment]) => !hasOutputSourceMapSetting(environment.build))
.flatMap(([, environment]) => getOutputDirs(config.root, environment.build));
.flatMap(([, environment]) => getOutputDirs(config.root, environment.build))
.filter(outDir => !serviceOutDirs.includes(outDir));

return [...new Set(outDirs)].map(outDir => {
const relativeOutDir = path.relative(process.cwd(), outDir).split(path.sep).join('/');
Expand All @@ -151,11 +161,6 @@ function getOutputDirs(root: string, build: ResolvedConfig['environments'][strin
return outputs.map(output => path.resolve(root, output.dir ?? build.outDir));
}

/** `output.sourcemap` of the bundler config overrides `build.sourcemap` in the build output. */
function hasOutputSourceMapSetting(build: Pick<BuildEnvironmentOptions, 'rolldownOptions'> | undefined): boolean {
return [build?.rolldownOptions?.output ?? []].flat().some(output => output.sourcemap !== undefined);
}

/** Vite tells plugins its version since Vite 7. */
function isVite8OrLater(viteVersion: string | undefined): boolean {
return Number(viteVersion?.split('.')[0]) >= 8;
Expand Down
Loading
Loading