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

// scripts/blogkit-md.ts
var import_node_http = require("http");
var import_node_child_process = require("child_process");
var import_node_fs = require("fs");
var import_node_path = __toESM(require("path"));
var args = process.argv.slice(2);
var inputArg = args.find((a) => !a.startsWith("--"));
var portArg = args.find((a) => a.startsWith("--port="));
var requestedPort = portArg ? parseInt(portArg.split("=")[1]) : 0;
if (!inputArg) {
  console.error("Usage: blogkit-md <path-to-markdown-file-or-directory> [--port=3001]");
  process.exit(1);
}
var packageRoot = import_node_path.default.dirname(import_node_path.default.dirname(process.argv[1]));
var inputPath = import_node_path.default.resolve(process.cwd(), inputArg);
var nextBin = import_node_path.default.join(packageRoot, "node_modules/.bin/next");
var inputStat;
try {
  inputStat = (0, import_node_fs.statSync)(inputPath);
} catch {
  console.error(`Path does not exist: ${inputPath}`);
  process.exit(1);
}
var isDirectory = inputStat.isDirectory();
var clients = /* @__PURE__ */ new Set();
function getFreePort() {
  return new Promise((resolve, reject) => {
    const s = (0, import_node_http.createServer)();
    s.listen(0, () => {
      const port = s.address().port;
      s.close((err) => err ? reject(err) : resolve(port));
    });
    s.on("error", reject);
  });
}
var sseServer = (0, import_node_http.createServer)((req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Access-Control-Allow-Origin": "*"
  });
  res.write("data: connected\n\n");
  clients.add(res);
  req.on("close", () => clients.delete(res));
});
sseServer.listen(0, async () => {
  const ssePort = sseServer.address().port;
  const nextPort = requestedPort || await getFreePort();
  const nextEnv = {
    ...process.env,
    ...isDirectory ? { MARKDOWN_DIR: inputPath } : { MARKDOWN_FILE: inputPath },
    SSE_PORT: String(ssePort)
  };
  const broadcastReload = () => {
    for (const client of clients) {
      client.write("data: reload\n\n");
    }
  };
  if (isDirectory) {
    (0, import_node_fs.watch)(inputPath, { recursive: true }, (_, filename) => {
      if (filename && filename.endsWith(".md")) broadcastReload();
    });
  } else {
    const markdownFilename = import_node_path.default.basename(inputPath);
    (0, import_node_fs.watch)(import_node_path.default.dirname(inputPath), (_, filename) => {
      if (filename === markdownFilename) broadcastReload();
    });
  }
  const child = (0, import_node_child_process.spawn)(nextBin, ["start", "--port", String(nextPort)], {
    cwd: packageRoot,
    env: nextEnv,
    stdio: ["inherit", "pipe", "inherit"]
  });
  let browserOpened = false;
  child.stdout?.on("data", (chunk) => {
    process.stdout.write(chunk);
    if (!browserOpened) {
      const match = chunk.toString().match(/http:\/\/localhost:\d+/);
      if (match) {
        browserOpened = true;
        (0, import_node_child_process.exec)(`open ${match[0]}`);
      }
    }
  });
  child.on("exit", (code) => {
    sseServer.close();
    process.exit(code ?? 0);
  });
});
