/*!
 Stencil Dev Server v4.41.0-dev.1767762501.0fa0bc8 | MIT Licensed | https://stenciljs.com
 */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// build/dev-server/index.js
var index_exports = {};
__export(index_exports, {
  start: () => start
});
module.exports = __toCommonJS(index_exports);
var import_path2 = __toESM(require("path"));

// build/dev-server/server-worker-main.js
var import_child_process = require("child_process");
var import_path = __toESM(require("path"));
function initServerProcessWorkerProxy(sendToMain) {
  const workerPath = require.resolve(import_path.default.join(__dirname, "server-worker-thread.js"));
  const filteredExecArgs = process.execArgv.filter((v) => !/^--(debug|inspect)/.test(v));
  const forkOpts = {
    execArgv: filteredExecArgs,
    env: process.env,
    cwd: process.cwd(),
    stdio: ["pipe", "pipe", "pipe", "ipc"]
  };
  let serverProcess = (0, import_child_process.fork)(workerPath, [], forkOpts);
  const receiveFromMain = (msg) => {
    if (serverProcess) {
      serverProcess.send(msg);
    } else if (msg.closeServer) {
      sendToMain({ serverClosed: true });
    }
  };
  serverProcess.on("message", (msg) => {
    if (msg.serverClosed && serverProcess) {
      serverProcess.kill("SIGINT");
      serverProcess = null;
    }
    sendToMain(msg);
  });
  serverProcess.stdout.on("data", (data) => {
    console.log(`dev server: ${data}`);
  });
  serverProcess.stderr.on("data", (data) => {
    sendToMain({ error: { message: "stderr: " + data } });
  });
  return receiveFromMain;
}

// build/dev-server/index.js
function start(stencilDevServerConfig, logger, watcher) {
  return new Promise(async (resolve, reject) => {
    try {
      const devServerConfig = {
        devServerDir: __dirname,
        ...stencilDevServerConfig
      };
      if (!import_path2.default.isAbsolute(devServerConfig.root)) {
        devServerConfig.root = import_path2.default.join(process.cwd(), devServerConfig.root);
      }
      let initServerProcess;
      if (stencilDevServerConfig.worker === true || stencilDevServerConfig.worker === void 0) {
        initServerProcess = initServerProcessWorkerProxy;
      } else {
        const devServerProcess = (await import("./server-process.js")).default;
        initServerProcess = devServerProcess.initServerProcess;
      }
      startServer(devServerConfig, logger, watcher, initServerProcess, resolve, reject);
    } catch (e) {
      reject(e);
    }
  });
}
function startServer(devServerConfig, logger, watcher, initServerProcess, resolve, reject) {
  var _a;
  const timespan = logger.createTimeSpan(`starting dev server`, true);
  const startupTimeout = logger.getLevel() !== "debug" || devServerConfig.startupTimeout !== 0 ? setTimeout(() => {
    reject(`dev server startup timeout`);
  }, (_a = devServerConfig.startupTimeout) != null ? _a : 15e3) : null;
  let isActivelyBuilding = false;
  let lastBuildResults = null;
  let devServer = null;
  let removeWatcher = null;
  let closeResolve = null;
  let hasStarted = false;
  let browserUrl = "";
  let sendToWorker = null;
  const closePromise = new Promise((resolve2) => closeResolve = resolve2);
  const close = async () => {
    clearTimeout(startupTimeout);
    isActivelyBuilding = false;
    if (removeWatcher) {
      removeWatcher();
    }
    if (devServer) {
      devServer = null;
    }
    if (sendToWorker) {
      sendToWorker({
        closeServer: true
      });
      sendToWorker = null;
    }
    return closePromise;
  };
  const emit = async (eventName, data) => {
    if (sendToWorker) {
      if (eventName === "buildFinish") {
        isActivelyBuilding = false;
        lastBuildResults = { ...data };
        sendToWorker({ buildResults: { ...lastBuildResults }, isActivelyBuilding });
      } else if (eventName === "buildLog") {
        sendToWorker({
          buildLog: { ...data }
        });
      } else if (eventName === "buildStart") {
        isActivelyBuilding = true;
      }
    }
  };
  const serverStarted = (msg) => {
    hasStarted = true;
    clearTimeout(startupTimeout);
    devServerConfig = msg.serverStarted;
    devServer = {
      address: devServerConfig.address,
      basePath: devServerConfig.basePath,
      browserUrl: devServerConfig.browserUrl,
      protocol: devServerConfig.protocol,
      port: devServerConfig.port,
      root: devServerConfig.root,
      emit,
      close
    };
    browserUrl = devServerConfig.browserUrl;
    timespan.finish(`dev server started: ${browserUrl}`);
    resolve(devServer);
  };
  const requestLog = (msg) => {
    if (devServerConfig.logRequests) {
      if (msg.requestLog.status >= 500) {
        logger.info(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`));
      } else if (msg.requestLog.status >= 400) {
        logger.info(logger.dim(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
      } else if (msg.requestLog.status >= 300) {
        logger.info(logger.dim(logger.magenta(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
      } else {
        logger.info(logger.dim(`${logger.cyan(msg.requestLog.method)} ${msg.requestLog.url}`));
      }
    }
  };
  const serverError = async (msg) => {
    if (hasStarted) {
      logger.error(msg.error.message + " " + msg.error.stack);
    } else {
      await close();
      reject(msg.error.message);
    }
  };
  const requestBuildResults = () => {
    if (sendToWorker) {
      if (lastBuildResults != null) {
        const msg = {
          buildResults: { ...lastBuildResults },
          isActivelyBuilding
        };
        delete msg.buildResults.hmr;
        sendToWorker(msg);
      } else {
        sendToWorker({
          isActivelyBuilding: true
        });
      }
    }
  };
  const compilerRequest = async (compilerRequestPath) => {
    if (watcher && watcher.request && sendToWorker) {
      const compilerRequestResults = await watcher.request({ path: compilerRequestPath });
      sendToWorker({ compilerRequestResults });
    }
  };
  const receiveFromWorker = (msg) => {
    try {
      if (msg.serverStarted) {
        serverStarted(msg);
      } else if (msg.serverClosed) {
        logger.debug(`dev server closed: ${browserUrl}`);
        closeResolve();
      } else if (msg.requestBuildResults) {
        requestBuildResults();
      } else if (msg.compilerRequestPath) {
        compilerRequest(msg.compilerRequestPath);
      } else if (msg.requestLog) {
        requestLog(msg);
      } else if (msg.error) {
        serverError(msg);
      } else {
        logger.debug(`server msg not handled: ${JSON.stringify(msg)}`);
      }
    } catch (e) {
      logger.error("receiveFromWorker: " + e);
    }
  };
  try {
    if (watcher) {
      removeWatcher = watcher.on(emit);
    }
    sendToWorker = initServerProcess(receiveFromWorker);
    sendToWorker({
      startServer: devServerConfig
    });
  } catch (e) {
    close();
    reject(e);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  start
});
