import path from 'path';
import ModuleFederation from '@module-federation/enhanced';
import webpack from 'webpack';
import { STATIC_TMP_FOLDER } from './constants.js';
import { logger } from './logger.js';
import { spawnSync } from 'child_process';
const ModuleFederationPlugin = ModuleFederation.ModuleFederationPlugin;
const logStats = (stats) => {
    const statsMessage = stats.toString({
        all: false,
        errors: true,
        warnings: true,
        colors: true,
    });
    if (statsMessage)
        logger.info(statsMessage);
    if (stats.hasErrors())
        logger.error('❌ Build failed unexpectedly. Check the logs above.');
    if (stats.hasWarnings())
        logger.info('⚠️ Build completed with warnings.');
};
export const bundle = (config) => {
    const { path: checkoutPath, mode } = config;
    const compiler = webpack({
        stats: 'verbose',
        context: checkoutPath,
        entry: './src/index.tsx',
        target: 'web',
        mode,
        output: {
            filename: '[name].[contenthash].js',
            chunkFilename: '[name].[contenthash].js',
            publicPath: 'auto',
            path: path.resolve(checkoutPath, STATIC_TMP_FOLDER),
        },
        resolve: {
            extensions: ['.tsx', '.ts', '.js'],
        },
        module: {
            rules: [
                {
                    test: /\.(ts|tsx)$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    options: {
                        presets: [
                            '@babel/preset-env',
                            ['@babel/preset-react', { runtime: 'automatic' }],
                            '@babel/preset-typescript',
                        ],
                    },
                },
                {
                    test: /\.css$/i,
                    use: ['style-loader', 'css-loader'],
                },
            ],
        },
        plugins: [
            new ModuleFederationPlugin({
                name: 'extensions',
                library: { type: 'var', name: 'extensions' },
                filename: 'checkout-extensions.js',
                exposes: {
                    './components': './src/index.tsx',
                },
                shared: {
                    react: {
                        import: 'react',
                        shareKey: 'react',
                        shareScope: 'default',
                        singleton: true,
                        requiredVersion: '^18',
                    },
                    'react/jsx-runtime': {
                        singleton: true,
                        requiredVersion: '^18',
                    },
                    'react-dom': {
                        singleton: true,
                        requiredVersion: '^18',
                    },
                },
            }),
        ],
    });
    if (mode === 'development') {
        compiler.watch({}, (err, stats) => {
            if (err) {
                logger.debug(err);
                return;
            }
            if (stats)
                logStats(stats);
            config.onChange();
        });
    }
    else {
        compiler.run((err, stats) => {
            if (err) {
                logger.error('⚠️ An error occurred during the extension build:', err);
                process.exit(1);
            }
            if (stats)
                logStats(stats);
            if (stats && stats.hasErrors()) {
                process.exit(1);
            }
            logger.info('✅ Extensions built successfully.');
        });
    }
};
export const compileTs = ({ path: projectPath }) => {
    const result = spawnSync('nlx', ['tsc', '--noEmit', '-p', projectPath], {
        stdio: 'inherit',
    });
    if (result.status !== 0) {
        logger.info('❌ Build stopped due to type errors. Check the logs above.');
        process.exit(1);
    }
};
//# sourceMappingURL=bundler.js.map