import {
  createRuntimeState,
  postProcessHtml
} from "./chunk-LSPXE4QP.mjs";
import {
  createViteConfig,
  getHtmlContent
} from "./chunk-REPPYLTL.mjs";
import "./chunk-PPE2X6R3.mjs";

// src/server/appServerWorker.ts
import { parentPort, workerData } from "worker_threads";
import invariant from "invariant";
import { createRpcClient } from "@mui/toolpad-utils/workerRpc";
var { notifyReady, loadDom, getComponents, getPagesManifest } = createRpcClient(
  workerData.mainThreadRpcPort
);
invariant(
  process.env.NODE_ENV === "development",
  "The dev server must be started with NODE_ENV=development"
);
function devServerPlugin({ config, base }) {
  return {
    name: "toolpad-dev-server",
    async configureServer(viteServer) {
      return () => {
        viteServer.middlewares.use("/", async (req, res, next) => {
          invariant(req.url, "request must have a url");
          try {
            const dom = await loadDom();
            const template = getHtmlContent({ canvas: true, base });
            let html = await viteServer.transformIndexHtml(req.url, template);
            html = postProcessHtml(html, {
              config,
              initialState: createRuntimeState({ dom })
            });
            res.setHeader("content-type", "text/html; charset=utf-8").end(html);
          } catch (e) {
            next(e);
          }
        });
      };
    }
  };
}
async function main({ port, ...config }) {
  const { reloadComponents, viteConfig } = await createViteConfig({
    ...config,
    dev: true,
    plugins: [devServerPlugin(config)],
    getComponents,
    getPagesManifest,
    loadDom
  });
  const vite = await import("vite");
  const devServer = await vite.createServer(viteConfig);
  await devServer.listen(port);
  invariant(parentPort, "parentPort must be defined");
  parentPort.on("message", async (msg) => {
    switch (msg.kind) {
      case "reload-components": {
        reloadComponents();
        break;
      }
      case "exit": {
        await devServer.close();
        break;
      }
      default:
        throw new Error(`Unknown command ${msg}`);
    }
  });
  await notifyReady();
}
main(workerData);
export {
  main
};
//# sourceMappingURL=appServerWorker.mjs.map