"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeCheckProject = void 0;
exports.uiPrebuild = uiPrebuild;
exports.uiPostbuild = uiPostbuild;
const sdk_build_core_1 = require("@servicenow/sdk-build-core");
const script_runner_1 = require("./script-runner");
const environment_1 = require("./environment");
const typeCheckProject = (project) => {
    const logger = project.getLogger();
    const config = project.getConfig();
    const fs = project.getFileSystem();
    const clientDir = project.resolvePath(config.clientDir);
    if (config.clientDir && sdk_build_core_1.FileSystem.existsSync(fs, clientDir)) {
        const defaultCompilerOptions = {
            moduleResolution: sdk_build_core_1.ts.ModuleResolutionKind.Bundler,
            module: sdk_build_core_1.ts.ModuleKind.ES2022,
            target: sdk_build_core_1.ts.ScriptTarget.ES2022,
            lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
            jsx: sdk_build_core_1.tsc.JsxEmit.Preserve,
        };
        const tsConfigFilePath = project.resolvePath(config.clientDir, 'tsconfig.json');
        const projectOptions = {
            fileSystem: new sdk_build_core_1.TsMorphFileSystemWrapper(fs),
            defaultCompilerOptions,
        };
        if (sdk_build_core_1.FileSystem.existsSync(fs, tsConfigFilePath)) {
            logger.debug(`Using client tsconfig.json for type checking: ${tsConfigFilePath}`);
            projectOptions.tsConfigFilePath = tsConfigFilePath;
            projectOptions.skipAddingFilesFromTsConfig = true;
        }
        else {
            logger.warn(`No tsconfig.json found in "${config.clientDir}" directory, using default compiler options for type checking`);
        }
        const compiler = new sdk_build_core_1.ts.Project(projectOptions);
        logger.debug(`Type checking client project with options:
${JSON.stringify(compiler.getCompilerOptions(), null, 2)}`);
        const sourceFiles = compiler.addSourceFilesAtPaths([
            sdk_build_core_1.path.join(clientDir, '**/*.ts'),
            sdk_build_core_1.path.join(clientDir, '**/*.tsx'),
            sdk_build_core_1.path.join(clientDir, '**/*.d.ts'),
            '!**/node_modules/**',
        ]);
        logger.debug(`Type checking ${sourceFiles.length} client source files:
${sourceFiles.map((file) => `  - ${file.getFilePath()}`).join('\n')}`);
        const diagnostics = compiler.getPreEmitDiagnostics();
        if (diagnostics.length > 0) {
            throw new Error(`Type check failed!
${compiler.formatDiagnosticsWithColorAndContext(diagnostics)}`);
        }
        else {
            logger.info('Type check completed successfully');
        }
    }
};
exports.typeCheckProject = typeCheckProject;
async function uiPrebuild({ project }) {
    const logger = project.getLogger();
    const config = project.getConfig();
    const fs = project.getFileSystem();
    (0, exports.typeCheckProject)(project);
    const hasPrebuildScript = (0, script_runner_1.projectHasScript)(project, 'prebuild');
    const supportsTaskScripts = !environment_1.isWebWorker || (0, environment_1.hasModuleLoader)();
    if (supportsTaskScripts && hasPrebuildScript) {
        await (0, script_runner_1.runScriptInProject)({
            scriptName: 'prebuild',
            project: project,
            throwIfNotFound: false,
        });
    }
    else if (config.clientDir) {
        if (hasPrebuildScript) {
            logger.debug('Custom scripts are not supported, so using the default UI build');
        }
        // This needs to be imported dynamically to avoid sass bundling issues
        const { defaultUiBuild } = await import('./default-ui-build.js');
        await defaultUiBuild({ project: project });
    }
    if (sdk_build_core_1.FileSystem.existsSync(fs, project.resolvePath(config.staticContent.buildDir))) {
        for (const file of project.reloadDirectory(config.staticContent.buildDir)) {
            // static content files are output from the prebuild process
            // and should be treated as read-only by the project
            file.setReadOnly(true);
        }
    }
}
async function uiPostbuild({ project }) {
    const logger = project.getLogger();
    const supportsTaskScripts = !environment_1.isWebWorker || (0, environment_1.hasModuleLoader)();
    if (supportsTaskScripts) {
        await (0, script_runner_1.runScriptInProject)({
            scriptName: 'postbuild',
            project: project,
            throwIfNotFound: false,
        });
    }
    else if ((0, script_runner_1.projectHasScript)(project, 'postbuild')) {
        logger.warn('Custom scripts are not supported, skipping postbuild script');
    }
}
//# sourceMappingURL=ui-build.js.map