#!/usr/bin/env node
import {
  createRepoLocalPackageResolutionPlugin,
  resolveCliRepoRoot
} from "./chunk-QBAF7EYR.mjs";

// src/utils/ts-module-loader.ts
import { mkdtemp, rm, writeFile } from "fs/promises";
import { tmpdir } from "os";
import path from "path";
import { pathToFileURL } from "url";
import { build } from "esbuild";
var ESBUILD_EXTERNALS = [
  "playwright",
  "playwright-core",
  "chromium-bidi",
  "electron"
];
function resolveSourceCheckoutBuildContext() {
  try {
    const repoRoot = resolveCliRepoRoot(import.meta.url);
    return {
      nodePaths: [
        path.join(repoRoot, "apps", "dreamboard-cli", "node_modules"),
        path.join(repoRoot, "node_modules")
      ],
      plugins: [createRepoLocalPackageResolutionPlugin({ repoRoot })]
    };
  } catch {
    return {
      nodePaths: [path.join(process.cwd(), "node_modules")],
      plugins: []
    };
  }
}
async function bundleTypeScriptModuleText(entryPath, options = {}) {
  const sourceCheckoutContext = resolveSourceCheckoutBuildContext();
  const result = await build({
    entryPoints: [entryPath],
    bundle: true,
    format: "esm",
    platform: "node",
    target: "node24",
    sourcemap: "inline",
    external: [...ESBUILD_EXTERNALS, ...options.external ?? []],
    nodePaths: sourceCheckoutContext.nodePaths,
    plugins: sourceCheckoutContext.plugins,
    write: false
  });
  const output = result.outputFiles?.[0];
  if (!output) {
    throw new Error(`Failed to bundle TypeScript module '${entryPath}'.`);
  }
  return output.text;
}
async function importTypeScriptModule(entryPath) {
  const tempDir = await mkdtemp(path.join(tmpdir(), "dreamboard-ts-module-"));
  const outfile = path.join(
    tempDir,
    `${path.basename(entryPath).replace(/\.[^.]+$/u, "")}.mjs`
  );
  try {
    const bundledText = await bundleTypeScriptModuleText(entryPath);
    await writeFile(outfile, bundledText);
    return await import(pathToFileURL(outfile).href);
  } finally {
    await rm(tempDir, { recursive: true, force: true });
  }
}

export {
  bundleTypeScriptModuleText,
  importTypeScriptModule
};
//# sourceMappingURL=chunk-XKCJBIRY.mjs.map