UNPKG

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