import http from "http";
import { performance } from "perf_hooks";
import send from "send";
import { fileURLToPath } from "url";
import * as msg from "../dev/messages.js";
import { error, info } from "../logger.js";
import { subpathNotUsedTemplate } from "../dev/template/4xx.js";
async function preview(config, { logging }) {
  const startServerTime = performance.now();
  const base = config.buildOptions.site ? new URL(config.buildOptions.site).pathname + "/" : "/";
  const server = http.createServer((req, res) => {
    if (!req.url.startsWith(base)) {
      res.statusCode = 404;
      res.end(subpathNotUsedTemplate(base, req.url));
      return;
    }
    send(req, req.url.substr(base.length - 1), {
      root: fileURLToPath(config.dist)
    }).pipe(res);
  });
  let port = config.devOptions.port;
  const { hostname } = config.devOptions;
  await new Promise((resolve, reject) => {
    const onError = (err) => {
      if (err.code && err.code === "EADDRINUSE") {
        info(logging, "astro", msg.portInUse({ port }));
        port++;
      } else {
        error(logging, "preview", err.stack);
        server.removeListener("error", onError);
        reject(err);
      }
    };
    server.listen(port, hostname, () => {
      info(logging, "preview", msg.devStart({ startupTime: performance.now() - startServerTime }));
      info(logging, "preview", msg.devHost({ host: `http://${hostname}:${port}${base}` }));
      resolve(server);
    }).on("error", (err) => {
      process.exit(1);
    });
  });
  return {
    hostname,
    port,
    server,
    stop: async () => {
      server.close();
    }
  };
}
export {
  preview as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvcHJldmlldy9pbmRleC50cyJdLAogICJtYXBwaW5ncyI6ICJBQUdBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBY0EsdUJBQXNDLFFBQXFCLEVBQUUsV0FBbUQ7QUFDOUcsUUFBTSxrQkFBa0IsWUFBWTtBQUNwQyxRQUFNLE9BQU8sT0FBTyxhQUFhLE9BQU8sSUFBSSxJQUFJLE9BQU8sYUFBYSxNQUFNLFdBQVcsTUFBTTtBQUczRixRQUFNLFNBQVMsS0FBSyxhQUFhLENBQUMsS0FBSyxRQUFRO0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