/**
 * Worker spawning that survives `bun build --compile`.
 *
 * Bun standalone executables fail to resolve nested worker entrypoints
 * (oven-sh/bun#29124): the main bundle is flattened into /$bunfs/root while
 * additional entrypoints keep their nested paths, so `new Worker(new URL(...))`
 * dies with ModuleNotFound in compiled binaries. Standalone builds therefore
 * embed each worker as a pre-bundled source string (generated by
 * scripts/build-standalone.ts into src/generated/worker-bundles.gen.ts) and
 * spawn it from a Blob URL, which works in both compiled binaries and source
 * checkouts. Source checkouts without generated bundles fall back to the
 * dev-mode URL form.
 */
import { WORKER_BUNDLES } from "../generated/worker-bundles.gen";

export function spawnWorker(devUrl: string, key: string): Worker {
  const src = WORKER_BUNDLES[key];
  if (src) {
    const blobUrl = URL.createObjectURL(new Blob([src], { type: "text/javascript" }));
    let worker: Worker;
    try {
      worker = new Worker(blobUrl);
    } catch (error) {
      URL.revokeObjectURL(blobUrl);
      throw error;
    }
    // Long-lived servers schedule workers repeatedly; release the blob URL
    // once the thread exits instead of leaking one per run.
    worker.addEventListener("close", () => URL.revokeObjectURL(blobUrl));
    return worker;
  }
  return new Worker(devUrl);
}
