UNPKG

35.1 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.WEBPACK_IGNORE_COMMENT_REGEXP = void 0;
7exports.camelCase = camelCase;
8exports.combineRequests = combineRequests;
9exports.defaultGetLocalIdent = defaultGetLocalIdent;
10exports.getExportCode = getExportCode;
11exports.getFilter = getFilter;
12exports.getImportCode = getImportCode;
13exports.getModuleCode = getModuleCode;
14exports.getModulesOptions = getModulesOptions;
15exports.getModulesPlugins = getModulesPlugins;
16exports.getPreRequester = getPreRequester;
17exports.isDataUrl = isDataUrl;
18exports.isURLRequestable = isURLRequestable;
19exports.normalizeOptions = normalizeOptions;
20exports.normalizeSourceMap = normalizeSourceMap;
21exports.normalizeUrl = normalizeUrl;
22exports.requestify = requestify;
23exports.resolveRequests = resolveRequests;
24exports.shouldUseIcssPlugin = shouldUseIcssPlugin;
25exports.shouldUseImportPlugin = shouldUseImportPlugin;
26exports.shouldUseModulesPlugins = shouldUseModulesPlugins;
27exports.shouldUseURLPlugin = shouldUseURLPlugin;
28exports.sort = sort;
29exports.stringifyRequest = stringifyRequest;
30
31var _url = require("url");
32
33var _path = _interopRequireDefault(require("path"));
34
35var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
36
37var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
38
39var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
40
41var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
42
43function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
44
45/*
46 MIT License http://www.opensource.org/licenses/mit-license.php
47 Author Tobias Koppers @sokra
48*/
49const WEBPACK_IGNORE_COMMENT_REGEXP = /webpackIgnore:(\s+)?(true|false)/;
50exports.WEBPACK_IGNORE_COMMENT_REGEXP = WEBPACK_IGNORE_COMMENT_REGEXP;
51const matchRelativePath = /^\.\.?[/\\]/;
52
53function isAbsolutePath(str) {
54 return _path.default.posix.isAbsolute(str) || _path.default.win32.isAbsolute(str);
55}
56
57function isRelativePath(str) {
58 return matchRelativePath.test(str);
59} // TODO simplify for the next major release
60
61
62function stringifyRequest(loaderContext, request) {
63 if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") {
64 return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
65 }
66
67 const splitted = request.split("!");
68 const {
69 context
70 } = loaderContext;
71 return JSON.stringify(splitted.map(part => {
72 // First, separate singlePath from query, because the query might contain paths again
73 const splittedPart = part.match(/^(.*?)(\?.*)/);
74 const query = splittedPart ? splittedPart[2] : "";
75 let singlePath = splittedPart ? splittedPart[1] : part;
76
77 if (isAbsolutePath(singlePath) && context) {
78 singlePath = _path.default.relative(context, singlePath);
79
80 if (isAbsolutePath(singlePath)) {
81 // If singlePath still matches an absolute path, singlePath was on a different drive than context.
82 // In this case, we leave the path platform-specific without replacing any separators.
83 // @see https://github.com/webpack/loader-utils/pull/14
84 return singlePath + query;
85 }
86
87 if (isRelativePath(singlePath) === false) {
88 // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
89 singlePath = `./${singlePath}`;
90 }
91 }
92
93 return singlePath.replace(/\\/g, "/") + query;
94 }).join("!"));
95} // We can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
96
97
98const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
99const IS_MODULE_REQUEST = /^[^?]*~/;
100
101function urlToRequest(url, root) {
102 let request;
103
104 if (IS_NATIVE_WIN32_PATH.test(url)) {
105 // absolute windows path, keep it
106 request = url;
107 } else if (typeof root !== "undefined" && /^\//.test(url)) {
108 request = root + url;
109 } else if (/^\.\.?\//.test(url)) {
110 // A relative url stays
111 request = url;
112 } else {
113 // every other url is threaded like a relative url
114 request = `./${url}`;
115 } // A `~` makes the url an module
116
117
118 if (IS_MODULE_REQUEST.test(request)) {
119 request = request.replace(IS_MODULE_REQUEST, "");
120 }
121
122 return request;
123} // eslint-disable-next-line no-useless-escape
124
125
126const regexSingleEscape = /[ -,.\/:-@[\]\^`{-~]/;
127const regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
128
129const preserveCamelCase = string => {
130 let result = string;
131 let isLastCharLower = false;
132 let isLastCharUpper = false;
133 let isLastLastCharUpper = false;
134
135 for (let i = 0; i < result.length; i++) {
136 const character = result[i];
137
138 if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
139 result = `${result.slice(0, i)}-${result.slice(i)}`;
140 isLastCharLower = false;
141 isLastLastCharUpper = isLastCharUpper;
142 isLastCharUpper = true;
143 i += 1;
144 } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
145 result = `${result.slice(0, i - 1)}-${result.slice(i - 1)}`;
146 isLastLastCharUpper = isLastCharUpper;
147 isLastCharUpper = false;
148 isLastCharLower = true;
149 } else {
150 isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
151 isLastLastCharUpper = isLastCharUpper;
152 isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
153 }
154 }
155
156 return result;
157};
158
159function camelCase(input) {
160 let result = input.trim();
161
162 if (result.length === 0) {
163 return "";
164 }
165
166 if (result.length === 1) {
167 return result.toLowerCase();
168 }
169
170 const hasUpperCase = result !== result.toLowerCase();
171
172 if (hasUpperCase) {
173 result = preserveCamelCase(result);
174 }
175
176 return result.replace(/^[_.\- ]+/, "").toLowerCase().replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toUpperCase()).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toUpperCase());
177}
178
179function escape(string) {
180 let output = "";
181 let counter = 0;
182
183 while (counter < string.length) {
184 // eslint-disable-next-line no-plusplus
185 const character = string.charAt(counter++);
186 let value; // eslint-disable-next-line no-control-regex
187
188 if (/[\t\n\f\r\x0B]/.test(character)) {
189 const codePoint = character.charCodeAt();
190 value = `\\${codePoint.toString(16).toUpperCase()} `;
191 } else if (character === "\\" || regexSingleEscape.test(character)) {
192 value = `\\${character}`;
193 } else {
194 value = character;
195 }
196
197 output += value;
198 }
199
200 const firstChar = string.charAt(0);
201
202 if (/^-[-\d]/.test(output)) {
203 output = `\\-${output.slice(1)}`;
204 } else if (/\d/.test(firstChar)) {
205 output = `\\3${firstChar} ${output.slice(1)}`;
206 } // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
207 // since they’re redundant. Note that this is only possible if the escape
208 // sequence isn’t preceded by an odd number of backslashes.
209
210
211 output = output.replace(regexExcessiveSpaces, ($0, $1, $2) => {
212 if ($1 && $1.length % 2) {
213 // It’s not safe to remove the space, so don’t.
214 return $0;
215 } // Strip the space.
216
217
218 return ($1 || "") + $2;
219 });
220 return output;
221}
222
223function gobbleHex(str) {
224 const lower = str.toLowerCase();
225 let hex = "";
226 let spaceTerminated = false; // eslint-disable-next-line no-undefined
227
228 for (let i = 0; i < 6 && lower[i] !== undefined; i++) {
229 const code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
230
231 const valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
232
233 spaceTerminated = code === 32;
234
235 if (!valid) {
236 break;
237 }
238
239 hex += lower[i];
240 }
241
242 if (hex.length === 0) {
243 // eslint-disable-next-line no-undefined
244 return undefined;
245 }
246
247 const codePoint = parseInt(hex, 16);
248 const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; // Add special case for
249 // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
250 // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
251
252 if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
253 return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
254 }
255
256 return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
257}
258
259const CONTAINS_ESCAPE = /\\/;
260
261function unescape(str) {
262 const needToProcess = CONTAINS_ESCAPE.test(str);
263
264 if (!needToProcess) {
265 return str;
266 }
267
268 let ret = "";
269
270 for (let i = 0; i < str.length; i++) {
271 if (str[i] === "\\") {
272 const gobbled = gobbleHex(str.slice(i + 1, i + 7)); // eslint-disable-next-line no-undefined
273
274 if (gobbled !== undefined) {
275 ret += gobbled[0];
276 i += gobbled[1]; // eslint-disable-next-line no-continue
277
278 continue;
279 } // Retain a pair of \\ if double escaped `\\\\`
280 // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
281
282
283 if (str[i + 1] === "\\") {
284 ret += "\\";
285 i += 1; // eslint-disable-next-line no-continue
286
287 continue;
288 } // if \\ is at the end of the string retain it
289 // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
290
291
292 if (str.length === i + 1) {
293 ret += str[i];
294 } // eslint-disable-next-line no-continue
295
296
297 continue;
298 }
299
300 ret += str[i];
301 }
302
303 return ret;
304}
305
306function normalizePath(file) {
307 return _path.default.sep === "\\" ? file.replace(/\\/g, "/") : file;
308} // eslint-disable-next-line no-control-regex
309
310
311const filenameReservedRegex = /[<>:"/\\|?*]/g; // eslint-disable-next-line no-control-regex
312
313const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g;
314
315function escapeLocalIdent(localident) {
316 // TODO simplify in the next major release
317 return escape(localident // For `[hash]` placeholder
318 .replace(/^((-?[0-9])|--)/, "_$1").replace(filenameReservedRegex, "-").replace(reControlChars, "-").replace(/\./g, "-"));
319}
320
321function defaultGetLocalIdent(loaderContext, localIdentName, localName, options) {
322 const {
323 context,
324 hashSalt,
325 hashStrategy
326 } = options;
327 const {
328 resourcePath
329 } = loaderContext;
330 const relativeResourcePath = normalizePath(_path.default.relative(context, resourcePath)); // eslint-disable-next-line no-param-reassign
331
332 options.content = hashStrategy === "minimal-subset" && /\[local\]/.test(localIdentName) ? relativeResourcePath : `${relativeResourcePath}\x00${localName}`;
333 let {
334 hashFunction,
335 hashDigest,
336 hashDigestLength
337 } = options;
338 const matches = localIdentName.match(/\[(?:([^:\]]+):)?(?:(hash|contenthash|fullhash))(?::([a-z]+\d*))?(?::(\d+))?\]/i);
339
340 if (matches) {
341 const hashName = matches[2] || hashFunction;
342 hashFunction = matches[1] || hashFunction;
343 hashDigest = matches[3] || hashDigest;
344 hashDigestLength = matches[4] || hashDigestLength; // `hash` and `contenthash` are same in `loader-utils` context
345 // let's keep `hash` for backward compatibility
346 // eslint-disable-next-line no-param-reassign
347
348 localIdentName = localIdentName.replace(/\[(?:([^:\]]+):)?(?:hash|contenthash|fullhash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi, () => hashName === "fullhash" ? "[fullhash]" : "[contenthash]");
349 }
350
351 let localIdentHash = "";
352
353 for (let tier = 0; localIdentHash.length < hashDigestLength; tier++) {
354 // TODO remove this in the next major release
355 const hash = loaderContext.utils && typeof loaderContext.utils.createHash === "function" ? loaderContext.utils.createHash(hashFunction) : // eslint-disable-next-line no-underscore-dangle
356 loaderContext._compiler.webpack.util.createHash(hashFunction);
357
358 if (hashSalt) {
359 hash.update(hashSalt);
360 }
361
362 const tierSalt = Buffer.allocUnsafe(4);
363 tierSalt.writeUInt32LE(tier);
364 hash.update(tierSalt); // TODO: bug in webpack with unicode characters with strings
365
366 hash.update(Buffer.from(options.content, "utf8"));
367 localIdentHash = (localIdentHash + hash.digest(hashDigest) // Remove all leading digits
368 ).replace(/^\d+/, "") // Replace all slashes with underscores (same as in base64url)
369 .replace(/\//g, "_") // Remove everything that is not an alphanumeric or underscore
370 .replace(/[^A-Za-z0-9_]+/g, "").slice(0, hashDigestLength);
371 } // TODO need improve on webpack side, we should allow to pass hash/contentHash without chunk property, also `data` for `getPath` should be looks good without chunk property
372
373
374 const ext = _path.default.extname(resourcePath);
375
376 const base = _path.default.basename(resourcePath);
377
378 const name = base.slice(0, base.length - ext.length);
379 const data = {
380 filename: _path.default.relative(context, resourcePath),
381 contentHash: localIdentHash,
382 chunk: {
383 name,
384 hash: localIdentHash,
385 contentHash: localIdentHash
386 }
387 }; // eslint-disable-next-line no-underscore-dangle
388
389 let result = loaderContext._compilation.getPath(localIdentName, data);
390
391 if (/\[folder\]/gi.test(result)) {
392 const dirname = _path.default.dirname(resourcePath);
393
394 let directory = normalizePath(_path.default.relative(context, `${dirname + _path.default.sep}_`));
395 directory = directory.substr(0, directory.length - 1);
396 let folder = "";
397
398 if (directory.length > 1) {
399 folder = _path.default.basename(directory);
400 }
401
402 result = result.replace(/\[folder\]/gi, () => folder);
403 }
404
405 if (options.regExp) {
406 const match = resourcePath.match(options.regExp);
407
408 if (match) {
409 match.forEach((matched, i) => {
410 result = result.replace(new RegExp(`\\[${i}\\]`, "ig"), matched);
411 });
412 }
413 }
414
415 return result;
416}
417
418function fixedEncodeURIComponent(str) {
419 return str.replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16)}`);
420}
421
422function isDataUrl(url) {
423 if (/^data:/i.test(url)) {
424 return true;
425 }
426
427 return false;
428}
429
430const NATIVE_WIN32_PATH = /^[A-Z]:[/\\]|^\\\\/i;
431
432function normalizeUrl(url, isStringValue) {
433 let normalizedUrl = url.replace(/^( |\t\n|\r\n|\r|\f)*/g, "").replace(/( |\t\n|\r\n|\r|\f)*$/g, "");
434
435 if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
436 normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, "");
437 }
438
439 if (NATIVE_WIN32_PATH.test(url)) {
440 try {
441 normalizedUrl = decodeURI(normalizedUrl);
442 } catch (error) {// Ignore
443 }
444
445 return normalizedUrl;
446 }
447
448 normalizedUrl = unescape(normalizedUrl);
449
450 if (isDataUrl(url)) {
451 // Todo fixedEncodeURIComponent is workaround. Webpack resolver shouldn't handle "!" in dataURL
452 return fixedEncodeURIComponent(normalizedUrl);
453 }
454
455 try {
456 normalizedUrl = decodeURI(normalizedUrl);
457 } catch (error) {// Ignore
458 }
459
460 return normalizedUrl;
461}
462
463function requestify(url, rootContext, needToResolveURL = true) {
464 if (needToResolveURL) {
465 if (/^file:/i.test(url)) {
466 return (0, _url.fileURLToPath)(url);
467 }
468
469 return url.charAt(0) === "/" ? urlToRequest(url, rootContext) : urlToRequest(url);
470 }
471
472 if (url.charAt(0) === "/" || /^file:/i.test(url)) {
473 return url;
474 } // A `~` makes the url an module
475
476
477 if (IS_MODULE_REQUEST.test(url)) {
478 return url.replace(IS_MODULE_REQUEST, "");
479 }
480
481 return url;
482}
483
484function getFilter(filter, resourcePath) {
485 return (...args) => {
486 if (typeof filter === "function") {
487 return filter(...args, resourcePath);
488 }
489
490 return true;
491 };
492}
493
494function getValidLocalName(localName, exportLocalsConvention) {
495 const result = exportLocalsConvention(localName);
496 return Array.isArray(result) ? result[0] : result;
497}
498
499const IS_MODULES = /\.module(s)?\.\w+$/i;
500const IS_ICSS = /\.icss\.\w+$/i;
501
502function getModulesOptions(rawOptions, exportType, loaderContext) {
503 if (typeof rawOptions.modules === "boolean" && rawOptions.modules === false) {
504 return false;
505 }
506
507 const resourcePath = // eslint-disable-next-line no-underscore-dangle
508 loaderContext._module && loaderContext._module.matchResource || loaderContext.resourcePath;
509 let auto;
510 let rawModulesOptions;
511
512 if (typeof rawOptions.modules === "undefined") {
513 rawModulesOptions = {};
514 auto = true;
515 } else if (typeof rawOptions.modules === "boolean") {
516 rawModulesOptions = {};
517 } else if (typeof rawOptions.modules === "string") {
518 rawModulesOptions = {
519 mode: rawOptions.modules
520 };
521 } else {
522 rawModulesOptions = rawOptions.modules;
523 ({
524 auto
525 } = rawModulesOptions);
526 } // eslint-disable-next-line no-underscore-dangle
527
528
529 const {
530 outputOptions
531 } = loaderContext._compilation;
532 const needNamedExport = exportType === "css-style-sheet" || exportType === "string";
533 const modulesOptions = {
534 auto,
535 mode: "local",
536 exportGlobals: false,
537 localIdentName: "[hash:base64]",
538 localIdentContext: loaderContext.rootContext,
539 localIdentHashSalt: outputOptions.hashSalt,
540 localIdentHashFunction: outputOptions.hashFunction,
541 localIdentHashDigest: outputOptions.hashDigest,
542 localIdentHashDigestLength: outputOptions.hashDigestLength,
543 // eslint-disable-next-line no-undefined
544 localIdentRegExp: undefined,
545 // eslint-disable-next-line no-undefined
546 getLocalIdent: undefined,
547 namedExport: needNamedExport || false,
548 exportLocalsConvention: (rawModulesOptions.namedExport === true || needNamedExport) && typeof rawModulesOptions.exportLocalsConvention === "undefined" ? "camelCaseOnly" : "asIs",
549 exportOnlyLocals: false,
550 ...rawModulesOptions
551 };
552 let exportLocalsConventionType;
553
554 if (typeof modulesOptions.exportLocalsConvention === "string") {
555 exportLocalsConventionType = modulesOptions.exportLocalsConvention;
556
557 modulesOptions.exportLocalsConvention = name => {
558 switch (exportLocalsConventionType) {
559 case "camelCase":
560 {
561 return [name, camelCase(name)];
562 }
563
564 case "camelCaseOnly":
565 {
566 return camelCase(name);
567 }
568
569 case "dashes":
570 {
571 return [name, dashesCamelCase(name)];
572 }
573
574 case "dashesOnly":
575 {
576 return dashesCamelCase(name);
577 }
578
579 case "asIs":
580 default:
581 return name;
582 }
583 };
584 }
585
586 if (typeof modulesOptions.auto === "boolean") {
587 const isModules = modulesOptions.auto && IS_MODULES.test(resourcePath);
588 let isIcss;
589
590 if (!isModules) {
591 isIcss = IS_ICSS.test(resourcePath);
592
593 if (isIcss) {
594 modulesOptions.mode = "icss";
595 }
596 }
597
598 if (!isModules && !isIcss) {
599 return false;
600 }
601 } else if (modulesOptions.auto instanceof RegExp) {
602 const isModules = modulesOptions.auto.test(resourcePath);
603
604 if (!isModules) {
605 return false;
606 }
607 } else if (typeof modulesOptions.auto === "function") {
608 const isModule = modulesOptions.auto(resourcePath);
609
610 if (!isModule) {
611 return false;
612 }
613 }
614
615 if (typeof modulesOptions.mode === "function") {
616 modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
617 }
618
619 if (needNamedExport) {
620 if (rawOptions.esModule === false) {
621 throw new Error("The 'exportType' option with the 'css-style-sheet' or 'string' value requires the 'esModules' option to be enabled");
622 }
623
624 if (modulesOptions.namedExport === false) {
625 throw new Error("The 'exportType' option with the 'css-style-sheet' or 'string' value requires the 'modules.namedExport' option to be enabled");
626 }
627 }
628
629 if (modulesOptions.namedExport === true) {
630 if (rawOptions.esModule === false) {
631 throw new Error("The 'modules.namedExport' option requires the 'esModules' option to be enabled");
632 }
633
634 if (typeof exportLocalsConventionType === "string" && exportLocalsConventionType !== "camelCaseOnly" && exportLocalsConventionType !== "dashesOnly") {
635 throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly" or "dashesOnly"');
636 }
637 }
638
639 return modulesOptions;
640}
641
642function normalizeOptions(rawOptions, loaderContext) {
643 const exportType = typeof rawOptions.exportType === "undefined" ? "array" : rawOptions.exportType;
644 const modulesOptions = getModulesOptions(rawOptions, exportType, loaderContext);
645 return {
646 url: typeof rawOptions.url === "undefined" ? true : rawOptions.url,
647 import: typeof rawOptions.import === "undefined" ? true : rawOptions.import,
648 modules: modulesOptions,
649 sourceMap: typeof rawOptions.sourceMap === "boolean" ? rawOptions.sourceMap : loaderContext.sourceMap,
650 importLoaders: typeof rawOptions.importLoaders === "string" ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
651 esModule: typeof rawOptions.esModule === "undefined" ? true : rawOptions.esModule,
652 exportType
653 };
654}
655
656function shouldUseImportPlugin(options) {
657 if (options.modules.exportOnlyLocals) {
658 return false;
659 }
660
661 if (typeof options.import === "boolean") {
662 return options.import;
663 }
664
665 return true;
666}
667
668function shouldUseURLPlugin(options) {
669 if (options.modules.exportOnlyLocals) {
670 return false;
671 }
672
673 if (typeof options.url === "boolean") {
674 return options.url;
675 }
676
677 return true;
678}
679
680function shouldUseModulesPlugins(options) {
681 if (typeof options.modules === "boolean" && options.modules === false) {
682 return false;
683 }
684
685 return options.modules.mode !== "icss";
686}
687
688function shouldUseIcssPlugin(options) {
689 return Boolean(options.modules);
690}
691
692function getModulesPlugins(options, loaderContext) {
693 const {
694 mode,
695 getLocalIdent,
696 localIdentName,
697 localIdentContext,
698 localIdentHashSalt,
699 localIdentHashFunction,
700 localIdentHashDigest,
701 localIdentHashDigestLength,
702 localIdentRegExp,
703 hashStrategy
704 } = options.modules;
705 let plugins = [];
706
707 try {
708 plugins = [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
709 mode
710 }), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
711 generateScopedName(exportName) {
712 let localIdent;
713
714 if (typeof getLocalIdent !== "undefined") {
715 localIdent = getLocalIdent(loaderContext, localIdentName, unescape(exportName), {
716 context: localIdentContext,
717 hashSalt: localIdentHashSalt,
718 hashFunction: localIdentHashFunction,
719 hashDigest: localIdentHashDigest,
720 hashDigestLength: localIdentHashDigestLength,
721 hashStrategy,
722 regExp: localIdentRegExp
723 });
724 } // A null/undefined value signals that we should invoke the default
725 // getLocalIdent method.
726
727
728 if (typeof localIdent === "undefined" || localIdent === null) {
729 localIdent = defaultGetLocalIdent(loaderContext, localIdentName, unescape(exportName), {
730 context: localIdentContext,
731 hashSalt: localIdentHashSalt,
732 hashFunction: localIdentHashFunction,
733 hashDigest: localIdentHashDigest,
734 hashDigestLength: localIdentHashDigestLength,
735 hashStrategy,
736 regExp: localIdentRegExp
737 });
738 return escapeLocalIdent(localIdent).replace(/\\\[local\\]/gi, exportName);
739 }
740
741 return escapeLocalIdent(localIdent);
742 },
743
744 exportGlobals: options.modules.exportGlobals
745 })];
746 } catch (error) {
747 loaderContext.emitError(error);
748 }
749
750 return plugins;
751}
752
753const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
754
755function getURLType(source) {
756 if (source[0] === "/") {
757 if (source[1] === "/") {
758 return "scheme-relative";
759 }
760
761 return "path-absolute";
762 }
763
764 if (IS_NATIVE_WIN32_PATH.test(source)) {
765 return "path-absolute";
766 }
767
768 return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
769}
770
771function normalizeSourceMap(map, resourcePath) {
772 let newMap = map; // Some loader emit source map as string
773 // Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
774
775 if (typeof newMap === "string") {
776 newMap = JSON.parse(newMap);
777 }
778
779 delete newMap.file;
780 const {
781 sourceRoot
782 } = newMap;
783 delete newMap.sourceRoot;
784
785 if (newMap.sources) {
786 // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
787 // We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
788 newMap.sources = newMap.sources.map(source => {
789 // Non-standard syntax from `postcss`
790 if (source.indexOf("<") === 0) {
791 return source;
792 }
793
794 const sourceType = getURLType(source); // Do no touch `scheme-relative` and `absolute` URLs
795
796 if (sourceType === "path-relative" || sourceType === "path-absolute") {
797 const absoluteSource = sourceType === "path-relative" && sourceRoot ? _path.default.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
798 return _path.default.relative(_path.default.dirname(resourcePath), absoluteSource);
799 }
800
801 return source;
802 });
803 }
804
805 return newMap;
806}
807
808function getPreRequester({
809 loaders,
810 loaderIndex
811}) {
812 const cache = Object.create(null);
813 return number => {
814 if (cache[number]) {
815 return cache[number];
816 }
817
818 if (number === false) {
819 cache[number] = "";
820 } else {
821 const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== "number" ? 0 : number)).map(x => x.request).join("!");
822 cache[number] = `-!${loadersRequest}!`;
823 }
824
825 return cache[number];
826 };
827}
828
829function getImportCode(imports, options) {
830 let code = "";
831
832 for (const item of imports) {
833 const {
834 importName,
835 url,
836 icss,
837 type
838 } = item;
839
840 if (options.esModule) {
841 if (icss && options.modules.namedExport) {
842 code += `import ${options.modules.exportOnlyLocals ? "" : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
843 } else {
844 code += type === "url" ? `var ${importName} = new URL(${url}, import.meta.url);\n` : `import ${importName} from ${url};\n`;
845 }
846 } else {
847 code += `var ${importName} = require(${url});\n`;
848 }
849 }
850
851 return code ? `// Imports\n${code}` : "";
852}
853
854function normalizeSourceMapForRuntime(map, loaderContext) {
855 const resultMap = map ? map.toJSON() : null;
856
857 if (resultMap) {
858 delete resultMap.file;
859 /* eslint-disable no-underscore-dangle */
860
861 if (loaderContext._compilation && loaderContext._compilation.options && loaderContext._compilation.options.devtool && loaderContext._compilation.options.devtool.includes("nosources")) {
862 /* eslint-enable no-underscore-dangle */
863 delete resultMap.sourcesContent;
864 }
865
866 resultMap.sourceRoot = "";
867 resultMap.sources = resultMap.sources.map(source => {
868 // Non-standard syntax from `postcss`
869 if (source.indexOf("<") === 0) {
870 return source;
871 }
872
873 const sourceType = getURLType(source);
874
875 if (sourceType !== "path-relative") {
876 return source;
877 }
878
879 const resourceDirname = _path.default.dirname(loaderContext.resourcePath);
880
881 const absoluteSource = _path.default.resolve(resourceDirname, source);
882
883 const contextifyPath = normalizePath(_path.default.relative(loaderContext.rootContext, absoluteSource));
884 return `webpack://./${contextifyPath}`;
885 });
886 }
887
888 return JSON.stringify(resultMap);
889}
890
891function printParams(media, dedupe, supports, layer) {
892 let result = "";
893
894 if (typeof layer !== "undefined") {
895 result = `, ${JSON.stringify(layer)}`;
896 }
897
898 if (typeof supports !== "undefined") {
899 result = `, ${JSON.stringify(supports)}${result}`;
900 } else if (result.length > 0) {
901 result = `, undefined${result}`;
902 }
903
904 if (dedupe) {
905 result = `, true${result}`;
906 } else if (result.length > 0) {
907 result = `, false${result}`;
908 }
909
910 if (media) {
911 result = `${JSON.stringify(media)}${result}`;
912 } else if (result.length > 0) {
913 result = `""${result}`;
914 }
915
916 return result;
917}
918
919function getModuleCode(result, api, replacements, options, loaderContext) {
920 if (options.modules.exportOnlyLocals === true) {
921 return "";
922 }
923
924 let sourceMapValue = "";
925
926 if (options.sourceMap) {
927 const sourceMap = result.map;
928 sourceMapValue = `,${normalizeSourceMapForRuntime(sourceMap, loaderContext)}`;
929 }
930
931 let code = JSON.stringify(result.css);
932 let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap ? "___CSS_LOADER_API_SOURCEMAP_IMPORT___" : "___CSS_LOADER_API_NO_SOURCEMAP_IMPORT___"});\n`;
933
934 for (const item of api) {
935 const {
936 url,
937 layer,
938 supports,
939 media,
940 dedupe
941 } = item;
942
943 if (url) {
944 // eslint-disable-next-line no-undefined
945 const printedParam = printParams(media, undefined, supports, layer);
946 beforeCode += `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${printedParam.length > 0 ? `, ${printedParam}` : ""}]);\n`;
947 } else {
948 const printedParam = printParams(media, dedupe, supports, layer);
949 beforeCode += `___CSS_LOADER_EXPORT___.i(${item.importName}${printedParam.length > 0 ? `, ${printedParam}` : ""});\n`;
950 }
951 }
952
953 for (const item of replacements) {
954 const {
955 replacementName,
956 importName,
957 localName
958 } = item;
959
960 if (localName) {
961 code = code.replace(new RegExp(replacementName, "g"), () => options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(getValidLocalName(localName, options.modules.exportLocalsConvention))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
962 } else {
963 const {
964 hash,
965 needQuotes
966 } = item;
967 const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? "needQuotes: true" : []);
968 const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";
969 beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
970 code = code.replace(new RegExp(replacementName, "g"), () => `" + ${replacementName} + "`);
971 }
972 } // Indexes description:
973 // 0 - module id
974 // 1 - CSS code
975 // 2 - media
976 // 3 - source map
977 // 4 - supports
978 // 5 - layer
979
980
981 return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
982}
983
984function dashesCamelCase(str) {
985 return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
986}
987
988function getExportCode(exports, replacements, icssPluginUsed, options) {
989 let code = "// Exports\n";
990
991 if (icssPluginUsed) {
992 let localsCode = "";
993
994 const addExportToLocalsCode = (names, value) => {
995 const normalizedNames = Array.isArray(names) ? new Set(names) : new Set([names]);
996
997 for (const name of normalizedNames) {
998 if (options.modules.namedExport) {
999 localsCode += `export var ${name} = ${JSON.stringify(value)};\n`;
1000 } else {
1001 if (localsCode) {
1002 localsCode += `,\n`;
1003 }
1004
1005 localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
1006 }
1007 }
1008 };
1009
1010 for (const {
1011 name,
1012 value
1013 } of exports) {
1014 addExportToLocalsCode(options.modules.exportLocalsConvention(name), value);
1015 }
1016
1017 for (const item of replacements) {
1018 const {
1019 replacementName,
1020 localName
1021 } = item;
1022
1023 if (localName) {
1024 const {
1025 importName
1026 } = item;
1027 localsCode = localsCode.replace(new RegExp(replacementName, "g"), () => {
1028 if (options.modules.namedExport) {
1029 return `" + ${importName}_NAMED___[${JSON.stringify(getValidLocalName(localName, options.modules.exportLocalsConvention))}] + "`;
1030 } else if (options.modules.exportOnlyLocals) {
1031 return `" + ${importName}[${JSON.stringify(localName)}] + "`;
1032 }
1033
1034 return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
1035 });
1036 } else {
1037 localsCode = localsCode.replace(new RegExp(replacementName, "g"), () => `" + ${replacementName} + "`);
1038 }
1039 }
1040
1041 if (options.modules.exportOnlyLocals) {
1042 code += options.modules.namedExport ? localsCode : `${options.esModule ? "export default" : "module.exports ="} {\n${localsCode}\n};\n`;
1043 return code;
1044 }
1045
1046 code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {${localsCode ? `\n${localsCode}\n` : ""}};\n`;
1047 }
1048
1049 const isCSSStyleSheetExport = options.exportType === "css-style-sheet";
1050
1051 if (isCSSStyleSheetExport) {
1052 code += "var ___CSS_LOADER_STYLE_SHEET___ = new CSSStyleSheet();\n";
1053 code += "___CSS_LOADER_STYLE_SHEET___.replaceSync(___CSS_LOADER_EXPORT___.toString());\n";
1054 }
1055
1056 let finalExport;
1057
1058 switch (options.exportType) {
1059 case "string":
1060 finalExport = "___CSS_LOADER_EXPORT___.toString()";
1061 break;
1062
1063 case "css-style-sheet":
1064 finalExport = "___CSS_LOADER_STYLE_SHEET___";
1065 break;
1066
1067 default:
1068 case "array":
1069 finalExport = "___CSS_LOADER_EXPORT___";
1070 break;
1071 }
1072
1073 code += `${options.esModule ? "export default" : "module.exports ="} ${finalExport};\n`;
1074 return code;
1075}
1076
1077async function resolveRequests(resolve, context, possibleRequests) {
1078 return resolve(context, possibleRequests[0]).then(result => result).catch(error => {
1079 const [, ...tailPossibleRequests] = possibleRequests;
1080
1081 if (tailPossibleRequests.length === 0) {
1082 throw error;
1083 }
1084
1085 return resolveRequests(resolve, context, tailPossibleRequests);
1086 });
1087}
1088
1089function isURLRequestable(url, options = {}) {
1090 // Protocol-relative URLs
1091 if (/^\/\//.test(url)) {
1092 return {
1093 requestable: false,
1094 needResolve: false
1095 };
1096 } // `#` URLs
1097
1098
1099 if (/^#/.test(url)) {
1100 return {
1101 requestable: false,
1102 needResolve: false
1103 };
1104 } // Data URI
1105
1106
1107 if (isDataUrl(url) && options.isSupportDataURL) {
1108 try {
1109 decodeURIComponent(url);
1110 } catch (ignoreError) {
1111 return {
1112 requestable: false,
1113 needResolve: false
1114 };
1115 }
1116
1117 return {
1118 requestable: true,
1119 needResolve: false
1120 };
1121 } // `file:` protocol
1122
1123
1124 if (/^file:/i.test(url)) {
1125 return {
1126 requestable: true,
1127 needResolve: true
1128 };
1129 } // Absolute URLs
1130
1131
1132 if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !NATIVE_WIN32_PATH.test(url)) {
1133 if (options.isSupportAbsoluteURL && /^https?:/i.test(url)) {
1134 return {
1135 requestable: true,
1136 needResolve: false
1137 };
1138 }
1139
1140 return {
1141 requestable: false,
1142 needResolve: false
1143 };
1144 }
1145
1146 return {
1147 requestable: true,
1148 needResolve: true
1149 };
1150}
1151
1152function sort(a, b) {
1153 return a.index - b.index;
1154}
1155
1156function combineRequests(preRequest, url) {
1157 const idx = url.indexOf("!=!");
1158 return idx !== -1 ? url.slice(0, idx + 3) + preRequest + url.slice(idx + 3) : preRequest + url;
1159}
\No newline at end of file