import { err as errNs } from "@simplysm/core-common";
import { SdTsCompiler } from "../ts-compiler/SdTsCompiler.js";
export function createTscPlugin(options) {
    // 내부 상태
    let lastProgram;
    let lastAffectedFiles;
    let lastDiagnostics = [];
    let lastErrors;
    let lastLintResult;
    // SdTsCompiler 인스턴스 (lazy 생성, resetBuilderProgram 시 재생성)
    let compiler;
    // onStart에서 생성한 compile Promise (onEnd에서 await)
    let compilePromise;
    const plugin = {
        name: "sd-tsc",
        setup(build) {
            build.onStart(() => {
                // microtask로 tsc 스케줄링 (await하지 않음)
                compilePromise = Promise.resolve().then(() => {
                    if (compiler == null) {
                        compiler = new SdTsCompiler({
                            pkgDir: options.pkgDir,
                            cwd: options.cwd,
                            output: { js: false, dts: options.output.dts },
                            env: options.env,
                            includeTests: options.includeTests,
                            lint: options.lint,
                        });
                    }
                    return compiler.compileAsync();
                });
            });
            build.onEnd(async () => {
                try {
                    const result = await compilePromise;
                    lastProgram = result.program;
                    lastAffectedFiles = result.affectedFiles;
                    lastDiagnostics = result.diagnostics;
                    lastErrors = result.errors;
                    lastLintResult = result.lint;
                }
                catch (err) {
                    lastProgram = undefined;
                    lastAffectedFiles = undefined;
                    lastDiagnostics = [];
                    lastErrors = [errNs.message(err)];
                    lastLintResult = undefined;
                }
            });
        },
    };
    return {
        plugin,
        getProgram: () => lastProgram,
        getAffectedFiles: () => lastAffectedFiles,
        getDiagnostics: () => lastDiagnostics,
        getErrors: () => lastErrors,
        getLintResult: () => lastLintResult,
        resetBuilderProgram: () => {
            compiler = undefined;
        },
    };
}
//# sourceMappingURL=esbuild-tsc-plugin.js.map