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 { fileURLToPath } = require("url");
|
---|
9 | const CommentCompilationWarning = require("../CommentCompilationWarning");
|
---|
10 | const RuntimeGlobals = require("../RuntimeGlobals");
|
---|
11 | const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
|
---|
12 | const WebpackError = require("../WebpackError");
|
---|
13 | const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression");
|
---|
14 | const {
|
---|
15 | evaluateToIdentifier,
|
---|
16 | evaluateToString,
|
---|
17 | expressionIsUnsupported,
|
---|
18 | toConstantDependency
|
---|
19 | } = require("../javascript/JavascriptParserHelpers");
|
---|
20 | const CommonJsFullRequireDependency = require("./CommonJsFullRequireDependency");
|
---|
21 | const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency");
|
---|
22 | const CommonJsRequireDependency = require("./CommonJsRequireDependency");
|
---|
23 | const ConstDependency = require("./ConstDependency");
|
---|
24 | const ContextDependencyHelpers = require("./ContextDependencyHelpers");
|
---|
25 | const LocalModuleDependency = require("./LocalModuleDependency");
|
---|
26 | const { getLocalModule } = require("./LocalModulesHelpers");
|
---|
27 | const RequireHeaderDependency = require("./RequireHeaderDependency");
|
---|
28 | const RequireResolveContextDependency = require("./RequireResolveContextDependency");
|
---|
29 | const RequireResolveDependency = require("./RequireResolveDependency");
|
---|
30 | const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
|
---|
31 |
|
---|
32 | /** @typedef {import("estree").CallExpression} CallExpression */
|
---|
33 | /** @typedef {import("estree").Expression} Expression */
|
---|
34 | /** @typedef {import("estree").NewExpression} NewExpression */
|
---|
35 | /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
|
---|
36 | /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
|
---|
37 | /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
|
---|
38 | /** @typedef {import("../javascript/JavascriptParser").ImportSource} ImportSource */
|
---|
39 | /** @typedef {import("../javascript/JavascriptParser").Range} Range */
|
---|
40 |
|
---|
41 | const createRequireSpecifierTag = Symbol("createRequire");
|
---|
42 | const createdRequireIdentifierTag = Symbol("createRequire()");
|
---|
43 |
|
---|
44 | class CommonJsImportsParserPlugin {
|
---|
45 | /**
|
---|
46 | * @param {JavascriptParserOptions} options parser options
|
---|
47 | */
|
---|
48 | constructor(options) {
|
---|
49 | this.options = options;
|
---|
50 | }
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * @param {JavascriptParser} parser the parser
|
---|
54 | * @returns {void}
|
---|
55 | */
|
---|
56 | apply(parser) {
|
---|
57 | const options = this.options;
|
---|
58 |
|
---|
59 | const getContext = () => {
|
---|
60 | if (parser.currentTagData) {
|
---|
61 | const { context } = parser.currentTagData;
|
---|
62 | return context;
|
---|
63 | }
|
---|
64 | };
|
---|
65 |
|
---|
66 | // #region metadata
|
---|
67 | /**
|
---|
68 | * @param {string} expression expression
|
---|
69 | * @param {() => string[]} getMembers get members
|
---|
70 | */
|
---|
71 | const tapRequireExpression = (expression, getMembers) => {
|
---|
72 | parser.hooks.typeof
|
---|
73 | .for(expression)
|
---|
74 | .tap(
|
---|
75 | "CommonJsImportsParserPlugin",
|
---|
76 | toConstantDependency(parser, JSON.stringify("function"))
|
---|
77 | );
|
---|
78 | parser.hooks.evaluateTypeof
|
---|
79 | .for(expression)
|
---|
80 | .tap("CommonJsImportsParserPlugin", evaluateToString("function"));
|
---|
81 | parser.hooks.evaluateIdentifier
|
---|
82 | .for(expression)
|
---|
83 | .tap(
|
---|
84 | "CommonJsImportsParserPlugin",
|
---|
85 | evaluateToIdentifier(expression, "require", getMembers, true)
|
---|
86 | );
|
---|
87 | };
|
---|
88 | /**
|
---|
89 | * @param {string | symbol} tag tag
|
---|
90 | */
|
---|
91 | const tapRequireExpressionTag = tag => {
|
---|
92 | parser.hooks.typeof
|
---|
93 | .for(tag)
|
---|
94 | .tap(
|
---|
95 | "CommonJsImportsParserPlugin",
|
---|
96 | toConstantDependency(parser, JSON.stringify("function"))
|
---|
97 | );
|
---|
98 | parser.hooks.evaluateTypeof
|
---|
99 | .for(tag)
|
---|
100 | .tap("CommonJsImportsParserPlugin", evaluateToString("function"));
|
---|
101 | };
|
---|
102 | tapRequireExpression("require", () => []);
|
---|
103 | tapRequireExpression("require.resolve", () => ["resolve"]);
|
---|
104 | tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]);
|
---|
105 | // #endregion
|
---|
106 |
|
---|
107 | // Weird stuff //
|
---|
108 | parser.hooks.assign
|
---|
109 | .for("require")
|
---|
110 | .tap("CommonJsImportsParserPlugin", expr => {
|
---|
111 | // to not leak to global "require", we need to define a local require here.
|
---|
112 | const dep = new ConstDependency("var require;", 0);
|
---|
113 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
114 | parser.state.module.addPresentationalDependency(dep);
|
---|
115 | return true;
|
---|
116 | });
|
---|
117 |
|
---|
118 | // #region Unsupported
|
---|
119 | parser.hooks.expression
|
---|
120 | .for("require.main")
|
---|
121 | .tap(
|
---|
122 | "CommonJsImportsParserPlugin",
|
---|
123 | expressionIsUnsupported(
|
---|
124 | parser,
|
---|
125 | "require.main is not supported by webpack."
|
---|
126 | )
|
---|
127 | );
|
---|
128 | parser.hooks.call
|
---|
129 | .for("require.main.require")
|
---|
130 | .tap(
|
---|
131 | "CommonJsImportsParserPlugin",
|
---|
132 | expressionIsUnsupported(
|
---|
133 | parser,
|
---|
134 | "require.main.require is not supported by webpack."
|
---|
135 | )
|
---|
136 | );
|
---|
137 | parser.hooks.expression
|
---|
138 | .for("module.parent.require")
|
---|
139 | .tap(
|
---|
140 | "CommonJsImportsParserPlugin",
|
---|
141 | expressionIsUnsupported(
|
---|
142 | parser,
|
---|
143 | "module.parent.require is not supported by webpack."
|
---|
144 | )
|
---|
145 | );
|
---|
146 | parser.hooks.call
|
---|
147 | .for("module.parent.require")
|
---|
148 | .tap(
|
---|
149 | "CommonJsImportsParserPlugin",
|
---|
150 | expressionIsUnsupported(
|
---|
151 | parser,
|
---|
152 | "module.parent.require is not supported by webpack."
|
---|
153 | )
|
---|
154 | );
|
---|
155 | // #endregion
|
---|
156 |
|
---|
157 | // #region Renaming
|
---|
158 | /**
|
---|
159 | * @param {Expression} expr expression
|
---|
160 | * @returns {boolean} true when set undefined
|
---|
161 | */
|
---|
162 | const defineUndefined = expr => {
|
---|
163 | // To avoid "not defined" error, replace the value with undefined
|
---|
164 | const dep = new ConstDependency(
|
---|
165 | "undefined",
|
---|
166 | /** @type {Range} */ (expr.range)
|
---|
167 | );
|
---|
168 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
169 | parser.state.module.addPresentationalDependency(dep);
|
---|
170 | return false;
|
---|
171 | };
|
---|
172 | parser.hooks.canRename
|
---|
173 | .for("require")
|
---|
174 | .tap("CommonJsImportsParserPlugin", () => true);
|
---|
175 | parser.hooks.rename
|
---|
176 | .for("require")
|
---|
177 | .tap("CommonJsImportsParserPlugin", defineUndefined);
|
---|
178 | // #endregion
|
---|
179 |
|
---|
180 | // #region Inspection
|
---|
181 | const requireCache = toConstantDependency(
|
---|
182 | parser,
|
---|
183 | RuntimeGlobals.moduleCache,
|
---|
184 | [
|
---|
185 | RuntimeGlobals.moduleCache,
|
---|
186 | RuntimeGlobals.moduleId,
|
---|
187 | RuntimeGlobals.moduleLoaded
|
---|
188 | ]
|
---|
189 | );
|
---|
190 |
|
---|
191 | parser.hooks.expression
|
---|
192 | .for("require.cache")
|
---|
193 | .tap("CommonJsImportsParserPlugin", requireCache);
|
---|
194 | // #endregion
|
---|
195 |
|
---|
196 | // #region Require as expression
|
---|
197 | /**
|
---|
198 | * @param {Expression} expr expression
|
---|
199 | * @returns {boolean} true when handled
|
---|
200 | */
|
---|
201 | const requireAsExpressionHandler = expr => {
|
---|
202 | const dep = new CommonJsRequireContextDependency(
|
---|
203 | {
|
---|
204 | request: options.unknownContextRequest,
|
---|
205 | recursive: options.unknownContextRecursive,
|
---|
206 | regExp: options.unknownContextRegExp,
|
---|
207 | mode: "sync"
|
---|
208 | },
|
---|
209 | /** @type {Range} */ (expr.range),
|
---|
210 | undefined,
|
---|
211 | parser.scope.inShorthand,
|
---|
212 | getContext()
|
---|
213 | );
|
---|
214 | dep.critical =
|
---|
215 | options.unknownContextCritical &&
|
---|
216 | "require function is used in a way in which dependencies cannot be statically extracted";
|
---|
217 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
218 | dep.optional = Boolean(parser.scope.inTry);
|
---|
219 | parser.state.current.addDependency(dep);
|
---|
220 | return true;
|
---|
221 | };
|
---|
222 | parser.hooks.expression
|
---|
223 | .for("require")
|
---|
224 | .tap("CommonJsImportsParserPlugin", requireAsExpressionHandler);
|
---|
225 | // #endregion
|
---|
226 |
|
---|
227 | // #region Require
|
---|
228 | /**
|
---|
229 | * @param {CallExpression | NewExpression} expr expression
|
---|
230 | * @param {BasicEvaluatedExpression} param param
|
---|
231 | * @returns {boolean | void} true when handled
|
---|
232 | */
|
---|
233 | const processRequireItem = (expr, param) => {
|
---|
234 | if (param.isString()) {
|
---|
235 | const dep = new CommonJsRequireDependency(
|
---|
236 | /** @type {string} */ (param.string),
|
---|
237 | /** @type {Range} */ (param.range),
|
---|
238 | getContext()
|
---|
239 | );
|
---|
240 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
241 | dep.optional = Boolean(parser.scope.inTry);
|
---|
242 | parser.state.current.addDependency(dep);
|
---|
243 | return true;
|
---|
244 | }
|
---|
245 | };
|
---|
246 | /**
|
---|
247 | * @param {CallExpression | NewExpression} expr expression
|
---|
248 | * @param {BasicEvaluatedExpression} param param
|
---|
249 | * @returns {boolean | void} true when handled
|
---|
250 | */
|
---|
251 | const processRequireContext = (expr, param) => {
|
---|
252 | const dep = ContextDependencyHelpers.create(
|
---|
253 | CommonJsRequireContextDependency,
|
---|
254 | /** @type {Range} */ (expr.range),
|
---|
255 | param,
|
---|
256 | expr,
|
---|
257 | options,
|
---|
258 | {
|
---|
259 | category: "commonjs"
|
---|
260 | },
|
---|
261 | parser,
|
---|
262 | undefined,
|
---|
263 | getContext()
|
---|
264 | );
|
---|
265 | if (!dep) return;
|
---|
266 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
267 | dep.optional = Boolean(parser.scope.inTry);
|
---|
268 | parser.state.current.addDependency(dep);
|
---|
269 | return true;
|
---|
270 | };
|
---|
271 | /**
|
---|
272 | * @param {boolean} callNew true, when require is called with new
|
---|
273 | * @returns {(expr: CallExpression | NewExpression) => (boolean | void)} handler
|
---|
274 | */
|
---|
275 | const createRequireHandler = callNew => expr => {
|
---|
276 | if (options.commonjsMagicComments) {
|
---|
277 | const { options: requireOptions, errors: commentErrors } =
|
---|
278 | parser.parseCommentOptions(/** @type {Range} */ (expr.range));
|
---|
279 |
|
---|
280 | if (commentErrors) {
|
---|
281 | for (const e of commentErrors) {
|
---|
282 | const { comment } = e;
|
---|
283 | parser.state.module.addWarning(
|
---|
284 | new CommentCompilationWarning(
|
---|
285 | `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
|
---|
286 | /** @type {DependencyLocation} */ (comment.loc)
|
---|
287 | )
|
---|
288 | );
|
---|
289 | }
|
---|
290 | }
|
---|
291 | if (requireOptions && requireOptions.webpackIgnore !== undefined) {
|
---|
292 | if (typeof requireOptions.webpackIgnore !== "boolean") {
|
---|
293 | parser.state.module.addWarning(
|
---|
294 | new UnsupportedFeatureWarning(
|
---|
295 | `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`,
|
---|
296 | /** @type {DependencyLocation} */ (expr.loc)
|
---|
297 | )
|
---|
298 | );
|
---|
299 | } else if (requireOptions.webpackIgnore) {
|
---|
300 | // Do not instrument `require()` if `webpackIgnore` is `true`
|
---|
301 | return true;
|
---|
302 | }
|
---|
303 | }
|
---|
304 | }
|
---|
305 |
|
---|
306 | if (expr.arguments.length !== 1) return;
|
---|
307 | let localModule;
|
---|
308 | const param = parser.evaluateExpression(expr.arguments[0]);
|
---|
309 | if (param.isConditional()) {
|
---|
310 | let isExpression = false;
|
---|
311 | for (const p of /** @type {BasicEvaluatedExpression[]} */ (
|
---|
312 | param.options
|
---|
313 | )) {
|
---|
314 | const result = processRequireItem(expr, p);
|
---|
315 | if (result === undefined) {
|
---|
316 | isExpression = true;
|
---|
317 | }
|
---|
318 | }
|
---|
319 | if (!isExpression) {
|
---|
320 | const dep = new RequireHeaderDependency(
|
---|
321 | /** @type {Range} */ (expr.callee.range)
|
---|
322 | );
|
---|
323 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
324 | parser.state.module.addPresentationalDependency(dep);
|
---|
325 | return true;
|
---|
326 | }
|
---|
327 | }
|
---|
328 | if (
|
---|
329 | param.isString() &&
|
---|
330 | (localModule = getLocalModule(
|
---|
331 | parser.state,
|
---|
332 | /** @type {string} */ (param.string)
|
---|
333 | ))
|
---|
334 | ) {
|
---|
335 | localModule.flagUsed();
|
---|
336 | const dep = new LocalModuleDependency(
|
---|
337 | localModule,
|
---|
338 | /** @type {Range} */ (expr.range),
|
---|
339 | callNew
|
---|
340 | );
|
---|
341 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
342 | parser.state.module.addPresentationalDependency(dep);
|
---|
343 | } else {
|
---|
344 | const result = processRequireItem(expr, param);
|
---|
345 | if (result === undefined) {
|
---|
346 | processRequireContext(expr, param);
|
---|
347 | } else {
|
---|
348 | const dep = new RequireHeaderDependency(
|
---|
349 | /** @type {Range} */ (expr.callee.range)
|
---|
350 | );
|
---|
351 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
352 | parser.state.module.addPresentationalDependency(dep);
|
---|
353 | }
|
---|
354 | }
|
---|
355 | return true;
|
---|
356 | };
|
---|
357 | parser.hooks.call
|
---|
358 | .for("require")
|
---|
359 | .tap("CommonJsImportsParserPlugin", createRequireHandler(false));
|
---|
360 | parser.hooks.new
|
---|
361 | .for("require")
|
---|
362 | .tap("CommonJsImportsParserPlugin", createRequireHandler(true));
|
---|
363 | parser.hooks.call
|
---|
364 | .for("module.require")
|
---|
365 | .tap("CommonJsImportsParserPlugin", createRequireHandler(false));
|
---|
366 | parser.hooks.new
|
---|
367 | .for("module.require")
|
---|
368 | .tap("CommonJsImportsParserPlugin", createRequireHandler(true));
|
---|
369 | // #endregion
|
---|
370 |
|
---|
371 | // #region Require with property access
|
---|
372 | /**
|
---|
373 | * @param {Expression} expr expression
|
---|
374 | * @param {string[]} calleeMembers callee members
|
---|
375 | * @param {CallExpression} callExpr call expression
|
---|
376 | * @param {string[]} members members
|
---|
377 | * @param {Range[]} memberRanges member ranges
|
---|
378 | * @returns {boolean | void} true when handled
|
---|
379 | */
|
---|
380 | const chainHandler = (
|
---|
381 | expr,
|
---|
382 | calleeMembers,
|
---|
383 | callExpr,
|
---|
384 | members,
|
---|
385 | memberRanges
|
---|
386 | ) => {
|
---|
387 | if (callExpr.arguments.length !== 1) return;
|
---|
388 | const param = parser.evaluateExpression(callExpr.arguments[0]);
|
---|
389 | if (
|
---|
390 | param.isString() &&
|
---|
391 | !getLocalModule(parser.state, /** @type {string} */ (param.string))
|
---|
392 | ) {
|
---|
393 | const dep = new CommonJsFullRequireDependency(
|
---|
394 | /** @type {string} */ (param.string),
|
---|
395 | /** @type {Range} */ (expr.range),
|
---|
396 | members,
|
---|
397 | /** @type {Range[]} */ memberRanges
|
---|
398 | );
|
---|
399 | dep.asiSafe = !parser.isAsiPosition(
|
---|
400 | /** @type {Range} */ (expr.range)[0]
|
---|
401 | );
|
---|
402 | dep.optional = Boolean(parser.scope.inTry);
|
---|
403 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
404 | parser.state.current.addDependency(dep);
|
---|
405 | return true;
|
---|
406 | }
|
---|
407 | };
|
---|
408 | /**
|
---|
409 | * @param {CallExpression} expr expression
|
---|
410 | * @param {string[]} calleeMembers callee members
|
---|
411 | * @param {CallExpression} callExpr call expression
|
---|
412 | * @param {string[]} members members
|
---|
413 | * @param {Range[]} memberRanges member ranges
|
---|
414 | * @returns {boolean | void} true when handled
|
---|
415 | */
|
---|
416 | const callChainHandler = (
|
---|
417 | expr,
|
---|
418 | calleeMembers,
|
---|
419 | callExpr,
|
---|
420 | members,
|
---|
421 | memberRanges
|
---|
422 | ) => {
|
---|
423 | if (callExpr.arguments.length !== 1) return;
|
---|
424 | const param = parser.evaluateExpression(callExpr.arguments[0]);
|
---|
425 | if (
|
---|
426 | param.isString() &&
|
---|
427 | !getLocalModule(parser.state, /** @type {string} */ (param.string))
|
---|
428 | ) {
|
---|
429 | const dep = new CommonJsFullRequireDependency(
|
---|
430 | /** @type {string} */ (param.string),
|
---|
431 | /** @type {Range} */ (expr.callee.range),
|
---|
432 | members,
|
---|
433 | /** @type {Range[]} */ memberRanges
|
---|
434 | );
|
---|
435 | dep.call = true;
|
---|
436 | dep.asiSafe = !parser.isAsiPosition(
|
---|
437 | /** @type {Range} */ (expr.range)[0]
|
---|
438 | );
|
---|
439 | dep.optional = Boolean(parser.scope.inTry);
|
---|
440 | dep.loc = /** @type {DependencyLocation} */ (expr.callee.loc);
|
---|
441 | parser.state.current.addDependency(dep);
|
---|
442 | parser.walkExpressions(expr.arguments);
|
---|
443 | return true;
|
---|
444 | }
|
---|
445 | };
|
---|
446 | parser.hooks.memberChainOfCallMemberChain
|
---|
447 | .for("require")
|
---|
448 | .tap("CommonJsImportsParserPlugin", chainHandler);
|
---|
449 | parser.hooks.memberChainOfCallMemberChain
|
---|
450 | .for("module.require")
|
---|
451 | .tap("CommonJsImportsParserPlugin", chainHandler);
|
---|
452 | parser.hooks.callMemberChainOfCallMemberChain
|
---|
453 | .for("require")
|
---|
454 | .tap("CommonJsImportsParserPlugin", callChainHandler);
|
---|
455 | parser.hooks.callMemberChainOfCallMemberChain
|
---|
456 | .for("module.require")
|
---|
457 | .tap("CommonJsImportsParserPlugin", callChainHandler);
|
---|
458 | // #endregion
|
---|
459 |
|
---|
460 | // #region Require.resolve
|
---|
461 | /**
|
---|
462 | * @param {CallExpression} expr call expression
|
---|
463 | * @param {boolean} weak weak
|
---|
464 | * @returns {boolean | void} true when handled
|
---|
465 | */
|
---|
466 | const processResolve = (expr, weak) => {
|
---|
467 | if (expr.arguments.length !== 1) return;
|
---|
468 | const param = parser.evaluateExpression(expr.arguments[0]);
|
---|
469 | if (param.isConditional()) {
|
---|
470 | for (const option of /** @type {BasicEvaluatedExpression[]} */ (
|
---|
471 | param.options
|
---|
472 | )) {
|
---|
473 | const result = processResolveItem(expr, option, weak);
|
---|
474 | if (result === undefined) {
|
---|
475 | processResolveContext(expr, option, weak);
|
---|
476 | }
|
---|
477 | }
|
---|
478 | const dep = new RequireResolveHeaderDependency(
|
---|
479 | /** @type {Range} */ (expr.callee.range)
|
---|
480 | );
|
---|
481 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
482 | parser.state.module.addPresentationalDependency(dep);
|
---|
483 | return true;
|
---|
484 | }
|
---|
485 | const result = processResolveItem(expr, param, weak);
|
---|
486 | if (result === undefined) {
|
---|
487 | processResolveContext(expr, param, weak);
|
---|
488 | }
|
---|
489 | const dep = new RequireResolveHeaderDependency(
|
---|
490 | /** @type {Range} */ (expr.callee.range)
|
---|
491 | );
|
---|
492 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
493 | parser.state.module.addPresentationalDependency(dep);
|
---|
494 | return true;
|
---|
495 | };
|
---|
496 | /**
|
---|
497 | * @param {CallExpression} expr call expression
|
---|
498 | * @param {BasicEvaluatedExpression} param param
|
---|
499 | * @param {boolean} weak weak
|
---|
500 | * @returns {boolean | void} true when handled
|
---|
501 | */
|
---|
502 | const processResolveItem = (expr, param, weak) => {
|
---|
503 | if (param.isString()) {
|
---|
504 | const dep = new RequireResolveDependency(
|
---|
505 | /** @type {string} */ (param.string),
|
---|
506 | /** @type {Range} */ (param.range),
|
---|
507 | getContext()
|
---|
508 | );
|
---|
509 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
510 | dep.optional = Boolean(parser.scope.inTry);
|
---|
511 | dep.weak = weak;
|
---|
512 | parser.state.current.addDependency(dep);
|
---|
513 | return true;
|
---|
514 | }
|
---|
515 | };
|
---|
516 | /**
|
---|
517 | * @param {CallExpression} expr call expression
|
---|
518 | * @param {BasicEvaluatedExpression} param param
|
---|
519 | * @param {boolean} weak weak
|
---|
520 | * @returns {boolean | void} true when handled
|
---|
521 | */
|
---|
522 | const processResolveContext = (expr, param, weak) => {
|
---|
523 | const dep = ContextDependencyHelpers.create(
|
---|
524 | RequireResolveContextDependency,
|
---|
525 | /** @type {Range} */ (param.range),
|
---|
526 | param,
|
---|
527 | expr,
|
---|
528 | options,
|
---|
529 | {
|
---|
530 | category: "commonjs",
|
---|
531 | mode: weak ? "weak" : "sync"
|
---|
532 | },
|
---|
533 | parser,
|
---|
534 | getContext()
|
---|
535 | );
|
---|
536 | if (!dep) return;
|
---|
537 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
538 | dep.optional = Boolean(parser.scope.inTry);
|
---|
539 | parser.state.current.addDependency(dep);
|
---|
540 | return true;
|
---|
541 | };
|
---|
542 |
|
---|
543 | parser.hooks.call
|
---|
544 | .for("require.resolve")
|
---|
545 | .tap("CommonJsImportsParserPlugin", expr => processResolve(expr, false));
|
---|
546 | parser.hooks.call
|
---|
547 | .for("require.resolveWeak")
|
---|
548 | .tap("CommonJsImportsParserPlugin", expr => processResolve(expr, true));
|
---|
549 | // #endregion
|
---|
550 |
|
---|
551 | // #region Create require
|
---|
552 |
|
---|
553 | if (!options.createRequire) return;
|
---|
554 |
|
---|
555 | /** @type {ImportSource[]} */
|
---|
556 | let moduleName = [];
|
---|
557 | /** @type {string | undefined} */
|
---|
558 | let specifierName;
|
---|
559 |
|
---|
560 | if (options.createRequire === true) {
|
---|
561 | moduleName = ["module", "node:module"];
|
---|
562 | specifierName = "createRequire";
|
---|
563 | } else {
|
---|
564 | let moduleName;
|
---|
565 | const match = /^(.*) from (.*)$/.exec(options.createRequire);
|
---|
566 | if (match) {
|
---|
567 | [, specifierName, moduleName] = match;
|
---|
568 | }
|
---|
569 | if (!specifierName || !moduleName) {
|
---|
570 | const err = new WebpackError(
|
---|
571 | `Parsing javascript parser option "createRequire" failed, got ${JSON.stringify(
|
---|
572 | options.createRequire
|
---|
573 | )}`
|
---|
574 | );
|
---|
575 | err.details =
|
---|
576 | 'Expected string in format "createRequire from module", where "createRequire" is specifier name and "module" name of the module';
|
---|
577 | throw err;
|
---|
578 | }
|
---|
579 | }
|
---|
580 |
|
---|
581 | tapRequireExpressionTag(createdRequireIdentifierTag);
|
---|
582 | tapRequireExpressionTag(createRequireSpecifierTag);
|
---|
583 | parser.hooks.evaluateCallExpression
|
---|
584 | .for(createRequireSpecifierTag)
|
---|
585 | .tap("CommonJsImportsParserPlugin", expr => {
|
---|
586 | const context = parseCreateRequireArguments(expr);
|
---|
587 | if (context === undefined) return;
|
---|
588 | const ident = parser.evaluatedVariable({
|
---|
589 | tag: createdRequireIdentifierTag,
|
---|
590 | data: { context },
|
---|
591 | next: undefined
|
---|
592 | });
|
---|
593 |
|
---|
594 | return new BasicEvaluatedExpression()
|
---|
595 | .setIdentifier(ident, ident, () => [])
|
---|
596 | .setSideEffects(false)
|
---|
597 | .setRange(/** @type {Range} */ (expr.range));
|
---|
598 | });
|
---|
599 | parser.hooks.unhandledExpressionMemberChain
|
---|
600 | .for(createdRequireIdentifierTag)
|
---|
601 | .tap("CommonJsImportsParserPlugin", (expr, members) =>
|
---|
602 | expressionIsUnsupported(
|
---|
603 | parser,
|
---|
604 | `createRequire().${members.join(".")} is not supported by webpack.`
|
---|
605 | )(expr)
|
---|
606 | );
|
---|
607 | parser.hooks.canRename
|
---|
608 | .for(createdRequireIdentifierTag)
|
---|
609 | .tap("CommonJsImportsParserPlugin", () => true);
|
---|
610 | parser.hooks.canRename
|
---|
611 | .for(createRequireSpecifierTag)
|
---|
612 | .tap("CommonJsImportsParserPlugin", () => true);
|
---|
613 | parser.hooks.rename
|
---|
614 | .for(createRequireSpecifierTag)
|
---|
615 | .tap("CommonJsImportsParserPlugin", defineUndefined);
|
---|
616 | parser.hooks.expression
|
---|
617 | .for(createdRequireIdentifierTag)
|
---|
618 | .tap("CommonJsImportsParserPlugin", requireAsExpressionHandler);
|
---|
619 | parser.hooks.call
|
---|
620 | .for(createdRequireIdentifierTag)
|
---|
621 | .tap("CommonJsImportsParserPlugin", createRequireHandler(false));
|
---|
622 | /**
|
---|
623 | * @param {CallExpression} expr call expression
|
---|
624 | * @returns {string | void} context
|
---|
625 | */
|
---|
626 | const parseCreateRequireArguments = expr => {
|
---|
627 | const args = expr.arguments;
|
---|
628 | if (args.length !== 1) {
|
---|
629 | const err = new WebpackError(
|
---|
630 | "module.createRequire supports only one argument."
|
---|
631 | );
|
---|
632 | err.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
633 | parser.state.module.addWarning(err);
|
---|
634 | return;
|
---|
635 | }
|
---|
636 | const arg = args[0];
|
---|
637 | const evaluated = parser.evaluateExpression(arg);
|
---|
638 | if (!evaluated.isString()) {
|
---|
639 | const err = new WebpackError(
|
---|
640 | "module.createRequire failed parsing argument."
|
---|
641 | );
|
---|
642 | err.loc = /** @type {DependencyLocation} */ (arg.loc);
|
---|
643 | parser.state.module.addWarning(err);
|
---|
644 | return;
|
---|
645 | }
|
---|
646 | const ctx = /** @type {string} */ (evaluated.string).startsWith("file://")
|
---|
647 | ? fileURLToPath(/** @type {string} */ (evaluated.string))
|
---|
648 | : /** @type {string} */ (evaluated.string);
|
---|
649 | // argument always should be a filename
|
---|
650 | return ctx.slice(0, ctx.lastIndexOf(ctx.startsWith("/") ? "/" : "\\"));
|
---|
651 | };
|
---|
652 |
|
---|
653 | parser.hooks.import.tap(
|
---|
654 | {
|
---|
655 | name: "CommonJsImportsParserPlugin",
|
---|
656 | stage: -10
|
---|
657 | },
|
---|
658 | (statement, source) => {
|
---|
659 | if (
|
---|
660 | !moduleName.includes(source) ||
|
---|
661 | statement.specifiers.length !== 1 ||
|
---|
662 | statement.specifiers[0].type !== "ImportSpecifier" ||
|
---|
663 | statement.specifiers[0].imported.type !== "Identifier" ||
|
---|
664 | statement.specifiers[0].imported.name !== specifierName
|
---|
665 | )
|
---|
666 | return;
|
---|
667 | // clear for 'import { createRequire as x } from "module"'
|
---|
668 | // if any other specifier was used import module
|
---|
669 | const clearDep = new ConstDependency(
|
---|
670 | parser.isAsiPosition(/** @type {Range} */ (statement.range)[0])
|
---|
671 | ? ";"
|
---|
672 | : "",
|
---|
673 | /** @type {Range} */ (statement.range)
|
---|
674 | );
|
---|
675 | clearDep.loc = /** @type {DependencyLocation} */ (statement.loc);
|
---|
676 | parser.state.module.addPresentationalDependency(clearDep);
|
---|
677 | parser.unsetAsiPosition(/** @type {Range} */ (statement.range)[1]);
|
---|
678 | return true;
|
---|
679 | }
|
---|
680 | );
|
---|
681 | parser.hooks.importSpecifier.tap(
|
---|
682 | {
|
---|
683 | name: "CommonJsImportsParserPlugin",
|
---|
684 | stage: -10
|
---|
685 | },
|
---|
686 | (statement, source, id, name) => {
|
---|
687 | if (!moduleName.includes(source) || id !== specifierName) return;
|
---|
688 | parser.tagVariable(name, createRequireSpecifierTag);
|
---|
689 | return true;
|
---|
690 | }
|
---|
691 | );
|
---|
692 | parser.hooks.preDeclarator.tap(
|
---|
693 | "CommonJsImportsParserPlugin",
|
---|
694 | declarator => {
|
---|
695 | if (
|
---|
696 | declarator.id.type !== "Identifier" ||
|
---|
697 | !declarator.init ||
|
---|
698 | declarator.init.type !== "CallExpression" ||
|
---|
699 | declarator.init.callee.type !== "Identifier"
|
---|
700 | )
|
---|
701 | return;
|
---|
702 | const variableInfo =
|
---|
703 | /** @type {TODO} */
|
---|
704 | (parser.getVariableInfo(declarator.init.callee.name));
|
---|
705 | if (
|
---|
706 | variableInfo &&
|
---|
707 | variableInfo.tagInfo &&
|
---|
708 | variableInfo.tagInfo.tag === createRequireSpecifierTag
|
---|
709 | ) {
|
---|
710 | const context = parseCreateRequireArguments(declarator.init);
|
---|
711 | if (context === undefined) return;
|
---|
712 | parser.tagVariable(declarator.id.name, createdRequireIdentifierTag, {
|
---|
713 | name: declarator.id.name,
|
---|
714 | context
|
---|
715 | });
|
---|
716 | return true;
|
---|
717 | }
|
---|
718 | }
|
---|
719 | );
|
---|
720 |
|
---|
721 | parser.hooks.memberChainOfCallMemberChain
|
---|
722 | .for(createRequireSpecifierTag)
|
---|
723 | .tap(
|
---|
724 | "CommonJsImportsParserPlugin",
|
---|
725 | (expr, calleeMembers, callExpr, members) => {
|
---|
726 | if (
|
---|
727 | calleeMembers.length !== 0 ||
|
---|
728 | members.length !== 1 ||
|
---|
729 | members[0] !== "cache"
|
---|
730 | )
|
---|
731 | return;
|
---|
732 | // createRequire().cache
|
---|
733 | const context = parseCreateRequireArguments(callExpr);
|
---|
734 | if (context === undefined) return;
|
---|
735 | return requireCache(expr);
|
---|
736 | }
|
---|
737 | );
|
---|
738 | parser.hooks.callMemberChainOfCallMemberChain
|
---|
739 | .for(createRequireSpecifierTag)
|
---|
740 | .tap(
|
---|
741 | "CommonJsImportsParserPlugin",
|
---|
742 | (expr, calleeMembers, innerCallExpression, members) => {
|
---|
743 | if (
|
---|
744 | calleeMembers.length !== 0 ||
|
---|
745 | members.length !== 1 ||
|
---|
746 | members[0] !== "resolve"
|
---|
747 | )
|
---|
748 | return;
|
---|
749 | // createRequire().resolve()
|
---|
750 | return processResolve(expr, false);
|
---|
751 | }
|
---|
752 | );
|
---|
753 | parser.hooks.expressionMemberChain
|
---|
754 | .for(createdRequireIdentifierTag)
|
---|
755 | .tap("CommonJsImportsParserPlugin", (expr, members) => {
|
---|
756 | // require.cache
|
---|
757 | if (members.length === 1 && members[0] === "cache") {
|
---|
758 | return requireCache(expr);
|
---|
759 | }
|
---|
760 | });
|
---|
761 | parser.hooks.callMemberChain
|
---|
762 | .for(createdRequireIdentifierTag)
|
---|
763 | .tap("CommonJsImportsParserPlugin", (expr, members) => {
|
---|
764 | // require.resolve()
|
---|
765 | if (members.length === 1 && members[0] === "resolve") {
|
---|
766 | return processResolve(expr, false);
|
---|
767 | }
|
---|
768 | });
|
---|
769 | parser.hooks.call
|
---|
770 | .for(createRequireSpecifierTag)
|
---|
771 | .tap("CommonJsImportsParserPlugin", expr => {
|
---|
772 | const clearDep = new ConstDependency(
|
---|
773 | "/* createRequire() */ undefined",
|
---|
774 | /** @type {Range} */ (expr.range)
|
---|
775 | );
|
---|
776 | clearDep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
777 | parser.state.module.addPresentationalDependency(clearDep);
|
---|
778 | return true;
|
---|
779 | });
|
---|
780 | // #endregion
|
---|
781 | }
|
---|
782 | }
|
---|
783 | module.exports = CommonJsImportsParserPlugin;
|
---|