Skip to content
Draft
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
58 changes: 58 additions & 0 deletions packages/bun/test/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,64 @@ describe('sentryBunPlugin', () => {
},
);

async function buildWithSourceMaps(
sourcemap: 'linked' | 'external' | undefined,
deleteSourceMaps: boolean | undefined,
): Promise<{ maps: string[]; bundleSources: string[] }> {
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: { delete: deleteSourceMaps } })],
});

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

const files = fs.readdirSync(outdir);
return {
maps: files.filter(file => file.endsWith('.map')),
bundleSources: files
.filter(file => file.endsWith('.js'))
.map(file => fs.readFileSync(path.join(outdir, file), 'utf8')),
};
}

test.each(['linked', 'external'] as const)(
'deletes the source maps and their URL comments with `sourcemaps.delete: true` (sourcemap: %s)',
async sourcemap => {
const { maps, bundleSources } = await buildWithSourceMaps(sourcemap, true);

expect(bundleSources.length).toBeGreaterThan(1);
expect(maps).toEqual([]);
for (const source of bundleSources) {
expect(source).not.toContain('sourceMappingURL');
}
},
);

test.each([false, undefined])('keeps linked source maps with `sourcemaps.delete: %s`', async deleteSourceMaps => {
const { maps, bundleSources } = await buildWithSourceMaps('linked', deleteSourceMaps);

expect(bundleSources.length).toBeGreaterThan(1);
expect(maps.length).toBe(bundleSources.length);
for (const source of bundleSources) {
expect(source).toMatch(/^\/\/# sourceMappingURL=.+\.js\.map$/m);
}
});

test('turns on hidden source maps and keeps them with `sourcemaps.delete: false`', async () => {
const { maps, bundleSources } = await buildWithSourceMaps(undefined, false);

expect(maps.length).toBe(bundleSources.length);
for (const source of bundleSources) {
expect(source).not.toContain('sourceMappingURL');
expect(source).toMatch(DEBUG_ID_MARKER);
}
});

test('builds when Bun keeps the output in memory', async () => {
const result = await Bun.build({
entrypoints: [path.join(tmpDir, 'src', 'index.ts')],
Expand Down
73 changes: 65 additions & 8 deletions packages/bundler-plugins/src/bun/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Options } from '../core';
import type { Options, SourceMapDecision, SourceMapKind } from '../core';
import {
createSentryBuildPluginManager,
generateReleaseInjectorCode,
Expand All @@ -7,6 +7,7 @@ import {
createDebugIdUploadFunction,
CodeInjection,
getSourceMapFeatures,
isJsFile,
} from '../core';
import * as fs from 'node:fs';

Expand All @@ -15,9 +16,11 @@ interface BunBuildArtifact {
kind: string;
}

type BunSourceMapSetting = 'none' | 'linked' | 'inline' | 'external' | boolean;

interface BunBuildConfig {
banner?: string;
sourcemap?: 'none' | 'linked' | 'inline' | 'external' | boolean;
sourcemap?: BunSourceMapSetting;
outdir?: string;
define?: Record<string, string>;
}
Expand All @@ -43,6 +46,22 @@ const DEBUG_ID_PLACEHOLDER = 'sentry-bun-debug-id-placeholder-0000';
// 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 sourceMapKindFromBunSetting(setting: BunSourceMapSetting | undefined): SourceMapKind {
switch (setting) {
case undefined:
return 'unset';
case false:
case 'none':
return 'off';
case 'external':
return 'hidden';
case 'inline':
return 'inline';
default:
return 'visible';
}
}

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)}`;
Expand All @@ -68,9 +87,6 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
}

const sourceMapFeatures = getSourceMapFeatures(options);
if (options.sourcemaps?.delete !== undefined) {
logger.warn('The Sentry Bun plugin does not support `sourcemaps.delete`. It removes no source maps.');
}

const staticInjectionCode = new CodeInjection();

Expand Down Expand Up @@ -126,8 +142,15 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
return;
}

// Without `outdir`, Bun writes no files that the placeholder can be
// replaced in.
// Without `outdir`, Bun keeps the output in memory, so there are no
// files to stamp, upload or delete.
const sourceMapDecision: SourceMapDecision = config.outdir
? sentryBuildPluginManager.sourceMaps.decide(sourceMapKindFromBunSetting(config.sourcemap))
: { enableHidden: false, deleteAfterUpload: false };
if (sourceMapDecision.enableHidden) {
config.sourcemap = 'external';
}

const injectDebugIds =
sourceMapFeatures.injectDebugIds && !!config.outdir && !!config.sourcemap && config.sourcemap !== 'none';

Expand All @@ -154,9 +177,13 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });

build.onEnd(async result => {
const { sourceMaps } = sentryBuildPluginManager;
const allMaps = result.outputs.filter(output => output.kind === 'sourcemap').map(output => output.path);

try {
await sentryBuildPluginManager.createRelease();

const deleteWithoutUpload = sourceMapDecision.deleteAfterUpload && !sourceMaps.uploadPossible;
if (injectDebugIds) {
const bundlePaths = result.outputs
.filter(output => output.kind === 'entry-point' || output.kind === 'chunk')
Expand All @@ -165,9 +192,39 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
await Promise.all(bundlePaths.map(replaceDebugIdPlaceholder));

if (sourceMapFeatures.upload) {
await upload(bundlePaths);
const { uploaded, uploadedSourceMapPaths } = await upload(bundlePaths);

// Bun writes before `onEnd` runs, so the maps are deleted from
// disk. A map the plugin turned on never stays in the output. A
// map the user turned on is only deleted once it was uploaded,
// unless `sourcemaps.delete` asks for it.
if (sourceMapDecision.deleteAfterUpload && !deleteWithoutUpload) {
const mapsToDelete = sourceMapDecision.removeAllSourceMaps ? allMaps : uploadedSourceMapPaths;

if (uploaded || options.sourcemaps?.delete === true) {
await sourceMaps.deleteFromOutput(mapsToDelete);
} else if (mapsToDelete.length > 0) {
logger.error('The source maps were not uploaded, so they stay in the build output.');
}
}
}
}

if (deleteWithoutUpload) {
const bundleOf = (map: string): string => map.slice(0, -'.map'.length);
const isUploaded = (map: string): boolean =>
isJsFile(bundleOf(map)) && sourceMaps.shouldUpload(bundleOf(map));
await sourceMaps.deleteFromOutput(
sourceMapDecision.removeAllSourceMaps ? allMaps : allMaps.filter(isUploaded),
);
}
} catch (error) {
// Bun already wrote the maps, and `sourcemaps.delete: true` also
// applies when the release or upload step fails.
if (options.sourcemaps?.delete === true && sourceMapDecision.deleteAfterUpload) {
await sourceMaps.deleteFromOutput(allMaps);
}
throw error;
} finally {
freeGlobalDependencyOnBuildArtifacts();
await sentryBuildPluginManager.deleteArtifacts();
Expand Down
134 changes: 129 additions & 5 deletions packages/bundler-plugins/test/bun/bun.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ import type * as DebugIdUpload from '../../src/core/debug-id-upload';

const { uploadSpy } = vi.hoisted(() => ({ uploadSpy: vi.fn() }));

vi.mock('sentry', () => ({
createSentrySDK: () => ({
release: { create: vi.fn(), finalize: vi.fn(), 'set-commits': vi.fn(), deploy: vi.fn() },
sourcemap: { upload: vi.fn(), inject: vi.fn() },
run: vi.fn(),
}),
}));

vi.mock('../../src/core/debug-id-upload', async importOriginal => ({
...(await importOriginal<typeof DebugIdUpload>()),
createDebugIdUploadFunction: () => uploadSpy,
Expand Down Expand Up @@ -46,6 +54,7 @@ describe('sentryBunPlugin', () => {

beforeEach(() => {
uploadSpy.mockReset();
uploadSpy.mockResolvedValue({ uploaded: true, uploadedSourceMapPaths: [] });
outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-bun-plugin-'));
});

Expand Down Expand Up @@ -222,13 +231,128 @@ describe('sentryBunPlugin', () => {
expect(uploadSpy).not.toHaveBeenCalled();
});

it('warns that `sourcemaps.delete` is not supported', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
describe('source map deletion', () => {
const uploadOptions = {
telemetry: false,
authToken: 't',
org: 'o',
project: 'p',
release: { name: 'test-release', create: false, finalize: false },
};

function writeBuild(banner: string): { entry: string; outputs: Output[] } {
const entry = writeBundle('index.js', banner);
return {
entry,
outputs: [
{ path: entry, kind: 'entry-point' },
{ path: `${entry}.map`, kind: 'sourcemap' },
],
};
}

it('turns on hidden source maps and deletes them after the upload when `sourcemap` is unset', async () => {
const config: Config = { outdir: outDir };
const { end } = setupPlugin(sentryBunPlugin(uploadOptions) as BunPlugin, config);

expect(config.sourcemap).toBe('external');

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(uploadSpy).toHaveBeenCalledWith([entry]);
expect(fs.existsSync(`${entry}.map`)).toBe(false);
});

it('keeps the hidden source maps it turns on with `sourcemaps.delete: false`', async () => {
const config: Config = { outdir: outDir };
const { end } = setupPlugin(
sentryBunPlugin({ ...uploadOptions, sourcemaps: { delete: false } }) as BunPlugin,
config,
);

expect(config.sourcemap).toBe('external');

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(fs.existsSync(`${entry}.map`)).toBe(true);
});

it('switches linked source maps to hidden ones and deletes them with `sourcemaps.delete: true`', async () => {
const config: Config = { sourcemap: 'linked', outdir: outDir };
const { end } = setupPlugin(
sentryBunPlugin({ ...uploadOptions, sourcemaps: { delete: true } }) as BunPlugin,
config,
);

expect(config.sourcemap).toBe('external');

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(fs.existsSync(`${entry}.map`)).toBe(false);
});

it('deletes the source maps with `sourcemaps.delete: true` when no upload can run', async () => {
const config: Config = { sourcemap: 'external', outdir: outDir };
const { end } = setupPlugin(
sentryBunPlugin({ telemetry: false, sourcemaps: { delete: true } }) as BunPlugin,
config,
);

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(fs.existsSync(`${entry}.map`)).toBe(false);
});

it('deletes the source maps with `sourcemaps.delete: true` when the upload fails', async () => {
uploadSpy.mockRejectedValue(new Error('upload failed'));
const config: Config = { sourcemap: 'external', outdir: outDir };
const { end } = setupPlugin(
sentryBunPlugin({ ...uploadOptions, sourcemaps: { delete: true } }) as BunPlugin,
config,
);

const { entry, outputs } = writeBuild(config.banner!);
await expect(end(outputs)).rejects.toThrow('upload failed');

expect(fs.existsSync(`${entry}.map`)).toBe(false);
});

it('keeps source maps the user turned on when `sourcemaps.delete` is unset', async () => {
const config: Config = { sourcemap: 'linked', outdir: outDir };
const { end } = setupPlugin(sentryBunPlugin(uploadOptions) as BunPlugin, config);

expect(config.sourcemap).toBe('linked');

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(fs.existsSync(`${entry}.map`)).toBe(true);
});

it('keeps the source maps the plugin turned on when the upload does not run', async () => {
uploadSpy.mockResolvedValue({ uploaded: false, uploadedSourceMapPaths: [] });
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const config: Config = { outdir: outDir };
const { end } = setupPlugin(sentryBunPlugin(uploadOptions) as BunPlugin, config);

const { entry, outputs } = writeBuild(config.banner!);
await end(outputs);

expect(fs.existsSync(`${entry}.map`)).toBe(true);
expect(error).toHaveBeenCalledWith(expect.stringContaining('stay in the build output'));
error.mockRestore();
});

sentryBunPlugin({ telemetry: false, sourcemaps: { delete: true } });
it('does not change the source map setting when Bun keeps the output in memory', () => {
const config: Config = {};
setupPlugin(sentryBunPlugin({ ...uploadOptions, sourcemaps: { delete: true } }) as BunPlugin, config);

expect(warn).toHaveBeenCalledWith(expect.stringContaining('does not support `sourcemaps.delete`'));
warn.mockRestore();
expect(config.sourcemap).toBeUndefined();
});
});

it('does not inject or upload with `sourcemaps.disable: true`', async () => {
Expand Down
Loading