import { IndexHtmlGenerator, } from "@angular/build/private";
import path from "path";
/**
 * esbuild metafile.outputs에서 JS/CSS 파일을 추출하여 FileInfo[] 로 변환한다.
 */
export function extractFilesFromMetafile(metafile, outdir) {
    const files = [];
    const normalizedOutdir = outdir.replace(/\\/g, "/");
    // cssBundle → entry name 매핑 (JS entry의 cssBundle로 CSS에 name 전파)
    const cssBundleToName = new Map();
    for (const output of Object.values(metafile.outputs)) {
        if (output.entryPoint != null && output.cssBundle != null) {
            const name = path.basename(output.entryPoint, path.extname(output.entryPoint));
            cssBundleToName.set(output.cssBundle.replace(/\\/g, "/"), name);
        }
    }
    for (const [outputPath, output] of Object.entries(metafile.outputs)) {
        const normalizedPath = outputPath.replace(/\\/g, "/");
        const ext = path.extname(normalizedPath);
        if (ext !== ".js" && ext !== ".css") {
            continue;
        }
        const relativePath = normalizedPath.startsWith(normalizedOutdir)
            ? normalizedPath.slice(normalizedOutdir.length).replace(/^\//, "")
            : path.relative(normalizedOutdir, normalizedPath).replace(/\\/g, "/");
        const fileInfo = {
            file: relativePath,
            extension: ext,
        };
        if (output.entryPoint != null) {
            fileInfo.name = path.basename(output.entryPoint, path.extname(output.entryPoint));
        }
        else if (ext === ".css") {
            const cssName = cssBundleToName.get(normalizedPath);
            if (cssName != null) {
                fileInfo.name = cssName;
            }
        }
        files.push(fileInfo);
    }
    return files;
}
/**
 * esbuild 빌드 결과를 기반으로 index.html을 생성한다.
 * IndexHtmlGenerator(@angular/build/private)를 활용하여 script/link 태그를 자동 주입한다.
 */
export async function generateIndexHtml(options) {
    const files = extractFilesFromMetafile(options.metafile, options.outdir);
    const entrypoints = options.entryNames.map((name) => [name, true]);
    const generator = new IndexHtmlGenerator({
        indexPath: options.indexPath,
        entrypoints,
        sri: options.mode === "build",
        postTransform: options.postTransform,
    });
    const result = await generator.process({
        lang: undefined,
        baseHref: options.baseHref,
        outputPath: options.outdir,
        files,
    });
    return {
        content: result.csrContent,
        warnings: result.warnings,
        errors: result.errors,
    };
}
//# sourceMappingURL=esbuild-index-html.js.map