#!/usr/bin/env node
import module from 'node:module';
import { spawnSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const cliPath = join(__dirname, 'cli.js');

function isServeCommand() {
  return process.argv[2] === 'serve';
}

if (isServeCommand()) {
  module.enableCompileCache?.();
  process.argv[1] = cliPath;
  await import(pathToFileURL(cliPath).href);
} else {
  const result = spawnSync(
    process.execPath,
    ['--expose-gc', cliPath, ...process.argv.slice(2)],
    { stdio: 'inherit' },
  );

  if (result.signal) {
    process.kill(process.pid, result.signal);
  } else {
    process.exit(result.status ?? 1);
  }
}
