AssetParser.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Yuta Hiroto @hiroppy
  4. */
  5. "use strict";
  6. const Parser = require("../Parser");
  7. /** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */
  8. /** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
  9. /** @typedef {import("../Module")} Module */
  10. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  11. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  12. /** @typedef {import("../Parser").ParserState} ParserState */
  13. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  14. /** @typedef {((source: string | Buffer, context: { filename: string, module: Module }) => boolean)} AssetParserDataUrlFunction */
  15. class AssetParser extends Parser {
  16. /**
  17. * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl
  18. */
  19. constructor(dataUrlCondition) {
  20. super();
  21. /** @type {AssetParserOptions["dataUrlCondition"] | boolean} */
  22. this.dataUrlCondition = dataUrlCondition;
  23. }
  24. /**
  25. * @param {string | Buffer | PreparsedAst} source the source to parse
  26. * @param {ParserState} state the parser state
  27. * @returns {ParserState} the parser state
  28. */
  29. parse(source, state) {
  30. if (typeof source === "object" && !Buffer.isBuffer(source)) {
  31. throw new Error("AssetParser doesn't accept preparsed AST");
  32. }
  33. const buildInfo =
  34. /** @type {BuildInfo} */
  35. (state.module.buildInfo);
  36. buildInfo.strict = true;
  37. const buildMeta =
  38. /** @type {BuildMeta} */
  39. (state.module.buildMeta);
  40. buildMeta.exportsType = "default";
  41. buildMeta.defaultObject = false;
  42. if (typeof this.dataUrlCondition === "function") {
  43. buildInfo.dataUrl = this.dataUrlCondition(source, {
  44. filename: /** @type {string} */ (state.module.getResource()),
  45. module: state.module
  46. });
  47. } else if (typeof this.dataUrlCondition === "boolean") {
  48. buildInfo.dataUrl = this.dataUrlCondition;
  49. } else if (
  50. this.dataUrlCondition &&
  51. typeof this.dataUrlCondition === "object"
  52. ) {
  53. buildInfo.dataUrl =
  54. Buffer.byteLength(source) <=
  55. /** @type {NonNullable<AssetParserDataUrlOptions["maxSize"]>} */
  56. (this.dataUrlCondition.maxSize);
  57. } else {
  58. throw new Error("Unexpected dataUrlCondition type");
  59. }
  60. return state;
  61. }
  62. }
  63. module.exports = AssetParser;