UNPKG

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