source: frontend/node_modules/css-loader/dist/utils.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

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