"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);

// packages/dev-tools/vite/main.ts
var main_exports = {};
__export(main_exports, {
  builderDevTools: () => builderDevTools
});
module.exports = __toCommonJS(main_exports);
var import_core = require("../core/index.cjs");
var import_node = require("../node/index.cjs");
var import_server = require("../server/index.cjs");

// packages/dev-tools/common/dotenv.ts
async function parseDotEnvFile(sys, envPath) {
  const envContent = await sys.readFile(envPath);
  if (typeof envContent === "string") {
    return parseDotEnvContent(envContent);
  }
  return null;
}
function parseDotEnvContent(envContent) {
  const envVars = {};
  const lines = envContent.replace(/\r\n?/gm, "\n");
  let match;
  while ((match = DOTENV_LINE.exec(lines)) != null) {
    const key = match[1];
    let value = match[2] || "";
    value = value.trim();
    const maybeQuote = value[0];
    value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
    if (maybeQuote === '"') {
      value = value.replace(/\\n/g, "\n");
      value = value.replace(/\\r/g, "\r");
    }
    envVars[key] = value;
  }
  return envVars;
}
var DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;

// packages/dev-tools/vite/main.ts
var import_node_path = __toESM(require("node:path"), 1);

// packages/dev-tools/common/constants.ts
var DEV_TOOLS_CLIENT_SCRIPT_PATH = "/~builder-dev-tools.js";

// packages/dev-tools/vite/main.ts
function builderDevTools(opts = {}) {
  const plugin = {
    name: "vite-plugin-builder-dev-tools",
    async configureServer(viteDevServer) {
      if (process.argv.includes("codegen")) {
        return;
      }
      const sys = await (0, import_node.createDevToolsNodeSys)({
        cwd: import_node_path.default.normalize(viteDevServer.config.root)
      });
      const devTools = await (0, import_core.createDevTools)(sys);
      const devToolsServer = await (0, import_server.createDevToolsServer)({
        ...devTools,
        getClientId: () => "vite-builder-dev-tools",
        closeAppServer: async () => {
          sys.debug("close server");
          await viteDevServer?.close();
        },
        restartAppServer: async () => {
          sys.debug("restart server");
          await viteDevServer?.restart();
        },
        enableAppWatch: async (enable) => {
          if (enable) {
            sys.debug("enable watch");
            viteDevServer?.watcher.add(viteDevServer.config.root);
            const gitPath = sys.join(viteDevServer.config.root, ".git");
            const nodeModulesPath = sys.join(
              viteDevServer.config.root,
              "node_modules"
            );
            viteDevServer?.watcher.unwatch([gitPath, nodeModulesPath]);
          } else {
            sys.debug("disable watch");
            viteDevServer?.watcher.unwatch(viteDevServer.config.root);
          }
          return enable;
        },
        ...sys,
        ...opts
      });
      viteDevServer.watcher.on("change", async (filePath) => {
        if (filePath.includes(".env")) {
          const envVars = await parseDotEnvFile(sys, filePath);
          if (envVars) {
            const envKeys = Object.keys(envVars);
            envKeys.forEach((key) => {
              process.env[key] = envVars[key];
            });
          }
        }
      });
      viteDevServer.middlewares.use(async (_req, res, next) => {
        try {
          const orgResponseEnd = res.end;
          res.end = function(...args) {
            const contentType = (res.getHeader("Content-Type") || "").toString();
            if (contentType.includes("text/html")) {
              const url = new URL(
                DEV_TOOLS_CLIENT_SCRIPT_PATH,
                devToolsServer.getUrl()
              );
              res.write(`<script defer src="${url}"></script>`);
            }
            return orgResponseEnd.apply(this, args);
          };
          next();
        } catch (e) {
          next(e);
        }
      });
    }
  };
  return plugin;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  builderDevTools
});
