
// Transforms GenerateMeshBVHWorker.js to replace the bare package specifier
// in `new URL('three-mesh-bvh/...', import.meta.url)` with a resolved relative path.
// Webpack 5 supports the `new Worker(new URL('./relative.js', import.meta.url))` pattern
// natively and will bundle the worker with all its dependencies as a separate chunk.
// We also prepend a `self.window = self` shim to handle three.js referencing `window`
// in a worker context.

const path = require('path');

/**
 * @param {string} source
 */
module.exports = function (source) {
    if (source.includes("Modified by Needle")) return source;
    console.log("Transform GenerateMeshBVHWorker import");

    // Resolve the actual file path of the worker
    let workerPath;
    try {
        workerPath = require.resolve('three-mesh-bvh/src/workers/generateMeshBVH.worker.js');
    } catch {
        console.warn("Could not resolve three-mesh-bvh worker path, skipping transform");
        return source;
    }

    // Make it relative to the source file being transformed
    const sourceDir = path.dirname(this.resourcePath);
    let relativePath = path.relative(sourceDir, workerPath).replace(/\\/g, '/');
    if (!relativePath.startsWith('.')) relativePath = './' + relativePath;

    // Replace the bare package specifier with the relative path.
    // Webpack 5 will detect `new Worker(new URL(..., import.meta.url))` and bundle it correctly.
    source = source.replace(
        `'three-mesh-bvh/src/workers/generateMeshBVH.worker.js'`,
        `'${relativePath}'`
    );

    return `// Modified by Needle\n${source}`;
};
