1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Yuta Hiroto @hiroppy
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const Parser = require("../Parser");
|
---|
9 |
|
---|
10 | /** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */
|
---|
11 | /** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
|
---|
12 | /** @typedef {import("../Module").BuildInfo} BuildInfo */
|
---|
13 | /** @typedef {import("../Module").BuildMeta} BuildMeta */
|
---|
14 | /** @typedef {import("../Parser").ParserState} ParserState */
|
---|
15 | /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
|
---|
16 |
|
---|
17 | class AssetParser extends Parser {
|
---|
18 | /**
|
---|
19 | * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl
|
---|
20 | */
|
---|
21 | constructor(dataUrlCondition) {
|
---|
22 | super();
|
---|
23 | this.dataUrlCondition = dataUrlCondition;
|
---|
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 (typeof source === "object" && !Buffer.isBuffer(source)) {
|
---|
33 | throw new Error("AssetParser doesn't accept preparsed AST");
|
---|
34 | }
|
---|
35 |
|
---|
36 | const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo);
|
---|
37 | buildInfo.strict = true;
|
---|
38 | const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
|
---|
39 | buildMeta.exportsType = "default";
|
---|
40 | buildMeta.defaultObject = false;
|
---|
41 |
|
---|
42 | if (typeof this.dataUrlCondition === "function") {
|
---|
43 | buildInfo.dataUrl = this.dataUrlCondition(source, {
|
---|
44 | filename: state.module.matchResource || state.module.resource,
|
---|
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 |
|
---|
61 | return state;
|
---|
62 | }
|
---|
63 | }
|
---|
64 |
|
---|
65 | module.exports = AssetParser;
|
---|