utils.js 37 KB

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