import { CollectedIslands } from "../island.js";
import { buildIslandBootstrap } from "../builder.js";
export function createIslandMiddleware(options) {
    let { islandsDir, modules } = options;
    return function* collectIslands(request, next) {
        let collection = yield* CollectedIslands.set({
            nextId: 0,
            seen: new Set(),
            modules,
            invocations: {},
        });
        let html = yield* next(request);
        let bytes = yield* buildIslandBootstrap({
            collection,
            islandsDir,
        });
        let value = new TextDecoder().decode(bytes);
        let script = {
            type: "element",
            tagName: "script",
            properties: {
                "type": "module",
            },
            children: [{
                    type: "text",
                    value,
                }],
        };
        return appendToBody(html, script);
    };
}
function appendToBody(html, node) {
    for (let child of html.children) {
        if (child.type === "element" && child.tagName === "body") {
            child.children.push(node);
            return html;
        }
    }
    throw new Error(`malformed html, no <body> element found`);
}
//# sourceMappingURL=island-middleware.js.map