All files / core/blong-browser/src sourceMapRegister.ts

12.5% Statements 2/16
0% Branches 0/14
33.33% Functions 1/3
15.38% Lines 2/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                2x     1x                                                                          
/**
 * Register a test module's source map for browser stack-trace resolution @@D-583.
 *
 * Only modules under a `test/` folder are registered, and only in dev (`apply: 'serve'`).
 */
import {type Plugin} from 'vite';
 
/** Global read by `core/blong-chain/sourceMap.ts`; keep the two names in step. */
const REGISTRY = '__BLONG_SOURCE_MAPS__';
 
export function sourceMapRegister(): Plugin {
    return {
        name: 'blong-source-map-register',
        apply: 'serve',
        enforce: 'post',
        transform(code, id) {
            const file = id.split('?')[0] ?? id;
            if (file.includes('node_modules') || !/[\\/]test[\\/]/.test(file)) return null;
            if (!/\.[cm]?[jt]sx?$/.test(file) || /\.d\.[cm]?ts$/.test(file)) return null;
 
            const map = (() => {
                try {
                    return this.getCombinedSourcemap();
                } catch {
                    return undefined;
                }
            })();
            if (!map?.mappings) return null;
 
            // Source content would be copied into the page for no benefit: the pointer only needs
            // the mappings table.
            const compact = {
                version: map.version ?? 3,
                sources: map.sources,
                names: map.names,
                mappings: map.mappings,
            };
            // Appended after the module body, so the generated positions the map describes, and
            // therefore the stack line numbers, stay unchanged.
            const register = [
                '',
                `;(globalThis.${REGISTRY} ??= Object.create(null))[import.meta.url] = ${JSON.stringify(compact)};`,
                '',
            ].join('\n');
            return {code: `${code}${register}`, map};
        },
    };
}