Repository navigation
feat(bun): Inject debug IDs and upload source maps in sentryBunPlugin
#25670
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
Merged
isaacs
merged 4 commits into
develop
from
isaacschlueter/js-3983-sentrybunplugin-should-inject-debug-ids-and-upload-source
Oct 23, 2026
+523
−3
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
| 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); | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.