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";
async function preview(config, {logging}) {
  const startServerTime = performance.now();
  const server = http.createServer((req, res) => {
    send(req, req.url, {
      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}/`}));
      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,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvcHJldmlldy9pbmRleC50cyJdLAogICJtYXBwaW5ncyI6ICJBQUdBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQWNBLHVCQUFzQyxRQUFxQixDQUFFLFVBQW1EO0FBQzlHLFFBQU0sa0JBQWtCLFlBQVk7QUFHcEMsUUFBTSxTQUFTLEtBQUssYUFBYSxDQUFDLEtBQUssUUFBUTtBQUM3QyxTQUFLLEtBQUssSUFBSSxLQUFNO0FBQUEsTUFDbEIsTUFBTSxjQUFjLE9BQU87QUFBQSxPQUMxQixLQUFLO0FBQUE7QUFJVixNQUFJLE9BQU8sT0FBTyxXQUFXO0FBQzdCLFFBQU0sQ0FBRSxZQUFhLE9BQU87QUFDNUIsUUFBTSxJQUFJLFFBQXFCLENBQUMsU0FBUyxXQUFXO0FBQ2xELFVBQU0sVUFBVSxDQUFDLFFBQStCO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