utils.js 21.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
"use strict";

/** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */

/** @typedef {import("terser").FormatOptions} TerserFormatOptions */

/** @typedef {import("terser").MinifyOptions} TerserOptions */

/** @typedef {import("terser").CompressOptions} TerserCompressOptions */

/** @typedef {import("terser").ECMA} TerserECMA */

/** @typedef {import("./index.js").ExtractCommentsOptions} ExtractCommentsOptions */

/** @typedef {import("./index.js").ExtractCommentsFunction} ExtractCommentsFunction */

/** @typedef {import("./index.js").ExtractCommentsCondition} ExtractCommentsCondition */

/** @typedef {import("./index.js").Input} Input */

/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */

/** @typedef {import("./index.js").PredefinedOptions} PredefinedOptions */

/** @typedef {import("./index.js").CustomOptions} CustomOptions */

/**
 * @typedef {Array<string>} ExtractedComments
 */
const notSettled = Symbol(`not-settled`);
/**
 * @template T
 * @typedef {() => Promise<T>} Task
 */

/**
 * Run tasks with limited concurency.
 * @template T
 * @param {number} limit - Limit of tasks that run at once.
 * @param {Task<T>[]} tasks - List of tasks to run.
 * @returns {Promise<T[]>} A promise that fulfills to an array of the results
 */

function throttleAll(limit, tasks) {
  if (!Number.isInteger(limit) || limit < 1) {
    throw new TypeError(`Expected \`limit\` to be a finite number > 0, got \`${limit}\` (${typeof limit})`);
  }

  if (!Array.isArray(tasks) || !tasks.every(task => typeof task === `function`)) {
    throw new TypeError(`Expected \`tasks\` to be a list of functions returning a promise`);
  }

  return new Promise((resolve, reject) => {
    const result = Array(tasks.length).fill(notSettled);
    const entries = tasks.entries();

    const next = () => {
      const {
        done,
        value
      } = entries.next();

      if (done) {
        const isLast = !result.includes(notSettled);
        if (isLast) resolve(
        /** @type{T[]} **/
        result);
        return;
      }

      const [index, task] = value;
      /**
       * @param {T} x
       */

      const onFulfilled = x => {
        result[index] = x;
        next();
      };

      task().then(onFulfilled, reject);
    };

    Array(limit).fill(0).forEach(next);
  });
}
/* istanbul ignore next */

/**
 * @param {Input} input
 * @param {SourceMapInput | undefined} sourceMap
 * @param {PredefinedOptions & CustomOptions} minimizerOptions
 * @param {ExtractCommentsOptions | undefined} extractComments
 * @return {Promise<MinimizedResult>}
 */


async function terserMinify(input, sourceMap, minimizerOptions, extractComments) {
  /**
   * @param {any} value
   * @returns {boolean}
   */
  const isObject = value => {
    const type = typeof value;
    return value != null && (type === "object" || type === "function");
  };
  /**
   * @param {TerserOptions & { sourceMap: undefined } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })} terserOptions
   * @param {ExtractedComments} extractedComments
   * @returns {ExtractCommentsFunction}
   */


  const buildComments = (terserOptions, extractedComments) => {
    /** @type {{ [index: string]: ExtractCommentsCondition }} */
    const condition = {};
    let comments;

    if (terserOptions.format) {
      ({
        comments
      } = terserOptions.format);
    } else if (terserOptions.output) {
      ({
        comments
      } = terserOptions.output);
    }

    condition.preserve = typeof comments !== "undefined" ? comments : false;

    if (typeof extractComments === "boolean" && extractComments) {
      condition.extract = "some";
    } else if (typeof extractComments === "string" || extractComments instanceof RegExp) {
      condition.extract = extractComments;
    } else if (typeof extractComments === "function") {
      condition.extract = extractComments;
    } else if (extractComments && isObject(extractComments)) {
      condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some";
    } else {
      // No extract
      // Preserve using "commentsOpts" or "some"
      condition.preserve = typeof comments !== "undefined" ? comments : "some";
      condition.extract = false;
    } // Ensure that both conditions are functions


    ["preserve", "extract"].forEach(key => {
      /** @type {undefined | string} */
      let regexStr;
      /** @type {undefined | RegExp} */

      let regex;

      switch (typeof condition[key]) {
        case "boolean":
          condition[key] = condition[key] ? () => true : () => false;
          break;

        case "function":
          break;

        case "string":
          if (condition[key] === "all") {
            condition[key] = () => true;

            break;
          }

          if (condition[key] === "some") {
            condition[key] =
            /** @type {ExtractCommentsFunction} */
            (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value);

            break;
          }

          regexStr =
          /** @type {string} */
          condition[key];

          condition[key] =
          /** @type {ExtractCommentsFunction} */
          (astNode, comment) => new RegExp(
          /** @type {string} */
          regexStr).test(comment.value);

          break;

        default:
          regex =
          /** @type {RegExp} */
          condition[key];

          condition[key] =
          /** @type {ExtractCommentsFunction} */
          (astNode, comment) =>
          /** @type {RegExp} */
          regex.test(comment.value);

      }
    }); // Redefine the comments function to extract and preserve
    // comments according to the two conditions

    return (astNode, comment) => {
      if (
      /** @type {{ extract: ExtractCommentsFunction }} */
      condition.extract(astNode, comment)) {
        const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments

        if (!extractedComments.includes(commentText)) {
          extractedComments.push(commentText);
        }
      }

      return (
        /** @type {{ preserve: ExtractCommentsFunction }} */
        condition.preserve(astNode, comment)
      );
    };
  };
  /**
   * @param {PredefinedOptions & TerserOptions} [terserOptions={}]
   * @returns {TerserOptions & { sourceMap: undefined } & { compress: TerserCompressOptions } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })}
   */


  const buildTerserOptions = (terserOptions = {}) => {
    // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
    return { ...terserOptions,
      compress: typeof terserOptions.compress === "boolean" ? terserOptions.compress ? {} : false : { ...terserOptions.compress
      },
      // ecma: terserOptions.ecma,
      // ie8: terserOptions.ie8,
      // keep_classnames: terserOptions.keep_classnames,
      // keep_fnames: terserOptions.keep_fnames,
      mangle: terserOptions.mangle == null ? true : typeof terserOptions.mangle === "boolean" ? terserOptions.mangle : { ...terserOptions.mangle
      },
      // module: terserOptions.module,
      // nameCache: { ...terserOptions.toplevel },
      // the `output` option is deprecated
      ...(terserOptions.format ? {
        format: {
          beautify: false,
          ...terserOptions.format
        }
      } : {
        output: {
          beautify: false,
          ...terserOptions.output
        }
      }),
      parse: { ...terserOptions.parse
      },
      // safari10: terserOptions.safari10,
      // Ignoring sourceMap from options
      // eslint-disable-next-line no-undefined
      sourceMap: undefined // toplevel: terserOptions.toplevel

    };
  }; // eslint-disable-next-line global-require


  const {
    minify
  } = require("terser"); // Copy `terser` options


  const terserOptions = buildTerserOptions(minimizerOptions); // Let terser generate a SourceMap

  if (sourceMap) {
    // @ts-ignore
    terserOptions.sourceMap = {
      asObject: true
    };
  }
  /** @type {ExtractedComments} */


  const extractedComments = [];

  if (terserOptions.output) {
    terserOptions.output.comments = buildComments(terserOptions, extractedComments);
  } else if (terserOptions.format) {
    terserOptions.format.comments = buildComments(terserOptions, extractedComments);
  }

  if (terserOptions.compress) {
    // More optimizations
    if (typeof terserOptions.compress.ecma === "undefined") {
      terserOptions.compress.ecma = terserOptions.ecma;
    } // https://github.com/webpack/webpack/issues/16135


    if (terserOptions.ecma === 5 && typeof terserOptions.compress.arrows === "undefined") {
      terserOptions.compress.arrows = false;
    }
  }

  const [[filename, code]] = Object.entries(input);
  const result = await minify({
    [filename]: code
  }, terserOptions);
  return {
    code:
    /** @type {string} **/
    result.code,
    // @ts-ignore
    // eslint-disable-next-line no-undefined
    map: result.map ?
    /** @type {SourceMapInput} **/
    result.map : undefined,
    extractedComments
  };
}
/**
 * @returns {string | undefined}
 */


terserMinify.getMinimizerVersion = () => {
  let packageJson;

  try {
    // eslint-disable-next-line global-require
    packageJson = require("terser/package.json");
  } catch (error) {// Ignore
  }

  return packageJson && packageJson.version;
};
/* istanbul ignore next */

/**
 * @param {Input} input
 * @param {SourceMapInput | undefined} sourceMap
 * @param {PredefinedOptions & CustomOptions} minimizerOptions
 * @param {ExtractCommentsOptions | undefined} extractComments
 * @return {Promise<MinimizedResult>}
 */


async function uglifyJsMinify(input, sourceMap, minimizerOptions, extractComments) {
  /**
   * @param {any} value
   * @returns {boolean}
   */
  const isObject = value => {
    const type = typeof value;
    return value != null && (type === "object" || type === "function");
  };
  /**
   * @param {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}} uglifyJsOptions
   * @param {ExtractedComments} extractedComments
   * @returns {ExtractCommentsFunction}
   */


  const buildComments = (uglifyJsOptions, extractedComments) => {
    /** @type {{ [index: string]: ExtractCommentsCondition }} */
    const condition = {};
    const {
      comments
    } = uglifyJsOptions.output;
    condition.preserve = typeof comments !== "undefined" ? comments : false;

    if (typeof extractComments === "boolean" && extractComments) {
      condition.extract = "some";
    } else if (typeof extractComments === "string" || extractComments instanceof RegExp) {
      condition.extract = extractComments;
    } else if (typeof extractComments === "function") {
      condition.extract = extractComments;
    } else if (extractComments && isObject(extractComments)) {
      condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some";
    } else {
      // No extract
      // Preserve using "commentsOpts" or "some"
      condition.preserve = typeof comments !== "undefined" ? comments : "some";
      condition.extract = false;
    } // Ensure that both conditions are functions


    ["preserve", "extract"].forEach(key => {
      /** @type {undefined | string} */
      let regexStr;
      /** @type {undefined | RegExp} */

      let regex;

      switch (typeof condition[key]) {
        case "boolean":
          condition[key] = condition[key] ? () => true : () => false;
          break;

        case "function":
          break;

        case "string":
          if (condition[key] === "all") {
            condition[key] = () => true;

            break;
          }

          if (condition[key] === "some") {
            condition[key] =
            /** @type {ExtractCommentsFunction} */
            (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value);

            break;
          }

          regexStr =
          /** @type {string} */
          condition[key];

          condition[key] =
          /** @type {ExtractCommentsFunction} */
          (astNode, comment) => new RegExp(
          /** @type {string} */
          regexStr).test(comment.value);

          break;

        default:
          regex =
          /** @type {RegExp} */
          condition[key];

          condition[key] =
          /** @type {ExtractCommentsFunction} */
          (astNode, comment) =>
          /** @type {RegExp} */
          regex.test(comment.value);

      }
    }); // Redefine the comments function to extract and preserve
    // comments according to the two conditions

    return (astNode, comment) => {
      if (
      /** @type {{ extract: ExtractCommentsFunction }} */
      condition.extract(astNode, comment)) {
        const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments

        if (!extractedComments.includes(commentText)) {
          extractedComments.push(commentText);
        }
      }

      return (
        /** @type {{ preserve: ExtractCommentsFunction }} */
        condition.preserve(astNode, comment)
      );
    };
  };
  /**
   * @param {PredefinedOptions & import("uglify-js").MinifyOptions} [uglifyJsOptions={}]
   * @returns {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}}
   */


  const buildUglifyJsOptions = (uglifyJsOptions = {}) => {
    // eslint-disable-next-line no-param-reassign
    delete minimizerOptions.ecma; // eslint-disable-next-line no-param-reassign

    delete minimizerOptions.module; // Need deep copy objects to avoid https://github.com/terser/terser/issues/366

    return { ...uglifyJsOptions,
      // warnings: uglifyJsOptions.warnings,
      parse: { ...uglifyJsOptions.parse
      },
      compress: typeof uglifyJsOptions.compress === "boolean" ? uglifyJsOptions.compress : { ...uglifyJsOptions.compress
      },
      mangle: uglifyJsOptions.mangle == null ? true : typeof uglifyJsOptions.mangle === "boolean" ? uglifyJsOptions.mangle : { ...uglifyJsOptions.mangle
      },
      output: {
        beautify: false,
        ...uglifyJsOptions.output
      },
      // Ignoring sourceMap from options
      // eslint-disable-next-line no-undefined
      sourceMap: undefined // toplevel: uglifyJsOptions.toplevel
      // nameCache: { ...uglifyJsOptions.toplevel },
      // ie8: uglifyJsOptions.ie8,
      // keep_fnames: uglifyJsOptions.keep_fnames,

    };
  }; // eslint-disable-next-line global-require, import/no-extraneous-dependencies


  const {
    minify
  } = require("uglify-js"); // Copy `uglify-js` options


  const uglifyJsOptions = buildUglifyJsOptions(minimizerOptions); // Let terser generate a SourceMap

  if (sourceMap) {
    // @ts-ignore
    uglifyJsOptions.sourceMap = true;
  }
  /** @type {ExtractedComments} */


  const extractedComments = []; // @ts-ignore

  uglifyJsOptions.output.comments = buildComments(uglifyJsOptions, extractedComments);
  const [[filename, code]] = Object.entries(input);
  const result = await minify({
    [filename]: code
  }, uglifyJsOptions);
  return {
    code: result.code,
    // eslint-disable-next-line no-undefined
    map: result.map ? JSON.parse(result.map) : undefined,
    errors: result.error ? [result.error] : [],
    warnings: result.warnings || [],
    extractedComments
  };
}
/**
 * @returns {string | undefined}
 */


uglifyJsMinify.getMinimizerVersion = () => {
  let packageJson;

  try {
    // eslint-disable-next-line global-require, import/no-extraneous-dependencies
    packageJson = require("uglify-js/package.json");
  } catch (error) {// Ignore
  }

  return packageJson && packageJson.version;
};
/* istanbul ignore next */

/**
 * @param {Input} input
 * @param {SourceMapInput | undefined} sourceMap
 * @param {PredefinedOptions & CustomOptions} minimizerOptions
 * @return {Promise<MinimizedResult>}
 */


async function swcMinify(input, sourceMap, minimizerOptions) {
  /**
   * @param {PredefinedOptions & import("@swc/core").JsMinifyOptions} [swcOptions={}]
   * @returns {import("@swc/core").JsMinifyOptions & { sourceMap: undefined } & { compress: import("@swc/core").TerserCompressOptions }}
   */
  const buildSwcOptions = (swcOptions = {}) => {
    // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
    return { ...swcOptions,
      compress: typeof swcOptions.compress === "boolean" ? swcOptions.compress ? {} : false : { ...swcOptions.compress
      },
      mangle: swcOptions.mangle == null ? true : typeof swcOptions.mangle === "boolean" ? swcOptions.mangle : { ...swcOptions.mangle
      },
      // ecma: swcOptions.ecma,
      // keep_classnames: swcOptions.keep_classnames,
      // keep_fnames: swcOptions.keep_fnames,
      // module: swcOptions.module,
      // safari10: swcOptions.safari10,
      // toplevel: swcOptions.toplevel
      // eslint-disable-next-line no-undefined
      sourceMap: undefined
    };
  }; // eslint-disable-next-line import/no-extraneous-dependencies, global-require


  const swc = require("@swc/core"); // Copy `swc` options


  const swcOptions = buildSwcOptions(minimizerOptions); // Let `swc` generate a SourceMap

  if (sourceMap) {
    // @ts-ignore
    swcOptions.sourceMap = true;
  }

  if (swcOptions.compress) {
    // More optimizations
    if (typeof swcOptions.compress.ecma === "undefined") {
      swcOptions.compress.ecma = swcOptions.ecma;
    } // https://github.com/webpack/webpack/issues/16135


    if (swcOptions.ecma === 5 && typeof swcOptions.compress.arrows === "undefined") {
      swcOptions.compress.arrows = false;
    }
  }

  const [[filename, code]] = Object.entries(input);
  const result = await swc.minify(code, swcOptions);
  let map;

  if (result.map) {
    map = JSON.parse(result.map); // TODO workaround for swc because `filename` is not preset as in `swc` signature as for `terser`

    map.sources = [filename];
    delete map.sourcesContent;
  }

  return {
    code: result.code,
    map
  };
}
/**
 * @returns {string | undefined}
 */


swcMinify.getMinimizerVersion = () => {
  let packageJson;

  try {
    // eslint-disable-next-line global-require, import/no-extraneous-dependencies
    packageJson = require("@swc/core/package.json");
  } catch (error) {// Ignore
  }

  return packageJson && packageJson.version;
};
/* istanbul ignore next */

/**
 * @param {Input} input
 * @param {SourceMapInput | undefined} sourceMap
 * @param {PredefinedOptions & CustomOptions} minimizerOptions
 * @return {Promise<MinimizedResult>}
 */


async function esbuildMinify(input, sourceMap, minimizerOptions) {
  /**
   * @param {PredefinedOptions & import("esbuild").TransformOptions} [esbuildOptions={}]
   * @returns {import("esbuild").TransformOptions}
   */
  const buildEsbuildOptions = (esbuildOptions = {}) => {
    // eslint-disable-next-line no-param-reassign
    delete esbuildOptions.ecma;

    if (esbuildOptions.module) {
      // eslint-disable-next-line no-param-reassign
      esbuildOptions.format = "esm";
    } // eslint-disable-next-line no-param-reassign


    delete esbuildOptions.module; // Need deep copy objects to avoid https://github.com/terser/terser/issues/366

    return {
      minify: true,
      legalComments: "inline",
      ...esbuildOptions,
      sourcemap: false
    };
  }; // eslint-disable-next-line import/no-extraneous-dependencies, global-require


  const esbuild = require("esbuild"); // Copy `esbuild` options


  const esbuildOptions = buildEsbuildOptions(minimizerOptions); // Let `esbuild` generate a SourceMap

  if (sourceMap) {
    esbuildOptions.sourcemap = true;
    esbuildOptions.sourcesContent = false;
  }

  const [[filename, code]] = Object.entries(input);
  esbuildOptions.sourcefile = filename;
  const result = await esbuild.transform(code, esbuildOptions);
  return {
    code: result.code,
    // eslint-disable-next-line no-undefined
    map: result.map ? JSON.parse(result.map) : undefined,
    warnings: result.warnings.length > 0 ? result.warnings.map(item => {
      return {
        name: "Warning",
        source: item.location && item.location.file,
        line: item.location && item.location.line,
        column: item.location && item.location.column,
        plugin: item.pluginName,
        message: `${item.text}${item.detail ? `\nDetails:\n${item.detail}` : ""}${item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : ""}`
      };
    }) : []
  };
}
/**
 * @returns {string | undefined}
 */


esbuildMinify.getMinimizerVersion = () => {
  let packageJson;

  try {
    // eslint-disable-next-line global-require, import/no-extraneous-dependencies
    packageJson = require("esbuild/package.json");
  } catch (error) {// Ignore
  }

  return packageJson && packageJson.version;
};

module.exports = {
  throttleAll,
  terserMinify,
  uglifyJsMinify,
  swcMinify,
  esbuildMinify
};