import commonjs from "@rollup/plugin-commonjs"
import inject from "@rollup/plugin-inject"
import { nodeResolve } from "@rollup/plugin-node-resolve"
import { globSync } from "glob"
import path from "node:path"
import url from "node:url"
import { defineConfig } from "rollup"
import del from "rollup-plugin-delete"
import esbuild from "rollup-plugin-esbuild"
import nodePolyfills from "rollup-plugin-polyfill-node"


export default defineConfig({
    input: Object.fromEntries(
        globSync(["./src/**/*.ts"]).map(file => [
            path.relative(".", file.slice(0, file.length - path.extname(file).length)),
            url.fileURLToPath(new URL(file, import.meta.url)),
        ])
    ),

    external: [/^godot/, /^jsb/],

    output: {
        dir: "./.godot/GodotJS",
        format: "cjs",
        exports: "named",
        esModule: true,
        preserveModules: true,
    },

    treeshake: true,

    plugins: [
        esbuild(),
        nodeResolve(),
        commonjs(),
        nodePolyfills({ include: null }),
        inject({
            TextEncoder: ["@nberlette/utf8", "TextEncoder"],
            TextDecoder: ["@nberlette/utf8", "TextDecoder"],
            TextEncoderStream: ["@nberlette/utf8", "TextEncoderStream"],
            TextDecoderStream: ["@nberlette/utf8", "TextDecoderStream"],
            URL: ["url-shim", "URL"],
            URLSearchParams: ["url-shim", "URLSearchParams"],
            React: ["react", "*"],
        }),
        del({ targets: "./.godot/GodotJS/*" }),
    ],
})
