"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const build_angular_1 = require("@angular-devkit/build-angular");
const architect_1 = require("@angular-devkit/architect");
const fs = __importStar(require("fs"));
const operators_1 = require("rxjs/operators");
const externals_1 = require("./externals");
let entryPointPath;
function buildPlugin(options, context, transforms = {}) {
    validateOptions(options);
    const originalWebpackConfigurationFn = transforms.webpackConfiguration;
    transforms.webpackConfiguration = (config) => {
        patchWebpackConfig(config, options);
        return originalWebpackConfigurationFn ? originalWebpackConfigurationFn(config) : config;
    };
    const result = (0, build_angular_1.executeBrowserBuilder)(options, context, transforms);
    return result.pipe((0, operators_1.tap)(() => {
        patchEntryPoint('');
    }));
}
function patchEntryPoint(contents) {
    fs.writeFileSync(entryPointPath, contents);
}
function validateOptions(options) {
    const { modulePath } = options;
    if (!modulePath) {
        throw Error('Please define modulePath!');
    }
}
function patchWebpackConfig(config, options) {
    const { sharedLibs } = options;
    // Make sure we are producing a single bundle
    // @ts-ignore
    delete config.entry.polyfills;
    delete config.entry['polyfills-es5'];
    delete config.optimization.runtimeChunk;
    delete config.optimization.splitChunks;
    // @ts-ignore
    delete config.entry.styles;
    config.externals = externals_1.EXTERNALS;
    if (sharedLibs) {
        config.externals = [config.externals];
        const sharedLibsArr = sharedLibs.split(',');
        sharedLibsArr.forEach(sharedLibName => {
            config.externals[0][sharedLibName] = sharedLibName; // define external for code
            // const factoryRegexp = new RegExp(`${sharedLibName}.ngfactory$`);
            // config.externals.push((context, request, callback) => {
            //     if (factoryRegexp.test(request)) {
            //         return callback(null, sharedLibName); // define external for factory
            //     }
            //     callback();
            // });
        });
    }
    const ngCompilerPluginInstance = config.plugins.find(x => x.constructor && x.constructor.name === 'AngularCompilerPlugin');
    if (ngCompilerPluginInstance) {
        // @ts-ignore
        ngCompilerPluginInstance._entryModule = options.modulePath;
    }
    // preserve path to entry point
    // so that we can clear use it within `run` method to clear that file
    // @ts-ignore
    entryPointPath = config.entry.main[0];
    const [modulePath, moduleName] = options.modulePath.split('#');
    // const factoryPath = `${
    //   modulePath.includes('.') ? modulePath : `${modulePath}/${modulePath}`
    //   }.ngfactory`;
    const entryPointContents = `
    export * from '${modulePath}';
    import { ${moduleName} } from '${modulePath}';
    export default ${moduleName};
  `;
    patchEntryPoint(entryPointContents);
    const pluginName = options.pluginName
        || modulePath.split('/').pop().split('.module')[0]
        || moduleName;
    const filename = options.addHash ?
        `${pluginName}.${Date.now()}.js` : // add output file hash to prevent bugs due to browser caching
        `${pluginName}.js`;
    config.output.filename = filename;
    config.output.library = pluginName;
    config.output.libraryTarget = 'umd';
    // workaround to support bundle on nodejs
    config.output.globalObject = `(typeof self !== 'undefined' ? self : this)`;
    // TODO #22944, #22945 remove global.ng.common.locales from plugin.js since it is already presented in base app
}
exports.default = (0, architect_1.createBuilder)(buildPlugin);
