JsonParser.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const parseJson = require("json-parse-even-better-errors");
  7. const Parser = require("../Parser");
  8. const JsonExportsDependency = require("../dependencies/JsonExportsDependency");
  9. const JsonData = require("./JsonData");
  10. /** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */
  11. /** @typedef {import("../Parser").ParserState} ParserState */
  12. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  13. class JsonParser extends Parser {
  14. /**
  15. * @param {JsonModulesPluginParserOptions} options parser options
  16. */
  17. constructor(options) {
  18. super();
  19. this.options = options || {};
  20. }
  21. /**
  22. * @param {string | Buffer | PreparsedAst} source the source to parse
  23. * @param {ParserState} state the parser state
  24. * @returns {ParserState} the parser state
  25. */
  26. parse(source, state) {
  27. if (Buffer.isBuffer(source)) {
  28. source = source.toString("utf-8");
  29. }
  30. /** @type {JsonModulesPluginParserOptions["parse"]} */
  31. const parseFn =
  32. typeof this.options.parse === "function" ? this.options.parse : parseJson;
  33. const data =
  34. typeof source === "object"
  35. ? source
  36. : parseFn(source[0] === "\ufeff" ? source.slice(1) : source);
  37. const jsonData = new JsonData(data);
  38. state.module.buildInfo.jsonData = jsonData;
  39. state.module.buildInfo.strict = true;
  40. state.module.buildMeta.exportsType = "default";
  41. state.module.buildMeta.defaultObject =
  42. typeof data === "object" ? "redirect-warn" : false;
  43. state.module.addDependency(new JsonExportsDependency(jsonData));
  44. return state;
  45. }
  46. }
  47. module.exports = JsonParser;