Skip to content
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@ Work in this release was contributed by @4ktLuffy, @adityareddy-dev, @dasilvalui

`httpIntegration` and `httpServerSpansIntegration` now accept `onSpanEnd`, a hook that runs when the response for an incoming request finishes, before its span ends. Use it to change the span based on the response. Deno and Bun already have this option.

- **feat(bun): Inject debug IDs and upload source maps in `sentryBunPlugin` ([#25670](https://github.com/getsentry/sentry-javascript/pull/25670))**

`sentryBunPlugin` from `@sentry/bun/plugin` now accepts the same options as `sentryEsbuildPlugin` (`org`, `project`, `authToken`, `release`, `sourcemaps`, ...). When `Bun.build` writes source maps to `outdir`, the plugin injects the debug ID that Bun writes into each bundle, injects the release, and uploads the source maps at the end of the build. You no longer need to run `sentry sourcemap inject` and `sentry sourcemap upload` after the build.

Like the other bundler plugins, `sentryBunPlugin` now sends build telemetry and injects the release it detects (for example, from git). To turn off telemetry, set `telemetry: false`.

## 11.8.0

### Important Changes
Expand Down
1 change: 1 addition & 0 deletions packages/bun/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"access": "public"
},
"dependencies": {
"@sentry/bundler-plugins": "11.9.0",
"@sentry/core": "11.9.0",
"@sentry/conventions": "^0.29.0",
"@sentry/node": "11.9.0",
Expand Down
46 changes: 43 additions & 3 deletions packages/bun/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,58 @@
/**
* Sentry code-transform plugin for Bun's bundler (`bun build`).
* Sentry plugin for Bun's bundler (`bun build`).
*
* Usage:
*
* ```ts
* import { sentryBunPlugin } from '@sentry/bun/plugin';
* await Bun.build({
* entrypoints: ['./app.ts'],
* plugins: [sentryBunPlugin()],
* outdir: './dist',
* sourcemap: 'external',
* plugins: [sentryBunPlugin({ org: '…', project: '…', authToken: process.env.SENTRY_AUTH_TOKEN })],
* });
* ```
*
* This is BUILD-ONLY. Runtime instrumentation (`bun run`) is currently not supported.
*
* @module
*/
export { sentryOrchestrionPlugin as sentryBunPlugin } from '@sentry/server-utils/orchestrion/bun';
import { sentryBunPlugin as sentryBunBundlerPlugin } from '@sentry/bundler-plugins/bun';
import type { SentryBunPluginOptions as SentryBunPluginOptionsBase } from '@sentry/bundler-plugins/bun';
import type { InstrumentationConfig } from '@sentry/server-utils';
import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/bun';

export type SentryBunPluginOptions = SentryBunPluginOptionsBase & {
/**
* @ignore This is for internal use only when this plugin is consumed by a framework SDK
*/
instrumentations?: InstrumentationConfig[];

/**
* Automatic instrumentation of server-side dependencies at build time.
*
* Set to `false` to turn it off.
*
* @default true
*/
buildTimeInstrumentation?: boolean;
};

/**
* Bun plugin that combines the Sentry bundler plugin (source maps, release
* injection, …) with the code transformer (build-time `diagnostics_channel`
* instrumentation for server libraries).
*/
// oxlint-disable-next-line typescript/no-explicit-any
export function sentryBunPlugin(options?: SentryBunPluginOptions): any {
Comment thread
cursor[bot] marked this conversation as resolved.
const bundlerPlugin = sentryBunBundlerPlugin(options);
const orchestrionPlugin: { setup: (build: unknown) => void } = sentryOrchestrionPlugin(options);

return {
name: 'sentry-bun',
setup(build: Parameters<typeof bundlerPlugin.setup>[0]): void {
bundlerPlugin.setup(build);
orchestrionPlugin.setup(build);
},
};
}
86 changes: 86 additions & 0 deletions packages/bun/test/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { sentryBunPlugin } from '../src/plugin';

const DEBUG_ID_MARKER = /sentry-dbid-([0-9a-f-]{36})/;
const BUN_DEBUG_ID = /\/\/# debugId=([0-9A-F]{32})/;

function readSourceMap(bundlePath: string, source: string): { debugId?: unknown } {
const inlineMap = source.match(/^\/\/# sourceMappingURL=data:application\/json;base64,(.*)$/m)?.[1];
return JSON.parse(
inlineMap ? Buffer.from(inlineMap, 'base64').toString() : fs.readFileSync(`${bundlePath}.map`, 'utf8'),
);
}

function toUuid(bunDebugId: string): string {
const hex = bunDebugId.toLowerCase();
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

describe('sentryBunPlugin', () => {
let tmpDir: string;

beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-bun-plugin-'));
fs.mkdirSync(path.join(tmpDir, 'src'));
fs.writeFileSync(
path.join(tmpDir, 'src', 'index.ts'),
'const { value } = await import("./lazy");\nconsole.log(JSON.stringify({ value, ids: globalThis._sentryDebugIds }));\n',
);
fs.writeFileSync(path.join(tmpDir, 'src', 'lazy.ts'), 'export const value = 42;\n');
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

test.each(['external', 'linked', 'inline'] as const)(
'registers the debug ID that Bun wrote into each bundle and its source map (sourcemap: %s)',
async sourcemap => {
const outdir = path.join(tmpDir, 'dist');
const result = await Bun.build({
entrypoints: [path.join(tmpDir, 'src', 'index.ts')],
outdir,
target: 'bun',
sourcemap,
splitting: true,
plugins: [sentryBunPlugin({ telemetry: false, sourcemaps: { disable: 'disable-upload' } })],
});

expect(result.success).toBe(true);

const bundles = result.outputs.filter(o => o.kind === 'entry-point' || o.kind === 'chunk');
expect(bundles.some(bundle => bundle.kind === 'chunk')).toBe(true);

const debugIds = bundles.map(bundle => {
const source = fs.readFileSync(bundle.path, 'utf8');
const map = readSourceMap(bundle.path, source);
const bunDebugId = source.match(BUN_DEBUG_ID)?.[1];

expect(bunDebugId).toBeDefined();
expect(map.debugId).toBe(bunDebugId);
expect(source.match(DEBUG_ID_MARKER)?.[1]).toBe(toUuid(bunDebugId!));
return toUuid(bunDebugId!);
});

const run = Bun.spawnSync([process.execPath, path.join(outdir, 'index.js')]);
const { value, ids } = JSON.parse(run.stdout.toString());

expect(value).toBe(42);
expect(Object.values(ids).sort()).toEqual(debugIds.sort());
},
);

test('builds when Bun keeps the output in memory', async () => {
const result = await Bun.build({
entrypoints: [path.join(tmpDir, 'src', 'index.ts')],
target: 'bun',
sourcemap: 'external',
plugins: [sentryBunPlugin({ telemetry: false, sourcemaps: { disable: 'disable-upload' } })],
});

expect(result.success).toBe(true);
});
});
5 changes: 5 additions & 0 deletions packages/bundler-plugins/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@
"import": "./build/esm/esbuild/index.js",
"require": "./build/cjs/esbuild/index.js"
},
"./bun": {
"types": "./build/types/bun/index.d.ts",
"import": "./build/esm/bun/index.js",
"require": "./build/cjs/bun/index.js"
},
"./core": {
"types": "./build/types/core/index.d.ts",
"import": "./build/esm/core/index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default makeNPMConfigVariants(
'src/rollup/index.ts',
'src/vite/index.ts',
'src/esbuild/index.ts',
'src/bun/index.ts',
'src/webpack/index.ts',
'src/webpack/component-annotation-transform.ts',
'src/babel-plugin/index.ts',
Expand Down
169 changes: 169 additions & 0 deletions packages/bundler-plugins/src/bun/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import type { Options } from '../core';
import {
createSentryBuildPluginManager,
generateReleaseInjectorCode,
generateModuleMetadataInjectorCode,
getDebugIdSnippet,
createDebugIdUploadFunction,
CodeInjection,
} from '../core';
import * as fs from 'node:fs';

interface BunBuildArtifact {
path: string;
kind: string;
}

interface BunBuildConfig {
banner?: string;
sourcemap?: 'none' | 'linked' | 'inline' | 'external' | boolean;
outdir?: string;
define?: Record<string, string>;
}

interface BunPluginBuilder {
// Bun passes no `config` when the plugin runs as a runtime plugin (`Bun.plugin()`)
config?: BunBuildConfig;
onEnd: (callback: (result: { outputs: BunBuildArtifact[] }) => void | Promise<void>) => void;
}

interface BunPlugin {
name: string;
setup: (build: BunPluginBuilder) => void;
}

const pluginName = 'sentry-bun-plugin';

// Bun computes the debug ID of an output after it adds the banner, so the
// banner holds this placeholder. It has the length of a debug ID, so the
// swap does not move any code that the source map points to.
const DEBUG_ID_PLACEHOLDER = 'sentry-bun-debug-id-placeholder-0000';
// Bun writes `//# sourceMappingURL=` after this comment for linked and
// inline source maps, so match the last debug ID line, not the file end.
const BUN_DEBUG_ID_REGEX = /^\/\/# debugId=([0-9a-fA-F]{32})$(?![\s\S]*^\/\/# debugId=)/m;

function bunDebugIdToUuid(bunDebugId: string): string {
const hex = bunDebugId.toLowerCase();
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {
loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,
buildTool: 'bun',
buildToolMajorVersion: process.versions['bun']?.split('.')[0],
});

const {
logger,
normalizedOptions: options,
bundleSizeOptimizationReplacementValues: replacementValues,
bundleMetadata,
createDependencyOnBuildArtifacts,
} = sentryBuildPluginManager;

if (options.disable) {
return { name: 'sentry-bun-noop-plugin', setup: () => undefined };
}

const staticInjectionCode = new CodeInjection();

if (!options.release.inject) {
logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');
} else if (!options.release.name) {
logger.debug(
'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',
);
} else {
staticInjectionCode.append(
generateReleaseInjectorCode({
release: options.release.name,
injectBuildInformation: options._experiments.injectBuildInformation || false,
}),
);
}

if (Object.keys(bundleMetadata).length > 0) {
staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));
}

void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {
// Telemetry failures are acceptable
});

async function replaceDebugIdPlaceholder(bundlePath: string): Promise<void> {
const source = await fs.promises.readFile(bundlePath, 'utf8');
const bunDebugId = source.match(BUN_DEBUG_ID_REGEX)?.[1];
if (!bunDebugId) {
logger.debug(`Bun wrote no debug ID into the bundle. File will not be source mapped: ${bundlePath}`);
return;
}

await fs.promises.writeFile(
bundlePath,
source.split(DEBUG_ID_PLACEHOLDER).join(bunDebugIdToUuid(bunDebugId)),
'utf8',
);
}

return {
name: pluginName,
setup(build: BunPluginBuilder): void {
const config = build.config;
if (!config) {
return;
}

// Without `outdir`, Bun writes no files that the placeholder can be
// replaced in.
const injectDebugIds =
options.sourcemaps?.disable !== true && !!config.outdir && !!config.sourcemap && config.sourcemap !== 'none';

const injectionCode = new CodeInjection();
injectionCode.append(staticInjectionCode);
if (injectDebugIds) {
injectionCode.append(getDebugIdSnippet(DEBUG_ID_PLACEHOLDER));
}

if (!injectionCode.isEmpty()) {
config.banner = config.banner ? `${config.banner}\n${injectionCode.code()}` : injectionCode.code();
}

if (Object.keys(replacementValues).length > 0) {
const replacementStringValues: Record<string, string> = {};
Object.entries(replacementValues).forEach(([key, value]) => {
replacementStringValues[key] = JSON.stringify(value);
});

config.define = { ...config.define, ...replacementStringValues };
}

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

build.onEnd(async result => {
try {
await sentryBuildPluginManager.createRelease();

if (injectDebugIds) {
const bundlePaths = result.outputs
.filter(output => output.kind === 'entry-point' || output.kind === 'chunk')
.map(output => output.path);

await Promise.all(bundlePaths.map(replaceDebugIdPlaceholder));

if (options.sourcemaps?.disable !== 'disable-upload') {
await upload(bundlePaths);
}
}
} finally {
freeGlobalDependencyOnBuildArtifacts();
await sentryBuildPluginManager.deleteArtifacts();
}
});
},
};
}

export default sentryBunPlugin;
export type { Options as SentryBunPluginOptions } from '../core';
Loading
Loading