import { spawn } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");

function run(script, args) {
  const child = spawn(process.execPath, [path.join(root, script), ...args], {
    cwd: root,
    stdio: "inherit",
  });

  return new Promise((resolve, reject) => {
    child.once("error", reject);
    child.once("exit", (code, signal) => {
      if (signal) {
        reject(new Error(`${script} terminated by ${signal}`));
        return;
      }
      resolve(code ?? 1);
    });
  });
}

const [typecheckStatus, viteStatus] = await Promise.all([
  run("node_modules/typescript/bin/tsc", ["-b"]),
  run("node_modules/vite/bin/vite.js", ["build"]),
]);

if (typecheckStatus !== 0 || viteStatus !== 0) {
  process.exitCode = 1;
}
