import {
  INITIAL_STATE_WINDOW_PROPERTY,
  RUNTIME_CONFIG_WINDOW_PROPERTY,
  asyncHandler,
  config_default,
  createRenderTree
} from "./chunk-PPE2X6R3.mjs";

// src/runtime/createRuntimeState.tsx
function createRuntimeState({ dom }) {
  return {
    dom: createRenderTree(dom)
  };
}

// src/server/toolpadAppServer.ts
import * as path from "path";
import * as fs from "fs/promises";
import * as express2 from "express";
import serializeJavascript from "serialize-javascript";

// src/server/basicAuth.ts
function checkBasicAuthHeader(headerContent) {
  if (!config_default.basicAuthUser) {
    return true;
  }
  if (headerContent) {
    const auth = headerContent.split(" ")[1];
    const [user, pwd] = atob(auth).toString().split(":");
    if (user === config_default.basicAuthUser && pwd === config_default.basicAuthPassword) {
      return true;
    }
  }
  return false;
}
function basicAuthUnauthorized(res) {
  res.setHeader("WWW-Authenticate", 'Basic realm="Protected"');
  res.statusCode = 401;
  res.end("Unauthorized");
}

// src/server/rpc.ts
import * as superjson from "superjson";
import express from "express";
import * as z from "zod";
import { fromZodError } from "zod-validation-error";
import { hasOwnProperty } from "@mui/toolpad-utils/collections";
import { errorFrom, serializeError } from "@mui/toolpad-utils/errors";
import { withContext, createServerContext } from "@mui/toolpad-core/serverRuntime";
var rpcRequestSchema = z.object({
  name: z.string(),
  params: z.array(z.any())
});
function createRpcHandler(definition) {
  const router = express.Router();
  router.post(
    "/",
    express.json(),
    asyncHandler(async (req, res) => {
      const parseResult = rpcRequestSchema.safeParse(req.body);
      if (!parseResult.success) {
        res.status(400).send(fromZodError(parseResult.error));
        return;
      }
      const { name, params } = parseResult.data;
      if (!hasOwnProperty(definition, name)) {
        res.status(404).end();
        return;
      }
      const method = definition[name];
      let rawResult;
      let error = null;
      try {
        const ctx = createServerContext(req, res);
        rawResult = await withContext(ctx, async () => {
          return method({ params, req, res });
        });
      } catch (rawError) {
        error = errorFrom(rawError);
      }
      const responseData = error ? { error: serializeError(error) } : { result: superjson.stringify(rawResult) };
      res.json(responseData);
    })
  );
  return router;
}
function createMethod(handler) {
  return handler;
}

// src/server/runtimeRpcServer.ts
function createRpcServer(project) {
  return {
    introspectDataProvider: createMethod(
      ({ params }) => {
        return project.functionsManager.introspectDataProvider(...params);
      }
    ),
    getDataProviderRecords: createMethod(
      ({ params }) => {
        return project.functionsManager.getDataProviderRecords(...params);
      }
    ),
    deleteDataProviderRecord: createMethod(({ params }) => {
      return project.functionsManager.deleteDataProviderRecord(...params);
    }),
    updateDataProviderRecord: createMethod(({ params }) => {
      return project.functionsManager.updateDataProviderRecord(...params);
    }),
    createDataProviderRecord: createMethod(({ params }) => {
      return project.functionsManager.createDataProviderRecord(...params);
    }),
    execQuery: createMethod(({ params }) => {
      return project.dataManager.execQuery(...params);
    }),
    execFunction: createMethod(({ params }) => {
      return project.functionsManager.execFunction(...params);
    })
  };
}

// src/server/toolpadAppServer.ts
function postProcessHtml(html, { config, initialState }) {
  const serializedConfig = serializeJavascript(config, { ignoreFunction: true });
  const serializedInitialState = serializeJavascript(initialState, { isJSON: true });
  const toolpadScripts = [
    `<script>window[${JSON.stringify(
      RUNTIME_CONFIG_WINDOW_PROPERTY
    )}] = ${serializedConfig}</script>`,
    `<script>window[${JSON.stringify(
      INITIAL_STATE_WINDOW_PROPERTY
    )}] = ${serializedInitialState}</script>`
  ];
  return html.replace(`<!-- __TOOLPAD_SCRIPTS__ -->`, () => toolpadScripts.join("\n"));
}
async function createProdHandler(project) {
  const handler = express2.Router();
  handler.use(express2.static(project.getAppOutputFolder(), { index: false }));
  handler.use((req, res, next) => {
    if (checkBasicAuthHeader(req.headers.authorization ?? null)) {
      next();
      return;
    }
    basicAuthUnauthorized(res);
  });
  handler.use("/api/data", project.dataManager.createDataHandler());
  const runtimeRpcServer = createRpcServer(project);
  handler.use("/api/runtime-rpc", createRpcHandler(runtimeRpcServer));
  handler.use(
    asyncHandler(async (req, res) => {
      const htmlFilePath = path.resolve(project.getAppOutputFolder(), "./index.html");
      const [runtimeConfig, dom] = await Promise.all([
        project.getRuntimeConfig(),
        project.loadDom()
      ]);
      let html = await fs.readFile(htmlFilePath, { encoding: "utf-8" });
      html = postProcessHtml(html, {
        config: runtimeConfig,
        initialState: createRuntimeState({ dom })
      });
      res.setHeader("Content-Type", "text/html; charset=utf-8").status(200).end(html);
    })
  );
  return { handler, dispose: async () => void 0 };
}

export {
  createRpcHandler,
  createMethod,
  createRpcServer,
  createRuntimeState,
  postProcessHtml,
  createProdHandler
};
//# sourceMappingURL=chunk-LSPXE4QP.mjs.map