JsonParser.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Parser = require("../Parser");
  7. const JsonExportsDependency = require("../dependencies/JsonExportsDependency");
  8. const parseJson = require("../util/parseJson");
  9. const JsonData = require("./JsonData");
  10. /** @import { JsonParserOptions } from "../../declarations/WebpackOptions" */
  11. /** @import { JsonModuleBuildInfo } from "./JsonModule" */
  12. /** @import { BuildMeta } from "../Module" */
  13. /** @import { ParserState, PreparsedAst } from "../Parser" */
  14. /** @import { JsonValue } from "../util/fs" */
  15. /** @typedef {(input: string) => Buffer | JsonValue} ParseFn */
  16. /**
  17. * Defines the function returning type used by this module.
  18. * @template T
  19. * @typedef {import("../util/memoize").FunctionReturning<T>} FunctionReturning
  20. */
  21. class JsonParser extends Parser {
  22. /**
  23. * Creates an instance of JsonParser.
  24. * @param {JsonParserOptions} options parser options
  25. */
  26. constructor(options = {}) {
  27. super();
  28. /** @type {JsonParserOptions} */
  29. this.options = options;
  30. }
  31. /**
  32. * Parses the provided source and updates the parser state.
  33. * @param {string | Buffer | PreparsedAst} source the source to parse
  34. * @param {ParserState} state the parser state
  35. * @returns {ParserState} the parser state
  36. */
  37. parse(source, state) {
  38. if (Buffer.isBuffer(source)) {
  39. source = source.toString("utf8");
  40. }
  41. const parseFn =
  42. typeof this.options.parse === "function" ? this.options.parse : parseJson;
  43. /** @type {Buffer | JsonValue | undefined} */
  44. const data =
  45. typeof source === "object"
  46. ? source
  47. : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source);
  48. const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data));
  49. const buildInfo = /** @type {JsonModuleBuildInfo} */ (
  50. state.module.buildInfo
  51. );
  52. buildInfo.jsonData = jsonData;
  53. buildInfo.strict = true;
  54. const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
  55. buildMeta.exportsType = "default";
  56. buildMeta.defaultObject =
  57. typeof data === "object"
  58. ? this.options.namedExports === false
  59. ? false
  60. : this.options.namedExports === true
  61. ? "redirect"
  62. : "redirect-warn"
  63. : false;
  64. state.module.addDependency(
  65. new JsonExportsDependency(
  66. jsonData,
  67. /** @type {number} */
  68. (this.options.exportsDepth)
  69. )
  70. );
  71. return state;
  72. }
  73. }
  74. module.exports = JsonParser;