import { join } from "@std/path";
import { call } from "effection";
import * as esbuild from "esbuild";
import { denoPlugins } from "../deps/jsr.io/@luca/esbuild-deno-loader/0.11.1/mod.js";
export function* buildIslandBootstrap(options) {
    let { collection, islandsDir } = options;
    let mainPath = new URL("./island-main.ts", import.meta.url).href;
    let bootstrap = [
        `const islands = ${JSON.stringify(collection.invocations)};`,
        "const modules = new Map();",
    ];
    let seen = [...collection.seen];
    for (let i = 0; i < seen.length; i++) {
        let name = seen[i];
        bootstrap.push(`import * as $${i} from "${join(islandsDir, name)}";`, `modules.set(${name}, $${i})`);
    }
    bootstrap.push("\n", `import { main } from "${mainPath}";`, `export const bootstrap = (dom) => main(dom, islands, modules);`, `if (typeof globalThis.document !== "undefined") { await bootstrap(document); }`);
    try {
        let result = yield* call(esbuild.build({
            plugins: [...denoPlugins({
                    configPath: new URL("../deno.json", import.meta.url).pathname,
                })],
            stdin: {
                contents: bootstrap.join("\n"),
                sourcefile: "bootstrap.js",
                resolveDir: ".",
            },
            jsx: "automatic",
            jsxImportSource: "revolution",
            write: false,
            bundle: true,
            format: "esm",
        }));
        if (result.errors.length) {
            throw new Error("esbuild failed", { cause: result });
        }
        else {
            if (!result.outputFiles) {
                throw new Error("esbuild failed to produce output", {
                    cause: result,
                });
            }
            let [output] = result.outputFiles;
            return output.contents;
        }
    }
    finally {
        esbuild.stop();
    }
}
//# sourceMappingURL=builder.js.map