oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
71.84k stars 2.56k forks source link

Custom Loader Plugin sourceMaps not working #6173

Open M-jerez opened 9 months ago

M-jerez commented 9 months ago

What version of Bun is running?

1.0.1

What platform is your computer?

Darwin 21.6.0 x86_64 i386

What steps can reproduce the bug?

I'm writing a plugin that uses a custom typescript transformer and outputs js with some extra types metadata. this is a similar scenario to an svelte plugin.

The problem is the sourceMaps are broken, esBuild support adding the source map as inlined sourcemaps, example here. But bun is not reading these source maps.

here is an example of the loader

export function runTypesLoader(options: LoaderOptions = {}): BunPlugin {
    return {
        name: 'bun-plugin-run-types',
        setup(builder) {
            builder.config = {
                ...builder.config,
                sourcemap: 'inline',
            };
            builder.onLoad({filter: /\.(ts|tsx)$/}, (args) => {
                const code = readFileSync(args.path, 'utf8');
                const contents = transform(code, args.path, options).code;
                return {
                    contents,
                    loader: 'js',
                };
            });
        },
    };
}

here is an example of an small size original TS file:

import {typeOf, TypeClass} from '@deepkit/type';
import {RpcError} from '@mionkit/core';

export const RPC_ERROR_TYPE = typeOf<RpcError>() as TypeClass;
export const ERROR_TYPE = typeOf<Error>() as TypeClass;

and here is an example of the transformed JS code returned by builder.onLoad (see the inline sourceMap)

import { typeOf } from '@deepkit/type';
import { RpcError } from '@mionkit/core';
export const RPC_ERROR_TYPE = typeOf([], [() => RpcError, 'P7!']);
export const ERROR_TYPE = typeOf([], ['!']);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9u.... // rest of inlined url encoded sourceMap

So when there are any errors bun is ignoring the inlined sourceMap and referencing the transformed code instead the original file.

What is the expected behavior?

bun to use the inlined sourceMap and prints valid errors that reference the original file instead the transformed code.

What do you see instead?

No response

Additional information

plugin loader and unit tests here: https://github.com/MionKit/mion/tree/ad-support-for-bun.sh/packages/bun/loader

niieani commented 7 months ago

It would also be useful to be able to pass the sourcemap directly, alongside contents, not just inlined. Note that this should also work for loaders stacktraces, not just the bundler.