| | |
| | | |
| | | const Parser = require("../Parser"); |
| | | const JsonExportsDependency = require("../dependencies/JsonExportsDependency"); |
| | | const memoize = require("../util/memoize"); |
| | | const parseJson = require("../util/parseJson"); |
| | | const JsonData = require("./JsonData"); |
| | | |
| | | /** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ |
| | |
| | | |
| | | /** @typedef {(input: string) => Buffer | JsonValue} ParseFn */ |
| | | |
| | | const getParseJson = memoize(() => require("json-parse-even-better-errors")); |
| | | /** |
| | | * Defines the function returning type used by this module. |
| | | * @template T |
| | | * @typedef {import("../util/memoize").FunctionReturning<T>} FunctionReturning |
| | | */ |
| | | |
| | | class JsonParser extends Parser { |
| | | /** |
| | | * Creates an instance of JsonParser. |
| | | * @param {JsonModulesPluginParserOptions} options parser options |
| | | */ |
| | | constructor(options) { |
| | | constructor(options = {}) { |
| | | super(); |
| | | this.options = options || {}; |
| | | /** @type {JsonModulesPluginParserOptions} */ |
| | | this.options = options; |
| | | } |
| | | |
| | | /** |
| | | * Parses the provided source and updates the parser state. |
| | | * @param {string | Buffer | PreparsedAst} source the source to parse |
| | | * @param {ParserState} state the parser state |
| | | * @returns {ParserState} the parser state |
| | |
| | | source = source.toString("utf8"); |
| | | } |
| | | |
| | | /** @type {ParseFn} */ |
| | | /** @type {typeof parseJson} */ |
| | | const parseFn = |
| | | typeof this.options.parse === "function" |
| | | ? this.options.parse |
| | | : getParseJson(); |
| | | typeof this.options.parse === "function" ? this.options.parse : parseJson; |
| | | /** @type {Buffer | JsonValue | undefined} */ |
| | | let data; |
| | | try { |
| | |
| | | : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source); |
| | | } catch (err) { |
| | | throw new Error( |
| | | `Cannot parse JSON: ${/** @type {Error} */ (err).message}` |
| | | `Cannot parse JSON: ${/** @type {Error} */ (err).message}`, |
| | | { cause: err } |
| | | ); |
| | | } |
| | | const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data)); |