1. 'use strict';
    
  2. 
    
  3. const ClosureCompiler = require('google-closure-compiler').compiler;
    
  4. const {promisify} = require('util');
    
  5. const fs = require('fs');
    
  6. const tmp = require('tmp');
    
  7. const writeFileAsync = promisify(fs.writeFile);
    
  8. 
    
  9. function compile(flags) {
    
  10.   return new Promise((resolve, reject) => {
    
  11.     const closureCompiler = new ClosureCompiler(flags);
    
  12.     closureCompiler.run(function (exitCode, stdOut, stdErr) {
    
  13.       if (!stdErr) {
    
  14.         resolve(stdOut);
    
  15.       } else {
    
  16.         reject(new Error(stdErr));
    
  17.       }
    
  18.     });
    
  19.   });
    
  20. }
    
  21. 
    
  22. module.exports = function closure(flags = {}) {
    
  23.   return {
    
  24.     name: 'scripts/rollup/plugins/closure-plugin',
    
  25.     async renderChunk(code) {
    
  26.       const inputFile = tmp.fileSync();
    
  27.       const tempPath = inputFile.name;
    
  28.       flags = Object.assign({}, flags, {js: tempPath});
    
  29.       await writeFileAsync(tempPath, code, 'utf8');
    
  30.       const compiledCode = await compile(flags);
    
  31.       inputFile.removeCallback();
    
  32.       return {code: compiledCode};
    
  33.     },
    
  34.   };
    
  35. };