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
6 changes: 6 additions & 0 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* oxlint-disable max-lines */
import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core';
import { sentryVitePlugin } from '@sentry/bundler-plugins/vite';
import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core';
import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Expand Down Expand Up @@ -139,6 +141,10 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
],
},
});
} else if (sdkEnabled.server && command !== 'dev') {
// TODO: Revisit which features the plugin should run when source maps are off. For now it only injects
// module versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime.
updateConfig({ vite: { plugins: [sentryVitePlugin(getDisabledSourcemapsOptions({ debug }))] } });
}

runtimeRelease && injectScript('head-inline', buildReleaseSnippet(runtimeRelease));
Expand Down
4 changes: 3 additions & 1 deletion packages/astro/test/integration/index.files.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { sentryAstro } from '../../src/integration';

Expand All @@ -9,7 +10,8 @@ vi.mock('fs', async requireActual => {
});

// Without a configured name, the real resolver falls back to the git revision of this checkout.
vi.mock('@sentry/bundler-plugins/core', () => ({
vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
...(await importOriginal<typeof BundlerPluginsCore>()),
resolveReleaseName: (name?: string) => name,
}));

Expand Down
44 changes: 41 additions & 3 deletions packages/astro/test/integration/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core';
import type * as FsModule from 'fs';
import type { AstroConfig, AstroIntegrationLogger } from 'astro';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand All @@ -22,7 +23,8 @@ vi.mock('@sentry/bundler-plugins/vite', () => ({

// Without a configured name, the real resolver falls back to the git revision of this checkout.
const resolveReleaseName = vi.fn((name?: string) => name);
vi.mock('@sentry/bundler-plugins/core', () => ({
vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
...(await importOriginal<typeof BundlerPluginsCore>()),
resolveReleaseName: (name?: string) => resolveReleaseName(name),
}));

Expand Down Expand Up @@ -531,19 +533,55 @@ describe('sentryAstro integration', () => {
it("doesn't enable source maps if `sourcemaps.disable` is `true`", async () => {
const integration = sentryAstro({
sourcemaps: { disable: true },
debug: true,
});

expect(integration.hooks['astro:config:setup']).toBeDefined();
// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config });

// only the orchestrion plugin and the server init are wired, no sourcemaps plugin
expect(updateConfig).toHaveBeenCalledTimes(2);
// one call each for the module versions plugin, the orchestrion plugin and the server init
expect(updateConfig).toHaveBeenCalledTimes(3);
expect(updateConfig).toHaveBeenCalledWith({
vite: {
plugins: [{ name: 'sentry-orchestrion-vite' }],
},
});
expect(updateConfig).not.toHaveBeenCalledWith({ vite: expect.objectContaining({ build: expect.anything() }) });
// the bundler plugin only injects module versions
expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1);
expect(sentryVitePluginSpy).toHaveBeenCalledWith({
debug: true,
telemetry: false,
sourcemaps: { upload: false, injectDebugIds: false },
release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false },
});
});

it("doesn't add the module versions plugin if `sourcemaps.disable` is `true` and the server SDK is disabled", async () => {
const integration = sentryAstro({
sourcemaps: { disable: true },
enabled: { client: true, server: false },
});

// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config });

expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0);
});

it("doesn't add the module versions plugin in dev mode", async () => {
const integration = sentryAstro({ sourcemaps: { disable: true } });

// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({
...baseConfigHookObject,
updateConfig,
injectScript,
config,
command: 'dev',
});

expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0);
});

Expand Down
9 changes: 9 additions & 0 deletions packages/bundler-plugins/src/bun/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createDebugIdUploadFunction,
CodeInjection,
getSourceMapFeatures,
getServerModulesDefinition,
} from '../core';
import * as fs from 'node:fs';

Expand All @@ -20,6 +21,7 @@ interface BunBuildConfig {
sourcemap?: 'none' | 'linked' | 'inline' | 'external' | boolean;
outdir?: string;
define?: Record<string, string>;
target?: 'browser' | 'bun' | 'node';
}

interface BunPluginBuilder {
Expand Down Expand Up @@ -150,6 +152,13 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
config.define = { ...config.define, ...replacementStringValues };
}

const serverModules = sentryBuildPluginManager.getModuleVersions({
isServerBuild: config.target === 'bun' || config.target === 'node',
});
if (serverModules) {
config.define = { ...config.define, ...getServerModulesDefinition(serverModules) };
}

const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });

Expand Down
34 changes: 34 additions & 0 deletions packages/bundler-plugins/src/core/build-plugin-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { createLogger } from './logger';
import { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry';
import type { InternalOptions, SentrySDKBuildFlags } from './types';
import { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils';
import { getInstalledModules } from './installed-modules';
import {
defaultRewriteSourcesHook,
prepareArtifactForUpload,
Expand Down Expand Up @@ -97,6 +98,12 @@ export type SentryBuildPluginManager = {
// See `generateModuleMetadataInjectorCode` for how this should be used exactly
bundleMetadata: Record<string, unknown>;

/**
* Returns the app's module versions to replace `__SENTRY_SERVER_MODULES__` with in a build, or `undefined` when the
* build gets none (see the `injectModuleVersions` option). The versions are read once per root.
*/
getModuleVersions(build: { root?: string; isServerBuild: boolean }): Record<string, string> | undefined;

/**
* Contains utility functions for emitting telemetry via the build plugin manager.
*/
Expand Down Expand Up @@ -239,6 +246,7 @@ export function createSentryBuildPluginManager(
},
},
bundleMetadata: {},
getModuleVersions: () => undefined,
createRelease: async () => {
/* noop */
},
Expand Down Expand Up @@ -474,6 +482,25 @@ export function createSentryBuildPluginManager(
}
}

const moduleVersionsByRoot = new Map<string, Record<string, string> | undefined>();
function getModuleVersions({
root = process.cwd(),
isServerBuild,
}: {
root?: string;
isServerBuild: boolean;
}): Record<string, string> | undefined {
if (!(options.injectModuleVersions ?? isServerBuild)) {
return undefined;
}

if (!moduleVersionsByRoot.has(root)) {
const modules = getInstalledModules(root);
moduleVersionsByRoot.set(root, Object.keys(modules).length > 0 ? modules : undefined);
}
return moduleVersionsByRoot.get(root);
}

return {
/**
* A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)
Expand All @@ -497,6 +524,8 @@ export function createSentryBuildPluginManager(
// See `generateModuleMetadataInjectorCode` for how this should be used exactly
bundleMetadata,

getModuleVersions,

/**
* Contains utility functions for emitting telemetry via the build plugin manager.
*/
Expand Down Expand Up @@ -527,6 +556,11 @@ export function createSentryBuildPluginManager(
* - adds deploy information
*/
async createRelease() {
const { create, finalize, setCommits, deploy, uploadLegacySourcemaps } = options.release;
if (!create && !finalize && setCommits === false && !deploy && !uploadLegacySourcemaps) {
return;
}

if (!options.release.name) {
logger.debug(
'No release name provided. Will not create release. Please set the `release.name` option to identify your release.',
Expand Down
5 changes: 5 additions & 0 deletions packages/bundler-plugins/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,17 @@ export type { InternalOptions, Options, SentrySDKBuildFlags } from './types';
export {
CodeInjection,
replaceBooleanFlagsInCode,
replaceInCode,
stringToUUID,
generateReleaseInjectorCode,
generateModuleMetadataInjectorCode,
resolveReleaseName,
getServerModulesDefinition,
getServerModulesReplacement,
SERVER_MODULES_PLACEHOLDER,
} from './utils';
export { createSentryBuildPluginManager } from './build-plugin-manager';
export { getDisabledSourcemapsOptions } from './installed-modules';
export type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager';
export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';
export {
Expand Down
28 changes: 28 additions & 0 deletions packages/bundler-plugins/src/core/installed-modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as fs from 'fs';
import { collectInstalledModules } from '@sentry/core/server';
import type { Options } from './types';

/**
* The dependencies of the app at `root`, with the exact version installed in `node_modules` where it resolves and
* the declared range otherwise.
*/
export function getInstalledModules(root: string): Record<string, string> {
return collectInstalledModules({
readFile: filePath => (fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : undefined),
cwd: root,
});
}

/**
* Plugin options for frameworks that add the plugin although the user turned source maps off. For now they turn off
* everything except injecting module versions: no source map upload, deletion or debug IDs, no release creation or
* injection, and no telemetry.
*/
export function getDisabledSourcemapsOptions(options: Pick<Options, 'debug' | 'injectModuleVersions'> = {}): Options {
return {
...options,
telemetry: false,
sourcemaps: { upload: false, injectDebugIds: false },
release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false },
};
}
2 changes: 2 additions & 0 deletions packages/bundler-plugins/src/core/options-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export type NormalizedOptions = {
};
applicationKey: string | undefined;
moduleMetadata: ModuleMetadata | ModuleMetadataCallback | undefined;
injectModuleVersions: boolean | undefined;
_experiments: {
injectBuildInformation?: boolean;
} & Record<string, unknown>;
Expand Down Expand Up @@ -138,6 +139,7 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption
},
applicationKey: userOptions.applicationKey,
moduleMetadata: userOptions.moduleMetadata,
injectModuleVersions: userOptions.injectModuleVersions,
_experiments: userOptions._experiments ?? {},
};

Expand Down
9 changes: 9 additions & 0 deletions packages/bundler-plugins/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,15 @@ export interface Options {
*/
applicationKey?: string;

/**
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
* Injects the installed versions of the app's dependencies for the Node SDK's `modulesIntegration`, which
* otherwise reads them from `node_modules` at runtime. Only takes effect when the SDK is bundled.
*
* Defaults to server builds only (Vite SSR, webpack `node` targets, esbuild `platform: 'node'`, Bun); plain Rollup
* needs `true`, and `false` disables it. Avoid `true` for browser builds, as it ships the list to users.
*/
injectModuleVersions?: boolean;

/**
* Options that are considered experimental and subject to change.
*
Expand Down
43 changes: 36 additions & 7 deletions packages/bundler-plugins/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,19 +369,41 @@ export function stripQueryAndHashFromPath(path: string): string {
return path.split('?')[0]!.split('#')[0]!;
}

export function replaceBooleanFlagsInCode(
code: string,
replacementValues: Record<string, boolean | undefined>,
): { code: string; map: SourceMap } | null {
const ms = new MagicString(code);
/** The placeholder that the Node SDK's `modulesIntegration` reads the module versions from. */
export const SERVER_MODULES_PLACEHOLDER = '__SENTRY_SERVER_MODULES__';

/** The `define` entry that replaces the module versions placeholder, for bundlers with `define` support. */
export function getServerModulesDefinition(serverModules: Record<string, string>): Record<string, string> {
return { [SERVER_MODULES_PLACEHOLDER]: stringifyForCodeInjection(serverModules) };
}

/** The replacement for the module versions placeholder in plain code, where the object needs parentheses. */
export function getServerModulesReplacement(serverModules: Record<string, string>): Record<string, string> {
return { [SERVER_MODULES_PLACEHOLDER]: `(${stringifyForCodeInjection(serverModules)})` };
}

/** The boolean flags as code, such as `'false'`. Flags without a value are left out. */
function getBooleanFlagReplacements(replacementValues: Record<string, boolean | undefined>): Record<string, string> {
const replacements: Record<string, string> = {};
Object.keys(replacementValues).forEach(key => {
const value = replacementValues[key];

if (typeof value === 'boolean') {
ms.replaceAll(key, JSON.stringify(value));
replacements[key] = JSON.stringify(value);
}
});
return replacements;
}

/** Replaces every occurrence of each key of `replacements` in `code` with its value. */
export function replaceInCode(
code: string,
replacements: Record<string, string>,
): { code: string; map: SourceMap } | null {
const ms = new MagicString(code);

Object.keys(replacements).forEach(key => {
ms.replaceAll(key, replacements[key] as string);
});

if (ms.hasChanged()) {
return {
Expand All @@ -393,6 +415,13 @@ export function replaceBooleanFlagsInCode(
return null;
}

export function replaceBooleanFlagsInCode(
code: string,
replacementValues: Record<string, boolean | undefined>,
): { code: string; map: SourceMap } | null {
return replaceInCode(code, getBooleanFlagReplacements(replacementValues));
}

// https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
export function getTurborepoEnvPassthroughWarning(envVarName: string): string {
return process.env['TURBO_HASH']
Expand Down
10 changes: 10 additions & 0 deletions packages/bundler-plugins/src/esbuild/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
addDebugIdToEmittedArtifacts,
isJsFile,
getSourceMapFeatures,
getServerModulesDefinition,
} from '../core';
import * as path from 'node:path';
import { createRequire } from 'node:module';
Expand Down Expand Up @@ -62,6 +63,7 @@ interface EsbuildInitialOptions {
absWorkingDir?: string;
logOverride?: Record<string, string>;
sourcemap?: EsbuildSourceMapSetting;
platform?: string;
}

/** Maps esbuild's `sourcemap` setting onto the plugin's source map kinds. */
Expand Down Expand Up @@ -223,6 +225,14 @@ export function sentryEsbuildPlugin(userOptions: InternalOptions = {}): any {
initialOptions.define = { ...initialOptions.define, ...replacementStringValues };
}

const serverModules = sentryBuildPluginManager.getModuleVersions({
root: initialOptions.absWorkingDir,
isServerBuild: initialOptions.platform === 'node',
});
if (serverModules) {
initialOptions.define = { ...initialOptions.define, ...getServerModulesDefinition(serverModules) };
}

// Debug ID injection - requires per-entry-point unique IDs
if (injectDebugIds) {
// `setup` runs once per context, `onStart` once per build, so a
Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/src/loader-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
// don't pull in the build plugin manager and the `sentry` CLI.
export { getCodeInjectionPosition } from '../core/get-code-injection-position';
export { createComponentNameAnnotateHooks } from '../core/component-annotate-hooks';
export { getInstalledModules } from '../core/installed-modules';
Loading
Loading