CssParser.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const vm = require("vm");
  7. const CommentCompilationWarning = require("../CommentCompilationWarning");
  8. const ModuleDependencyWarning = require("../ModuleDependencyWarning");
  9. const { CSS_MODULE_TYPE_AUTO } = require("../ModuleTypeConstants");
  10. const Parser = require("../Parser");
  11. const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
  12. const WebpackError = require("../WebpackError");
  13. const ConstDependency = require("../dependencies/ConstDependency");
  14. const CssIcssExportDependency = require("../dependencies/CssIcssExportDependency");
  15. const CssIcssImportDependency = require("../dependencies/CssIcssImportDependency");
  16. const CssIcssSymbolDependency = require("../dependencies/CssIcssSymbolDependency");
  17. const CssImportDependency = require("../dependencies/CssImportDependency");
  18. const CssLocalIdentifierDependency = require("../dependencies/CssLocalIdentifierDependency");
  19. const CssSelfLocalIdentifierDependency = require("../dependencies/CssSelfLocalIdentifierDependency");
  20. const CssUrlDependency = require("../dependencies/CssUrlDependency");
  21. const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
  22. const binarySearchBounds = require("../util/binarySearchBounds");
  23. const { parseResource } = require("../util/identifier");
  24. const {
  25. webpackCommentRegExp,
  26. createMagicCommentContext
  27. } = require("../util/magicComment");
  28. const walkCssTokens = require("./walkCssTokens");
  29. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  30. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  31. /** @typedef {import("../Parser").ParserState} ParserState */
  32. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  33. /** @typedef {import("./walkCssTokens").CssTokenCallbacks} CssTokenCallbacks */
  34. /** @typedef {[number, number]} Range */
  35. /** @typedef {{ line: number, column: number }} Position */
  36. /** @typedef {{ value: string, range: Range, loc: { start: Position, end: Position } }} Comment */
  37. const CC_COLON = ":".charCodeAt(0);
  38. const CC_SLASH = "/".charCodeAt(0);
  39. const CC_LEFT_PARENTHESIS = "(".charCodeAt(0);
  40. const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0);
  41. const CC_LOWER_F = "f".charCodeAt(0);
  42. const CC_UPPER_F = "F".charCodeAt(0);
  43. // https://www.w3.org/TR/css-syntax-3/#newline
  44. // We don't have `preprocessing` stage, so we need specify all of them
  45. const STRING_MULTILINE = /\\[\n\r\f]/g;
  46. // https://www.w3.org/TR/css-syntax-3/#whitespace
  47. const TRIM_WHITE_SPACES = /(^[ \t\n\r\f]*|[ \t\n\r\f]*$)/g;
  48. const UNESCAPE = /\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g;
  49. const IMAGE_SET_FUNCTION = /^(-\w+-)?image-set$/i;
  50. const OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE = /^@(-\w+-)?keyframes$/;
  51. const OPTIONALLY_VENDOR_PREFIXED_ANIMATION_PROPERTY =
  52. /^(-\w+-)?animation(-name)?$/i;
  53. const IS_MODULES = /\.module(s)?\.[^.]+$/i;
  54. const CSS_COMMENT = /\/\*((?!\*\/).*?)\*\//g;
  55. /**
  56. * @param {string} str url string
  57. * @param {boolean} isString is url wrapped in quotes
  58. * @returns {string} normalized url
  59. */
  60. const normalizeUrl = (str, isString) => {
  61. // Remove extra spaces and newlines:
  62. // `url("im\
  63. // g.png")`
  64. if (isString) {
  65. str = str.replace(STRING_MULTILINE, "");
  66. }
  67. str = str
  68. // Remove unnecessary spaces from `url(" img.png ")`
  69. .replace(TRIM_WHITE_SPACES, "")
  70. // Unescape
  71. .replace(UNESCAPE, match => {
  72. if (match.length > 2) {
  73. return String.fromCharCode(Number.parseInt(match.slice(1).trim(), 16));
  74. }
  75. return match[1];
  76. });
  77. if (/^data:/i.test(str)) {
  78. return str;
  79. }
  80. if (str.includes("%")) {
  81. // Convert `url('%2E/img.png')` -> `url('./img.png')`
  82. try {
  83. str = decodeURIComponent(str);
  84. } catch (_err) {
  85. // Ignore
  86. }
  87. }
  88. return str;
  89. };
  90. // eslint-disable-next-line no-useless-escape
  91. const regexSingleEscape = /[ -,.\/:-@[\]\^`{-~]/;
  92. const regexExcessiveSpaces =
  93. /(^|\\+)?(\\[A-F0-9]{1,6})\u0020(?![a-fA-F0-9\u0020])/g;
  94. /**
  95. * @param {string} str string
  96. * @returns {string} escaped identifier
  97. */
  98. const escapeIdentifier = str => {
  99. let output = "";
  100. let counter = 0;
  101. while (counter < str.length) {
  102. const character = str.charAt(counter++);
  103. let value;
  104. if (/[\t\n\f\r\u000B]/.test(character)) {
  105. const codePoint = character.charCodeAt(0);
  106. value = `\\${codePoint.toString(16).toUpperCase()} `;
  107. } else if (character === "\\" || regexSingleEscape.test(character)) {
  108. value = `\\${character}`;
  109. } else {
  110. value = character;
  111. }
  112. output += value;
  113. }
  114. const firstChar = str.charAt(0);
  115. if (/^-[-\d]/.test(output)) {
  116. output = `\\-${output.slice(1)}`;
  117. } else if (/\d/.test(firstChar)) {
  118. output = `\\3${firstChar} ${output.slice(1)}`;
  119. }
  120. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  121. // since they’re redundant. Note that this is only possible if the escape
  122. // sequence isn’t preceded by an odd number of backslashes.
  123. output = output.replace(regexExcessiveSpaces, ($0, $1, $2) => {
  124. if ($1 && $1.length % 2) {
  125. // It’s not safe to remove the space, so don’t.
  126. return $0;
  127. }
  128. // Strip the space.
  129. return ($1 || "") + $2;
  130. });
  131. return output;
  132. };
  133. const CONTAINS_ESCAPE = /\\/;
  134. /**
  135. * @param {string} str string
  136. * @returns {[string, number] | undefined} hex
  137. */
  138. const gobbleHex = str => {
  139. const lower = str.toLowerCase();
  140. let hex = "";
  141. let spaceTerminated = false;
  142. for (let i = 0; i < 6 && lower[i] !== undefined; i++) {
  143. const code = lower.charCodeAt(i);
  144. // check to see if we are dealing with a valid hex char [a-f|0-9]
  145. const valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57);
  146. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  147. spaceTerminated = code === 32;
  148. if (!valid) break;
  149. hex += lower[i];
  150. }
  151. if (hex.length === 0) return undefined;
  152. const codePoint = Number.parseInt(hex, 16);
  153. const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
  154. // Add special case for
  155. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  156. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  157. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
  158. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  159. }
  160. return [
  161. String.fromCodePoint(codePoint),
  162. hex.length + (spaceTerminated ? 1 : 0)
  163. ];
  164. };
  165. /**
  166. * @param {string} str string
  167. * @returns {string} unescaped string
  168. */
  169. const unescapeIdentifier = str => {
  170. const needToProcess = CONTAINS_ESCAPE.test(str);
  171. if (!needToProcess) return str;
  172. let ret = "";
  173. for (let i = 0; i < str.length; i++) {
  174. if (str[i] === "\\") {
  175. const gobbled = gobbleHex(str.slice(i + 1, i + 7));
  176. if (gobbled !== undefined) {
  177. ret += gobbled[0];
  178. i += gobbled[1];
  179. continue;
  180. }
  181. // Retain a pair of \\ if double escaped `\\\\`
  182. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  183. if (str[i + 1] === "\\") {
  184. ret += "\\";
  185. i += 1;
  186. continue;
  187. }
  188. // if \\ is at the end of the string retain it
  189. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  190. if (str.length === i + 1) {
  191. ret += str[i];
  192. }
  193. continue;
  194. }
  195. ret += str[i];
  196. }
  197. return ret;
  198. };
  199. class LocConverter {
  200. /**
  201. * @param {string} input input
  202. */
  203. constructor(input) {
  204. this._input = input;
  205. this.line = 1;
  206. this.column = 0;
  207. this.pos = 0;
  208. }
  209. /**
  210. * @param {number} pos position
  211. * @returns {LocConverter} location converter
  212. */
  213. get(pos) {
  214. if (this.pos !== pos) {
  215. if (this.pos < pos) {
  216. const str = this._input.slice(this.pos, pos);
  217. let i = str.lastIndexOf("\n");
  218. if (i === -1) {
  219. this.column += str.length;
  220. } else {
  221. this.column = str.length - i - 1;
  222. this.line++;
  223. while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1)
  224. this.line++;
  225. }
  226. } else {
  227. let i = this._input.lastIndexOf("\n", this.pos);
  228. while (i >= pos) {
  229. this.line--;
  230. i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1;
  231. }
  232. this.column = pos - i;
  233. }
  234. this.pos = pos;
  235. }
  236. return this;
  237. }
  238. }
  239. const EMPTY_COMMENT_OPTIONS = {
  240. options: null,
  241. errors: null
  242. };
  243. const CSS_MODE_TOP_LEVEL = 0;
  244. const CSS_MODE_IN_BLOCK = 1;
  245. const eatUntilSemi = walkCssTokens.eatUntil(";");
  246. const eatUntilLeftCurly = walkCssTokens.eatUntil("{");
  247. const eatSemi = walkCssTokens.eatUntil(";");
  248. /**
  249. * @typedef {object} CssParserOptions
  250. * @property {boolean=} importOption need handle `@import`
  251. * @property {boolean=} url need handle URLs
  252. * @property {("pure" | "global" | "local" | "auto")=} defaultMode default mode
  253. * @property {boolean=} namedExports is named exports
  254. */
  255. class CssParser extends Parser {
  256. /**
  257. * @param {CssParserOptions=} options options
  258. */
  259. constructor({
  260. defaultMode = "pure",
  261. importOption = true,
  262. url = true,
  263. namedExports = true
  264. } = {}) {
  265. super();
  266. this.defaultMode = defaultMode;
  267. this.import = importOption;
  268. this.url = url;
  269. this.namedExports = namedExports;
  270. /** @type {Comment[] | undefined} */
  271. this.comments = undefined;
  272. this.magicCommentContext = createMagicCommentContext();
  273. }
  274. /**
  275. * @param {ParserState} state parser state
  276. * @param {string} message warning message
  277. * @param {LocConverter} locConverter location converter
  278. * @param {number} start start offset
  279. * @param {number} end end offset
  280. */
  281. _emitWarning(state, message, locConverter, start, end) {
  282. const { line: sl, column: sc } = locConverter.get(start);
  283. const { line: el, column: ec } = locConverter.get(end);
  284. state.current.addWarning(
  285. new ModuleDependencyWarning(state.module, new WebpackError(message), {
  286. start: { line: sl, column: sc },
  287. end: { line: el, column: ec }
  288. })
  289. );
  290. }
  291. /**
  292. * @param {string | Buffer | PreparsedAst} source the source to parse
  293. * @param {ParserState} state the parser state
  294. * @returns {ParserState} the parser state
  295. */
  296. parse(source, state) {
  297. if (Buffer.isBuffer(source)) {
  298. source = source.toString("utf-8");
  299. } else if (typeof source === "object") {
  300. throw new Error("webpackAst is unexpected for the CssParser");
  301. }
  302. if (source[0] === "\uFEFF") {
  303. source = source.slice(1);
  304. }
  305. let mode = this.defaultMode;
  306. const module = state.module;
  307. if (
  308. mode === "auto" &&
  309. module.type === CSS_MODULE_TYPE_AUTO &&
  310. IS_MODULES.test(
  311. parseResource(module.matchResource || module.resource).path
  312. )
  313. ) {
  314. mode = "local";
  315. }
  316. const isModules = mode === "global" || mode === "local";
  317. /** @type {BuildMeta} */
  318. (module.buildMeta).isCSSModule = isModules;
  319. const locConverter = new LocConverter(source);
  320. /** @type {number} */
  321. let scope = CSS_MODE_TOP_LEVEL;
  322. /** @type {boolean} */
  323. let allowImportAtRule = true;
  324. /** @type [string, number, number][] */
  325. const balanced = [];
  326. let lastTokenEndForComments = 0;
  327. /** @type {boolean} */
  328. let isNextRulePrelude = isModules;
  329. /** @type {number} */
  330. let blockNestingLevel = 0;
  331. /** @type {"local" | "global" | undefined} */
  332. let modeData;
  333. /** @type {boolean} */
  334. let inAnimationProperty = false;
  335. /** @type {[number, number, boolean] | undefined} */
  336. let lastIdentifier;
  337. /** @type {Set<string>} */
  338. const declaredCssVariables = new Set();
  339. /** @typedef {{ path?: string, value: string }} IcssDefinition */
  340. /** @type {Map<string, IcssDefinition>} */
  341. const icssDefinitions = new Map();
  342. /**
  343. * @param {string} input input
  344. * @param {number} pos position
  345. * @returns {boolean} true, when next is nested syntax
  346. */
  347. const isNextNestedSyntax = (input, pos) => {
  348. pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
  349. if (input[pos] === "}") {
  350. return false;
  351. }
  352. // According spec only identifier can be used as a property name
  353. const isIdentifier = walkCssTokens.isIdentStartCodePoint(
  354. input.charCodeAt(pos)
  355. );
  356. return !isIdentifier;
  357. };
  358. /**
  359. * @returns {boolean} true, when in local scope
  360. */
  361. const isLocalMode = () =>
  362. modeData === "local" || (mode === "local" && modeData === undefined);
  363. /**
  364. * @param {string} input input
  365. * @param {number} pos start position
  366. * @param {(input: string, pos: number) => number} eater eater
  367. * @returns {[number,string]} new position and text
  368. */
  369. const eatText = (input, pos, eater) => {
  370. let text = "";
  371. for (;;) {
  372. if (input.charCodeAt(pos) === CC_SLASH) {
  373. const newPos = walkCssTokens.eatComments(input, pos);
  374. if (pos !== newPos) {
  375. pos = newPos;
  376. if (pos === input.length) break;
  377. } else {
  378. text += "/";
  379. pos++;
  380. if (pos === input.length) break;
  381. }
  382. }
  383. const newPos = eater(input, pos);
  384. if (pos !== newPos) {
  385. text += input.slice(pos, newPos);
  386. pos = newPos;
  387. } else {
  388. break;
  389. }
  390. if (pos === input.length) break;
  391. }
  392. return [pos, text.trimEnd()];
  393. };
  394. /**
  395. * @param {0 | 1} type import or export
  396. * @param {string} input input
  397. * @param {number} pos start position
  398. * @returns {number} position after parse
  399. */
  400. const parseImportOrExport = (type, input, pos) => {
  401. pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
  402. /** @type {string | undefined} */
  403. let importPath;
  404. if (type === 0) {
  405. let cc = input.charCodeAt(pos);
  406. if (cc !== CC_LEFT_PARENTHESIS) {
  407. this._emitWarning(
  408. state,
  409. `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected '(')`,
  410. locConverter,
  411. pos,
  412. pos
  413. );
  414. return pos;
  415. }
  416. pos++;
  417. const stringStart = pos;
  418. const str = walkCssTokens.eatString(input, pos);
  419. if (!str) {
  420. this._emitWarning(
  421. state,
  422. `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected string)`,
  423. locConverter,
  424. stringStart,
  425. pos
  426. );
  427. return pos;
  428. }
  429. importPath = input.slice(str[0] + 1, str[1] - 1);
  430. pos = str[1];
  431. pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
  432. cc = input.charCodeAt(pos);
  433. if (cc !== CC_RIGHT_PARENTHESIS) {
  434. this._emitWarning(
  435. state,
  436. `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected ')')`,
  437. locConverter,
  438. pos,
  439. pos
  440. );
  441. return pos;
  442. }
  443. pos++;
  444. pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
  445. }
  446. /**
  447. * @param {string} name name
  448. * @param {string} value value
  449. * @param {number} start start of position
  450. * @param {number} end end of position
  451. */
  452. const createDep = (name, value, start, end) => {
  453. if (type === 0) {
  454. icssDefinitions.set(name, {
  455. path: /** @type {string} */ (importPath),
  456. value
  457. });
  458. } else if (type === 1) {
  459. const dep = new CssIcssExportDependency(name, value);
  460. const { line: sl, column: sc } = locConverter.get(start);
  461. const { line: el, column: ec } = locConverter.get(end);
  462. dep.setLoc(sl, sc, el, ec);
  463. module.addDependency(dep);
  464. }
  465. };
  466. let needTerminate = false;
  467. let balanced = 0;
  468. /** @type {undefined | 0 | 1 | 2} */
  469. let scope;
  470. /** @typedef {[number, number]} Name */
  471. /** @type {Name | undefined} */
  472. let name;
  473. /** @type {number | undefined} */
  474. let value;
  475. /** @type {CssTokenCallbacks} */
  476. const callbacks = {
  477. leftCurlyBracket: (_input, _start, end) => {
  478. balanced++;
  479. if (scope === undefined) {
  480. scope = 0;
  481. }
  482. return end;
  483. },
  484. rightCurlyBracket: (_input, _start, end) => {
  485. balanced--;
  486. if (scope === 2) {
  487. const [nameStart, nameEnd] = /** @type {Name} */ (name);
  488. createDep(
  489. input.slice(nameStart, nameEnd),
  490. input.slice(value, end - 1).trim(),
  491. nameEnd,
  492. end - 1
  493. );
  494. scope = 0;
  495. }
  496. if (balanced === 0 && scope === 0) {
  497. needTerminate = true;
  498. }
  499. return end;
  500. },
  501. identifier: (_input, start, end) => {
  502. if (scope === 0) {
  503. name = [start, end];
  504. scope = 1;
  505. }
  506. return end;
  507. },
  508. colon: (_input, _start, end) => {
  509. if (scope === 1) {
  510. scope = 2;
  511. value = walkCssTokens.eatWhitespace(input, end);
  512. return value;
  513. }
  514. return end;
  515. },
  516. semicolon: (input, _start, end) => {
  517. if (scope === 2) {
  518. const [nameStart, nameEnd] = /** @type {Name} */ (name);
  519. createDep(
  520. input.slice(nameStart, nameEnd),
  521. input.slice(value, end - 1),
  522. nameEnd,
  523. end - 1
  524. );
  525. scope = 0;
  526. }
  527. return end;
  528. },
  529. needTerminate: () => needTerminate
  530. };
  531. pos = walkCssTokens(input, pos, callbacks);
  532. pos = walkCssTokens.eatWhiteLine(input, pos);
  533. return pos;
  534. };
  535. const eatPropertyName = walkCssTokens.eatUntil(":{};");
  536. /**
  537. * @param {string} input input
  538. * @param {number} pos name start position
  539. * @param {number} end name end position
  540. * @returns {number} position after handling
  541. */
  542. const processLocalDeclaration = (input, pos, end) => {
  543. modeData = undefined;
  544. pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
  545. const propertyNameStart = pos;
  546. const [propertyNameEnd, propertyName] = eatText(
  547. input,
  548. pos,
  549. eatPropertyName
  550. );
  551. if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return end;
  552. pos = propertyNameEnd + 1;
  553. if (propertyName.startsWith("--") && propertyName.length >= 3) {
  554. // CSS Variable
  555. const { line: sl, column: sc } = locConverter.get(propertyNameStart);
  556. const { line: el, column: ec } = locConverter.get(propertyNameEnd);
  557. const name = unescapeIdentifier(propertyName.slice(2));
  558. const dep = new CssLocalIdentifierDependency(
  559. name,
  560. [propertyNameStart, propertyNameEnd],
  561. "--"
  562. );
  563. dep.setLoc(sl, sc, el, ec);
  564. module.addDependency(dep);
  565. declaredCssVariables.add(name);
  566. } else if (
  567. OPTIONALLY_VENDOR_PREFIXED_ANIMATION_PROPERTY.test(propertyName)
  568. ) {
  569. inAnimationProperty = true;
  570. }
  571. return pos;
  572. };
  573. /**
  574. * @param {string} input input
  575. */
  576. const processDeclarationValueDone = input => {
  577. if (inAnimationProperty && lastIdentifier) {
  578. const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]);
  579. const { line: el, column: ec } = locConverter.get(lastIdentifier[1]);
  580. const name = unescapeIdentifier(
  581. lastIdentifier[2]
  582. ? input.slice(lastIdentifier[0], lastIdentifier[1])
  583. : input.slice(lastIdentifier[0] + 1, lastIdentifier[1] - 1)
  584. );
  585. const dep = new CssSelfLocalIdentifierDependency(name, [
  586. lastIdentifier[0],
  587. lastIdentifier[1]
  588. ]);
  589. dep.setLoc(sl, sc, el, ec);
  590. module.addDependency(dep);
  591. lastIdentifier = undefined;
  592. }
  593. };
  594. /**
  595. * @param {string} input input
  596. * @param {number} start start
  597. * @param {number} end end
  598. * @returns {number} end
  599. */
  600. const comment = (input, start, end) => {
  601. if (!this.comments) this.comments = [];
  602. const { line: sl, column: sc } = locConverter.get(start);
  603. const { line: el, column: ec } = locConverter.get(end);
  604. /** @type {Comment} */
  605. const comment = {
  606. value: input.slice(start + 2, end - 2),
  607. range: [start, end],
  608. loc: {
  609. start: { line: sl, column: sc },
  610. end: { line: el, column: ec }
  611. }
  612. };
  613. this.comments.push(comment);
  614. return end;
  615. };
  616. walkCssTokens(source, 0, {
  617. comment,
  618. leftCurlyBracket: (input, start, end) => {
  619. switch (scope) {
  620. case CSS_MODE_TOP_LEVEL: {
  621. allowImportAtRule = false;
  622. scope = CSS_MODE_IN_BLOCK;
  623. if (isModules) {
  624. blockNestingLevel = 1;
  625. isNextRulePrelude = isNextNestedSyntax(input, end);
  626. }
  627. break;
  628. }
  629. case CSS_MODE_IN_BLOCK: {
  630. if (isModules) {
  631. blockNestingLevel++;
  632. isNextRulePrelude = isNextNestedSyntax(input, end);
  633. }
  634. break;
  635. }
  636. }
  637. return end;
  638. },
  639. rightCurlyBracket: (input, start, end) => {
  640. switch (scope) {
  641. case CSS_MODE_IN_BLOCK: {
  642. if (--blockNestingLevel === 0) {
  643. scope = CSS_MODE_TOP_LEVEL;
  644. if (isModules) {
  645. isNextRulePrelude = true;
  646. modeData = undefined;
  647. }
  648. } else if (isModules) {
  649. if (isLocalMode()) {
  650. processDeclarationValueDone(input);
  651. inAnimationProperty = false;
  652. }
  653. isNextRulePrelude = isNextNestedSyntax(input, end);
  654. }
  655. break;
  656. }
  657. }
  658. return end;
  659. },
  660. url: (input, start, end, contentStart, contentEnd) => {
  661. if (!this.url) {
  662. return end;
  663. }
  664. const { options, errors: commentErrors } = this.parseCommentOptions([
  665. lastTokenEndForComments,
  666. end
  667. ]);
  668. if (commentErrors) {
  669. for (const e of commentErrors) {
  670. const { comment } = e;
  671. state.module.addWarning(
  672. new CommentCompilationWarning(
  673. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  674. comment.loc
  675. )
  676. );
  677. }
  678. }
  679. if (options && options.webpackIgnore !== undefined) {
  680. if (typeof options.webpackIgnore !== "boolean") {
  681. const { line: sl, column: sc } = locConverter.get(
  682. lastTokenEndForComments
  683. );
  684. const { line: el, column: ec } = locConverter.get(end);
  685. state.module.addWarning(
  686. new UnsupportedFeatureWarning(
  687. `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`,
  688. {
  689. start: { line: sl, column: sc },
  690. end: { line: el, column: ec }
  691. }
  692. )
  693. );
  694. } else if (options.webpackIgnore) {
  695. return end;
  696. }
  697. }
  698. const value = normalizeUrl(
  699. input.slice(contentStart, contentEnd),
  700. false
  701. );
  702. // Ignore `url()`, `url('')` and `url("")`, they are valid by spec
  703. if (value.length === 0) return end;
  704. const dep = new CssUrlDependency(value, [start, end], "url");
  705. const { line: sl, column: sc } = locConverter.get(start);
  706. const { line: el, column: ec } = locConverter.get(end);
  707. dep.setLoc(sl, sc, el, ec);
  708. module.addDependency(dep);
  709. module.addCodeGenerationDependency(dep);
  710. return end;
  711. },
  712. string: (_input, start, end) => {
  713. switch (scope) {
  714. case CSS_MODE_IN_BLOCK: {
  715. if (inAnimationProperty && balanced.length === 0) {
  716. lastIdentifier = [start, end, false];
  717. }
  718. }
  719. }
  720. return end;
  721. },
  722. atKeyword: (input, start, end) => {
  723. const name = input.slice(start, end).toLowerCase();
  724. switch (name) {
  725. case "@namespace": {
  726. this._emitWarning(
  727. state,
  728. "'@namespace' is not supported in bundled CSS",
  729. locConverter,
  730. start,
  731. end
  732. );
  733. return eatUntilSemi(input, start);
  734. }
  735. case "@import": {
  736. if (!this.import) {
  737. return eatSemi(input, end);
  738. }
  739. if (!allowImportAtRule) {
  740. this._emitWarning(
  741. state,
  742. "Any '@import' rules must precede all other rules",
  743. locConverter,
  744. start,
  745. end
  746. );
  747. return end;
  748. }
  749. const tokens = walkCssTokens.eatImportTokens(input, end, {
  750. comment
  751. });
  752. if (!tokens[3]) return end;
  753. const semi = tokens[3][1];
  754. if (!tokens[0]) {
  755. this._emitWarning(
  756. state,
  757. `Expected URL in '${input.slice(start, semi)}'`,
  758. locConverter,
  759. start,
  760. semi
  761. );
  762. return end;
  763. }
  764. const urlToken = tokens[0];
  765. const url = normalizeUrl(
  766. input.slice(urlToken[2], urlToken[3]),
  767. true
  768. );
  769. const newline = walkCssTokens.eatWhiteLine(input, semi);
  770. const { options, errors: commentErrors } = this.parseCommentOptions(
  771. [end, urlToken[1]]
  772. );
  773. if (commentErrors) {
  774. for (const e of commentErrors) {
  775. const { comment } = e;
  776. state.module.addWarning(
  777. new CommentCompilationWarning(
  778. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  779. comment.loc
  780. )
  781. );
  782. }
  783. }
  784. if (options && options.webpackIgnore !== undefined) {
  785. if (typeof options.webpackIgnore !== "boolean") {
  786. const { line: sl, column: sc } = locConverter.get(start);
  787. const { line: el, column: ec } = locConverter.get(newline);
  788. state.module.addWarning(
  789. new UnsupportedFeatureWarning(
  790. `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`,
  791. {
  792. start: { line: sl, column: sc },
  793. end: { line: el, column: ec }
  794. }
  795. )
  796. );
  797. } else if (options.webpackIgnore) {
  798. return newline;
  799. }
  800. }
  801. if (url.length === 0) {
  802. const { line: sl, column: sc } = locConverter.get(start);
  803. const { line: el, column: ec } = locConverter.get(newline);
  804. const dep = new ConstDependency("", [start, newline]);
  805. module.addPresentationalDependency(dep);
  806. dep.setLoc(sl, sc, el, ec);
  807. return newline;
  808. }
  809. let layer;
  810. if (tokens[1]) {
  811. layer = input.slice(tokens[1][0] + 6, tokens[1][1] - 1).trim();
  812. }
  813. let supports;
  814. if (tokens[2]) {
  815. supports = input.slice(tokens[2][0] + 9, tokens[2][1] - 1).trim();
  816. }
  817. const last = tokens[2] || tokens[1] || tokens[0];
  818. const mediaStart = walkCssTokens.eatWhitespaceAndComments(
  819. input,
  820. last[1]
  821. );
  822. let media;
  823. if (mediaStart !== semi - 1) {
  824. media = input.slice(mediaStart, semi - 1).trim();
  825. }
  826. const { line: sl, column: sc } = locConverter.get(start);
  827. const { line: el, column: ec } = locConverter.get(newline);
  828. const dep = new CssImportDependency(
  829. url,
  830. [start, newline],
  831. layer,
  832. supports && supports.length > 0 ? supports : undefined,
  833. media && media.length > 0 ? media : undefined
  834. );
  835. dep.setLoc(sl, sc, el, ec);
  836. module.addDependency(dep);
  837. return newline;
  838. }
  839. default: {
  840. if (isModules) {
  841. if (name === "@value") {
  842. const semi = eatUntilSemi(input, end);
  843. const atRuleEnd = semi + 1;
  844. const params = input.slice(end, semi);
  845. let [alias, from] = params.split(/\s*from\s*/);
  846. if (from) {
  847. const aliases = alias
  848. .replace(CSS_COMMENT, " ")
  849. .trim()
  850. .replace(/^\(|\)$/g, "")
  851. .split(/\s*,\s*/);
  852. from = from.replace(CSS_COMMENT, "").trim();
  853. const isExplicitImport = from[0] === "'" || from[0] === '"';
  854. if (isExplicitImport) {
  855. from = from.slice(1, -1);
  856. }
  857. for (const alias of aliases) {
  858. const [name, aliasName] = alias.split(/\s*as\s*/);
  859. icssDefinitions.set(aliasName || name, {
  860. value: name,
  861. path: from
  862. });
  863. }
  864. } else {
  865. const ident = walkCssTokens.eatIdentSequence(alias, 0);
  866. if (!ident) {
  867. this._emitWarning(
  868. state,
  869. `Broken '@value' at-rule: ${input.slice(
  870. start,
  871. atRuleEnd
  872. )}'`,
  873. locConverter,
  874. start,
  875. atRuleEnd
  876. );
  877. const dep = new ConstDependency("", [start, atRuleEnd]);
  878. module.addPresentationalDependency(dep);
  879. return atRuleEnd;
  880. }
  881. const pos = walkCssTokens.eatWhitespaceAndComments(
  882. alias,
  883. ident[1]
  884. );
  885. const name = alias.slice(ident[0], ident[1]);
  886. let value =
  887. alias.charCodeAt(pos) === CC_COLON
  888. ? alias.slice(pos + 1)
  889. : alias.slice(ident[1]);
  890. if (value && !/^\s+$/.test(value)) {
  891. value = value.trim();
  892. }
  893. if (icssDefinitions.has(value)) {
  894. const def =
  895. /** @type {IcssDefinition} */
  896. (icssDefinitions.get(value));
  897. value = def.value;
  898. }
  899. icssDefinitions.set(name, { value });
  900. const dep = new CssIcssExportDependency(name, value);
  901. const { line: sl, column: sc } = locConverter.get(start);
  902. const { line: el, column: ec } = locConverter.get(end);
  903. dep.setLoc(sl, sc, el, ec);
  904. module.addDependency(dep);
  905. }
  906. const dep = new ConstDependency("", [start, atRuleEnd]);
  907. module.addPresentationalDependency(dep);
  908. return atRuleEnd;
  909. } else if (
  910. OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE.test(name) &&
  911. isLocalMode()
  912. ) {
  913. const ident = walkCssTokens.eatIdentSequenceOrString(
  914. input,
  915. end
  916. );
  917. if (!ident) return end;
  918. const name = unescapeIdentifier(
  919. ident[2] === true
  920. ? input.slice(ident[0], ident[1])
  921. : input.slice(ident[0] + 1, ident[1] - 1)
  922. );
  923. const { line: sl, column: sc } = locConverter.get(ident[0]);
  924. const { line: el, column: ec } = locConverter.get(ident[1]);
  925. const dep = new CssLocalIdentifierDependency(name, [
  926. ident[0],
  927. ident[1]
  928. ]);
  929. dep.setLoc(sl, sc, el, ec);
  930. module.addDependency(dep);
  931. return ident[1];
  932. } else if (name === "@property" && isLocalMode()) {
  933. const ident = walkCssTokens.eatIdentSequence(input, end);
  934. if (!ident) return end;
  935. let name = input.slice(ident[0], ident[1]);
  936. if (!name.startsWith("--") || name.length < 3) return end;
  937. name = unescapeIdentifier(name.slice(2));
  938. declaredCssVariables.add(name);
  939. const { line: sl, column: sc } = locConverter.get(ident[0]);
  940. const { line: el, column: ec } = locConverter.get(ident[1]);
  941. const dep = new CssLocalIdentifierDependency(
  942. name,
  943. [ident[0], ident[1]],
  944. "--"
  945. );
  946. dep.setLoc(sl, sc, el, ec);
  947. module.addDependency(dep);
  948. return ident[1];
  949. } else if (name === "@scope") {
  950. isNextRulePrelude = true;
  951. return end;
  952. }
  953. isNextRulePrelude = false;
  954. }
  955. }
  956. }
  957. return end;
  958. },
  959. semicolon: (input, start, end) => {
  960. if (isModules && scope === CSS_MODE_IN_BLOCK) {
  961. if (isLocalMode()) {
  962. processDeclarationValueDone(input);
  963. inAnimationProperty = false;
  964. }
  965. isNextRulePrelude = isNextNestedSyntax(input, end);
  966. }
  967. return end;
  968. },
  969. identifier: (input, start, end) => {
  970. if (isModules) {
  971. const name = input.slice(start, end);
  972. if (icssDefinitions.has(name)) {
  973. let { path, value } =
  974. /** @type {IcssDefinition} */
  975. (icssDefinitions.get(name));
  976. if (path) {
  977. if (icssDefinitions.has(path)) {
  978. const definition =
  979. /** @type {IcssDefinition} */
  980. (icssDefinitions.get(path));
  981. path = definition.value.slice(1, -1);
  982. }
  983. const dep = new CssIcssImportDependency(path, value, [
  984. start,
  985. end - 1
  986. ]);
  987. const { line: sl, column: sc } = locConverter.get(start);
  988. const { line: el, column: ec } = locConverter.get(end - 1);
  989. dep.setLoc(sl, sc, el, ec);
  990. module.addDependency(dep);
  991. } else {
  992. const { line: sl, column: sc } = locConverter.get(start);
  993. const { line: el, column: ec } = locConverter.get(end);
  994. const dep = new CssIcssSymbolDependency(name, value, [
  995. start,
  996. end
  997. ]);
  998. dep.setLoc(sl, sc, el, ec);
  999. module.addDependency(dep);
  1000. }
  1001. return end;
  1002. }
  1003. switch (scope) {
  1004. case CSS_MODE_IN_BLOCK: {
  1005. if (isLocalMode()) {
  1006. // Handle only top level values and not inside functions
  1007. if (inAnimationProperty && balanced.length === 0) {
  1008. lastIdentifier = [start, end, true];
  1009. } else {
  1010. return processLocalDeclaration(input, start, end);
  1011. }
  1012. }
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. return end;
  1018. },
  1019. delim: (input, start, end) => {
  1020. if (isNextRulePrelude && isLocalMode()) {
  1021. const ident = walkCssTokens.skipCommentsAndEatIdentSequence(
  1022. input,
  1023. end
  1024. );
  1025. if (!ident) return end;
  1026. const name = unescapeIdentifier(input.slice(ident[0], ident[1]));
  1027. const dep = new CssLocalIdentifierDependency(name, [
  1028. ident[0],
  1029. ident[1]
  1030. ]);
  1031. const { line: sl, column: sc } = locConverter.get(ident[0]);
  1032. const { line: el, column: ec } = locConverter.get(ident[1]);
  1033. dep.setLoc(sl, sc, el, ec);
  1034. module.addDependency(dep);
  1035. return ident[1];
  1036. }
  1037. return end;
  1038. },
  1039. hash: (input, start, end, isID) => {
  1040. if (isNextRulePrelude && isLocalMode() && isID) {
  1041. const valueStart = start + 1;
  1042. const name = unescapeIdentifier(input.slice(valueStart, end));
  1043. const dep = new CssLocalIdentifierDependency(name, [valueStart, end]);
  1044. const { line: sl, column: sc } = locConverter.get(start);
  1045. const { line: el, column: ec } = locConverter.get(end);
  1046. dep.setLoc(sl, sc, el, ec);
  1047. module.addDependency(dep);
  1048. }
  1049. return end;
  1050. },
  1051. colon: (input, start, end) => {
  1052. if (isModules) {
  1053. const ident = walkCssTokens.skipCommentsAndEatIdentSequence(
  1054. input,
  1055. end
  1056. );
  1057. if (!ident) return end;
  1058. const name = input.slice(ident[0], ident[1]).toLowerCase();
  1059. switch (scope) {
  1060. case CSS_MODE_TOP_LEVEL: {
  1061. if (name === "import") {
  1062. const pos = parseImportOrExport(0, input, ident[1]);
  1063. const dep = new ConstDependency("", [start, pos]);
  1064. module.addPresentationalDependency(dep);
  1065. return pos;
  1066. } else if (name === "export") {
  1067. const pos = parseImportOrExport(1, input, ident[1]);
  1068. const dep = new ConstDependency("", [start, pos]);
  1069. module.addPresentationalDependency(dep);
  1070. return pos;
  1071. }
  1072. }
  1073. // falls through
  1074. default: {
  1075. if (isNextRulePrelude) {
  1076. const isFn = input.charCodeAt(ident[1]) === CC_LEFT_PARENTHESIS;
  1077. if (isFn && name === "local") {
  1078. const end = ident[1] + 1;
  1079. modeData = "local";
  1080. const dep = new ConstDependency("", [start, end]);
  1081. module.addPresentationalDependency(dep);
  1082. balanced.push([":local", start, end]);
  1083. return end;
  1084. } else if (name === "local") {
  1085. modeData = "local";
  1086. // Eat extra whitespace
  1087. end = walkCssTokens.eatWhitespace(input, ident[1]);
  1088. if (ident[1] === end) {
  1089. this._emitWarning(
  1090. state,
  1091. `Missing whitespace after ':local' in '${input.slice(
  1092. start,
  1093. eatUntilLeftCurly(input, end) + 1
  1094. )}'`,
  1095. locConverter,
  1096. start,
  1097. end
  1098. );
  1099. }
  1100. const dep = new ConstDependency("", [start, end]);
  1101. module.addPresentationalDependency(dep);
  1102. return end;
  1103. } else if (isFn && name === "global") {
  1104. const end = ident[1] + 1;
  1105. modeData = "global";
  1106. const dep = new ConstDependency("", [start, end]);
  1107. module.addPresentationalDependency(dep);
  1108. balanced.push([":global", start, end]);
  1109. return end;
  1110. } else if (name === "global") {
  1111. modeData = "global";
  1112. // Eat extra whitespace
  1113. end = walkCssTokens.eatWhitespace(input, ident[1]);
  1114. if (ident[1] === end) {
  1115. this._emitWarning(
  1116. state,
  1117. `Missing whitespace after ':global' in '${input.slice(
  1118. start,
  1119. eatUntilLeftCurly(input, end) + 1
  1120. )}'`,
  1121. locConverter,
  1122. start,
  1123. end
  1124. );
  1125. }
  1126. const dep = new ConstDependency("", [start, end]);
  1127. module.addPresentationalDependency(dep);
  1128. return end;
  1129. }
  1130. }
  1131. }
  1132. }
  1133. }
  1134. lastTokenEndForComments = end;
  1135. return end;
  1136. },
  1137. function: (input, start, end) => {
  1138. const name = input
  1139. .slice(start, end - 1)
  1140. .replace(/\\/g, "")
  1141. .toLowerCase();
  1142. balanced.push([name, start, end]);
  1143. switch (name) {
  1144. case "src":
  1145. case "url": {
  1146. if (!this.url) {
  1147. return end;
  1148. }
  1149. const string = walkCssTokens.eatString(input, end);
  1150. if (!string) return end;
  1151. const { options, errors: commentErrors } = this.parseCommentOptions(
  1152. [lastTokenEndForComments, end]
  1153. );
  1154. if (commentErrors) {
  1155. for (const e of commentErrors) {
  1156. const { comment } = e;
  1157. state.module.addWarning(
  1158. new CommentCompilationWarning(
  1159. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  1160. comment.loc
  1161. )
  1162. );
  1163. }
  1164. }
  1165. if (options && options.webpackIgnore !== undefined) {
  1166. if (typeof options.webpackIgnore !== "boolean") {
  1167. const { line: sl, column: sc } = locConverter.get(string[0]);
  1168. const { line: el, column: ec } = locConverter.get(string[1]);
  1169. state.module.addWarning(
  1170. new UnsupportedFeatureWarning(
  1171. `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`,
  1172. {
  1173. start: { line: sl, column: sc },
  1174. end: { line: el, column: ec }
  1175. }
  1176. )
  1177. );
  1178. } else if (options.webpackIgnore) {
  1179. return end;
  1180. }
  1181. }
  1182. const value = normalizeUrl(
  1183. input.slice(string[0] + 1, string[1] - 1),
  1184. true
  1185. );
  1186. // Ignore `url()`, `url('')` and `url("")`, they are valid by spec
  1187. if (value.length === 0) return end;
  1188. const isUrl = name === "url" || name === "src";
  1189. const dep = new CssUrlDependency(
  1190. value,
  1191. [string[0], string[1]],
  1192. isUrl ? "string" : "url"
  1193. );
  1194. const { line: sl, column: sc } = locConverter.get(string[0]);
  1195. const { line: el, column: ec } = locConverter.get(string[1]);
  1196. dep.setLoc(sl, sc, el, ec);
  1197. module.addDependency(dep);
  1198. module.addCodeGenerationDependency(dep);
  1199. return string[1];
  1200. }
  1201. default: {
  1202. if (this.url && IMAGE_SET_FUNCTION.test(name)) {
  1203. lastTokenEndForComments = end;
  1204. const values = walkCssTokens.eatImageSetStrings(input, end, {
  1205. comment
  1206. });
  1207. if (values.length === 0) return end;
  1208. for (const [index, string] of values.entries()) {
  1209. const value = normalizeUrl(
  1210. input.slice(string[0] + 1, string[1] - 1),
  1211. true
  1212. );
  1213. if (value.length === 0) return end;
  1214. const { options, errors: commentErrors } =
  1215. this.parseCommentOptions([
  1216. index === 0 ? start : values[index - 1][1],
  1217. string[1]
  1218. ]);
  1219. if (commentErrors) {
  1220. for (const e of commentErrors) {
  1221. const { comment } = e;
  1222. state.module.addWarning(
  1223. new CommentCompilationWarning(
  1224. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  1225. comment.loc
  1226. )
  1227. );
  1228. }
  1229. }
  1230. if (options && options.webpackIgnore !== undefined) {
  1231. if (typeof options.webpackIgnore !== "boolean") {
  1232. const { line: sl, column: sc } = locConverter.get(
  1233. string[0]
  1234. );
  1235. const { line: el, column: ec } = locConverter.get(
  1236. string[1]
  1237. );
  1238. state.module.addWarning(
  1239. new UnsupportedFeatureWarning(
  1240. `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`,
  1241. {
  1242. start: { line: sl, column: sc },
  1243. end: { line: el, column: ec }
  1244. }
  1245. )
  1246. );
  1247. } else if (options.webpackIgnore) {
  1248. continue;
  1249. }
  1250. }
  1251. const dep = new CssUrlDependency(
  1252. value,
  1253. [string[0], string[1]],
  1254. "url"
  1255. );
  1256. const { line: sl, column: sc } = locConverter.get(string[0]);
  1257. const { line: el, column: ec } = locConverter.get(string[1]);
  1258. dep.setLoc(sl, sc, el, ec);
  1259. module.addDependency(dep);
  1260. module.addCodeGenerationDependency(dep);
  1261. }
  1262. // Can contain `url()` inside, so let's return end to allow parse them
  1263. return end;
  1264. } else if (isLocalMode()) {
  1265. // Don't rename animation name when we have `var()` function
  1266. if (inAnimationProperty && balanced.length === 1) {
  1267. lastIdentifier = undefined;
  1268. }
  1269. if (name === "var") {
  1270. const customIdent = walkCssTokens.eatIdentSequence(input, end);
  1271. if (!customIdent) return end;
  1272. let name = input.slice(customIdent[0], customIdent[1]);
  1273. // A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo.
  1274. // The <custom-property-name> production corresponds to this:
  1275. // it’s defined as any <dashed-ident> (a valid identifier that starts with two dashes),
  1276. // except -- itself, which is reserved for future use by CSS.
  1277. if (!name.startsWith("--") || name.length < 3) return end;
  1278. name = unescapeIdentifier(
  1279. input.slice(customIdent[0] + 2, customIdent[1])
  1280. );
  1281. const afterCustomIdent = walkCssTokens.eatWhitespaceAndComments(
  1282. input,
  1283. customIdent[1]
  1284. );
  1285. if (
  1286. input.charCodeAt(afterCustomIdent) === CC_LOWER_F ||
  1287. input.charCodeAt(afterCustomIdent) === CC_UPPER_F
  1288. ) {
  1289. const fromWord = walkCssTokens.eatIdentSequence(
  1290. input,
  1291. afterCustomIdent
  1292. );
  1293. if (
  1294. !fromWord ||
  1295. input.slice(fromWord[0], fromWord[1]).toLowerCase() !==
  1296. "from"
  1297. ) {
  1298. return end;
  1299. }
  1300. const from = walkCssTokens.eatIdentSequenceOrString(
  1301. input,
  1302. walkCssTokens.eatWhitespaceAndComments(input, fromWord[1])
  1303. );
  1304. if (!from) {
  1305. return end;
  1306. }
  1307. const path = input.slice(from[0], from[1]);
  1308. if (from[2] === true && path === "global") {
  1309. const dep = new ConstDependency("", [
  1310. customIdent[1],
  1311. from[1]
  1312. ]);
  1313. module.addPresentationalDependency(dep);
  1314. return end;
  1315. } else if (from[2] === false) {
  1316. const dep = new CssIcssImportDependency(
  1317. path.slice(1, -1),
  1318. name,
  1319. [customIdent[0], from[1] - 1]
  1320. );
  1321. const { line: sl, column: sc } = locConverter.get(
  1322. customIdent[0]
  1323. );
  1324. const { line: el, column: ec } = locConverter.get(
  1325. from[1] - 1
  1326. );
  1327. dep.setLoc(sl, sc, el, ec);
  1328. module.addDependency(dep);
  1329. }
  1330. } else {
  1331. const { line: sl, column: sc } = locConverter.get(
  1332. customIdent[0]
  1333. );
  1334. const { line: el, column: ec } = locConverter.get(
  1335. customIdent[1]
  1336. );
  1337. const dep = new CssSelfLocalIdentifierDependency(
  1338. name,
  1339. [customIdent[0], customIdent[1]],
  1340. "--",
  1341. declaredCssVariables
  1342. );
  1343. dep.setLoc(sl, sc, el, ec);
  1344. module.addDependency(dep);
  1345. return end;
  1346. }
  1347. }
  1348. }
  1349. }
  1350. }
  1351. return end;
  1352. },
  1353. leftParenthesis: (input, start, end) => {
  1354. balanced.push(["(", start, end]);
  1355. return end;
  1356. },
  1357. rightParenthesis: (input, start, end) => {
  1358. const popped = balanced.pop();
  1359. if (
  1360. isModules &&
  1361. popped &&
  1362. (popped[0] === ":local" || popped[0] === ":global")
  1363. ) {
  1364. modeData = balanced[balanced.length - 1]
  1365. ? /** @type {"local" | "global"} */
  1366. (balanced[balanced.length - 1][0])
  1367. : undefined;
  1368. const dep = new ConstDependency("", [start, end]);
  1369. module.addPresentationalDependency(dep);
  1370. }
  1371. return end;
  1372. },
  1373. comma: (input, start, end) => {
  1374. if (isModules) {
  1375. // Reset stack for `:global .class :local .class-other` selector after
  1376. modeData = undefined;
  1377. if (scope === CSS_MODE_IN_BLOCK && isLocalMode()) {
  1378. processDeclarationValueDone(input);
  1379. }
  1380. }
  1381. lastTokenEndForComments = start;
  1382. return end;
  1383. }
  1384. });
  1385. /** @type {BuildInfo} */
  1386. (module.buildInfo).strict = true;
  1387. /** @type {BuildMeta} */
  1388. (module.buildMeta).exportsType = this.namedExports
  1389. ? "namespace"
  1390. : "default";
  1391. if (!this.namedExports) {
  1392. /** @type {BuildMeta} */
  1393. (module.buildMeta).defaultObject = "redirect";
  1394. }
  1395. module.addDependency(new StaticExportsDependency([], true));
  1396. return state;
  1397. }
  1398. /**
  1399. * @param {Range} range range
  1400. * @returns {Comment[]} comments in the range
  1401. */
  1402. getComments(range) {
  1403. if (!this.comments) return [];
  1404. const [rangeStart, rangeEnd] = range;
  1405. /**
  1406. * @param {Comment} comment comment
  1407. * @param {number} needle needle
  1408. * @returns {number} compared
  1409. */
  1410. const compare = (comment, needle) =>
  1411. /** @type {Range} */ (comment.range)[0] - needle;
  1412. const comments = /** @type {Comment[]} */ (this.comments);
  1413. let idx = binarySearchBounds.ge(comments, rangeStart, compare);
  1414. /** @type {Comment[]} */
  1415. const commentsInRange = [];
  1416. while (
  1417. comments[idx] &&
  1418. /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd
  1419. ) {
  1420. commentsInRange.push(comments[idx]);
  1421. idx++;
  1422. }
  1423. return commentsInRange;
  1424. }
  1425. /**
  1426. * @param {Range} range range of the comment
  1427. * @returns {{ options: Record<string, EXPECTED_ANY> | null, errors: (Error & { comment: Comment })[] | null }} result
  1428. */
  1429. parseCommentOptions(range) {
  1430. const comments = this.getComments(range);
  1431. if (comments.length === 0) {
  1432. return EMPTY_COMMENT_OPTIONS;
  1433. }
  1434. /** @type {Record<string, EXPECTED_ANY> } */
  1435. const options = {};
  1436. /** @type {(Error & { comment: Comment })[]} */
  1437. const errors = [];
  1438. for (const comment of comments) {
  1439. const { value } = comment;
  1440. if (value && webpackCommentRegExp.test(value)) {
  1441. // try compile only if webpack options comment is present
  1442. try {
  1443. for (let [key, val] of Object.entries(
  1444. vm.runInContext(
  1445. `(function(){return {${value}};})()`,
  1446. this.magicCommentContext
  1447. )
  1448. )) {
  1449. if (typeof val === "object" && val !== null) {
  1450. val =
  1451. val.constructor.name === "RegExp"
  1452. ? new RegExp(val)
  1453. : JSON.parse(JSON.stringify(val));
  1454. }
  1455. options[key] = val;
  1456. }
  1457. } catch (err) {
  1458. const newErr = new Error(String(/** @type {Error} */ (err).message));
  1459. newErr.stack = String(/** @type {Error} */ (err).stack);
  1460. Object.assign(newErr, { comment });
  1461. errors.push(/** @type (Error & { comment: Comment }) */ (newErr));
  1462. }
  1463. }
  1464. }
  1465. return { options, errors };
  1466. }
  1467. }
  1468. module.exports = CssParser;
  1469. module.exports.escapeIdentifier = escapeIdentifier;
  1470. module.exports.unescapeIdentifier = unescapeIdentifier;