啊鑫
7 天以前 fca192d3c38c5dcfbb6ace8bc71d6078f6a079b2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Ivan Kopeykin @vankop
*/
 
"use strict";
 
const { pathToFileURL } = require("url");
const CommentCompilationWarning = require("../CommentCompilationWarning");
const {
    JAVASCRIPT_MODULE_TYPE_AUTO,
    JAVASCRIPT_MODULE_TYPE_ESM
} = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression");
const { approve } = require("../javascript/JavascriptParserHelpers");
const InnerGraph = require("../optimize/InnerGraph");
const ConstDependency = require("./ConstDependency");
const URLDependency = require("./URLDependency");
 
/** @typedef {import("estree").MemberExpression} MemberExpression */
/** @typedef {import("estree").NewExpression} NewExpressionNode */
/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser")} Parser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */
 
const PLUGIN_NAME = "URLPlugin";
 
class URLPlugin {
    /**
     * @param {Compiler} compiler compiler
     */
    apply(compiler) {
        compiler.hooks.compilation.tap(
            PLUGIN_NAME,
            (compilation, { normalModuleFactory }) => {
                compilation.dependencyFactories.set(URLDependency, normalModuleFactory);
                compilation.dependencyTemplates.set(
                    URLDependency,
                    new URLDependency.Template()
                );
 
                /**
                 * @param {NormalModule} module module
                 * @returns {URL} file url
                 */
                const getUrl = module => pathToFileURL(module.resource);
 
                /**
                 * @param {Parser} parser parser parser
                 * @param {MemberExpression} arg arg
                 * @returns {boolean} true when it is `meta.url`, otherwise false
                 */
                const isMetaUrl = (parser, arg) => {
                    const chain = parser.extractMemberExpressionChain(arg);
 
                    if (
                        chain.members.length !== 1 ||
                        chain.object.type !== "MetaProperty" ||
                        chain.object.meta.name !== "import" ||
                        chain.object.property.name !== "meta" ||
                        chain.members[0] !== "url"
                    )
                        return false;
 
                    return true;
                };
 
                /**
                 * @param {Parser} parser parser parser
                 * @param {JavascriptParserOptions} parserOptions parserOptions
                 * @returns {void}
                 */
                const parserCallback = (parser, parserOptions) => {
                    if (parserOptions.url === false) return;
                    const relative = parserOptions.url === "relative";
 
                    /**
                     * @param {NewExpressionNode} expr expression
                     * @returns {undefined | string} request
                     */
                    const getUrlRequest = expr => {
                        if (expr.arguments.length !== 2) return;
 
                        const [arg1, arg2] = expr.arguments;
 
                        if (
                            arg2.type !== "MemberExpression" ||
                            arg1.type === "SpreadElement"
                        )
                            return;
 
                        if (!isMetaUrl(parser, arg2)) return;
 
                        return parser.evaluateExpression(arg1).asString();
                    };
 
                    parser.hooks.canRename.for("URL").tap(PLUGIN_NAME, approve);
                    parser.hooks.evaluateNewExpression
                        .for("URL")
                        .tap(PLUGIN_NAME, expr => {
                            const request = getUrlRequest(expr);
                            if (!request) return;
                            const url = new URL(request, getUrl(parser.state.module));
 
                            return new BasicEvaluatedExpression()
                                .setString(url.toString())
                                .setRange(/** @type {Range} */ (expr.range));
                        });
                    parser.hooks.new.for("URL").tap(PLUGIN_NAME, _expr => {
                        const expr = /** @type {NewExpressionNode} */ (_expr);
                        const { options: importOptions, errors: commentErrors } =
                            parser.parseCommentOptions(/** @type {Range} */ (expr.range));
 
                        if (commentErrors) {
                            for (const e of commentErrors) {
                                const { comment } = e;
                                parser.state.module.addWarning(
                                    new CommentCompilationWarning(
                                        `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
                                        /** @type {DependencyLocation} */ (comment.loc)
                                    )
                                );
                            }
                        }
 
                        if (importOptions && importOptions.webpackIgnore !== undefined) {
                            if (typeof importOptions.webpackIgnore !== "boolean") {
                                parser.state.module.addWarning(
                                    new UnsupportedFeatureWarning(
                                        `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`,
                                        /** @type {DependencyLocation} */ (expr.loc)
                                    )
                                );
                                return;
                            } else if (importOptions.webpackIgnore) {
                                if (expr.arguments.length !== 2) return;
 
                                const [, arg2] = expr.arguments;
 
                                if (
                                    arg2.type !== "MemberExpression" ||
                                    !isMetaUrl(parser, arg2)
                                )
                                    return;
 
                                const dep = new ConstDependency(
                                    RuntimeGlobals.baseURI,
                                    /** @type {Range} */ (arg2.range),
                                    [RuntimeGlobals.baseURI]
                                );
                                dep.loc = /** @type {DependencyLocation} */ (expr.loc);
                                parser.state.module.addPresentationalDependency(dep);
 
                                return true;
                            }
                        }
 
                        const request = getUrlRequest(expr);
 
                        if (!request) return;
 
                        const [arg1, arg2] = expr.arguments;
                        const dep = new URLDependency(
                            request,
                            [
                                /** @type {Range} */ (arg1.range)[0],
                                /** @type {Range} */ (arg2.range)[1]
                            ],
                            /** @type {Range} */ (expr.range),
                            relative
                        );
                        dep.loc = /** @type {DependencyLocation} */ (expr.loc);
                        parser.state.current.addDependency(dep);
                        InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
                        return true;
                    });
                    parser.hooks.isPure.for("NewExpression").tap(PLUGIN_NAME, _expr => {
                        const expr = /** @type {NewExpressionNode} */ (_expr);
                        const { callee } = expr;
                        if (callee.type !== "Identifier") return;
                        const calleeInfo = parser.getFreeInfoFromVariable(callee.name);
                        if (!calleeInfo || calleeInfo.name !== "URL") return;
 
                        const request = getUrlRequest(expr);
 
                        if (request) return true;
                    });
                };
 
                normalModuleFactory.hooks.parser
                    .for(JAVASCRIPT_MODULE_TYPE_AUTO)
                    .tap(PLUGIN_NAME, parserCallback);
 
                normalModuleFactory.hooks.parser
                    .for(JAVASCRIPT_MODULE_TYPE_ESM)
                    .tap(PLUGIN_NAME, parserCallback);
            }
        );
    }
}
 
module.exports = URLPlugin;