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