"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = boot;
const http = require("http");
const jsdom_1 = require("jsdom");
const SYSTEM_ROOT_ID_1 = require("../../SYSTEM_ROOT_ID");
const boot_1 = require("../web/boot");
const canvas_1 = require("./canvas");
function boot(opt) {
    const { window } = new jsdom_1.JSDOM(`<div id="${SYSTEM_ROOT_ID_1.SYSTEM_ROOT_ID}"></div>`, {
        url: 'http://localhost/',
    });
    const root = window.document.getElementById(SYSTEM_ROOT_ID_1.SYSTEM_ROOT_ID);
    window.fetch = globalThis.fetch;
    window.HTMLCanvasElement.prototype.getContext = (contextId) => {
        if (contextId === '2d') {
            return new canvas_1.NoopCanvasRenderingContext2D();
        }
        return null;
    };
    // @ts-ignore
    const [system, unlisten] = (0, boot_1.webBoot)(window, root, opt);
    system.api.http.listen = (port, handler) => {
        const server = http.createServer(async (req, res) => {
            const _req = {
                headers: { ...req.headers },
                method: req.method,
                path: req.url,
                body: '',
                search: '',
                query: {},
            };
            let data = '';
            req
                .on('data', (chunk) => {
                data += chunk;
            })
                .on('end', async () => {
                _req.body = data;
                const _res = await handler(_req);
                res.writeHead(_res.status, _res.body, _res.headers);
            });
        });
        server.listen(port);
        return () => {
            server.close();
        };
    };
    return [system, unlisten];
}
//# sourceMappingURL=boot.js.map