// @ts-check
const { minify } = require('terser');

const terserOptions = {
  sourceMap: true,
  mangle: {
    // Pass true to work around the Safari 10 loop iterator bug "Cannot
    // declare a let variable twice".
    // https://bugs.webkit.org/show_bug.cgi?id=171041
    safari10: true,
  },
  // Set this option to true to work around the Safari 10/11 await bug.
  // https://bugs.webkit.org/show_bug.cgi?id=176685
  output: {
    safari10: true,
  },
};

module.exports = function rollupMinify() {
  /**
   * @type {import('rollup').RenderChunkHook}
   */
  const renderChunk = async function renderChunk(inputCode) {
    const { code, map } = await minify(inputCode, terserOptions);

    if (typeof code === 'undefined') {
      return { code: '' };
    }

    return { code, map };
  };

  return {
    name: 'minify',
    renderChunk,
  };
};
