#!/usr/bin/env node

/**
 * This script bundles superjson and its dependency (copy-anything) into
 * vendored CJS and ESM bundles to avoid the ERR_REQUIRE_ESM error.
 *
 * superjson v2.x is ESM-only, which causes issues on:
 * - Node.js versions before 22.12.0 (require(ESM) not enabled by default)
 * - AWS Lambda (intentionally disables require(ESM))
 *
 * The output files are gitignored and regenerated during each build.
 * This script runs automatically as part of `pnpm run build`.
 *
 * Usage:
 *   node scripts/bundle-superjson.mjs          # Bundle to src/v3/vendor
 *   node scripts/bundle-superjson.mjs --copy   # Also copy to dist directories
 */

import * as esbuild from "esbuild";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { readFileSync, mkdirSync, copyFileSync } from "node:fs";

const __dirname = dirname(fileURLToPath(import.meta.url));
const packageRoot = join(__dirname, "..");
const vendorDir = join(packageRoot, "src", "v3", "vendor");

// Get the installed superjson version for the banner
const superjsonPkg = JSON.parse(
  readFileSync(join(packageRoot, "node_modules", "superjson", "package.json"), "utf-8")
);
const banner = `/**
 * Bundled superjson v${superjsonPkg.version}
 *
 * This file is auto-generated by scripts/bundle-superjson.mjs
 * Do not edit directly - run the script to regenerate.
 *
 * Original package: https://github.com/flightcontrolhq/superjson
 * License: MIT
 */`;

async function bundle() {
  // Ensure vendor directory exists
  mkdirSync(vendorDir, { recursive: true });

  // Bundle for CommonJS
  await esbuild.build({
    entryPoints: [join(packageRoot, "node_modules", "superjson", "dist", "index.js")],
    bundle: true,
    format: "cjs",
    platform: "node",
    target: "node18",
    outfile: join(vendorDir, "superjson.cjs"),
    banner: { js: banner },
    // Don't minify to keep it debuggable
    minify: false,
  });

  // Bundle for ESM
  await esbuild.build({
    entryPoints: [join(packageRoot, "node_modules", "superjson", "dist", "index.js")],
    bundle: true,
    format: "esm",
    platform: "node",
    target: "node18",
    outfile: join(vendorDir, "superjson.mjs"),
    banner: { js: banner },
    minify: false,
  });

  console.log("Bundled superjson v" + superjsonPkg.version);
  console.log("  -> src/v3/vendor/superjson.cjs (CommonJS)");
  console.log("  -> src/v3/vendor/superjson.mjs (ESM)");

  // Copy to dist directories if --copy flag is passed
  if (process.argv.includes("--copy")) {
    const distCommonjsVendor = join(packageRoot, "dist", "commonjs", "v3", "vendor");
    const distEsmVendor = join(packageRoot, "dist", "esm", "v3", "vendor");

    mkdirSync(distCommonjsVendor, { recursive: true });
    mkdirSync(distEsmVendor, { recursive: true });

    copyFileSync(join(vendorDir, "superjson.cjs"), join(distCommonjsVendor, "superjson.cjs"));
    copyFileSync(join(vendorDir, "superjson.mjs"), join(distEsmVendor, "superjson.mjs"));

    console.log("Copied to dist directories");
  }
}

bundle().catch((err) => {
  console.error(err);
  process.exit(1);
});
