"use strict";exports.__esModule=true;exports.default=void 0;var path=_interopRequireWildcard(require("path"));var _webpack=_interopRequireWildcard(require("webpack"));var _webpackSources=_interopRequireDefault(require("webpack-sources"));var _pLimit=_interopRequireDefault(require("p-limit"));var _jestWorker=_interopRequireDefault(require("jest-worker"));var _crypto=_interopRequireDefault(require("crypto"));var _cacache=_interopRequireDefault(require("next/dist/compiled/cacache"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap();_getRequireWildcardCache=function(){return cache;};return cache;}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj};}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj.default=obj;if(cache){cache.set(obj,newObj);}return newObj;}// @ts-nocheck
const isWebpack5=parseInt(_webpack.default.version)===5;function getEcmaVersion(environment){// ES 6th
if(environment.arrowFunction||environment.const||environment.destructuring||environment.forOf||environment.module){return 2015;}// ES 11th
if(environment.bigIntLiteral||environment.dynamicImport){return 2020;}return 5;}function buildError(error,file){if(error.line){return new Error(`${file} from Terser\n${error.message} [${file}:${error.line},${error.col}]${error.stack?`\n${error.stack.split('\n').slice(1).join('\n')}`:''}`);}if(error.stack){return new Error(`${file} from Terser\n${error.message}\n${error.stack}`);}return new Error(`${file} from Terser\n${error.message}`);}class Webpack4Cache{constructor(cacheDir,{SourceMapSource,RawSource}){this.cacheDir=cacheDir;this.sources={SourceMapSource,RawSource};}getLazyHashedEtag(obj){let str;if(obj.source){str=obj.source();}const hash=_crypto.default.createHash('md4');hash.update(str?str:obj);return hash.digest('base64');}async getPromise(identifier,etag){let cachedResult;try{cachedResult=await _cacache.default.get(this.cacheDir,etag);}catch(ignoreError){// eslint-disable-next-line no-undefined
return undefined;}cachedResult=JSON.parse(cachedResult.data);const{code,name,map,input,inputSourceMap}=cachedResult;let source;if(map){source=new this.sources.SourceMapSource(code,name,map,input,inputSourceMap,true);}else{source=new this.sources.RawSource(code);}return{source};}async storePromise(identifier,etag,data){await _cacache.default.put(this.cacheDir,etag,JSON.stringify(data));}}class TerserPlugin{constructor(options={}){const{cacheDir,terserOptions={},parallel}=options;this.options={cacheDir,parallel,terserOptions};}async optimize(compilation,assets,optimizeOptions,cache,{SourceMapSource,RawSource}){let numberOfAssetsForMinify=0;const assetsList=isWebpack5?Object.keys(assets):[...Array.from(compilation.additionalChunkAssets||[]),...Array.from(assets).reduce((acc,chunk)=>{return acc.concat(Array.from(chunk.files||[]));},[])];const assetsForMinify=await Promise.all(assetsList.filter(name=>{if(!_webpack.ModuleFilenameHelpers.matchObject.bind(// eslint-disable-next-line no-undefined
undefined,{test:/\.[cm]?js(\?.*)?$/i})(name)){return false;}const res=compilation.getAsset(name);if(!res){console.log(name);return false;}const{info}=res;// Skip double minimize assets from child compilation
if(info.minimized){return false;}return true;}).map(async name=>{const{info,source}=compilation.getAsset(name);const eTag=cache.getLazyHashedEtag(source);const output=await cache.getPromise(name,eTag);if(!output){numberOfAssetsForMinify+=1;}return{name,info,inputSource:source,output,eTag};}));const numberOfWorkers=Math.min(numberOfAssetsForMinify,optimizeOptions.availableNumberOfCores);let initializedWorker;// eslint-disable-next-line consistent-return
const getWorker=()=>{if(initializedWorker){return initializedWorker;}initializedWorker=new _jestWorker.default(path.join(__dirname,'./minify.js'),{numWorkers:numberOfWorkers,enableWorkerThreads:true});initializedWorker.getStdout().pipe(process.stdout);initializedWorker.getStderr().pipe(process.stderr);return initializedWorker;};const limit=(0,_pLimit.default)(numberOfAssetsForMinify>0?numberOfWorkers:Infinity);const scheduledTasks=[];for(const asset of assetsForMinify){scheduledTasks.push(limit(async()=>{const{name,inputSource,info,eTag}=asset;let{output}=asset;if(!output){let input;let inputSourceMap;const{source:sourceFromInputSource,map}=inputSource.sourceAndMap();input=sourceFromInputSource;if(Buffer.isBuffer(input)){input=input.toString();}const options={name,input,inputSourceMap:map,terserOptions:{...this.options.terserOptions}};if(typeof options.terserOptions.module==='undefined'){if(typeof info.javascriptModule!=='undefined'){options.terserOptions.module=info.javascriptModule;}else if(/\.mjs(\?.*)?$/i.test(name)){options.terserOptions.module=true;}else if(/\.cjs(\?.*)?$/i.test(name)){options.terserOptions.module=false;}}try{output=await getWorker().minify(options);}catch(error){compilation.errors.push(buildError(error,name));return;}if(output.map){output.source=new SourceMapSource(output.code,name,output.map,input,/** @type {SourceMapRawSourceMap} */inputSourceMap,true);}else{output.source=new RawSource(output.code);}if(isWebpack5){await cache.storePromise(name,eTag,{source:output.source});}else{await cache.storePromise(name,eTag,{code:output.code,map:output.map,name,input,inputSourceMap});}}/** @type {AssetInfo} */const newInfo={minimized:true};const{source}=output;compilation.updateAsset(name,source,newInfo);}));}await Promise.all(scheduledTasks);if(initializedWorker){await initializedWorker.end();}}/**
   * @param {Compiler} compiler
   * @returns {void}
   */apply(compiler){var _compiler$webpack;const{SourceMapSource,RawSource}=(compiler==null?void 0:(_compiler$webpack=compiler.webpack)==null?void 0:_compiler$webpack.sources)||_webpackSources.default;const{output}=compiler.options;if(typeof this.options.terserOptions.ecma==='undefined'){this.options.terserOptions.ecma=getEcmaVersion(output.environment||{});}const pluginName=this.constructor.name;const availableNumberOfCores=this.options.parallel;compiler.hooks.compilation.tap(pluginName,compilation=>{const cache=isWebpack5?compilation.getCache('TerserWebpackPlugin'):new Webpack4Cache(this.options.cacheDir,{SourceMapSource,RawSource});const handleHashForChunk=(hash,chunk)=>{hash.update('a');};if(isWebpack5){const JSModulesHooks=_webpack.default.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);JSModulesHooks.chunkHash.tap(pluginName,(chunk,hash)=>{if(!chunk.hasRuntime())return;return handleHashForChunk(hash,chunk);});compilation.hooks.processAssets.tapPromise({name:pluginName,stage:compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE},assets=>this.optimize(compilation,assets,{availableNumberOfCores},cache,{SourceMapSource,RawSource}));compilation.hooks.statsPrinter.tap(pluginName,stats=>{stats.hooks.print.for('asset.info.minimized').tap('terser-webpack-plugin',(minimized,{green,formatFlag})=>// eslint-disable-next-line no-undefined
minimized?green(formatFlag('minimized')):undefined);});}else{compilation.mainTemplate.hooks.hashForChunk.tap(pluginName,handleHashForChunk);compilation.chunkTemplate.hooks.hashForChunk.tap(pluginName,handleHashForChunk);compilation.hooks.optimizeChunkAssets.tapPromise(pluginName,assets=>this.optimize(compilation,assets,{availableNumberOfCores},cache,{SourceMapSource,RawSource}));}});}}var _default=TerserPlugin;exports.default=_default;
//# sourceMappingURL=index.js.map