utils.js 38 KB

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