// build.mjs
//
// Build the browser demo bundle as a classic (non-module) script so the
// single-file demo also runs when opened directly from disk (file://),
// where browsers refuse ES module scripts.
//
//   bun examples/browser-demo/build.mjs
//
// Steps: bundle the real widget + verifier + signer as an IIFE, then
// neutralize the one `import.meta.url` reference that rides along from the
// signer's CLI guard. That guard is dead code in the browser (its `isNode`
// check is false), but `import.meta` is a parse error in a classic script,
// so we replace it with an empty string. Nothing that runs is affected.
//
// SPDX-License-Identifier: MIT

import { $ } from "bun";

const dir = new URL(".", import.meta.url).pathname;
const out = `${dir}playground.bundle.js`;

await $`bun build ${dir}playground.src.js --outfile ${out} --format iife --target browser --minify`.quiet();

let code = await Bun.file(out).text();
const before = code;
code = code.replaceAll("import.meta.url", '""').replaceAll("import.meta.main", "false");
if (code.includes("import.meta")) {
  console.error("!! import.meta still present after neutralization; aborting");
  process.exit(1);
}
await Bun.write(out, code);
console.log(
  `built ${(code.length / 1024) | 0}KB classic bundle` +
    (code === before ? "" : " (import.meta neutralized)")
);
